How to prevent timeout response to winform client from WCF service - winforms

I have a WCF service method being called by a winform client. The client passes a couple strings to the method, the method then performs a series of operations which can take in excess of 20 minutes.
At around 15 minutes into the process the client receives a response that the TCP connection has been terminated. The WCF service continues to process beyond this point until it finishes the job.
I have set the timeouts in the binding configuration in the client to 30 minutes each. I have also set the compilation batch timeout to 30 minutes. The WCF service returns a string to the client just saying "Success", so it is not a size issues regarding the transmission. It almost seems as if IIS is terminating the TCP connection due to some timeout.
An error occurred while receiving the HTTP response to http://xxxxxxxxxxxxx.svc . This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. Inner Exception: The underlying connection was closed: An unexpected error occurred on a receive. Inner Exception: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. Inner Exception: An existing connection was forcibly closed by the remote host
Any help? The error is generated by the winform client, not the wcf service btw.
Here are the binding settings:
<wsHttpBinding>
<binding name="WSHttpBinding_STUFFGOESHERE" closeTimeout="00:30:00"
openTimeout="00:30:00" receiveTimeout="00:30:00" sendTimeout="00:30:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288000" maxReceivedMessageSize="65536" messageEncoding="Text"
textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:30:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" />
</security>
</binding>
</wsHttpBinding>

have you set the timeouts on your httpbinding?
in code:
((WSHttpBinding)binding).OpenTimeout = new TimeSpan(0, 1, 0);
((WSHttpBinding)binding).CloseTimeout = new TimeSpan(0, 1, 0);
((WSHttpBinding)binding).SendTimeout = new TimeSpan(0, 30, 0);
((WSHttpBinding)binding).ReceiveTimeout = new TimeSpan(0, 30, 0);
or in the service config-file
<bindings>
<wsHttpBinding>
<binding openTimeout="00:1:00"
closeTimeout="00:1:00"
sendTimeout="00:30:00"
receiveTimeout="00:30:00">
</binding>
</wsHttpBinding>
</bindings>
also see http://msdn.microsoft.com/en-us/library/hh924831.aspx

Related

What is the maximum value for timeout attributes in httpbinding in WCF

My config setting is as below.
<bindings>
<basicHttpBinding>
<!-- This binding is used when connecting to services secured using SSL (e.g. when accessible over internet/WAN) -->
<binding name="SecuredBasicHttpBinding" closeTimeout="10675199.02:48:05.4775807"
openTimeout="10675199.02:48:05.4775807" receiveTimeout="10675199.02:48:05.4775807" sendTimeout="10675199.02:48:05.4775807"
maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxStringContentLength="16384" />
<security mode="Transport">
<transport clientCredentialType="Basic" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
I want to set maximum value for closetimeout,opentimeout..etc..
I got this value 10675199.02:48:05.4775807 from below url.but it didnt work.
How can I set the receiveTimeout and sendTimeout to infinity with this WCF contact?
what is the max value which can be set for timeout?
This post is stating that the max timeout is almost 25 days. Good luck with that! :p
As i mentioned before consider setting it to a realistic timespan and take appropriate actions when the response is timed-out.
The max timeout value is the max value of a signed 32 bit integer: 2147483647

Winforms App becomes unresponsive after a period of time when making Asynchronous WCF calls via netTcpBinding

Scenario
I am supporting/enhancing a Windows Form App that communicates via a WCF service hosted in IIS using a ServiceHostFactory class.
For the problem I am trying to solve, I am dealing with these 2 methods in the ServiceContract. The ServiceContract is marked as PerCall.
[OperationContract(IsOneWay = true)]
void RunJob(int jobId);
[OperationContract]
byte[] GetUserJobs(int userID);
The user will submit a job, via the RunJob method in a fire and forget fashion. This job will make a WCF call to another service, get some data back, do a lot of stuff with it and store it in the database. This particular job takes roughly 62 minutes to complete.
While the job is in a Running state, the client calls the GetUserJobs method asynchronously every 10 seconds to check job status and update the GUI accordingly. The client is communicating with the WCF service via netTcpBinding.
Problem
Right around the 1 hour mark, the GUI becomes completely unresponsive. Asynchronous calls are still being made, but the completed event is never being called. It seems to me something is deadlocked or blocking, and I can't figure exactly why this is happening. The GUI can start becoming unresponsive before the RunJob (OneWay) is actually finished on the server, but the job itself always finishes and data gets saved to the database.
So even though the GUI is unusable, the Server is still working, except it won't respond to any WCF calls.
If I edit the web.config on the server to recycle IIS, the GUI becomes responsive again.
I am by no means a WCF expert, and I am really struggling with coming up with a solution to this problem. I am pretty sure it is happening because of the asynchronous calls, but I can't pinpoint the exact cause yet. The Asynchronous calls are getting closed, according to the code below.
According to my trace logs, I see the following errors right around when the GUI becomes unresponsive:
<ExceptionType>System.ServiceModel.CommunicationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>There was an error writing to the pipe: The pipe is being closed. (232, 0xe8).</Message>
Then for Activity http://tempuri.org/IConnectionRegister/ValidateUriRoute I will see:
<DataItem> <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Warning"> <TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.CommunicationObjectFaulted.aspx</TraceIdentifier> <Description>Faulted System.ServiceModel.Channels.ClientFramingDuplexSessionChannel</Description> <AppDomain>/LM/W3SVC/2/ROOT/Service_mt-4-130395564562210673</AppDomain> <Source>System.ServiceModel.Channels.ClientFramingDuplexSessionChannel/56837067</Source> </TraceRecord> </DataItem>
<DataItem> <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Warning"> <TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.CommunicationObjectFaulted.aspx</TraceIdentifier> <Description>Faulted System.ServiceModel.Channels.ServiceChannel</Description> <AppDomain>/LM/W3SVC/2/ROOT/Service_mt-4-130395564562210673</AppDomain> <Source>System.ServiceModel.Channels.ServiceChannel/3537205</Source> </TraceRecord> </DataItem>
Relevant Code/Config (Sanitized a bit)
Client Binding Config
I have tried to set all the timeouts to "infinite" for now, just to rule out that there was some strange timeout behavior. I have tried various timeout settings, but nothing seems to work.
<binding name="MyEndpoint" closeTimeout="infinite"
openTimeout="infinite" receiveTimeout="infinite" sendTimeout="infinite"
transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard" listenBacklog="10"
maxBufferPoolSize="2147483647" maxBufferSize="2147483647"
maxConnections="100" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
<reliableSession ordered="true" inactivityTimeout="infinite"
enabled="false" />
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
<message clientCredentialType="Windows" />
</security>
</binding>
Server Binding Config
<netTcpBinding>
<binding name="MyBinding" portSharingEnabled="true" transferMode="Buffered" closeTimeout="infinite" openTimeout="infinite" receiveTimeout="infinite" sendTimeout="infinite" maxBufferPoolSize="524288" maxBufferSize="2147483647" maxConnections="10" listenBacklog="200" maxReceivedMessageSize="2147483647">
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
<message clientCredentialType="Windows" />
</security>
<reliableSession ordered="true"
inactivityTimeout="infinite"
enabled="false" />
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
<netTcpBinding>
<serviceBehaviors>
<behavior name="MyServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<ServiceErrorHandler />
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
The GUI does something similar to the following to asynchronously call the WCF service:
public void RefreshJobs()
{
//When the GUI becomes unresponsive, a lot of these log statements start piling up in the log file, until service is restarted
Logger.GetInstance().Info("Begin RefreshJobs");
ServiceClient svc = new ServiceClient("MyEndpoint", url);
try
{
svc.GetUserJobsCompleted += new EventHandler<GetUserJobsCompletedEventArgs>(svc_GetJobsCompleted);
}
catch (Exception e)
{
throw e;
}
svc.GetUserJobsAsync(SomeSingleton().CurrentUser.UserID, false, svc);
Logger.GetInstance().Info("End RefreshJobs");
}
private void svc_GetJobsCompleted(object sender, GetUserJobsCompletedEventArgs e)
{
Logger.GetInstance().Info("Start GetJobsCompleted");
if (e.Result != null)
{
//Do Stuff to Update GUI
}
//Close the connection
if (e.UserState is ServiceClient)
{
((ServiceClient)e.UserState).Close();
}
Logger.GetInstance().Info("End GetJobsCompleted");
}
The problem ended up being the CPU being overloaded, which caused the Smsvchost.exe to stop responding.
A fix from Microsoft is available

WCF with Silverlight 4, Publish Subscribe UserName Auth ServiceSecurityContext.Current NULL Reference

I've built a WCF Publish Subscribe Topic Service and can successfully publish/subscribe with a console appplication (meaning I know it at least works in a console), and can successfully add both service references to both in my Silverlight Application.
The Problem:
Every time I try to subscribe or publish (in other words, anytime, I pass through my user name and password) while using Silverlight, the ServiceSecurityContext.Current.PrimaryIdentity is NULL, but it works fine in the console. Also, when accessing the service, it doesn't hit my custom user name and password validator when accessing it from Silverlight, but it does from a console.
What are my requirements?
I need to consume my publish subscribe service via Silverlight. The WCF Service needs to user UserName authentication. The WCF Service needs to be as secure as possible while still allowing for use with Silverlight. I have to use .Net, I have to use WCF PubSubTopic, I have to use Silverlight.
I am open to creating multiple subscriber endpoints(for instance, maybe a custom one for SL to use, and another for my api users), but I need to user the same publisher as the rest of my api users (oh yeah, btw, the WCF service is built as an api for my users to access if they want... I'm only allowing them access to the subscriber, and blocking the publisher)
I'm looking for example, advice, and/or troubleshooting help with my current problem. Here's some of my code
VB.NET code of Silverlight trying to publish something
Private Const PUBLISHER_ENDPOINT_ADDRESS As String = "http://myserver/portal/api/v1/Publisher.svc"
Friend Shared Sub PublishSomething()
Dim binding As PollingDuplexHttpBinding = New PollingDuplexHttpBinding()
Dim endpoint_address As EndpointAddress = New EndpointAddress(PUBLISHER_ENDPOINT_ADDRESS)
Dim client As New PublisherClient(binding, endpoint_address)
client.ClientCredentials.UserName.UserName = String.Format("{0}\{1}", Common.CompanyName, Common.UserName)
client.ClientCredentials.UserName.Password = "mypassword"
Dim uUpdate As New PortalPublisherService.UserUpdatedNotification
uUpdate.CompanyID = CompanyId
uUpdate.CompanyName = CompanyName
uUpdate.isAdvisor = True
uUpdate.isMaster = True
uUpdate.MetaNotes = "Testing from silverlight."
uUpdate.updateById = UserId
uUpdate.updateByName = UserName
uUpdate.userEmail = "bill#domain.com"
uUpdate.userId = UserId
client.UserUpdateAsync(uUpdate)
End Sub
Here's the web.config from the service
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
<protocolMapping>
<add scheme="http" binding="wsDualHttpBinding"/>
</protocolMapping>
<extensions>
<bindingExtensions>
<add name="pollingDuplexHttpBinding"
type="System.ServiceModel.Configuration.PollingDuplexHttpBindingCollectionElement,
System.ServiceModel.PollingDuplex, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</bindingExtensions>
</extensions>
<behaviors>
<serviceBehaviors>
<!--primary behavior-->
<behavior name="Portal.Api.Behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceCredentials>
<serviceCertificate findValue="PortalApiCert" storeLocation="LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectName"/>
<clientCertificate>
<authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck"/>
</clientCertificate>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Portal.Web.UserPassAuth, Portal.Web"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<pollingDuplexHttpBinding>
<binding name="pollingBindingConfig"
closeTimeout="00:01:00"
openTimeout="00:01:00"
receiveTimeout="00:10:00"
sendTimeout="00:01:00"
transferMode="Buffered"
hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="5242880"
maxBufferSize="655360"
maxReceivedMessageSize="655360">
<readerQuotas maxDepth="32"
maxStringContentLength="81920"
maxArrayLength="163840"
maxBytesPerRead="16384"
maxNameTableCharCount="163840" />
<security mode="TransportCredentialOnly" />
</binding>
</pollingDuplexHttpBinding>
</bindings>
<services>
<!--publisher endpoint configuration settings-->
<service behaviorConfiguration="Portal.Api.Behavior" name="Portal.Web.Publisher">
<endpoint address="" binding="pollingDuplexHttpBinding" contract="Portal.Publisher.IPublisher" bindingConfiguration="pollingBindingConfig"/>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="meta"/>
<host>
<baseAddresses>
<add baseAddress="http://server/portal/api/v1/IPublisher"/>
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
I want to emphasize that I've tried, figuratively, a million different configurations, but can't remember every combination I've tried. I know I'm doing some stuff in the config I shouldn't be, but I was just trying to get it to work period. Also, here are the links I've looked at already
this one
and this one
there's more, but ... well... it's been a long day...
Thanks in advance for any help
Additional NOTE:
This is the binding I'm successfully using with NON-Silverlight implementations
<wsDualHttpBinding>
<binding name="Portal.Api.Binding" maxReceivedMessageSize="2147483647" sendTimeout="00:10:00">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
<security mode="Message">
<message clientCredentialType="UserName" negotiateServiceCredential="false"/>
</security>
</binding>
</wsDualHttpBinding>
Since no one has answered this, I will answer this with my findings. What I'm looking for here is not possible with RIA services and Silverlight over HTTPS. WCF RIA services just don't offer this functionality at this time. If you know this statement not to be true.. please answer my question above with a solution.

PrincipalPermission.Demand() failing once WCF Service was moved to SSL

My Silverlight/WCF application uses PrincipalPermission in each service method to ensure the user is Authenticated. This works just fine when I have everything configured to HTTP, but once I configured my service endpoints/bindings to support HTTPS (SSL), I get an exception thrown when I call the Demand() method of my PrincipalPermission object.
EDIT: I should mention I am using IIS 7.5 Express to host and debug this project.
Here is the method that checks to make sure the user is authendicated. It's called from each of my service methods:
protected void SecurityCheck(string roleName, bool authenticated)
{
System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
PrincipalPermission p = new PrincipalPermission(null, roleName, authenticated);
try
{
p.Demand();
}
catch (Exception ex)
{
/* wrap the exception so that Silverlight can consume it */
ServiceException fault = new ServiceException()
{
/* Code = 1 will mean "unauthenticated!" */
Code = 1, Message = ex.Message
};
throw new FaultException<ServiceException>(fault); }
}
}
The execption thown is "Request for principal failed."
Here are the important bits of my web.config file:
<behavior name="BinarySSL">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer maxItemsInObjectGraph="6553600"/>
<serviceTimeouts transactionTimeout="00:10:00"/>
</behavior>
<binding name="MyApp.Web.Services.ProjectService.customBinding0"
receiveTimeout="00:10:00" sendTimeout="00:10:00">
<binaryMessageEncoding />
<httpsTransport authenticationScheme="Basic"/>
</binding>
<service name="MyApp.Web.Services.ProjectService" behaviorConfiguration="BinarySSL">
<endpoint address="" binding="customBinding" bindingConfiguration="MyApp.Web.Services.ProjectService.customBinding0"
contract="MyApp.Web.Services.ProjectService" />
</service>
Here is the ClientConfig:
<binding name="CustomBinding_ProjectService">
<binaryMessageEncoding />
<httpsTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
</binding>
<endpoint address="https://localhost:44300/Services/ProjectService.svc"
binding="customBinding" bindingConfiguration="CustomBinding_ProjectService"
contract="ProjectProxy.ProjectService" name="CustomBinding_ProjectService" />
I'm hoping someone can point in in the right direction here. Again, this configuration works just fine until I configure my services for SSL. Any thoughts?
Thanks,
-Scott
I thought I found the problem, and answered my own question - but I was wrong. Still have the same issue.

The HTTP request to *.svc has exceeded the allotted timeout. The time allotted to this operation may have been a portion of a longer timeout.

I have been developing a Silverlight application using WCF.
The problem is that sometimes it throws an exception stating:
"The HTTP request to 'http://localhost:1276/Foo.svc' has exceeded the allotted timeout. The time allotted to this operation may have been a portion of a longer timeout."
So how do I increase the timespan? Some have suggested the usage of receive time out as below in web config and in service.client config file
<bindings>
<customBinding >
<binding name="customBinding0" receiveTimeout="02:00:00" >
<binaryMessageEncoding maxReadPoolSize="2147483647" maxWritePoolSize="2147483647" maxSessionSize="2147483647" />
<httpTransport maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" transferMode="Buffered"/>
</binding>
</customBinding>
</bindings>
what would be the maximum value for the receiveTimeout property?
I imagine the issue is not that your ReceiveTimeout is beyond the maximum value for that setting, as the MaxValue of a TimeSpan is over 10 million days. Instead, I think the settings are just not taking effect.
You should try increasing the timeout values on both the server and the client-side:
On the server (in your web.config)
<binding name="customBinding0" receiveTimeout="00:10:00" sendTimeout="00:10:00" openTimeout="00:10:00" closeTimeout="00:10:00">
On the client (in your ServiceReferences.ClientConfig)
<binding name="CustomBinding_DesignOnDemandService" receiveTimeout="00:10:00" sendTimeout="00:10:00" openTimeout="00:10:00" closeTimeout="00:10:00">
The HTTP request to has exceeded the allotted timeout. The time allotted to this operation may have been a portion of a longer timeout.
Three places to set time values to fix this issue…
Web.Config
<httpRuntime executionTimeout="600" />
(this is seconds, so here it’s 10min). More info on httpRuntime here.
On your Web.Config Binding Elements
<binding name="customBinding123" receiveTimeout="00:10:00" sendTimeout="00:10:00" openTimeout="00:10:00" closeTimeout="00:10:00" />
On your ServerReferences.ClientConfig binding elements within the system.serviceModel
<binding name="CustomBinding" receiveTimeout="00:10:00" sendTimeout="00:10:00" openTimeout="00:10:00" closeTimeout="00:10:00" />
Some days ago we got the same error message. I found this thread, but before we started to increase the different timeout properties, we checked the antivirus software of the client machine: it was NOD. The newer NOD (and maybe other AVs) has port filter/block possibility. We turned off the 80/443 port blocking, and the client connected without any timeout error message.

Resources