Upload
vijay-patil
View
224
Download
1
Embed Size (px)
Citation preview
7/26/2019 Learning WCF Practical Implementation
1/83
7/26/2019 Learning WCF Practical Implementation
2/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Learning WCF
Practical Implementation
ThisfreebookisprovidedbycourtesyofC#CornerandMindcrackerNetworkandits
authors.Feelfreetosharethisbookwithyourfriendsandco-workers.Pleasedonot
reproduce,republish,editorcopythisbook.
Akshay Patel
Microsoft Certified Professional
Sam Hobbs
Editor, C# Corner
http://www.c-sharpcorner.com/http://www.c-sharpcorner.com/7/26/2019 Learning WCF Practical Implementation
3/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Table of Contents
Chapter 1: Introductionof 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
7/26/2019 Learning WCF Practical Implementation
4/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
4.1 Data Contract
4.2 Data Contract Attribute
4.3 Properties of Data Contract Attribute
4.4 Data Member
4.5 Properties of Data Member Attribute
4.6 Sample code
Chapter 5: Difference between Service Application and service library
5.1 Introduction
5.2 Service Application Vs. Service Library
5.3 Summary
Chapter 6: Serialization
6.1 Introduction
6.2 Types of Serialization
6.2.1 XMLSerializer
6.2.2 NetDataContractSerializer
6.2.3 DataContractSerializer
6.3 Step-by-step implementation of DataContractSerializer
6.4 Summary
Chapter 7: Different Approach in WCF
7.1 Introduction
7.2 Opt-out Approach
7.3 Opt-in Approach
7.4 Data Contract Serializer
7.5 XML Serializer
7/26/2019 Learning WCF Practical Implementation
5/83
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
7/26/2019 Learning WCF Practical Implementation
6/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Chapter 1: Introductionof WCF and Contracts
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.
Difference between WCF and Web service
In a web service we need to add the [WebService] attribute to the class.
In WCF we need to add the [ServiceContract] attribute to the class.
Add the [WebMethod] attribute to the method in a web service.
Add the [OperationContract] attribute to the method in WCF.
For serialization in a web service use the System.Xml.serialization namespace.
WCF uses the System.Runtime.Serialization namespace for serialization.
7/26/2019 Learning WCF Practical Implementation
7/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
We can host a web service in IIS.
We can host WCF in IIS, WAS (Windows Activation Service), self-hosting and a Windows
Service .
Description using help of example
Let's see the basics terminology used WCF service application step-by-step.
Step 1
Start Menu >> All Programs >> Microsoft Visual Studio 2010 >> Microsoft Visual Studio 2010
In that "File" >> "New" >> "Project..."
Step 2
Select WCF from Installed Templates
Select .NET Framework 4 from dropdownlist Select WCF Service Application
Give desired name and select the location
7/26/2019 Learning WCF Practical Implementation
8/83
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:
7/26/2019 Learning WCF Practical Implementation
9/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
In this file you willl find a ServiceContract, OperationContract and DataContract.
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.
7/26/2019 Learning WCF Practical Implementation
10/83
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.
WCF Contracts map directly to a corresponding web services standard:
ServiceContracts map to WSDL
DataContracts map to XSD
MessageContracts map to SOAP
Step 4
There is one method "GetData" which accepts parameters of type int.
7/26/2019 Learning WCF Practical Implementation
11/83
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.
7/26/2019 Learning WCF Practical Implementation
12/83
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.
7/26/2019 Learning WCF Practical Implementation
13/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Chapter 2: Fault Contract
Introduction
This chapter explains fault contracts in Windows Communication Foundation. It also explains thedifference 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. Lets
us try to understand the fault contract with the help of 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 isthrown 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.
FaultException
A FaultException is used to send untyped fault data to the client.
FaultException
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]
publicinterfaceIService1
{
[OperationContract]
[FaultContract(typeof(FaultInfo))]
stringTopup(stringOperator, stringMobileNumber, doubleAmount);
}
[DataContract()]
publicclassFaultInfo
{
[DataMember()]
7/26/2019 Learning WCF Practical Implementation
14/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
publicstringReason = 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 wecreate 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.
publicstringTopup(stringOperator, stringMobileNumber, doubleAmount)
{
if(Amount == 0.0d)
{
FaultInfofi = newFaultInfo();
fi.Reason = "Amount should not be in double.";
thrownewFaultException(fi,newFaultReason(fi.Reason));
}
return"Recharge Successful.";
}
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.
Faults Vs. Exceptions
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
Summary
This chapter explains FaultException and the difference between faults and exceptions. It also
explains the sample code to implement fault exceptions. You can download the code and check
the application.
7/26/2019 Learning WCF Practical Implementation
15/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Chapter 3: Message Exchange Pattern
Introduction
This chapter explains exchange patterns. Various types of message exchange patterns and codedemonstration for each message exchange pattern.
MEPs (Message Exchange Pattern)
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:
Request / Response One-Way
Duplex
Now let us see each with an example.
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 chapter.
[ServiceContract]
publicinterfaceIService1
{
[OperationContract]
stringGetTransaction(intvalue);
}
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
7/26/2019 Learning WCF Practical Implementation
16/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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]
publicinterfaceIService1{
[OperationContract]
voidDoTransaction(stringvalue);
}
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]
publicinterfaceIService1
{
[OperationContract(IsOneWay=true)]
voidChangeTransactionStatus(intvalue);
}
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.
7/26/2019 Learning WCF Practical Implementation
17/83
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.
namespaceWcfService1{
[ServiceContract]
publicinterfaceITransactionHandler
{
[OperationContract(IsOneWay=true)]
voidTransactionDone(intvalue);
}
[ServiceContract(CallbackContract = typeof(ITransactionHandler))]
interfaceITransactionService
{
[OperationContract(IsOneWay = true)]
voidDoTransaction(stringvalue);
}
}
publicclassTransactionService: ITransactionService
{
publicvoidDoTransaction(stringvalue)
{intTransactionId = 1;//Get TransactionId from database
ITransactionHandlercallbackHandler
=OperationContext.Current.GetCallbackChannel();
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.
7/26/2019 Learning WCF Practical Implementation
18/83
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.
7/26/2019 Learning WCF Practical Implementation
19/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Chapter 4: Data Contract
DataContract
Data contracts are the conceptual agreement of the format and structure of the data in themessage 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
The DataContractAttribute is defined in the System.Runtime.Serialization namespace. It is used to
declare a type as a DataContract.
Properties of DataContractAttribute
Name: It determines the type name as it is generated in the resulting schema.
Namespace: It sets the target namespace of the schema.
7/26/2019 Learning WCF Practical Implementation
20/83
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
7/26/2019 Learning WCF Practical Implementation
21/83
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.
namespaceDataContractServiceApp
{
[ServiceContract]publicinterfaceIService1
{
[OperationContract]
PlaceGetPlace(stringPlaceCode);
}
[DataContract(Name ="Place", Namespace ="")]
publicclassPlace
{
[DataMember(Name ="PlaceCode", Order = 1, IsRequired=true)]
publicstringPlaceCode;
[DataMember(Name ="PlaceName", Order = 2)]
publicstringPlaceName;
}
7/26/2019 Learning WCF Practical Implementation
22/83
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.
namespaceDataContractServiceApp
{
publicclassService1: IService1
{
publicPlaceGetPlace(stringPlaceCode)
{
Placeplace = newPlace();
// Get placename by placecode from database.
returnplace;
}
}
}
7/26/2019 Learning WCF Practical Implementation
23/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Chapter 5: Difference between Service Application and service
library
Introduction
This chapter explains the difference between a Service Application and a Service Library. It also
explains where we should use Service Applications and where to use a Service Library.
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.
Application Vs, Service Library
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 youcreate 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.
7/26/2019 Learning WCF Practical Implementation
24/83
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
7/26/2019 Learning WCF Practical Implementation
25/83
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.
7/26/2019 Learning WCF Practical Implementation
26/83
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.
7/26/2019 Learning WCF Practical Implementation
27/83
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.
7/26/2019 Learning WCF Practical Implementation
28/83
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 thevarious 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.
WCF supports three basic serializers:
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]
publicinterfaceIService1
{
[OperationContract]
voidAddAuthor(Authorauthor);
}
The XmlSerializerFormat attribute above the ServiceContract means this serializer is for all
operation contracts. You can also set a separate contract for each operation.
7/26/2019 Learning WCF Practical Implementation
29/83
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 specificserializer.
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
It is used when we have WCF services at both sides.
It is easier when we want to migrate .Net remoting applications.
DataContractSerializer
DataContractSerializer is a default serializer for WCF. We need not to mention
DataContractSerializer attribute above the service contract.
Usage
Used by default unless we specify otherwise.
It is the best choice for code-first designs.
In my next chapter we will see step-by-step implementation of DataContractSerializer and code
demonstration.
7/26/2019 Learning WCF Practical Implementation
30/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Step-by-step implementation of DataContractSerializer
File -> New -> Project
Select "WCF" from Installed Templates.
Select "WCF Service Library" and give a proper name, for example "AuthorSerializationLibrary".
Create one DataContract in the Interface i.e. IService1.cs using the following code:
7/26/2019 Learning WCF Practical Implementation
31/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
namespaceAuthorServiceLibrary
{
[ServiceContract]
publicinterfaceIService1
{
}
[DataContract]
publicclassAuthor
{
[DataMember]
publicstringFirstName;
[DataMember]
publicstringLastName;
[DataMember]
publicDateTimeStartDate;
[DataMember]
publicstringArticleName;
}
}
I have not created an operation contract. So there is no code in the service class.
namespaceAuthorServiceLibrary
{
publicclassService1: IService1
{
}
}
Now right-click on the Solution file and select Add >> New Project, as in:
7/26/2019 Learning WCF Practical Implementation
32/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Select "Windows" from the Installed Templates.
Select "Console Application" and give it the name "AuthorSerialization", as in:
Add a reference for "AuthorServiceLibrary" into "AuthorSerialization".
7/26/2019 Learning WCF Practical Implementation
33/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Right-click on "References" in AuthorSerialization and select "Add Reference...", as in:
Select "AuthorServiceLibrary" from the Projects tab.
Press the "OK" button.
One more time right-click on references and select "Add Reference", as in:
7/26/2019 Learning WCF Practical Implementation
34/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Select "System.Runtime.Serialization" from the .NET tab, as in:
Import the System.Runtime.Serialization namespace into the console application
"AuthorSerialization"; see:
7/26/2019 Learning WCF Practical Implementation
35/83
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:
staticvoidSerialize()
{
Authorauthor = newAuthor();
author.FirstName = "Akshay";
author.LastName = "Patel";
author.StartDate = DateTime.Now;author.ArticleName = "WCF - Serialization - Day 6";
using(FileStreamfs = newFileStream("author.xml", FileMode.Create))
{
DataContractSerializer dcSerializer = newDataContractSerializer (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:
staticvoidDeserialize()
{
using(FileStreamfs = newFileStream("author.xml", FileMode.Open))
{
DataContractSerializer dcSerializer = newDataContractSerializer (typeof(Author));
Authorauthor = dcSerializer.ReadObject(fs) asAuthor;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
7/26/2019 Learning WCF Practical Implementation
36/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
object of DataContractSerializer and read the file.
Add the following lines of code in the main function:
staticvoidMain(string[] args){
if(args.Length > 0 && args[0].Equals("ds"))
Deserialize();
else
Serialize();
}
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 .
Now build the console application "AuthorSerialization".
For that right-click on the AuthorSerialization project and select "Build".
Now you will see in the output window that "Build: 2 succeeded or up-to-date".
Open a Visual Studio Command Prompt; see:
7/26/2019 Learning WCF Practical Implementation
37/83
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.
7/26/2019 Learning WCF Practical Implementation
38/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Now open the author.xml file in Internet Explorer.
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.
7/26/2019 Learning WCF Practical Implementation
39/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
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.
Now generate a XSD of our DataContract with the help of svcutil.exe.
Run the following command: svcutil /dconly AuthorServiceLibrary.dll
In the above command "dconly" means DataContract only.
Once you run this command, it will generate a .xsd file.
Now open AuthorServiceLibrary.xsd in notepad.
7/26/2019 Learning WCF Practical Implementation
40/83
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.
Now open the AuthorServiceLibrary.cs file in Notepad.
This is our original code generated back by the tool.
//------------------------------------------------------------------------------
//
// 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.
//
7/26/2019 Learning WCF Practical Implementation
41/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
//------------------------------------------------------------------------------
namespaceAuthorServiceLibrary
{
usingSystem.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")]
publicpartialclassAuthor: object, System.Runtime.Serialization.IExtensibleDataObject
{
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
privatestringArticleNameField;
privatestringFirstNameField;
privatestringLastNameField;
privateSystem.DateTimeStartDateField;
public System.Runtime.Serialization.ExtensionDataObject ExtensionData
{
get
{
returnthis.extensionDataField;
}
set
{
this.extensionDataField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()] publicstringArticleName
{
get
{
returnthis.ArticleNameField;
7/26/2019 Learning WCF Practical Implementation
42/83
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()]
publicstringFirstName
{
get
{
returnthis.FirstNameField;
}
set
{
this.FirstNameField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringLastName
{
get
{
returnthis.LastNameField;}
set
{
this.LastNameField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicSystem.DateTimeStartDate
{
get
{
returnthis.StartDateField;
}
set
7/26/2019 Learning WCF Practical Implementation
43/83
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")]
publicpartialclassService1: object, System.Runtime.Serialization.IExtensibleDataObject
{
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
public System.Runtime.Serialization.ExtensionDataObject ExtensionData
{
get
{
returnthis.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.
7/26/2019 Learning WCF Practical Implementation
44/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Chapter 7: Different Approach in WCF
Introduction
In this chapter we will discuss two approaches 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.
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.
7/26/2019 Learning WCF Practical Implementation
45/83
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.
7/26/2019 Learning WCF Practical Implementation
46/83
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 bea public. It cannot understand the DataContractSerializer attribute. It will not serialize unless we
apply the serializable attribute.
Summary
7/26/2019 Learning WCF Practical Implementation
47/83
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.
7/26/2019 Learning WCF Practical Implementation
48/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Chapter 8: Message Contract
Introduction
In this chapter we will discuss Message Contracts. We will also discuss
MessageContractAttriubtes, MessageHeaderAttriubtes, MessageBodyMemberAttriubtes and a
sample code demonstration.
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.
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
7/26/2019 Learning WCF Practical Implementation
49/83
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()]
publicclassAuthorRequest
{
}
Properties of MessageContractAttribute
public bool HasProtectionLevel { get; }
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.
public bool IsWrapped { get; set; }
IsWrapped gets or sets a value that specifies whether the message body has a wrapper
element.
It returns true if the message body has a wrapper element; otherwise, false. The default is
true.
public ProtectionLevel ProtectionLevel { get; set; }
ProtectionLevel gets or sets a value that specified whether the message must be
encrypted, signed, or both.
It returns one of the System.Net.Security.ProtectionLevel values. The default is
System.Net.Security.ProtectionLevel.None.
public string WrapperName { get; set; }
WrapperName gets or sets the name of the wrapper element of the message body.
7/26/2019 Learning WCF Practical Implementation
50/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
It returns the name of the wrapper element in the message body.
public string WrapperNamespace { get; set; }
WrapperNamespace gets or sets the namespace of the message body wrapper element.
It returns the wrapper element namespace.
For example:
[MessageContract(IsWrapped = false,ProtectionLevel=ProtectionLevel.None)]
publicclassAuthorRequest
{
}
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)]
publicclassAuthorRequest
{
[MessageHeader()]publicstringAuthorId;
}
Properties of MessageHeaderAttribute
public string Name { get; set; }
Name specifies the name of the element that corresponds to this member.
It returns the name of the element that corresponds to this member. This string must be avalid XML element name.
public string Namespace { get; set; }
Namespace specifies the namespace of the element that corresponds to this member.
7/26/2019 Learning WCF Practical Implementation
51/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
It returns a namespace URI of the element that corresponds to this member.
public ProtectionLevel ProtectionLevel { get; set; }
ProtectionLevel specifies whether the member is to be transmitted as-is, signed, or signed
and encrypted.
It returns one of the System.Net.Security.ProtectionLevel values. The default is
System.Net.Security.ProtectionLevel.None.
public string Actor { get; set; }
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 whenSOAP 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.
public bool MustUnderstand { get; set; }
MustUnderstand specifies whether the node acting in the
System.ServiceModel.MessageHeaderAttribute.Actor role must understand this header.
This is mapped to the mustUnderstand SOAP header attribute.
It returns true if the node acting in the
System.ServiceModel.MessageHeaderAttribute.Actor role must understand this header;
otherwise, false.
public bool Relay { get; set; }
Relay specifies whether this header is to be relayed to downstream nodes. This is mapped
to the relay SOAP header attribute.
It returns true if this header is to be relayed to downstream nodes; otherwise, false.
MessageBodyMemberAttribute
MessageBodyMemberAttribute is applied to the members of message contracts to declare the
7/26/2019 Learning WCF Practical Implementation
52/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
members within the message body.
Properties of MessageBodyMemberAttribute
Name, Namespace, ProtectionLevel and Order are the properties ofMessageBodyMemberAttribute. As we are now familiar with all the properties, I am not
explaining here once again.
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 contractwhich 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.
While creating a MessageContract consider the following two points:
When we pass a parameter of type MessageContract, only one parameter is used in the
service operation.
7/26/2019 Learning WCF Practical Implementation
53/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
The return type of the OperationContract is of MessageContractType or Void type.
1.
Now add the following lines of code to your Interface.
7/26/2019 Learning WCF Practical Implementation
54/83
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.
7/26/2019 Learning WCF Practical Implementation
55/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Test Client Output (IsWrapped = false)
Insert 'db2972' as the input for the AuthorIdentity parameter; see:
SOAP Request
An AuthorIdentity element is in the SOAP request as we pass this under the MessageHeader. And
7/26/2019 Learning WCF Practical Implementation
56/83
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.
Test Client Output (IsWrapped = true)
Now change the code, set IsWrapped to true in the MessageContract and once again check the
result in Test Client.
7/26/2019 Learning WCF Practical Implementation
57/83
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.
7/26/2019 Learning WCF Practical Implementation
58/83
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.
7/26/2019 Learning WCF Practical Implementation
59/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Chapter 9: Address Binding and Contract
Introduction
In this chapter we will discuss endpoints which consists of Address, Binding and Contract.
In previous chapter we have seen about ServiceContract, OperationContract and implementation
of these in service class. In this implementation we write business logic. Services expose
endpoints to the world. There may be multiple endpoints in a service. Endpoints define
communication options.
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
7/26/2019 Learning WCF Practical Implementation
60/83
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
7/26/2019 Learning WCF Practical Implementation
61/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
o MTOM - Message Transmission Optimization Mechanism encoding methods.
wsHttpBinding
Uses SOAP over HTTP and supports reliability, transactions and security over the internet. Supports:
o HTTP - Hypertext Transfer Protocol
o HTTPS - Hypertext Transfer Protocol over SSL
o MTOM - Message Transmission Optimization Mechanism encoding methods.
wsDualHttpBinding
Used for duplex service contract because it supports bidirectional communication.
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
Used to send binary-encoded SOAP messages from one computer to another
Uses TCP (Transmission Control Protocol) and includes support for reliability, transactions
and security
NetPeerTcpBinding
Used for peer-to-peer communication over TCP
Communication should occur between two or more computers
netNamedPipeBinding
Binary encoded SOAP messages are sent over named pipes
Used on a single WCF computer
netMSMQBinding
Queued binding is used to send binary-encoded SOAP messages over MSMQ
Communication should occur between two computers
7/26/2019 Learning WCF Practical Implementation
62/83
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" andthe project name is "Utility". The contract for this service would be Utility.ITopupService.
7/26/2019 Learning WCF Practical Implementation
63/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Chapter 10: Service Configuration
Introduction
In this chapter 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
behaviors, bindings and services. We can define various behaviors like endpoint behaviors and
servicebehaviors under the behaviors 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. Wemust specify at least one endpoint, otherwise we will get an error during runtime.
The Element
system.serviceModel is a root element of all WCF configuration elements. The
configuration information for a service is contained within a system.servicemodel element.
Element
7/26/2019 Learning WCF Practical Implementation
64/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
This configuration section represents all the behaviors defined for a specific endpoint.
This configuration section represents all the behaviors defined for a specific service.
Element
The element contains the specifications for all bindings that can be used by any endpoint defined
in any service.
This element represents a binding that a WCF service can use to configure and expose
endpoints.
The binding element can be a system provided binding or can be a custom binding.
Element
The services element contains the specifications for all services the application hosts.
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 requires address, binding and contract. We have already seen these in myprevious chapter.
Multiple Bindings
7/26/2019 Learning WCF Practical Implementation
65/83
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.
7/26/2019 Learning WCF Practical Implementation
66/83
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 needto 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.
7/26/2019 Learning WCF Practical Implementation
67/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Configuration using Configuration Editor
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.
7/26/2019 Learning WCF Practical Implementation
68/83
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
7/26/2019 Learning WCF Practical Implementation
69/83
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
7/26/2019 Learning WCF Practical Implementation
70/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Configuration Editor
Service Behavior
App.config
7/26/2019 Learning WCF Practical Implementation
71/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Configuration Editor
How to add new endpoint?
There are two approaches to add a new endpoint using this configuration editor. Use the
following to create a new endpoint.
7/26/2019 Learning WCF Practical Implementation
72/83
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 navigate to the path "\bin\Debug\EditConfigurationServiceLib.dll" and select the contract.
7/26/2019 Learning WCF Practical Implementation
73/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
And click on the "Open" button.
This will add a contract to your binding. Now you will see an address, binding and contract for
basicHttpBinding.
Now click on services and it will show endpoints for the service, as in:
7/26/2019 Learning WCF Practical Implementation
74/83
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.
7/26/2019 Learning WCF Practical Implementation
75/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Select TCP and click on "Next" button, as in:
7/26/2019 Learning WCF Practical Implementation
76/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Specify the address in the address text box.
Click on the "Finish" button.
7/26/2019 Learning WCF Practical Implementation
77/83
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:
7/26/2019 Learning WCF Practical Implementation
78/83
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.
How to specify base address?
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.
7/26/2019 Learning WCF Practical Implementation
79/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
How to set service behavior?
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.
7/26/2019 Learning WCF Practical Implementation
80/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Select "serviceMetadata" from different behaviors.
7/26/2019 Learning WCF Practical Implementation
81/83
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.
7/26/2019 Learning WCF Practical Implementation
82/83
2013 C# CORNER.
SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
7/26/2019 Learning WCF Practical Implementation
83/83
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.