Return XML as HTTP response - asp.net

I've been given a seemingly simple task.
When a given URL is requested the response should simply be some valid XML.
How do I achieve this?
The URL will contain all the necessary code behind to get the data and construct the correct XML string. How do you then go ahead and manipulate the response to return this string only? The caller is receiving the XML string and populating a database with it, that's there responsibility I just need to provide this part of the project.
Thanks

Take a look at this :
Response.Clear();
Response.Write(yourXml);
Response.ContentType = "text/xml";
Response.End();

I would go for an HttpHandler. This way you circumvent all asp.net control creation etc. which is better for performance and seeing as you will not be outputting any html there's no point in using an actual aspx page.

Assuming you have your XML string created you can clear the response and just write your string out.
Response.Clear();
Response.ContentType = "text/xml";
Response.Write(myXMLString);

If you don't want to use full blown webservice then you could do something like this:
private void Page_Load(object sender, System.EventArgs e)
{
Response.ContentType = "text/xml";
//get data from somewhere...
Response.Write(data);
}
}
See here for something similar using images http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=325

Below is the way to send xml data to the browser as a response.
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.Append("<Books>");
xmlBuilder.Append("<Book>");
xmlBuilder.Append("Maths");
xmlBuilder.Append("</Book>");
xmlBuilder.Append("</Books>");
context.Response.ContentType = "text/xml";
context.Response.BinaryWrite(Encoding.UTF8.GetBytes(xmlBuilder.ToString()));
context.Response.End();

Related

Export a data set to Excel and raise a file download dialog from an asp.net web method

I am using the following code to export a data set to an Excel sheet.
[WebMethod]
public static void ExporttoExcel()
{
DataSet ds;
productfactory pf=new productfactory();
ds = pf.getproducts();
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
response.ContentEncoding = System.Text.Encoding.Default;
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"products.xls\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\products.xls";
response.Write(sw.ToString());
// response.End();
}
}
}
The problem is that it's not raising file download and hence no export is taking place. The same code works fine in a normal method. But with the web method it's not working.
I suggest to make an HttpHandler ending in ashx, and place inside him your code that create the excel file.
then call it from your javascript code like that.
document.location.href = "ExporttoExcel.ashx";
The problem is that WebMethods are not designed to allow you to interact with the Response object (evident in that it wasn't available and you had to use HttpContext.Current.Response to get to it). WebMethods are designed to be blackbox to the user. They will perform and action and/or return a value.
Perhaps you can give us a better idea of what you are trying to accomplish and we can suggest an alternate solution.
u can use to create a dynamic iframe with URL set to the Web Handler to generate the Excel this will raise the file download with out posting the current page.

What am I doing wrong with HttpResponse content and headers when downloading a file?

I want to download a PDF file from a SQL Server database which is stored in a binary column. There is a LinkButton on an aspx page. The event handler of this button looks like this:
protected void LinkButtonDownload(object sender, EventArgs e)
{
...
byte[] aByteArray;
// Read binary data from database into this ByteArray
// aByteArray has the size: 55406 byte
Response.ClearHeaders();
Response.ClearContent();
Response.BufferOutput = true;
Response.AddHeader("Content-Disposition", "attachment; filename=" + "12345.pdf");
Response.ContentType = "application/pdf";
using (BinaryWriter aWriter = new BinaryWriter(Response.OutputStream))
{
aWriter.Write(aByteArray, 0, aByteArray.Length);
}
}
A "File Open/Save dialog" is offered in my browser. When I store this file "12345.pdf" to disk, the file has a size of 71523 Byte. The additional 16kB at the end of the PDF file are the HTML code of my page (as I can see when I view the file in an editor). I am confused because I was believing that ClearContent and ClearHeaders would ensure that the page content is not sent together with the file content.
What am I doing wrong here?
Thanks for help!
I think you want a Response.End at the end of this method.
In a quick glance, you're missing Response.End();

How can I make a VERY simple web proxy using ASP.NET?

I'm about to launch a site that was working well until I found the following hiccup:
I can't request a Yahoo! Pipe over SSL.
So the pages that require SSL are now missing a piece of their functionality unless I figure out a way around this; obviously, this could be done if I use an SSL-hosted page on my app to request the Yahoo! pipe for me.
I've seen solutions like http://www.iisproxy.net/license.html, but it seems to be a bit heavy for what I'm trying to do.
Can't I do this with a simple ASHX handler? Or is it more complex than that?
Thank you,
Michael
Thank you, John -- in case it's helpful to anyone else, here's the code I'm using in my ASHX file:
public override void ProcessRequest(HttpContext context)
{
var strURL = context.Server.UrlDecode(context.Request["url"]);
WebResponse objResponse = default(WebResponse);
WebRequest objRequest = default(WebRequest);
string result = null;
objRequest = HttpWebRequest.Create(strURL);
objResponse = objRequest.GetResponse();
StreamReader sr = new StreamReader(objResponse.GetResponseStream());
result = sr.ReadToEnd();
//clean up StreamReader
sr.Close();
//WRITE OUTPUT
context.Response.ContentType = "application/json";
context.Response.Write(result);
context.Response.Flush();
}
However, I was getting a couple extra characters (as opposed to the version that came direct from Yahoo! Pipes), so I had to remove those before parsing the JSON.
I guess if all you want to do is read the contents of a request you could use a WebRequest & WebResponse
here are some details on using that
http://www.west-wind.com/presentations/dotnetWebRequest/dotnetWebRequest.htm

ASP.NET stream content from memory and not from file

The users have requested the option to "download" a csv file representation of GridView contents. Does anyone know how to do this without saving the file to the server but rather just streaming it to the user from memory?
Thanks
Implement an IHttpHandler.
I used something similar to the following in the ProcessResponse for outputing a CSV that had previously been constructed in a database table...
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
//Get data to output here...
//Turn off Caching and enforce a content type that will prompt to download/save.
response.AddHeader("Connection", "close");
response.AddHeader("Cache-Control", "private");
response.ContentType = "application/octect-stream";
//Give the browser a hint at the name of the file.
response.AddHeader("content-disposition", string.Format("attachment; filename={0}", _filename));
//Output the CSV here...
foreach(BatchDTO.BatchRecordsRow row in dtoBatch.BatchRecords)
response.Output.WriteLine(row.Data);
response.Flush();
response.Close();
}
There are a number of libraries that make generating a CSV easier, you should just be able to pass it the Response.OutputStream to have it write to there rather than to a file stream.
Use context.Response.OutputStream.
Here's an example.
I created a StringBuilder and dump the contents to the Response object using the following code ("csv" is the StringBuilder variable).
Response.ContentType = #"application/x-msdownload";
Response.AppendHeader("content-disposition", "attachment; filename=" + FILE_NAME);
Response.Write(csv.ToString());
Response.Flush();
Response.End();
I have used the RKLib export library a few times to great effect, this uses a memory stream and can be given any datatable which it will export as a csv download:
http://www.codeproject.com/KB/aspnet/ExportClassLibrary.aspx

How to generate HTML email content with asp.net

I want to send emails in HTML format. How can I use asp.net to generate HTML content for emails.
Using output of .aspx page(Tried there was nothing in email body. Must be something in page that can't be used for email)
Using Webcontrol and get web control output and use it as email body.
Using custom http handler so can call handler to get email body.
Can you please suggest what would be the best solution?
Some guide or sample reference would be great if know one.
Thanks for all answers:
I am implementing code below:
string lcUrl = "http://localhost:50771/webform1.aspx";
// *** Establish the request
HttpWebRequest loHttp =
(HttpWebRequest)WebRequest.Create(lcUrl);
// *** Set properties
//loHttp.Timeout = 10000; // 10 secs
loHttp.UserAgent = "Code Web Client";
// *** Retrieve request info headers
HttpWebResponse loWebResponse = (HttpWebResponse)loHttp.GetResponse();
Encoding enc;
try
{
enc = Encoding.GetEncoding(loWebResponse.ContentEncoding);
}
catch
{
enc = Encoding.GetEncoding(1252);
}
StreamReader loResponseStream =
new StreamReader(loWebResponse.GetResponseStream(), enc);
string lcHtml = loResponseStream.ReadToEnd();
loWebResponse.Close();
loResponseStream.Close();
I think the ASPX file will make the most easy to edit mechanism. You can use
var stream = new MemoryStream();
var textWriter = new StreamWriter(stream);
Server.Execute("EmailGenerator.aspx", textWriter);
to capture the output of that page.
I personally don't like any of your options. I would probably do it by using an HTML file (or a template stored in a database) and substituting something like {{name}} with the appropriate parameter.
I did this, essentially we had a page that the user could view, and then they could click a button and send the html on the page in an email. Basically my page was responsible for generating the email. I did this by overriding the Render method, and providing my own stream or using the one passed to us. We did this dpeneding on if we were rendering what the user would see or emailing it.
protected override void Render(HtmlTextWriter writer)
{
if (_altPrintMethod)
{
System.Net.Mail.MailMessage....
mailMsg.Body=RenderHtml(baseUrl);
}
}
protected virtual string RenderHtml(string baseUrl)
{
RemapImageUrl(baseUrl);
StreamWriter sw = new StreamWriter(new MemoryStream());
HtmlTextWriter writer = new HtmlTextWriter(sw);
base.Render(writer);
writer.Flush();
StreamReader sr = new StreamReader(sw.BaseStream);
sr.BaseStream.Position = 0;
return sr.ReadToEnd();
}
One thing to note is you have to make sure all links are fully qualified. You might be able to use the base functionality. this is what I was doing in the RemapImageUrl basically I appended an absolute path on all my image files.

Resources