I am retrieving data from a wcf web service and when data is more than 0.2 million records i get an exception which is as under:
System.ServiceModel.CommunicationException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. ---> System.Net.WebException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. ---> 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.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
My web.config looks like this :
<basicHttpBinding>
<binding name="BasicHttpBinding_IService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
messageEncoding="Text" textEncoding="utf-8" transferMode="StreamedResponse" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647"
maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
<binding maxReceivedMessageSize="2147483647" allowCookies="true">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
</binding>
</basicHttpBinding>
I am sure that my web service is retrieving data from DB. but is unable to transfer to my web from where i initiated the call. Thanks in advance for any help.
I had recently the same problem with a Wcf service within a .Net 4.0 web app. I increased the maxItemsInObjectGraph value and server didn't throw the exception anymore. The documentation here says the default maximum is Int32.MaxValue but I think it is incorrect, the maximum value is 65535.
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<dataContractSerializer maxItemsInObjectGraph="6553500"/>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
The other thing you can do is enable tracing. This is an example of what I have in the web.config:
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\temp\log\Traces.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
If you double click on the Traces.svclog, windows should open the Microsoft Service Trace Viewer.
If you test your service with the Microsoft WCF Test Client make sure you change the default client config to match the server settings (this includes the client endpoint behavior) to make sure the client can receive the response from the server.
Make your client basicHttpBinding the same as your server binding. This is a verry common error to only change one binding instead of server and client binding.
If that not works you can enable wcf tracing:
wcf tracing
That will give you more insights in what the underling problem is.
Add following configuration to your wcf service config. And see c:\log\Traces.svclog file.
My exception was throw for ;
There was an error while trying to serialize parameter
The InnerException message was 'Enum value '0' is invalid for type 'ThyCams2014.XrmBase.new_filingstatu' and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attrienter code herebute.'. Please see InnerException for more details.
<configuration>
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\log\Traces.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
</configuration>
This statement solved my problem:
db.ContextConfiguration.ProxyCreationEnabled = false;
we had a loop in our object graph that were returning. I know this probably isn't your problem but I'm adding it here in case anyone else has the same problem. We had includeExceptionDetailInFaults enabled but weren't getting the error in any client (our application or the WCF Test Client). Luckily it showed up in server logs so we were able to find it that way.
We had Parent -> child and child -> parent for two-way navigation, we had to break that link and instead have parent -> child, and the child had an id to lookup the parent, then the error went away.
Had the same error after migrating to a new server.
It finally boiled down to a missing targetFramework attribute that was not needed on the old server...
<system.web>
<httpRuntime enableVersionHeader="false" targetFramework="4.7.2"/>
</system.web>
Related
I have a WCF service running on a virtual machine. I haven't changed anything on this server or the service in quite some time. When I try to send up a file through the service that is ~25 mb I am getting this:
----------------------------------------------------------
DateTime: 1/24/2019 12:22:04 PM
ClassName: UploadPpsZipFile
Message: There was no endpoint listening at http://www.myservice.com/xxx/FileService.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
Server stack trace:
at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()
at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at WebStorageFileTransfer.TruckTransferServiceReference.IFileService.UploadPpsZipFile(UploadFileRequest uploadFileRequest)
at WebStorageFileTransfer.ProgramTypes.SendZip.SendZip_Upload.UploadPpsZipFile(FileParms fileParms)
Unable to connect to the remote server
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()
An attempt was made to access a socket in a way forbidden by its access permissions xxx.xxx.xxx.xxx:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
----------------------------------------------------------
My app.exe.config looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IFileService" maxReceivedMessageSize="2147483647" sendTimeout="00:02:00">
<readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://www.myservice.com/xxxx/FileService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IFileService" contract="TruckTransferServiceReference.IFileService" name="BasicHttpBinding_IFileService" />
</client>
</system.serviceModel>
</configuration>
When I send up a smaller file, such as a 1mb file, I have no issues. I have tested this on several computers and I get the same results.
Any suggestions?
There are 3 things that you can change in order to make it work :
IIS Host Settings:
I believe you have hosted the WCF service in IIS. Hence you need to set the
When sending large amounts of data you will need to set the maxAllowedContentLength IIS setting (for more information see Configuring IIS Request Limits)
This value defaults to ~28MB as far as I know.
Max Received Message Size:
You will have to change this to some other value (e.g. long.MaxValue). By default it is set to 64 KB.
Enable Streaming
By default the mode of transmission for WCF is buffered. While sending and receiving all data need to be present in memory - which would not be possible for large files.
Hence you will have to change the mode to "streaming" as shown below:
<system.serviceModel>
…
<bindings>
<basicHttpBinding>
<binding name="ExampleBinding" transferMode="Streaming"/>
</basicHttpBinding>
</bindings>
…
<system.serviceModel>
Refer the documentation.
I am using a RestClient app to communicate with my WCF service .and I am getting the following exception
The underlying connection was closed: An unexpected error occurred on a receive.
This is the C# code I use
string q = string.Format(#"xxxxxxxxxxxxxxxxxxxxxxxxxxx");
WebClient client = new WebClient();
string Url = string.Format("{0}/Get?queries={1}", BaseUrl,HttpUtility.UrlEncodeUnicode(q));
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var result = client.DownloadString(Url);
Console.WriteLine("======================output================================");
Console.WriteLine(result);
Console.WriteLine("===========================================");
Here is the error message
System.Net.WebException was caught
HResult=-2146233079
Message=The underlying connection was closed: An unexpected error occurred on a receive.
Source=System
StackTrace:
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadString(Uri address)
at System.Net.WebClient.DownloadString(String address)
at RestClient.Program.GetRecordsTest() in C:\Users\Wiemon\Downloads\RestAppClient\RestAppClient\Program.cs:line 118
InnerException: System.IO.IOException
HResult=-2146232800
Message=Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Source=System
StackTrace:
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security._SslStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.TlsStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
InnerException: System.Net.Sockets.SocketException
HResult=-2147467259
Message=An existing connection was forcibly closed by the remote host
Source=System
ErrorCode=10054
NativeErrorCode=10054
StackTrace:
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
InnerException:
Here is my binding
<binding name="wsHttpEndpoint" >
<readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="Transport">
<transport clientCredentialType="Certificate" />
<message clientCredentialType="Certificate" />
</security>
</binding>
And my endpoint behavior ,not that I set maxItemsInObjectGraph="2147483647"
<behavior name="MyEndpointBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<clientCredentials>
<clientCertificate findValue="xxxxxxxxxxxxxxxxxx" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My" />
<serviceCertificate>
<authentication certificateValidationMode="None" revocationMode="NoCheck" />
</serviceCertificate>
</clientCredentials>
</behavior>
Its common (generic) message.
You should use Trace Viewer Tool (SvcTraceViewer.exe) to find out server error
I had similar errors coming from the depths of my http bindings in WCF.
client -> The underlying connection was closed: An unexpected error occurred on a receive.
client -> Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
server (got this with the help of "procdump") -> The I/O operation has been aborted because of either a thread exit or an application request
Eventually after many hours I came upon the HTTP.sys logging (in C:\WINDOWS\System32\LogFiles\HTTPERR ) and I discovered that the WCF self-hosted service connections were being forcibly dropped (on purpose) because of an obscure configuration issue (minimum send rate bytes per second). Unfortunately it took another few hours to reconfigure that (you cannot do it via "netsh http add timeout" so you have to do it within the app or within IIS when not self-hosted).
I dont't know if is the same error, but in my case, the exception was in Json, that cannot convert the Date value, because it was empty.
DateTime values that are greater than DateTime.MaxValue or smaller than DateTime.MinValue when converted to UTC cannot be serialized to JSON.
The trace viewer was very useful to find the issue.
Configure WCF tracing in your app.config / web.config and check Error.svclog (it will be created near your binary file) for details.
In my case it was because of using Auto-property initializer (property without setter) - a feature from C# 6.0
<Message>No set method for property 'FailedCount' in type 'MyProject.Contracts.Data.SyncStatusByVersion'.</Message>
<StackTrace> at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message, Type type)
at WriteSyncStatusByVersionToJson(XmlWriterDelegator , Object , XmlObjectSerializerWriteContextComplexJson , ClassDataContract , XmlDictionaryString[] )
...
</StackTrace>
To configure WCF tracing:
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true" >
<listeners>
<add name="xml"/>
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging">
<listeners>
<add name="xml"/>
</listeners>
</source>
<source name="myUserTraceSource" switchValue="Information, ActivityTracing">
<listeners>
<add name="xml"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add name="xml" type="System.Diagnostics.XmlWriterTraceListener" initializeData="Error.svclog" />
</sharedListeners>
</system.diagnostics>
This is my first WCF service project writing both client and server side. I'm from a Windows Forms background.
I think I've been having problems with packet/receive buffer size but I don't have a clue how to test whether my app.config is working correctly or what I've done wrong.
The client project's app.config is set as follows and it's testproj.exe.config reflects the contents correctly
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IPulseWebService"
closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8"
useDefaultWebProxy="true">
<readerQuotas
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxDepth="2147483647"
maxNameTableCharCount="2147483647"
maxStringContentLength="2147483647" />
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="blah"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IPulseWebService"
contract="ServiceReference1.IPulseWebService" name="WSHttpBinding_IPulseWebService">
<identity>
<dns value="localhst" />
</identity>
</endpoint>
</client>
</system.serviceModel>
My web service's webservice.dll.config contains the following service.serviceModel section
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IPulseWebService"
closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8"
useDefaultWebProxy="true">
<readerQuotas
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxDepth="2147483647"
maxNameTableCharCount="2147483647"
maxStringContentLength="2147483647" />
</binding>
</wsHttpBinding>
<basicHttpBinding>
<binding name="BasicHttpBinding_IPulseWebService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="SmartcentreWcfLib.PulseWebService">
<host>
<baseAddresses>
<add baseAddress="http://l0calhost:8732/Design_Time_Addresses/SmartcentreWcfLib/PulseWebService/" />
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address="" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IPulseWebService"
contract="SmartcentreWcfLib.IPulseWebService">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="l0calhost" />
</identity>
</endpoint>
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="True" />
<!-- To receive exception details in faults for debugging purposes,
set the value below to true. Set to false before deployment
to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
In my server side wcf dll, I have the following function just as a test to return some rows of data. Each row is a set of key/value pairs stored in an Dictionary. Each object should be a simple byte[] or variable type.
List<IDictionary<string, object>> IAuditV1.ReadAuditForStaffMember(long staffId, DateTime startDate,
DateTime endDate, Int32 recordCount)
{
List<TableAdminAudit> tempResult = DatabaseInterface.Instance.AuditQueries.ReadAdminAudit(staffId, startDate,
endDate, recordCount);
return tempResult.Select(record => record.PrepareForWebInterface()).Cast<IDictionary<string, object>>().ToList();
}// function
In my client application I am running the following loop, which simply increments the number of received records.
Int32 totalRecords = 0;
while (true)
{
results = client.ReadAuditForStaffMember(1, DateTime.MinValue, DateTime.Now, totalRecords);
totalRecords += 10; //results.Length;
if (totalRecords == 0) break;
}
On the 3rd loop when the returned buffer reaches 30 records in size I receive the following error message.
I looked up the error and forums suggested it relates to the connection closing before the whole data had been received so change the various buffer sizes etc. As you can see from my config files, I've upped all the values I'm aware of to 2147483647 but it's not worked.
So I don't know where to go from here. Can anybody help please?
System.ServiceModel.CommunicationException occurred
HResult=-2146233087
Message=An error occurred while receiving the HTTP response to blah2/Design_Time_Addresses/SmartcentreWcfLib/PulseWebService/. 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.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.RequestClientReliableChannelBinder`1.OnRequest(TRequestChannel channel, Message message, TimeSpan timeout, MaskingMode maskingMode)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout, MaskingMode maskingMode)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionClientSettings`1.SecurityRequestSessionChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at WcfTester.ServiceReference1.IPulseWebService.ReadAuditForStaffMember(Int64 staffId, DateTime startDate, DateTime endDate, Int32 startIndex)
at WcfTester.ServiceReference1.PulseWebServiceClient.ReadAuditForStaffMember(Int64 staffId, DateTime startDate, DateTime endDate, Int32 startIndex) in W:\Projects\pulse.smartcentre.root\pulse.smartcentre\WcfTester\Service References\ServiceReference1\Reference.cs:line 481
at WcfTester.Program.Main(String[] args) in W:\Projects\pulse.smartcentre.root\pulse.smartcentre\WcfTester\Program.cs:line 40
InnerException: System.Net.WebException
HResult=-2146233079
Message=The underlying connection was closed: An unexpected error occurred on a receive.
Source=System
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
InnerException: System.IO.IOException
HResult=-2146232800
Message=Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Source=System
StackTrace:
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
InnerException: System.Net.Sockets.SocketException
HResult=-2147467259
Message=An existing connection was forcibly closed by the remote host
Source=System
ErrorCode=10054
NativeErrorCode=10054
StackTrace:
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
InnerException:**
The file something.dll.config is never used. You need to copy those settings into the web.config or servicehost.exe.config file.
This is how .NET has worked since Day 1, and is not specific to WCF. Consider that a given DLL can be used by multiple "executables", and each of these may have different settings for the DLL.
I'm trying to build a WCF Application service, using FW4.0.
My service work correctly when transferring EntiryFramework object between Server and client. But I'm having problem passing EF object from Client to Server.
Here some more detail about my environment:
- The service is running in debug mode locally on IIS
- I'm running all this on my Windows 7
- I'm using Visual Studio 2010 on FW4.0
I'm trying to send a object (tblClient) to server to save the record, but a keep having the error (413) Request Entity Too Large.
Here the full stack:
System.ServiceModel.ProtocolException occurred
HResult=-2146233087
Message=The remote server returned an unexpected response: (413) Request Entity Too Large.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory`1 factory, WebException responseException, ChannelBinding channelBinding)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at ClientApp.ServiceReference1.IService.SaveClient(tblClient client)
at ClientApp.ServiceReference1.ServiceClient.SaveClient(tblClient client) in C:\dufh\WPF Project\ClientApp\Service References\ServiceReference1\Reference.vb:line 2383
at ClientApp.ViewModel.ClientViewModel.SaveClient() in C:\dufh\WPF Project\ClientApp\ViewModel\ClientViewModel.vb:line 48
InnerException: System.Net.WebException
HResult=-2146233079
Message=The remote server returned an error: (413) Request Entity Too Large.
Source=System
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
InnerException:
I've do some research and all point to the maxBufferSize and/or maxBufferPoolSize and/or maxReceivedMessageSize witch is not large enough in the Client config App.Config. So I inscresed them to maximum value :
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
But still the error remain.
Here my full Client App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="MVVM Sampling"/>
</sharedListeners>
</system.diagnostics>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"/>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:7803/Service1.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference1.IService"
name="BasicHttpBinding_IService" />
</client>
</system.serviceModel>
</configuration>
and the full Web.Config WCF service Web.Config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
<readerQuotas maxDepth="200" maxStringContentLength="8388608" maxArrayLength="16384" maxBytesPerRead="2147483647" maxNameTableCharCount="16384" />
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<connectionStrings>
<add name="MaitreEntities" connectionString="metadata=res://*/Schemat.csdl|res://*/Schemat.ssdl|res://*/Schemat.msl;provider=System.Data.SqlClient;provider connection string="data source=INFOFILE2\SQL2008R2;initial catalog=0001ConneryFerland;user id=sa;password=kermit80;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Any help would be very welcome :-)
For the record
I think I got it.
The Web.Config from the service does not have the binding information.
I placed this info in it, and voila!
<bindings>
<basicHttpBinding>
<binding maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text">
<readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
</basicHttpBinding>
</bindings>
Note here that the binding did not have a name specified.
You don't have an explicit endpoint (meaning one defined in your config file) for your service, so the binding configuration you declared ("BasicHttpBinding_IService") isn't being used. WCF is providing a default endpoint along with a default binding (basicHttpBinding unless you overrode it in the protocolMapping section of the config file).
You have two ways to resolve this in your service's config file:
You can make the "BasicHttpBinding_IService" configuration the default by removing the name attribute:
<binding maxBufferPoolSize="2147483647".....
Or you define an endpoint explicitly in the config and assign your binding configuration to the bindingConfiguration attribute of the endpoint.
<services>
<endpoint address=""
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService"
contract="ServiceReference1.IService" />
</services>
If you create custom binding e.g. MybasicBinding,
<basicHttpBinding>
<binding name="MybasicBinding" closeTimeout="01:00:00" openTimeout="01:00:00" receiveTimeout="01:00:00" sendTimeout="01:00:00"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" >
<readerQuotas maxDepth="32" maxBytesPerRead="200000000"
maxArrayLength="200000000" maxStringContentLength="200000000" />
</binding>
</basicHttpBinding>
To avoid the 413 error, Do not foreget to Specify the bindingConfiguration="MybasicBinding" for service endpointas,
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="MybasicBinding" contract="WCFService.IService" />
Another way to fix this and have a better look at web.config file, is to edit the web.config file with the "Microsoft Service Configuration Editor" (C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\SvcConfigEditor.exe)
if no binding is specified and httpsgetenabled is true then you may need to set basichttpsbinding in your service application's web.config
<bindings>
<basicHttpsBinding>
<binding maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text">
<readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
</basicHttpsBinding>
I was getting this error. I discovered that I had created the binding configuration, but failed to set the endpoint to that configuration. Therefore, the endpoint was using an unnamed binding configuration with the default settings. So, maxReceivedMessageSize was 65k.
This can also be due to IIS restriction.
IIS Manager-> Select your application-> Features Veiw->Request Filtering->Edit Feature Settings->Maximum Allowed Content Length 30000000(28.6M)-> Increase the value
I've created wcf service and everything works correctly but when i try to return Type[] (i got it from Assembly.GetTypes()) i have following exception:
System.ServiceModel.CommunicationException: The underlying connection was closed: The connection was closed unexpectedly.
---> System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at ConsoleApplication1.ServiceReference1.IWcfAssembly.GetAssemblyTypes(String a)
at ConsoleApplication1.ServiceReference1.WcfAssemblyClient.GetAssemblyTypes(String a) in D:\Projekty\ConsoleApplication1\ConsoleApplication1\Service References\ServiceReference1\Reference.cs:line 50
at ConsoleApplication1.Program.Main(String[] args) in D:\Projekty\ConsoleApplication1\ConsoleApplication1\Program.cs:line 17
I thought it might be maxItemsInObjectGraph property or maxArrayLenght (and similar) but it didn't help. Still got the same exception. Maybe I did something wrong with the property declaration?
this is my client config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IWcfAssembly" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="128" maxStringContentLength="2147483647" maxArrayLength="2147483647"
maxBytesPerRead="4096" maxNameTableCharCount="2147483647" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:57040/WcfAssembly.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IWcfAssembly" contract="ServiceReference1.IWcfAssembly"
name="BasicHttpBinding_IWcfAssembly" />
</client>
</system.serviceModel>
</configuration>
and this is my service config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IWcfAssembly" receiveTimeout="00:10:00" sendTimeout="00:10:00" openTimeout="00:10:00" closeTimeout="00:10:00"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="52428899">
<readerQuotas maxDepth="128"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="4096"
maxNameTableCharCount="2147483647" />
<security mode="None"/>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
I have also added [ServiceBehavior(MaxItemsInObjectGraph = int.MaxValue)] as a class attribute. I had it in my service config before but this is one of tries.
Do you have any ideas guys? Why the array returned from Assembly.GetTypes() causes such error? (big array of int[] works OK)
The problem is that the System.RunTimeType is not serialize (which is in the internal implementation of Type)
using this mock:
void Main()
{
var dto = new MyDto();
dto.Tada = new Type[] { this.GetType() };
DataContractSerializer ser =
new DataContractSerializer(typeof(MyDto));
var ms = new MemoryStream();
ser.WriteObject(ms, dto);
ms.Dump();
dto.Dump();
}
public class MyDto
{
public Type[] Tada { get; set; }
}
Throws:
SerializationException: Type 'System.RuntimeType' with data contract
name 'RuntimeType:http://schemas.datacontract.org/2004/07/System' is
not expected. Consider using a DataContractResolver or add any types
not known statically to the list of known types - for example, by
using the KnownTypeAttribute attribute or by adding them to the list
of known types passed to DataContractSerializer.
Which makes sense because RunTimeType is internal (Type itself is abstract). You have to come up with your own serialized type that can convey the info you want.