A generic error occurred in GDI+ - c#

Hı I'm trying to take some data and pictures from a web page. I can take data and some pictures but sometimes it gives error when taking pictures
error is =
System.Drawing---->Void Save(System.String, System.Drawing.Imaging.ImageCodecInfo, System.Drawing.Imaging.EncoderParameters)
A generic error occurred in GDI+.
where is my fault ?
my code is:
if (!added)
{
i = 0;
object[] array = new object[6];
HtmlElementCollection aad = webBrowser2.Document.GetElementsByTagName("p");
array[3] = aad[4].InnerHtml;
array[1] = aad[3].InnerHtml;
array[2] = aad[6].InnerHtml;
aad = webBrowser2.Document.GetElementsByTagName("h1");
array[0] = aad[0].InnerHtml;
aad = webBrowser2.Document.GetElementsByTagName("span");
array[4] = aad[3].InnerHtml.Replace("<BR>", "\n");
array[5] = webBrowser2.Document.Url.ToString();
timer1.Enabled = false;
added = true;
get = true;
HtmlElementCollection imgs = webBrowser2.Document.Images;
if (Directory.Exists(Convert.ToString(array[1])))
{
}
else
{
Directory.CreateDirectory("" + array[1]);
}
IHTMLDocument2 doc = (IHTMLDocument2)webBrowser2.Document.DomDocument;
IHTMLControlRange imgRange = (IHTMLControlRange)((HTMLBody)doc.body).createControlRange();
var clip = Clipboard.GetDataObject();
int iaa = 0;
foreach (IHTMLImgElement img in doc.images)
{
try
{
if (img.nameProp.Contains("zoom"))
{
imgRange.add((IHTMLControlElement)img);
imgRange.execCommand("Copy", false, null);
using (Bitmap bmp = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap))
{
try
{
bmp.Save(#"" + Application.StartupPath + "\\" + array[1] + "\\" + img.nameProp, ImageFormat.Jpeg);
richTextBox2.Text += img.nameProp + " Saved " + array[1];
iaa++;
}
catch
{
bmp.Save(#"" + Application.StartupPath + "\\" + array[1] + "\\" + img.nameProp, ImageFormat.Bmp);
richTextBox2.Text += img.nameProp + " Saved as bmp due error for " + array[1]+"\n";
iaa++;
}
}
}
}
catch(Exception ex)
{
HtmlElementCollection aads = webBrowser2.Document.GetElementsByTagName("p");
richTextBox2.Text += ex.Source + "---->" + ex.TargetSite + "\n" + ex.Message + "\n" + ex.InnerException + "\n" + aads[3].InnerHtml + "\n"+img.nameProp+"\n";
}
}
a.Tables[0].Rows.Add(array);
Clipboard.SetDataObject(clip);
richTextBox2.Text += "Product " + array[1] + " Succesfully Added with " + (iaa-1).ToString() + " images \n ";
}

sometimes it gives error
Analyze when that happens. If it always happens for the same image file, download it using your browser and inspect the image. If it happens randomly, it might be that the image isn't loaded yet for example.
You can create a static HTML page to test this, manually adding images to test with.
Alternatively, you can use Html Agility Pack to find all img elements and download the resource behind their src URL with HttpWebRequest for example.

Related

out of memory exception while drawing image in asp.net

We are drawing and editing pdf by using the following code,but when we play with 11mb size file,we are getting out of memory exception,can we fix the issue,I had used System.Drawing.Image.FromFile instead of FromStream but no luck..
public static string ImageCar()
{
string FileName = HttpContext.Current.Session["filename"].ToString();
Document doc = new Document(FileName);
ArrayList arrFiles = new ArrayList();
string strFileName = "";
for (int pageCount = 1; pageCount <= TotalPages; pageCount++)
{
using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath("Input/image_" + strDateTime + "_" + pageCount + ".png"), FileMode.Create, FileAccess.ReadWrite))
{
strFileName = HttpContext.Current.Server.MapPath("Path" + strDateTime + "_" + pageCount + ".png");
arrFiles.Add(strFileName);
PngDevice pngDevice = new PngDevice();
//Convert a particular page and save the image to stream
pngDevice.Process(doc.Pages[pageCount], imageStream);
using (System.Drawing.Image image = System.Drawing.Image.FromStream(imageStream))
{
ScaleImage(image, 1189, 835, HttpContext.Current.Server.MapPath("Input/image1_" + strDateTime + "_" + pageCount + ".png"), out height, out Aratio);
image.Dispose();
imageStream.Close();
if (pageCount == 1)
fields = CheckFields(doc, pageCount, "image1_" + strDateTime + "_" + pageCount + ".png", fields, Convert.ToDouble(Aratio), licensed);
pages = pages + "," + "image1_" + strDateTime + "_" + pageCount + ".png";
Ratios = Ratios + "," + Aratio;
Allheights = Allheights + "," + height;
// Delete file from image folder
try
{
if (File.Exists(strFileName))
{
File.Delete(strFileName);
}
}
catch (Exception ex)
{
}
}
}
}
Ratios = Ratios.Substring(1, Ratios.Length - 1);
pages = pages.Substring(1, pages.Length - 1);
Allheights = Allheights.Substring(1, Allheights.Length - 1);
if (fields != "")
{
fields = fields.Substring(3, fields.Length - 3);
}
return pages + "%#" + Ratios + "%#" + Allheights + "%#" + fields;
}
System.Drawing has known memory leaks in a ASP site, and should never be used.
It will eventually case OOM errors, and while you can avoid it by restarting the server every so often, or throwing more memory at it, there is no real, long term fix. Use some other library for the image manipulation portion, and you should have less issues.
See the bottom of this page:
https://msdn.microsoft.com/en-us/library/system.drawing(v=vs.110).aspx
Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. For a supported alternative, see Windows Imaging Components.

Try Catch Block not preventing exception

I am building a program that will move a bunch of files.
if (line.Contains("INSERT INTO BACKLOGITEM_ATTACHMENT VALUES"))
{
string AttachementID = line.Split(',', ')')[1];
string FileName = AttachementsDictionary[AttachementID];
string BacklogScrumID = BacklogLookupDictionary[AttachementID];
BacklogItem Story = BacklogItemDictionary[BacklogScrumID];
Product Product = ProductDictionary[Story.ProductScrumId];
string FileToCopy = "\\\\dxScrum01v\\ScrumWorksPro\\scrumworks\\data\\attachments\\product" + Story.ProductScrumId + "\\attachement" + AttachementID;
string FileToSave = "C:\\ScrumWorksAttachementExport\\" + Product.ProductName + "\\" + Product.StoryPrefix + "-" + Story.StoryTitle + "\\" + FileName;
//Console.WriteLine(FileToCopy + " >>> " + FileToSave);
try
{
File.Copy(#FileToCopy, #FileToSave);
}
catch (Exception)
{
Console.WriteLine("Failed: " + FileToSave);
throw;
}
}
The issue is that I am getting an exception when running the program. There are times when the file does not exist.
How can I make it so that if it fails it just outputs the failure and keeps going?
Remove throw; if you dont want your application to break, you can handle the exception too

Problem with C# File IO in Winforms

I'm having issues with a C# Winforms file IO. The code complies just fine, but then it returns errors on execution.
The output code is here:
private void saveData()
{
string fullPath = System.Environment.GetEnvironmentVariable(#"%MyDocuments%\HellsingRPG\");
StreamWriter writer = new StreamWriter(fullPath + textBox2.Text + ".txt");
writer.WriteLine(textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + "," + textBox4.Text + "," + comboBox1.SelectedText + "," +
numericUpDown25.Value + "," + numericUpDown1.Value + "," + numericUpDown2.Value + "," + numericUpDown3.Value + "," + numericUpDown4.Value + "," +
numericUpDown5.Value + "," + numericUpDown6.Value + "," + numericUpDown7.Value + "," + numericUpDown8.Value + "," + numericUpDown9.Value + "," +
numericUpDown10.Value + "," + numericUpDown11.Value + "," + numericUpDown12.Value + "," + numericUpDown13.Value + "," + numericUpDown14.Value
+ "," + numericUpDown15.Value + "," + numericUpDown16.Value + "," + numericUpDown17.Value + "," + numericUpDown18.Value + "," +
numericUpDown19.Value + "," + numericUpDown20.Value + "," + numericUpDown21.Value + "," + numericUpDown22.Value);
writer.Close();
}
And the code to load the data is here:
private void loadData()
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = System.Environment.GetEnvironmentVariable(#"%MyDocuments%\HellsingRPG\");
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
List<string> myData = parseCSV(System.Convert.ToString(myStream));
textBox1.Text = myData[0];
textBox2.Text = myData[1];
textBox3.Text = myData[3];
textBox4.Text = myData[4];
comboBox1.SelectedText = myData[5];
numericUpDown25.Value = System.Convert.ToDecimal(myData[6]);
numericUpDown1.Value = System.Convert.ToDecimal(myData[7]);
numericUpDown2.Value = System.Convert.ToDecimal(myData[8]);
numericUpDown3.Value = System.Convert.ToDecimal(myData[9]);
numericUpDown4.Value = System.Convert.ToDecimal(myData[10]);
numericUpDown5.Value = System.Convert.ToDecimal(myData[11]);
numericUpDown6.Value = System.Convert.ToDecimal(myData[12]);
numericUpDown7.Value = System.Convert.ToDecimal(myData[13]);
numericUpDown8.Value = System.Convert.ToDecimal(myData[14]);
numericUpDown9.Value = System.Convert.ToDecimal(myData[15]);
numericUpDown10.Value = System.Convert.ToDecimal(myData[16]);
numericUpDown11.Value = System.Convert.ToDecimal(myData[17]);
numericUpDown12.Value = System.Convert.ToDecimal(myData[18]);
numericUpDown13.Value = System.Convert.ToDecimal(myData[19]);
numericUpDown14.Value = System.Convert.ToDecimal(myData[20]);
numericUpDown15.Value = System.Convert.ToDecimal(myData[21]);
numericUpDown16.Value = System.Convert.ToDecimal(myData[22]);
numericUpDown17.Value = System.Convert.ToDecimal(myData[23]);
numericUpDown18.Value = System.Convert.ToDecimal(myData[24]);
numericUpDown19.Value = System.Convert.ToDecimal(myData[25]);
numericUpDown20.Value = System.Convert.ToDecimal(myData[26]);
numericUpDown21.Value = System.Convert.ToDecimal(myData[27]);
numericUpDown22.Value = System.Convert.ToDecimal(myData[28]);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
And that compiles just fine. But when I use it, I get the following errors:
"Could not find file "C:\Users\collmark\Documents\Visual Studio
2015\Projects\WindowsFormsApplication1\WindowsFormsApplication1\bin\Release\System.IO.Filestream".
"Error: Could not read file from disk. Original error: Index out of
range. Must be non-negative and less than the size of the collection.
Parameter name: index."
Thanks
your save data seems to save 22 fields while the read expects 28.
I suspect the myData object does not contain the fields index you are trying to read, hence index out of range.
do yourself a favour when printing exception data don't limit yourself to the message but print the whole stack trace, it will tell you which line is faulty giving you a hint at the actual problem.
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.ToString());

Code for Google Analytic product hit in c#

I'm new in google analytic. I go through some regarding this. I found that there is no direct method to hit a windows application in google analytic. But i found some solutions in stackoverflow. I tried that, but didn't work for me. Below is the code that I'm using.
private void analyticsmethod4(string trackingId, string pagename)
{
Random rnd = new Random();
long timestampFirstRun, timestampLastRun, timestampCurrentRun, numberOfRuns;
// Get the first run time
timestampFirstRun = DateTime.Now.Ticks;
timestampLastRun = DateTime.Now.Ticks - 5;
timestampCurrentRun = 45;
numberOfRuns = 2;
// Some values we need
string domainHash = "123456789"; // This can be calcualted for your domain online
int uniqueVisitorId = rnd.Next(100000000, 999999999); // Random
string source = "Shop";
string medium = "medium123";
string sessionNumber = "1";
string campaignNumber = "1";
string culture = Thread.CurrentThread.CurrentCulture.Name;
string screenRes = Screen.PrimaryScreen.Bounds.Width + "x" + Screen.PrimaryScreen.Bounds.Height;
string statsRequest = "http://www.google-analytics.com/__utm.gif" +
"?utmwv=4.6.5" +
"&utmn=" + rnd.Next(100000000, 999999999) +
// "&utmhn=hostname.mydomain.com" +
"&utmcs=-" +
"&utmsr=" + screenRes +
"&utmsc=-" +
"&utmul=" + culture +
"&utmje=-" +
"&utmfl=-" +
"&utmdt=" + pagename + // Here i passed my profile name "MyWindowsApp"
"&utmhid=1943799692" +
"&utmr=0" +
"&utmp=" + pagename +
"&utmac=" + trackingId + //Tracking id : ie "UA-XXXXXXXX-X"
"&utmcc=" +
"__utma%3D" + domainHash + "." + uniqueVisitorId + "." + timestampFirstRun + "." + timestampLastRun + "." + timestampCurrentRun + "." + numberOfRuns +
"%3B%2B__utmz%3D" + domainHash + "." + timestampCurrentRun + "." + sessionNumber + "." + campaignNumber + ".utmcsr%3D" + source + "%7Cutmccn%3D(" + medium + ")%7Cutmcmd%3D" + medium + "%7Cutmcct%3D%2Fd31AaOM%3B";
try
{
using (var client = new WebClient())
{
//byte[] bt = client.DownloadData(statsRequest);
Stream data = client.OpenRead(statsRequest);
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
MessageBox.Show(s);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This example is also got from this site itself. I don't know where was the problem. Please direct me, how can i make it. This is the output i'm getting "GIF89a".
Thanks
Bobbin Paulose
So it's working. The Google Analytics call loads a tiny GIF image, and the querystring parameters provided in the request trigger all the Google Analytics goodness. If you're getting a response back, you have registered your event successfully with Google.

How to convert a HTML File to PDF using WkHTMLToSharp / wkhtmltopdf with Images in C#

I am generating HTML files on the fly, and I would like to create a PDF from the final file. I am using the following to generate the HTML file:
public static void WriteHTML(string cFile, List<Movie> mList)
{
int lineID = 0;
string strHeader, strMovie, strGenre, tmpGenre = null;
string strPDF = null;
// initiates streamwriter for catalog output file
FileStream fs = new FileStream(cFile, FileMode.Create);
StreamWriter catalog = new StreamWriter(fs);
strHeader = "<style type=\"text/css\">\r\n" + "<!--\r\n" + "tr#odd {\r\n" + " background-color:#e2e2e2;\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "\r\n" + "tr#even {\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "div#title {\r\n" + " font-size:16px;\r\n" + " font-weight:bold;\r\n" + "}\r\n" + "\r\n" + "div#mpaa {\r\n" + " font-size:10px;\r\n" + "}\r\n" + "\r\n" + "div#genre {\r\n" + " font-size:12px;\r\n" + " font-style:italic;\r\n" + "}\r\n" + "\r\n" + "div#plot {\r\n" + " height: 63px;\r\n" + " font-size:12px;\r\n" + " overflow:hidden;\r\n" + "}\r\n" + "-->\r\n" + "</style>\r\n" + "\r\n" + "<html>\r\n" + " <body>\r\n" + " <table>\r\n";
catalog.WriteLine(strHeader);
strPDF = strHeader;
foreach (Movie m in mList)
{
tmpGenre = null;
strMovie = lineID == 0 ? " <tr id=\"odd\" style=\"page-break-inside:avoid\">\r\n" : " <tr id=\"even\" style=\"page-break-inside:avoid\">\r\n";
catalog.WriteLine(strMovie);
strPDF += strMovie;
foreach (string genre in m.Genres)
tmpGenre += ", " + genre + "";
strGenre = tmpGenre != null ? tmpGenre.Substring(2) : null;
strMovie = " <td>\r\n" + " <img src=\".\\images\\" + m.ImageFile + "\" width=\"75\" height=\"110\">\r\n" + " </td>\r\n" + " <td>\r\n" + " <div id=\"title\">" + m.Title + "</div>\r\n" + " <div id=\"mpaa\">" + m.Certification + " " + m.MPAA + "</div>\r\n" + " <div id=\"genre\">" + strGenre + "</div>\r\n" + " <div id=\"plot\">" + m.Plot + "</div>\r\n" + " </td>\r\n" + " </tr>\r\n";
catalog.WriteLine(strMovie);
strPDF += strMovie;
lineID = lineID == 0 ? 1 : 0;
}
string closingHTML = " </table>\r\n" + " </body>\r\n" + "</html>";
catalog.WriteLine(closingHTML);
strPDF += closingHTML;
WritePDF(strPDF, cFile + ".PDF");
catalog.Close();
}
Once completed, I want to call the following function to generate the PDF file:
public static void WritePDF(string cFile, string pdfFile)
{
WkHtmlToPdfConverter w = new WkHtmlToPdfConverter();
byte[] strHTML = w.Convert(cFile);
File.WriteAllBytes(pdfFile, strHTML);
w.Dispose();
}
I've discovered that the .Convert function will convert HTML code to PDF, not a file. Secondly, when I pass in the HTML code directly, the images are not appearing in the PDF. I know there is an issue with .GIF files, but these are all .JPG files.
I've read a lot about how good wkhtmltopdf is, and the guy who wrote WkHTMLToSharp posted his project all over SO, but I've been disappointed by the lack of documentation for it.
I WANT to be able to pass in a file to convert, change the margins (I know this is possible, I just need to figure out the correct settings), have it convert images correctly, and most importantly, to not break up my items across multiple pages (support "page-break-inside:avoid" or something similar).
I'd love to see how others are using this!
I have coded an example about how to create a PDF from HTML. I just updated it to also print images.
https://github.com/hmadrigal/playground-dotnet/tree/master/MsDotNet.PdfGeneration
(In my blog post I explain most of the project https://hmadrigal.wordpress.com/2015/10/16/creating-pdf-reports-from-html-using-dotliquid-markup-for-templates-and-wkhtmltoxsharp-for-printing-pdf/ )
Pretty much you have two options:
1: Using file:// and the fullpath to the file.
<img alt="profile" src="{{ employee.PorfileFileName | Prepend: "Assets\ProfileImage\" | ToLocalPath }}" />
2: Using URL Data (https://en.wikipedia.org/wiki/Data_URI_scheme)
<img alt="profile" src="data:image/png;base64,{{ employee.PorfileFileName | Prepend: "Assets\ProfileImage\" | ToLocalPath | ToBase64 }}" />
Cheers,
Herb
Use WkHtmlToXSharp.
Download the latest DLL from Github
public static string ConvertHTMLtoPDF(string htmlFullPath, string pageSize, string orientation)
{
string pdfUrl = htmlFullPath.Replace(".html", ".pdf");
try
{
#region USING WkHtmlToXSharp.dll
//IHtmlToPdfConverter converter = new WkHtmlToPdfConverter();
IHtmlToPdfConverter converter = new MultiplexingConverter();
converter.GlobalSettings.Margin.Top = "0cm";
converter.GlobalSettings.Margin.Bottom = "0cm";
converter.GlobalSettings.Margin.Left = "0cm";
converter.GlobalSettings.Margin.Right = "0cm";
converter.GlobalSettings.Orientation = (PdfOrientation)Enum.Parse(typeof(PdfOrientation), orientation);
if (!string.IsNullOrEmpty(pageSize))
converter.GlobalSettings.Size.PageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), pageSize);
converter.ObjectSettings.Page = htmlFullPath;
converter.ObjectSettings.Web.EnablePlugins = true;
converter.ObjectSettings.Web.EnableJavascript = true;
converter.ObjectSettings.Web.Background = true;
converter.ObjectSettings.Web.LoadImages = true;
converter.ObjectSettings.Load.LoadErrorHandling = LoadErrorHandlingType.ignore;
Byte[] bufferPDF = converter.Convert();
System.IO.File.WriteAllBytes(pdfUrl, bufferPDF);
converter.Dispose();
#endregion
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
return pdfUrl;
}
You can use Spire.Pdf to do so.
This component could convert html to pdf.
PdfDocument pdfdoc = new PdfDocument();
pdfdoc.LoadFromHTML(fileFullName, true, true, true);
//String url = "http://www.e-iceblue.com/";
//pdfdoc.LoadFromHTML(url, false, true, true);
pdfdoc.SaveToFile("FromHTML.pdf");
We're also using wkhtmltopdf and are able to render images correctly. However, by default the rendering of images is disabled.
You have to specify those options on your converter instance:
var wk = _GetConverter()
wk.GlobalSettings.Margin.Top = "20mm";
wk.GlobalSettings.Margin.Bottom = "10mm";
wk.GlobalSettings.Margin.Left = "10mm";
wk.GlobalSettings.Margin.Right = "10mm";
wk.GlobalSettings.Size.PaperSize = PdfPaperSize.A4;
wk.ObjectSettings.Web.PrintMediaType = true;
wk.ObjectSettings.Web.LoadImages = true;
wk.ObjectSettings.Web.EnablePlugins = false;
wk.ObjectSettings.Web.EnableJavascript = true;
result = wk.Convert(htmlContent);

Categories

Resources