Introduction
Windows Communication Foundation (WCF) is an extension of the .NET
framework to build and run connected systems. Windows Communication
Foundation provides a unified framework for building secure and reliable
transacted Web services. Windows Communication Foundation combines and
extends the capabilities of Distributed Systems, Microsoft .NET
Remoting, Web Services, and Web Services Enhancements (WSE), to develop
and deliver unified secured systems. The WCF framework builds
loosely-coupled applications on a service oriented architecture that
interoperates more securely and reliably across platforms.
WCF simplifies the development effort to make service oriented
applications by combining the technologies together, leading to higher
development productivity. Also, it reduces the complexity of
applications by unifying Enterprise Services, Messaging, .NET Remoting,
Web Services, and WSE. WCF builds applications with an attributed
programming model, leading to higher developer productivity. WCF was
introduced as part of the .NET 3.0 Runtime components. The Windows
Communication Foundation provides a service oriented programming model
to build service oriented applications that interoperate across
organizational and platform boundaries. It supports a broad range of Web
Service standards like XML, XSD, SOAP, XPath, WSDL, and advanced
standards and specifications like WS-Addressing, WS-Policy, WS-Security,
WS-Trust, WS-Secure Conversation, WS-Reliable Messaging, WS-Atomic
Transaction, WS-Coordination, and WS-Policy. The following diagram
depicts the Windows Communication Foundation (WCF) framework model:
WCF Communication Model
Windows Communication Foundation (WCF) follows a client–server model
to establish communication between applications. Client applications can
directly access services through Endpoints exposed by the service.
Endpoints are nothing but locations defined, through which messages can
be sent or received, and a service can have multiple endpoints.
A WCF Service is comprised of the following major components. The
diagram below shows how the components are related to each other:
- Service Contract
- Operation Contract
- Data Contract
- Data Member
Service Contract
Service contract is a contract that specifies the direction and type
of the messages in a conversation. It is an interface or a class that
defines the service contract in a Windows Communication Foundation (WCF)
application. A service contract is the gateway to a service for
external applications to make use of the service functions, and at least
one service contract should be available in a service. A service
contract is defined as follows:
[ServiceContract]
public interface IStudentService
{
}
The
ServiceContract
attribute of the interface defines
the service contract in the service interface. The service contract
defines the operations available in the service, operations like web
service methods in a web service.
IstudentService
is a student service interface which exposes all the operation contracts or methods in this service to external systems.
Operation Contract
An operation contract defines the methods of the service that are accessible by external systems. The
OperationContract
attribute needs to be applied for all these methods, these are also
like web methods in a web service. Operation contracts are defined as
follows:
[ServiceContract]
public interface IStudentService
{
[OperationContract]
String GetStudentFullName (int studentId);
[OperationContract]
StudentInformation GetStudentInfo (int studentId);
}
Data Contract
A data contract defines a type with a set of data members or fields
that will be used as the composite type in a service contract. It is a
loosely-coupled model that is defined outside the implementation of the
service and accessible by services in other platforms. To define a data
contract, apply the
DataContract
attribute to the class to serialize the class by a serializer, and apply the
DataMember
attribute to the fields in the class that must be serialized. A
StudentInformation
data contract can be defined as follows:
[DataContract]
public class StudentInformation
{
}
Data Member
A data member specifies the type which is part of a data contract
used as a composite type member of the contract. To define a data
member, apply the
DataMember
attribute to the fields that must be serialized. The
DataMember
attribute can be applied to private properties, but they will be
serialized and deserialized, and will be accessible to the user or
process. The code below shows how to define a data member in a data
contract:
[DataContract]
public class StudentInformation
{
_studentId = studId;
[DataMember]
public int StudentId
{
get { return _studentId; }
set { _studentId = value; }
}
}
Creating WCF Applications with Visual Studio 2008
These are the steps needed to be followed to create a WCF application with Visual Studio 2008:
- Open Visual Studio 2008.
- Click on New Project in the File menu.
- Expand the Visual C# node in the Project types tree, and select the Web node.
- Select WCF Service Application.
- Choose the folder where the application is to be saved and click the OK button.
- The project will be created with the default files, which are IService1.cs, Service1.svc, Service1.svc.cs, and web.config.
You can see the
ServiceContract
attribute with
IService1
, and the methods exposed are defined with the
OperationContract
attribute.
Service1
is the concrete class for the implementation of
IService1
. Endpoints and other behavioral properties are defined in the
system.serviceModel
section of the
Web.Config file.
You need to make the necessary changes in the above section of
Web.Config if you are renaming the services; otherwise, external systems can not identify the services.
Customizing the Default WCF Service
Now, we need to make the necessary changes in the default WCF
application according to our requirements. The first step is renaming
the existing service files or deleting the existing files and create new
ones. In this example, I would go ahead with the first approach,
renaming the existing files.
Rename the project to
WcfStudentService, the file
Iservice1.cs to
IstudentService.cs,
Service.svc to
StudentService.svc. Note that the code file
Service.svc.cs will also be renamed to
Service.svc.cs. Make the corresponding changes in the
Web.Config file.
Remove the existing code from
IstudentService
and add the following code. The
OperationContract
attribute should be applies to the methods which are accessible to external systems.
DataContract
should be applied to the
StudentInformation
class, and fields in the
StudentInformation
attributed with
DataMember
since
StudentInformation
is using as composite type in
IstudentService
.
namespace WcfStudentService
{
[ServiceContract ]
public interface IStudentService
{
[OperationContract]
String GetStudentFullName(int studentId);
[OperationContract]
IEnumerable GetStudentInfo(int studentId);
}
[DataContract]
public class StudentInformation
{
int _studentId ;
string _lastName;
string _firstName;
public StudentInformation(int studId, string firstname, string lastName)
{
_studentId = studId;
_lastName = lastName;
_firstName = firstname;
}
[DataMember]
public int StudentId
{
get { return _studentId; }
set { _studentId = value; }
}
[DataMember]
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
[DataMember]
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
}
}
Note that
StudentInformation
is an independent class and accessible to external systems since it declared as
public
.
StudentService
is the concrete class implemented from
IstudentService
. Add the following code in the service class:
namespace WcfStudentService
{
public class StudentService : IStudentService
{
List Students = new List() ;
public StudentService()
{
Students.Add(new StudentInformation(1001, "Nikhil",
"Vinod"));
Students.Add(new StudentInformation(1002, "Joshua",
"Hunter"));
Students.Add(new StudentInformation(1003, "David",
"Sam"));
}
public string GetStudentFullName(int studentId)
{
IEnumerable<string> Student
= from student in Students
where student.StudentId == studentId
select student.FirstName + " " + student.LastName;
return Student.Count() != 0 ? Student.First() : string.Empty;
}
public IEnumerable GetStudentInfo(int studentId)
{
IEnumerable Student = from student in Students
where student.StudentId == studentId
select student ;
return Student;
}
}
Hosting and Testing the WCF Service
The WCF service can be hosted in Internet Information Service (IIS),
and Windows Activation Service (WAS) with Vista and IIS 7.0. In this
example, IIS is used for hosting the WCF service. Build the service
project, and run it by pressing F5 to run from Visual Studio 2008. By
default, it would take IIS as the hosting service. You can select the
StudentService.svc file from the list of files displayed in the browser window, and the page will be displayed as follows:
You can not directly test the WCF service with out a client, as we do in a web service.
There is an interface provided by Microsoft to test the service in an
easy way, which is the WcfTestClient utility. The WcfTestClient window
will be opened if the service is hosted by the WCF Service Host (
WcfSvcHost.exe), from Visual Studio, or you can explicitly run the WcfTestClient utility from the command prompt. You can run it as follows:
C :\> WcfTestClient http://localhost:4489/StudentService.svc
http://localhost:4489/StudentService.svc should be the name
of the service to be tested. WcfTestClient displays the service with the
exposed methods on the left side pane; it also provide the options to
enter the parameter values on the right top pane. When you enter the
values in the parameter box and click the Invoke button, it displays the
results on the right bottom pane of this utility.
Consuming the WCF Service
The WCF service can be communicated through a WCF client from a
client application. The first step of consuming a WCF service is to
create a WCF client and the related configuration files. The Service
Model Metadata Utility Tool (
Svcutil.exe) is a command-line
tool and one of its options is to create a WCF Client. The other option
is to create a WCF Client by adding the service reference in the Windows
project. The second option is used in this example to create the WCF
Client.
Also, add a Windows application with a form which has
Button
s,
Label
s, a
TextBox
, and a
DataGridView
to display the student information.
Create the WCF Client
To add the service reference to the Windows application, follow these steps:
- Open Solution Explorer.
- Right click on References of the Windows application, or right click on Service References and select Add Service Reference.
- And Service Reference window will pop up.
- Click on Discover, select the Services in the Solution in the Discover dropdown.
- It would search and display the services in the solution as shown below:
- Rename Namespace to StudentServiceReference, select StudentService, and click the OK button.
- The proxy is created and added to the service reference, and is
ready to consume the service in the application with the StudentService
reference.
Using the WCF Client
Create the instance of the WCF client to communicate to the service. The following line create the service client proxy:
StudentServiceClient studClient =
new StudentServiceClient("WSHttpBinding_IStudentService");
StudentServiceClient
is the WCF client class generated when the service reference is added to the project.
WSHttpBinding
is the endpoint binding method specified in the
web.config file of the service, and
IStudentService
is the service to be communicated.
After creating the proxy or instance of the WCF client, we can access
the methods of the service like accessing the methods of a web service
in the previous versions of .NET. The
GetStudentFullName
and
GetStudentInfo
methods of the service can be called as follows:
lblFullName.Text = studClient.GetStudentFullName(
Convert.ToInt16(textBox1.Text));
IEnumerable x =
studClient.GetStudentInfo(Convert.ToInt16(textBox1.Text));
dataGridView1.DataSource = x;
In the form, if you enter the student ID and click on the Display
Student Info button, you will call the service methods and populate the
Fullname
label and The
DataGridView
with the details.
That it. This article reffered from CodeProject.com