A generic error occurred in GDI+, possible server.mappath issue - asp.net

I've narrowed down the issue I'm having to this block of code, where I am resizing an uploaded image and saving it. This works fine on my local machine, but when I run the site on the server, I get a generic GDI+ error that's coming from the "thumbnail.Save" call.
if(fup_displayPicUpload.HasFile)
{
string imageDir = Server.MapPath("./images/");
if (!Directory.Exists(imageDir + username))
{
Directory.CreateDirectory(imageDir + username);
lbl_profileMessage.ForeColor = Color.Yellow;
lbl_profileMessage.Text = "Created User Folder";
}
String userFolder = imageDir + username + "/";
using (System.Drawing.Image originalPhoto = new Bitmap(new MemoryStream(fup_displayPicUpload.FileBytes)))
{
System.Drawing.Image thumbnail = originalPhoto.GetThumbnailImage(300, 300, Abort, IntPtr.Zero);
thumbnail.Save(userFolder + "displaypicture.jpg", ImageFormat.Jpeg);
}
displayPictureUrl = "/images/" + username + "/displaypicture.jpg";
}

The most common cause of this is an access denied error to the directory that you are trying to save the image to. Make sure that the user that the application is running as has write access to the destination directory.

Related

FailedToExecuteCommand ghostscript gswin64c.exe on azure

I am trying to convert pdf into images using magickNET and ghostscript. It works well on local and windows VMS servers. But when i push to azure servers it gives me the error saying FailedToExecuteCommand ghostscript gswin64c.exe. Details of error in attachements.
I tried changing the path for ghostscript dll but found no luck. The path is correct and dll file is there. One thing I am sure of. I have put dll inside wwwroot/GhostScriptDll. on error it shows "D:/home/site/wwwroot/wwwroot/GhostScriptDll/gswin64c.exe" which is also correct there are 2's wwwroot.
can someone help me to use ghostscript without webjobs things.
C# code i tried is like this
enter image description here
string rawpath = _hostingEnvironment.WebRootPath + "\\GhostScriptDll"
MagickNET.SetGhostscriptDirectory(rawpath);
MagickReadSettings settings = new MagickReadSettings();
settings.Density = new Density(300, 300);
List<string> intList = new List<string>() { };
using (MagickImageCollection images = new MagickImageCollection())
{
images.Read($"{rawFileLocation}{model.OriginalDocName}", settings);
int page = 1;
string tempName = "";
foreach (MagickImage image in images)
{
tempName = System.IO.Path.GetRandomFileName().Replace(".", string.Empty) + "_processed_" + page + ".png";
image.Write($"{processedFileLocation}{tempName}");
intList.Add(tempName);
page++;
}
}
i doubt in this part of error D:/local/Temp/magick-MB0cs71xMgZUfIHIwbzlzehBIlLL-NED"' (The system cannot find the file specified.
) # error/delegate.c/ExternalDelegateCommand/475 ...i dont find the local/temp/.. folder in server though

Can't return word document, generated in memory stream, for downloading to user

I've got a problem while resolving one task. The task was: Create an opportunity for users to download a .docx document with pasted data. But I'm stuck at the moment at sending the file as a byte array (taken from a MemoryStream) to the context's response. Here's a sample:
using (MemoryStream stream = new MemoryStream(FileBytes))
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(stream, true))
{
MainDocumentPart mainPart = myDoc.MainDocumentPart;
foreach (SdtElement obj in mainPart.Document.Body.Descendants<SdtElement>().ToList())
{
foreach (Text t in obj.Descendants<Text>().ToList())
{
switch (t.Text)
{
//.... here is code that fiiling content control's
}
}
}
myDoc.MainDocumentPart.Document.Save();
myDoc.Close();
}
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.AddHeader("content-disposition", "attachment; filename=\"" + DocName + ".docx\"");
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
context.Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
stream.Seek(0, SeekOrigin.Begin);
context.Response.BinaryWrite(stream.ToArray());
}
context.Response.Flush();
The HTTP handler doesn't return any errors - page refresh and download don't start. The handler is calling from JS. Here is the sample of the JS function:
function save_word_doc(id_btn) {
// ... here is code that gets params from default page data
jQuery.post("DataHandler.ashx?CN=" + vCN + "&CommandName=SaveWord&auctionID=" + oFormRecord.auctionID
+ "&user_login=" + user_login
+ ....
+ "&amount=" + oFormRecord.value.amount
+ "&percent=" + percent);
}
By the way, this sample code is working well in an ASP.Net MVC project, where the handler is calling from a link button. But this must work in a Web Forms project.
Update to pretend questions and incorrect answers: the file is generated and saved correctly to the local machine.
I see a few issues in your code. Firstly, new MemoryStream(FileBytes) creates a non-resizable MemoryStream, which is not what you want in case you are changing the WordprocessingDocument. You would should use new MemoryStream() to create a resizable MemoryStream and copy your FileBytes to that MemoryStream.
Secondly, since you are in a using statement, you don't need the following two lines of code. This is done automatically for you.
myDoc.MainDocumentPart.Document.Save();
myDoc.Close();
Lastly, I am not sure about your ContentEncoding value for the binary data you are sending. You might want to use a tool like Fiddler or Postman to verify what happens.

Dynamic FTP Folder pipeline

I'm trying to set Dynamically the output folder of an FTP location.
Assignment, for each customer I need to create a separate folder to store an Excel file and / or XML file.
What I've tried
Created a Custom Pipeline Component to set all the required Properties into a FTP send port.
Tried the same pipeline into a Dynamic Send Port
For testing tried the code in an Orchestration.
What I've noticed:
When I send through the FTP Send Port the properties won't be overridden by the custom pipeline properties.
When I send through the Dynamic I always get the following error
A failure was encountered while transmiting the message
Even when I'm trying to set the properties into the Orchestration I get the same error.
Also when I'm trying to send through the Dynamic Send Port I notice that the pipeline component is not touched.
Execute code part of the custom pipeline component
public IBaseMessage Execute(IPipelineContext pipelineContext, IBaseMessage inputMessage)
{
Guid callToken = TraceManager.PipelineComponent.TraceIn(CLASSNAME + ".Execute() - Start", pipelineContext.PipelineID, pipelineContext.PipelineName, pipelineContext.StageID);
if (!this.Active)
{
TraceManager.PipelineComponent.TraceOut(callToken, CLASSNAME + ".Execute() - Pipeline component is not active!");
return inputMessage;
}
try
{
string completeFTPUri = null;
string fileName = null;
string accountNumber = Convert.ToString(inputMessage.Context.Read(PROP_ACCOUNTNUMBER.Name.Name, PROP_ACCOUNTNUMBER.Name.Namespace));
if (!string.IsNullOrWhiteSpace(accountNumber))
this.Folder = string.Format("{0}/{1}", this.Folder, accountNumber);
if (!string.IsNullOrWhiteSpace(this.Folder))
completeFTPUri = string.Format("ftp://{0}:21/{1}", this.FTPUri, this.Folder);
else
completeFTPUri = this.FTPUri;
if (!UseDefaultFilename)
{
string receiveFilename = null;
receiveFilename = Convert.ToString(inputMessage.Context.Read(FTP_RECEIVED_FILENAME.Name.Name, FTP_RECEIVED_FILENAME.Name.Namespace));
if (!string.IsNullOrWhiteSpace(receiveFilename))
fileName = Path.GetFileName(receiveFilename);
}
if (string.IsNullOrWhiteSpace(fileName))
{
if (string.IsNullOrWhiteSpace(this.Filename))
fileName = DEFAULT_FILENAME;
else
fileName = this.Filename;
}
if (fileName.Contains("{0") || fileName.Contains("{1"))
{
fileName = string.Format(fileName, DateTime.Now, inputMessage.MessageID);
}
if (!string.IsNullOrWhiteSpace(this.Folder))
{
//inputMessage.Context.Write(FTP_BEFORE_PUT.Name.Name, FTP_BEFORE_PUT.Name.Namespace, string.Format("MKDIR {0}", string.Format("ftp://{0}:21/{1}", this.FTPUri, this.Folder)));
inputMessage.Context.Promote(FTP_BEFORE_PUT.Name.Name, FTP_BEFORE_PUT.Name.Namespace, string.Format("MKDIR {0}", completeFTPUri));
}
//inputMessage.Context.Write(OUTBOUND_TRANSPORT_LOCATION.Name.Name, OUTBOUND_TRANSPORT_LOCATION.Name.Namespace, completeFTPUri);
//inputMessage.Context.Write(FILE_RECEIVED_FILENAME.Name.Name, FILE_RECEIVED_FILENAME.Name.Namespace, fileName);
//inputMessage.Context.Write(FTP_USERNAME.Name.Name, FTP_USERNAME.Name.Namespace, _userName);
//inputMessage.Context.Write(FTP_PASSWORD.Name.Name, FTP_PASSWORD.Name.Namespace, _password);
inputMessage.Context.Promote(OUTBOUND_TRANSPORT_LOCATION.Name.Name, OUTBOUND_TRANSPORT_LOCATION.Name.Namespace, completeFTPUri);
inputMessage.Context.Promote(OUTBOUND_TRANSPORT_TYPE.Name.Name, OUTBOUND_TRANSPORT_TYPE.Name.Namespace, "FTP");
inputMessage.Context.Promote(FILE_RECEIVED_FILENAME.Name.Name, FILE_RECEIVED_FILENAME.Name.Namespace, fileName);
inputMessage.Context.Promote(FTP_USERNAME.Name.Name, FTP_USERNAME.Name.Namespace, this.UserName);
inputMessage.Context.Promote(FTP_PASSWORD.Name.Name, FTP_PASSWORD.Name.Namespace, this.Password);
}
catch (Exception ex)
{
TraceManager.PipelineComponent.TraceError(ex, false, callToken);
throw new Exception(CLASSNAME + ".Execute() - Failed to set the filename.", ex);
}
TraceManager.PipelineComponent.TraceOut(callToken, CLASSNAME + ".Execute() - Finished.");
return inputMessage;
}
EDIT:
After trying a lot this morging an update.
When I try to Send Dynamicly through the Static SendPort I keep the same issue.
When I try to Send Dynamicly through a Dynamic SendPort I'm getting different error:
Inner exception: The value assigned to property 'Microsoft.XLANGs.BaseTypes.Address' is not valid: 'FTP URI'.
I don't know what the best solution is to resolve this issue.
I can also write everything to a helper class en try to send through C# code. But I want to use the force of BizTalk and want to be able to enable en disable ports when necessary. That's the main reason.
I'm not afraid to write custom pipeline components or somthing else, so if someone could help. PLEASE
Code of the Message Assign of the Orchestration
MsgPublishArticleMessage = MsgFullArticleMessage;
MsgPublishArticleMessage(*) = MsgFullArticleMessage(*);
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Domain) = "ArticleMessage";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Service) = "PricatService";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Action) = "PublishPricatXLSX";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Version) = "1.0";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.AccountNumber) = articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(BTS.OutboundTransportLocation) = "ftp://URI:21/Pricat/" + articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(BTS.OutboundTransportType) = "FTP";
MsgPublishArticleMessage(FTP.Password) = "********";
MsgPublishArticleMessage(FTP.UserName) = "UserName";
MsgPublishArticleMessage(FTP.BeforePut) = "MKDIR " + articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(FTP.ReceivedFileName) = Destil.BizTalk.ArticleMessage.Components.OrchestrationHelper.CreateReceivedFileName(articleMessageRequest, ".xlsx");
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.Address) = "FTPURI";
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.TransportType) = "FTP";
MsgPublishArticleMessage(BTS.IsDynamicSend) = true;
EDIT 2:
When I change the Message Assingment to below code I can send the file to a dynamic folder.
The only problem I'm running into now:
When the Folder already exist I'm getting a failure.
Does anyone know what FTP command I need to use to create a Folder only if it don't exist?
I've try'ed the following commands
MDK -p /Pricat/AccountNumber;
MDK /Pricat/AccountNumber;
if not exist "/Pricat/AccountNumber" MDK /Pricat/AccountNumber
Changed code of message assign in the orchestration
MsgPublishArticleMessage = MsgFullArticleMessage;
MsgPublishArticleMessage(*) = MsgFullArticleMessage(*);
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Domain) = "ArticleMessage";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Service) = "PricatService";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Action) = "PublishPricatXLSX";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.Version) = "1.0";
MsgPublishArticleMessage(DOMAIN.BizTalk.Common.Schemas.AccountNumber) = articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(BTS.OutboundTransportLocation) = "ftp://URI:21/Pricat/" + articleMessageRequest.AccountNumber;
MsgPublishArticleMessage(BTS.OutboundTransportType) = "FTP";
MsgPublishArticleMessage(FTP.Password) = "*********";
MsgPublishArticleMessage(FTP.UserName) = "username";
MsgPublishArticleMessage(FTP.BeforePut) = "MKD Pricat/" + articleMessageRequest.AccountNumber + "; CWD Pricat/" + articleMessageRequest.AccountNumber;
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.Address) = "ftp://URI:21/" + DOMAIN.BizTalk.ArticleMessage.Components.OrchestrationHelper.CreateReceivedFileName(articleMessageRequest, ".xlsx");
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.TransportType) = "FTP";
MsgPublishArticleMessage(BTS.IsDynamicSend) = true;
From the code snippet you have provided, can you check the below line.
PublishArticleMessagePort(Microsoft.XLANGs.BaseTypes.Address) = "FTPURI";
You have declared FTPURI as a variable and assigning a constant string to the address. This might explain the error -
Inner exception: The value assigned to property 'Microsoft.XLANGs.BaseTypes.Address' is not valid: 'FTP URI'.
When overwriting static send port properties you have to give adapter know that it should use message properties instead of port properties.
Set IsDynamicSend property to true
inmsg.Context.Promote("IsDynamicSend", "http://schemas.microsoft.com/BizTalk/2003/system-properties", true);

Uploading Image Access to C drive denied

so i have this code:
try
{
if ((uplImage.FileName != ""))
{
//to allow only jpg gif and png files to be uploaded.
string extension = Path.GetExtension(uplImage.PostedFile.FileName);
if (((extension == ".jpg") || ((extension == ".gif") || (extension == ".png"))))
{
DALBio bio = new DALBio();
byte[] raw;
FileStream fs = new FileStream(uplImage.PostedFile.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
raw = new byte[fs.Length];
fs.Read(raw, 0, Convert.ToInt32(fs.Length));
bio.PlayerID = Session["playerID"].ToString();
bio.Pending = 'Y';
bio.Photo = raw;
DALBio.insertImage(bio);
}
}
}
catch (Exception e1)
{
Label1.Text = e1.InnerException.ToString();
}
and the program breaks on the FileStream fs = new FileStream line.
at first my image was in my downloads folder and it said access to c:\prog(x86)\filefolder\file\folder\and so on was denied
so i moved it to my images folder, and i got the same error to a different folder on c.
my google searches have said it oculd be a permissions thing (if its UAC, that makes no sense, i have all permissions possible across the board). another thing is it could be a change in my web.config file about application settings, however without any examples or better insight than what i did get from those searches, i am lost.
You have to give account under which ASP.NET worker process runs "write" permissions. Ordinary it's Network Services account.

Itext, access denied on htmlworker.parseToList

I have spent far too long trying to work out why I am getting an access denied here so I am
really hoping someone can help?
I am using itextsharp, the latest version downloaded today.
I am parsing an html page within my own project so I can convert it to pdf, but everytime I run
it I get an access denied on path c:\
For starters I cannot work out why it's trying to access the c drive other than the website directory which it definitely has access to.
And I have tried adding network service with full permission to everything but it didn't work.
I even impersonated an admin user in the web config but I still got access denied.
My code is:
string download = new WebClient().DownloadString("http://" + HttpContext.Current.Request.Url.Host + "/pagetoparse.aspx?user=" + userName);
string tempFolder = HttpContext.Current.Server.MapPath("pdfs");
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
}
string fileName = Path.Combine(tempFolder, "test3.pdf");
Document document = new Document(PageSize.A4, 80, 50, 30, 65);
try
{
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
using (StringReader stringReader = new StringReader(download))
{
List<IElement> parsedList = HTMLWorker.ParseToList(stringReader, null);//<-- fails here!
document.Open();
foreach (object item in parsedList)
{
document.Add((IElement)item);
}
document.Close();
}
}
catch (Exception exc)
{
Console.Error.WriteLine(exc.Message);
}
return document;
It must be obvious, what I am doing wrong??
Bex
Arrrgh! And the answer is:
An empty image tag! It tried to parse it as a path!!

Resources