Sie sind auf Seite 1von 13

WCF:

Windows Communication Foundation (WCF) is an extension of .NET framework to build and


run the 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, Web Services Enhancements (WSE), to develop and deliver unified secured systems.
WCF framework builds the loosely-coupled applications on service oriented architecture that
interoperate more securely and reliably across the platforms.
WCF simplifies the development effort to make service oriented applications by combining the
technologies together leads to the higher development productivity. Also reduces the complexity
of application by unifying Enterprise Services, Messaging, .Net Remoting, Web Services and
WSE. WCF build the application with attributed programming model, leads to the developer
productivity. WCF introduced as part of .NET 3.0 Runtime components. Windows
Communication Foundation provides the service oriented programming model to build service
oriented applications that interoperate across organizational and platform boundaries. It supports
a broad range of the web service standards like XML, XSD, SOAP,Xpath, WSDL and advanced
standard and specifications like WS-Addressing, WS-Policy, WS-Security, WS-Trust, WSSecure Conversation, WS-Reliable Messaging, WS-Atomic Transaction, WS-Coordination, WSPolicy . The following diagram depicts the Windows Communication Foundation (WCF)
framework model.

WCF Communication Model


Windows Communication Foundation (WCF) follows Client Server model to establish the
communication between the applications. Client applications can be directly access the services
through the Endpoints exposed by the service. Endpoints are nothing but a location defined
through which messages can be sent or receive, and a service can have multiple endpoints.

The WCF Service is comprised of the following major components. The below diagram shows
the how the components related each other.

Service Contract

Operation Contract

Data Contract

Data Member

Service Contract
Service contract is a contract specifies the direction and type of the messages in conversation. It
is an interface or class defines the service contract in Windows Communication Foundation
(WCF) application. Service Contract is the gateway to the service by the external applications to
make use of service functions and at least one ServiceContract should be available in a service.
The ServiceContract defined as follows:
// Student ServiceContract
[ServiceContract]
public interface IStudentService
{
// Define the OperationContact here.
}

ServiceContract attribute of the interface defines the ServiceContract in the service interface.
ServiceContract defines the operations available in the service, operations like web service
methods in web service. IstudentService is a student service interface which expose the all the
OperationContract or methods in this service to the external systems.
Operation Contract
Operation contract is defines the methods of the service can be accessible by the external
systems. OperationContract attribute needs to apply for all these methods, these are like web
methods in web service. The operation contracts are defined as follows
// Student ServiceContract
[ServiceContract]
public interface IStudentService
{
// Define the GetStudentFullName OperationContact here.
[OperationContract]
String GetStudentFullName (int studentId);
// Define the GetStudentInfo OperationContact here.
[OperationContract]

StudentInformation GetStudentInfo (int studentId);


}

Data Contract
Data Contract defines a type with set of DataMembers or fields will be used as the composite
type in ServiceContract. It is a loosely-coupled model defines outside the implementation of
service accessible by services in other platforms. To define a Data Contract apply DataContract
attribute to the class to serialize the class by a serializer and apply DataMember attribute to the
fields in the class that must be serialized. StudentInformation DataContract can be defined as
follows.
[DataContract]
public class StudentInformation
{
// Define the Datamembers here.
}

Data Member
Data member specifies the type which is part of a Data Contract used as composite type
members of the contract. To define a DataMember apply DataMember attribute to the fields that
must be serialized. DataMember attribute can be applied to private properties, but it will be
serialized and deserialized and can be accessible to the user or process. The code below shows
how to define DataMember in a DataContract.
[DataContract]
public class StudentInformation
{
_studentId = studId;
[DataMember]
public int StudentId
{
get { return _studentId; }
set { _studentId = value; }
}
}

Creating WCF Application with Visual studio 2008


These are steps needs to follow to create the WCF application with Visual studio 2008. 1. Open
Visual studio 2008 2. Click on New Project in File menu 3. Expand Visual C# node in the Project
types tree and select the Web node 4. Select WCF Service Application 5. Choose the folder
where the application want to save and click OK button 6. Project will be created with default
files which are IService1.cs, Service1.svc , Service1.svc.cs, web.config.

You can see the ServiceContract attribute with IService1 and methods exposed are defined with
OperationContract attribute. Service1 is the concrete class for the implementation of the
IService1. Endpoints and other behavioral properties are defined in system.serviceModel section
of the Web.Config file.
Need to make the necessary changes in the above section of Web.Config if you are renaming the
services, otherwise the external system cannot identify the services.

Customizing the Default WCF Service

Now we need to make necessary changes in the default WCF application according to our
requirement. First step is renaming the existing service files or delete the existing file and create
new ones. In this example, I would go ahead with the 1st approach, renaming the existing files.
Rename the project to WcfStudentService, the files Iservice1.cs to IstudentService.cs,
Service.svc to StudentService.svc. Note that the code file Service.svc.cs will also re named to
Service.svc.cs. Make the corresponding changes in the Web.Config file.
Remove the existing code from IstudentService and add the following code. OperationContract
attribute should apply to the methods which are accessible to external systems. DataContract
applied to the StudentInformation class and fields in the StudentInformation attributed with
DataMember since StudentInformation is using as composite type in the IstudentService.
Collapse
namespace WcfStudentService
{
// Defines IStudentService here
[ServiceContract ]
public interface IStudentService
{
// Define the GetStudentFullName OperationContact here.
[OperationContract]
String GetStudentFullName(int studentId);

// Define the GetStudentInfo OperationContact here.


[OperationContract]
IEnumerable GetStudentInfo(int studentId);

// Use a data contract as illustrated in the sample below to add


// composite types to service operations.
[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 a independent class and accessable to external system since it
declared as public.
StudentService is the concrete class implemented from IstudentService. Add the following code
in the service class.
Collapse
namespace WcfStudentService
{
// StudentService is the concrete implmentation of IStudentService.
public class StudentService : IStudentService
{
List Students = new List() ;
// Create list of students
public StudentService()
{
Students.Add(new StudentInformation(1001, "Nikhil",
"Vinod"));
Students.Add(new StudentInformation(1002, "Joshua",
"Hunter"));
Students.Add(new StudentInformation(1003, "David",
"Sam"));
}
// Method returning the Full name of the student for the studentId
public string GetStudentFullName(int studentId)
{
IEnumerable Student
= from student in Students
where student.StudentId == studentId
select student.FirstName + " " + student.LastName;
return Student.Count() != 0 ? Student.First() : string.Empty;
}

// Method returning the details of the student for the studentId


public IEnumerable GetStudentInfo(int studentId)
{
IEnumerable Student =
return Student;
}

from student in Students


where student.StudentId == studentId
select student ;

Hosting and Testing WCF Service


The WCF service can be hosted in Internet Information Service (IIS), Windows Activation
Service (WAS) with vista and IIS 7.0. In this example IIS is used as the 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 webservice.

There is an interface provided by Microsoft to test the service in an easy way is the
WcfTestClient utility. WcfTestClient window will be opened if the service is hosting by 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 exposed methods on the left side pane; 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 Invoke button, it displays the results on the right bottom pane of this
utility.

Consuming WCF Service

The WCF service can be communicated through a WCF client from the client application. The
first step of consuming a WCF service is to create a WCF client and related configuration files.
The Service Model Metadata Utility Tool (Svcutil.exe) is a command-line tool is one of the
options to create the WCF Client. The other option is to create WCF Client by adding the service
reference in the windows project. The second option is using in this example to create the WCF
Client.
Also add a Windows application with form which has with button, labels, textbox and
datagridview to display the student information.
Create WCF Client
To add the service reference to the windows application follow the below steps.
1. Open the Solution Explorer
2. Right Click on Reference of Windows application or right click on Service References
and select Add Service Reference
3. Add Service Reference window will be popped up.

4. Click on Discover / select the Services in Solution in Discover dropdown.

5. It would search and displays the services in the solution as shown below.

6. Rename the Namespace to StudentServiceReference, select the StudentService and click


OK button.
7. The proxy is being created and added to the service reference and ready to consume the
service in the application with StudentService Reference.

Using the WCF Client


Create the instance of the WCF Client to communicate to the service. The following lines create
the service client proxy.
// create the proxy to access the service
StudentServiceClient studClient = new StudentServiceClient
("WSHttpBinding_IStudentService");

StudentServiceClient is the WCF client class generated when the service reference 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
as acceing the methods of the web service in the previous versions of the .Net.
GetStudentFullName and GetStudentInfo methods of the service can be called as follows:
// Get Fullname of the Student through the proxy from service
lblFullName.Text =
studClient.GetStudentFullName(Convert.ToInt16(textBox1.Text));
// Get details of the Student through the proxy from service
IEnumerable x = studClient.GetStudentInfo(Convert.ToInt16(textBox1.Text));
dataGridView1.DataSource = x;

In the form if you enter the student ID and click on Display Student Info button will call the
service methods and populate the Fullname label and DataGridview with the details.

Das könnte Ihnen auch gefallen