StreamReader into DataTable - c#

I want to read atom xml, and used following code
string str1 = "http://moss:133333/_vti_bin/ExcelRest.aspx/Document Library/OrdersExcel.xlsx/Model/Tables('Table1')?$format=atom";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(str1);
req.UseDefaultCredentials = true;
req.PreAuthenticate = true;
req.Credentials = CredentialCache.DefaultCredentials;
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
WebResponse response = req.GetResponse();
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new StreamReader(response.GetResponseStream(), enc);
string Response = loResponseStream.ReadToEnd();
The last line in above code basically reads whole stream reader into the string Response.
Now I do not know how do I read the above string's atom xml into the data table.

DataTable.ReadXml reads XML schema and data into the DataTable using the specified TextReader.
var reader = new System.IO.StreamReader(xmlStream);
var newTable = new DataTable();
newTable.ReadXml(reader);

Related

Stream was not writable

I am trying to read response from the web SOAP Api and getting Stream was not writable error on the second run in the foreach loop. With the first value in the list ArrayList it works as expected but with the second value it says that Stream was not writable on the Stream was not writable line. What am I doing wrong?
WebRequest webRequest = WebRequest.Create("https://www.api.com/v2.0/xml/");
HttpWebRequest httpRequest = (HttpWebRequest)webRequest;
httpRequest.Method = "POST";
httpRequest.ContentType = "text/xml; charset=utf-8";
httpRequest.ProtocolVersion = HttpVersion.Version11;
httpRequest.Credentials = CredentialCache.DefaultCredentials;
Stream requestStream = httpRequest.GetRequestStream();
StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.ASCII);
StringBuilder soapRequest;
foreach (var bol in list) {
oRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
oRequest = oRequest + "<file>";
oRequest = oRequest + "<IntDocNumber>" + bol + "</IntDocNumber>";
oRequest = oRequest + "</file>";
soapRequest = new StringBuilder(oRequest);
streamWriter = new StreamWriter(requestStream, Encoding.ASCII);
streamWriter.Write(soapRequest.ToString());
streamWriter.Close();
//Get the Response
HttpWebResponse wr = (HttpWebResponse)httpRequest.GetResponse();
StreamReader srd = new StreamReader(wr.GetResponseStream());
string resulXmlFromWebService = srd.ReadToEnd();
XmlDocument xml = new XmlDocument();
xml.LoadXml(resulXmlFromWebService);
XmlNodeList xnList = xml.SelectNodes("/root/data/item");
}
All HTTP communication happens as three steps:
client opens a connection
client sends its headers and data (in your case, the XML document) and ends the input (in your case where you close the request stream)
server sends its response and closes the connection
So, when you close the connection, you cannot send anything else, because you have to wait for the server answer. If you want to send more data, move the beginning of your code (where you create a new WebRequest) inside the For loop.

Arabic WebRequest C#

I am trying to access a website through C# using the WebRequest and the WebResponse object,
I logged on to the site and preserved the cookie to further browse it,
The problem is that the website is arabic and somehow I got a formatted message from the website indicating that my browser does not support arabic.
Perhaps I can add something to the request object to ensure the website that arabic is supported.
This is the code I used, please let me know how to update it:
string formUrl = "http://www.kuwaitlook.com/Ar/Residential.asp";
string formParams = string.Format("Mega={0}", searchTarget);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1);Accept-Language:ar";
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
req.Headers.Add("Cookie", cookieHeader);
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream()) {
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
StreamReader streamReader = new StreamReader(resp.GetResponseStream());
using (StreamWriter writer = new StreamWriter("text.xml")) {
string line;
while ((line = streamReader.ReadLine()) != null) {
writer.WriteLine(line);
}
}
Like Mikael suggested try this one:
HttpWebRequest request=(HttpWebRequest)WebRequest.Create("http://www.yourdomain.com");
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1);Accept-Language:ar"
Here is how you do it in vb.net:
Dim SW As StreamWriter
Dim ar As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Request.ContentLength = ar.GetByteCount(your_string) ' Here
SW = New StreamWriter(Request.GetRequestStream(), ar) ' And Here
SW.Write(your_string)

.NET HTTP POST Method - Cookies issue

I'm trying to use C# to login to hotfile.com. The first big issue was to overcome the 417 Error, which this line solved it:
System.Net.ServicePointManager.Expect100Continue = false;
Now I'm getting this error as I try to login using POST:
You don't seem to accept cookies. Cookies are required in order to log in. Help
I've tried several times, and googled around and I still can't login to Hotfile.com.. My code is this:
string response;
byte[] buffer = Encoding.ASCII.GetBytes("user=XX&pass=XX");
CookieContainer cookies = new CookieContainer();
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create("http://hotfile.com/login.php");
WebReq.Credentials = new NetworkCredential("XX", "XX");
WebReq.PreAuthenticate = true;
WebReq.Pipelined = true;
WebReq.CookieContainer = cookies;
WebReq.KeepAlive = true;
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
WebReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1)";
Stream PostData = WebReq.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
response = _Answer.ReadToEnd();
File.WriteAllText("dump.html", response);
Naturally, the user and pass would have your accounts values.
Here's a working example I wrote for you:
var cookies = new CookieContainer();
ServicePointManager.Expect100Continue = false;
var request = (HttpWebRequest)WebRequest.Create("http://www.hotfile.com/login.php");
request.CookieContainer = cookies;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = request.GetRequestStream())
using (var writer = new StreamWriter(requestStream))
{
writer.Write("user=XX&pass=XX&returnto=/");
}
using (var responseStream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
var result = reader.ReadToEnd();
Console.WriteLine(result);
}

Why am I getting a 401 (Unauthorized) error when POSTing to Google Reader API?

I'm trying to interface with the Google Reader (undocumented/unofficial) API using information from this page. My first step is to get a SID and token, which works fine, but I can't seem to POST anything without getting a 401 error.
Here is the code I'm using to get my SID and token:
static string getSid()
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.google.com/accounts/ClientLogin?service=reader&Email=username&Passwd=password");
req.Method = "GET";
string sid;
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
using (var stream = response.GetResponseStream())
{
StreamReader r = new StreamReader(stream);
string resp = r.ReadToEnd();
int indexSid = resp.IndexOf("SID=") + 4;
int indexLsid = resp.IndexOf("LSID=");
sid = resp.Substring(indexSid, indexLsid - 5);
return sid;
}
}
And to generate a cookie and get the token:
static Cookie getCookie(string sid)
{
Cookie cookie = new Cookie("SID", sid, "/", ".google.com");
return cookie;
}
static string getToken(string sid, Cookie cookie)
{
string token;
string url = "http://www.google.com/reader/api/0/token";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(cookie);
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
using (var stream = response.GetResponseStream())
{
StreamReader r = new StreamReader(stream);
token = r.ReadToEnd();
return token;
}
}
Now if I try to do a POST (in this example, insert a new tag) using the following, I get the 401 error.
static void insertTag(string tag, Cookie cookie)
{
string result = "";
string data = Uri.EscapeDataString("a="+tag+"&T=" + Program.token);
byte[] buffer = Encoding.GetEncoding(1252).GetBytes(data);
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create
("http://www.google.com/reader/api/0/edit-tag?client=-");
WebReq.Method = "POST";
WebReq.Credentials = new NetworkCredential("username", "password");
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
Stream PostData = WebReq.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
result = _Answer.ReadToEnd();
if (result.Length < 0)
result = "";
}
The error occurs on the line Stream Answer = WebResp.GetResponseStream();
You need to double check that you have a user agent set. I have run into this same problem before when i didnt have it set.
For example:
WebClient client = new WebClient();
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
Or: MSDN Link
myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebRequest.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
Turns out I was using the wrong URL to access the Google Reader APIs thanks to some outdated documentation! The correct URL for adding labels in Google Reader (as of August 2009) is
http://www.google.com/reader/api/0/subscription/edit?client=scroll
with POST arguments
a=user/-/label/[your label]&s=feed/[feed url]&ac=edit&T=[token]

How to access wikipedia

I want to access HTML content from wikipedia .But it is showing access denied.
How can i access Wiki. Please give some suggestion
Use HttpWebRequest
Try the following:
string Text = "http://www.wikipedia.org/";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Text);
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)";
HttpWebResponse respons;
respons = (HttpWebResponse)request.GetResponse();
Encoding enc = Encoding.GetEncoding(respons.CharacterSet);
StreamReader reader = new StreamReader(respons.GetResponseStream(), enc);
string sr = reader.ReadToEnd();

Categories