WCF Fundamentals
-
Upload
safaa-farouk -
Category
Technology
-
view
195 -
download
1
Transcript of WCF Fundamentals
WCFWindows communication foundation
From Objects to Services
PolymorphismEncapsulationSubclassing
Message-basedSchema+ContractBinding via Policy
1980s
2000s
Interface-basedDynamic LoadingRuntime Metadata
1990s
Object-Oriented
Service-Oriented
Component-Based
SOA can be simply defined as an architectural concept or style that uses a set of “loosely coupled services” to achieve the desired functionality.
SOA service oriented architecture
Boundaries are Explicit.
Services are Autonomous
Services share schema and contract, not class
Service compatibility is determined based on policy
The Four Tenets of Service-Orientation
Services are secure
Services leave the system in a consistent state
Services are thread-safe
Services are reliable
Practical principles
Windows Communication Foundation
overview
WCF is a programming model that enables developers to build service solutions that are reliable and secure, and even transacted.
WCF simplifies development of unified, simplified and manageable distributed systems
WCF
Unifying Programming Models
ASMX
Interoperable
WSE
InteroperableSecure
Remoting
FastSecure‘Objects’
COM+
FastSecureTransactions
MSMQ
QueuedSecureTransactions
WCF goals
Interoperability across platforms
Service –oriented development
Unification of existing distributed technology
Programming model type1. You can use the object model programmatically.2. You can use configuration files.3. You can use declarative programming
(attributes). The order in which settings are applied is as
follows:1. Attributes are applied.2. The configuration is applied.3. The code runs.
WCF programming model
Web Service Communication
Client
SOAP Request
SOAP ResponseService
Metadata
Message (SOAP)
Headers: Addressing, Security, etc
Body: Payload
What do I send?
Where do I send it?
How should I send it?
Contract
Address
Binding
Windows Communication Foundation
ServiceClientEndpoint Endpoint
a network address indicates where the service is located.
specifies how a client can communicate with the
endpointidentifies what
operations are available to the clients
WCF Service Library◦ WCF Test Client◦ WCF Configuration Editor◦ Output is dll◦ Has app.config file
Website Project Template◦ Has web.config ◦ Used over asp.net webservice◦ Has a .svc file
WCF Project Templates
Address
Binding
Contract
The ABCs of WCF
It contains information about what a service does and the type of information it will make available.
There are three types of contracts: Data Contract Message Contract Service Contract Operation Contact
Contract
Contract & Service Definition
16
[ServiceContract]public interface IHello{ [OperationContract] string Hello(string name);}
public class HelloService : IHello{ public string Hello(string name) { return “Hello, ” + name; }}
The service contract expresses the “methods” that are exposed to the outside world.
Service Contract
using System.ServiceModel;namespace MyFirstWCF{[ServiceContract(Namespace = "http://Ebusiness30/WCF")]interface IService{ [OperationContract] Operation1( ); [OperationContract] Operation2( );}}
class MyService : IMyContract{ public string MyMethod( ) { return "Hello WCF"; }}
Define the custom types that you will use as a parameter or return in your operation contract
Data contract
[DataContract(Namespace=" Ebusiness30WCF")]public class Customer{ [DataMember(Name=“CustomerName")] public string Name; [DataMember(Name=“NID")] public int id; [DataMember(Name=“Type")] private string type;}
use message contracts to control how properties of your types map to the SOAP headers and SOAP body
Message contract
[MessageContract(Namespace=" Ebusiness30/WCF")]public class Customer{ [MessageBody(Name=“CustomerName")] public string Name; [MessageBody(Name=“NID")] public int id; [MessageHeader(Name=“Type")] private string type;}
Binding
Http-Based Binding◦ BasicHttpBinding-wsBinding-wsDualHttpBinding-
wsFederationHttpBinding- TCP-Based Binding
◦ netNamedPipeBinding-netPeerTcpBinding-netTcpBinding
MSMQ-Based Binding◦ msmqIntegrationBinding-netMsmqBinding
WCF Binding
Bindings are the mechanism by which communication details are specified to make connecting to a service’s WCF endpoint possible
A binding defines how you can communicate with the service The binding controls the following:
◦ The transport (HTTP, MSMQ, Named Pipes, TCP)◦ The channels (one-way, duplex, request-reply)◦ The encoding (XML, binary,MTOM)◦ The supported WS-* protocols (WS-Security, WS-Federation, WS-
reliability, WS-Transactions) Using bindings is a two-step process, as follows
◦ Select the binding from the predefined list of WCF bindings that you will use for a particular endpoint.
◦ Create an endpoint that utilizes the binding that you have selected or created.
Binding
Service Bindings
Binding Name
Transport Encoding Intero
pSecurity
Session
Transaction
Duplex
Streaming
BasicHttpBinding HTTP/S Text.MTOM BP 1.1 T
X
WsHttpBinding HTTP/S Text.MTOM WS T | S X X XWsDualHttpBinding HTTP/S Text.MTOM WS T | S X X X XNetTcpBinding TCP Binary .NET T | S X X X XNetNamedPipesBinding IPC Binary .NET T | S X X X XNetMsmqBinding MSMQ Binary .NET T | S XNetPeerTcpBinding P2P Binary .NET T | S XMsmqIntegrationBinding MSMQ Binary MSMQ T XT = Transport Security | S = WS-Security
It specifies the communication details required to connect to the endpoint.
Bindings
ServiceClientMessage Message
Transactions
Security
Transport
Transactions
Security
Transport
ChannelsConfiguration
Configuration
Configuration
Transport Channel (HTTP, TCP, etc)Configuration
Service Addresses
An address basically declares “here I am” to the outside world.
Example http://localhost/myservice/
Address
protocol domain Service path
HTTP◦ http://domain [:port]/path
HTTPS◦ https://domain[:port]/path
TCP◦ net.tcp://domain/path
MSMQ◦ net.msmq://domain/queue name
Named pipe no port not cross-machine◦ net.pipe://localhost/path
IIS◦ http://domain[:port]/virtual directory[.svc file]
Address formats
Base address◦ enables you to host multiple endpoints under the same
base address◦ [transport]://[host name][:optional port]/[optional path]
Endpoint address◦ Endpoint address is where the service is actually listening.
Mex address◦ Used to obtain metadata of the service◦ [transport]://[host name][:optional port]/[optional path]
MyServiceMex
Address types
Base address example<host><baseAddresses><add baseAddress="http://localhost:8080/QuickReturns"/><add baseAddress="net.tcp://localhost/QuickReturns"/></baseAddresses></host>
<endpointname="BasicHttpBinding"address="Exchange"bindingsSectionName="BasicHttpBinding"contract="IExchange" />
<endpointname="NetNamedPipeBinding"address="Exchange"bindingsSectionName="NetNamedPipeBinding"contract="IExchange" />
This allows you to define the following endpoints:
Custom .exe (self hosting ) IIS
Windows Service
WCF Hosting
ServiceHost States and transitions
Service Hosting IIS 6 (ASPNET_WP.EXE / W3wp.exe)
◦ Activation on demand upon client request.◦ Only supports HTTP/S transport.
Self Hosting◦ Can be any managed application, i.e. Console or
WinForms application.◦ Low-level but flexible.
Windows Activation Service (WAS)◦ Supports all transports.◦ Will ship with IIS 7 on Vista and Longhorn Server.
Managed Windows Services (NT Services)
Service Hosting
33
class HelloHost{ static void Main(string[] args) { ServiceHost host = new ServiceHost(typeof(HelloService)); host.Open(); // Wait until done accepting connections Console.ReadLine(); host.Close(); }}
<%@ Service Language=“C#” Class=“HelloService” %>
http://localhost/HelloService/HelloService.svc
Self-host
WAS/IIS-host
Service Configuration
34
<?xml version="1.0" encoding="utf-8" ?><configuration> <system.serviceModel> <services> <service type=“HelloService" <endpoint address=“http://localhost/HelloService" binding=“basicHttpBinding" contract="IHello" /> </service> </services> </system.serviceModel></configuration>
Self Hosting Create a service host Open the host to allow calls in Close the host to gracefully exit
◦ Calls in progress complete.◦ Host refuse any further calls even if host process is still running.
public static void Main (){ Uri baseAddress = new Uri ("http://localhost:8000"); using (ServiceHost serviceHost = new ServiceHost (typeof(MyService), baseAddress)) { serviceHost.Open (); // The service can now be accessed. Console.WriteLine ("Press <ENTER> to terminate service."); Console.ReadLine (); }}
Service Configuration Application hosting
◦ App.Config<system.serviceModel> <services> <service name = "MyNamespace.MyService" > <endpoint address = "http://localhost:8000/MyService" binding = "wsHttpBinding" contract = "MyNamespace.IMyContract"> </endpoint> </service> </services></system.serviceModel>
Enabling Metadata Exchange
Exposing Metadata
Using svcutil.exe
Using visual studio 2008
Generating Proxy Class
Client Programming 1 Client uses a proxy to consume the service The proxy
◦ Is CLR interface and class representing the service.◦ Provides the same operations as service.◦ Has additional methods for managing the proxy and the
connection. Generate the proxy
◦ SvcUtil.exe <Base Address> [/out:<file>] [/config:<file>]
◦ When hosted in IIS/WASSvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs
◦ When self-hostingSvcUtil http://localhost:8000/MyService/ /out:Proxy.csSvcUtil net.tcp://localhost:8001/ /out:Proxy.csSvcUtil net.pipe://localhost/MyPipe/ /out:Proxy.cs
◦ HTTP transport Add Service Reference to the project in VS 2005
Client Programming 2 Client Configuration
◦ Application: App.Config
<system.serviceModel> <client> <endpoint name="MyEndpoint" address="http://localhost:8000/MyService" binding="wsHttpBinding" contract="MyNamespace.IMyContract" /> </client></system.serviceModel>
Client Programming 3 Client needs to instantiate proxy object
◦ Provide the constructor with endpoint◦ Endpoint section name from config file
Use service methods Close proxy instance
using (MyContractProxy proxy = new MyContractProxy ("MyEndpoint") ){ proxy.MyMethod (); }
Client Programming 4 No Proxy Client
◦ Work directly with channelChannelFactory<IMyContract> factory = new ChannelFactory<IMyContract> ("MyEndpoint");IMyContract channel = factory.CreateChannel();channel.MyMethod (); factory.Close ();
Need to know the contract interface upfront
WCF Exception Handling
Advanced topics
in this section you will learn how 1. Handle exceptions in the client applications and
services2. Specify the exception that a WCF can raise 3. Propagate information about exceptions form
service to client 4. Learn about services state 5. Recover service that has failed 6. Detect unrecognized messages sent to the
service by the client application
Before we start Why SOAP fault and not CLR exception
◦ Simply , CLR exceptions are specific to the.NET framework, java client application would not understand the format of a CLR exception raised by a WCF service
So, Interoperable services built by using the WCF should convert .NET Framework exceptions into SOAP faults and follow the SOAP specification for reporting these faults to client applications.
Throwing and Catching a SOAP Fault
WCF Service
WCF runtime Client
Throws FaultException Object
Generate Soap fault message
Throwing Service side
ServiceMthod{Try{ service logic that may generate an exception }catch(Exception e ) { throw new FaultException( e.message, new FaultCode(“FaultName”) }
Catching Client sideSeviceCall{Try{ calling serviceMethod() }catch(FaultException e ) { print e.code.name, print e.Reason }
Using strongly typed exception Strongly typed exception
◦ A SOAP fault message that contains a sufficient detail about the exception in order to enable the user, or an administrator, to understand the reason for the exception and if possible take any necessary corrective action.
◦ Use FaultContract attributes in a service contract◦ Note you cannot use it with one way operations
Lets practice
Reporting Unanticipated Exceptions Configure the WCF service to send details
of Unanticipated exceptions ◦ Configuration file
In the <serviceBehaviors> section of the App.config file add this tag in the <behavior> section
Setting the includeExceptionDetailInFaults attribute to true causes WCF to transmit the full details of exceptions when it generates SOAP faults for unanticipated errors.
◦ Programmatically
<serviceDebug includeExceptionDetailInFaults="true"/>
[ServiceBehavior(IncludeExceptionDetailInFaults=true)] public class ServiceImpl : IService {}
Managing Exceptions in Service Host Applications May I decide to make it a self study topic or
research that must be given in lab Or give them a hint about it Or decide to give it with no examples Or decide to give it with examples Summary if I didn’t give it I won’t be upset
s
Handling Faults in a Host Application when a ServiceHost object enters the Faulted state it triggers Faulted
event . You should subscribe to this event, and provide a method that attempts to determine the cause, and then abort and restart the service.// ServiceHost object for hosting a WCF service ServiceHost HelloworldServiceHost; HelloworldServiceHost = new ServiceHost(…); // Subscribe to the Faulted event of the productsServiceHost object HelloworldServiceHost.Faulted += new EventHandler(faultHandler); // FaultHandler method Runs when productsServiceHost enters the Faulted state void faultHandler(object sender, EventArgs e) { // Examine the properties of the HelloworldServiceHost object // and log the reasons for the fault // Abort the service HelloWorldServiceHost.Abort(); // Recreate the ServiceHost object HelloWorldServiceHost = new ServiceHost(…); // Start the service HelloWorldServiceHost.Open(); }
Handling Unexpected Messages in a Host Application If a client application sends a message specifying an action that
the service does not recognize, the service host application raises the UnknownMessageReceived event. The host application can catch this event and record the unrecognized message, like this// ServiceHost object for hosting a WCF service
ServiceHost HelloWorldServiceHost; HelloWorldServiceHost = new ServiceHost(…); // Subscribe to the UnknownMessageReceived event of the HelloWorldServiceHost object HelloWorldServiceHost.UnknownMessageReceived += new EventHandler<UnknownMessageReceivedEventArgs>(unknownMessage); // UnknownMessageReceived event handler void unknownMessage(object sender, UnknownMessageReceivedEventArgs e) { // Log the unknown message // Display a message to the administrator MessageBox.Show("A client attempted to send the message " + e.Message.Headers.Action); }