The following code does not put everything in an email. The only result is the word test. When I run all code, there is data from the database. What am I missing to get the data to populate in the email table?
performanceCompare += "<table>";
//Compares last hour today......need to compare to another day results
var performDate = ErrDb.PerformanceDatas.Where(d => d.loggedAt > hourlyBegin && d.loggedAt < hourlyEnd).ToList();
var performanceDataOneDay = ErrDb.PerformanceDatas.Where(o => o.loggedAt > dayBegin && o.loggedAt < dayEnd).ToList();
performanceCompare += "<tr>";
performanceCompare += "<td><b>test</b></td>";
performanceCompare += "</tr>";
var avgTimeList = new List<AvgTime>();
var specialIDS = performDate.Select(x => new {x.sitename, x.functionName }) .Distinct();
foreach (var key in specialIDS)
{
var funComapre = performDate.Where(g => g.functionName == key.functionName && g.sitename == key.sitename);
AvgTime avgTime = new AvgTime();
avgTime.siteName = "<tr>" + key.sitename + "</tr>";
avgTime.functionName = "<td>" + funComapre.Select(x => x.functionName).First() + "</td>";
avgTime.avgFunctTime = "<td>" + (funComapre.Select(x => x.functionTime).Average()) + "</td>";//needs to be a string, not a double
avgTimeList.Add(avgTime);
var anotherFunComapre = performanceDataOneDay.Where(g => g.functionName == key.functionName && g.sitename == key.sitename);
if (anotherFunComapre != null)
{
AvgTime anotherAvgTime = new AvgTime();
avgTime.siteName = "<tr>" + key.sitename + "</tr>";
avgTime.functionName = "<td>" + funComapre.Select(x => x.functionName).First() + "</td>";
anotherAvgTime.avgFunctTime = funComapre.Select(x => x.functionTime).Average();
avgTimeList.Add(anotherAvgTime);
}
}
performanceCompare += "</table>";
Anyone has an idea of how I can make this less redundant? I need to populate the inner html of multiple div elements on the client with the same content.
Client:
<div id="projectList_dialog1" class="listView" runat="server"></div>
<div id="projectList_dialog2" class="listView" runat="server"></div>
Code Behind:
protected void loadProjectList()
{
var projectsPath = userDataPath + #"\" + username + #"\Projects";
if (Directory.Exists(projectsPath))
{
var projects = Directory.GetDirectories(userDataPath + #"\" + username + #"\Projects");
projectList_dialog1.InnerHtml = "<table>";
projectList_dialog2.InnerHtml = "<table>";
projectList_dialog1.InnerHtml += "<tr><td>Name</td><td>Date modified</td></tr>";
projectList_dialog2.InnerHtml += "<tr><td>Name</td><td>Date modified</td></tr>";
List<string> storedProjectNamesList = new List<string>();
for (var i = 0; i < projects.Length; i++)
{
var storedProjectName = projects[i].Remove(0, projects[i].LastIndexOf('\\') + 1);
storedProjectNamesList.Add('"' + storedProjectName + '"');
var lastModified = System.IO.File.GetLastWriteTime(storedProjectName);
projectList_dialog1.InnerHtml += "<tr class='" + storedProjectName + "' onclick='listViewAction(event)'><td>" + storedProjectName + "</td><td>" + lastModified + "</td></tr>";
projectList_dialog2.InnerHtml += "<tr class='" + storedProjectName + "' onclick='listViewAction(event)'><td>" + storedProjectName + "</td><td>" + lastModified + "</td></tr>";
}
projectList_dialog1.InnerHtml += "</table>";
projectList_dialog2.InnerHtml += "</table>";
storedProjectNames = string.Join(",", storedProjectNamesList);
}
else
{
serverMessage.InnerHtml = "Code (0x3): The system cannot find the path specified.";
}
}
Assign the data to a local variable like innerHtml, only change InnerHtml of the elements once
protected void loadProjectList()
{
var projectsPath = userDataPath + #"\" + username + #"\Projects";
if (Directory.Exists(projectsPath))
{
var projects = Directory.GetDirectories(userDataPath + #"\" + username + #"\Projects");
//create a variable
var innerHtml = "<table><tr><td>Name</td><td>Date modified</td></tr>";
List<string> storedProjectNamesList = new List<string>();
for (var i = 0; i < projects.Length; i++)
{
var storedProjectName = projects[i].Remove(0, projects[i].LastIndexOf('\\') + 1);
storedProjectNamesList.Add('"' + storedProjectName + '"');
var lastModified = System.IO.File.GetLastWriteTime(storedProjectName);
//add to that variable
innerHtml += "<tr class='" + storedProjectName + "' onclick='listViewAction(event)'><td>" + storedProjectName + "</td><td>" + lastModified + "</td></tr>";
}
innerHtml += "</table>";
//NOW set innerhtml on the objects
projectList_dialog1.InnerHtml = innerHtml;
projectList_dialog2.InnerHtml = innerHtml;
storedProjectNames = string.Join(",", storedProjectNamesList);
}
else
{
serverMessage.InnerHtml = "Code (0x3): The system cannot find the path specified.";
}
}
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.
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);
I m developing a web project in asp.net 3.5
I want to export datatable to Excel. But there are 20.000 rows in datatable. Sometimes timeout problem happens..
protected string Worksheet97_Header()
{
string s = "<tr>";
foreach (ExcelColumn col in Columns)
{
s += "<th>" + col.Header_Text + "</th>";
}
s+="</tr>";
return s;
}
protected string Worksheet97_Data()
{
string s = "";
try
{
for (int i = 0; i < data.Rows.Count; i++)
{
s += "<tr>";
foreach (ExcelColumn col in Columns)
{
if (col.Column_Type == "System.String")
s += "<td>" + data.Rows[i][col.Field_Name].ToString() + "</td>";
if (col.Column_Type == "System.DateTime")
s += "<td>" + Convert.ToDateTime(data.Rows[i][col.Field_Name]).ToString("dd.MM.yyyy HH:mm:ss") + "</td>";
if (col.Column_Type == "System.Int32")
s += "<td>" + data.Rows[i][col.Field_Name].ToString() + "</td>";
if ((col.Column_Type == "System.Double") |
(col.Column_Type == "System.Decimal") |
(col.Column_Type == "System.Int16") |
(col.Column_Type == "System.Int32") |
(col.Column_Type == "System.Int64"))
s += "<td>" + Convert.ToDouble(data.Rows[i][col.Field_Name]).ToString("0.00") + "</td>";
}
}
}
catch (Exception ex)
{
string a = ex.ToString();
}
return s;
}
public string Export_Excel97()
{
string s = "";
s = "<table border=\"1\">";
s += Worksheet97_Header();
s += Worksheet97_Data();
s += "</table>";
return s;
}
Thanks.
IMHO, i think you should page the query so that you don't load everything into memory.
To write the excel file you may want to try this solution too and compare results of performance: http://msmvps.com/blogs/deborahk/archive/2009/07/23/writing-data-from-a-datatable-to-excel.aspx which will use Microsoft Excel Object Library, so you'll need to have Excel installed in the machine where you're running your code.
HTH somehow.
Regards!
This might help... http://www.dotnetjohn.com/PrintFriend.aspx?articleid=36
It is in VB.NET but you should be able to convert it anyway ;-)