How to generate HTML in a Pop Up window with Asp.Net - asp.net

I have very simple html report generated from one of my objects on server. I generate html code at PageLoad because I need to clear that object from session and don't want ask external web service for data after user clicks on link button.
Roughly idea is that user clicks on button on page and the report will be displayed at new window.
As I said I have html generated at PageLoad and right now stored in unique file at server. I also thought that I could hide the html code in hidden control. But that wont work without extra work, that would convert html code into some nonsense string and restored later on.
I can manage to display my html code into current window by using Response.Write(myhtml as string);
So my question are:
where could I store my html code beyond file system (that is tricky with security issues)
how to display my htmlcode into new window on click event. What way could I use.
I found one possible solution described here.
UPDATE:
Just adding pieces of code. It displays html string in current window which is not exactly I want.
private void InitData(){
string filename = DateTime.Now.ToString("yyyyMMdd_HHmmssfff");
lbtnPrintOutOrder.CommandArgument = filename;
StreamWriter swXLS = new StreamWriter((MapPath("Files\\")) + filename);
string message = GetEmail();//get data form session object
swXLS.Write(message);//save data to file
swXLS.Close();
}
protected void lbtnPrintOutOrder_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
{
string filePath = (MapPath("Files\\")) + e.CommandArgument.ToString();
string content;
using (StreamReader reader = File.OpenText(filePath)) {
content = reader.ReadToEnd();//get html from file
}
Response.Write(content);//load it to current window
Response.End();
}

One big question, is why do you need to clear the object from Session? Why cant you keep the object in session until after the string is displayed in the new window?
You could open an aspx page in the new window, use the string object stored in the session to output the html, and clear the session once the html is displayed.

Related

ASP.NET "application/pdf": code runs only once

I'm working on a SharePoint 2013 site and I've added the ability to save pages in PDF. The PDF conversion is handled by the third party library SelectPdf.
I managed to get everything to work (rendering and file download), except that the "PDF Download" button that I have on my page works only 1 time. Meaning, the click event on the code behind is fired only once, no matter how many times I click the button (notice that I click it with intervals of 10+ seconds). If I want to download the PDF file again, I have to refresh the page.
I put together a "hello world" example (see below) in order to pinpoint the problem:
protected void lnkPdfDownload_Click(object sender, EventArgs e)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=test.pdf");
/************************************ Create PDF File ************************************/
string html = #"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"">
<html dir=""ltr"" lang=""en-US"">
<body><h1>Hello World</h1></body>
</html>";
HtmlToPdf converter = new HtmlToPdf();
PdfDocument doc = converter.ConvertHtmlString(html);
byte[] bytes = doc.Save();
Response.OutputStream.Write(bytes, 0, bytes.Length); // ALTERNATIVE: doc.Save(Response.OutputStream);
/************************************ Create PDF File ************************************/
//Response.End(); // This throw a ThreadAbortException, therefore I'm using the alternative code below
Response.Flush();
Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
At the beginning I thought it was Response.End() that caused the issue (by throwing the ThreadAbortException), but I replaced it with other code and I still have the same problem (no exceptions are thrown now).
I don't think the problem is in the SelectPdf library: I can comment out the entire block (between the "Create PDF File" comments), and I still get the same thing (obviously no PDF is generated).
I noticed that, at most, I can successfully click the "download" button up to 2 times (it's rare, and not consistent): the third time nothing happens.
While this isn't a huge deal, I think there is something wrong going on that I'm not seeing. Here is why: after I click the "download" button (and get my PDF file), I am not able to go on edit mode in my SharePoint page. The "loading" message keeps spinning but nothing happens (again, unless I refresh the page).
Has anyone had this problem? I looked online but I couldn't find anything about it.
I'm using Internet Explorer 11 and Chrome 51. Please let me know if you need more information. Thank you.
Are you sure there are not javascript/jquery errors happening when the download button is clicked that prevent the re-clicking of the PDF button and also going into edit mode?
Especially since refreshing the page makes everything work again.

how to locate elements on a different webpage?

I'm new to java and webdriver. My web-applications adds some data to a table on a webpage. If the addition is successful, a new web page is opened and the success message is displayed on the new page. If the addition is not successful, a javascript alert is thrown. After accepting the alertHow do I check the presence of an the message on the new webpage using webdriver?
If it is opening in new window you need to switch the control to new window first
Find the logic here to switch the control between windows
After switching the control to new window you can verify whatever you want. Either element or text.
isElementPresent? method logic here .
isTextPresent? method logic here.
If I understand the question correctly, after sending the data to the table, if the sending is successful then the window is loaded with a new webpage else an alert appears once you accept the alert the window is loaded.
After sending the data, check for the presence of the alert, if the alert is present then accept it. Next is verifying whether a text is present in the newly loaded webpage or not.
public void isAlertPresent(){
try {
driver.switchTo.alert().accept();
}
catch ( NoAlertPresentException e ){
}
System.out.println(driver.findElement(By.tagName("body")).getText().contains("Expected Message"));
If the location where the message appears is static then I would suggest you to use a better approach than the above like if an element has that text
WebElement element = driver.findElement(By.id("elementID"));
System.out.println(element.getText().trim().equals("Expected Message"));

Access to the path is denied C# error

I want my user to be able to hit the submit button and have a string write into a css file. When I hit the submit button, I am getting the error message:
Access to the path 'C:/.....' is denied
This happens when running the site from localhost and on my hosting (123reg)
protected void btnSubmit(object sender, EventArgs e)
{
using (StreamWriter writer = new StreamWriter("B00101168.css"))
{
writer.Write("Word ");
writer.WriteLine("word 2");
}
}
The first problem is, you can't write to a file without setting permissions on the folder. See this link for details. Essentially, you must give the Internet Guest Account permission to write to the folder.
But, the bigger problem is, you probably shouldn't be trying to dynamically write a CSS file anyway. At least, not the way you are trying to do it. Can you explain why you are trying to dynamically change a CSS file on your server? If you can explain what you are trying to accomplish, I might have some suggestions on how to do it that work better than what you are trying to do.
UPDATE: You're using WebForms, and you're trying to dynamically generate CSS. So here's one way to do that.
Use a generic page handler -- a file that ends in .ashx. You dynamically create the CSS however you're doing it now, but instead of writing it to a file, you output it directly to the browser. Here is some (untested!) code:
In the DynamicStyles.ashx file, there is basically nothing to add from what it automatically generates.
In the DynamicStyles.ashx.cs file:
public void ProcessRequest( HttpContext context )
{
StringBuilder css = new StringBuilder();
// Use the StringBuilder to generate the CSS
// however you are currently doing it.
context.Response.ContentType = "text/css";
context.Response.Write( css.ToString() );
}
Then, in your code that needs the CSS file, include it just like you would any other CSS:
<link rel="stylesheet" type="text/css" href="/path/to/DynamicStyles.ashx">

Display image from database in ASP.net with C#

I know this kind of question has been asked many times.
Yet I don't succeed in displaying an image from my db on a page.
I tried the following method.
protected void Page_Load(object sender, EventArgs e)
{
//Get the picture id by url
//Query here
byte[] picture = queryoutput;
Response.ContentType = "image/jpeg";
Response.BinaryWrite(picture);
}
Link to get the image.
<asp:Image runat="server" ImageUrl="~/givememypicture.aspx?pic=3" ID="testimage" />
The <asp:Image /> tag is located in between <asp:Content > tags.
When I run this code and check in firebug, it simply states 'Failed to load fiven URL'.
I also tried putting the Respone.Con...(picture); part into a public method and call that method with the byte var given.
I'm quite new to asp.net, but I have somewhat more experience in c#.
I start to really dislike asp.net... I have been struggling with this for about 20 hours already and tried a lot of options, yet none worked.
The best would be if I could just fill in the picture via the codefile from that same page. It seems quite illogical to me to call another page to load the image from.
Can somebody please tell me what I'm doing wrong here?
Solution: Master page reference removed from the page directive on the page that handles the image response. Also removed everything else except for the #page directive itself within the aspx file.
try using a handler file (.ashx) put the code form your page_load in that lie so
public void ProcessRequest (HttpContext context) {
//Get the picture id by url
//Query here
byte[] picture = queryoutput;
Response.ContentType = "images/jpeg";
Response.BinaryWrite(picture);
}
public bool IsReusable {
get {
return false;
}
}
then call the handler file and pass the correct querystring items from the
this should then work
There's an error in your path reference...
ImageUrl="/~givememypicture.aspx?pic=3"
should be:
ImageUrl="~/givememypicture.aspx?pic=3"
~ is shorthand for "the application root" and needs to be followed by a slash to indicate that it's a directory. Think of it as similar to other path shorthand notations such as . and ...
Make sure you call Response.Flush(); and also Response.End(); and see if that does the trick
Also, your content type has a misspelling. Is not "images/jpgeg" I think it's "image/jpeg"
EDIT: Yes, I just confirmed in Wikipedia that the correct content-type is image/jpeg.
I do this all the time. Here's some sample code:
Response.ContentType = "image/jpeg";
Response.BinaryWrite(bytes);
That's all there is too it. If it's not working, then something is probably wrong with your data.
A flush is not required. I have working code for this open on my screen right now.
I would suggest that you try writing that buffer of data to a file and see if it opens up as a valid picture. I bet something's wrong with that data.
Also, it's a good idea to enable browser side caching for your dynamic content. Here's a GREAT link that shows exactly how to do that, which will boost your performance / scalability a lot.
http://edn.embarcadero.com/article/38123

How to Convert my ASP.NET Page to PDF?

I have the following acceptance criteria for creating a pdf file from my asp.net page which contains nested RadGrid controls:
The current view of the page should be converted to PDF which means that the viewstate and session information of the current page request should be taken into account. This leaves me with only one option; make the PDF conversion at Page_Render() event handler of the current session when a new pdf postback is sent.
The asp.net page layout is changed using JQuery at the time of the $(document).ready(...) that means that not only the rendered HTML should be converted to PDF but also the javascripts have to run on it to have the desired layout changes in the final PDF file; e.g. column alignments, etc. I hope it would be possible otherwise ...
The asp.net page only appears correctly in IE 6+ therefore the PDF tool which is used must use IE rendering engine.
Please could you advise which tool can help in such scenario?
I downloaded and tested EvoPdf tool but it doesn't support IE rendering engine apparently (only FireFox rendering) and couldn't make the javascripts enabling work correctly with it.
I'm going to evaluate ABCPdf and Winnovetive but I'm not sure they would support what I want.
If I could find no tool to help with the above, another possible solution might be just taking a screenshot of the page using client script (don't know whether it'd be possible), then sending it to the server and finally converting that image to pdf.
Many thanks,
You can try WebToPDF.NET.
Try to convert HTML page which you get after the asp.net page have been rendered
WebToPDF.NET suports JavaScript(and JQuery), so it's not problem
WebToPDF.NET passes all W3C tests (except BIDI) and supports HTML 4.01, JavaScript, XHTML 1.0, XHTML 1.1 and CSS 2.1 including page breaks, forms and links.
Don't know exactly about your requirements but have a look at wkhtmltopdf
How to use wkhtmltopdf.exe in ASP.net
winnovative did exactly what I needed :) it uses IE rendering engine unlike EvoPdf.
I haven't had time testing other tools.
Thanks
EvoPdf is developed by the same team who develop ExpertPDF (http://www.html-to-pdf.net/). ExpertPDF is the older product so although the APIs are almost identical, the EvoPDF API is slightly more refined.
The main difference between the products is that ExpertPDF uses the local IE rendering engine.
Winnovative HTML to PDF Converter does not use IE as rendering engine. It is compatible with WebKit rendering and does not depend on IE or any other third party tools.
You can convert the current HTML page overriding the Render() method of the ASP.NET page and capture the HTML code being rendered by page. You can find complete example with C# source code in Convert the Current HTML Page to PDF Demo.
Here is the relevant source code for this approach:
// Controls if the current HTML page will be rendered to PDF or as a normal page
bool convertToPdf = false;
protected void convertToPdfButton_Click(object sender, EventArgs e)
{
// The current ASP.NET page will be rendered to PDF when its Render method will be called by framework
convertToPdf = true;
}
protected override void Render(HtmlTextWriter writer)
{
if (convertToPdf)
{
// Get the current page HTML string by rendering into a TextWriter object
TextWriter outTextWriter = new StringWriter();
HtmlTextWriter outHtmlTextWriter = new HtmlTextWriter(outTextWriter);
base.Render(outHtmlTextWriter);
// Obtain the current page HTML string
string currentPageHtmlString = outTextWriter.ToString();
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set license key received after purchase to use the converter in licensed mode
// Leave it not set to use the converter in demo mode
htmlToPdfConverter.LicenseKey = "fvDh8eDx4fHg4P/h8eLg/+Dj/+jo6Og=";
// Use the current page URL as base URL
string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri;
// Convert the current page HTML string a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(currentPageHtmlString, baseUrl);
// Send the PDF as response to browser
// Set response content type
Response.AddHeader("Content-Type", "application/pdf");
// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Convert_Current_Page.pdf; size={0}", outPdfBuffer.Length.ToString()));
// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);
// End the HTTP response and stop the current page processing
Response.End();
}
else
{
base.Render(writer);
}
}

Resources