IOException when making HttpWebRequest to local ASHX file - httpwebrequest

Greetings, all. Here is my situation. I am attempting to make an HttpWebRequest to a local handler file and I keep getting the following exception:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Now, I'm using a local handler file because I am writing some integration code for a third party that the site will be using. Until I have a test environment available for me to make requests to, I'm basically mocking the process with a local handler file. Here is the relevant code. Thanks.
WebRequest code (subRequest variable is object passed to the method executing this code):
XmlSerializer serializer;
XmlDocument xmlDoc = null;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
webRequest.KeepAlive = true;
webRequest.Accept = "*/*";
serializer = new XmlSerializer(subRequest.GetType());
XmlWriter writer = new XmlTextWriter(webRequest.GetRequestStream(), Encoding.UTF8);
serializer.Serialize(writer, subRequest);
writer.Close();
xmlDoc = new XmlDocument();
xmlDoc.Load(XmlReader.Create(webRequest.GetResponse().GetResponseStream()));
The "requestUrl" is defined as "http://localhost:2718/Handlers/MyHandler.ashx". I can hit the handler file just fine and have stepped through the code. All it does is assemble an XML response as a string and writes it out to the Response object:
context.Response.ContentType = "text/xml";
string newSubscriptionId = Utils.GetUniqueKey();
StringBuilder sb = new StringBuilder();
sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
// Assemble XML string here
context.Response.Write(sb.ToString());
As far as I can tell, this is all working just fine. But when my code hits the last line of the WebRequest chunk:
xmlDoc.Load(XmlReader.Create(webRequest.GetResponse().GetResponseStream()));
Is when the exception is thrown. Any ideas? Thanks in advance.
James

First, if you don't intend to reuse the connection or there's not going to be another request to the same schema/server/port, I would set KeepAlive to false.
The problem is that XmlDocument.Load() does not read the entire stream before the server closes the connection or that it keeps reading beyond the end and when the server keep-alive timeout is over, the connection is closed by the server. Also, you never close the response stream. To verify that this theory is correct, do something like:
// Optional -> webRequest.KeepAlive = false;
string xml = null;
using (StreamReader reader = new StreamReader (webRequest.GetResponse().GetResponseStream())) {
xml = reader.ReadToEnd ();
}
xmlDoc.LoadXml (xml);
and see if that fixes your problem.

Related

OneDrive REST API Download file

I'm using the REST API of OneDrive in my WCF Web Service. Everything works well but the Download of a file. I need to get the Stream object of the file downloaded but MemoryStream class gives me an Exception about ReadTimeout and WriteTimeout.
This is the code:
.... some code ....
var rClient = new RestClient("https://apis.live.net/v5.0/");
var rRequest = new RestRequest(rootFile.id + "/content", Method.GET);
rRequest.AddParameter("access_token", data.accessToken);
var rResponse = rClient.Execute(rRequest); // THE RESPONSE IS OK
byte[] array = rResponse.RawBytes;
Stream stream = new MemoryStream(array); // PROBLEM HERE!
return stream;
So when I create the Stream Object the MemoryStream throw 2 Exception on the fields ReadTimeout and WriteTimeout saying that they are not supported for this stream.
I don't know how to solve it
As suggested by Will in the comment, I discovered that the Exception on ReadTimeout and WriteTimeout was not the real problem. The Exception was thrown by a null object in the caller method, after the code posted above.
Below there is the point where the Exception was thrown: the Current object was null.
stream = client.DownloadFile(token);
if (stream != null)
{
**WebOperationContext.Current.OutgoingResponse.ContentType = "text/octet-stream";** //HERE
return stream;
}
I removed the line and everything was fixed

Issues performing a query to Solr via HttpClient using Solr 3.5 and HttpClient 4.2

I am trying to query my local Solr server using HttpClient and I cannot figure out why the parameters are not being added to the GET call.
My code for doing this is:
HttpRequestBase request = new HttpGet("http://localhost:8080/solr/select");
HttpParams params = new BasicHttpParams();
params.setParameter("q", query);
params.setParameter("start", String.valueOf(start));
params.setParameter("rows", String.valueOf(rows));
request.setParams(params);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
return stringToStreamConversion(is); //500 error, NullPointerException, response is empty
I have tried to return several things in hopes of seeing what I would get and trying to figure out where the problem was. I have finally realized that I was only getting back the http://localhost:8080/solr/select when I returned
return request.getURI().toURL().toString();
I cannot figure out why the parameters are not getting added. If I do
return request.getQuery();
I get nothing back...any ideas? Thanks for the help in advance!
From what I have seen you are not able to associate your paeans with the request.
So, instead of creating a new HttpParams object and associating it with request, can you try the following approach ?
httpCclient.getParams().setParameter("q", query");
....
The simpler option is to use the approach I used in HTTPPostScheduler, like this:
URL url = new URL(completeUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("type", "submit");
conn.setDoOutput(true);
// Send HTTP POST
conn.connect();

How to edit WCF Message - WCF message interceptors

i'm having some problems implementing my WCF message interceptor. Basically i'm accessing the body contents and performing an xslt tranform over the nodeset to sort it alphabethicaly.
I've tested the XSLT stylesheet and it's working no problems. I write the result of the transform to a MemoryStream object and then attempt to recreate the message from the stream contents.
I examine the resulting stream using either a StreamReader or by loading it into an XmlDocument and i can see the the xml it contains it my expected result from the XSLT transform.
My problem occures when i try to recreate the message! I create an XmlReader based on the stream and use this as my body source for Message.CreateMessage(.....);
I cannot understand why i'm suddenly losing the "correct" contents in the stream when i could examine it and see a couple of statements earlier.
Help very much appreciated!
Full code of the method below:
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel, InstanceContext instanceContext)
{
MessageBuffer msgbuf = request.CreateBufferedCopy(int.MaxValue);
Message tmpMessage = msgbuf.CreateMessage();
XmlDictionaryReader xdr = tmpMessage.GetReaderAtBodyContents();
MemoryStream ms = new MemoryStream();
_compiledTransform.Transform(xdr,null,ms);
ms.Position = 0;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(ms);
MemoryStream newStream = new MemoryStream();
xmlDoc.Save(newStream);
newStream.Position = 0;
//To debug contents of the stream
StreamReader sr = new StreamReader(newStream);
var temp = sr.ReadToEnd();
//At this point the XSLT tranforms has resulted in the fragment we want so all good!
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
newStream.Position = 0;
XmlReader reader = XmlReader.Create(newStream,settings);
reader.MoveToContent();
//Reader seems to have lost the correct fragment!!! At least returned message does not contain correct fragment.
Message newMessage = Message.CreateMessage(request.Version, null, reader);
newMessage.Properties.CopyProperties(request.Properties);
request = newMessage;
return request;
}
I think your code works Griff. I've just plugged it into an existing an existing IDispatchMessageInspector implementation and it generated a good (transformed) message. I therefore suspect your problem lies elsewhere.
How are you establishing that the 'losing' the correct contents? Could whatever is inspecting the transformed message be reading the message prior to transformation by mistake?
Unless you are trying to correlate state with the BeforeSendReply method then you should be returning null instead of the request reference.

Stream text to client via handler ASP.NET

To get around twitters streaming API not having a crossdomain file to access it from client side( in this case Silverlight) I have made a Generic Handler file in a web project which basically downloads the stream from twitter and as it reads it, writes it to the client.
Here is the handler code:
context.Response.Buffer = false;
context.Response.ContentType = "text/plain";
WebRequest request = WebRequest.Create("http://stream.twitter.com/1/statuses/filter.json?locations=-180,-90,180,90");
request.Credentials = new NetworkCredential("username", "password");
StreamReader responseStream = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.GetEncoding("utf-8"));
while (!responseStream.EndOfStream)
{
string line = "(~!-/" + responseStream.ReadLine() + "~!-/)";
context.Response.BinaryWrite((Encoding.UTF8.GetBytes(line)));}
And this does work, but the problem is that once the client disconnects the handler just carry's on downloading. So how do I tell if the client is still busy receiving the request and if not, end the while loop?
Also, my second problem is that on the client side doing a "ReadLine()" does nothing, presumably because it is counting the entire stream as one line so never gets the full response. To work around that I read it byte by byte and when it sees "(~!-/" around something it know that is one line. VERY hacky, I know.
Thanks!
Found the answer!
while (context.Response.IsClientConnected)
:)

Why am I getting a "double response" from HttpWebResponse?

The follow code (running in ASP.Net 2.0) displays the contents of the requested URL twice. I only want it to display the contents of the requested URL once. I can't figure out what I'm doing wrong. The URL requested is returning XML and if I visit the URL directly, it works fine.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/xml";
request.ContentLength = postDataBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
requestStream.Close();
// get response and write to console
response = (HttpWebResponse) request.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
try {
Response.Write(responseReader.ReadToEnd());
}
finally {
responseReader.Close();
}
response.Close();
Your code looks good, so I don't think the problem is there... but what I would suggest is the following:
1) Maybe the error is on the URL's other end... so try hitting Google and see if the returned content is good or not.
2) Put a breakpoint at the "responseReader.ReadToEnd()" spot, and see if what's coming out of there is good.
3) If this code above is in an ASPX page... are you making sure to call "Response.End();" after you're last line of code? (not "resposne.close()", but "Response.End()").
I found the problem. It's not with the above code at all, but with the page being called. The page I was calling was inherited from a class whose Page_OnInit method contained the following line: "MyBase.OnLoad(e)", which caused the Page_OnLoad method to be executed twice. Obviously, it should have been MyBase.OnInit(e) instead. I didn't catch it because when I tested the page directly I had to temporarily remove the inheritance from the class because of some other code that would've have prevented me from testing the page directly.
I will now put on my "Dunce" hat and retreat to the corner for a time out. Thanks anyway for the help.