HttpListenerResponse - behavior when throwing HttpListenerException - c#

people,
I created a small webserver for a custom application. The webserver works fine, yet from time to time it throws some exceptions, when I try to send a response to the client using HttpListenerResponse. Assume I have
HttpListenerResponse res = ctx.Response; // My HttpListenerContext
... //initialize the response
res.StatusCode = 200;
try
{
res.OutputStream.Write(terminate, 0, terminate.Length);
res.Close();
}
catch(HttpListenerException hex){ ... }
Now, it happens that the connection breaks down (I get Windows System Error-Codes 22, 64, 1229)
MSDN-reference. My client is the WPF-Webbrowser-control.
What does the client receive? Does the client receive the HTTP 200? Or can I alter the status-code inside the exception and somehow push it to the client?
Thank you for your help.

Related

Azure Service Bus MessageReceiver Receive() web sockets error

I am working with a c# program within my network and am able to post messages to an Azure Service Bus queue. When receiving them, I get an exception on MessageReceiver.Receive(). The code and error is below;
MessagingFactory factory = MessagingFactory.CreateFromConnectionString(QueueConnectionString);
//Receiving a message
MessageReceiver testQueueReceiver = factory.CreateMessageReceiver(QueueName);
using (BrokeredMessage retrievedMessage = testQueueReceiver.Receive(new TimeSpan(0, 0, 20)))
{
try
{
var message = new StreamReader(retrievedMessage.GetBody<Stream>(), Encoding.UTF8).ReadToEnd();
retrievedMessage.Complete();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
retrievedMessage.Abandon();
}
}
The error gets thrown on the 'using' line at
testQueueReceiver.Receive(...);
The server rejected the upgrade request. 400 This endpoint is only for web-socket requests
I can't find anything on the web with the exception of one post which seems to suggest it is a firewall / ports issue. I have all the azure service bus ports outbound open (9350-9354, 80, 443) locally but there is a chance the 9000's are blocked at the firewall. Should it require these? Any pointers would be greatly appreciated !
Service MessagingCommunication Exception - The End point is only for web socket requests
I'm just wondering why don't you use OnMessage instead of polling the queue?
var connectionString = "";
var queueName = "samplequeue";
var client = QueueClient.CreateFromConnectionString(connectionString, queueName);
client.OnMessage(message =>
{
Console.WriteLine(String.Format("Message body: {0}", message.GetBody<String>()));
Console.WriteLine(String.Format("Message id: {0}", message.MessageId));
message.Complete()
});
This was fixed due to some proxy issues.
The account that the code was running under was an async service. I needed to log in as that account, open IE and go to connections (LAN) and remove the proxy checkboxes (detect settings automatically, etc). Once this was done, the code bypassed the proxy and worked fine.

how to control if web service is unavailable?

I have a webservice that gets a list from client and inserts it to database. Client has a windows service that is sending a list per 10 seconds. But there is a problem. What if it cannot reach to webservice(server). I should not lost any of the data. I decided to save data to a txt or binary if server is not reachable, and then upload them after the server starts to run. However, how can I decide whether the webservice is unavaliable. If I store the data to a file in a catch block, it will store when ever it gets an error, not only webservice unavaliable error. Any advice?
You can make an http request on the service's endpoint url and check if everything is ok :
var url = "http://....";
//OR
var url = service_object.Url;
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 2000; //timeout 20 seconds
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException(response.StatusDescription);
}
}
catch (ApplicationException ex)
{
//Do what you want here, create a file for example...
}
I'd introduce a queuing system (such as MSMQ or NServiceBus) so that the windows service only needs to place message(s) into the queue and something else (co-located with the web service) can dequeue messages and apply them (either directly or via the web service methods).
When everything is up and running, it shouldn't introduce much more overhead over your current (direct) web service call, and when the web service is down, everything just builds up in the queuing system.

Duplicated http request using HttpListener

I have a scenario where an HttpListener listens for http requests. I created a thread where is called Request method of HttpListenerContext:
while (true)
{
var ctx = listener.GetContext();
HttpListenerRequest req = ctx.Request;
...
ctx.Response.StatusCode = 200;
ctx.Response.StatusDescription = "OK";
ctx.Response.Close();
}
The problem here is that even if i send only one request (for example by telnet) sometimes i see a lot of requests. The listener prefix is http://localhost:9999. The strange thing is that printing remote endpoint of the request i see two or more different end points for each request. Any ideas?

TCP connection phase fails (calling web service from JAVA client to C#-server)

so I have an app for Android that calls a webservice (C#) and I have from the start noticed that it often, but not all the time, it is extremely slow in returning an answer or that the request fails altogether.
At first I thought it had something to do with the backend code, ie the server takes to long to process the request and return a result. I have now excluded that possibility as the processing only takes about 40ms. I did however notice that the webservice code isnt called sometimes, or it takes a long time for the code to be executed.
So I started up Wireshark and took a look at the packets transferred, and discovered what I see as a faulty TCP connection phase. The first picture below show a faulty connection.
It looks like this:
Client: SYN
Server: SYN ACK
Client: SYN ACK
as this image shows:
But it should look like this:
Client: SYN
Server: SYN, ACK
Client: ACK
When I try another time, just calling the webservie again from the Android app (no restart or anything) I get the correct steps and also a response as expected. Here is a Wireshark-image from that:
I am pretty sure that this is the problem with what I see as a "very slow webservice", as there is usually a long delay before receiving an answer and sometimes (as in the first image), there is no response at all. Wireshark also shows that it can just "stall" with the answers for 10-20 seconds, and that is before actually reacing the web service code.
There is no network problem, as this is all run on a local WLAN (the computer acts as a hotspot, no one else is connected to it). The Android device is a Samsung S2 running 2.3.3, the webservice is .NET 3.5 running a self-hosted ServiceHost.
Any ideas?
-------- ADDITIONAL INFO ------------
Here is how I call my webservice from the JAVA-code (Method is GET):
private void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
try
{
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
This is how the web service method is defined in .NET:
[OperationContract]
[WebGet(UriTemplate = "PutMessage?jsonString={jsonString}", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat= WebMessageFormat.Json)]
string PutMessage(string jsonString);
If you look at the dump a little closer, what you're actually seeing is the client not getting any packets from the server;
Client: SYN
Server: SYN ACK (ACK, never reaches the client)
Server: SYN ACK (Retransmission of the first ACK, also lost. )
Client: SYN (Retransmission, it does not know the server received the first SYN)
Server: SYN ACK (ACK on the SYN from the client, once again lost)
Client: SYN (Retransmission since it *still* does not know the server got the SYN)
In other words, a perfectly normal retransmission from both sides, provided the client does not receive any server packets.

Terminate Web Request Early (C#)

As part of a suite of integration tests I am writing, I want to assert that my server behaves correctly when a client HTTP request terminates early, before all the response data has been sent.
Is it possible to create an HTTP request and terminate it after receiving just a few bytes of data in C#?
You don't have to read all bytes out fo the response. Just read as many bytes as you want and then return from your test.
You can do so more or less like this:
Stream myStream = resp.GetResponseStream();
myStream.Read(bufferArray, 0, 1); //read 1 byte into bufferArray
return;
You may find the documentation on WebReponse useful.
Just start the call asynchronously using, say a background worker, and then close the thread/channel.
I found a solution which works for me. I just close the response after getting it. This seems to leave me with the response headers, but closes the connection before the server is finished sending.
var response = request.getResponse();
response.Close();
// Assert that server has dealt with closed response correctly

Categories

Resources