11/18/2009. 1. Tutorial 2 - the ABCs of WCF programming written by Alex Kogan (
) winter semester, 2009-2010. ▻ Several ...
11/18/2009
Tutorial 2 - the ABCs of WCF programming written by Alex Kogan (
[email protected]) winter semester, 2009-2010
Several communication technologies for different needs ◦ ASP.Net Web Services for platform-independent communication
◦ Web Service Enhancements advanced Web Services capabilities reliability, atomic transactions, etc.
◦ .Net Remoting fast .Net-based communication
◦ Enterprise Services, MSMQ (Message Queuing), …
2
1
11/18/2009
Unified communication programming model
Combines all functionality features from the previous technologies
Cross-platform, extendible and secure infrastructure
Designed for service-oriented communication
3
Service - a passive piece of code that interacts with clients through messages ◦ clients send messages to request some work/data ◦ services perform the work and respond with a result
Services expose one or more endpoints where messages can be sent Endpoint
Client
Service Endpoint
4
2
11/18/2009
Each endpoint is composed of ◦ Address: ddress where is the service? ◦ Binding: inding how do I talk to the service? ◦ Contract ontract: what can the service do?
Writing and configuring a WCF service includes 3 steps (for each endpoint): ◦ define and implement a contract ◦ choose or define a service binding ◦ deploy the contract by binding it to a network address 5
Client code
Service
Proxy
Dispatcher
Channel
invokes a method on the proxy
6
3
11/18/2009
Client code
Service
Proxy
Dispatcher
Channel
offers methods as defined by the service contract converts the method call to a message transfers the message to a channel
7
Client code
Service
Proxy
Dispatcher
Channel
passes messages between client-side and server-side 8
4
11/18/2009
Client code
Service
Proxy
Dispatcher
Channel
converts the message to a method call according to message headers invokes the requested service 9
Client code
Service
Proxy
Dispatcher
Channel
executes the requested operation
10
5
11/18/2009
Web Services Description Language
Describes the service along with its messages, operations and bindings
Defines service metadata that can be used to create a proxy for the client ◦ manually, by reading the WSDL file ◦ by tools for generating client-side code from WSDL definitions
11
Calculator service server side
12
6
11/18/2009
Start by defining the interface of the service namespace CalculatorService { public interface ICalculatorService { int Sum(int x, int y); double Sqrt(int x); Rational Sub(Rational r, Rational y); } public class Rational { public int Numerator { get; set; } public int Denumerator { get; set; } } } 13
Add attributes ◦ [ServiceContract] to define the service contract ◦ [OperationContract] to specify the operations of the contract [ServiceContract] public interface ICalculatorService { [OperationContract] int Sum(int x, int y); [OperationContract] double Sqrt(int x); [OperationContract] Rational Sub(Rational x, Rational y); } 14
7
11/18/2009
Defines the mapping between .Net objects and data transferred in messages WCF provides an implicit mapping for all .Net primitive types ◦ string, int, double, int[] …
In custom types, fields that should be serialized have to be explicitly annotated ◦ also applies to properties [DataContract] public class Rational { [DataMember] public int Numerator { get; set; } [DataMember] public int Denumerator { get; set; } } 15
Add a new class implementing the ICalculatorService interface namespace CalculatorService { public class CalculatorService : ICalculatorService { public int Sum(int x, int y) { return x + y; } public double Sqrt(int x) { return Math.Sqrt(x); } public Rational Sub(Rational x, Rational y) { // implement substraction here } } }
16
8
11/18/2009
To use the CalculatorService, it needs to be hosted in a .Net-based application
Several options: ◦ custom service host in a console application ◦ using WCF Service Host application provided by Visual Studio
◦ using IIS Web Server
17
The ServiceHost class provides a direct control over the WCF hosting infrastructure ◦ should be instantiated based on a particular service using System.ServiceModel; namespace CalculatorService { class HostingProgram { static void Main(string[] args) { using (ServiceHost host = new ServiceHost( typeof(CalculatorService), new Uri("http://localhost:8080/Services"))) { …
18
9
11/18/2009
Each endpoint consists of an address, a binding and a contract Added to ServiceHost by calling AddServiceEnpoint method using (ServiceHost host = new ServiceHost( typeof(CalculatorService), new Uri("http://localhost:8080/Services"))) { // define the service endpoints host.AddServiceEndpoint(typeof(ICalculatorService), new BasicHttpBinding(), “CalculatorService"); host.AddServiceEndpoint(typeof(ICalculatorService), new NetTcpBinding(), "net.tcp://localhost:8082/Services/CalculatorService");
19
The binding controls three aspects of message communication ◦ message encoding XML, binary, …
◦ transport protocol HTTP, TCP, MS Message Queuing
◦ suite of Web Services protocols WS-Security, WS-ReliableMessaging, …
A given binding specifies one encoding, one transport and several WS protocols
20
10
11/18/2009
WCF provides a set of predefined bindings The most useful: ◦ BasicHttpBinding : XML encoding + HTTP transport + basic WS functionaliy for interoperability
◦ WSHttpBinding: XML encoding + HTTP transport + advanced WS functionality for both interoperability and security/reliability
◦ NetTcpBinding: binary encoding + TCP transport + advanced WS functionality when both server and client use WCF for higher performance
21
Hardcoding endpoint information into the host application is not ideal ◦ endpoint details may change over time
Much more flexible approach exists! ◦ application configuration file ◦ can be added to the project (if not there)
22
11
11/18/2009
replaces calls to AddServiceEnpoint
23
Build the WCF runtime to support the service operation: host.Open();
Now the runtime is ready to receive messages at the addresses specified by each endpoint static void Main(string[] args) { using (ServiceHost host = new ServiceHost( typeof(CalculatorService), new Uri("http://localhost:8080/Services"))) { // define the service endpoints host.Open(); // keep the process alive Console.ReadLine(); } }
24
12
11/18/2009
http://localhost:8080 http://localhost:8080/Services 8080/Services
25
26
13
11/18/2009
27
Visual Studio provides a template for WCF service development ◦ includes interface, implementation and configuration files that have to be customized for the actual service
28
14
11/18/2009
When running the library from Visual Studio: ◦ WCF Service Host application is started no need for a custom service host application
◦ WCF Test Client application is started can be used for a quick service testing
29
3 steps process: ◦ define and implement the interface ◦ configure the endpoints ◦ host the service
Prefer XML-based configuration over coding
Visual Studio provides a useful template to facilitate the development process
30
15
11/18/2009
Calculator service client side
31
Create ServiceEndpoint instance representing the target endpoint ◦ specify the contact, binding and network address of the service ServiceEndpoint httpEndpoint = new ServiceEndpoint( ContractDescription.GetContract( typeof(ICalculatorService)), new BasicHttpBinding(), new EndpointAddress ("http://localhost:8080/Services/CalculatorService"));
We assume here that the client shares the same ICalculatorService interface 32
16
11/18/2009
Create a ChannelFactory based on the ServiceEndpoint Use ChannelFactory to create a service proxy Use the service proxy to invoke operations defined by the contract
// create channel factory based on HTTP endpoint using (ChannelFactory httpFactory = new ChannelFactory(httpEndpoint)) { // create channel proxy for endpoint ICalculatorService calc = httpFactory.CreateChannel(); // invoke service operation Console.WriteLine("1 + 2 = {0}", calc.Sum(1, 2); } 33
Similar configuration mechanism for specifying service endpoints at the client
34
17
11/18/2009
Use the name of the endpoint to create a ChannelFactory ◦ no need to create ServiceEndpoint
static void Main(string[] args) { // create channel factory based on HTTP endpoint using (ChannelFactory httpFactory = new ChannelFactory("httpEndpoint")) { // create channel proxy for endpoint ICalculatorService calc = httpFactory.CreateChannel(); // invoke service operation Console.WriteLine("1 + 2 = {0}", calc.Sum(1, 2)); } ...
35
What if we want to access an external service? ◦ how do we get its interface? ◦ how do we know its endpoints? ◦ what if it is not implemented with the .Net Framework?
Use WSDL metadata provided by the service! ◦ use svcutil.exe tool to extract all the required information from WSDL the tool can be found in MS SDK installation directory
36
18
11/18/2009
$ ./svcutil.exe http://localhost:8080/Services?wsdl Microsoft (R) Service Model Metadata Tool [Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.648] Copyright (c) Microsoft Corporation. All rights reserved. Attempting to download metadata from 'http://localhost:8080/Services?wsdl' using WS-Metadata Exchange or DISCO. Generating files... c:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\CalculatorService.cs c:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\output.config
CalculatorService.cs contains an interface definition similar to the one used by the service output.config contains the endpoints configuration information
◦ merge its contents with the application configuration file 37
In addition to ICalculatorService declaration, the generated CalculatorService.cs contains also a proxy public partial class CalculatorServiceClient : System.ServiceModel.ClientBase, ICalculatorService
Can simplify the client code further ◦ instantiate the proxy with the name of the endpoint configuration and make method calls ◦ no ServiceEndpoint and ChannelFactory needed
using (CalculatorServiceClient proxy = new CalculatorServiceClient("NetTcpBinding_ICalculatorService")) { // invoke service operation Console.WriteLine("Invoking TCP endpoint: {0}", proxy.Sqrt(17)); }
38
19
11/18/2009
Two ways to define a proxy and configure service endpoints: ◦ manual access to the same interface used by the service + coded or XML-based endpoints configuration ◦ svcutil.exe tool to extract all the required information from WSDL provided by the service
39
20