contentVersion (image/png) created is empty - salesforce

//lightning controller- Here I am capturing the signature in a hidden canvas and extracting the base64 data from it , and sending it to the server side apex
var tCtx = document.getElementById('textCanvas').getContext('2d'),
imageElem = document.getElementById('Signimage');
tCtx.canvas.width = 720;
tCtx.canvas.height= 100;
tCtx.font = "italic 30px monospace";
var theSignature = n; // name of person - the text that is to be converted to an img
tCtx.fillText(theSignature,10, 50);
imageElem.src = tCtx.canvas.toDataURL();
var base64Canvas = tCtx.canvas.toDataURL().split(';base64,')[1];
component.set('{!v.storeApplicantSign}',base64Canvas);
//lightning helper
uploadonSubmit: function(component,event,helper) {
// call the apex method 'saveChunk'
var action = component.get("c.saveChunk");
action.setParams({
parentId: component.get("v.recordId"),
base64Data: component.get("v.storeApplicantSign"), // contains the base64 data
});
// set call back
action.setCallback(this, function(response) {
// store the response / Attachment Id
var result = response.getReturnValue();
var state = response.getState();
if (state === "SUCCESS") {
alert("Success");
// this.showtheToast();
} else if (state === "INCOMPLETE") {
alert("From server: " + response.getReturnValue());
} else if (state === "ERROR") {
var errors = response.getError();
if (errors) {
if (errors[0] && errors[0].message) {
console.log("Error message: " + errors[0].message);
}
} else {
console.log("Unknown error");
}
}
});
// enqueue the action
$A.enqueueAction(action);
},
// apex class
//Here decoding the data from the lightning and creating content version
#AuraEnabled
public static Id saveChunk(Id parentId,String base64Data) {
String fileId = saveTheFile(parentId,base64Data,'Signature.png');
return Id.valueOf(fileId);
}
public static Id saveTheFile(Id parentId,String base64Data,String fileName) {
base64Data = EncodingUtil.urlDecode(base64Data,'UTF-8');
ContentVersion contentVersion = new ContentVersion(
versionData = EncodingUtil.base64Decode(base64Data),
title = fileName,
pathOnClient = 'Signature'+'.'+'png',
ContentLocation='S',
FirstPublishLocationId = parentId);
system.debug('contentversion data=> '+contentVersion+'version data ----> '+contentVersion.VersionData);
insert contentVersion;
return contentVersion.Id;
}
// File is being created but it's empty that is image is not there / can't be opened as img

The issue was in apex side :
just removed the line :
`base64Data = EncodingUtil.urlDecode(base64Data,'UTF-8'); // this wasn't required
removing the above line solved it .

Related

discordjs Embed won't show up

Ok, so i'm trying to make a push notification for my discord.
i found this script online.
but it will not post the embed....
This is my monitor code:
TwitchMonitor.onChannelLiveUpdate((streamData) => {
const isLive = streamData.type === "live";
// Refresh channel list
try {
syncServerList(false);
} catch (e) { }
// Update activity
StreamActivity.setChannelOnline(streamData);
// Generate message
const msgFormatted = `${streamData.user_name} is nu live op twitch <:bday:967848861613826108> kom je ook?`;
const msgEmbed = LiveEmbed.createForStream(streamData);
// Broadcast to all target channels
let anySent = false;
for (let i = 0; i < targetChannels.length; i++) {
const discordChannel = targetChannels[i];
const liveMsgDiscrim = `${discordChannel.guild.id}_${discordChannel.name}_${streamData.id}`;
if (discordChannel) {
try {
// Either send a new message, or update an old one
let existingMsgId = messageHistory[liveMsgDiscrim] || null;
if (existingMsgId) {
// Fetch existing message
discordChannel.messages.fetch(existingMsgId)
.then((existingMsg) => {
existingMsg.edit(msgFormatted, {
embed: msgEmbed
}).then((message) => {
// Clean up entry if no longer live
if (!isLive) {
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
}
});
})
.catch((e) => {
// Unable to retrieve message object for editing
if (e.message === "Unknown Message") {
// Specific error: the message does not exist, most likely deleted.
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
// This will cause the message to be posted as new in the next update if needed.
}
});
} else {
// Sending a new message
if (!isLive) {
// We do not post "new" notifications for channels going/being offline
continue;
}
// Expand the message with a #mention for "here" or "everyone"
// We don't do this in updates because it causes some people to get spammed
let mentionMode = (config.discord_mentions && config.discord_mentions[streamData.user_name.toLowerCase()]) || null;
if (mentionMode) {
mentionMode = mentionMode.toLowerCase();
if (mentionMode === "Nu-Live") {
// Reserved # keywords for discord that can be mentioned directly as text
mentionMode = `#${mentionMode}`;
} else {
// Most likely a role that needs to be translated to <#&id> format
let roleData = discordChannel.guild.roles.cache.find((role) => {
return (role.name.toLowerCase() === mentionMode);
});
if (roleData) {
mentionMode = `<#&${roleData.id}>`;
} else {
console.log('[Discord]', `Cannot mention role: ${mentionMode}`,
`(does not exist on server ${discordChannel.guild.name})`);
mentionMode = null;
}
}
}
let msgToSend = msgFormatted;
if (mentionMode) {
msgToSend = msgFormatted + ` ${mentionMode}`
}
let msgOptions = {
embed: msgEmbed
};
discordChannel.send(msgToSend, msgOptions)
.then((message) => {
console.log('[Discord]', `Sent announce msg to #${discordChannel.name} on ${discordChannel.guild.name}`)
messageHistory[liveMsgDiscrim] = message.id;
liveMessageDb.put('history', messageHistory);
})
.catch((err) => {
console.log('[Discord]', `Could not send announce msg to #${discordChannel.name} on ${discordChannel.guild.name}:`, err.message);
});
}
anySent = true;
} catch (e) {
console.warn('[Discord]', 'Message send problem:', e);
}
}
}
liveMessageDb.put('history', messageHistory);
return anySent;
});
This is the embed code:
const Discord = require('discord.js');
const moment = require('moment');
const humanizeDuration = require("humanize-duration");
const config = require('../data/config.json');
class LiveEmbed {
static createForStream(streamData) {
const isLive = streamData.type === "live";
const allowBoxArt = config.twitch_use_boxart;
let msgEmbed = new Discord.MessageEmbed();
msgEmbed.setColor(isLive ? "RED" : "BLACK");
msgEmbed.setURL(`https://twitch.tv/${(streamData.login || streamData.user_name).toLowerCase()}`);
// Thumbnail
let thumbUrl = streamData.profile_image_url;
if (allowBoxArt && streamData.game && streamData.game.box_art_url) {
thumbUrl = streamData.game.box_art_url;
thumbUrl = thumbUrl.replace("{width}", "288");
thumbUrl = thumbUrl.replace("{height}", "384");
}
msgEmbed.setThumbnail(thumbUrl);
if (isLive) {
// Title
msgEmbed.setTitle(`:red_circle: **${streamData.user_name} is live op Twitch!**`);
msgEmbed.addField("Title", streamData.title, false);
} else {
msgEmbed.setTitle(`:white_circle: ${streamData.user_name} was live op Twitch.`);
msgEmbed.setDescription('The stream has now ended.');
msgEmbed.addField("Title", streamData.title, true);
}
// Add game
if (streamData.game) {
msgEmbed.addField("Game", streamData.game.name, false);
}
if (isLive) {
// Add status
msgEmbed.addField("Status", isLive ? `Live with ${streamData.viewer_count} viewers` : 'Stream has ended', true);
// Set main image (stream preview)
let imageUrl = streamData.thumbnail_url;
imageUrl = imageUrl.replace("{width}", "1280");
imageUrl = imageUrl.replace("{height}", "720");
let thumbnailBuster = (Date.now() / 1000).toFixed(0);
imageUrl += `?t=${thumbnailBuster}`;
msgEmbed.setImage(imageUrl);
// Add uptime
let now = moment();
let startedAt = moment(streamData.started_at);
msgEmbed.addField("Uptime", humanizeDuration(now - startedAt, {
delimiter: ", ",
largest: 2,
round: true,
units: ["y", "mo", "w", "d", "h", "m"]
}), true);
}
return msgEmbed;
}
}
module.exports = LiveEmbed;
But it won't post the embed, only the msg. as you can see it updates teh msg aswell.
enter image description here
i'm stuck on this for four days now, can someone help?

trying to convetr json array to multiple json objects in nodejs

trying to convetr json array to multiple json objects in nodejs looking for help here is my code have tried loops to achieve that but failed just want to send the data as multiple objects not array
router.get('/frontpage-mobile', function (req, res, next) {
qryFilter = { "Product_Group": 'SIMPLE' };
// if we have a cart, pass it - otherwise, pass an empty object
var successMsg = req.flash('success')[0];
var errorMsg = req.flash('error')[0];
Product.find(qryFilter, function (err, product) {
// console.log("Product: " + JSON.stringify(product));
var pro=JSON.stringify(product)
if (err || product === 'undefined' || product == null) {
// replace with err handling
var errorMsg = req.flash('error', 'unable to find product');
res.send(errorMsg);
}
if (!product) {
req.flash('error', 'Product is not found.');
res.send('error', 'Product is not found.');
}
for(i=0;i<pro.length;i++)
res.send(pro[i]);
});
});
// Dummy Mongodb Result Array
var db_result = [{_id:1,name:"Cake_1"},{_id:2,name:"Cake_2"},{_id:3,name:"Cake_3"}]
// define data variable
var data = { total : 0, dataObj : {} } // default total = 0, = {}
var dataObj = {}
// convert array to obj
// { key1 : obj1, key2 : obj2, key3 : obj3, ... }
for(var i=0; i < db_result.length;i++){
let key = "key"+i;
dataObj[key] = db_result[i];
}
// assign data to variable
data.total = db_result.length;
data.dataObj = dataObj
// rend back to client
res.send(data);
// Result
{
"total":3,
"dataObj":{
"key0":{"_id":1,"name":"Cake_1"},
"key1":{"_id":2,"name":"Cake_2"},
"key2":{"_id":3,"name":"Cake_3"}
}
}

Return promise from Angularjs webapi

Using Angularjs here:
I have a form where user fills up some data and clicks save button to save data :
$scope.save = function (isValid) {
if (isValid) {
if (!$scope.checkBoxChecked) {
$scope.getExistingName($scope.uName);
}
var name = $scope.uName != '' ? $scope.uName? : 'testuser';
//Call save api
}
else {
return false;
}
};
In the save method I am checking for uname, which gets it value by calling another api as below:
$scope.getExistingName = function (uName) {
myService.getDataFromApi(uName).then(function (data) {
var existingSetName = '';
if(data.length >0)
{
$scope.uName = data[i].uName;
}
});
}
The issue is $scope.uName in my Save button is always ''. I tried to debug and found out that the result from the $scope.getExistingName method
being is promise is deffered and returned after the orignal call. Because of which my $scope.uName is empty.
What am I missing here?
--Updated---
Save method:
var name = $scope.getExistingName($scope.uName);
Updated getExistingName
$scope.getExistingName = function (uName) {
return myService.getDataFromApi(uName).then(function (data) {
var existingSetName = '';
if(data.length >0)
{
return data[i].uName;
}
});
}
--This works--
if (!$scope.checkBoxChecked) {
$scope.getExistingName($scope.uName).then(function(data)
{
var name = $scope.uName != '' ? $scope.uName? : 'testuser';
//Call save api
});
}
else
{
var name = $scope.uName != '' ? $scope.uName? : 'testuser';
//Call save api
}

Use array to add new entry in model in asp.net mvc

I'm using asp.net mvc 4 and Entity Framework 6 to make a website where I can store data in MSSQL database. I want to make a function where it'll make a copy of an entry with different id. I want to put those copied values in an array and push it to the model to make the back-end processing faster. But I'm not sure how to do it.
Here are my codes:
public ActionResult FlatCopy(FlManagement FlTable, int FlId = 0)
{
var getOwner = rentdb.OwnerRegs.Where(a => a.username == User.Identity.Name).FirstOrDefault();
var getId = getOwner.serial;
var getLimit = getOwner.limit;
var getPosted = getOwner.posted;
FlInfo model = FlTable.Flats;
if (ModelState.IsValid)
{
if (getLimit != 0)
{
try
{
getOwner.limit = getLimit - 1;
getOwner.posted = getPosted + 1;
var dbPost = rentdb.FlatInfoes.Where(p => p.serial == FlId).FirstOrDefault();
if (dbPost == null)
{
TempData["flat_edit_fail"] = "Error! Information update failed!";
return RedirectToAction("FlatManager", new { FlPanelId = "AllFl" });
}
model.flatno = "Copy of " + dbPost.flatno;
model.type = dbPost.type;
model.owner_id = getId;
model.t_id = 0;
model.t_name = "N/A";
model.t_phone = "N/A";
model.basic = dbPost.basic;
model.electric = dbPost.electric;
model.gas = dbPost.gas;
model.water = dbPost.water;
model.total = dbPost.total;
model.advancerent = dbPost.advancerent;
model.currency = dbPost.currency;
model.title = dbPost.title;
model.status = "N/A";
db.FlatInfoes.Add(model);
db.SaveChanges();
TempData["success"] = "Information Added Successfully!";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
catch
{
TempData["fail"] = "Error! Please Provide Valid Information.";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
}
else
{
TempData["fail"] = "You've reached your post limit!";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
}
else
{
TempData["fail"] = "Error! Please Provide Valid Information.";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
}
How can I put the values in an array and push the array in model to add a new entry?
You could detach the entity from the DbContext then re-add it to the EntityCollection.
rentdb.Entry(dbPost).State = EntityState.Detached;
rentdb.FlatInfoes.Add(dbPost);
solution 2:(is better)
var model = new FlInfo();
rentdb.FlatInfoes.Add(model);
var sourceValues = rentdb.Entry(dbPost).CurrentValues;
rentdb.Entry(model).CurrentValues.SetValues(sourceValues);
rentdb.SaveChanges();

how to save two file from two different html file upload in same function using angularjs and MVC3

here is my all code i am trying to upload small image and large image separate but angularjs not let me allow to do this, it only taking one file but not taking other one. plz anyone help with this. thanks in advance.
<div ng-app="eventModule" >
<div ng-controller="eventController">
<div>
<span >Thumbnail Image</span>
<input type="file" id="fileToUpload" onchange="angular.element(this).scope().selectThumbnail(this.files)" accept="image/*" />
</div>
<div>
<span >Large Image</span>
<input type="file" onchange="angular.element(this).scope().selectLargeImage(this.files)" class="LargeImageSubCategory" />
</div>
</div>
<span data-ng-click="SaveFile()">Submit</span>
</div>
<script>
var eventModule = angular.module('eventModule', []);
eventModule.controller('eventController', function ($scope,ArticleService, $http, $sce) {
$scope.selectThumbnail = function (file) {
$scope.SelectedThumbnail = file[0];
}
$scope.selectLargeImage = function (file) {
$scope.SelectedLargeImage = file[0];
}
$scope.SaveFile = function () {
$scope.IsFormSubmitted = true;
$scope.Message = "";
ArticleService.UploadFile($scope.SelectedThumbnail, $scope.SelectedLargeImage).then(function (d) {
alert(d.Message);
ClearForm();
}, function (e) {
alert(e);
});
};
});
eventModule.service("ArticleService", function ($http, $q) {
this.UploadFile = function (Thumbnail, LargeImage, TitleHeading, Topic, SmallDesc, LargeDesc) {
var formData = new FormData();
formData.append("Thumbnail", Thumbnail);
formData.append("LargeImage", LargeImage);
// here when i am trying to send two files so controller is not called
//and function is breaking and alert is comming "File Upload Failed"
formData.append("TitleHeading", TitleHeading);
formData.append("Topic", Topic);
var defer = $q.defer();
$http.post("/Articles/SaveFiles", formData,
{
withCredentials: true,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity
}).success(function (d) {
defer.resolve(d);
}).error(function () {
defer.reject("File Upload Failed!");
});
return defer.promise;
}
});
</script>
//And My ArticlesController.cs code is
[HttpPost]
public JsonResult SaveFiles(string TitleHeading, string Topic)
{
string Message, fileName, actualFileName;
Message = fileName = actualFileName = string.Empty;
bool flag = false;
if (Request.Files != null)
{
var file = Request.Files[0];
actualFileName = file.FileName;
fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
int size = file.ContentLength;
try
{
file.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), fileName));
using (TCDataClassesDataContext dc = new TCDataClassesDataContext())
{
Article insert = new Article();
insert.ArticleId = Guid.NewGuid();
insert.TitleHeading = TitleHeading;
insert.SmallImagePath = fileName;
dc.Articles.InsertOnSubmit(insert);
dc.SubmitChanges();
Message = "File uploaded successfully";
flag = true;
}
}
catch (Exception)
{
Message = "File upload failed! Please try again";
}}
return new JsonResult { Data = new { Message = Message, Status = flag } };
}
You are appending the files to the formdata, thus you need to specify the Thumbnail and LargeImage as parameters of your MVC controller. Please see below:
[HttpPost]
public JsonResult SaveFiles(
HttpPostedFileBase thumbnail
, HttpPostedFileBase largeImage
, string titleHeading
, string topic)
{
string Message, fileName, actualFileName;
Message = fileName = actualFileName = string.Empty;
bool flag = false;
if (thumbnail != null && thumbnail.ContentLength != 0)
{
SaveFile(thumbnail);
}
if (largeImage != null && largeImage.ContentLength != 0)
{
SaveFile(largeImage);
}
return new JsonResult { Data = new { Message = Message, Status = flag } };
}
private void SaveFile(
HttpPostedFileBase httpFile)
{
var actualFileName = httpFile.FileName;
var fileName = Guid.NewGuid() + Path.GetExtension(httpFile.FileName);
int size = httpFile.ContentLength;
try
{
httpFile.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), fileName));
using (TCDataClassesDataContext dc = new TCDataClassesDataContext())
{
Article insert = new Article();
insert.ArticleId = Guid.NewGuid();
insert.TitleHeading = TitleHeading;
insert.SmallImagePath = fileName;
dc.Articles.InsertOnSubmit(insert);
dc.SubmitChanges();
Message = "File uploaded successfully";
flag = true;
}
}
catch (Exception)
{
Message = "File upload failed! Please try again";
}
}

Resources