WCF This could be due to the service endpoint binding not using the HTTP protocol - wcf

Default.aspx.cs
WCFService.Service1Client client = new WCFService.Service1Client();
string stream = client.JsonSerializeFromDatabase();
client.Close();
WCFService.Service1Client client2 = new WCFService.Service1Client();
foreach (WCFService.Person in client2.JsonDeserializeFromDatabase(stream))
Service1.svc.cs
public IList<Person> JsonDeserializeFromDatabase(string value)
{
MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(value));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Person>));
IList<Person> tableData = (IList<Person>)ser.ReadObject(ms);
ms.Close();
ms.Dispose();
return tableData;
}
IService1.cs
[OperationContract]
IList<Person> JsonDeserializeFromDatabase(string value);
Server Web.config
<httpRuntime maxRequestLength="8192"/>
</system.web>
...
<system.serviceModel>
<services>
<service name="TestWCF.Service1" behaviorConfiguration="TestWCF.Service1Behavior">
<endpoint address="" binding="wsHttpBinding" contract="TestWCF.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="TestWCF.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>
</behavior>
</serviceBehaviors>
Client Web.config
<httpRuntime maxRequestLength="8192"/>
</system.web>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="debuggingBehaviour">
<dataContractSerializer maxItemsInObjectGraph="2147483646" />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IService1" closeTimeout="00:50:00" openTimeout="00:50:00" receiveTimeout="00:50:00" sendTimeout="00:50:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="64" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
<reliableSession ordered="true" inactivityTimeout="00:50:00" enabled="false"/>
<security mode="Message">
<message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="~~~~~/Service1.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1" contract="WCFService.IService1" name="WSHttpBinding_IService1" behaviorConfiguration="debuggingBehaviour">
Exception Information
- Type: System.ServiceModel.CommunicationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- Message: An error occurred while receiving the HTTP response to ~~~~~/Service1.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.
I got this exception information from Server trace viewer, so please do not advise me to put <-system.diagnostics-> tag.
As you can see, I increased all the size thing.
Like.. i don't know why I am getting an error when I call JsonDeserializeFromDatabase(stream).
"An error occurred while receiving the HTTP response to ~~~~~/Service1.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."

I too have experienced this error message when returning records from a database in a WCF service. As well as increasing maxReceivedMessageSize in the binding in the client configuration (App.config), a separate problem seems to be that WCF has problems serializing Entity Framework objects if they have relationships that lead to circularity in their object graphs.
I solved this by returning buddy class objects (which are copies of the raw database records, but without any relationship links) rather than the raw database classes themselves.
Hope this helps -
And WHY doesn't Microsoft produce better error messages?? Here, as in many other cases, the error message gives no clue to the real problem (the serialization of the return value from the WCF call)!

re: WCF & problems serializing Entity Framework objects if they have relationships that lead to circularity in their object graphs. I was getting the same error and the answer provided by user1956642 and it did point me in the right direction, but later realized I could serialize these entities by configuring the DbContext
context.Configuration.ProxyCreationEnabled = false;
Lazy loading is still enabled, but I believe the dynamic proxies are used for change tracking and lazy loading. So yea ... just my 5c

Related

Disable CustomUserNamePasswordValidator for specific operation

I am using a CustomUserNamePasswordValidator for my WCF web service. However, i am trying to add a IsAlive operation, which should be able to be called from clients, even when not authenticated.
For example, i want to be able to do a check, if a service is online and accessible on startup, so i can notify the user on missing inet connection or a not available service (due to maintenance).
I have code for all this already in place. What i am missing is how i can access the operation without passing a username and password.
I could probably just add a second service which allows anon access, but i'd really prefer to use the existing service.
The Validator is implemented like this (i ommited the actual checking code):
public sealed class MyCredentialValidator : UserNamePasswordValidator
{
public MyCredentialValidator ()
{
}
public override void Validate(string userName, string password)
{
Debug.WriteLine("MyCredentialValidator : Validate called.");
// do some checks
var isValid = CheckCredentials(userName, password)
if(!isValid)
{
throw new FaultException(...);
}
}
}
It is registered in the web.config like so:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="SecureBehavior">
<serviceMetadata httpsGetEnabled="false"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyCredentialValidator,..."/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
<bindings>
<wsHttpBinding>
<binding name="SecureBinding" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" maxReceivedMessageSize="2147483647">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName"/>
</security>
<readerQuotas maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxStringContentLength="2147483647"/>
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="my service" behaviorConfiguration="SecureBehavior">
<endpoint address="" binding="wsHttpBinding" contract="my contract" bindingConfiguration="SecureBinding">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
client side configuration:
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="SecureBinding"
closeTimeout="00:10:00"
openTimeout="00:10:00"
receiveTimeout="00:10:00"
sendTimeout="00:10:00"
maxReceivedMessageSize="2147483647">
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName"/>
</security>
<readerQuotas maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxStringContentLength="2147483647"/>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="https://my service url"
contract="my contract"
binding="wsHttpBinding"
bindingConfiguration="SecureBinding"
name="secure" />
</client>
</system.serviceModel>
client side wcf call code:
var cf = new ChannelFactory<my contract>("secure");
using (IClientChannel channel = (IClientChannel)cf.CreateChannel())
{
channel.OperationTimeout = TimeSpan.FromSeconds(3);
bool success = false;
try
{
channel.Open();
result = ((my contract)channel).IsAlive();
channel.Close();
success = true;
}
finally
{
if (!success)
{
channel.Abort();
}
}
}
I have done something like this before,
depending on how you have integrated your custom validator in the wcf pipleline,
you could simply before you do the actual validation, which I guess returns something like true or false, you could check the incoming url or address and see if it is going to be going to your IsAlive operation, if that is the case, you could simply do a early return true.
Wcf has a few ways with which you can check what operation the client has called.
to be more accurate, I would need to know how you wrote your custom validator and where in the pipeline it integrates.

WCF ERROR: The server did not provide a meaningful reply;

please somebody can help me to find out what is happened. I have my WCF service which worked fine, and now suddenly I have this error:
The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal
server error
I must tell that it still works when I select some thousands of records, but when the data is huge I receive this error, although before it worked fine!
private static string ConnString = "Server=127.0.0.1; Port=5432; Database=DBname; User Id=UName; Password=MyPassword;"
DataTable myDT = new DataTable();
NpgsqlConnection myAccessConn = new NpgsqlConnection(ConnString);
myAccessConn.Open();
string query = "SELECT * FROM Twitter";
NpgsqlDataAdapter myDataAdapter = new NpgsqlDataAdapter(query, myAccessConn);
myDataAdapter.Fill(myDT);
foreach (DataRow dr in myDT.Rows)
{
**WHEN I HAVE TOO MANY RECORDS IT STOPS HERE**
...
web.config
<configuration>
<system.web>
<compilation debug="false" targetFramework="4.0" />
<httpRuntime maxRequestLength="2147483647" executionTimeout="100000" />
</system.web>
<system.diagnostics>
<trace autoflush="true" />
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="Traces4.svclog"/>
</listeners>
</source>
</sources>
</system.diagnostics>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IDBService" closeTimeout="00:30:00"
openTimeout="00:30:00" receiveTimeout="00:30:00" sendTimeout="00:30:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" transferMode="Streamed"
useDefaultWebProxy="true">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IDBService" contract="DBServiceReference.IDBService"
name="BasicHttpBinding_IDBService" />
</client>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483646" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>
client config (Edited)
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IRouteService" maxBufferSize="2147483647"
maxReceivedMessageSize="2147483647">
<security mode="None" />
</binding>
<binding name="BasicHttpBinding_IDBService" closeTimeout="00:30:00"
openTimeout="00:30:00" receiveTimeout="00:30:00" sendTimeout="00:30:00"
maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"
transferMode="Buffered" >
<security mode="None" />
</binding>
</basicHttpBinding>
<customBinding>
<binding name="CustomBinding_IRouteService">
<binaryMessageEncoding />
<httpTransport maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647" />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="http://dev.virtualearth.net/webservices/v1/routeservice/routeservice.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IRouteService"
contract="BingRoutingService.IRouteService" name="BasicHttpBinding_IRouteService" />
<endpoint address="http://dev.virtualearth.net/webservices/v1/routeservice/routeservice.svc/binaryHttp"
binding="customBinding" bindingConfiguration="CustomBinding_IRouteService"
contract="BingRoutingService.IRouteService" name="CustomBinding_IRouteService" />
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IDBService"
contract="DBServiceReference.IDBService" name="BasicHttpBinding_IDBService" />
</client>
</system.serviceModel>
</configuration>
In my file scvlog I don' t get any exception!
I don't have any other idea what else I can do for understand where is the problem. Please somebody help me!!!
A different answer, just in case anyone arrives here as I did looking for a general answer to the question.
It seems that the DataContractSerializer that does the donkey-work is incredibly finicky, but doesn't always pass the real error to the client. The server process dies straight after the failure - hence no error can be found. In my case the problem was an enum that was used as flags, but not decorated with the [Flags] attribute (picky or what!).
To solve it I created an instance of the serializer and inspected the error in the debugger; here's a code snippet since I have it to hand.
EDIT: In response to request in comments ...
Amended the code snippet to show the helper method I now use. Much the same as before, but in a handy generic wrapper.
public static T CheckCanSerialize<T>(this T returnValue) {
var lDCS = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
Byte[] lBytes;
using (var lMem1 = new IO.MemoryStream()) {
lDCS.WriteObject(lMem1, returnValue);
lBytes = lMem1.ToArray();
}
T lResult;
using (var lMem2 = new IO.MemoryStream(lBytes)) {
lResult = (T)lDCS.ReadObject(lMem2);
}
return lResult;
}
And to use this, instead of returning an object, return the object after calling the helper method, so
public MyDodgyObject MyService() {
... do lots of work ...
return myResult;
}
becomes
public MyDodgyObject MyService() {
... do lots of work ...
return CheckCanSerialize(myResult);
}
Any errors in serialization are then thrown before the service stops paying attention, and so can be analysed in the debugger.
Note; I wouldn't recommend leaving the call in production code, it has the overhead of serializing and deserializing the object, without any real benefit once the code is debugged.
Hope this helps someone - I've wasted about 3 hours trying to track it down.
I don't know if it's really can be an answer, but I have tried to change in web.config from <security mode="None" /> to <security mode="Transport" /> and It worked!!!
I'd want to pay attention that this part should be changed only in web.config and in client configuration remains <security mode="None" />, because with Transport in both It doesn't work!
So after that, I decided to try to come back again to None security and It worked for some minutes and then stopped again, and it came back the error:
The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error
So It seems that the solution in my case is to set in web.config
security mode to Transport
In my case, I was working on a windows app project communicating with a WCF Web Service.
The web service, using netTcpBinding was returning a Stream object (a picture).
As the windows app doesn't have configuration file, default values are used for bindings. And simply extending the MaxReceivedMessageSize on the client side backend code solved my problem.
var API = new StreamService.StreamServiceClient(
new System.ServiceModel.NetTcpBinding(System.ServiceModel.SecurityMode.None)
{
MaxReceivedMessageSize = 2147483647
},
new System.ServiceModel.EndpointAddress("net.tcp://machine/app/service.svc")
);
Sometimes this problem is caused by an oversized message that was cut due to default values in the binding.
You should add maxReceivedMessageSize, maxBufferPoolSize and maxBufferSize with some large enough values to the binding in your app.config file - that should do the trick :)
Example:
<bindings>
<netTcpBinding>
<binding
name="ExampleBinding" closeTimeout="00:01:00"
maxReceivedMessageSize="73400320"
maxBufferPoolSize="70000000"
maxBufferSize="70000000"/>
</netTcpBinding>
</bindings>
Good Luck!
In my case I was working on an MVC application and I have changed
maxReceivedMessageSize ="10000000"
to
maxReceivedMessageSize ="70000000"
and it worked! It's because the response from the web server exceeds maxReceivedMessageSize ="10000000",
so I have increased maxReceivedMessageSize to maxReceivedMessageSize ="70000000".
In my experience of this error, just check the service's host computer's event log to see what is the actual root exception.
For me it was a lazy-loading list of items retrieved from the DB.
The WCF receiver would try to iterate them, which would try to go to the DB, which obviously could not work.
In BizTalk we use to get this issue.
Mostly the issue will happen due to size of the message from the service. So we need to increase the size of the receiving message from 65,356 to 2,365,60. It worked for me.
enter image description here
ASP.NET applications can execute with the Windows identity (user account) of the user making the request. Impersonation is commonly used in applications that rely on Microsoft Internet Information Services (IIS) to authenticate the user. ASP.NET impersonation is disabled by default.
Enable this, your API will start working - it is in IIS authentication
In my case, after upgrading from .NET Framework 4.5 to .NET Framework 4.8, I had to remove read-only modifiers of properties that were decorated with DataMemberAttribute.

WCF Silverlight enabled service "Not Found" error

I'm struggling with the following scenario (here is the big picture):
I have a WCF Silverlight-enabled service (based on the DomainService class) into my Web project. The service is designed to be called by the Silverlight 5 clients and also by non-Silverlight consumers.
The service displays the WSDL info at the address
"http://localhost/mywebapproot/Services/MailService.svc" and therefore it can
be discovered and implemented by any client within the Web
project (which is fine).
Here are the symptoms:
The service can't be called by any
Silverlight client (here is the problem!) The error returned is "The remote server returned an exception: Not Found". If I change the name of the
service in Web.Config (let's say I change
MyCompany.Web.Services.MailService into MailService), the service can
now be called by any Silverlight client but at that time the service
is no longer discoverable.
I put includeExceptionDetailInFaults at True and tried to inspect the service with Fiddler/HTTPDebuggerPro but they didn't give me any detailed information about the exception. It looks to me that the Silverlight clients, in this configuration and for some reason, aren't able to create the .SVC file on the fly.
Here is the implementation:
MailService.svc implementation
<%# ServiceHost Language="C#" Debug="true" Service="MyCompany.Web.Services.MailService" CodeBehind="MailService.svc.cs" %>
MailService.svc.cs implementation
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public sealed partial class MailService : DomainService, IMailService
{
}
IMailService interface
[ServiceContract(ConfigurationName = "MyCompany.Web.Services.IMailService")]
public interface IMailService
{
//Some public methods flagged as [OperationContract] go here
}
Web.Config implementation
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="Secure_Behavior_Configuration">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="Public_MailService_BasicHttpBinding" transferMode="Streamed"
maxBufferSize="2147483647"
maxReceivedMessageSize="2147483647"
maxBufferPoolSize="2147483647">
<readerQuotas maxArrayLength="21400000" maxStringContentLength="21400000" maxBytesPerRead="21400000"/>
<security mode="None"/>
</binding>
</basicHttpBinding>
<services>
<service name="MyCompany.Web.Services.MailService" behaviorConfiguration="Secure_Behavior_Configuration">
<endpoint
address=""
binding="basicHttpBinding"
bindingConfiguration="Public_MailService_BasicHttpBinding"
contract="MyCompany.Web.Services.IMailService" />
<endpoint
address=""
binding="basicHttpBinding"
bindingConfiguration="Secure_MailService_BasicHttpBinding"
contract="MyCompany.Web.Services.IMailService" />
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
Thanks a lot for any help!
Chris.

Hosted WCF Service Hangs after the weekend

We have a WCF service hosted in a windows service which hangs after long periods of inactivity: ie after the weekend.
This behavior happens at different locations.
The service uses WSHttpBinding which is set to use transport security a Custom serviceAuthorization authorizationPolicy which uses windows authentication.
The Spring framework is used. Spring.ServiceModel.Activation.ServiceHostFactory creates the Service hosts.
Service throttle is set to 200 sessions, instances and calls. There are at most 15 users of the system.
Tracing is enabled and set to Warning which should let me know about throttle issues.
There are no messages in the service trace log.
There are no messages in the Event log which look relevant.
There are no relevant logs in HTTPPerf logs.
We log considerably in the server side application but there is no activity being recorded when the system hangs.
It is a total black box when the system hangs.
The client fails with the following message.
08:13:32.014 [1] ERROR App - System.TimeoutException: Client is unable to finish the security negotiation within the configured timeout (00:00:59.9941374). The current negotiation leg is 1 (00:00:59.9863206). ---> System.TimeoutException: The request channel timed out while waiting for a reply after 00:00:59.9628702. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout. ---> System.TimeoutException: The HTTP request to 'http://localhost:8080/OrderManagementService.svc' has exceeded the allotted timeout of 00:00:59.9690000. The time allotted to this operation may have been a portion of a longer timeout. ---> System.Net.WebException: The operation has timed out
at System.Net.HttpWebRequest.GetResponse()
I have spent many hours searching for relevant information on this.
I do not think this is related to inactivity timeout as this should be recorded in the trace log.
Only thing that I can think of is related to Active Directory credential caching or something of that nature or that it is related to the use of the Spring framework.
Any help would be greatly, greatly appreciated.
Am thinking of moving away from WSHttpBinding or WCF altogether as this is an unacceptable situation.
Service side configuration is as follows.
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646">
<readerQuotas maxDepth="2147483646" maxStringContentLength="2147483646" maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
<reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
<security>
<transport></transport>
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceAuthorization principalPermissionMode="Custom">
<authorizationPolicies>
<add policyType="Kodi.Kodiak.Security.AuthorizationPolicy, Kodi.Kodiak.Security" />
</authorizationPolicies>
</serviceAuthorization>
<serviceCredentials>
<windowsAuthentication includeWindowsGroups="true" allowAnonymousLogons="false" />
</serviceCredentials>
<serviceThrottling maxConcurrentCalls="200" maxConcurrentSessions="200" maxConcurrentInstances="200" />
<dataContractSerializer maxItemsInObjectGraph="2147483646" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="rest">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="OrderManagementService">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding" contract="Kodi.Kodiak.Services.ServiceContracts.IOrderManagementService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
SPRING CONFIG
<object id="OrderManagementService"
singleton="false"
type="Kodi.Kodiak.Services.OrderManagementService, Kodi.Kodiak.Services"
scope="session">
</object>
How the clients are calling the service? If they are calling the service through the SvcUtil generated proxy; are they closing the proxy connection properly? I think the clients are not closing the connections or simply the connections are not getting closed properly.
One important thing is, you should avoid using using statement while creating proxies.
A better approach would be something like this,
ServiceClient client = null;
try
{
client = new ServiceClient();
client.CallMethod();
}
finally
{
client.CloseConnection(); // extension method
}
public static void CloseConnection(this ICommunicationObject client)
{
if (client.State != CommunicationState.Opened)
{
return;
}
try
{
client.Close();
}
catch (CommunicationException)
{
client.Abort();
throw;
}
catch (TimeoutException)
{
client.Abort();
throw;
}
catch (Exception)
{
client.Abort();
throw;
}
}
I think this can be done by maintaining the client and server Binding End Points and Behavior same, the timeout values specified in the Client and Server Configs Should be Same.

WCF FaultException error

I'm new to WCF and I have issues throwing exceptions from my WCF Service to the client. I'm using code examples which I copied from the web. (I'm using VS2010 .NET Framework 4.0)
I created an ErrorHandler where the ProvideFault-method looks like this:
public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message msg)
{
FaultException<Exception> faultException = new FaultException<Exception>(error, error.Message, new FaultCode("Testing."));
MessageFault messageFault = faultException.CreateMessageFault();
msg = Message.CreateMessage(version, messageFault, Constants.FaultAction);
}
The fault contract looks like this:
[FaultContract(typeof(Exception), Action=Constants.FaultAction)]
The client side test code looks like this:
private void button1_Click(object sender, EventArgs e)
{
HistorianAccessServiceClient cli = new HistorianAccessServiceClient();
Tables.Batch bt = new Tables.Batch();
try
{
bt = cli.GetBatch(3241);
}
catch (FaultException<Exception> ex)
{
MessageBox.Show(ex.Message);
}
}
I noticed that if the error parameter to the ProvideFault method contains an inner exception then a System.ServiceModel.CommunicationException is thrown on the client side (!?), the inner exception is System.Net.WebException, the inner exception to that exception is System.IO.IOException and the inner exceptin to that exception is System.Net.Sockets.SocketException (Error Code 10054)?!?!
(Unfortunately I have a swedish operating system installed which means that the messages from the debugger is in swedish.)
The exception message (google translate) looks like this:
An error occurred while receiving the HTTP response to http://localhost:7070/Historian.WebAccess/HistorianAccessService. It may be that the service endpoint binding not using the http protocol. It may also be due to a context for the http request has been interrupted by the server (probably because the service is terminated). You can find more information in server logs.
If I throw an exception without an inner exception, the exception is handled by the client perfectly ok!?!?!
My configuration files looks like this (Service):
<system.serviceModel>
<bindings />
<client />
<services>
<service name="Historian.WebAccess.HistorianAccessService">
<host>
<baseAddresses>
<!--<add baseAddress="http://localhost:8732/Design_Time_Addresses/Historian.WebAccess/HistorianAccessService/"/>-->
<add baseAddress="http://localhost:7070/Historian.WebAccess/"/>
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<!--<endpoint address="HistorianAccessService" binding="wsHttpBinding" contract="Historian.WebAccess.IHistorianAccessService">-->
<endpoint address="HistorianAccessService" binding="wsHttpBinding" contract="Historian.WebAccess.IHistorianAccessService">
<!--
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="localhost"/>
</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="false"/>
<serviceThrottling maxConcurrentCalls="16" maxConcurrentInstances="2147483646" maxConcurrentSessions="10"/>
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>
<!-- 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>
Configuration file (Client):
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IHistorianAccessService" closeTimeout="00:10:00"
openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="104857600" maxReceivedMessageSize="104857600"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="104857600" maxStringContentLength="104857600" maxArrayLength="104857600"
maxBytesPerRead="104857600" maxNameTableCharCount="104857600" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:7070/Historian.WebAccess/HistorianAccessService"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IHistorianAccessService"
contract="HistorianAccessHost.IHistorianAccessService"
name="WSHttpBinding_IHistorianAccessService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</client>
<behaviors>
<endpointBehaviors>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
Does anyone out there recognize this phenomenon and the solution to it?!
I'd be greatful for all the help I can get!
The solution is to not attempt to pass .NET Exception objects back to the client. This limits you to clients running .NET.
In fact, it limits you to running clients which know about all of the exceptions that you might throw. What if you add a new MyNewException on the server, and throw it back to the client? The client will need to have the assembly containing that exception in order for it to be deserialized at all.
I think you're being too fancy for what you're trying to do. If you're just trying to throw FaultException, just do new FaultException(error). You have to do a bit more work if you're throwing a custom fault type, but none of that message stuff is necessary. Here's a VB example I found:
Public Function DoSomething() As Data()
Try
DoSomething()
Catch ex As Exception
Throw New FaultException(ex.Message)
End Try
End Function
If you're throwing a custom type of fault (like say PermissionDenied or such), you need to create an object for that, which is a bit more work.
You also want to be careful what you're returning here. Sending back a lot of details like stack traces to the client can help an attacker trying to break into the system, and isn't a lot of use to your standard end user. You should log that on the server instead.