Silent exception caught by IntelliTrace - c#

Good afternoon,
I am running into a curious problem with WCF and IntelliTrace. I have an application that I'm testing using a locally-hosted WCF endpoint (the development server built into VS2010) using the basicHttpBinding. The application has been running normally: no exceptions are are making their way to the app and all of the WCF calls are returning data.
On a lark, I decided to take a look at the IntelliTrace output and noticed that my first call to WCF throws two exceptiosn:
Exception:Thrown: "No connection could be made because the target machine actively refused it" (System.Net.Sockets.SocketException)
A System.Net.Sockets.SocketException was thrown: "No connection could be made because the target machine actively refused it"
Exception:Caught: "No connection could be made because the target machine actively refused it" (System.Net.Sockets.SocketException)
A System.Net.Sockets.SocketException was caught: "No connection could be made because the target machine actively refused it"
I've reduced the application to a trivial use case:
ServiceClient client = new ServiceClient();
string[] output = client.LegacyCheck("username");
Console.WriteLine(output[0]);
Console.WriteLine(client.GetData(65));
And I get the same behavior. The second call has no exception associated with it.
I'm very puzzled. If the connection is being refused, then why does the exception not make it up to the application? And why would it success after 2 failed tries?
Any help is appreciated!

For what it's worth, I've noticed this behavior too with my IronPython/WPF applications. I've eventually realized that Intellitrace is simply showing you ALL of the exceptions that are raised and caught during normal operation, even if its part of a BCL or other library.
Of course, you only need to worry about unhandled exceptions (after they break your execution, you'll usually see those in IntelliTrace as a long chain of Thrown: Caught: Thrown: Caught: .... all the way down to Thrown: which will be the last line as the exception was not caught.
What I'm willing to bet is that the WCF code try's a couple of things first, catches the SocketExceptions, and then continues on its merry way. You wouldn't ever see this, but for IntelliTrace :)

Related

How to trap when server forcebly closes HttpClient

One is encouraged to re-use HttpClient rather than making a new one for each api call.
https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client
My client program has a single connection that remains open.
However, if somebody stops IIS then the connection can't remain open.
In this case I get an exception that kills my client program even though I have a catch for it. (see code)
Is there some way to make the exception handler handle the exception without crashing the program?
Alternatively, is there some property of HttpClient that indicates that the server has closed it?
try
{
return await m_Client.GetAsync(AppVars.Instance.ServerAddress + method);
}
catch (Exception ex)
{
// getting 'An existing connection was forcibly closed by the remote host' kills the
// application
// getting 'No connection could be made because the target machine actively refused it'
// does not kill the application - i.e. catch behaves as expected
}
I have discovered that this is caused by Visual Studio. I am debugging both the client and the server from one solution (multiple startup projects). When I close IIS Express, Visual Studio kills the client next time it tries to use the connection. If I launch a separate instance of Visual Studio and debug the client from there then the client does not get killed when I try to re-use the closed connection, i.e. the exception handling works as expected. (so I can make a new connection and retry)
Hopefully this will help anyone who experiences the same issue.

Transport errors

I'm working on a crawler and my attempt at fixing an issue with this exception:
System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host at System.Net.Sockets.NetworkStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
was to implement a retry pattern after using wireshark and looking at network logs I concluded that these errors are most likely transient.
However these exceptions are really bugging me now and I would really like to get to the bottom of why I am getting these errors. Can anyone suggest a good strategy to adopt and tools I can use or reasons you can think of why the connection is being forcibly closed?
Thanks
I see two questions here:
Why is the Exception being thrown?
Why is the connection being forcibly closed?
Why is the Exception being thrown?
This is a problem with the transport implementation you have chosen to consume. Apparently, microsoft decided to communicate the error by wrapping it up in an exception and throw it up the stack. The corresponding source code can be found here: http://referencesource.microsoft.com/#System/net/System/Net/Sockets/NetworkStream.cs,766
In the source code, you can also see that the InnerException is set and contains a localization independent representation of the errorCode.
The bottom line is that this exception being thrown does not mean anything exceptional happened, it can happen just because the connection was dropped.
Which brings us to the next question:
Why is the connection being forcibly closed?
Just as the exceptions message hints, the reason could well be the remote host. Therefore, looking at the remote hosts implementation could be required to get to the bottom of this.
I suspect though, that just judging by the exception, you cannot rule out the reason to be somewhere in between the hosts (sharks have shown an appetite for fiber cables).
I suggest the following experiment:
Set up the two hosts residing on different machines and let them connect through a cable.
While the connection is established, unplug the cable.
This could not disproof but at least proof the possibility.
However, "working on a crawler" suggests that you might encounter a variety of different hosts and it is to be expected that some of them turn taciturn sometimes for whatever reason you would care to imagine.
EDIT:
I remember catching this exception when using TCP over IP when the remote host sent a packet with the RST Flag set. The value of the RST Flag is displayed in Wireshark.
networkstream
My 50 cents: This is the normal behaviour when using networkstreams for reading data from a socket. It is not a user error, the exception thrown just causes the data processing in the reading thread to be interrupted. Just wrap it up with a try/catch-handler accordingly.
You could try to use the DebuggerNonUserCode attribute (https://msdn.microsoft.com/de-de/library/system.diagnostics.debuggernonusercodeattribute%28v=vs.110%29.aspx) to suppress debugger alerts when an exception is triggered. Be aware that this may also "hide" other exceptions...

WebExcpetion usind WebRequest.BeginGetResponse

i have a question which is bothering me for a long time.
I am using Windows Phone 8 and c#.
From time to time I get this Excpetion while downloading a file from the web:
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.ni.dll
A first chance exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll
A first chance exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll
ExceptionMessage:The remote server returned an error: NotFound.
But then I run the programm again and it works fine. I don't know why it can't find the remote server sometimes, is the problem really with the server?
It think its something in my code, i use these functions:
WebRequest request = WebRequest.Create("http...);
IAsyncResult res = request.BeginGetResponse(new AsyncCallback(DownloadComplete), null);
I would be grateful for any advice, because this Exception keeps popping up and I couldn't solve it.
It doesn't say it can't find the remote server, but that the server balked at the file requested because it didn't exist on that remote server at that time. It's hard to know your exact scenario, but putting aside network issues, it could be something as simple as the file doesn't exist, at that point in time.
How often is this file being updated, if ever? Think of the possibility that, at the time you request the file, it has been deleted and will momentarily be rewritten.
The web isn't inherently reliable and is only made to look reliable; there are numerous techniques in this, but what I'm saying is that, in your case, it might be worse some 'recovery' logic to try again upon failure after a period.
Just a possibility.
I get this when I forget the phone is running in an emulator and change the web reference to localhost. Localhost will then be interpreted on the phone itself and obviously the web service isn't running on the phone. If you are doing local debugging, make sure to use your machine's IP address and not localhost or 127.0.0.1.

Wince Socket exception on asynchronous HTTP request

I am writing a WinCE app in C# that makes an HTTP POST to an APACHE server residing on my network. Because of some network issues (I am guessing), I get the following exception in the managed code
System.Net.Sockets.SocketException occurred
Message="A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond"
ErrorCode=10060
NativeErrorCode=10060
StackTrace:
at System.Net.Sockets.Socket.ConnectNoCheck(EndPoint remoteEP)
at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
at System.Net.Connection.doConnect(IPEndPoint ep)
at System.Net.Connection.connect(Object ignored)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()
This exception isn't always thrown, but when it is thrown, my app fails to connect to the server AT ALL. Repeated connection attempts don't help in reconnecting either. The only thing that helps is closing and re-deploying the app.
I can't catch the exception because its inside of managed code. Is there any way to circumvent this and close all socket connections to my server and re-initialize them? Is there something I am doing wrong?
The exception message looks a bit misleading ("connection attempt failed because the connected party") but I think it means your hardware is communicating with the server, but the server is not accepting the connection on the TCP level.
A problem I could think of is "hanging" connections, causing the server to reach the maximum number of concurrent connections and to stop accepting new ones.
Although it's just a guess, you might want to check the apache log if you can to see if you can find out if the server reports anything, and perhaps try restarting apache as soon as the problem occurs again. If that helps, you still need to find the cause of course.

WCF REST Client Exception

I have the following WCF client code:
string add = String.Format("http://localhost:{0}/ServiceRequestRest",accessPort);
var cf = new ChannelFactory<IServiceRequestRest>(new WebHttpBinding(), add);
cf.Endpoint.Behaviors.Add(new WebHttpBehavior());
busService = cf.CreateChannel();
busService.DoMyStuff("hello",null);
When I have "first chance exception break" activated, that last line of code throws a series of exceptions. The first exception is this:
System.InvalidOperationException occurred
Message="Envelope Version 'EnvelopeNone (http://schemas.microsoft.com/ws/2005/05/envelope/none)' does not support adding Message Headers."
Source="System.ServiceModel"
StackTrace:
at System.ServiceModel.Channels.MessageHeaders.ValidateHeaderKind(HeaderKind headerKind)
I am not aware that I am trying to "add Message Headers", but I choose to continue execution and immediately get the next exception:
System.Net.WebException occurred
Message="The underlying connection was closed: The connection was closed unexpectedly."
Source="System"
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
With all that said, I'm having difficulty understanding what the problem is. Any clues?
Update: The return type of my REST call could not be serialized, as I learned from another site. That alone could cause this problem, but after I fixed it I still had the same problem. When I use a regular catch block for the exception, all I get is "the connection was closed unexpectedly." What else could I be missing?
Update2: I think I found the final problem. I was getting interference from Skype. The code is working now. :)
The main problem that I see is that you are trying to use a WCF Channel to communicate using WebHttpBinding.
IMHO the entire purpose of WebHttpBinding was so that the client did not have to use the WCF stack to communicate with it. You simply use any HTTP stack to make the requests.

Categories