mvc3 ImageResizer - asp.net-mvc-3

I downloaded the Nugent ImageResizer and I am trying to resize a picture on upload following an example on this page http://imageresizing.net/docs/managed but I can't seen to put this in a Var or Image variable so i can see it in the Path.Combine here is the code
var fileName = Path.GetFileName(file.FileName);
var changename = getid + "_" + fileName;
ImageBuilder.Current.Build(changename, changename,
new ResizeSettings("width=130&height=130"));
var path = Path.Combine(Server.MapPath("~/uploads/profilepic"), changename);
file.SaveAs(path);
How can I get the ImageBuilder inside a var or some type of image variable what i would like to do is something like this
var resized= ImageBuilder.Current.Build(changename, changename,
new ResizeSettings("width=130&height=130"));
var path = Path.Combine(Server.MapPath("~/uploads/profilepic"), resized);
file.SaveAs(path);
all that im trying to do is put the ImageBuilder inside the Path.Combine without getting an error, any help would be appreciated .

ImageResizer should be given the uploaded file and the output path directly
ImageResizer supports both GUIDs and path sanitization. NEVER use the uploaded filename as-is!
var i = new ImageJob(file,
"~/uploads/profilepic/<guid>_<filename:A-Za-z0-9>.<ext>",
new ResizeSettings("width=130&height=130&format=jpg"));
i.CreateParentDirectory = true; //Auto-create the uploads directory.
i.Build();
var newVirtualPath = ImageResizer.Util.PathUtils.GuessVirtualPath(i.FinalPath);

Related

Unable to view PDF attached with ServiceNow table records

I am able to successfully attach PDF file with ServiceNow table record using GlideSysAttachment API and attachment.write() function in script, however whenever I download and try to open same, I get the error shown in below screenshot.
Code snippet
(function execute() {
try{
var rec = new GlideRecord('incident');
var attachment = new GlideSysAttachment();
var incidentSysID = incident.number;
rec.get(incidentSysID);
var fileName = 'Test_Incident.pdf';
var contentType = 'application/pdf'; // Also tried with contentType as 'text/pdf'
var content = pdf_content;
var agr = attachment.write(rec, fileName, contentType, content);<br>
gs.info('The PDF attachment sys_id is: ' + agr);
}catch(err){
gs.log('Got Error: ' + err);
gs.info(err);
}
})()
I also tried "AttachmentCreator" with ecc_queue within script but same error occurs. Below is code for it.
(function execute()
{var attCreator = new GlideRecord('ecc_queue');
attCreator.agent = "AttachmentCreator";
attCreator.topic = "AttachmentCreator";
attCreator.name = "Test.pdf" + ":" + "text/pdf";
//Also tried, "Test.pdf:application/pdf"
attCreator.source = "incident"+":"+ incident.number;
// Record Table name and sys_id of the particular record
var content = pdf_content; // pdf_content is any string variable
var stringUtil = new GlideStringUtil();
var base64String = stringUtil.base64Encode(content);
var isValid=GlideStringUtil.isBase64(base64String);
var base64String= gs.base64Encode(content);
gs.info("Is valid base64 format in ecc_queue ? "+ isValid);
attCreator.payload = base64String; //base64 content of the file
attCreator.insert();
})()
I am able to attach and view excel and word files with similar scripts without any issues. I have checked system properties for attachments but everything looks fine. I am able to view the PDF file uploaded from UI to particular table records however not the one I attach via REST API or scripts.
I have also tried sending encoded data as bytes, base64 or simple string but nothing seems to work. I don't get any errors and attachment id is returned each time on creation of attachment.
After modifying my code slightly for above functions w.r.t scoped application instead of global; I got some information from logs when I debug:
05:38:38.411 Security restricted: File type is not allowed or does not match the content for file Test.pdf
05:38:38.410 Security restricted: MIME type mismatch for file: Test.pdf. Expected type:application/pdf, Actual type: text/plain
05:38:38.394 App:XYZ App x_272539_xyz_ap: Is valid base64 format in ecc_queue ? true
First a comment: This line in your code is accidentally working -- make sure you understand that a task number is not the object sys_id
var incidentSysID = incident.number; // should be incident.sys_id
Next, it's unclear where the PDF content is coming from. IF your complete code is listed, I would expect the errors given as you have noted that pdf_content is "any string variable."
ServiceNow does have a the capability to create a PDF from an HTML argument.
Generating a PDF from HTML
Here's a helpful blog post for getting a PDF (Platform generated) of an existing record:
Love PDF? PDF loves you too

Insert Image into a Google Sheet with Apps Script using base64 encoded data

Given some base64 encoded data for a png file, as in the example below from the image tag.
<img src="data:image/png;base64,R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7">
I need to create an image blob from the base64 encoded data for the insertImage() method.
sheetClass.insertImage(imageBlob, column, row)
Documentation:
Sheets Class - insertImage method
I've tried using the code below, but it throws the error:
Execution failed: Error retrieving image from URL or bad URL
The documentation states that the method needs a blob, not a URL, but it seems like it's expecting a link to an image file.
function insertImageFromBase64Src() {
var data = 'R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7';
var imageBlob = Utilities.newBlob(Utilities.base64Decode(data), 'image/png').getBytes();
var ss = SpreadsheetApp.getActiveSpreadsheet();//This code is bound to a Sheet
var po = {
shName:'Update File',
column:1,
row:37
}
var sh = ss.getSheetByName(po.shName);
var image = sh.insertImage(imageBlob, po.column, po.row);//Insert an image and return the image
}
How about this modification?
Modification points:
insertImage can use the blob and URL which is the direct link of the image file.
In your script, imageBlob is an byte array which is "number[]". By this, I think that an error occurs.
Please add the name to the blob.
When the name is not given, an error occurs.
Modified script:
When your script is modified, it becomes as follows.
function insertImageFromBase64Src2() {
var data = 'R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7';
var imageBlob = Utilities.newBlob(Utilities.base64Decode(data), 'image/png', 'sample'); // Modified
var ss = SpreadsheetApp.getActiveSpreadsheet(); //This code is bound to a Sheet
var po = {
shName:'Update File',
column:1,
row:37
}
var sh = ss.getSheetByName(po.shName);
var image = sh.insertImage(imageBlob, po.column, po.row);//Insert an image and return the image
}
In this modification, it supposes that data can be correctly decoded.
References:
insertImage(blobSource, column, row)
insertImage(url, column, row)
If this was not the direct solution of your issue, I apologize.

How to get app name programatically in native script

I'm trying to save some files on my local File storage So, I'm doing Something like below
var folder_name = "abcde/" + viewModel.dir_path;
const documents = fileSystemModule.knownFolders.documents();
documents._path = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
const folder = documents.getFolder(folder_name);
var file = fileSystemModule.path.join(folder._path, this.pdf_url.split("/").pop());
var url = this.pdf_url;
httpModule.getFile(url, file).then(function(result) {
console.log(result);
Toast.makeText(`${result._name} is succesfully downloaded in ${folder_name}`).show();
}, function(e) {
console.log(e);
});
the only problem is the hardcoded value abcde/ I want it to be app name. whatever the app name is it should take that name.
I don't find any ways to read app name programatically. I need this to Android I'm not interested in IOS.
may be this is one could be the answer. but still this is not a proper way
const documents = fileSystemModule.knownFolders.currentApp();
console.log(documents); --> "/data/data/org.nativescript.app_name/files/app"
var str = documents;
var arr = str.split("/")[3];
console.log(arr.split(".")[2]); ---> app_name
In Android, you can set the app name for the application in strings.xml, for example:
<string name="app_name">"App_Name"</string>
Then whenever you want to reuse the app name, you can use the getString method with its name in the application.

Webmatrix image upload and ImageMagick

I have a simple image upload page which works really well:
WebImage photo = null;
var newFileName = "";
var imagePath = "";
if(IsPost){
using (var bitmap = (Bitmap)Image.FromFile(Server.MapPath("~/" + imagePath))){
using (var newBitmap = new Bitmap(bitmap)){
newBitmap.SetResolution(72f, 72f);
newBitmap.Save("file300.jpg", ImageFormat.Jpeg);
}
}
var image = "UPDATE PropertyInfo SET PrimaryImage = #0 WHERE PropertyID = #1";
db.Execute(image, newFileName, rPropertyId);
}
Now i also want to use ImageMagick to convert any images uploaded using this form to 72dpi. I have the command line i need to do this, but i don't now how to apply it to the upload process?
convert c:\image.jpg -density 72 c:\image.jpg
Should i do this during the upload process, or once the file has already been uploaded to a server. Is there any way of initiating a command prompt from within WebMatrix?
It seems easier to use existing .NET features to manage the DPI, namely with the System.Drawing.Bitmap.SetResolution method
using (var bitmap = (Bitmap)Image.FromFile(Server.MapPath("~/" + imagePath))){
using (var newBitmap = new Bitmap(bitmap)){
newBitmap.SetResolution(72f, 72f);
newBitmap.Save("file300.jpg", ImageFormat.Jpeg);
}
}
However, you can also use the System.Diagnostics.Process.Start method to run .exes via C# code.

Save and read files in isolated storage

I try to save files in IsoStore. In WP8 emulator files have been successfully saved, but when I run my program in other emulators or on my phone(with WP7.8) I get a error: "path must be a valid file name"
I do this:
var path = #"\Shared\Media\mapp\";
var imageName = guid from the server;
if (!_fileStorage.DirectoryExists(path))
_fileStorage.CreateDirectory(path);
//here I get a error using (IsolatedStorageFileStream fileStream =
_fileStorage.OpenFile(path + imageName,
FileMode.OpenOrCreate))
{//do anything}
I try to set path = #"iso:\Shared\Media\mapp\" or #"isostore:\Shared\Media\mapp\" or #"files:\Shared\Media\mapp\" or #"file:\Shared\Media\mapp\" and it doesn't work.
If I set #"\Shared\Media\" all fine in all devices. Who can tell me why I can't create a directory?
For Windows-Phone-7 you can't create a directory, which name ends with "/" or "//", that will cause an "path must be a valid file name" error.
To solve your problem, just change your code a bit:
var path = #"\Shared\Media\mapp";
var imageName = guid from the server;
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!store.FileExists(path))
{
store.CreateDirectory(path);
}
store.OpenFile(path + "\\" + imageName, FileMode.OpenOrCreate);
}
Hope, that helps.

Resources