title: WCF Method throwing SerializationException
body: <p>So I'm self hosting a WCF service. When I call my GetProject() method via the client I get a Unhandled CommuncationException with an InnerException of </p>
  
  <blockquote>
    <p>"The underlying connection was closed: An unexpected error occurred on
    a receive." </p>
  </blockquote>
  
  <p>And the InnerException of that: </p>
  
  <blockquote>
    <p>"Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."</p>
  </blockquote>
  
  <p>Now I know this is just a generic message that doesn't tell me much. So I configured a Service Trace and this is what I got:</p>
  
  <blockquote>
    <p>at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.Reply(MessageRpc&amp;amp; rpc)System.Runtime.Serialization.SerializationException: Type 'System.FormatException' with data contract name 'FormatException:<a href="http://schemas.datacontract.org/2004/07/System" rel="nofollow">http://schemas.datacontract.org/2004/07/System</a>' 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.</p>
  </blockquote>
  
  <p>So I took this message and modified my code and I believe now that I am doing this correctly. I have followed several tutorials, but I still keep getting this exception in the Service Trace.</p>
  
  <p>In my <code>ServiceContract</code> I have the following:</p>
  
  <pre><code>[OperationContract]
  Project GetProject(int id);
  </code></pre>
  
  <p><strong>Edit Removed <code>KnownTypeAttribute</code> use. Commented out here to reflect the changes.</strong></p>
  
  <p>Here is my implementation of the Project class and the classes that it utilizes:</p>
  
  <pre><code>    [DataContract]
      //[KnownType(typeof(Contact))]
      //[KnownType(typeof(ProjectDetails))]
      //[KnownType(typeof(CommercialEntity))]
      public class Project
      {
          [DataMember]
          public ProjectDetails details = new ProjectDetails();
          [DataMember]
          public List&lt;Contact&gt; contacts = new List&lt;Contact&gt;();
          [DataMember]
          public List&lt;CommercialEntity&gt; POs = new List&lt;CommercialEntity&gt;();
          [DataMember]
          public List&lt;CommercialEntity&gt; invoices = new List&lt;CommercialEntity&gt;();
          [DataMember]
          public List&lt;CommercialEntity&gt; quotes = new List&lt;CommercialEntity&gt;();
          [DataMember]
          public List&lt;CommercialEntity&gt; CRs = new List&lt;CommercialEntity&gt;();
      }
  
      [DataContract]
      public class ProjectDetails 
      {
          [DataMember]
          public int projectId { get; set; }
          [DataMember]
          public string name { get; set; }
          [DataMember]
          public int calYearId { get; set; }
          [DataMember]
          public string projectState { get; set; }
          [DataMember]
          public string reportTitle { get; set; }
          [DataMember]
          public int plantId { get; set; }
          [DataMember]
          public string holdNumber { get; set; }
          [DataMember]
          public string holdDescription { get; set; }
          [DataMember]
          public string remarks { get; set; }
          [DataMember]
          public string adminComments {get; set; }
          [DataMember]
          public int companyId { get; set; }
          [DataMember]
          public int customerId { get; set; }
          [DataMember]
          public string folderNumber { get;  set; }
          [DataMember]
          public int invoicedInFull { get; set; }
          [DataMember]
          public int approved { get; set; }
          }
      }
  
      [DataContract]
      public class CommercialEntity
      {
          [DataMember]
          public string number { get; set; }
          [DataMember]
          public DateTime date { get; set; }
          [DataMember]
          public string comments { get; set; }
  
          public CommercialEntity(string setNumber, DateTime setDate, string setComments)
          {
              number = setNumber;
              date = setDate;
              comments = setComments;
          }
      }
  
      [DataContract]
      public class Contact
      {
          [DataMember]
          public string firstName { get; set; }
          [DataMember]
          public string lastName { get; set; }
          [DataMember]
          public string emailAddress { get; set; }
          [DataMember]
          public string phoneNumber { get; set; }
          [DataMember]
          public int alert { get; set; }
          [DataMember]
          public int projectLead { get; set; }
          [DataMember]
          public int mainContact { get; set; }
  
          public Contact(string first, string last, string email, string phone, int alrt, int projLead, int mainCntct)
          {
              firstName = first;
              lastName = last;
              emailAddress = email;
              phoneNumber = phone;
              alert = alrt;
              projectLead = projLead;
              mainContact = mainCntct;
          }
  
          public Contact() { }
      }
  </code></pre>
  
  <p>Where is the hole in my understanding?</p>
  
  <p>Here is what I see when I run the client:</p>
  
  <blockquote>
    <p>See the end of this message for details on invoking  just-in-time
    (JIT) debugging instead of this dialog box.</p>
    
    <p><em><strong></em>**<em>*</em>**<em></strong> Exception Text <strong></em>**<em>*</em>****</strong> </p>
    
    <p>System.ServiceModel.CommunicationException: An error occurred while
    receiving the HTTP response to
    myInternalIP:myPort/ProjectService/ProjectService. 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. ---> System.Net.WebException: The underlying
    connection was closed: An unexpected error occurred on a receive. --->
    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</p>
    
    <p>at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32
    size, SocketFlags socketFlags)</p>
    
    <p>at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset,
    Int32 size) </p>
    
    <p>--- End of inner exception stack trace --- </p>
    
    <p>at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset,
    Int32 size)    </p>
    
    <p>at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)</p>
    
    <p>at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean
    userRetrievedStream, Boolean probeRead)   </p>
    
    <p>--- End of inner exception stack trace ---    </p>
    
    <p>at System.Net.HttpWebRequest.GetResponse()    </p>
    
    <p>at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
    timeout)   </p>
    
    <p>--- End of inner exception stack trace ---</p>
    
    <p>Server stack trace:<br>
    at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException
    webException, HttpWebRequest request, HttpAbortReason abortReason)   </p>
    
    <p>at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
    timeout)    </p>
    
    <p>at System.ServiceModel.Channels.RequestChannel.Request(Message message,
    TimeSpan timeout)    </p>
    
    <p>at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message
    message, TimeSpan timeout)    </p>
    
    <p>at System.ServiceModel.Channels.ServiceChannel.Call(String action,
    Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
    Object[] outs, TimeSpan timeout)    </p>
    
    <p>at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
    methodCall, ProxyOperationRuntime operation)    </p>
    
    <p>at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
    message)</p>
    
    <p>Exception rethrown at [0]:    </p>
    
    <p>at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
    reqMsg, IMessage retMsg)    </p>
    
    <p>at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&amp;
    msgData, Int32 type)    </p>
    
    <p>at IProjectService.GetQuerytoList(Int32 id)   </p>
    
    <p>at ProjectServiceClient.GetQuerytoList(Int32 id) in
    C:\Users\drwill\documents\visual studio
    2010\Projects\ProjectBaseWCF\ProjectBase\generatedProxy.cs:line 1065<br>
    at ProjectWCFClient.MainForm.openToolStripMenuItem_Click(Object
    sender, EventArgs e) in C:\Users\drwill\documents\visual studio
    2010\Projects\ProjectBaseWCF\ProjectBase\PBMain.cs:line 961    </p>
    
    <p>at ProjectWCFClient.MainForm.ProjectListBox_DoubleClick(Object sender,
    EventArgs e) in C:\Users\drwill\documents\visual studio
    2010\Projects\ProjectBaseWCF\ProjectBase\PBMain.cs:line 55</p>
    
    <p>at System.Windows.Forms.Control.OnDoubleClick(EventArgs e)    </p>
    
    <p>at System.Windows.Forms.ListBox.WndProc(Message&amp; m)    </p>
    
    <p>at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m)</p>
    
    <p>at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp;
    m) </p>
    
    <p>at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32
    msg, IntPtr wparam, IntPtr lparam)</p>
  </blockquote>
  
  <p>Here is my Client config:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;configuration&gt;
      &lt;system.serviceModel&gt;
          &lt;bindings&gt;
              &lt;basicHttpBinding&gt;
                  &lt;binding name="BasicHttpBinding_IProjectService" maxReceivedMessageSize="500000000" /&gt;
              &lt;/basicHttpBinding&gt;
          &lt;/bindings&gt;
          &lt;client&gt;
              &lt;endpoint address="http://192.168.0.99:9000/ProjectService/ProjectService"
                  binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IProjectService"
                  contract="IProjectService" name="BasicHttpBinding_IProjectService" /&gt;
          &lt;/client&gt;
      &lt;/system.serviceModel&gt;
  &lt;/configuration&gt;
  </code></pre>
  
  <p>Here is my service config:</p>
  
  <pre><code>&lt;?xml version="1.0"?&gt;
  &lt;configuration&gt;
    &lt;system.web&gt;
      &lt;compilation debug="true"/&gt;
    &lt;/system.web&gt;
    &lt;!-- When deploying the service library project, the content of the config file must be added to the host's 
    app.config file. System.Configuration does not support config files for libraries. --&gt;
    &lt;system.serviceModel&gt;
      &lt;services&gt;
        &lt;service behaviorConfiguration="ProjectBaseWCFServiceLib.Service1Behavior" name="ProjectBaseWCFServiceLib.ProjectService"&gt;
          &lt;endpoint address="" binding="basicHttpBinding" contract="ProjectBaseWCFServiceLib.IProjectService"&gt;
            &lt;identity&gt;
              &lt;dns value="localhost"/&gt;
            &lt;/identity&gt;
          &lt;/endpoint&gt;
          &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/&gt;
          &lt;host&gt;
            &lt;baseAddresses&gt;
              &lt;add baseAddress="http://localhost:8732/Design_Time_Addresses/ProjectBaseWCFServiceLib/Service1/"/&gt;
            &lt;/baseAddresses&gt;
          &lt;/host&gt;
        &lt;/service&gt;
      &lt;/services&gt;
      &lt;behaviors&gt;
        &lt;serviceBehaviors&gt;
          &lt;behavior name="ProjectBaseWCFServiceLib.Service1Behavior"&gt;
            &lt;!-- To avoid disclosing metadata information, 
            set the value below to false and remove the metadata endpoint above before deployment --&gt;
            &lt;serviceMetadata httpGetEnabled="True"/&gt;
            &lt;!-- 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 --&gt;
            &lt;dataContractSerializer maxItemsInObjectGraph="2147483646"/&gt;
            &lt;serviceDebug includeExceptionDetailInFaults="True"/&gt;
          &lt;/behavior&gt;
        &lt;/serviceBehaviors&gt;
      &lt;/behaviors&gt;
    &lt;/system.serviceModel&gt;
  &lt;startup&gt;&lt;supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/&gt;&lt;/startup&gt;&lt;/configuration&gt;
  </code></pre>
  
  <p>In addition, I programatically configure my Console App Host with:</p>
  
  <pre><code>     BasicHttpBinding binding = new BasicHttpBinding();
       binding.OpenTimeout = new TimeSpan(0, 10, 0);
       binding.CloseTimeout = new TimeSpan(0, 10, 0);
       binding.SendTimeout = new TimeSpan(0, 10, 0);
       binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
       binding.MaxReceivedMessageSize = 500000000;
       binding.MaxBufferSize = 500000000;
       binding.MaxBufferPoolSize = 500000000;
  
       selfHost.AddServiceEndpoint(typeof(IProjectService), binding, "ProjectService");
  </code></pre>