Learning WCF Practical Implementation
Learning WCF Practical Implementation
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
Microsoft Certified Professional
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
Chapter 1: Introduction of WCF and Contracts
1.1 Introduction
1.2 What WCF is?
1.3 Difference between WCF and Web Service
1.4 Description using help of example
1.5 Service Contract
1.6 Data Contract
1.7 Summary
Chapter 2: Fault Contract
2.1 Introduction
2.2 Fault Contract
2.3 Fault Exceptions
2.4 Fault Vs. Exceptions
2.5 Summary
Chapter 3: Message Exchange Pattern
3.1 Introduction
3.2 Message Exchange Pattern
3.2.1 Request / Response
3.2.2 One-Way
3.2.3 Duplex
3.3 Summary
Chapter 4: Data Contract
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
7.6 Summary
Chapter 8: Message Contract
8.1 Introduction
8.2 Message Contract Attribute
8.2.1 Message Contract Attribute
8.2.2 Message Header Attribute
8.2.3 Message Body Member Attribute
8.3 Why we use Message Contract
8.4 Code Sample
8.5 Summary
Chapter 9: Address Binding and Contract
9.1 Introduction
9.2 Endpoint
9.3 Address
9.4 Binding
9.5 Contract
Chapter 10: Service Configuration
10.1 Introduction
10.2 Multiple Binding
10.3 Base Address
10.4 Publishing Metadata
10.5 Steps to configure the config file using configuration editor
10.6 Summary
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Introduction
This chapter demonstrates how to create a WCF service application. This chapter also covers
basic information of all the contracts and a code demonstration.
What WCF is?
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Step 2
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Click on OK button
Step 3
Now your Windows Communication Foundation service application is ready as a default service.
You will see in Solution Explorer Service1.svc and IService1.cs
Open the IService1.cs file, as in:
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
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.
Step 4
There is one method "GetData" which accepts parameters of type int.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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
Now let us run this service.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
Summary
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Request / Response
One-Way
Duplex
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);
}
Before using this pattern, keep following points in your mind
You cannot use FaultContract with this pattern. In my previous chapter we have seen
FaultContract. For FaultContract there 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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
Before using this pattern, keep the following points in mind.
In the real world this pattern is problematic because it requires a connection back to the client.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
Summary
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
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.
If you apply a data member attribute to both property and field, then it generates
duplicate members in the schema.
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);
}
[DataContract(Name ="Place", Namespace ="")]
public classPlace
{
[DataMember(Name ="PlaceCode", Order = 1, IsRequired=true)]
public string PlaceCode;
[DataMember(Name ="PlaceName", Order = 2)]
public string PlaceName;
}
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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();
// Get placename by placecode from database.
return place;
}
}
}
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
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
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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:
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
A WCF Service Library is not hosted by the ASP.Net development server. It is hosted by the Test
Client, since a Service Library does not have .svc file.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
Summary
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Chapter 6: Serialization
Introduction
In this chapter we will discuss serialization in WCF, including the default serializer in WCF and the
various kinds of serializers that WCF supports.
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 deserializes 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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
It can also be used when integrating with non WCF Services.
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
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Create one DataContract in the Interface i.e. IService1.cs using the following code:
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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;
}
}
I have not created an operation contract. So there is no code in the service class.
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Create a static function to serialize data in the program.cs file of "AuthorSerialization" using:
static void Serialize()
{
Author author = new Author();
author.FirstName = "Akshay";
author.LastName = "Patel";
author.StartDate = DateTime.Now;
author.ArticleName = "WCF - Serialization - Day 6";
using (FileStream fs = new FileStream("author.xml", FileMode.Create))
{
DataContractSerializer dcSerializer = new DataContractSerializer(typeof(Author));
dcSerializer.WriteObject(fs, author);
}
}
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:
static void Deserialize()
{
using (FileStream fs = new FileStream("author.xml", FileMode.Open))
{
DataContractSerializer dcSerializer = new DataContractSerializer(typeof(Author));
Author author = dcSerializer.ReadObject(fs) as Author;
Console.WriteLine("Name: {0}, Article: {1}", author.FirstName,author.ArticleName);
}
}
In the preceding code we open author.xml with the help of a FileStream object. We create an
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Now you will see in the output window that "Build: 2 succeeded or up-to-date".
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
Once you have executed it successfully, run the dir command.
You will see that an author.xml file has been created.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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. In my previous chapter we have seen the order attribute
of DataContract. 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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Now with the same svcutil generate the .cs file. You can see in the command prompt.
//-----------------------------------------------------------------------------namespace AuthorServiceLibrary
{
using System.Runtime.Serialization;
[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
{
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
private string ArticleNameField;
private string FirstNameField;
private string LastNameField;
private System.DateTime StartDateField;
public System.Runtime.Serialization.ExtensionDataObject ExtensionData
{
get
{
return this.extensionDataField;
}
set
{
this.extensionDataField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string ArticleName
{
get
{
return this.ArticleNameField;
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
}
set
{
this.ArticleNameField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
public string FirstName
{
get
{
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
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
{
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
{
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
public System.Runtime.Serialization.ExtensionDataObject ExtensionData
{
get
{
return this.extensionDataField;
}
set
{
this.extensionDataField = value;
}
}
}
}
Summary
In this chapter we have learned the serialization and different types of serialization like
XMLSerializer, NetDataContractSerializer and DataContractSerializer as well as we have learned
the implementation of DataContractSerializer.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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 chaptermember
then set the NonSerialized attribute on chaptermember. In this case only the firstname and
lastname are serialized.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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 chaptermember then we need to set the
DataMember attribute to the firstname and lastname.
In the above code snippet you can see that we are not applying the DataMember attribute to the
chaptermember. 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.
Open the AuthorServiceLibrary.xsd file in the Notepad.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Check the result in the Notepad file. In this file you will see only FirstName and LastName. The
chaptermember is not serialized.
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.
Summary
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
Message Contract Attributes
MessageContractAttribute
MessageHeaderAttribute
MessageBodyMemberAttribute
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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
For example:
[MessageContract(IsWrapped = false,ProtectionLevel=ProtectionLevel.None)]
public class AuthorRequest
{
}
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
MessageBodyMemberAttribute
MessageBodyMemberAttribute is applied to the members of message contracts to declare the
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
1.
Now add the following lines of code to your Interface.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
SOAP Request
An AuthorIdentity element is in the SOAP request as we pass this under the MessageHeader. And
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
the Body element is empty because we are not passing any value.
SOAP Response
In response we get author information directly under the body element as we set IsWrapped to
false.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
SOAP Request
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Summary
In this chapter I explained the IsWrapped property with an example. You can check the output by
changing other properties values. The ProtectionLevel property is very important and we will
discuss it later on in next chapter.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
Address
Address - Where - Where to send messages
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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:
Binding
Binding - How - How to send messages
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
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
wsHttpBinding
Uses SOAP over HTTP and supports reliability, transactions and security over the internet.
Supports:
o
o
o
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
netMSMQBinding
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
<behaviors> Element
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
<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.
<basicHttpBinding>
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 behavior elements found in the
behaviors element.
<endpoint>
Endpoint requires address, binding and contract. We have already seen these in my
previous chapter.
Multiple Bindings
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
Now let's see how to create multiple bindings.
Base Address
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
App.config
Configuration Editor
Base Address
App.config
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Configuration Editor
Service Behavior
App.config
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Configuration Editor
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Approach 1
Right-click on the Endpoints folder, select "New Service Endpoint".
In the general tab, insert the address as "basic" and select "basicHttpBinding" for the binding. For
contract click on the button which is available on the right side.
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.
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
It will show an address, binding and contract for netTcpBinding, which we just created.
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.
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.
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Now select "serviceMetadata" from the left panel and set the "HttpGetEnabled" attribute to true.
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.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Finally save the changes and check the app.config file for these changes.
Summary
In my previous chapter we have seen WCF service configurations using web.config and in this
chapter we covered the same thing except using the configuration editor.
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS. PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.