System.ServiceModel.ProtocolException with two 'parallel' proxies - wcf

My web services have been working perfectly, It's hard to tell what I did do that resulted in them crashing from time to time. I added HTTP Basic Authentication and swapped database providers, from ObjectDB to MySQL, so there was a drop in performance but this seems irrelevant.
I have SSL protected Java Metro web services hosted on GlassFish v3.1 with MTOM streaming enabled. I'm calling them with a WCF client. The exception occurs randomly from time to time even when I call the same service with the same parameters.
UPDATE Sometimes it just behaves like it makes a successful call, and then no matter which service I'm calling, even with a helloWorld, I'm getting the exception. If I call only one of the proxies, the calls go just fine, but for eg I get the exception, if I make a call to dataMiningClient and then dataStoreClient. Thread safety?
See:
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
DataStoreWSClient dataStoreClient = getDataStoreClient(email, password);
DataMiningWSClient dataMiningClient = getDataMiningClient(email, password);
byte[] dataSet = File.ReadAllBytes(textBox1.Text);
string dataSetName = Path.GetFileName(textBox1.Text);
long checkSum = getCheckSumForDataSet(dataSet);
//WS Call
try
{
//Example:
//The second time I click on this button,
//this is the point where I get the ProtocolException
bool checkSumResponse = dataStoreClient.checkDataSet(checkSum);
//checkSumResponse was always true when I was debugging this
//So no MTOM streaming involved
if (checkSumResponse)
{
richTextBox1.Text = dataMiningClient.kNearestNeighbour(checkSum, notifyByEmail);
}
else
{
richTextBox1.Text = dataMiningClient.kNearestNeighbourMTOM(dataSetName, notifyByEmail, dataSet);
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
richTextBox1.Text = ex.ToString();
}
dataMiningClient.Close();
dataStoreClient.Close();
}
I do not have any error messages on the server side.
This is the exception message I get:
System.ServiceModel.ProtocolException: The content type multipart/related;start="";type="application/xop+xml";boundary="uuid:d64b0098-0dcb-4da4-a047-d305b55da9f5";start-info="text/xml" of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: '--uuid:d64b0098-0dcb-4da4-a047-d305b55da9f5
Content-Id:
Content-Type: application/xop+xml;charset=utf-8;type="text/xml"
Content-Transfer-Encoding: binary
<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<S:Header>
<To xmlns="http://www.w3.org/2005/08/addressing">http://www.w3.org/2005/08/addressing/anonymous</To>
<Action xmlns="http://www.w3.org/2005/08/addressing"
xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"
S:mustUnderstand="1">http://webServices/DataStoreWS/checkDataSetResponse</Action>
<MessageID xmlns="http://www.w3.org/2005/08/addressing">uuid:1cbcfdc6-01e4-4ddc-960d-a9a2d4e3021a</MessageID>
<RelatesTo xmlns="http://www.w3.org/2005/08/addressin'. sender, EventArgs e) in F:\2.0\WSClient3.5ServiceRef\WSClient3.5\Form1.cs:line 51
Server stack trace:
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.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 WSClient3._5.DataStore.DataStoreWS.checkDataSet(checkDataSetRequest request)
at WSClient3._5.DataStore.DataStoreWSClient.WSClient3._5.DataStore.DataStoreWS.checkDataSet(checkDataSetRequest request) in F:\Dropbox\Suli\MSc\DIPLOMA_MSc\JavaWSJMX\2.0\WSClient3.5ServiceRef\WSClient3.5\Service References\DataStore\Reference.cs:line 1227
at WSClient3._5.DataStore.DataStoreWSClient.checkDataSet(Int64 checkSum) in F:\Dropbox\Suli\MSc\DIPLOMA_MSc\JavaWSJMX\2.0\WSClient3.5ServiceRef\WSClient3.5\Service References\DataStore\Reference.cs:line 1233
at WSClient3._5.Form1.button1_Click(Object sender, EventArgs e) in F:\Dropbox\Suli\MSc\DIPLOMA_MSc\JavaWSJMX\2.0\WSClie
Client Code:
DataMiningWSClient getDataMiningClient(String username, String password)
{
//IMPORTANT - THIS LINE IS ONLY FOR TESTING PURPOSES!
//This code is for accepting self-signed server certificate
ServicePointManager.ServerCertificateValidationCallback += (sender_ws, cert, chain, sslPolicyErrors) => true;
//instantiate transport binding element, leave the defaults
HttpsTransportBindingElement transport = new HttpsTransportBindingElement();
transport.MaxReceivedMessageSize = 2147483647;
transport.AuthenticationScheme = AuthenticationSchemes.Basic;
//instantiate message encoding element, where message version must be Soap11WSAddressing10 to match metro web service requirement.
MtomMessageEncodingBindingElement mtom = new MtomMessageEncodingBindingElement();
mtom.WriteEncoding = System.Text.Encoding.UTF8;
mtom.MessageVersion = MessageVersion.Soap11WSAddressing10;
mtom.MaxBufferSize = 2147483647;
mtom.ReaderQuotas.MaxStringContentLength = 2147483647;
//instantiate transport security binding element, with all the suggested values in app.config
TransportSecurityBindingElement b_element = new TransportSecurityBindingElement();
b_element.DefaultAlgorithmSuite = new Basic128SecurityAlgorithmSuite();
b_element.IncludeTimestamp = true;
b_element.KeyEntropyMode = SecurityKeyEntropyMode.CombinedEntropy;
b_element.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;
b_element.SecurityHeaderLayout = SecurityHeaderLayout.Lax;
//instantiate the custom binding and add the elements created above
CustomBinding customBinding = new CustomBinding();
customBinding.Name = "myOwnPersonalCustomBinding";
customBinding.Elements.Add(b_element);
customBinding.Elements.Add(mtom);
customBinding.Elements.Add(transport);
//instantiate the client
DataMiningWSClient DMclient = new DataMiningWSClient(customBinding, new EndpointAddress(new Uri("https://localhost:8181/DataMiner/DataMiner")));
setCredentials(username, password, DMclient.ClientCredentials);
return DMclient;
}
Any hints what could be the problem here? Please tell me if I should extend this question with more info; I may dig into the WCF message logs.

Reason of ProtocolException: I did NOT configure both proxies with an MtomMessageEncodingBindingElement, however both services were defined with the #MTOM annotation.
After defining it for both proxies everything worked fine:
//instantiate message encoding element, where message version must be Soap11WSAddressing10 to match metro web service requirement.
MtomMessageEncodingBindingElement mtom = new MtomMessageEncodingBindingElement();
mtom.WriteEncoding = System.Text.Encoding.UTF8;
mtom.MessageVersion = MessageVersion.Soap11WSAddressing10;
mtom.MaxBufferSize = 2147483647;
mtom.ReaderQuotas.MaxStringContentLength = 2147483647;

Related

WCF-NetNamedPipe's ChannelFactory

Update 20121214
consultation with the developers of the conflict service,
they use net.pipe://echonet as service address,
and use DuplexChannelFactory.
why it will block my Pipe?
Question:
I have a very simple WCF application.
Service and Client through NetNamedPipe communication.
But it is strange , some machines may be the reason because other software,
resulting in the ChannelFactory began to call the Service, throw an exception : System.ServiceModel.ProtocolException .
How could I know which application catch my WCF message,
and how should I avoid this problem.
here is exception:
System.ServiceModel.ProtocolException: The requested upgrade is not supported by 'net.pipe://localhost/xxxx/xxxx'. This could be due to mismatched bindings (for example security enabled on the client and not on the server)
Server stack trace:
System.ServiceModel.Channels.ConnectionUpgradeHelper.DecodeFramingFault(ClientFramingDecoder decoder, IConnection connection, Uri via, String contentType, TimeoutHelper& timeoutHelper)
System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.SendPreamble(IConnection connection, ArraySegment`1 preamble, TimeoutHelper& timeoutHelper)
System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.DuplexConnectionPoolHelper.AcceptPooledConnection(IConnection connection, TimeoutHelper& timeoutHelper)
System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)
System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
xxx.xxxxx.Communication.Contracts.IxxxComClientService.Register(ClientInfo clientInfo)
xxx.xxxxx.Communication.xxxComClient.ActionClientRegisterOnlineClientInfo(IxxxComClientService channel)
xxx.xxxxx.Communication.xxxComClient.ActionReceivedClientOnline(EndpointAddress endpoint)
here is my code'
----------------------------Service------------------------------
using (var host = new ServiceHost(typeof(StringReverser), new[] { new Uri("net.pipe://localhost") }))
{
host.AddServiceEndpoint(typeof(IStringReverser), new NetNamedPipeBinding(), "PipeReverse");
host.Open();
Console.WriteLine("Service is available. Press <ENTER> to exit.");
Console.ReadLine();
host.Close();
}
--------------------------Client---------------------------------
var pipeFactory = new ChannelFactory<IStringReverser>(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/PipeReverse"));
Console.WriteLine("pipeFactory Created. Press <Exit> to exit");
var pipeProxy = pipeFactory.CreateChannel();
Console.WriteLine("pipeProxy Created.");
while (true)
{
var str = Console.ReadLine();
Console.WriteLine("pipe: " + pipeProxy.ReverseString(str));
}
b1. the service, is host on windowsservice,run as administrator
b2. the service, is set net.pipe://echonet as his address
b3. my service, is self host,run as localuser
windowsservice > localuser
so, namedpipe will redirect to the service.
s1. stop the service
s2. change my service host, let it host on
windowsservice.

WCF IOutboundHandler Send non xml

I am trying to write a custom WCF Adapter using the WCF LOB Adapter SDK. Everything seems to work ok, except that I need to send a text string to the downstream system over a socket. When the Execute Method of the IOutboundhandler gets exectued I get the following error:
System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
With the following stack trace:
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndRequest(IAsyncResult result)
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 System.ServiceModel.Channels.IRequestChannel.EndRequest(IAsyncResult result)
at Microsoft.BizTalk.Adapter.Wcf.Runtime.WcfClient`2.RequestCallback(IAsyncResult result)".
Here is my execute Method:
/// <summary>
/// Executes the request message on the target system and returns a response message.
/// If there isn’t a response, this method should return null
/// </summary>
public Message Execute(Message message, TimeSpan timeout)
{
OperationMetadata om = this.MetadataLookup.
GetOperationDefinitionFromOutputMessageAction(message.Headers.Action, timeout);
if (om == null)
{
throw new AdapterException("Invalid operation " + message.Headers.Action);
}
MessageBuffer msgBuffer = message.CreateBufferedCopy(int.MaxValue);
XmlDictionaryReader reader = msgBuffer.CreateMessage().GetReaderAtBodyContents();
XmlDocument request = new XmlDocument();
request.LoadXml(reader.ReadOuterXml());
string positionalRs = this.Connection.Send(request.OuterXml);
XmlDocument response = new XmlDocument();
response.LoadXml(positionalRs);
XmlReader replyReader = XmlReader.Create(new StringReader(response.InnerXml));
return Message.CreateMessage(message.Version, message.Headers.Action + "/Response", replyReader);
}
How can I access the body of a WCF message that is not xml?
here is what my WCF Message looks like:
Message:
<s:Envelope xmlns:a=http://www.w3.org/2005/08/addressing
xmlns:s=http://www.w3.org/2003/05/soap-envelope>
<s:Header>
<a:Action s:mustUnderstand=1>TCPCall</a:Action>
<a:MessageID>urn:uuid:e473f4e4-f6f5-47b5-92a6-123116fafaa5</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
</s:Header>
<s:Body>... stream ...</s:Body>
</s:Envelope>
the body of the message is not xml. whenever I try and acess it I get the following error:
"System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
I am trying to send data at a socket on the other end using wfc. I seem to have everything working, except the ability to pull out the contents of the WCF message if they are not xml.
Does that help?
Sounds like you may be using the wrong WCF binding for your project. The basicHttp, wsHttp, & netTcp bindings all assume you are dealing with soap (xml) documents. Sounds like you may want to look at the webHttpBinding and/or the various WCF REST toolkits which give more options for building you request & response documents (XML or json but don't know about plain text). More detail about what you are trying to do would be helpful in getting better answers.

How to configure WCF client to work with third party WS service hosted on the server that doesn't return content-type in the reply?

How to configure WCF client to work with third party WS service hosted on the server that doesn't return content-type in the reply?
Problem is that such WCF client configured to use basicHttpBinding throw an exception: "content-type is required"...
Should I use custom bindings or refuse WCF?
P.S. .NET 3.5
P.P.S
Message: An HTTP Content-Type header is required for SOAP messaging and none was found
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at blablabla (custom code)
I can say that this is impossible. I want to show why:
Very deep internal code (System.ServiceModel.Channels.HttpChannelFactory+HttpRequestChannel+HttpChannelRequest class, WaitForReply method) - you will never want to do inheritance and reflecetion focuses there with those inner classes - contains two lines
var response = (HttpWebResponse) this.webRequest.GetResponse(); // webRequest is type of HttpWebRequest
HttpInput input = HttpChannelUtilities.ValidateRequestReplyResponse(this.webRequest, response, this.factory, responseException);
since HttpWebRequest is public and GetResponse is virtual seems that it's possible to override it this way
public class FakedHttpWebRequest: HttpWebRequest
{
protected FakedHttpWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
{
}
public override WebResponse GetResponse()
{
WebResponse wr = base.GetResponse();
wr.ContentType = "text/xml";
return wr;
}
}
and then we need using reflection somewhere create FakedHttpWebRequest instead of HttpWebRequest...
Unfortunately this time "somewhere" appear to be static(!) method (WebRequest.Create), so there are no chance to stay in "small hack" scope.
I feel I found the scheme how it can be hacked.
Inherit new class from
System.ServiceModel.Channels.HttpChannelFactory+HttpRequestChannel+HttpChannelRequest
and override WaitForReply virtual method
Inherit new class from
System.ServiceModel.Channels.HttpChannelFactory+HttpRequestChannel
and override CreateRequest(Message) interface method
Inherit new class form
System.ServiceModel.Channels.HttpChannelFactory
and override OnCreateChannel(EndpointAddress remoteAddress, Uri via) method
problem: all those classes are private and internal (!). solution, create them on run-time using: reflection/emit/TypeBuilder/codedom. All mentioned methods are short (only WaitForReply is verbose) and all methods are virtual - there we are really lucky.
then inherit from Http(s)TransportBindingElement
and override BuildChannelFactory(BindingContext context);
and then create custom binding
:)
P.S. I'm not sure is it possible to create new type inheriting it from internal, protected class, from other assembly, but I guess it is possible.

Error when making First WCF Service Call

I am writing WCF client for service writtern in Java by one of the partner. I am getting an exception when I make first service call to thier service. But subsequent request did not throw any exception. I am using console application to test this. Why is that failing on first time not other times?
Here is code how I am calling the service multiple times
for (int i = 0; i < 3; i++)
{
ServiceClientTest();
}
Here is the Binding code
TransportBindingElement transportElement = null;
transportElement = new HttpsTransportBindingElement();
((HttpsTransportBindingElement)transportElement).AuthenticationScheme = AuthenticationSchemes.Basic;
var messegeElement = new TextMessageEncodingBindingElement
{
MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap11, AddressingVersion.None),
ReaderQuotas =
{
MaxArrayLength = 200000,
MaxBytesPerRead = 200000,
MaxDepth = 200000,
MaxNameTableCharCount = 200000,
MaxStringContentLength = 200000
}
};
var binding = new CustomBinding(messegeElement, transportElement);
return binding;
Here is the exception details of first request
Failed to score for CompanyXYZ ServiceCompany System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to https://test.intelligentcusomer.ServiceCompany.com/XYZCompanyAdapter/1.0. 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 established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.HttpWebRequest.MakeMemoryStream(Stream stream)
--- 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 ---
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.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 MyCompany.Services.Clients.ServiceCompany.XYZCompanyAdapter.process(processRequest request)
at MyCompany.Services.Clients.ServiceCompany.XYZCompanyAdapterClient.MyCompany.Services.Clients.ServiceCompany.XYZCompanyAdapter.process(processRequest request) in C:\Projects\MyCompany\MyCompany.Distribution\CustomDeliveryProcessor\Clients\XYZCompanyServiceClient.cs:line 1122
at MyCompany.Services.Clients.ServiceCompany.XYZCompanyAdapterClient.process(process process1) in C:\Projects\MyCompany\MyCompany.Distribution\CustomDeliveryProcessor\Clients\XYZCompanyServiceClient.cs:line 1129
at CustomDeliveryProcessor.CusomerDelivery.CompanyTestTest() in C:\Projects\MyCompany\MyCompany.Distribution\CustomDeliveryProcessor\CusomerDelivery.cs:line 131
I fixed this error by setting KeepAlive property to false. What I found was happened, when first request sent to the service endpoint, got 401 response from server (it is obivous because service using the basic authontication and then client sent basic authorization header in next request) that closes the connection. Default behaviour of client endpoint is to keep the connection alive. Though connection closed, client still send next request by using the same connection that already closed by the server that causes the above said error in the question. But this error won't happen again for subsequent requests because client send request with authorization header in the first request itself. So there is no chance of 401 response. What I did to fix this issue that set Keep alive property to false. So that, after 401 response, client send another request with new connection instead of using the old connection. Here is code
Binding binding = null;
var transportElement = new HttpsTransportBindingElement
{
AuthenticationScheme = AuthenticationSchemes.Basic,
KeepAliveEnabled = false,
};
var messegeElement = new TextMessageEncodingBindingElement
{
MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap11, AddressingVersion.None),
ReaderQuotas =
{
MaxArrayLength = 200000,
MaxBytesPerRead = 200000,
MaxDepth = 200000,
MaxNameTableCharCount = 200000,
MaxStringContentLength = 200000
}
};
binding = new CustomBinding(messegeElement, transportElement);
return binding;

Data Contract for a class with fields being user defined classes itself

I am Using WCF service to implement my web-service I have problem when I try to call my function which takes URL as input parameter and returns an object class which was defined by me.
public class Service: IService<br>
{
public ClassWS My_Stores(String URL)
{
try
{
//ClassWS is a class which has other classes like address() defined by me
ClassWS My_WS = new ClassWS ();
return ClsStore.My_Stores(URL);
}
catch (Exception ex)
{}
}
}
[DataContract]
public class ClassWS
{
[DataMember]
public granularity Granularity;
[DataMember]
public address[] Address = new address[5];
[DataMember]
public Store[] Stores;
[DataMember]
public int Status;
public ClassWS My_Stores(String URL)
{
ClassQuery q = new ClassQuery();
return (sq.PopulateStores(URL));
}
}
I have included every class defined by me in the DataContract as I have done in the above class. I am getting the error below mentioned when I am trying to return ClassWS but does not have any error with return Store[] or Address[]
I am getting the error. The error is not returned in the service code but occurs when the retuning the value to proxy.
The underlying connection was closed:
The connection was closed
unexpectedly. Server stack trace:
at
System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException
webException, HttpWebRequest request,
HttpAbortReason abortReason) at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
timeout) at
System.ServiceModel.Channels.RequestChannel.Request(Message
message, TimeSpan timeout) at
System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message
message, TimeSpan timeout) at
System.ServiceModel.Channels.ServiceChannel.Call(String
action, Boolean oneway,
ProxyOperationRuntime operation,
Object[] ins, Object[] outs, TimeSpan
timeout) at
System.ServiceModel.Channels.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
IFindStore.My_Stores(String URL) at
FindStoreClient.My_Stores(String URL)
Inner Exception: The underlying
connection was closed: The connection
was closed unexpectedly. at
System.Net.HttpWebRequest.GetResponse()
at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
timeout)
I would like to know how to get a datacontract for a class which has another classes as their fields.
Should I write the object to a stream using datacontractserialzer (even though data-contract uses datacontractserializer). Should I be using XmlSerializer?
Thanks in advance
In general, as long as you are having DataContract + Datamembers for all relevant classes, which you already seem to have, that is all that is needed for the DataContractSerializer to serialize them.
The following
The underlying connection was closed: The connection was closed unexpectedly.
Server stack trace: at System.ServiceModel.Channels.HttpChannelUtilities.
ProcessGetResponseWebException (WebException .....
is a generic exception that you will commonly see if there is an unhandled exception in your service which is causing the remote connection to be closed.
It is not necessarily something to do with the serialization of your classes.
I would suggest that you step-into your service method while debugging as that will tell you exactly what exception is being thrown and why!