WCF Behavioral Contracts and Message Exchange Patterns

Challenge:

Architect was busy on other tasks, So, he was not able to share his WCF knowledge with you since last few days. He apologize for this!
Architect’s team liked his WCF Fundamentals notes and they requested him to share his all notes whatever he has related to WCF!
So, here’s the 3rd part (1st part, 2nd part) of WCF Story where our architect would like to share his WCF Behavioral Contracts and Message Exchange Patterns with you!

Solution:

Here’s the discussion between Architect and his team!
Contracts
Contract defines:

  • What service operations you are going to get?
  • How to format the messages you send to a given service.?
  • What will it do when it receives the messages?
  • What kind of response message you should expect in return, or if something goes wrong, what kind of fault does the service issue?

WCF Structures an overall contract by with its consumers by defining the following three core contracts:

  • Service Contract :- Defines which operations the service makes available to be invoked as request messages are sent to the service from the client.
  • Data Contract :- Defines the structure of the data included in the payloads of the messages flowing in and out of the service.
  • Message Contract :- Enables you to control the headers that appear in the messages and how the messages are structured.

Categorically there are two types of contracts:
1. Behavioral Contracts
2. Structural Contracts
Today we are going to delve in to first category — Behavioral contract
Behavioral Contracts

  • Tools to start defining WCF services.
  • It helps you to define how your service will behave (and in OOPs term we define class’s behavior using methods]

It focused on .NET attributes you need from System.ServiceModel namespace to specify the behavioral aspects of your WCF Service:

  • How the service behaves and what operations it exposes.
  • When the service might issue faults and what kind of faults it might issue.
  • What are the MEPs required to interact with the service? – Operation is request/response way, one way or duplex.

Basically there are 3 types of Behavioral contracts:

  1. ServiceContractAttribute
  2. OperationContractAttribute
  3. Fault Contracts

Let’s discuss them one by one.
ServiceContractAttribute
Service contract describes the operation that service provide. A Service can have more than one service contract but it should have at least one Service contract.

  • It describes the client-callable operations (functions) exposed by the service
  • It maps the interface and methods of your service to a platform-independent description
  • It describes message exchange patterns that the service can have with another party. Some service operations might be one-way; others might require a request-reply pattern
  • It is analogous to the element in WSDL

To create a service contract you define an interface with related methods representative of a collection of service operations, and then decorate the interface with the ServiceContract Attribute to indicate it is a service contract.
Named parameter options:

Named Parameter Description
Name
•Specifies a different for the contract instead of the default,
which is simply the interface or class type name. This contract name will
appear in WSDL.
Namespace
•Specifies a target namespace in the WSDL for the service.
The default namespace is http://tempuri.org . It’s really good practice to provide
Namespace.

Just a note : Please note that there are other named parameters as well. But it has been omitted intentionally to make things simple.
[sourcecode language=”csharp”]
[ServiceContract(Name="CalculatorService",
Namespace="http://schemas.demo.com/2011/10/calc/")]
public interface ICalculator
{
[OperationContract]
double Add(double number1, double number2);
}
[/sourcecode]
TIP:

  1. Always use Namespace property to provide a URI that in some way uniquely identifies both your organization and the conceptual or business domain in which the service operates. W3C standard – year and month to differentiate versions of your service.
  2. Good practice to use the Name property to remove the leading I because I is more of a .NET idiom.

OperationContractAttribute

  • Can be applied only to methods
    Used to declare the method belonging to a Service contract.

Named parameter options:

Named Parameter Description
Name
•Specifies a different name for the operation instead of using the default
which is the method name.
IsOneWay
•Indicates whether the operation is one-way and has no reply.

Just a note : Please note that there are other named parameters as well. But it has been omitted intentionally to make things simple.
[sourcecode language=”csharp”]
[ServiceContract(Name="CalculatorService",
Namespace="http://schemas.demo.com/2011/10/calc/")]
public interface ICalculator
{
[OperationContract(Name=“AddMethod",
IsOneWay=true)]]
double Add(double number1, double number2);
}
[/sourcecode]
Fault Contracts

  • When something goes wrong – what to do? (When service issues some faults then what type of information should be issued)
  • Faults (SOAP Faults) Vs. Exceptions (Exceptions) : Faults and exceptions are not the same thing. Exceptions, as referred to here, are a .NET mechanism used to communicate problems encountered as a program executes. The .NET Lang. allows you to throw, catch/handle, and possibly ignore exceptions so that they can be further propagated up the call stack. At the same point they should be handled else .NET runtime will terminate that thread.
    Fault, refer to the SOAP fault mechanism for transferring error or fault conditions from a service. The SOAP specification includes definition for SOAP Faults. Issue faults in a standard way.
  • WCF FaultException Class :- Provides standard mechanism for translating between two world of .NET Exceptions and SOAP Faults – WCF serialized your exception in SOAP Fault.
  • FaultContractAttribute :- enables a service developer to declare which faults a given service might issue if things go wrong. It can be applied to operations only and also more than once if needed.

[sourcecode language=”csharp”]
// Service Contract
[OperationContract]
[FaultContract(typeof(string))]
double Divide(double numerator, double denominator);
// Service Implementation
public double Divide(double numerator, double denominator)
{
if (denominator == 0.0d)
{
string faultDetail = "cannot divide by zero";
throw new FaultException(faultDetail);
}
return numerator / denominator;
}
[/sourcecode]
Message Exchange Patterns (MEP)
MEPs describe the protocol of message exchanges a consumer must engage in to converse properly with the service. For instance, if a consumer sends a message, it needs to know whether it should expect a message back or whether simply sending the request is enough. Further, can the consumer expect unsolicited messages back from the service? WCF supports
the following three MEPs:
1. One-way

  • One-way operation can be enabled by setting IsOneWay property to true in Operation contract attribute.
  • It can’t be used in conjunction with Fault Contract – Because it needs two-way channel.  Also, One way is not really one way!

In One-Way operation mode, client will send a request to the server and does not care whether it is success or failure of service execution. There is no return from the server-side, it is one-way communication.
Client will be blocked only for a moment till it dispatches its call to service. If any exception thrown by service will not reach the server.
Client can continue to execute its statement, after making one-way call to server. There is no need to wait, till server execute. Sometime when one-way calls reach the service, they may not be dispatched all at once but may instead be queued up on the service side to be dispatched one at a time, according to the service’s configured concurrency mode behavior. If the number of queued messages has exceeded the queue’s capacity, the client will be blocked even if it’s issued a one-way call. However, once the call is queued, the client will be unblocked and can continue executing, while the service processes the operation in the background.
[sourcecode language=”csharp”]
[ServiceContract(Name = "PizzaService",
Namespace = "http://schemas.demo.com/2011/10/pizza/")]
public interface IPizzaService
{
[OperationContract(IsOneWay = true)]
void CancelPizza(int pizzaOrderNumber);
}
[/sourcecode]
2. Request / Response [Default Message exchange pattern]

By default all WCF will be operated in the Request-Response [IsOneWay property of OperationContractAttribute is false) mode. It means that, when client make a request to the WCF service and client will wait to get response from service (till receiveTimeout). After getting the response it will start executing the rest of the statement. If service doesn’t respond to the service within receiveTimeout, client will receive TimeOutException
Void method doesn’t mean OneWay. It can use Request/Response and it’s really good practice to use it because this MEP allows to receive faults.
3. Duplex
Duplex MEP is a two-way message channel whose usage might be applicable in following situation:

  • Consumer sends a message to the service to initiate longer-running processing and then subsequently requires notification back from the service, confirming the requested processing has been done.

Duplex MEP has following issues:

  • it’s problematic in real world because a service needs connection back to the client – Firewalls and NAT problems.
  • Not Scalable. – We want stateless.
  • You lose interoperability. Because to implement Duplex MEP we need to use Callback method in WCF. But what if client is JAVA – which doesn’t supports callback methods.
  • Threading problems.

In Short Duplex is Complex! – Avoid using it. Use it if you really need it! – Okay, then how to deal with above given situation without Duplex?
Stay tuned for next story! (Just a note : If you would like to get email update whenever new story get posted, please do subscribe using subscription form — given right side)
Happy WCF Programming! 🙂

WCF Fundamentals and Quick start

Challenge:

After receiving lot of appreciation and positive comments on my first WCF article Why we need Windows Communication Foundation? and suggestion from Manaday (Which was going back of my mind. But somehow I was not bringing it in implementation), Henceforth I am going to post full WCF Series based on last fictional story.
So, here’s the 2nd part of WCF Story where our architect would like to share his WCF Fundamentals with you!

Solution:

Architect was kind enough to share his WCF Fundamental notes what he created for his team with you! [We should be thankful to him :)]
WCF provides API for creating systems that send messages between clients and services. Which can be sent either Intranet or Internet over TCP,HTTP,MSMQ, Web Services etc. Also it’s Interoperable!

Following are most of the concepts and terms used in WCF:

  • Message: Self-contained packets of data that may consist of several parts including header and body. All parts of a message can be encrypted and digitally signed except for the header which must be in clear text.
  • Service: A software module (EXE or DLL) that provides 1 to n endpoints with each endpoint providing 1 to n service operations.
  • Endpoint: A single interface that is used to establish communications between clients and hosts. Each endpoint has its own address that is appended to the base address of the service, making it a unique entity. A WCF service is a collection of endpoints.
  • Binding: A set of properties that define how an endpoint communicates with the outside world. At the very least, the binding defines the transport (HTTP or TCP) that is necessary to communicate with the endpoint. A binding may also specify other details such as security or the message pattern used by the endpoint.
  • System-provided bindings: A collection of bindings that are optimized for certain scenarios. For example, WSHttpBinding is designed for interoperability with Web Services that implement various WS-* specifications.
  • Service Contract: The contract defines the name of the service, its namespace, and other global attributes. In practice, a contract is defined by creating an interface (interface in C#) and applying the [ServiceContract] attribute. The actual service code is the class that implements this interface.
  • Operation Contract: Given that a service contract is defined by creating an interface and annotating it with [ServiceContract], an operation contract is a member method of that interface that defines the return type and parameters of an operation. Such an interface method must be annotated with [OperationContract].
  • Data Contract: Data types used by a service must be described in metadata to enable clients to interoperate with the service. The descriptions of the data types are known as data contracts and the types may be used in any message (parameters or return types).
  • Service operation: A method that is implemented and exposed by a service for consumption by any client. If a service contract is defined by creating an interface, then a service operation is the class that implements this interface.The method may or may not return a value, and may or may not take any arguments. Note while a method invocation might appear as a single operation on the client, it can result in sending multiple messages to the service. For example, a method with two arguments called on a WCF client results in two messages sent to the service.
  • Host: A host is an application (typically .exe) that is used to control the lifetime of a service. A host can be a console, a Windows Service, a Window Activation Service (WAS) and Internet Information Service (IIS) among others. For IIS, you can set a virtual directory that contains the service assemblies and configuration file. When a message is received, IIS starts the service and control its lifetime. When a client (or clients) end(s) the session, IIS closes the application and releases it resources.
  • Behavior: A behavior is a type (i.e., class) that augments the runtime functionality of a service. Service behaviors are enabled by applying a [ServiceBehavior] attribute to a service class and setting properties to enable various behaviors. Behaviors are used to control various runtime aspects of a service or endpoint. Behaviors are grouped according to scope: Common behaviors affect all endpoints, service behaviors affect only service-related aspects, and endpoint behaviors affect only endpoint-related properties. For example, an endpoint behavior may specify where and how to find a security credential.
  • Instancing: A service has an instancing model which controls how many instances of the service can run at one time. There are four instancing models: single, per call, per session, and shareable. The first two are similar in concepts to the Singleton and Single Call SAOs in .NET Remoting. Instancing is a behavior and and as such it is specified as part of the [ServiceBehavior] attribute as follows: [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)].
  • Client Application: A program that exchanges messages with one or more endpoints. The client application typically creates a WCF Client Object and then calling methods on this proxy object.
  • Channel: This is the transport connection between a client application and an endpoint in a service. A client uses a transport (TCP, HTTP, etc.) and an address to construct a channel to a specific endpoint.
  • WCF Client Object: This a client-side construct that encapsulates service operations as methods, in other words, a WCF Client Object is a proxy to the service methods. Note that any application can host a WCF Client Object, even an application hosting a service. Therefore, it is possible to create a service that includes and uses proxies to other services. These proxies are typically generated using the svcutil.exe command-line utility.
  • Metadata: data that is generated by the svcutil.exe command-line utility. This data includes:
  1. XML schema that define the data contract of the service.
  2. WSDL to describe the methods of the service.
  3. Application configuration files.
  • Metadata exchange point: An endpoint with its own address that is used to publish metadata.
  • Security: Security in WCF includes encryption of messages, integrity of messages, authentication and authorization. These functions can be provided by either using existing security mechanisms such as HTTPS or by implementing one or more of the various WS-* security specifications.
  • Message pattern: The message pattern determines the relationship and direction of messages between the client and the service. The most basic pattern is the one-shot (or one way) pattern is which a message is sent to the server but not response is expected. The most complex pattern is a dual HTTP pattern where two HTTP channels are constructed between a client and a service, with both sides invoking operations on each other.
  • Reliable messaging: The assurance that a message is received only once and in the order in which it was sent.
  • Sessions: A session is used to establish communication between a client and a service in which all messages are tagged with an ID that identifies the sessions. If a session is interrupted, it can be restarted with the session ID. If a service contract supports a session, then you will need to use Instancing to determine how the class that implements the service contract behaves during the session. See the Duplex Message Pattern example in Designing Contracts chapter.

Basic WCF Programming Lifecycle

Here are the basic steps of WCF Programming Lifecycle – Order matters!

  1. Define the service contract. A service contract specifies the signature of a service, the data it exchanges, and other contractually required data.
  2. Implement the contract. To implement a service contract, create the class that implements the contract and specify custom behaviors that the runtime should have.
  3. Configure the service by specifying endpoint information and other behavior information.
  4. Host the service in an application.
  5. Build a client application.

Just a note : Although the topics in this section follow this order, some scenarios do not start at the beginning. For example, if you want to build a client for a pre-existing service, you start at step 5. Or if you are building a service that others will use, you may skip step 5.

WCF Quick start

Following steps will help you to create your first WCF service (In this example we are going to create two console applications one console application will be hosting the service and second one will be consuming the service):
Step 1 : Define a Windows Communication Foundation Service Contract : When creating a basic WCF service, the first task is to create the contract for the service that is shared with the outside world that describes how to communicate with the service. This contract specifies the collection and structure of messages required to access the operations offered by the service. This is done by creating an interface that defines the input and output types, which apply the ServiceContractAttribute to the interface and OperationContractAttribute to the methods that you want to expose.

NOTE : We need to add reference to System.ServiceModel

The service contract that is used here employees a request-reply message exchange pattern by default that is not explicitly specified. You can specify this and other message exchange patterns for client-service communications by setting properties of the OperationContractAttribute and ServiceContractAttribute in the contract.
Example:
[sourcecode language=”csharp”]
namespace WCFService
{
[ServiceContract]
public interface ICalculator
{
// It will be exposed to clients
[OperationContract]
double Add(double number1, double number2);
}
}
[/sourcecode]
Step 2 : Implement a Windows Communication Foundation Service Contract : Implement the Service Contract defined in step1.
Example:
[sourcecode language=”csharp”]
namespace WCFService
{
public class CalculatorService : ICalculator
{
#region ICalculator Members
public double Add(double number1, double number2)
{
Console.WriteLine("Service called at : {0}", DateTime.Now.ToString());
Console.WriteLine(@"Calculator Service got called
with two parameters {0} and {1}",
number1,
number2);
double result = number1 + number2;
Console.WriteLine("The result is : {0}",result);
Console.WriteLine("——————————-");
return result;
}
#endregion
}
}
[/sourcecode]
Step 3 : Run a Basic Windows Communication Foundation Service :
This topic describes how to run a basic Windows Communication Foundation (WCF) service. This procedure consists of the following steps:

  • Create a base address for the service.
  •  Create a service host for the service.
  •  Enable metadata exchange.
  •  Open the service host.

Example:
[sourcecode language=”csharp”]
namespace WCFService
{
class Program
{
static void Main(string[] args)
{
// Address
Uri baseAddress =
new Uri("http://localhost:8080/WCFService/Service");
// Host
ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService),
baseAddress);
try
{
// Binding, Contract
serviceHost.AddServiceEndpoint(typeof(ICalculator),
new WSHttpBinding(),
"CalculatorService");
// Metadatabehavior
// WSDL information we need to expose to clients
// it works on HTTP GET Method
ServiceMetadataBehavior serviceMetadatabehavior
= new ServiceMetadataBehavior();
serviceMetadatabehavior.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(serviceMetadatabehavior);
// Start the service
serviceHost.Open();
Console.WriteLine("Service started : {0}",
DateTime.Now.ToString());
// Stop the service
Console.WriteLine("Press ENTER to shut down the service");
Console.ReadLine();
serviceHost.Close();
Console.WriteLine(@"Service shutdown successfully.
Thank you for using our service!");
}
catch (CommunicationException ce)
{
Console.WriteLine(ce.Message);
serviceHost.Abort();
}
}
}
}
[/sourcecode]
Step 4: Create a Windows Communication Foundation Client : This topic describes how to retrieve metadata from a WCF service and use it to create a proxy that can access the service. This task is most easily completed by using the ServiceModel Metadata Utility Tool (Svcutil.exe) provided by WCF. This tool obtains the metadata from the service and generates a managed source code file for a client proxy in the language you have chosen. In addition to creating the client proxy, the tool also creates the configuration file for the client that enables the client application to connect to the service at one of its endpoints.

svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config

By default, the client proxy code is generated in a file named after the service (in this case, for example, CalculatorService.cs or CalculatorService.vb where the extension is appropriate to the programming language: .vb for Visual Basic or .cs for C#). The /out switch used changes the name of the client proxy file to “generatedProxy.cs”. The /config switch used changes the name of the client configuration file from the default “output.config” to “app.config”.

Just a note : If you would like to test your service quickly. You can use WCFTestClient.exe utility which will help you to test your service without writing a single line of code for your WCF Client!


Step 5: Configure a Basic Windows Communication Foundation Client : This topic adds the client configuration file that was generated using the Service Model Metadata Utility (Svcutil.exe) to the client project and explicates the contents of the client configuration elements. Configuring the client consists of specifying the endpoint that the client uses to access the service. An endpoint has an address, a binding and a contract, and each of these must be specified in the process of configuring the client.
svcutil.exe will provide you the default configuration automatically.
Step 6 : Use a Windows Communication Foundation Client : Once a Windows Communication Foundation (WCF) proxy has been created and configured, a client instance can be created and the client application can be compiled and used to communicate with the WCF service. This topic describes procedures for creating and using a WCF client. This procedure does three things: creates a WCF client, calls the service operations from the generated proxy, and closes the client once the operation call is completed.
Now, copy paste the svcutil generated files (CS and Config file) within your console project and then you can call your service from your client application as shown below:
Example:
[sourcecode language=”csharp”]
namespace WCFClient
{
class Program
{
static void Main(string[] args)
{
CalculatorClient calculatorClient = new CalculatorClient();
Console.WriteLine("Proxy calling service…");
Console.WriteLine(calculatorClient.Add(10, 20));
// Good practice
calculatorClient.Close();
Console.WriteLine("closed!");
}
}
}
[/sourcecode]
And then first start your service (your service must be in running state before you run the client) and then run the client. And this is how it will look like:

Resources

Mike Taulty’s Video : Windows Communication Foundation:” Hello World”:
http://go.microsoft.com/?linkid=4091084
http://download.microsoft.com/download/f/b/3/fb3c2a8b-604e-479b-ab22-e31dc094a40d/WCF_Hello_World.zip
Stay tuned for next story! (Just a note : If you would like to get email update whenever new story get posted, please do subscribe using subscription form — given right side) 🙂
Happy WCF Programming! 🙂

Why we need Windows Communication Foundation?

Challenge:

In earlier days, when i was totally newbie to WCF, I was not clear why we need WCF? one thing I was clear that it has something to do with Web Services. But other than that nothing was much clear.
Then at one fine day, I came across Shivprasad Koirala’s .NET Interview questions book. In which he explained why we need WCF and what is WCF using a fictional story. It is really nicely written and it clears why we need WCF.
Before couple of days, I got good time (as I was on holidays) to convert that story in a comic — To make it more funny (And that’s what philosophy I follow — “Coding should be fun” :-)) and comic blog — a new concept which I always wanted to start!
So, here we go my first comic blog article which explains why we need WCF?

Solution:

  • Long Long time ago there lived a hardworking and a nice architecture.
  • Develop a Booking Engine which books tickets for any flight carriers.
  • The nice and hardworking architecture and his team developed a nice booking engine by which you can book tickets through any of the flight Carriers. The Travel Agent Company was very happy with the architecture and his team Member’s achievements.

  • As time passed by the travel agent’s business grew in multiples
  • Architecture and his team was very excited and they started to work on this new stuff
  • All franchises run on Windows Platform.
  • Booking engine was located in the main head office and all the franchise should communicate to this booking engine.
  • After months he rolled out his project successfully.

  • Time passed by and because of the good automated booking service more companies wanted to take the franchise from the travel agent. But the big issue was many of the franchise did not have windows operating system. They worked on Linux and other Non-Microsoft operating systems.
  • Due to this limitation travel agent was losing lot of franchise business.
  • Now, booking engine runs on two platforms .NET Remoting (for Windows based clients) and Web Services (for non-windows based clients).

  • Franchise client had to wait to get response and was not able to process the next ticket booking until the first one was served. Travel Agent started receiving huge complaints because of this synchronous processing.
  • Booking engine had the capacity of serving 20 tickets / second but it had now to serve 50 tickets / second.
  • when the travel agent makes a booking it will come and fall in the queue and release the travel agent. Booking engine will always poll for this queue. When the booking engine finishes he will publish the booking results back to the queue. Travel agent client can then come at his leisure and see the results.

  • Everyone in the travel company was really happy and impressed by the architect and his team members
  • Travel Agent then felt a huge necessity of a good security model with the booking engine.

  • Till now the travel agent was booking one ticket at a time. But soon he started getting lot of orders to book group family tickets.
  • Consistency – If father’s ticket gets canceled. Kid’s ticket should also be got canceled.


They were working on:

  • .NET
  • .NET Remoting
  • Web Services
  • MSMQ
  • WSE
  • COM+


WCF is a unification of all distributed technologies like:

  • .NET Remoting
  • MSMQ
  • Web Services
  • COM+

Thanks a lot Shivprasad Koirala for writing such a nice story!
Happy Coding! 🙂

“The underlying connection was closed: The connection was closed unexpectedly.” While returning Data Table from WCF service.

Error:

“The underlying connection was closed: The connection was closed unexpectedly.”

StackTrace:

System.ServiceModel.CommunicationException was unhandled by user code

Message=”The underlying connection was closed: The connection was closed unexpectedly.”

Source=”mscorlib”

StackTrace:

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.Channels.ClientReliableChannelBinder`1.RequestClientReliableChannelBinder`1.OnRequest(TRequestChannel channel, Message message, TimeSpan timeout, MaskingMode maskingMode)

at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout, MaskingMode maskingMode)

at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout)

at System.ServiceModel.Security.SecuritySessionClientSettings`1.SecurityRequestSessionChannel.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 System.Web.UI.Control.OnLoad(EventArgs e)

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

InnerException: System.Net.WebException

Message=”The underlying connection was closed: The connection was closed unexpectedly.”

Source=”System”

StackTrace:

at System.Net.HttpWebRequest.GetResponse()

at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

InnerException:

Scenario:

I have one OperationContract defined in my service contract which was returning DatTable as its return Type So it was looking like this:

[OperationContract]

DatTable LoadEmployeeInformation(long employeeID);

And in implementation I am filling this data Table using Table Adapter and returning it.

But it was throwing me error which was really annoying i had spent 4-5 hours to figure out it…

Solution:

I have changed my operation Contract to return Dataset Instead of Data Table

[OperationContract]

DataSet LoadEmployeeInformation(long employeeID);

and it worked like a charm!!!! For me…and hope that it works for you also…then go ahead and try this change….

Root cause:

Sorry guys I don’t know the root cause of this error. But i read some forums from Microsoft and they says that don’t use Data Table as a return type because some problem occurs in deserializaing it at client side…hooh…but I think it is BUG of WCF!!

Webliography:

http://connect.microsoft.com/wcf/feedback/ViewFeedback.aspx?FeedbackID=286535

http://processmentor.com/community/blogs/scott_middleton/archive/2007/06/08/169.aspx

http://blogs.msdn.com/lifenglu/archive/2007/08/01/passing-datatable-across-web-wcf-services.aspx

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1828652&SiteID=1&mode=1

http://blogs.conchango.com/merrickchaffer/archive/2007/09/19/WCF-System.Net.WebException_3A00_-The-underlying-connection-was-closed_3A00_-The-connection-was-closed-unexpectedly.aspx

-Kiran