WCF ServiceHost throws exception when UI client exits - c#

I am creating a a service which I am hosting in a Console Application. It contains a single method to get data from the service, and a couple of methods that can be executed on the server.
In order to test the service I made a simple WinForms application that connects to the service and calls the operations on the host. This seemingly works just fine, but when I added service tracing to the config file to see what was going on I noticed that an exception is thrown on the service side as soon as I close the UI client:
<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error">
<TraceIdentifier>http://msdn.microsoft.com/nb-NO/library/System.ServiceModel.Diagnostics.ThrowingException.aspx</TraceIdentifier>
<Description>Throwing an exception.</Description>
<AppDomain>WCF.Host.vshost.exe</AppDomain>
<Exception>
<ExceptionType>System.Net.Sockets.SocketException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>
An existing connection was forcibly closedby the remote host
</Message>
<StackTrace>
at System.ServiceModel.Channels.SocketConnection.HandleReceiveAsyncCompleted() at System.ServiceModel.Channels.SocketConnection.OnReceiveAsync(Object sender, SocketAsyncEventArgs eventArgs) at System.Net.Sockets.SocketAsyncEventArgs.FinishOperationAsyncFailure(SocketError socketError, Int32 bytesTransferred, SocketFlags flags) at System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</StackTrace>
<ExceptionString>
System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
</ExceptionString>
<NativeErrorCode>2746</NativeErrorCode>
</Exception>
</TraceRecord>
(I've added a ConsoleTraceListener to the config so that I can see the warnings as soon as they occur.)
When this happens it doesn't affect the server side as far as I can tell, no exceptions are thrown in the console application that hosts the service, and if I restart the UI client it happily lets me perform the operations against the host.
Even so, this is an exception I'd very much like to catch at the host side so that I could handle it. In my opinion, any sign of an exception in the trace log should be investigated, but I simply can't understand where I can catch this error in my code. The Closed and Faulted events on the channel doesn't seem to fire at all.
I've recreated the problem in this VS 2012 solution that can be downloaded here:
http://db.tt/7l2Dnkpr (110 kB)
It consists of three projects, a DLL with the service definitions, a console host and a WinForms UI client. This replicates the setup I have in the real application, but this test is a lot simpler. The solution is setup to start multiple projects, so it should be straight forward to test it.
The WCF.Host application creates a host that is listening on net.tcp://localhost:5000/singleservice
In the UI client, click "GetObjects". This creates the channel to the servicehost and calls the GetObjects() method on it.
Now, exit the UI application and notice the trace output in the console window.
Can anyone see a reason why this would happen, and/or how I could handle the exception in code?

You're holding a reference to service object in your wcf client application (WCF.ClientUI). So you've to close the channel before exiting client process. Add the following code in client, you'll not get any exceptions on closing the client application.
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
((IChannel)service).Close();
}

Related

Windows Server can not use WCF Server

I can use this program on my own computer, but I can not use on the server.
Server use supreme authority Administrator to open the program.
Server WCF HTTP Activation Feature with .NET4.5 is opening.
Server endpoint address use "http://localhost" like following
endpoint address="http://localhost" binding="basicHttpBinding" bindingConfiguration="NewBinding0" name="ProductService" contract="ProductService.IWCFProductService"
Wrong Message:
The communication object, System.ServiceModel.ServiceHost, cannot be used for communication because it is in the Faulted state.
Stack trace at System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan timeout)
at System.ServiceModel.ServiceHostBase.System.IDisposable.Dispose()
at FileUtilityHelperService.Program.Main(String[] args)
This simply means that there has been an unexpected exception somewhere in your code. The error message "...because it is in the Faulted state" means that communication between the server and the client is unusable.
What you need is better error handeling.
Use try/catch around your code that can potentially generate an exception
Always order exeptions from the most specific to the least specific
You would probably like to log your errors to a file or database, log4net is great for this (and comes as a nuget package)

Microsoft Azure Service Bus Timeout Exceptions

We have an application that runs on the Microsoft Azure cloud platform. The communication between some components is made using Service Bus. Everything was working fine, until recently we started to get the following type of timeout exceptions:
When calling QueueClient x.Send(...)
Exception rethrown at [0]: at
Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult
result) at
Microsoft.ServiceBus.Messaging.Sbmp.DuplexRequestBindingElement.DuplexRequestSessionChannel.DuplexCorrelationAsyncResult.End(IAsyncResult
result) at
Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory `1.RequestSessionChannel.RequestAsyncResult.b__4(RequestAsyncResult
thisPtr, IAsyncResult r) at
Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult
result)
When calling NamespaceManager x.GetQueue(...)
PROGRESS queue processing failed. System.TimeoutException: The request
has timed out after 60000 milliseconds. The successful completion of
the request cannot be determined. Additional queries should be made to
determine whether or not the operation has succeeded.
TrackingId:bdffb6bd-5367-4573-aaa3-8ea9a03f5a2b,TimeStamp:5/28/2015
8:39:46 AM ---> System.Net.WebException: The request was aborted: The
request was canceled. at
System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at
Microsoft.ServiceBus.Messaging.ServiceBusResourceOperations.GetAsyncResult`1.b__49(GetAsyncResult`1
thisPtr, IAsyncResult r) at
Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult
result)
When calling NamespaceManager x.SubscriptionExists(...)
Exception doing periodic work: System.TimeoutException: The request
has timed out after 00:10:00 milliseconds. The successful completion
of the request cannot be determined. Additional queries should be made
to determine whether or not the operation has succeeded. Server stack
trace: Exception rethrown at [0]: at
Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult
result) at
Microsoft.ServiceBus.NamespaceManager.OnEndSubscriptionExists(IAsyncResult
result) at
Microsoft.ServiceBus.NamespaceManager.SubscriptionExists(String
topicPath, String name) ...
When calling QueueClient x.Receive(...)
PROGRESS queue processing failed.
Microsoft.ServiceBus.Messaging.MessagingCommunicationException: Error
during communication with Service Bus. Check the connection
information, then retry. --->
System.ServiceModel.CommunicationObjectFaultedException: Internal
Server Error: The server did not provide a meaningful reply; this
might be caused by a premature session shutdown.
TrackingId:04ba0220-0350-4806-9c65-c2bba9671054, Timestamp:28.05.2015
13:00:55 Server stack trace: Exception rethrown at [0]: at
Microsoft.ServiceBus.Common.ExceptionDispatcher.Throw(Exception
exception) at
Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult
result) at
Microsoft.ServiceBus.Messaging.Sbmp.DuplexRequestBindingElement.DuplexRequestSessionChannel.DuplexCorrelationAsyncResult.End(IAsyncResult
result) at
Microsoft.ServiceBus.Messaging.Sbmp.DuplexRequestBindingElement.DuplexRequestSessionChannel.EndRequest(IAsyncResult
result) at
Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement.ReconnectChannelFactory`1.RequestSessionChannel.RequestAsyncResult.b__4(RequestAsyncResult
thisPtr, IAsyncResult r) at
Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.StepCallback(IAsyncResult
result) ….
The exceptions are clearly related to ServiceBus and they are non-deterministic. The functions throwing them, e.g., Send, GetQueue, SubscriptionExists, are called no more than 100-120 times per minute. We changed nothing in the code and increasing the timeout values (even to ridiculously high values, like 10min) did not help. Also, we do not believe it is some network related problem (on our side) since the same error occur when the application is run from different places.
Has anyone else encountered recently these kind of exceptions? Is there a problem on the side of Microsoft or we are missing something?
A few weeks back we had sudden and unexplainable timing issues crop up with our Service Bus app that has been in production for many months. Ours continued to work but every few calls would take 10+ seconds when they are normally 100-200 millisconds. This went on for a couple weeks and I spent most of that trying to figure out what was going on and never did as the problem suddenly vanished.
We did learn that new Service Bus namespaces we created in the same and other data centers for testing while the problem was occurring did not exhibit the same issue. The Service Bus group offered no help and would only say response times are not guaranteed only the SLA is.
I had similar problem when my running code started to generate Timeout exception. Upon research found that firewall blocked the port used for communication. However, port 80 and 443 were still open. So adding following line of code worked for me:
ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Https;

WCF RIA Service Has ServiceActivationException After App Pool Recycle With Unusual Error

I maintain a very large Silverlight application that makes heavy use of WCF RIA Services.
When a user is in the SL application, and the app pool running the RIA services is restarted for any reason, subsequent calls from the client all fail until the user closes the app, and comes in from the main entry point again.
The error in the logs does not correlate to the problem it describes. These services work just fine if a user comes in "clean" essentially.
That said, there should be no reason for this, services do restart from time to time.
The error I get is below. Does anyone have any ideas at what to look at?
[ServiceActivationException]: The service '/ade/Services/DomainServices-Web-
UserService.svc'
cannot be activated due to an exception during compilation.
The exception message is: Entity 'DomainServices.Web.Role_Permission'
has a property 'PermissionReference' with an unsupported type
As stated above, this same call, 10 seconds before the restart, works swimmingly.
Any help would be most appreciated.
I'm sorry I cant answer your question but I can confirm that I get a very similar problem with our large Silverlight application that also makes heavy use of WCF RIA Services. Every so often when the app pool recycles due it's scheduled recycle I see the following type of exceptions in the event log on the IIS server.
WebHost failed to process a request. Sender Information:
System.ServiceModel.ServiceHostingEnvironment+HostingManager/12036987
Exception: System.ServiceModel.ServiceActivationException: The service
'/Services/DomainServices-Web-ServiceLayer-ReportsDomainService.svc' cannot
be activated due to an exception during compilation. The exception
message is: Invalid Include specification for member
'Activity.ActivitySourceType'. Non-projection includes can only be
specified on members with the AssociationAttribute applied.. --->
System.InvalidOperationException: Invalid Include specification for
member 'Activity.ActivitySourceType'. Non-projection includes can only
be specified on members with the AssociationAttribute applied. at
System.ServiceModel.DomainServices.Server.DomainServiceDescription.ValidateEntityTypes()
at
System.ServiceModel.DomainServices.Server.DomainServiceDescription.Initialize()
at
System.ServiceModel.DomainServices.Server.DomainServiceDescription.CreateDescription(Type
domainServiceType) at
System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey
key, Func2 valueFactory) at
System.ServiceModel.DomainServices.Server.DomainServiceDescription.GetDescription(Type
domainServiceType) at
System.ServiceModel.DomainServices.Hosting.DomainServiceHost..ctor(Type
domainServiceType, Uri[] baseAddresses) at
System.ServiceModel.DomainServices.Hosting.DomainServiceHostFactory.CreateServiceHost(Type
serviceType, Uri[] baseAddresses) at
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String
constructorString, Uri[] baseAddresses) at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.CreateService(String
normalizedVirtualPath) at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String
normalizedVirtualPath) at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath) --- End of inner exception stack trace ---
at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath) at
System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String
relativeVirtualPath) Process Name: w3wp Process ID: 15172
These exceptions are logged immediately after the application pool recycles and our users cannot use the application until I manually recycle the application pool again.
Have you made any progress on this?
Thanks
Kevin

Problems with Starksoft.Net.Proxy for SOCKS and bittorrent

I'm using C# to make a bittorrent application with MonoTorrent. The application is somewhat mature, but I'm adding SOCKSv5 proxy support. I've found Starksoft.Net.Proxy to handle the proxy part. However, I'm having some trouble.
I got a BTGuard account for testing with. When I connect (providing username and password and such), I get this error:
Starksoft.Net.Proxy.ProxyException: Connection to proxy host 63.142.161.35 on port 1025 failed. ---> Starksoft.Net.Proxy.ProxyException: The the connection is not allowed by proxy destination rule set concerning destination host 195.122.253.23 port number 11523. The destination reported the host as 0.0.0.0 port -16676.
at Starksoft.Net.Proxy.Socks5ProxyClient.HandleProxyCommandError(Byte[] response, String destinationHost, Int32 destinationPort)
at Starksoft.Net.Proxy.Socks5ProxyClient.SendCommand(Byte command, String destinationHost, Int32 destinationPort)
at Starksoft.Net.Proxy.Socks5ProxyClient.CreateConnection(String destinationHost, Int32 destinationPort)
--- End of inner exception stack trace ---
at Starksoft.Net.Proxy.Socks5ProxyClient.CreateConnection(String destinationHost, Int32 destinationPort)
at Starksoft.Net.Proxy.Socks5ProxyClient.CreateConnectionAsync_DoWork(Object sender, DoWorkEventArgs e)
Which is weird. I have no idea what causes this. I read through the Starksoft code and it seems reasonably in-line with the SOCKS RFC.
Here's the code I'm using to connect to the proxy via Starksoft.Net.Proxy. The stack trace above comes from e.Error on line 133.
I found the issue. Here's the part where Starksoft.Net.Proxy prepares and then discards the data for the username/password exchange.
I fixed it by updating to Biko, but it required some tweaking to get working right. Should be simple for anyone who finds this problem later to deal with.
Alternatively, just grab the source of the broken version and stick some code in to send the data and receive the confirmation.

System.ServiceModel.CommunicationObjectFaultedException

I am facing the following problem on one server only on another server or locally it is working properly.
I am using IIS6 Windows 2003. Is there any setting related problem?
System.ServiceModel.CommunicationObjectFaultedException: The
communication object, System.ServiceModel.Channels.ServiceChannel,
cannot be used for communication because it is in the Faulted state.
Server stack trace: at
System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan
timeout) Exception rethrown at [0]: at
System.Runtime.Remoting.Proxies.RealProxy.
You cannot use a channel that has been faulted. You will need to recreate a new channel.
My toolkit has inbuilt support for this so that you can seamlessly make another call to the channel. It handles this scenario internally.
See http://neovolve.codeplex.com/releases/view/53499.
First, we need to find out what the real problem or issue is. For this set includeExceptionDetailInFaults to true as below in you service App.Config file:
serviceDebug includeExceptionDetailInFaults="true"
Then you will get the real exception detail when you catch an exception. I was getting AccessDeniedException. So I ran this command from Power Shell:
netsh http add urlacl url=http://+:8080/ user=Domainxxx\UserNamexxx. Problem solved.

Categories

Resources