how to access EF navigation properties via WCF SOAP service? - wcf

I am struggling with this WCF error for some time now without any luck. Basically I am tying to fetch an Entity Poco with Navigation Properties and connected objects via WCF Services. My EF v6 code successfully get the poco with all the related entities from the DB
Poco debug view
but as i try to access this Entity via WCF service, i see the following error -
An error occurred while receiving the HTTP response to http://localhost:8734/Design_Time_Addresses/BusinessLogicServicesLayer/userServices/. 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.HttpChannelFactory1.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 IuserServicesQuery.getCompleteUserSnapshot(String emailAddress)
at IuserServicesQueryClient.getCompleteUserSnapshot(String emailAddress)
Inner Exception:
The underlying connection was closed: An unexpected error occurred on a receive.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory1.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)
my AppConfig file looks like this -
<endpoint address="" behaviorConfiguration="MyBehavior" binding="basicHttpBinding"
bindingConfiguration="IncreasedTimeout" name="BasicHttpEndpoint"
contract="BusinessLogicServicesLayer.IuserServicesQuery" listenUriMode="Explicit">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
&&
<bindings>
<basicHttpBinding>
<binding name="IncreasedTimeout"
openTimeout="12:00:00"
receiveTimeout="12:00:00" closeTimeout="12:00:00"
sendTimeout="12:00:00">
</binding>
</basicHttpBinding>
</bindings>
.
.
<behaviors>
<endpointBehaviors>
<behavior name="MyBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483646" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
can someone please help out or point me to a correct direction

This is because when data is returned, serialization fails, causing the WCF service to stop automatically.
Solution:
We can serialize the proxy class into the entities we need before returning the data.
Here is a demo,The student class contains the navigation properties of other entities:
public Student Getstu()
{
CodeFirstDBContext codeFirstDBContext = new CodeFirstDBContext();
Student student =codeFirstDBContext.Student.Find(1);
var serializer = new DataContractSerializer(typeof(Student), new DataContractSerializerSettings()
{
DataContractResolver = new ProxyDataContractResolver()
});
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, student);
stream.Seek(0, SeekOrigin.Begin);
var stu = (Student)serializer.ReadObject(stream);
return stu;
}
}
This is the method that the client will call.
ServiceReference1.ServiceClient serviceClient = new ServiceReference1.ServiceClient();
var stu = serviceClient.Getstu();
Client-side will call successfully.
UPDATE Disabling Loading loading also solves this problem:
public class CodeFirstDBContext : DbContext
{
public CodeFirstDBContext() : base("name=DBConn")
{
this.Configuration.ProxyCreationEnabled = false;
this.Configuration.LazyLoadingEnabled = false;
Database.SetInitializer(new CreateDatabaseIfNotExists<CodeFirstDBContext>());
}
}

Related

Consuming a web service with WCF with just a public key

I'm consuming a third-party's web service with WCF. I've got a PFX certificate file that I'm attaching via the ClientCredentials.ClientCertificate.SetCertificate method. I'm using the "Message Security Version" WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10.
Everything works fine. Now the third-party's certificate is expiring so they've issued a new one. However, this time it's a P7B file with just the public key.
When I try to use this certificate, I get a NotSupportedException with the message "The private key is not present in the X.509 certificate."
No part of my code is supplying the private key password, so I'm assuming this means that the private key is not being used. If this is the case, how can I consume this web service using only the public key? Or have I misunderstood something? (very likely)
EDIT
Ok, here's some code. The service client class I'm using was generated by svcutil and has been modified via a partial class to implement IDisposable. These are the relevant fragments:
private ServiceResponse CallService(ServiceParameters serviceParameters)
{
...
using (var client = new ThirdPartyServiceClient())
{
SetClientCredentials(client);
client.RemoteCall(serviceParameters);
}
...
}
private void SetClientCredentials(ThirdPartyServiceClient client)
{
if (client.ClientCredentials == null)
{
throw new InvalidOperationException("ClientCredentials was null and certificate could not be set");
}
client.ClientCredentials.ClientCertificate.SetCertificate(
StoreLocation.LocalMachine,
StoreName.My,
X509FindType.FindBySubjectName,
_configuration.CertificateSubject);
}
And this is my WCF config:
<system.serviceModel>
<bindings>
<customBinding>
<binding name="ThirdPartyServiceBinding">
<security includeTimestamp="true" enableUnsecuredResponse="true" authenticationMode="CertificateOverTransport" messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" />
<textMessageEncoding messageVersion="Soap11WSAddressing10" />
<httpsTransport requireClientCertificate="true" />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="https://third-party.com/service" binding="customBinding" bindingConfiguration="ThirdPartyServiceBinding" contract="Namespace.To.ProxyClasses" name="ThirdPartyService" />
</client>
</system.serviceModel>
The exception is thrown by the client.RemoteCall(serviceParameters); call, and the stack trace is
Server stack trace:
at System.IdentityModel.Tokens.X509AsymmetricSecurityKey.GetSignatureFormatter(String algorithm)
at System.IdentityModel.SignedXml.ComputeSignature(SecurityKey signingKey)
at System.ServiceModel.Security.WSSecurityOneDotZeroSendSecurityHeader.CompletePrimarySignatureCore(SendSecurityHeaderElement[] signatureConfirmations, SecurityToken[] signedEndorsingTokens, SecurityToken[] signedTokens, SendSecurityHeaderElement[] basicTokens, Boolean isPrimarySignature)
at System.ServiceModel.Security.WSSecurityOneDotZeroSendSecurityHeader.CreateSupportingSignature(SecurityToken token, SecurityKeyIdentifier identifier)
at System.ServiceModel.Security.SendSecurityHeader.SignWithSupportingToken(SecurityToken token, SecurityKeyIdentifierClause identifierClause)
at System.ServiceModel.Security.SendSecurityHeader.SignWithSupportingTokens()
at System.ServiceModel.Security.SendSecurityHeader.CompleteSecurityApplication()
at System.ServiceModel.Security.SecurityAppliedMessage.OnWriteMessage(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.BufferedMessageWriter.WriteMessage(Message message, BufferManager bufferManager, Int32 initialOffset, Int32 maxSizeQuota)
at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
at System.ServiceModel.Channels.HttpOutput.SerializeBufferedMessage(Message message, Boolean shouldRecycleBuffer)
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.Channels.SecurityChannelFactory`1.SecurityRequestChannel.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 Namespace.To.ProxyClasses.ThirdPartyService.RemoteCall(ServiceParameters request)
[back up the normal call hierarchy of my code]
With message security, you sign a document with your private key, and you encrypt a document with the other parties public key. They can decrypt it with their private key, and they can verify your signature with your public key. It sounds like they replaced their key so they provided you their new public key. If their public key doesn't have a publicly verifiable chain of trust, then you need to install their public key in your local certificate store as a trusted key. If you don't do this and they aren't publicly verifiable, you will get an exception about being unable to verify the chain trust. If it is your key which is expiring, then they need a public key to identify you, and you need the private half which they shouldn't have.

Working with Named Pipes in WCF, PipeException thrown?

Despite many searches and read articles such as this: Exploring the WCF Named Pipe Binding - Part 1(part 2 and 3 inclusively), I haven't been able to make my service work properly.
Here's my config:
<system.serviceModel>
<client>
<endpoint address="net.pipe://localhost/GlobalPositioningService"
binding="netNamedPipeBinding"
contract="GI.Services.GlobalPositioning.Contracts.IGlobalPositioning" />
</client>
<services>
<service name="GI.Services.GlobalPositioning.Services.GlobalPositioningService">
<endpoint address=""
binding="wsHttpBinding"
contract="GI.Services.GlobalPositioning.Contracts.IGlobalPositioning">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="net.pipe://localhost/GlobalPositioningService"
binding="netNamedPipeBinding"
contract="GI.Services.GlobalPositioning.Contracts.IGlobalPositioning" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/GlobalPositioningService/"/>
</baseAddresses>
</host>
</service>
</services>
Then, I try to test my service through Named Pipes:
[TestFixture]
public class GlobalPositioningServiceTests {
[TestFixtureSetUp]
public void SetUpHost() {
var channelFactory = new ChannelFactory<IGlobalPositioning>(binding, new EndpointAddress(address));
channelFactory.Open();
service = channelFactory.CreateChannel();
}
private const string address = "net.pipe://localhost/GlobalPositioningService";
private static readonly Binding binding = new NetNamedPipeBinding();
private static IGlobalPositioning service;
}
And I have also tried another way using a ServiceHost instance:
[TestFixtureSetUp]
public void SetUpHost() {
host = new ServiceHost(typeof(GlobalPositioningService));
host.AddServiceEndpoint(typeof(IGlobalPositioning), binding, address);
host.Open();
service = new GlobalPositioningService();
}
And I always obtain this error with stack trace:
Error 2 Test 'GI.Services.GlobalPositioning.Services.Tests.GlobalPositioningServiceTests.GetGlobalPositionWorksWithDiacriticsInMunicipalityName("143, rue Marcotte, Sainte-Anne-de-la-P\x00E9rade",46.5736528d,-72.2021346d)' failed:
System.ServiceModel.EndpointNotFoundException : There was no endpoint listening at net.pipe://localhost/GlobalPositioningService that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
----> System.IO.PipeException : The pipe endpoint 'net.pipe://localhost/GlobalPositioningService' could not be found on your local machine.
Server stack trace:
at System.ServiceModel.Channels.PipeConnectionInitiator.GetPipeName(Uri uri)
at System.ServiceModel.Channels.NamedPipeConnectionPoolRegistry.NamedPipeConnectionPool.GetPoolKey(EndpointAddress address, Uri via)
at System.ServiceModel.Channels.CommunicationPool`2.TakeConnection(EndpointAddress address, Uri via, TimeSpan timeout, TKey& key)
at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(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 GI.Services.GlobalPositioning.Contracts.IGlobalPositioning.GetGlobalPosition(String mailingAddress)
at GI.Services.GlobalPositioning.Services.Tests.GlobalPositioningServiceTests.GetGlobalPositionWorksWithDiacriticsInMunicipalityName(String address, Double latitude, Double longitude) in C:\Open\Projects\Framework\Src\GI.Services\GI.Services.GlobalPositioning.Services.Tests\GlobalPositioningServiceTests.cs:line 27
--PipeException C:\Open\Projects\Framework\Src\GI.Services\GI.Services.GlobalPositioning.Services.Tests\GlobalPositioningServiceTests.cs 27
For your information, I'm using:
Visual Studio 2010
Windows 7
NUnit
And my service is contained within a WCF Service Library.
It seems that you are attempting to do integration testing with a running instance of your service using the netNamedPipesBinding. To do this, you need to have both a service host providing an instance of your service and a service proxy instance to use for making calls to the service. You could try combining both the code in both of your sample TestFixtureSetup methods so that you are instantiating both the service host and the service proxy (the result of the CreateChannel method). For an example of how to do this, look at this blog post.

Basic HTTP Authentication over HTTPS with WCF

I’m calling a web service via WCF (w/ .NET 4.0) that requires basic HTTP authentication (with username and password.) over HTTPS. While, I think I’ve got everything setup correctly, I’m getting a 401 error whenever I make the call to the service. I monitored the HTTP traffic and noticed that WCF seems to be ignoring that I told it to use an authorization header with the username and password, as none is sent in the request. Here’s my configuration below. Any ideas? Thanks!
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicAuthSecured">
<security mode="Transport">
<transport clientCredentialType="Basic" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://REMOVED FOR CONFIDENTIALITY"
binding="basicHttpBinding" bindingConfiguration="BasicAuthSecured"
contract="Five9.WsAdmin" name="WsAdminPort" />
</client>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
And here’s my code:
var five_9_client = new WsAdminClient();
five_9_client.ClientCredentials.UserName.UserName = “REMOVED FOR CONFIDENTIALITY";
five_9_client.ClientCredentials.UserName.Password = "REMOVED FOR CONFIDENTIALITY";
var call_log_response = five_9_client.getCallLogReport(call_log); //Bombing out here
I’m getting this exception:
{"The HTTP request is unauthorized with client authentication scheme 'Basic'. The authentication header received from the server was ''."}
With inner exception:
{"The remote server returned an error: (401) Unauthorized."}
With stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest request, HttpWebResponse response, WebException responseException, HttpChannelFactory factory)
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException, ChannelBinding channelBinding)
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)
Found the solution: basically, the problem was that the header had to be attached to the current request, like so:
var base_64_encoded_credentials =
BasicHTTPAuthenticationEncoder.base_64_encode_credentials(
client.ClientCredentials.UserName.UserName, client.ClientCredentials.UserName.Password);
HttpRequestMessageProperty request = new HttpRequestMessageProperty();
request.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " + base_64_encoded_credentials;
OperationContextScope clientScope = new OperationContextScope(five_9_client.InnerChannel);
OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, request);
It may be that the problem is that you have not set the client credential type, see http://msdn.microsoft.com/en-us/library/ms731925.aspx
Either it is not being sent at all, or the default client credential type does not send the credentials in the header.

wcf linq to sql error

I am getting an error returning a linq query over http to an ASP.Net application
I have the following wcf service running in IIS
public class ProductService : IProductService
{
NorthwindEntities context = new NorthwindEntities();
public List<Customer> GetCustomers()
{
return context.Customers.Select(c => c).ToList();
}
}
Web Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
</system.web>
<system.serviceModel>
<services>
<service name="WCF_Entity.ProductService">
<endpoint address="" binding="wsHttpBinding" contract="WCF_Entity.IProductService" />
</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="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<connectionStrings>
<add name="NorthwindEntities" connectionString="metadata=res://*/Northwind.csdl|res://*/Northwind.ssdl|res://*/Northwind.msl;provider=System.Data.SqlClient;provider connection string="Data Source=SHLOMOKATZ-PC;Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
I created a ASP.Net application to use the service
myService.ProductServiceClient objService = new ProductServiceClient();
var customers = objService.GetCustomers();
on debuging, I get the following error
An existing connection was forcibly closed by the remote host
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
Source Error:
Line 2454:
Line 2455: public ASPWFC.myService.Customer[] GetCustomers() {
Line 2456: return base.Channel.GetCustomers();
Line 2457: }
Line 2458: }
Source File: D:\My Documents\Visual Studio 2010\Projects\wcf\WCF_Entity\ASPWFC\Service References\myService\Reference.cs Line: 2456
Stack Trace:
[SocketException (0x2746): An existing connection was forcibly closed by the remote host]
System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) +6132200
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +134
[IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.]
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +300
System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) +26
System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead) +265
[WebException: The underlying connection was closed: An unexpected error occurred on a receive.]
System.Net.HttpWebRequest.GetResponse() +6038435
System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +103
[CommunicationException: An error occurred while receiving the HTTP response to http://localhost/WCF_Entity_SVC/ProductService.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.]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +9464367
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +345
ASPWFC.myService.IProductService.GetCustomers() +0
ASPWFC.myService.ProductServiceClient.GetCustomers() in D:\My Documents\Visual Studio 2010\Projects\wcf\WCF_Entity\ASPWFC\Service References\myService\Reference.cs:2456
ASPWFC._Default.Page_Load(Object sender, EventArgs e) in D:\My Documents\Visual Studio 2010\Projects\wcf\WCF_Entity\ASPWFC\Default.aspx.cs:36
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +37
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +95
System.Web.UI.Control.OnLoad(EventArgs e) +145
System.Web.UI.Control.LoadRecursive() +134
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3412
changing the buffer length, etc... Didn't solve the issue. The database is the sample NorthWind database
I am able to browse to the service
It seems that Aliostad is correct as I recreated the service without using IIs and used ASP to consume the service, and get the below error. So it is a problem invoking the svc from the app, I can still run the service directly via http
The underlying connection was closed: The connection was closed unexpectedly.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly.
Source Error:
Line 2337:
Line 2338: public NorthwindApp.myService.Customer[] getCustomers() {
Line 2339: return base.Channel.getCustomers();
Line 2340: }
Line 2341: }
Source File: d:\my documents\visual studio 2010\Projects\wcf\NorthwindServices\NorthwindApp\Service References\myService\Reference.cs Line: 2339
Stack Trace:
[WebException: The underlying connection was closed: The connection was closed unexpectedly.]
System.Net.HttpWebRequest.GetResponse() +6038435
System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +51
[CommunicationException: The underlying connection was closed: The connection was closed unexpectedly.]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +9464367
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +345
NorthwindApp.myService.INorthwindService.getCustomers() +0
NorthwindApp.myService.NorthwindServiceClient.getCustomers() in d:\my documents\visual studio 2010\Projects\wcf\NorthwindServices\NorthwindApp\Service References\myService\Reference.cs:2339
NorthwindApp._Default.Page_Load(Object sender, EventArgs e) in d:\my documents\visual studio 2010\Projects\wcf\NorthwindServices\NorthwindApp\Default.aspx.cs:18
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +46
System.Web.UI.Control.OnLoad(EventArgs e) +83
System.Web.UI.Control.LoadRecursive() +120
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3954
I found an article that says that with entity framework 4 there is a problem to serialize entities in wcf with lazy loading enabled
I added the following code to the service and everything works
context.ContextOptions.LazyLoadingEnabled = false;
link to article http://geekswithblogs.net/danemorgridge/archive/2010/05/04/entity-framework-4-wcf-amp-lazy-loading-tip.aspx
How many records are being returned? There are a couple of things in play here:
From a WCF Perspective:
MaxBufferSize: Gets or sets the maximum size of the buffer to use. For buffered messages this value is the same as MaxReceivedMessageSize. For streamed messages, this value is the maximum size of the SOAP headers, which must be read in buffered mode. For a non-streamed message, if the message size is greater than this property, then the message is dropped.
If not specified, this defaults to 65536.
This is only 0.0625 megabytes!
MaxReceivedMessageSize: Gets and sets the maximum allowable message size that can be received.
Default here is also 65536 bytes.
MaxStringContentLength: Gets and sets the maximum string length returned by the reader.
Your service is probably returning a value greater in size than the defaults.
So, you could try modifying your service behavior to include these attributes with higher limits, say 6 MB or so to see if it resolves your issue.
Also - remember there is maxRequestLength limit which is enforced by IIS which trumps any WCF setting, the default is 4096 KB, so you may have to tweak that if you alter the above properties.

System.ServiceModel.CommunicationException - On Large Message Size

I'm getting this exception on the client application, not sure how to get past this.
I encounter this exception when the data returned(A list of prices) exceeds 15MB, but works for message size less that 15MB.
Error Message:
An error occurred while receiving the HTTP response to "http://localhost:8782/CMDService". 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.
Trace O/P for client from TraceViewer:
<ApplicationData>
<TraceData>
<DataItem>
<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error">
<TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.ThrowingException.aspx</TraceIdentifier>
<Description>Throwing an exception.</Description>
<AppDomain>CMD.Web.Test.exe</AppDomain>
<Exception>
<ExceptionType>System.ServiceModel.CommunicationException, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>An error occurred while receiving the HTTP response to "http://localhost:8782/CMDService". 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.</Message>
<StackTrace>
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)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at CMD.Client.Interface.ICMDService.GetData(String region, DateTime QuoteDate)
at CMD.Web.Test.Program.TestGetData()
at CMD.Web.Test.Program.Main(String[] args)
</StackTrace>
<ExceptionString>System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to "http://localhost:8782/CMDService". 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
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.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---</ExceptionString>
<InnerException>
<ExceptionType>System.Net.WebException, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The underlying connection was closed: An unexpected error occurred on a receive.</Message>
<StackTrace>
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
</StackTrace>
<ExceptionString>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
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.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)</ExceptionString>
<InnerException>
<ExceptionType>System.IO.IOException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.</Message>
<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)
</StackTrace>
<ExceptionString>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)</ExceptionString>
<InnerException>
<ExceptionType>System.Net.Sockets.SocketException, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>An existing connection was forcibly closed by the remote host</Message>
<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)
</StackTrace>
<ExceptionString>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)</ExceptionString>
<NativeErrorCode>2746</NativeErrorCode>
</InnerException>
</InnerException>
</InnerException>
</Exception>
</TraceRecord>
</DataItem>
</TraceData>
</ApplicationData>
Tracing on the service did not report any exceptions
Config on both service and client are identical
<basicHttpBinding>
<binding name="CMDServiceBinding"
receiveTimeout="00:10:00"
closeTimeout="00:10:00"
openTimeout="00:10:00"
sendTimeout="00:10:00"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
</binding>
</basicHttpBinding>
<behaviors>
<serviceBehaviors>
<behavior name="UBS.Firc.Broil.CMD.QuotesServiceBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</serviceBehaviors>
</behaviors>
Any help would be much appreciated. Thanks
Briefly in behaviors you have serviceBehavior and endpointBehavior. You should write something like this:
<behaviors>
<endpointBehaviors>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="10000000"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
Hoping that helps !
Hope It may help you...
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IVtmWebResolution" maxBufferSize="2147483647" receiveTimeout="00:10:00" sendTimeout="00:10:00"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
Happy Coding
If your service was hosted by ASP.NET, you might have to increase ASP.NET's max upload size:
<system.web>
<httpRuntime maxRequestLength="2147483647" />
</system.web>