How to flush xml file in asp.net? - asp.net

I want to return a xml file to a client, and THEN perform my logic.
I try to use Response.Flush(), but it doesn't work correctly for me.
My code:
protected void Page_Load(object sender, EventArgs e)
{
string arg1= this.Request["arg1"];
string arg2= this.Request["arg2"];
string arg3= this.Request["arg3"];
var doc = new XmlDocument();
XmlNode responseNode = doc.CreateElement("response");
doc.AppendChild(responseNode);
var messageNode = responseNode.AppendChild(doc.CreateElement("message"));
messageNode.InnerText = "Your request is being processed";
Response.Clear();
Response.ContentType = "text/xml";
Response.ContentEncoding = System.Text.Encoding.UTF8;
doc.Save(Response.Output);
Response.Flush(); // I want to display xml in this moment but it doesn't work
LogicManager manager = new LogicManager();
manager.DoSth(arg1, arg2, arg3);
Response.End();
}

Response.End();
Generally, it is a bad idea to be using Response.End() in your code.
From the source: This method is provided only for compatibility with ASP—that is, for compatibility with COM-based Web-programming technology that preceded ASP.NET. If you want to jump ahead to the EndRequest event and send a response to the client, it is usually preferable to call CompleteRequest instead.
Given this info, instead of this:
Response.Flush(); // I want to display xml in this moment but it doesn't work
LogicManager manager = new LogicManager();
manager.DoSth(arg1, arg2, arg3);
Response.End();
do this:
Response.Flush(); // I want to display xml in this moment but it doesn't work
Response.CompleteRequest();
LogicManager manager = new LogicManager();
manager.DoSth(arg1, arg2, arg3);
// here you might want to make sure that no other page handlers are executed

Related

how to create a hyperlink for file download in asp.net?

I have some files stored on my machine. When a user wants to generate a link the page should generate a hyperlink. This hyperlink can be used by any other user so as to download the file
Have a LinkButton and for the click event do the following
your aspx file will have the following
<asp:LinkButton runat="server" OnClick="btnDownload_Click" Text="Download"/>
Your code behind will have the following
protected void btnDownload_Click(object sender, EventArgs e)
{
try
{
var fileInBytes = Encoding.UTF8.GetBytes("Your file text");
using (var stream = new MemoryStream(fileInBytes))
{
long dataLengthToRead = stream.Length;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.BufferOutput = true;
Response.ContentType = "text/xml"; /// if it is text or xml
Response.AddHeader("Content-Disposition", "attachment; filename=" + "yourfilename");
Response.AddHeader("Content-Length", dataLengthToRead.ToString());
stream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
}
Response.End();
}
}
catch (Exception)
{
}
}
you can direct link the hyperlink with the file if you know the address but this is limited by the browser. eg. if pdf reader is installed on the client then the pdf will not be downloaded instead it will be shown. A good solution would be to have a seperate page for downloading files. just pass filename in querystring and in the pageload event just outpit the file in response stream.This way you can use url say dwnld.aspx?filename.ext
Now you can generate urls via the above logic.

Displaying a web page as a pdf with click of a button

I have a new requirement to have a button in my web page, and upon clicking, it displays the web page as a PDF. On researching I found that iTextSharp is used for such purpose.
But I have many Telerik and ASP controls in my web page too. Can I get that also in the PDF using iTextSharp?
If yes then can anyone please provide me a basic link to start using iTextSharp as I haven't came across this tool yet.
According to the answer from #ahaliav I tried with the following code. However, I'm not getting the controls on the pdf.
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(HtmlContent);
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
HTMLWorker worker = new HTMLWorker(document);
// step 2:
// we create a writer that listens to the document
// and directs a XML-stream to a file
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
// step 3: we create a worker parse the document
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(reader);
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
//Response.Write(document);
//Response.End();
}
protected override void Render(HtmlTextWriter writer)
{
// setup a TextWriter to capture the markup
TextWriter tw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(tw);
// render the markup into our surrogate TextWriter
base.Render(htw);
// get the captured markup as a string
string pageSource = tw.ToString();
// render the markup into the output stream verbatim
writer.Write(pageSource);
// remove the viewstate field from the captured markup
HtmlContent = Regex.Replace(pageSource,
"<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\".*?\" />",
"", RegexOptions.IgnoreCase);
// the page source, without the viewstate field, is in viewStateRemoved
// do what you like with it
}
Please help .
I have other option also,that is to display the image of the full web page when i click a button.Can anyone guide me to any possible directions for these two issues please.
I finally changed my code as:
Response.ContentType = "application/msword";
Response.AddHeader("content-disposition", "attachment;filename=TestPage.doc");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
MemoryStream msOutput = new MemoryStream();
With this i am able to get the msword document containing all my controls ,but i am also getting some unwanted texts,how can i remove that,if anyone encountered the same problem?
After some research i did not find any solution for showing the controls in the html this code below works fine but with out showing the controls,
in the past i used this http://www.winnovative-software.com/ and it works good for html pages including all controlls you can also test it onlie, the "only" problem is it you need to pay for the license
protected void btnExportToPdf_Click(object sender, EventArgs e)
{
renderPDF = true;
}
protected override void Render(HtmlTextWriter writer)
{
if (renderPDF == true)
{
MemoryStream mem = new MemoryStream();
StreamWriter twr = new StreamWriter(mem);
HtmlTextWriter myWriter = new HtmlTextWriter(twr);
base.Render(myWriter);
myWriter.Flush();
myWriter.Dispose();
StreamReader strmRdr = new StreamReader(mem);
strmRdr.BaseStream.Position = 0;
string pageContent = strmRdr.ReadToEnd();
strmRdr.Dispose();
mem.Dispose();
writer.Write(pageContent);
CreatePDFDocument(pageContent);
}
else
{
StringBuilder sb = new StringBuilder();
HtmlTextWriter tw = new HtmlTextWriter(new System.IO.StringWriter(sb));
base.Render(tw);
// get the captured markup as a string
string pageSource = tw.ToString();
//Get the rendered content
string sContent = sb.ToString();
//Now output it to the page, if you want
writer.Write(sContent);
}
}
public void CreatePDFDocument(string strHtml)
{
string strHTMLpath = Server.MapPath("MyHTML.html");
StreamWriter strWriter = new StreamWriter(strHTMLpath, false, Encoding.UTF8);
strWriter.Write(strHtml);
strWriter.Close();
string strFileName = HttpContext.Current.Server.MapPath("map1.pdf"); // strFileName "C:\\Inetpub\\wwwroot\\Test\\map1.pdf"
// step 1: creation of a document-object
Document document = new Document();
// step 2:
// we create a writer that listens to the document
PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
StringReader se = new StringReader(strHtml);
TextReader tr = new StreamReader(Server.MapPath("MyHTML.html"));
//add the collection to the document
document.Open();
/////////
iTextSharp.text.html.simpleparser.HTMLWorker worker = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
worker.StartDocument();
//// step 5: parse the html into the document
worker.Parse(tr);
//// step 6: close the document and the worker
worker.EndDocument();
//worker.Parse(tr); // getting error "Illegal characters in path"
document.Close();
ShowPdf(strFileName);
}
public void ShowPdf(string strFileName)
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
Response.ContentType = "application/pdf";
Response.WriteFile(strFileName);
Response.Flush();
Response.Clear();
}
A very simple Google search brings us to the following forum thread which has your "sollution":
http://forums.asp.net/t/1039486.aspx/1
iTextSharp comes with a little companion : XML Worker
For a demo, have a look here
Even though the documentation refers to the Java API, the adaptation to C# should be straightforward.
As for Telerik/ASP tags, you can extend XMLWorker and define how to convert such tags into PDF elements.

Cannot hear audio from ASP.NET "Text to Speech" Application

in my asp.net project, I code below for a text to speech function.
in my page's c# file.
byte[] SpeakText(string text)
{
using (SpeechSynthesizer s = new SpeechSynthesizer())
{
using (MemoryStream ms = new MemoryStream())
{
s.SetOutputToWaveStream(ms);
s.Speak(text);
return ms.GetBuffer();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
Response.Write(SpeakText(TextBox1.Text));
}
}
but not hear the audio while run it.
How to solve the problem?
Try setting the response content type:
Response.ContentType = "audio/wav";
Also don't use Response.Write as it expects encoded characters. You need to write binary to avoid getting corrupt data:
Response.Clear();
Response.ContentType = "audio/wav";
Response.BinaryWrite(SpeakText(TextBox1.Text));
Response.End();
your code is executing on the server, not on the client machine.
Once you have generated the Speech output you should stream it down to the client (as a wav file for example), check this answer for a full example:
https://stackoverflow.com/a/1719867/559144

Download a string as a file in ASP.NET

The following method, based on code in this question, shows a file download dialog box in the browser, but then the download never starts (it stays at 0%):
protected void lnkExport_Click(object sender, EventArgs e) {
var bytes = Encoding.ASCII.GetBytes(SelectRecords()); //Data to be downloaded
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=\"test.xls\"");
using (var stream = new MemoryStream(bytes)) {
Response.AddHeader("Content-Length", stream.Length.ToString());
stream.WriteTo(Response.OutputStream);
}
}
Any idea what's up?
Your code worked fine for me but you may want to try adding this as the last line of your click handler:
Response.End();

How can i write a datatable content on web page in XMl foramte in asp.net?

How can i write a datatable content on web page in XMl foramte in asp.net?
i also need to customize the datatable before writing to web page.
Edited:-
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/xml";
DataTable dt = new DataTable("XML");
String email = EmailAddress.Text.ToString();
dt.Load(obj.GetXML("XYZ#gmail.com"));
//now i want this dt to dosplayed in the XMl form on the same page, how can i achieve this?
'XmlDocument xml = new XmlDocument();
'XmlTextReader xr=new XmlTextReader(
'WriteGoogleMap(dt.ToString(), Response.OutputStream);
'Response.End();
//System.Xml.
}
Try this :
public string GetXml(string urlBase)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = true;
StringBuilder output = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(output, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
// Repeat this code:
writer.WriteStartElement("url");
writer.WriteElementString("loc", "[your url]");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
}
return output.ToString();
}
Then use the result to feed a label :
<script runat="server" type=text/C#>
protected void Page_Load(object sender, EventArgs e)
{
myLabel.Text = HttpUtility.HtmlEncode(
GetXml("http://www.dotnetperls.com/")
);
}
</script>
[Edit]
I think you should start by the beginning. Do not mix all concepts in your single question. Spend time for learning the basics (read books, take courses, etc.). In your specific case, I suggest you to split the work in several layers:
A data layer the is responsible to build a datatable
A business or service layer, capable of creating the xml document from the databable
A presentation layer that will contains :
a custom http handler (.ashx) that will return the xml
a visual page that can show the html representation of the Xml
good luck
DataTable has method named:
WriteXml

Resources