using web sites to transfer xml - asp.net

How do I setup a scenario where one website hosted at X publishes a URL that when browsed to will return purely XML.
A web page elsewhere is going to hit this URL, load the XML into objects.
So I want a url like http://www.xml.com/document.aspx?id=1
Another site will use webresponse and webrequest objects to get the response from the above page, I want the response to be good XML so I can just use the XML to populate objects.
I did get something working but the response contained all the HTML required to render the page and I actually just want XML as the response.

Probably the best way to this is with a HttpHandler/ASHX file, but if you want to do it with a page it's perfectly possible. The two key points are:
Use an empty page. All you want in the markup for your ASPX is the
<% Page ... %> directive.
Set the ContentType of the Response stream
to XML - Response.ContentType = "text/xml"
How you generate the XML itself is up to you, but if the XML represents an object graph, you can use an XmlSerializer (from the System.Xml.Serialization namespace) to write the XML directly to the Response stream for you e.g.
using System.Xml.Serialization;
// New up a serialiser, passing in the System.Type we want to serialize
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
// Set the ContentType
Response.ContentType = "text/xml";
// Serialise the object to XML and pass it to the Response stream
// to be returned to the client
serialzer.Serialize(Response.Output, MyObject);
If you already have the XML, then once you've set the ContentType, you just need to write it to the Response stream and then end and flush the stream.
// Set the ContentType
Response.ContentType = "text/xml";
Response.Write(myXmlString);
Response.Flush();
Response.End();

Related

Fortify Cross-site scripting: Persistent issue in Response.Binarywrite

In an existing Asp.Net application, we are using Response.BinaryWrite to render image on an aspx page. This is the required functionality, and below is the C# code-
1. byte[] img = getImage();
2. Response.BinaryWrite(img);
The getImage function reads the image from a folder on server and returns byte array. Fortify scan shows cross-site vulnerability on 2nd line.
I did following validations, but fortify still reports it as cross-site issue -
Validated bytearray to check if the file is of correct format (jpeg or bmp), used this link - Determine file type of an image
Response.BinaryWrite(ValidateFileType(img));
Validated the domain in the file path to check if the file is originating from correct domain.
Is there any specific way to pass the fortify cross-site issue with byte array or can i consider it as false positive?
Had to use a workaround to resolve this, below is the old and new code -
Old Code -
1. byte[] byteImage = getImage();
2. Response.BinaryWrite(byteImage);
New Code (Replaced 2nd line in old code with below block) -
byte[] byteImage = getImage();
var msIn = new MemoryStream(byteImage);
System.Drawing.Image img = System.Drawing.Image.FromStream(msIn);
var msOut = new MemoryStream();
img.Save(msOut, img.RawFormat);
Response.BinaryWrite(msOut.ToArray());
msIn.Dispose();
msOut.Dispose();
Response.Flush();
So, basically converting the byteArray to an Image object, and then writing the image object back to the Response.BinaryWrite stream resolved this, and it passed through Fortify scan.
If anyone is looking for a solution, this might help.

Run a URL in background without opening in browser vb.net on clicking a button

I am using aspx with vb.I have a textbox and a login button.
On clicking this button,if username is correct, I need to run a URL in background without showing in browser.
http://example.com/sms.php?email=username
Username is get from the textbox
Dim url As String
url = "example.com/sms.php?email=" & txtUser.Text
CreateObject("wscript.shell").run(url)
You need to perform an async request to the server. You can use jquery ajax or native XMLHttpRequest to perform it on a client-side. If you want to perform request on a server-side you can use WebRequest or WebClient. Give me to know if you need a detailed example with on of this features.
You can use WebRequest Class or you can use HTTPClient class and Get the response stream from the URL, Then you can parse the response in memmory from the data for example if your data is HTML you can Load it in an XDocument and extract whatever information is required from the response , and it is better to use async and await to access the external Url.
eg
Dim client As HttpClient = New HttpClient()
'Dim urlContents As Byte() = Await client.GetByteArrayAsync(url).

ASP.NET JSON response without web service

I've got an ASP.NET based website that already has the necessary hooks into my back-end database and I want to write something really simple to return a small bit of JSON based on a URL parameter.
So, for example:
http://example.com/JSON/GetInfo.aspx?prodID=1234
And it would return some JSON with product details for the given ID.
I conceptually know how to do this from any ASPX page but I'm wondering if this is the right way to do it? (Assuming I would just be writing JSON back out to the response instead of HTML)
I don't need (or want) a full on .NET web service, just something that I could call from other pages on my site as well as one of our applications with a GET request to retrieve the desired info.
In visual studio, when I'm adding a new file what type should I use?
You should use a Generic Web Handler for this. It's a lightweight web component that you can call from any client code on your site.
Your url would looks like this
http://example.com/JSON/GetInfo.ashx?prodID=1234
Look into to ASP.Net Web Methods
http://msdn.microsoft.com/en-us/library/byxd99hx(v=vs.90).aspx
Wouldn't an ordinary .aspx file do this?
string s= "{\"data\":\"test\"}";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(s);
Response.End();
Create your aspx page "GetInfo.aspx"
In your Page_Load :
string myID = request.QueryString["prodID"];
string myJson = "";
//Fill your JSON with database, ...
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(myJson);
Response.End();
That will returning your JSON

Displaying a PDF on a website

I require some assistance, I have a pdf file that is located on a ftp location.
What i want to do, is on a button click i want to retrieve the pdf file and display it on a new tab.
Please assist on how to accomplish this task.
Thanks in advance.
One approach would be to make a web request to download the file and then pass the download stream along to the ASP.NET response stream. I haven't compiled or executed this code, but it might look something like this:
WebRequest request = HttpWebRequest.Create("ftp://ftp.yoursite.com/yourfile.pdf");
request.Credentials = new NetworkCredential("ftpuser","ftppassword");
// Get the response
WebResponse response = request.GetResponse();
StreamReader responseStream = new StreamReader(response.GetResponseStream());
// Send the response directly to output
Response.ContentEncoding = responseStream.CurrentEncoding;
Response.ContentType = "application/pdf";
Response.Write(responseStream.ReadToEnd());
Response.End();
Just use the HTML anchor tag ("a" tag). In the href attribute put the FTP address of the PDF file (eg. ftp://example.com/file.pdf). To open in a new window you should also specify a target attribute with the value "_blank".
Example:
<a href='ftp://example.com/file.pdf' target='_blank'>Click here to open the PDF file</a>

Showing dynamically generated bitmap in ASP.NET page

I need to create some block diagrams on my ASP.NET page. Is it best done by drawing on Bitmap? How to display this dynamically generated Bitmap object?
Create a http handler that writes the bitmap to the response stream.
Heres a link on handlers themselves http://www.dotnetperls.com/ashx.
If you can write a file to the file system, using some form of naming convention, so that your not generating it over and over again.
If you have it written to a file you can write that to the response stream using context.Response.WriteFile(path);
You'll need to set appropriate headers for the response if you want to cahce something like the below should be ok.
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetLastModified(lastWrite);
context.Response.Cache.SetETag(string.Format("\"{0}\"", lastWrite.Ticks));
context.Response.ContentType = "image/png";
you can check these headers on an incoming request and return a 304 with something like (do a null check before)
if (context.Request.Headers[since] >= lastwrite || context.Request.Headers[eTag] >= lastwriteTicks) {
context.Response.StatusCode = 304;
context.Response.StatusDescription = "Not Modified";
return;
}
If you need to generate fresh every time dont worry about caching and just write your iamge to the context.Response.OutputStream.

Resources