1

I have a Service where all methods work fine except one which returns a list<Module>

My Module Class (An Entity) is as follow

[DataContract(IsReference = true)] //prevents Infinite loop
[KnownType(typeof(SubModule))]
public class ModuleMst 
{
    public ModuleMst ()
    { }

    [Key]
    [DataMember]
    public int moduleid { get; set; }

    [StringLength(100)]
    [DataMember]
    public string modulename { get; set; }

    [StringLength(1)]
    [DataMember]
    public string status { get; set; }

    [DataMember]
    public string crby { get; set; }

    [DataMember]
    public DateTime crdt { get; set; }

    [DataMember]
    public string modby { get; set; }

    [DataMember]
    public DateTime moddt { get; set; }

    //[DataMember]
    public virtual List<SubModule> SubModules { get; set; }

}

The Exception WcfTestClient shows as

An error occurred while receiving the HTTP response to http://localhost:8888/ArchService/. 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.

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)

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 IArchService.GetAllModules()
   at ArchServiceClient.GetAllModules()

Inner Exception:
The underlying connection was closed: An unexpected error occurred on a receive.
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

Inner Exception:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
   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)

Inner Exception:
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)

The Configuration being

  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="LargeSettingsWS" maxBufferPoolSize="524288" maxReceivedMessageSize="6553600">
          <readerQuotas maxDepth="32" maxStringContentLength="100000" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="None" />
        </binding>
      </wsHttpBinding>
      <netTcpBinding>
        <binding name="LargeSettingsTcp" maxBufferSize="524288" maxBufferPoolSize="524288" maxReceivedMessageSize="524288">
          <readerQuotas maxDepth="32" maxStringContentLength="100000" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="Transport" >
            <transport clientCredentialType="Windows" />
            <message clientCredentialType="Windows" />
          </security>
        </binding>
      </netTcpBinding>
      <netNamedPipeBinding>
        <binding name="LargeSettingsPipe" maxBufferSize="524288" maxBufferPoolSize="524288" maxReceivedMessageSize="524288">
          <readerQuotas maxDepth="32" maxStringContentLength="100000" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="Transport" />
        </binding>
      </netNamedPipeBinding>
    </bindings>
    <services>
      <service name="AppService.ArchService">
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8808/ArchService" />
            <add baseAddress="net.pipe://localhost/ArchService/" />
            <add baseAddress="http://localhost:8888/ArchService/" />
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied above -->
        <endpoint address="" binding="wsHttpBinding" bindingConfiguration="LargeSettingsWS" contract="AppService.IArchService">

          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="" binding="netTcpBinding" bindingConfiguration="LargeSettingsTcp" name="netTcpEndPoint" contract="AppService.IArchService" listenUriMode="Explicit">
          <identity>
            <certificateReference storeName="My" storeLocation="LocalMachine" x509FindType="FindBySubjectDistinguishedName" />
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="NetSvc" binding="netNamedPipeBinding" bindingConfiguration="LargeSettingsPipe" name="netPipeEndPoint" contract="AppService.IArchService" />

        <endpoint address="mex" binding="mexTcpBinding" name="MetadatEndpointTcp" contract="IMetadataExchange" endpointConfiguration="" />
        <endpoint address="mex" binding="mexNamedPipeBinding" name="MetadatEndpointNetPipe" contract="IMetadataExchange" />
        <endpoint address="mex" binding="mexHttpBinding" name="MetadatEndpointHttpDual" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <dataContractSerializer maxItemsInObjectGraph="2147483646" />

          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True" />

          <serviceDebug includeExceptionDetailInFaults="True" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

The Exception is not being very helpful.

Also All of the bindings fail with this particular method.

What did i miss ?

EDIT

It seems like any method that tries to return a List (where T can be any entity )fails with the error An existing connection was forcibly closed by the remote host

EDIT

Client Configuration is as follow

<bindings>
  <netNamedPipeBinding>
    <binding name="netPipeEndPoint" maxBufferPoolSize="524288" maxReceivedMessageSize="6553600" >
      <readerQuotas maxDepth="32" maxStringContentLength="100000" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="Transport" />
    </binding>
  </netNamedPipeBinding>
  <netTcpBinding>
    <binding name="netTcpEndPoint" maxBufferPoolSize="524288" maxReceivedMessageSize="6553600">
      <readerQuotas maxDepth="32" maxStringContentLength="100000" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="Transport" />
    </binding>
  </netTcpBinding>

  <wsHttpBinding>
    <binding name="WSHttpBinding_IArchService" maxBufferPoolSize="524288" maxReceivedMessageSize="6553600">
      <readerQuotas maxDepth="32" maxStringContentLength="100000" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="None" />
    </binding>
  </wsHttpBinding>
</bindings>




<client>
  <endpoint address="http://localhost:8888/ArchService/" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IArchService" contract="ServiceReference.IArchService" name="WSHttpBinding_IArchService">
    <identity>
      <dns value="localhost" />
    </identity>
  </endpoint>
  <endpoint address="net.tcp://localhost:8808/ArchService" binding="netTcpBinding" bindingConfiguration="netTcpEndPoint" contract="ServiceReference.IArchService" name="netTcpEndPoint">
    <identity>
      <dns value="localhost" />
    </identity>
  </endpoint>
  <endpoint address="net.pipe://localhost/ArchService/NetSvc" binding="netNamedPipeBinding" bindingConfiguration="netPipeEndPoint" contract="ServiceReference.IArchService" name="netPipeEndPoint">
    <identity>
      <userPrincipalName value="SYS1\deb" />
    </identity>
  </endpoint>
</client>

EDIT 3

My Other Related Entity Classes are causing the error. I dont know why. Here are they

[Table("SubModuleMst", Schema = "setp")]
[DataContract(IsReference = true)] //prevents Infinite loop
[KnownType(typeof(ModuleMst))]
[KnownType(typeof(List<PageMst>))]

public class SubModule
{
    public SubModule()
    { }

    #region SubModule

    [Key]
    [DataMember]
    public int submoduleid { get; set; }
     [DataMember]
    public int moduleid { get; set; }
    [DataMember]
    [StringLength(100)]
    public string submodulename { get; set; }
    [DataMember]
    public int orderno { get; set; }
    [DataMember]
    [StringLength(1)]
    public string status { get; set; }
    [DataMember]
    public string crby { get; set; }
    [DataMember]
    public DateTime crdt { get; set; }
    [DataMember]
    public string modby { get; set; }
    [DataMember]
    public DateTime moddt { get; set; }
    #endregion

    [DataMember]
    public virtual ModuleMst Module { get; set; }
    [DataMember]
    public virtual List<PageMst> Pages { get; set; }
}

[Table("PageMst", Schema = "setp")]
[DataContract(IsReference = true)] //prevents Infinite loop
[KnownType(typeof(SubModule))]
public class PageMst
{
    public PageMst()
    { }

    #region PageMst

    [Key]
    [DataMember]
    public int pageid { get; set; }
    [DataMember]
    [Required]
    [ForeignKey("SubModule")]
    public int submoduleid { get; set; }
    [DataMember]
    [StringLength(1000)]
    [Required]
    public string pagename { get; set; }
    [DataMember]
    [StringLength(1000)]
    public string pageurl { get; set; }
    [DataMember]
    public int orderno { get; set; }
    [DataMember]
    [StringLength(1)]
    public string menuitm { get; set; }
    [DataMember]
    public int rptparentid { get; set; }
    [DataMember]
    [StringLength(1)]
    public string alertflag { get; set; }
    [DataMember]
    [StringLength(1)]
    public string status { get; set; }
    [DataMember]
    public string crby { get; set; }
    [DataMember]
    public DateTime crdt { get; set; }
    [DataMember]
    public string modby { get; set; }
    [DataMember]
    public DateTime moddt { get; set; }
    [DataMember]
    [StringLength(200)]
    public string paramids { get; set; }
    [DataMember]
    [StringLength(500)]
    public string repurl { get; set; }
    #endregion

    [DataMember]
    public virtual SubModule SubModule { get; set; }
}

EDIT 4

Now I am confirmed that the error is due to The Proxy created by EF are Not Serializable as such According to this MSDN Article https://msdn.microsoft.com/en-us/library/ee705457(v=vs.100).aspx And Also according to this SO Article

Community
  • 1
  • 1
Deb
  • 981
  • 13
  • 39
  • WCF/SOAP doesn't have a problem with lists. I expect it is down to a particular part of the DataContract. I would recommend attaching to the service if possible to see the service-side exception detail. – Glen Thomas Mar 27 '16 at 16:55
  • @Glen Thomas The funny thing is that i can return an object of the same type. The problem happens only with the List of said type !! – Deb Mar 27 '16 at 17:05
  • If you can get the exception detail we can solve this a lot faster – Glen Thomas Mar 27 '16 at 17:06
  • @GlenThomas Presently i am testing with WCFTestClient and posted the exception details. How do i attach to the service in this scenario i dont know. Can you elaborate ? – Deb Mar 27 '16 at 17:09
  • If the service in running in IIS on your local machine you can attach to the application pool process (w3wp.exe). In visual studio, Debug->Attach To Process. Then when the exception is thrown you should see the service side exception. – Glen Thomas Mar 27 '16 at 17:11
  • @GlenThomas I am using SelfHost with Logging. There are no exceptions at server side. The method executes without error on server. – Deb Mar 27 '16 at 17:44
  • When you say "SelfHost", do you mean the service is running in your own application of some sort? Can you attach to that? – Glen Thomas Mar 27 '16 at 20:49
  • @GlenThomas Yes I can. And I did. No exceptions are raised on my ServiceHostApp. I think may be it has something to do with my client config. – Deb Mar 27 '16 at 21:13
  • If you have changed the DataContract and the client doesn't reference the classes directly then you may need to update the service reference.. I don't think there is any problem with your client config as you would see a different error. If you delete the service reference and add it back again everything will be regenerated. – Glen Thomas Mar 27 '16 at 21:21
  • @GlenThomas The Entity class project is shared by both service & client. – Deb Mar 27 '16 at 21:25
  • I have seen the same error when using enums in my data contract. do you have any enums? – Glen Thomas Mar 27 '16 at 21:28
  • @GlenThomas No Enums. I did run some test and found out that my entity class is the culprit. But why and where dont know. I am updating the entity classes in the Edit. Pls have a look. Thanks – Deb Mar 27 '16 at 21:51
  • I'm not sure you are using the KnownType attribute correctly. This is used to state classes that may inherit from the DataContract. – Glen Thomas Mar 27 '16 at 21:59
  • @GlenThomas Should i use T instead of List ? – Deb Mar 27 '16 at 22:02
  • I don't think you should use either unless PageMst inherits from SubModule. But I don't know if you need to specify KnownType for virtual members? – Glen Thomas Mar 27 '16 at 22:04
  • @GlenThomas Removing them did not work either – Deb Mar 27 '16 at 22:09

1 Answers1

1

Since nobody answered my question, I am posting here what i did to make it work in the hope that it will help somebody else like me.

It turns out that the POCO proxy type cannot be directly serialized or deserialized by the Windows Communication Foundation (WCF) as per this MSDN Article.

This is because EF creates a Wrapper around the POCO for Entity Tracking which is not the same class as the POCO class and hence WCF can not serialize it since it can only serialize known Types.

So in order to make entities Serializable through WCF one of the following needs to be done.

  1. Disable Proxy creation in the DBContext Configuration. (See this )
  2. Use .AsNoTracking() (See this SO Post)
  3. Use an Attribute to decorate your service methods that return Entities using ProxyDataContractResolver (See above MSDN article for a Walkthrough)

I used the 3rd approach and my service returns POCO Entities finally. The code in the walkthrough article is self explanatory so not posting here.

And at last i think DTOs are the best way to go as far as EF is considered.

Community
  • 1
  • 1
Deb
  • 981
  • 13
  • 39