Cropper JS Duplicates on reupload of image - cropperjs

when i upload a new image using cropper js it duplicates the cropper like so:
Here is my code on how i handle the whole uploading and reuploading:
$(window).ready(function() {
function cropImage($image, input, trigger, preview, output, options) {
input.change(function() {
var oFReader = new FileReader();
oFReader.readAsDataURL(this.files[0]);
oFReader.onload = function (oFREvent) {
let cropper = null;
// Cropper instance
cropper = new Cropper(
$image[0],
options
);
// Destroy Cropper Instance
cropper.destroy();
$image[0].setAttribute('src', this.result);
trigger.removeClass('disabled').addClass('active');
// Create New cropper instance after destorying
cropper = new Cropper(
$image[0],
options
);
cropperPreview(trigger, $image,preview, cropper, output);
};
});
}
I followed the advice of the plugin creator to use the replace method but it is the same output.

you might have to look into destroy() & re-init..hope it will solve your problem.

Related

How to get current filters from PowerBi embedded export report

I am using powerbi embedded and I would like an export button similar to the one used on powerbi.com, that asks if you want to apply the current filters or not.
How can I get the current filters in javaScript in such a way that these can be passed to the back end, or to the javascript api to generate a PDF?
I am using the following code to generate the PDF currently, I just don't know how to get the current configuration current filters and current page selected in javaScript
public PowerBiExportViewModel CreateExport(Guid groupId,
Guid reportId,
IEnumerable<PowerBiReportPage> reportPages,
FileFormat fileFormat,
string urlFilter,
TimeSpan timeOut)
{
var errorMessage = string.Empty;
Stream stream = null;
var fileSuffix = string.Empty;
var securityToken = GetAccessToken();
using (var client = new PowerBIClient(new Uri(BaseAddress), new TokenCredentials(securityToken, "Bearer")))
{
var powerBiReportExportConfiguration = new PowerBIReportExportConfiguration
{
Settings = new ExportReportSettings
{
Locale = "en-gb",
IncludeHiddenPages = false
},
Pages = reportPages?.Select(pn => new ExportReportPage { PageName = pn.Name }).ToList(),
ReportLevelFilters = !string.IsNullOrEmpty(urlFilter) ? new List<ExportFilter>() { new ExportFilter(urlFilter) } : null,
};
var exportRequest = new ExportReportRequest
{
Format = fileFormat,
PowerBIReportConfiguration = powerBiReportExportConfiguration
};
var export = client.Reports.ExportToFileInGroupAsync(groupId, reportId, exportRequest).Result;
You can go to PowerBi playground and play around with their sample report. Next to "Embed" button you have "Interact" and option to get filters. In response you get JSON with filters. If you are too lazy to go there, here is the code it created for me
// Get a reference to the embedded report HTML element
var embedContainer = $('#embedContainer')[0];
// Get a reference to the embedded report.
report = powerbi.get(embedContainer);
// Get the filters applied to the report.
try {
const filters = await report.getFilters();
Log.log(filters);
}
catch (errors) {
Log.log(errors);
}

Test not passing when db context n separate using blocks

I trying to do in memory ef core testing.
I have something similar to this:
Startup
services.AddEntityFrameworkNpgsql().AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(Configuration.GetConnectionString("PostgresConnection"), x=>x.UseNetTopologySuite()))
.BuildServiceProvider();
Test method
public void Add_writes_to_database()
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: "Add_writes_to_database")
.Options;
// Run the test against one instance of the context
using (var context = new ApplicationDbContext(options))
{
var service = new BlogService(context);
service.Add("http://sample.com");
}
// Use a separate instance of the context to verify correct data was saved to database
using (var context = new ApplicationDbContext(options))
{
Assert.AreEqual(1, context.Blogs.Count());
Assert.AreEqual("http://sample.com", context.Blogs.Single().Url);
}
}
When the context is split into 2 using blocks like above it does not pass the test.
But when its all wrapped in one context it works ok.
Any ideas?
Had to also iclude InMemoryDatabaseRoot
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString(),
databaseRoot: new InMemoryDatabaseRoot())
.Options;

Add Images for my Sitecore Items through program

I am creating Sitecore item programtically and want to add some images for my item while creating programatically.It should get that image from Sitecore media, How to do that, need help.I Know how to do that using content item
If you only want to assign an image to a field you have to add this code:
item.Editing.BeginEdit();
ImageField imageField = item.Fields["Your Image Field"];
imageField.MediaID = new ID("IMAGE ID");
item.Editing.EndEdit();
If you want to create an image dynamically from a URL and then assign it to your item, you could use the following code:
var destinationPath = StringUtil.EnsurePostfix('/', imagesFolder.Paths.Path);
string imageName = ItemUtil.ProposeValidItemName(model.Title);
var options = new MediaCreatorOptions
{
Database = ItemHelpers.GetMasterDatabase(),
Versioned = false,
Destination = destinationPath + imageName,
FileBased = false,
IncludeExtensionInItemName = false,
KeepExisting = true,
AlternateText = imageName
};
try
{
WebClient cli = new WebClient();
byte[] imgBytes = cli.DownloadData(imageUrl);
using (var memStream = new MemoryStream(imageBytes))
{
Item scImage = MediaManager.Creator.CreateFromStream(memStream, imageUrl, options);
//Publish your Item
//scImage.ID is the one you need to assign to you image field
}
}
catch (Exception)
{
//Your code
}

Read content of SP.File object as text using JSOM

as the title suggests, I am trying to read the contents of a simple text file using JSOM. I am using a Sharepoint-hosted addin for this, the file I am trying to read resides on the host web in a document library.
Here's my JS code:
function printAllListNamesFromHostWeb() {
context = new SP.ClientContext(appweburl);
factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
context.set_webRequestExecutorFactory(factory);
appContextSite = new SP.AppContextSite(context, hostweburl);
this.web = appContextSite.get_web();
documentslist = this.web.get_lists().getByTitle('Documents');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><ViewFields><FieldRef Name="Name"/></ViewFields></View>');
listitems = documentslist.getItems(camlQuery);
context.load(listitems, 'Include(File,FileRef)');
context.executeQueryAsync(
Function.createDelegate(this, successHandler),
Function.createDelegate(this, errorHandler)
);
function successHandler() {
var enumerator = listitems.getEnumerator();
while (enumerator.moveNext()) {
var results = enumerator.get_current();
var file = results.get_file();
//Don't know how to get this to work...
var fr = new FileReader();
fr.readAsText(file.get);
}
}
function errorHandler(sender, args) {
console.log('Could not complete cross-domain call: ' + args.get_message());
}
}
However, in my succes callback function, I don't know how I can extract the contents of the SP.File object. I tried using the FileReader object from HTML5 API but I couldn't figure out how to convert the SP.File object to a blob.
Can anybody give me a push here?
Once file url is determined file content could be loaded from the server using a regular HTTP GET request (e.g. using jQuery.get() function)
Example
The example demonstrates how to retrieve the list of files in library and then download files content
loadItems("Documents",
function(items) {
var promises = $.map(items.get_data(),function(item){
return getFileContent(item.get_item('FileRef'));
});
$.when.apply($, promises)
.then(function(content) {
console.log("Done");
//print files content
$.each(arguments, function (idx, args) {
console.log(args[0])
});
},function(e) {
console.log("Failed");
});
},
function(sender,args){
console.log(args.get_message());
}
);
where
function loadItems(listTitle,success,error){
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getByTitle(listTitle);
var items = list.getItems(createAllFilesQuery());
ctx.load(items, 'Include(File,FileRef)');
ctx.executeQueryAsync(
function() {
success(items);
},
error);
}
function createAllFilesQuery(){
var qry = new SP.CamlQuery();
qry.set_viewXml('<View Scope="RecursiveAll"><Query><Where><Eq><FieldRef Name="FSObjType" /><Value Type="Integer">0</Value></Eq></Where></Query></View>');
return qry;
}
function getFileContent(fileUrl){
return $.ajax({
url: fileUrl,
type: "GET"
});
}

Loopback strange behaviour

I am talking about loopback push component. I am trying to intercept the "create" method of "Installation" model. My code looks like this -
server/boot/installationex.js
module.exports = function (app) {
var Installation = app.models.Installation;
var create = Installation.create;
Installation.create = function (data, cb) {
//reinitializing old implementation
this.create = create;
console.log("Received data: "+JSON.stringify(data));
if (!data || !data.imei) {
console.log("No data or imei was provided, creating new");
this.create(data, cb);
return;
}
//saving 'this' reference
var that = this;
//search by imei filter
var filter = {where: {imei: data.imei}};
this.findOne(filter, function (err, result) {
if (err) {
console.log("Error occurred while looking for installation by IMEI");
cb(err);
return;
}
if (!result) {
console.log("No installation found by IMEI, will create a new installation");
that.create(data, cb);
return;
}
console.log("Found existing installation with id: " + JSON.stringify(result));
result.deviceToken = result.gpsLocation = result.osVersion = result.vendor = result.phoneNumbers = null;
if (data.deviceToken) {
result.deviceToken = data.deviceToken;
}
if (data.gpsLocation) {
result.gpsLocation = data.gpsLocation;
}
if (data.osVersion) {
result.osVersion = data.osVersion;
}
if (data.vendor) {
//result.vendor=data.vendor;
result.vendor = 'jahid';
}
if (data.phoneNumbers) {
result.phoneNumbers = data.phoneNumbers;
}
that.upsert(result, cb);
});
}
}
Unfortunately this code is invoked only once, I mean the first time. After that this code is never invoked. I became sure by looking at the log. It only prints the log first time. After that it does not print any log.
Any idea why this glue code is only invoked once? My intention is to intercept all create method invocation for Installation model. And check if there is already an entry for supplied "IMEI", if so then reuse that. Otherwise create new.
Thanks in advance.
Best regards,
Jahid
What I would start here with is:
instead of implementing your own intercepting mechanism use Model Hooks
check out findOrCreate() method
boot scripts are only run once during application startup. if you want a function that triggers every time a function is called, use a remote hook or model hook. probably something along the lines of:
...
Installation.beforeRemote('create', ...
...
see http://docs.strongloop.com/display/LB/Adding+logic+to+models for more info