Essential WCF
Essential WCF
Essential WCF
Practical Implementation
This free book is provided by courtesy of C# Corner and Mindcracker Network and its authors.
Feel free to share this book with your friends and co-workers.
Please do not reproduce, republish, edit or copy this book.
Akshay Patel
Sam Hobbs
Editor, C# Corner
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Table of Contents
3
This Book is about the basic introduction of the “WCF (Windows Communication Foundation)” for the
beginners.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
1 WCF Introduction and Contracts
4
Introduction
Defining the basic information of all the contracts and a code demonstration for creating the WCF service application.
What is WCF?
WCF is a combined feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET
communication. It is a part of .Net 3.0.
Step 1
Start Menu >> All Programs >> Microsoft Visual Studio 2010 >> Microsoft Visual Studio 2010
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
5
Step 2
Step 3
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Now your Windows Communication Foundation service application is ready as a default service. You will see in Solution
Explorer Service1.svc and IService1.cs 6
Open the IService1.cs file, as in:
Service Contract
Service contract is an attribute applied to an interface i.e. IService1. It describes which operations the client can perform
on the services.
Operation Contract
Operation Contract is an attribute applied to methods in interfaces i.e. IService1. It is used to define a method in
an interface.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
7
Data Contract
DataContract defines which data types are passed to and from the service. It is used to define a class and the
DataMember attribute is used to define the properties.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Step 4
8
There is one method "GetData" which accepts parameters of type in
An implementation of this method is in the Service1.svc.cs file. This method returns a string with the value you passed as
a parameter.
Step 5
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
9
You can test your service in WCF Test Client. WCF Test Client is a GUI tool which enables us to enter parameters, invoke
services with these parameters and view the responses returned by services.
Now double-click on the "GetData" method and enter a parameter value of type System.int32. Here I enter "25" as a
parameter value and press the "Invoke" button. You will get "You entered: 25" as a response.
Conclusion
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
We have seen a very basic example of a WCF Service application. We entered a parameter value of type int and got the
entered value as a response. 10
Discuss about the fault contracts property in Windows Communication Foundation and also explains the difference
between faults & exceptions and provides sample code for implementing fault contracts.
Fault Contracts
Windows Communication Foundation enables us to specify the fault behavior of our service.
For example
We create a service and this service is consumed by a client. Suppose this service throws an exception. But how can the
client be notified of this exception? Because whenever an exception is thrown from a service, it cannot be sent to the
client. But if you want to know the reason then a fault contract can help us. We can send information regarding this with
the fault.
The main thing in faults and exceptions is that "faults and exceptions are not the same thing".
An exception is a .Net mechanism. It is used when the program encounters an error. The .Net language allows us to
throw, catch and ignore the exception. At some point they should be handled or the .Net runtime will terminate the
thread in which the exception was thrown.
Faults refer to the SOAP fault mechanism to transfer error information from a service to a client. WCF provides the
FaultException class. Whenever a service throws a FaultException, WCF serializes the information sent to the client.
FaultException
FaultException<TDetail>
This generic version is used to send typed fault data to the client. TDetail represents the type parameter for the fault
information. Now let's see the example of typed fault data.
Create one WCF Service Application. Add the following segment of code in the Interface. In this code we are using the
FaultContract attribute. It is applied to the interface only. Suppose we want to return various types of faults then we need
to set the FaultContract attribute multiple times.
[ServiceContract]
public interface IService1
{
[OperationContract]
[FaultContract(typeof(FaultInfo))]
string Topup(string Operator, string MobileNumber, double Amount);
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
}
[DataContract()] 11
public class FaultInfo
{
[DataMember()]
public string Reason = null;
}
If we choose to use a typed fault then we need to define a DataContract for the type that holds the error information. In
our example we create a datacontract for the FaultInfo class and we create one data-member i.e. reason to hold the error
information.
Add the following lines of code in the .svc.cs file. In this method we check whether the amount is double or not. If the
amount is double then we throw a fault exception.
If the amount is double then we create an object of the "FaultInfo" class and set the information we want to send to the
client in the datamember i.e. the Reason. Finally we throw a fault exception of the fault info type.
Conclusion
Defining the FaultException and the difference between faults and exceptions and also defines the sample code to
implement fault exceptions. You can download the code and check the application.
Simple introduction about the WCF Message exchange patterns. Various types of message exchange patterns and code
demonstration for each message exchange pattern.
MEPs
MEP stands for Message Exchange Pattern. In WCF we are creating services. What does a service do for us? A service
does some task on behalf of us or sends a response back from our request. All such communications are done using
messages. We send some message as a request and get a message as a response from the service. WCF supports three
types of MEPs:
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Request / Response
One-Way 12
Duplex
Request / Response
Request / Response is a very common MEP. To set this pattern we need to set the IsOneWay property of
OperationContractAttribute as false. And the default value of the IsOneWay property is false. So ultimately we do not
need to set this property. It is set by default. That is why it is very easy to implement.
One more thing we should keep in mind is that we should not the use the Duplex Channel setting. We will see about
Duplex later in this article.
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetTransaction(int value);
Here you may assume that since we are sending a request and against this request we are getting something in response,
we cannot use a void return type. This is absolutely wrong. You can use a void return type. In this case the response
message is still being sent back to the client. The difference is it sends an empty SOAP body.
[ServiceContract]
public interface IService1
{
[OperationContract]
void DoTransaction(string value);
}
Oneway
Set the IsOneWay property of OperationContractAttribute to true for a OneWay message exchange pattern. Suppose you
send a message to a service. This pattern is used when the service does some operation and you do not want a response
back. For example you want to change the status of a transaction from pending to completed and you do not want to get
a confirmation from the service that the status is changed. You can use a OneWay pattern.
[ServiceContract]
public interface IService1
{
[OperationContract(IsOneWay=true)]
void ChangeTransactionStatus(int value);
}
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
You cannot use FaultContract with this pattern. In my previous article we have seen FaultContract. For FaultContract there 13
should be a two-way channel. So it is not possible in a Oneway pattern.
It is dangerous to send a oneway message since there is no assurance that the operation is processed. In our above
example we sent a message to change the transaction status but there is no assurance that the transaction is changed or
not.
Duplex
The duplex MEP is a two-way message channel. When the client sends a message to the service to instantiate some long-
running processing and requires notification back from the service, a duplex MEP is applicable.
There are two types of contacts, ServiceContract and CallbackContract required to implement a duplex MEP. This MEP is
declared by associating a CallbackContract with the ServiceContract. It is done through a CallbackContract property of
ServiceContract.
namespace WcfService1
{
[ServiceContract]
public interface ITransactionHandler
{
[OperationContract (IsOneWay=true)]
void TransactionDone(int value);
}
[ServiceContract(CallbackContract = typeof(ITransactionHandler))]
interface ITransactionService
{
[OperationContract(IsOneWay = true)]
void DoTransaction(string value);
}
}
public class TransactionService : ITransactionService
{
public void DoTransaction(string value)
{
int TransactionId = 1; //Get TransactionId from database
ITransactionHandler callbackHandler =
OperationContext.Current.GetCallbackChannel<ITransactionHandler>();
callbackHandler.TransactionDone(TransactionId);
}}
In the preceding example the client sends a one-way message to the TransactionService. After some period of time the
service calls back to the client and says TransactionDone.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Before using this pattern, keep the following points in mind.
14
In the real world this pattern is problematic because it requires a connection back to the client. And there may be a
chance to not connect back due to firewall and Network Address Translation problems.
This pattern doesn't scale very well due to long-running sessions maintained between client and service.
Threading problems can occur if either of the Callback channels are not empty.
Conclusion
The Request / Response MEP are used in most cases, because some kind of acknowledgement is required. In our case if
the client gets TransactionId back at the time of changing the status, he can query further with this TransactionId. So
acknowledgement is mandatory.
Data contracts are the conceptual agreement of the format and structure of the data in the message exchanged between
a service and client. It is a format of data passed to and from the service operations. It defines the structure and types of
data exchanged in service messages.
DataContractAttribute
Properties of DataContractAttribute
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
15
DataMemberAttribute
The DataMemberAttribute is also the part of the System.Runtime.Serialization namespace. It is applied to the members
and it is used to declare that the members should be included in the serialization.
Properties of DataMemberAttribute
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
16
EmitDefaultValue : If you want to add default values in the serialization then set the EmitDefaultValue to true
else EmitDefaultValue to false. By default it is true.
IsRequired : It controls the minOccurs attribute for the schema element. The default value is false.
Name : It creates the schema element name generated for the member.
Order : It maintains the order of each element in the schema. By default it appears alphabetically.
Note
For example you set the EmitDefaultValue to false and IsRequired to true and you are not assigning any value, at
that time it creates a problem. Because the serializer emits the default value and we are not passing any value, on
the other side it is required. That is why it throws an error.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
If you apply a data member attribute to both property and field, then it generates duplicate members in the
schema. 17
Sample Code
Create one DataContract for Place. Add the data members PlaceCode and PlaceName.
Set the order for the data members and set IsRequired to true for PlaceCode.
Create one OperationContract with return type Place.
namespace DataContractServiceApp
{
[ServiceContract]
public interface IService1
{
[OperationContract]
Place GetPlace(string PlaceCode);
}
In the service class, the GetPlace method is implemented and in that we create an object of place, assign some
values to it and return a Place object.
namespace DataContractServiceApp
{
public class Service1 : IService1
{
public Place GetPlace(string PlaceCode)
{
Place place = new Place();
return place;
} }}
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Difference between a Service Application and a Service Library. And explains where we should use Service Applications
and where to use a Service Library. 18
When you try to create a WCF service using Visual Studio IDE, you will have a choice of two types of WCF services, WCF
Service Application and WCF Service Library. Now let us see the differences between them. We will do this by generating
each of them and comparing the results.
Differences
1. The very basic point is that you need to select a "WCF Service Application" template under the WCF project type
at the time of project creation. In other words when you create the project from File >> New >> Project, select
the WCF as project type from the left side of the screen and select "WCF Service Application" from the template.
Select your desired location and provide an appropriate name for your project and press the "OK" button.
For a WCF Service Library you need to select "WCF Service Library" template at the time of project creation.
2. After creating the projects, compare the files created by Visual Studio IDE.
In the Service Application we have a service contract i.e. IService1 for the service implementation and Service1 as
a Web.config file.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
19
In the Service Library we also have a service contract i.e. IService1 for the service implementation and Service1 as
an App.config file for the configuration (instead of web.config as in the Service Application).
The major difference is that the WCF Service Application has a .svc file, whereas the Service Library does not have
a .svc file. Suppose we want to host this service application in IIS, then you need to specify for IIS the execution
runtime environment requirements.
In a web application we set an .aspx, similarly for a Service Application we need to set a .svc.
3. Run the WCF Service Application and it will show a directory listing, as in:
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
20
Now double-click on Service1.svc and it is hosted by default by the ASP.Net Development server. You can see in the
above popup window that the ASP.Net development server has been started.
A WCF Service Library is not hosted by the ASP.Net development server. It is hosted by the Test Client, since a Service
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Library does not have .svc file.
21
If you want to host your service in IIS then you should select the WCF Service Application template and if you want to
host it as a Windows Service or set a reference of your library then you should select the WCF Service Library template.
Conclusion
The WCF Service Application template can be used to create WCF services with a hosting website created within the
project
The WCF Service Library template can be used to create WCF services that are hosted by the WCF Service Host, and these
can be tested using the WCF service Test Client.
Here we will discuss about serialization in WCF, including the default serializer in WCF and the various kinds of serializers
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
that WCF supports.
22
WCF provides a message-oriented programming framework. We use WCF to transmit messages between applications.
Internally WCF represents all the messages by a Message class. When WCF transmits a message it takes a logical message
object and encodes it into a sequence of bytes. After that WCF reads those bytes and decodes them in a logical object.
The process forms a sequence of bytes into a logical object; this is called an encoding process. At runtime when WCF
receives the logical message, it transforms them back into corresponding .Net objects. This process is called serialization.
XMLSerializer
NetDataContractSerializer
DataContractSerializer
WCF desterilizes WCF messages into .Net objects and serializes .Net objects into WCF messages. WCF provides
DataContractSerializer by default with a servicecontract. We can change this default serializer to a custom serializer like
XMLSerializer.
[XmlSerializerFormat]
[ServiceContract]
public interface IService1
{
[OperationContract]
void AddAuthor(Author author);
}
The XmlSerializerFormat attribute above the ServiceContract means this serializer is for all operation contracts. You can
also set a separate contract for each operation.
Each serializer calls different algorithms for mapping between .Net object and WCF messages. And each serializer
produces a slightly different message.
We can use SvcUtil.exe to move between .Net types and XSD. We can export an XSD that describes what the serializer
expects and can import an XSD to product types for a specific serializer.
XMLSerializer
We can find XMLSerializer in the System.Xml.Serialization namespace. WCF supports this serialization from .Net 1.0. It is
used by default with the ASP.Net webservices (ASMX).
Usage
We can use this serializer whenever we want to get backward compatibility with ASMX.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
It can also be used when integrating with non WCF Services.
23
NetDataContractSerializer
NetDataContractSerializer is analogous to .Net Remoting Formatters. It implements IFormatter and it is compatible with
[Serializable] types. It is not recommended for service oriented design.
Usage
DataContractSerializer
DataContractSerializer is a default serializer for WCF. We need not to mention DataContractSerializer attribute above the
service contract.
Usage
In my next article we will see step-by-step implementation of DataContractSerializer and code demonstration.
7 WCF Serialization
Introduction
Create an application, in this application we use a DataContractSerializer to serialize and deserialize data. We also see
how we can use SvcUtil.exe.
Select "WCF Service Library" and give a proper name, for example "AuthorSerializationLibrary".
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
24
Create one DataContract in the Interface i.e. IService1.cs using the following code:
namespace AuthorServiceLibrary
{
[ServiceContract]
public interface IService1
{
}
[DataContract]
public class Author
{
[DataMember]
public string FirstName;
[DataMember]
public string LastName;
[DataMember]
public DateTime StartDate;
[DataMember]
public string ArticleName;
}
}
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
I have not created an operation contract. So there is no code in the service class.
25
namespace AuthorServiceLibrary
{
public class Service1 : IService1
{
}
}
Now right-click on the Solution file and select Add >> New Project, as in:
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
26
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
27
One more time right-click on references and select "Add Reference", as in:
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
28
Import the System.Runtime.Serialization namespace into the console application "AuthorSerialization"; see:
Create a static function to serialize data in the program.cs file of "AuthorSerialization" using:
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
DataContractSerializer dcSerializer = new DataContractSerializer(typeof(Author));
dcSerializer.WriteObject(fs, author); 29
}
}
In the preceding Serialize function we create an object of the Author class and assign some values to each field. We
create a .xml file using a FileStream object. After that we serialize the class using DataContractSerializer and write into the
.xml file.
Create one more function to deserialize the data under the preceding function; the code is:
In the preceding code we open author.xml with the help of a FileStream object. We create an object of
DataContractSerializer and read the file.
In the preceding code we check the length of args and args equal to ds, if it fulfills the condition then call the Deserialize
function and if not then call the Serialize function. In other words if you want to call the Deserialize function then pass
"ds" as an argument .
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
30
Now you will see in the output window that "Build: 2 succeeded or up-to-date".
Now navigate to the path where you created your AuthorSerialization application. Navigate to bin and in that go to
debug.
Run the command dir, it will show all files and directories contained in the debug folder.
Run AuthorSerialization.exe.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Once you have executed it successfully, run the dir command.
31
You will see that an author.xml file has been created.
Here in author.xml "Author" is a root element because we declared a DataContract with this name. In this element you
can see ArticleName, FirstName, LastName, StartDate and their values which we have
supplied. The very important thing you can observe is that all elements in the author element is in alphabetical order.
Here we are not setting the order attribute so by default the DataContract is generated in alphabetical order.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
32
Previously we ran AuthorSerialization.exe without a parameter i.e. we do a serialization process; now the deserialize
method is called. For that run AuthorSerialization.exe with the "ds" parameter.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
33
Now with the same svcutil generate the .cs file. You can see in the command prompt.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17020
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AuthorServiceLibrary
{
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
using System.Runtime.Serialization;
34
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name = "Author", Namespace =
"http://schemas.datacontract.org/2004/07/AuthorServiceLibrary")]
public partial class Author : object, System.Runtime.Serialization.IExtensibleDataObject
{
[System.Runtime.Serialization.DataMemberAttribute()]
public string ArticleName
{
get
{
return this.ArticleNameField;
}
set
{
this.ArticleNameField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string FirstName
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
{
get 35
{
return this.FirstNameField;
}
set
{
this.FirstNameField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string LastName
{
get
{
return this.LastNameField;
}
set
{
this.LastNameField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public System.DateTime StartDate
{
get
{
return this.StartDateField;
}
set
{
this.StartDateField = value;
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name = "Service1", Namespace =
"http://schemas.datacontract.org/2004/07/AuthorServiceLibrary")]
public partial class Service1 : object, System.Runtime.Serialization.IExtensibleDataObject
{
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
public System.Runtime.Serialization.ExtensionDataObject ExtensionData
{ 36
get
{
return this.extensionDataField;
}
set
{
this.extensionDataField = value;
}
}
}
}
Discuss about two approaches of WCF i.e. Opt-In and Opt-Out used by DataContractSerializer and XMLSerializer. We will
also see the difference between DataContractSerializer and XMLSerializer.
Opt-Out Approach
In this approach, members are assumed to be serialized except we mention it as NonSerialized. XMLSerializer uses this
approach.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
37
In the above example, we set the Serializable attribute to the Author class. In other words all class members are going to
be serialized but suppose we do not want to serialize the article member then set the NonSerialized attribute on article
member. In this case only the firstname and lastname are serialized.
Opt-In Approach
In this approach we need to specify each member, which we want to serialize. For example we want to serialize the
firstname and lastname, not an article member then we need to set the DataMember attribute to the firstname and
lastname.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
38
In the above code snippet you can see that we are not applying the DataMember attribute to the Article member. That's
why this member is not serialized.
Now check this with svcutil.exe from the command prompt. It will generate an AuthorServiceLibrary.xsd file.
Check the result in the Notepad file. In this file you will see only FirstName and LastName. The Article member is not
serialized.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
39
DataContractSerializer
DataContractSerializer uses the Opt-In approach. This approach serializes properties as well as fields. We can serialize
protected and private members also. The DataContractSerializer is faster than XMLSerializer because we don't have full
control over serialization.
XMLSerializer
XMLSerializer uses The Opt-Out approach. This approach serializes properties only and it must be a public. It cannot
understand the DataContractSerializer attribute. It will not serialize unless we apply the serializable attribute.
Conclusion
The DataContractSerializer is always able to serialize to XML, but it is for very small and simple XML. It focuses on speed
instead of on being comprehensive. And XMLSerializer is used for comprehensive XML schemas.
In WCF services, a DataContract enables us to define the structure of the data. This data is sent in the body of our SOAP
(Simple Object Access Protocol) messages. These messages may be of either inbound (request) or outbound (response)
type. A message is nothing but a packet and WCF uses this packet to transfer information from source to destination.
This message contains an envelope, header and body.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
40
A Message Contract is used to control the structure of a message body and serialization process. It is also used to send /
access information in SOAP headers.
MessageContractAttribute
MessageHeaderAttribute
MessageBodyMemberAttribute
MessageContractAttribute
The MessageContract Attribute is applied to a class or structure to define our own message structure, as in:
[MessageContract()]
public class AuthorRequest
{
Properties of MessageContractAttribute
HasProtectionLevel gets a value that indicates whether the message has a protection level.
It returns true if the message must be encrypted, signed, or both; otherwise false. The default is false.
IsWrapped gets or sets a value that specifies whether the message body has a wrapper element.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
It returns true if the message body has a wrapper element; otherwise, false. The default is true. 41
ProtectionLevel gets or sets a value that specified whether the message must be encrypted, signed, or both.
WrapperName gets or sets the name of the wrapper element of the message body.
WrapperNamespace gets or sets the namespace of the message body wrapper element.
[MessageContract(IsWrapped = false,ProtectionLevel=ProtectionLevel.None)]
MessageHeaderAttribute
MessageHeaderAttribute is applied to the members of the MessageContract to declare the members within the message
header; see:
[MessageContract(IsWrapped = false,ProtectionLevel=ProtectionLevel.None)]
public class AuthorRequest
{
[MessageHeader()]
public string AuthorId;
}
Properties of MessageHeaderAttribute
Name specifies the name of the element that corresponds to this member.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
It returns the name of the element that corresponds to this member. This string must be a valid XML element
name. 42
Namespace specifies the namespace of the element that corresponds to this member.
ProtectionLevel specifies whether the member is to be transmitted as-is, signed, or signed and encrypted.
Actor gets or sets a URI that indicates the node at which this header is targeted. It maps to the role header
attribute when SOAP 1.2 is used and the actor header attribute when SOAP 1.1 is used.
It returns a URI that indicates the node at which this header is targeted. This URI maps to the role header
attribute when SOAP 1.2 is used and the actor header attribute when SOAP 1.1 is used.
Relay specifies whether this header is to be relayed to downstream nodes. This is mapped to the relay SOAP
header attribute.
MessageBodyMemberAttribute
MessageBodyMemberAttribute is applied to the members of message contracts to declare the members within the
message body.
Properties of MessageBodyMemberAttribute
Name, Namespace, ProtectionLevel and Order are the properties of MessageBodyMemberAttribute. As we are now
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
familiar with all the properties, I am not explaining here once again.
43
Why should we use MessageContract
Suppose we are not using MessageContract in our service, by default SOAP body element contains a child wrapper
element of operation name and wraps parameters. If there is no parameter then this element will be empty in the
inbound (request) message. In the same way, in an outbound (response) message, if it is of type void or say nothing to
return then this element will be empty.
For example we create a service and set MessageContract with the property IsWrapped to false. Then there is no child
element in the SOAP body. You will see a collection of MessageBodyMembers directly under the SOAP body within the
MessageContract.
Controlling wrapping is important when we deal with the other platforms except WCF because they might serialize their
SOAP messages differently.
Sample Code
Consider a scenario where we create a service and in this service we have one operation contract which returns the
author information. Now we want to set some authentication like AuthorId should be
matched. In this case we store AuthorId in MessageHeader because it is safe. Here we create two MessageContracts, one
is for the request i.e. AuthorRequest and another is for the response i.e. AuthorResponse.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
44
Now add an implementation of the above operation contract in the service class.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
45
SOAP Request
An AuthorIdentity element is in the SOAP request as we pass this under the MessageHeader. And the Body element is
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
empty because we are not passing any value.
46
SOAP Response
In response we get author information directly under the body element as we set IsWrapped to false.
Now change the code, set IsWrapped to true in the MessageContract and once again check the result in Test Client.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
SOAP Request
47
AuthorRequest element is empty and is added under the body element because we set IsWrapped to true.
SOAP Response
In the same way in the response also the AuthorResponse element is added under the body element.
Conclusion
I explained the IsWrapped property with an example. You can download the source code and check the output by
changing other properties values. The ProtectionLevel property is very important and we will discuss it later on in future
articles.
Endpoint
An Endpoint is a piece of information that tells WCF how to build the runtime communication channels to send and
receive messages. An endpoint consists of the three things address, binding and contract.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
48
Address
An Address is a unique Uniform Resource Locator (URI) that identifies the location of the service. It defines the network
address for sending and receiving the messages. It is divided into four parts:
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Binding 49
A Binding specifies which transport protocol to use, what message format and which any of the ws* protocols we want to
use to a particular endpoint.
BasicHttpBinding
Replacement for earlier Web Service based on ASMX (Active Server Methods)
Supports:
o HTTP - Hypertext Transfer Protocol
o HTTPS - Hypertext Transfer Protocol over SSL
o MTOM - Message Transmission Optimization Mechanism encoding methods.
wsHttpBinding
Uses SOAP over HTTP and supports reliability, transactions and security over the internet.
Supports:
wsDualHttpBinding
webHttpBinding
Sends information directly over HTTP or HTTPS without creating a SOAP envelope
It is a good choice when SOAP is not required by the client
NetTcpBinding
NetPeerTcpBinding
netNamedPipeBinding
Contract
A Contract provides the additional detail about the structuring contents of the various messages that will be used by the
various operations exposed to the particular endpoints. For example we create a service "TopupService", the interface
used to define the service is "ITopupService" and the project name is "Utility". The contract for this service would be
Utility.ITopupService.
Introduction
Here we will see how to configure a service using a XML-based configuration file i.e. web.config. We will also see
definition of endpoints, multiple endpoints and publishing metadata.
To understand service configuration, first create a new project using the WCF Service Application template. Once you
have completed the service application creation part, open the web.config file. The configuration information for a service
is contained within a system.servicemodel element in the web.config file. Under the first level of the system.servicemodel
element, there are behaviours, bindings and services. We can define various behaviours like endpoint behaviours and
servicebehaviors under the behaviours element. In the binding section different bindings like basicHttpBinding,
wsHttpBinding etc. In our example we define basicHttpBinding. Under the services element, there is a service element
and under this element we can define endpoints. We must specify at least one endpoint, otherwise we will get an error
during runtime.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
51
system.serviceModel is a root element of all WCF configuration elements. The configuration information for a
service is contained within a system.servicemodel element.
<behaviors> Element
<endpointBehaviors>
This configuration section represents all the behaviors defined for a specific endpoint.
<serviceBehaviors>
This configuration section represents all the behaviors defined for a specific service.
<bindings> Element
The element contains the specifications for all bindings that can be used by any endpoint defined in any service.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
<basicHttpBinding>
52
This element represents a binding that a WCF service can use to configure and expose endpoints.
<binding>
The binding element can be a system provided binding or can be a custom binding.
<services> Element
The services element contains the specifications for all services the application hosts.
<service>
This element contains two attributes, name and behaviorConfiguration. The Name specifies the type that
provides an implementation of the ServiceContract and behaviorConfiguration specifies the name of the
behaviour elements found in the behaviors element.
<endpoint>
Endpoint requires address, binding and contract. We have already seen these in my previous article.
Multiple Bindings
In the preceding example we are defining a single binding i.e. basicHttpBinding. Now you may ask, can we define
multiple bindings? The answer is yes, we can define multiple bindings for different clients. To define multiple bindings we
need to define multiple endpoints.
When creating multiple endpoints, we should remember that the address should be unique. If the two endpoints use the
same address, an error will be thrown at runtime.
You can define the same address when you have a service that uses two interfaces. Here you can have two endpoints
with the same address, but the contract name must be different.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Base Address 53
In the preceding example we specify an address as an absolute address. It is a very easy method to understand. We can
also specify a relative address. When we are using multiple endpoints then it is an efficient approach to specify the
relative address method.
Specify the base address under the host element for each service. We can also add multiple base addresses by using the
add method.
In the previous example we define multiple endpoints and there is an address like
"http://localhost:8000/BindingConfigService". This portion of address is common in the first two endpoints. So we can set
this common portion as the base address under the host element.
Publishing Metadata
We can publish service metadata using the HTTP-GET protocol. To expose this metadata we need to create a metadata
exchange endpoint. This endpoint can append "mex" to the HTTP address. The endpoint uses mex as the address,
mexHttpBinding as the binding and IMetadataExchange interface as a contract. We also need to set the attribute of the
servicemetadata i.e. HttpGetEnabled to true in the servicebehaviors.
The client can access this metadata using a HTTP-GET request with a ?wsdl query string appended.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
54
Conclusion
It is normally a good practice to use a configuration file when specifying endpoints because we can make changes in
endpoints without a code recompile.
Let us configure a WCF Service using the WCF Service Configuration Editor.
Open the Visual Studio editor and select "File" -> "New" -> "Project...". Select the WCF Service Library from the template
and provide an appropriate name for it.
In the web.config file you can see under the system.serviceModel element, there are two endpoints specified. One is for
wsHttpBinding and another is to expose metadata using the IMetadataExchange interface. The base address is also
specified under the host element. In service behavior with the serviceMetadata element set httpGetEnabled attribute to
true. This is the default configuration in the WCF Service Library.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
55
Right-click on App.config and select Edit WCF Configuration to open the WCF Configuration Editor.
The WCF Service configuration information is contained under the system.servicemodel element. So now check how this
configuration is shown in the configuration editor.
Endpoints
App.config
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
56
Configuration Editor
Base Address
App.config
Configuration Editor
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
57
Service Behavior
App.config
Configuration Editor
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
58
There are two approaches to add a new endpoint using this configuration editor. Use the following to create a new
endpoint.
Approach 1
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
In the general tab, insert the address as "basic" and select "basicHttpBinding" for the binding. For contract click on the 59
button which is available on the right side.
This will add a contract to your binding. Now you will see an address, binding and contract for basicHttpBinding.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
60
Now click on services and it will show endpoints for the service, as in:
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
61
Here you will see that one more endpoint is added, as the one covered in an orange rectangle in the image.
Approach 2
On the preceding image, there is a link "Create New Service Endpoint€¦" to create a new endpoint. So click on this link.
The Contract is selected by default. Now click on the "Next" button.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
62
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
63
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
64
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
65
It will show an address, binding and contract for netTcpBinding, which we just created.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
66
Click on services, which now shows one more binding i.e. netTcpBinding; see:
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
67
We have exposed two more endpoints i.e. for basicHttpBinding and netTcpBinding. Now go to the file menu and save
these changes. Now open the app.config file. It will reflect all the changes done through the configuration editor.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
68
Select host under the services and in the bottom-right side there are buttons to add new base addresses and to update
base addresses. You can select any according to your requirement. After creating or changing the base address, save
these changes and check in the app.config file for reflection of these changes.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
69
Go to the Advanced section and select Service Behavior. On the right panel click on the link "New Service Behavior
Configuration".
Give the configuration name as "Metadata" and click on the "Add" button
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
70
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
71
Now select "serviceMetadata" from the left panel and set the "HttpGetEnabled" attribute to true.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
72
The "Metadata" behavior is created now. The next step is to assign this behavior to a service. For that select the service
"EditConfigurationServiceLib.EditConfigurationService" and select a newly created behavior for the BehaviorConfiguration
attribute.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
73
Finally save the changes and check the app.config file for these changes.
©2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.