Stuck Streaming Xml - asp.net

This is the code i have written to get the xml of one url but it says
"Data at the root level is invalid" with any url.. Can someone specify why?
XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing
xdoc.LoadXml("http://latestpackagingnews.blogspot.com/feeds/posts/default");//loading XML in xml doc
XmlNodeList xNodelst = xdoc.DocumentElement.SelectNodes("entry");//reading node so that we can traverse thorugh the XML
Response.Write(xNodelst);

You need to first download your xml data using WebClient class
string downloadedString;
System.Net.WebClient client = new System.Net.WebClient();
downloadedString = client.DownloadString("http://latestpackagingnews.blogspot.com/feeds/posts/default");
//Now write this string as an xml
//I think you can easily do it with XmlDocument class and then read it

The xdoc.LoadXml can not for read url, change it to xdoc.Load and it will work.
You can also read : Using Returned XML with C#

XmlDocument.LoadXml method awaits XML-text, but not the source URL.
First, download page content into string and then pass it to LoadXml. Here is how you can download:
public string GetUrlContent(string url)
{
var request = (HttpWebRequest)HttpWebRequest.Create(url);
var response = (HttpWebResponse)request.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
var content = reader.ReadToEnd();
reader.Close();
response.Close();
return content;
}
In your case it would be:
var content = GetUrlContent("http://latestpackagingnews.blogspot.com/feeds/posts/default");
var doc = new XmlDocument();
doc.LoadXml(content);

Related

Serializing using protobuf-net and sending as postdata in http

I'm using Protobuf-net to try and send a serialized object to a webapplication that I'm running in another project. The Serializer.Serialize<T>() method takes a Stream (to write to) and and instance of T (in this case, a list of a few objects that I set up to work with protobuf-net)
How do I go about doing this? Do I need to write to a file or can I send the stream as postdata somehow? Below you can see I'm using a string as the postdata.
My execute post method
public static void ExecuteHttpWebPostRequest(Uri uri,string postdata, int requestTimeOut, ref string responseContent)
{
if (string.IsNullOrEmpty(uri.Host))// || !IsConnectedToInternet(uri))
return;
var httpWebReq = (HttpWebRequest)WebRequest.Create(uri);
var bytePostData = Encoding.UTF8.GetBytes(postdata);
httpWebReq.Timeout = requestTimeOut*1000;
httpWebReq.Method = "POST";
httpWebReq.ContentLength = bytePostData.Length;
//httpWebReq.ContentType = "text/xml;charset=utf-8";
httpWebReq.ContentType = "application/octet-stream";
//httpWebReq.TransferEncoding=
//httpWebReq.ContentType = "application/xml";
//httpWebReq.Accept = "application/xml";
var dataStream = httpWebReq.GetRequestStream();
dataStream.Write(bytePostData, 0, bytePostData.Length);
dataStream.Close();
var httpWebResponse = (HttpWebResponse)httpWebReq.GetResponse();
// Get the stream associated with the response.
var receiveStream = httpWebResponse.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
var readStream = new StreamReader(receiveStream,Encoding.Default);
responseContent = readStream.ReadToEnd();
httpWebResponse.Close();
}
You can just serialize to the request:
Serializer.Serialize(dataStream, obj);
And equally, you can deserialize from receiveStream, if you choose.
Note, however, that protobuf data is not text, and should not be treated as such - very bad things happen if you try that.

How to call a WebService which has a querystring data?

I have a webservice which i need to call in .net application. The link looks like this.
http://www.contoso.com/student?id=12345
This will work only when its called like this. For rest of the this i dont have access. ie if i call it on a browser without the querystring it will not work. but with querystring it will return an XML data.
Now, when i call this in the .net application its not working?
How can I call this in a .NET application?
The Normal Webservice Importing methods are not working since it needs a querystring with value and we dont have access to the links which doesnt have the querystring.
How are you currently trying to download it?
A very simple way to do this is to use the HttpWebRequest and HttpWebResponse classes;
public XmlDocument GetStudentXml(int studentId)
{
XmlDocument targetXml = new XmlDocument();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(String.Format("http://www.contoso.com/student?id={0}", studentId));
webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.Accept = "text/xml";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using (Stream responseStream = webResponse.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(responseStream);
targetXml.Load(reader);
reader.Close();
}
webResponse.Close();
return targetXml;
}
This method simply creates a HttpWebRequest, initializes it with the URL (via String.Format so as to append the student id), some windows credentials and the expected content type.
It then calls the remote address via the GetResponse method. The response is then loaded into a stream, and an XmlTextReader is used to load the Xml data from the response stream into the XmlDocument, which is then returned to the caller.
You can also use WebClient and XDocument to achieve the same thing:
string url = String.Format("http://www.contoso.com/student?id={0}", studentId);
string remoteXml;
using (var webClient = new WebClient())
{
remoteXml = webClient.DownloadString(url);
}
XDocument doc = XDocument.Parse(remoteXml);

Retrieve XML from HTTP POST Request Payload

I have an ActiveX that POSTs to the server (HTTP Handler) with a payload of a certain XML document.
Is there a better way to retrieve the payload into XML than the below?
private static byte[] RequestPayload()
{
int bytesToRead = HttpContext.Current.Request.TotalBytes;
return (HttpContext.Current.Request.BinaryRead(bytesToRead));
}
using (var mem = new MemoryStream(RequestPayload()))
{
var docu = XDocument.Load(mem);
}
Once I have the "docu" I can query using LINQ to XML.
Thanks
Simply load the XML from the InputStream of the Request e.g.
XDocument doc;
using (Stream input = HttpContext.Current.Request.InputStream)
{
doc = XDocument.Load(input);
}
there is no need for a MemoryStream in my view.

Embedded WebResource and FileStream

[assembly: System.Web.UI.WebResource("Project.ConfigurationFiles.Tools.xml", "text/xml")]
string resource = "Project.ConfigurationFiles.Tools.xml";
string pathXML =Page.ClientScript.GetWebResourceUrl(this.GetType(), resource);
XmlSerializer mySerializer = new XmlSerializer(typeof(ToolB));
using (FileStream myFileStream = new FileStream(pathXML, FileMode.Open))
{
The error I get:
Illegal characters in path.
I guess this happens because FilleStream need file and not url.
This exception occurs because GetWebResourceUrl function returns an HTTP address but FileStream expects a file path. From your code snippet I suppose you are trying to read the XML file that's embedded into the assembly and deserialize it back to an object. Here's how you could achieve this:
var executingAssembly = Assembly.GetExecutingAssembly();
var resource = "Project.ConfigurationFiles.Tools.xml";
using (var stream = executingAssembly.GetManifestResourceStream(resource))
{
var serializer = new XmlSerializer(typeof(ToolB));
var toolB = (ToolB)serializer.Deserialize(stream);
}

How to send a xml file over HTTP and HTTPS protocol and get result back

i want to send xml file with userid and password over HTTPs and then send all other xml file on HTTP using POST method and get the response as a xml file back. in ASP.NET (with vb.net preferred)
The url to which i want to send my xml file is:http://www.hostelspoint.com/xml/xml.php
exect xml file pettern is:
<?xml version="1.0" encoding="UTF-8"?>
<OTA_PingRQ xmlns="http://www.opentravel.org/OTA/2003/05"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05OTA_PingRQ.xsd"
TimeStamp="2003-03-17T11:09:47-05:00"
Target="Production" Version="1.001" PrimaryLangID="en"
EchoToken="testtoken12">
<EchoData>Hello</EchoData>
</OTA_PingRQ>
You should check out the WCF REST Starter Kit, and watch the screencast on HTTP Plain XML (POX) Services which explains step by step how to do just that - create a WCF REST service that will accept and process a plain XML stream.
All the WCF and WCF REST screencasts by Pluralsight are highly recommended! It's excellent material on how to get started and work with WCF.
In addition to that, the MSDN WCF Developer Center is your first point of contact for any questions or more information on WCF and WCF REST.
i don't know why u removed correct answer from here but yesterday i got correct answer here. and it is:- (can any one tell me how to do same with HTTPS protocol?)
string targetUri = "http://www.hostelspoint.com/xml/xml.php";
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\myfile.xml"));
string formParameterName = "OTA_request";
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
string respStr = "";
if (request.HaveResponse)
{
if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
{
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respStr = respReader.ReadToEnd(); // get the xml result in the string object
XmlDocument doc = new XmlDocument();
doc.LoadXml(respStr);
Label1.Text = doc.InnerXml.ToString();
}
}
Yes, you can do same thing using HTTPS protocol. You have to add this code before request:
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
bool validationResult = true;
//
// policy code here ...
//
return validationResult;
};

Resources