user2404595
user2404595

Reputation:

An existing connection was forcibly closed by the remote host("CommunicationException was Unhandled")

I have created WCF service and hosted it into IIS. this WCF service I use to upload file to server from client machine. In this service I upload more than one image file to server but when image file size is in MB(e.g. 6MB) it gives me an error "CommunicationException was Unhandled"

An error occurred while receiving the HTTP response to http://localhost:50904

/Transferservice.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.

StackTrace

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.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 WindowsForms.TransferServiceReference1.ITransferService.UploadFile(RemoteFileInfo request)
   at WindowsForms.TransferServiceReference1.TransferServiceClient.WindowsForms.TransferServiceReference1.ITransferService.UploadFile(RemoteFileInfo request) in F:\TransferServiceReference1\Reference.cs:line 206
   at WindowsForms.Form1.btnUpload_Click(Object sender, EventArgs e) in F:\Project Under Amit Sir\WindowsForms\WindowsForms\Form1.cs:line 37
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at WindowsForms.Program.Main() in F:\Project Under Amit Sir\WindowsForms\WindowsForms\Program.cs:line 18
   at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

WCF Service Code

ITransferService.cs

 [ServiceContract]
    public interface ITransferService
    {
           [OperationContract]
           void  UploadFile(RemoteFileInfo request);
    }

    [MessageContract]
    public class RemoteFileInfo : IDisposable
    {
        [MessageHeader(MustUnderstand = true)]
        public string FileName;

        [MessageHeader(MustUnderstand = true)]
        public long Length;

        [MessageBodyMember(Order = 1)]
        public System.IO.Stream FileByteStream;

        public void Dispose()
        {
            if(FileByteStream != null)
            {
                FileByteStream.Close();
                FileByteStream = null;
            }
        }
    }

Service1 .cs

public class Service1 : ITransferService
    {
public void UploadFile(RemoteFileInfo request)
        {
            FileStream targetStream = null;
            Stream sourceStream = request.FileByteStream;

                    string uploadFolder = @"D:\upload\FileName\";

            string filePath = Path.Combine(uploadFolder, request.FileName);

            using(targetStream = new FileStream(filePath, FileMode.Create,
                                  FileAccess.Write, FileShare.None))
            {
                //read from the input stream in 65000 byte chunks
                            const int bufferLen = 65000;
                byte[] buffer = new byte[bufferLen];
                int count = 0;
            while((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                {
                    // save to output stream
                    targetStream.Write(buffer, 0, count);
                }
                targetStream.Close();
                sourceStream.Close();
            }
        }
}

Web.Config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>

  </system.web>
  <system.serviceModel>

    <!--<bindings>
      <basicHttpBinding>
        <binding name="TansferService.Service1Behavior" messageEncoding="Text" transferMode="Streamed" maxReceivedMessageSize="4294967294"
                 maxBufferSize="65536" maxBufferPoolSize="65536">
        </binding>
      </basicHttpBinding>
    </bindings>-->

    <services>
      <service behaviorConfiguration="TansferService.Service1Behavior" name="TansferService.Service1">
        <endpoint address="" binding="basicHttpBinding" contract="TansferService.ITransferService">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost/TransferService.svc"/>
          </baseAddresses>
        </host>
      </service>
    </services>    
     <behaviors>
      <serviceBehaviors>
        <behavior name="TansferService.Service1Behavior">
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
          <!-- 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>

Client Side Code on client side just single upload button this upload button transfer multiple file to server using WCF service code as

private void btnUpload_Click(object sender, EventArgs e)
        {
            DirectoryInfo dir = new DirectoryInfo(Application.StartupPath+@"\Upload Files");

            TransferServiceClient obj = new TransferServiceClient();
            ITransferService clientUpload = new TransferServiceClient();
            RemoteFileInfo uploadRequestInfo = new RemoteFileInfo();
            foreach (FileInfo fileInfo in dir.GetFiles())
            {
                string fileName = Path.Combine(fileInfo.DirectoryName , fileInfo.ToString());           
                using (FileStream stream = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    uploadRequestInfo.FileName = fileInfo.ToString();
                    uploadRequestInfo.Length = fileInfo.Length;
                    uploadRequestInfo.FileByteStream = stream;
                    clientUpload.UploadFile(uploadRequestInfo);
                }
            }
        }

App.Config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_ITransferService" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="4294967294"
                    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>
                <binding name="BasicHttpBinding_ITransferService1" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    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>
        <client>
            <endpoint address="http://localhost:50904/Transferservice.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITransferService"
                contract="TransferServiceReference.ITransferService" name="BasicHttpBinding_ITransferService" />
            <endpoint address="http://localhost:50904/Transferservice.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITransferService1"
                contract="TransferServiceReference1.ITransferService" name="BasicHttpBinding_ITransferService1" />
        </client>
    </system.serviceModel>

</configuration>

Upvotes: 1

Views: 2913

Answers (3)

flayn
flayn

Reputation: 5322

For testing purpose you can include the server exception details in the fault.

in your web.config change this:

<serviceDebug includeExceptionDetailInFaults="false"/>

to:

<serviceDebug includeExceptionDetailInFaults="true"/>

More details here: http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicedebugbehavior.includeexceptiondetailinfaults.aspx

Upvotes: 1

Alireza Maddah
Alireza Maddah

Reputation: 5885

Try turning on WCF tracing using the following configuration from MSDN to investigate what is going on behind the scenes and discover the exception that is being thrown; since the exception that you are encountering is a general exception and does not tell you the exact source of problem.

<configuration>
    <system.diagnostics>
        <sources>
            <source name="System.ServiceModel" 
                    switchValue="Information, ActivityTracing"
                    propagateActivity="true">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
            <source name="CardSpace">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
            <source name="System.IO.Log">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
            <source name="System.Runtime.Serialization">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
            <source name="System.IdentityModel">
                <listeners>
                    <add name="xml" />
                </listeners>
            </source>
        </sources>

        <sharedListeners>
            <add name="xml"
                 type="System.Diagnostics.XmlWriterTraceListener"
                 initializeData="c:\log\Traces.svclog" />
        </sharedListeners>
    </system.diagnostics>
</configuration>

Upvotes: 1

Vyacheslav Volkov
Vyacheslav Volkov

Reputation: 4742

Try this settings:

<system.web>    
<httpRuntime maxRequestLength="102400" />
</system.web>

This will set the maximum message length to 100 MB. Check this MSDN page for more information.

Upvotes: 0

Related Questions