C# Function works on development machine but fails on web - c#

I have this function in my Visual Studio web app and it seems to work just fine when I run the project on the development machine, but when I publish it to the web and go to the page where the function runs, it always runs the catch exception part. Can anyone help? I'm scratching my head here :( Here is the code for the function.
public void printData()
{
try
{
//The path to the Bid Form
string pdfPath = Server.MapPath("PDF/Bid_Form.pdf");
var pdfReader = new PdfReader(pdfPath);
var pdfOutput = new MemoryStream();
var pdfStamper = new PdfStamper(pdfReader, pdfOutput);
CultureInfo ci = new CultureInfo("en-US");
//This code block gets the date
string date = BidDateTextBox.Value;
DateTime dateNow = Convert.ToDateTime(date);
string newDate = dateNow.ToString("MMMM dd, yyyy", ci);
//This gets the values from the hidden fields
decimal airTotal = (Convert.ToDecimal(at.Value) + Convert.ToDecimal(att.Value));
decimal waterTotal = (Convert.ToDecimal(wt.Value) + Convert.ToDecimal(wtt.Value));
decimal preTestAir = String.IsNullOrEmpty(AirPreTestTextBox.Value) ? 0 : decimal.Parse(AirPreTestTextBox.Value);
decimal preTestWater = String.IsNullOrEmpty(WaterPreTestTextBox.Value) ? 0 : decimal.Parse(WaterPreTestTextBox.Value);
decimal preTestCombine = preTestAir + preTestWater;
decimal airTotalAll = (Convert.ToDecimal(at.Value) + Convert.ToDecimal(att.Value) + preTestAir);
decimal waterTotalAll = (Convert.ToDecimal(wt.Value) + Convert.ToDecimal(wtt.Value) + preTestWater);
//This line gets the total of all areas
decimal combineTotal = Convert.ToDecimal(gt.Value);
//This line gets the checked check boxes in the Per Specifications area
string selectedSpecItems = (String.Join(",", CheckBoxList1.Items.OfType<ListItem>().Where(r => r.Selected).Select(r => r.Text)) + ", " + CustomSpecTextBox.Value);
//This line gets the checked check boxes in the Exclusions area
string selectedExItems = (String.Join(",", CheckBoxList2.Items.OfType<ListItem>().Where(r => r.Selected).Select(r => r.Text)) + ", " + CustomExcTextBox.Value);
//This checks if the pre test check box is checked. If so it doesnt include the pretest amounts.
if (PreTestCheckBox.Checked) {
pdfStamper.AcroFields.SetField("PreTestAirBid", "$" + preTestAir);
pdfStamper.AcroFields.SetField("PreTestWaterBid", "$" + preTestWater);
pdfStamper.AcroFields.SetField("PreTestCombineBid", "$" + preTestCombine);
pdfStamper.AcroFields.SetField("PreTestText", "Pre-Test");
pdfStamper.AcroFields.SetField("AirBid", "$" + airTotal);
pdfStamper.AcroFields.SetField("WaterBid", "$" + waterTotal);
pdfStamper.AcroFields.SetField("CombineBid", "$" + combineTotal);
}
else
{
pdfStamper.AcroFields.SetField("PreTestAirBid", "");
pdfStamper.AcroFields.SetField("PreTestWaterBid", "");
pdfStamper.AcroFields.SetField("PreTestCombineBid", "");
pdfStamper.AcroFields.SetField("AirBid", "$" + airTotalAll);
pdfStamper.AcroFields.SetField("WaterBid", "$" + waterTotalAll);
pdfStamper.AcroFields.SetField("CombineBid", "$" + combineTotal);
}
pdfStamper.AcroFields.SetField("Date", "" + newDate);
pdfStamper.AcroFields.SetField("Bid#", "");
pdfStamper.AcroFields.SetField("Location", "" + LocationTextBox.Value);
pdfStamper.AcroFields.SetField("ProjectName", "" + ProjectNameTextBox.Value);
pdfStamper.AcroFields.SetField("Engineer", "" + EngineerTextBox.Value);
pdfStamper.AcroFields.SetField("EngineerPhone", "");
pdfStamper.AcroFields.SetField("EngineerFax", "");
pdfStamper.AcroFields.SetField("Architect", "" + ArchitectTextBox.Value);
pdfStamper.AcroFields.SetField("ArchitectPhone", "");
pdfStamper.AcroFields.SetField("ArchitectFax", "");
pdfStamper.AcroFields.SetField("Specifications", "" + selectedSpecItems);
pdfStamper.AcroFields.SetField("Exclusions", "" + selectedExItems);
pdfStamper.FormFlattening = false;
pdfStamper.Close();
pdfReader.Close();
Response.AddHeader("Content-Disposition", "attachment; filename=NewBid.pdf");
Response.ContentType = "application/pdf";
Response.BinaryWrite(pdfOutput.ToArray());
Response.End();
}
catch (Exception e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorAlert", "alert('An error has occured.');", true);
}
}

Without knowing the exception my guess would be the server does not have appropriate access to the file at the path you are referencing. Try outputting the exception message in the catch block instead of your custom error message. Should help.

Related

How to send information from a DataGridView to a textfile

I am currently working on a weather forecasting application which stores forecasts in a textfile. The functionality of capturing the information into a textfile has been complete. I have also displayed the information in a DataGridView. The issue I have encountered is when a change is made to the DataGridView and the "Save" button is clicked, the updated information must be written to a textfile.
I keep getting a ArgumentOutOfRangeException error on the windspeed1 = dgRow.Cells[8].Value.ToString();
string city1, day, date1, minTemp1, maxTemp1, precipitation1, humidity1, windSpeed1;
foreach (DataGridViewRow dgRow in dataGridView2.Rows)
{
city1 = dgRow.Cells[1].Value.ToString();
day = dgRow.Cells[2].Value.ToString();
date1 = dgRow.Cells[3].Value.ToString();
minTemp1 = dgRow.Cells[4].Value.ToString();
maxTemp1 = dgRow.Cells[5].Value.ToString();
precipitation1 = dgRow.Cells[6].Value.ToString();
humidity1 = dgRow.Cells[7].Value.ToString();
windSpeed1 = dgRow.Cells[8].Value.ToString();
using (StreamWriter sw = new StreamWriter("forecasts.txt", true))
{
sw.WriteLine(city1 + "," + day + "," + date1 + "," + minTemp1 + "," +
maxTemp1 + "," + precipitation1 + "," + humidity1 + "," + windSpeed1);
sw.Close();
}
}

A generic error occurred in GDI+

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.

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);

Payment succeeds, and our data matches querystring data, but falls thru to INVALID anyway!

Why does my ipn script I wrote always fail? It always goes to INVALID even though it matches everything in the query string that paypal sends to me?
notification.cshtml?tx=b78v54b5b55rby92S&st=Completed&amt=3.04&cc=USD&cm=&item_number=&merchant_return_link=Return+to+web+site+name&form_charset=UTF-8
And the part that checks it is:
string LiveURL = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(LiveURL);
// Set request back values.
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] parameters = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string RequestString = System.Text.Encoding.ASCII.GetString(parameters);
RequestString += "&cmd=_notify-validate";
request.ContentLength = RequestString.Length;
// Send request to PP and get response.
StreamWriter Sout = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
Sout.Write(RequestString);
Sout.Close();
StreamReader Sin = new StreamReader(request.GetResponse().GetResponseStream());
string response = Sin.ReadToEnd();
Sin.Close();
if(result != null && result.OrderStatus == "Confirmed")
{
switch(response)
{
case "VERIFIED":
if(Request["st"] == "Completed")
{
var PPQuery = "SELECT TransactionId, OrderTotal FROM Orders WHERE OrderId = '" + Session["OSFOID"] + "' AND UserId = '" + WebSecurity.CurrentUserId + "'";
var ppQueryResult = database.Query(PPQuery);
foreach(var item in ppQueryResult)
{
decimal fff = 3.04M;
if(item["TransactionId"] != Request["tx"])
{
if(item["OrderTotal"] == TotalPrice)
{
// Payment was a success. Convey that to the user.
output = "Thanks. Order complete.";
}
else
{
// Possible fraud. Log it.
}
}
else
{
// This is a duplicate transaction. Log it and Redirect to homepage.
}
}
}
break;
case "INVALID":
output = "Invalid was returned. Investigate further.";
break;
default:
output = "Other exception has occured. Investigate further and log.";
break;
}
}
The code looks fine. The problem must be with response not matching "VERIFIED".
You're not in Turkey by chance, and changing response to uppercase prior to the comparison? *
*) If the locale is Turkey, uppercasing a string turns i into İ, not I (just one of the many traps with string manipulation)
Within the "VERIFIED" block, check:
if (Request.Params["payment_status"] == "Completed")
{
...
}
Request["st"] is incorrect.
Be sure to set IPN URL in one place in PayPal admin and do not use the other form of return URL checking (can't remember the name of it offhand) and IPN at the same time.
There is no "merchant_return_link" parameter; I think it should be "notify_url"... the URL string and the list of params doesn't look right to me; for example: &cm=&item_number
I know your list of params will be unique for your situation, but here's some sample code where I construct the URL to be passed to PayPal:
protected string GetPayPalURL(string SERVER_URL, string business, string[] itemNames,
int[] quantities, decimal[] amounts, double[] weight, string invoiceID, string transID, string NOTIFY_URL)
{
// Customer will be required to specify delivery address to PayPal - VERY IMPORTANT
const string NO_SHIPPING = "2";
StringBuilder url = new StringBuilder();
url.Append(SERVER_URL + "?cmd=_cart&upload=1");
url.Append("&business=" + HttpUtility.UrlEncode(business));
for (int i = 0; i < itemNames.Length; i++)
{
url.Append("&item_name" + "_" + (i + 1).ToString() + "=" + HttpUtility.UrlEncode(itemNames[i]));
url.Append("&quantity" + "_" + (i + 1).ToString() + "=" + quantities[i].ToString().Replace(",", "."));
url.Append("&amount" + "_" + (i + 1).ToString() + "=" + amounts[i].ToString().Replace(",", "."));
url.Append("&weight" + "_" + (i + 1).ToString() + "=" + weight[i].ToString().Replace(",", "."));
}
url.Append("&no_shipping=" + HttpUtility.UrlEncode(NO_SHIPPING));
url.Append("&custom=" + HttpUtility.UrlEncode(invoiceID));
url.Append("&txn_id=" + HttpUtility.UrlEncode(transID));
url.Append("&notify_url=" + HttpUtility.UrlEncode(NOTIFY_URL));
return url.ToString();
}
I think the Paypal method you are trying to do is as follows on code project
and if you get payment_status = INVALID, then check the reason in payment_reason
i dont see in the code where you are defining result which is checked in the if, also in the switch you are checking against request, surely this should be against response?

Categories

Resources