Wcf architecture overview


Published on

This is a fundamental understanding of WCF services.

1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Wcf architecture overview

  1. 1. WCF Architecture OverviewSunday, December 16, 2012 Arbind
  2. 2. WCF ServiceA service exposes endpoints(Endpoint: a port to communicate with outside world)Sunday, December 16, 2012 Arbind
  3. 3. A ClientExchanges messages with one or more Endpoints.May also expose an Endpoint to receive Messages from a Service in a duplex message exchange pattern.Sunday, December 16, 2012 Arbind
  4. 4. Endpoint: Has 1. An Address 2. A Binding 3. A ContractSunday, December 16, 2012 Arbind
  5. 5. Address:A network location where the Endpoint resides.Represented by an EndpointAddress ClassEndpointAddress is a URI, a collection of AddressHeader and identitySunday, December 16, 2012 Arbind
  6. 6. Bindings: Has 1. A name 2. A namespace 3. A collection of binding elementsSunday, December 16, 2012 Arbind
  7. 7. Collection of binding elements:Each binding elements describe how to communicate with the end point 1. TcpTransportBindingElement indicates that the Endpoint will communicate with the world using TCP as the transport protocol. 2. ReliableSessionBindingElement indicates that the Endpoint uses reliable messaging to provide message delivery assurances. 3. SecurityBindingElement indicates that the Endpoint uses SOAP message security.Sunday, December 16, 2012 Arbind
  8. 8. Contracts:Refers to the collection of operations which specify what endpoint will communicate to out side worldSunday, December 16, 2012 Arbind
  9. 9. ContractDescription class is used to describe WCF Contracts and their operations.Each Contract Operation have OperationDescriptions andeach operationDescription have MessageDescriptionSunday, December 16, 2012 Arbind
  10. 10. Duplex Contract: Defines two Logical Operations 1. A set that the Service exposes for the Client to call 2. A set that the Client exposes for the Service to callSunday, December 16, 2012 Arbind
  11. 11. Contract: Has 1. Name 2. Namespace 3. IdentitySunday, December 16, 2012 Arbind
  12. 12. Contract:Sunday, December 16, 2012 Arbind
  13. 13. Behaviors:Are types which modifies services or client functionalitiesSunday, December 16, 2012 Arbind
  14. 14. ServiceBehavior is a type which implements IServiceBehavior and applies to serviceSunday, December 16, 2012 Arbind
  15. 15. ChannelBehavior is a type which implements IChannelBehavior and applies to clientSunday, December 16, 2012 Arbind
  16. 16. Service and Channel DescriptionsThe ServiceDescription class describes a WCF Service including the Endpoints exposed by the Service, the Behaviors applied to the Service, and the type (a class) that implements the Service.ServiceDescription is used to create metadata, code/config, and channels.Sunday, December 16, 2012 Arbind
  17. 17. Behavior:Sunday, December 16, 2012 Arbind
  18. 18. ChannelDescription describes a WCF Clients Channel to a specific EndpointServiceDescription can have multiple endpoint butChannelDescription have only one endpointSunday, December 16, 2012 Arbind
  19. 19. WCF Runtime:The set of objects responsible for sending and receiving messagesSunday, December 16, 2012 Arbind
  20. 20. Message:The unit of data exchange between a Client and an EndpointA message should be of SOAP message type and can be serialized using the WCF binary format, text XML, or any other custom format.Sunday, December 16, 2012 Arbind
  21. 21. Channels:Channels are the core abstraction for sending Messages to and receiving Messages from an Endpoint.Sunday, December 16, 2012 Arbind
  22. 22. Two Category of channel:1. Transport Channels handle sending or receiving opaque octet streams using some form of transport protocol such as TCP, UDP, or MSMQ.2. Protocol Channels, implement a SOAP-based protocol by processing and possibly modifying messages.Sunday, December 16, 2012 Arbind
  23. 23. Procedure to define WCF ServiceStep1: Defining and Implementing a Contractusing System.ServiceModel;[ServiceContract]public interface IMath{ [OperationContract] int Add(int x, int y);}Step2: Define a service classThis contract (interface IMath) is implemented to a class which becomes a service classpublic class MathService : IMath{ public int Add(int x, int y) { return x + y; }}Sunday, December 16, 2012 Arbind
  24. 24. Step3: Defining Endpoints and Starting the Service(endpoint can be defined in code or in config)In Code:public class WCFServiceApp{ public void DefineEndpointImperatively() { //create a service host for MathService ServiceHost sh = new ServiceHost(typeof(MathService)); //use the AddEndpoint helper method to //create the ServiceEndpoint and add it //to the ServiceDescription sh.AddServiceEndpoint( typeof(IMath), //contract type new WSHttpBinding(), //one of the built-in bindings "http://localhost/MathService/Ep1"); //the endpoints address //create and open the service runtime sh.Open(); } public void DefineEndpointInConfig() { //create a service host for MathService ServiceHost sh = new ServiceHost (typeof(MathService)); //create and open the service runtime sh.Open(); }}Sunday, December 16, 2012 Arbind
  25. 25. Endpoint in config file:<!-- configuration file used by above code --><configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"><system.serviceModel><services><!-- service element references the service type --><service type="MathService"><!-- endpoint element defines the ABCs of the endpoint --><endpoint address="http://localhost/MathService/Ep1" binding="wsHttpBinding" contract="IMath"/></service></services></system.serviceModel></configuration> Sunday, December 16, 2012 Arbind
  26. 26. Step4: Sending Messages to the Endpointusing System.ServiceModel;//this contract is generated by svcutil.exe//from the services metadatapublic interface IMath{ [OperationContract] public int Add(int x, int y) { return x + y; }}//this class is generated by svcutil.exe//from the services metadata//generated config is not shown herepublic class MathProxy : IMath{ ... }Continue……….Sunday, December 16, 2012 Arbind
  27. 27. In the following code first way to send the message to endpoint is like SendMessageToEndpoint part. This hides the channel creation which is happening behind the sceneSecond way (SendMessageToEndpointUsingChannel) does it explicitly.public class WCFClientApp{ public void SendMessageToEndpoint() { //this uses a proxy class that was //created by svcutil.exe from the services metadata MathProxy proxy = new MathProxy(); int result = proxy.Add(35, 7); } public void SendMessageToEndpointUsingChannel() { //this uses ChannelFactory to create the channel //you must specify the address, the binding and //the contract type (IMath) ChannelFactory<IMath> factory=new ChannelFactory<IMath>( new WSHttpBinding(), new EndpointAddress("http://localhost/MathService/Ep1")); IMath channel=factory.CreateChannel(); int result=channel.Add(35,7); factory.Close(); }}Sunday, December 16, 2012 Arbind
  28. 28. Step5: Defining custom behaviorWe need to implement IServiceBehavior for service and IChannelBehavior for clientAll behaviors can be applied imperatively by adding an instance of the behavior to the ServiceDescription (or the ChannelDescription on the client side).ServiceHost sh = new ServiceHost(typeof(MathService)); sh.AddServiceEndpoint( typeof(IMath), new WSHttpBinding(), "http://localhost/MathService/Ep1");//Add the behavior imperatively// InspectorBehavior is a custom behaviorInspectorBehavior behavior = new InspectorBehavior(); sh.Description.Behaviors.Add(behavior);sh.Open(); Sunday, December 16, 2012 Arbind
  29. 29. Secure Hosting and Deployment of WCF ServicesService host is a execution environment for service codeService has to be hosted before deploymentSunday, December 16, 2012 Arbind
  30. 30. Why host is required? Provide security context for the execution of WCF service Providing a mechanism to configure the WCF service Providing a mechanism to monitor the statistics and health of WCF service Provide rapid fail protection and tools for WCF service managementSunday, December 16, 2012 Arbind
  31. 31. Type of host 1. Managed Application / Self Host 2. Managed Windows Service 3. IIS 4. WASSunday, December 16, 2012 Arbind
  32. 32. Criteria for Choosing a WCF Service HostConsider following things before coming to conclusionA. Target Deployment PlatformB. Protocol to be supported by the service Sunday, December 16, 2012 Arbind
  33. 33. Example:If service needed to support HTTP, TCP, MSMQ and Named Pipe and platform is Windows longhorn server – IIS 7.0 with WAS should be usedIf service needed to support HTTP and platform is Windows server 2003 – IIS 6.0 should be usedif TCP, MSMQ and Named Pipe required to be supported and platform is Windows server 2003 - Managed Windows Service can be usedIf service need to support HTTP, TCP, MSMQ and Named Pipe protocols on Windows Vista – IIS 7.0 along with WAS should be usedOn Windows XP, IIS 5.1 should be used if supported protocol is HTTP and Windows service can be used for TCP, MSMQ and Named PipeSunday, December 16, 2012 Arbind
  34. 34. How to select host?Managed Application / Self HostAny .NET managed application can host a WCF service by creating an instance of ServiceHost ClassServiceHost Class is a member of System.ServiceModel namespace(Hosting a Service in managed application is also called Self Hosting)Sunday, December 16, 2012 Arbind
  35. 35. Point to note: Self host does not provide features like message based activation, mechanism to monitor service health or service host resources or recycling of the service host process upon detection of error conditions.And so: This is useful in development environment but not in production environmentSunday, December 16, 2012 Arbind
  36. 36. In Self Hosting, the Service Host has to be instantiated at the time of the managed application startup and closed before the managed application shutdown.Sunday, December 16, 2012 Arbind
  37. 37. The security context in Self Host is the identity under which the managed application runsSunday, December 16, 2012 Arbind
  38. 38. A WCF Service hosted in a managed application can be exposed over TCP, HTTP, HTTPS, Named Pipe and MSMQ protocols.Sunday, December 16, 2012 Arbind
  39. 39. Code sample for creating a Service Host in managed applicationUsing(ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService))){ //Open the Service Host to start receiving messages serviceHost.Open(); // The service is now ready to accept requests ….. ….. // Close the ServiceHost to shutdown the service. serviceHost.Close();}Sunday, December 16, 2012 Arbind
  40. 40. The base address and the endpoints for the service host have to be configured in the <services> sub section of the <system.serviceModel> section of the App.Config as shown below:<system.serviceModel> <services> <service name="SecureHosting.Samples.CalculatorService" behaviorConfiguration="CalculatorServiceBehavior"> <host> <baseAddresses> <add baseAddress="http://localhost:9000/SecureHostingSamples/service"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" contract="SecureHosting.Samples.ICalculator" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="CalculatorServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="True" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> Sunday, December 16, 2012 Arbind
  41. 41. Base Address and endpoint can also be configured programmatically instead of configuring in App.Config file// Create a ServiceHost for the CalculatorService type. using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService),new Uri("http://localhost:9000/SecureHostingSamples/service"))) { //Configure the service with an end point serviceHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), ""); // Open the ServiceHost to start receiving messages serviceHost.Open(); …. …. …. //Close the service host to shutdown the service serviceHost.Close ();}Sunday, December 16, 2012 Arbind
  42. 42. Managed Window Service(A Window Service running under managed environment)Service can be installed using Installutil tool.The service can be exposed to HTTP, TCP, MSMQ and Named Pipe protocolSunday, December 16, 2012 Arbind
  43. 43. The window service which host the service inherits from the ServiceBase class and also implements contractSunday, December 16, 2012 Arbind
  44. 44. Windows Service provides the facility to manage the lifecycle of the service via the Service Control Manager (SCM) consoleSunday, December 16, 2012 Arbind
  45. 45. Windows Service Host does not provide a message based activationSunday, December 16, 2012 Arbind
  46. 46. Window service leverages the OnStart event to create service host and host closes on OnStop event.Sunday, December 16, 2012 Arbind
  47. 47. Security context can be configured using Installer Class with the help of ServiceProcessInstaller.Sunday, December 16, 2012 Arbind
  48. 48. Sample Code to create Managed Window Servicepublic class CalculatorService : ServiceBase, ICalculator{ public ServiceHost serviceHost = null; public static void Main() { ServiceBase.Run(new CalculatorService()); } public CalculatorService() { ServiceName = "WCFWindowsCalculatorService"; } //Start the Windows service. protected override void OnStart(string[] args) { if (serviceHost != null) { serviceHost.Close(); } // Create a ServiceHost for the Service serviceHost = new ServiceHost(typeof(CalculatorService)); // Start Listening for the Messages serviceHost.Open(); } //Stop the Windows Service protected override void OnStop() { if (serviceHost != null) { serviceHost.Close(); serviceHost = null; } }} Sunday, December 16, 2012 Arbind
  49. 49. IISAllows the Services to be hosted in the App Domains inside the ASP.NET worker processSupported IIS: 5.1, 6.0, 7.0 8.0(BETA)(Only Http and Https can be handled)Sunday, December 16, 2012 Arbind
  50. 50. IIS handles the service request in the same way as it handles web requestSupports message based activation and service instance is created only after receiving the first message.Sunday, December 16, 2012 Arbind
  51. 51. The security context for the WCF Service hosted inside the ASP.NET worker process is provided by the service account under which the worker process runs. (Knowledge Sharing) WHAT WILL BE THE SECURITY TO BE IMPLEMENTED?Sunday, December 16, 2012 Arbind
  52. 52. Hosting a service in IIS requires .SVC file to be createdIf required a Custom Service Host we can create it using System.ServiceModel.Activation.ServiceHostFactory Class(Virtual applications are created and DLLs and sources are deployed to the physical path associated with the virtual application)Sunday, December 16, 2012 Arbind
  53. 53. The configuration for the service endpoints has to be defined in the Web.ConfigThe .SVC file should contain code like:<%@ServiceHost language=c# Debug="true" Service=" SecureHosting.Samples.CalculatorService" %>Sunday, December 16, 2012 Arbind
  54. 54. Web.Config for IIS Host:<system.serviceModel> <services> <service name="SecureHosting.Samples.CalculatorService" behaviorConfiguration="CalculatorServiceBehavior"> <!-- This endpoint is exposed at the base address provided by host: http://localhost/securehostingsamples/service.svc --> <endpoint address="" binding="wsHttpBinding" contract="SecureHosting.Samples.ICalculator" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <!--For debugging purposes set the includeExceptionDetailInFaults attribute to true-- > <behaviors> <serviceBehaviors> <behavior name="CalculatorServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="True" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>Sunday, December 16, 2012 Arbind
  55. 55. WAS (Windows Activation Service)WAS enables IIS 7.0 to leverage message based activation for protocols such as TCP, MSMQ and Named Pipes in addition to the HTTP protocolAvailable with Windows Vista and Windows Longhorn ServerService deployment process for IIS 7.0/WAS is same as discussed earlier for IIS hostSunday, December 16, 2012 Arbind
  56. 56. Note:1. web sites need to be configured via the APPCMD utility to support non HTTP protocols2. To do this command shell must be started in “Run as Administrator” modeSunday, December 16, 2012 Arbind
  57. 57. Command to run:%windir%system32inetsrvappcmd.exe set site "Default Web Site" -+bindings.[protocol=net.tcp,bindingInformation=808:*] FOR TCP%windir%system32inetsrvappcmd.exe set site "Default Web Site" -+bindings.[protocol=net.msmq,bindingInformation=*] FOR MSMQ%windir%system32inetsrvappcmd.exe set site "Default Web Site" -+bindings.[protocol=net.pipe,bindingInformation=*] FOR NAMED PIPESunday, December 16, 2012 Arbind
  58. 58. After running the command APPCMD updates configuration file for WAS ApplicationHost.Config<system.applicationHost> <sites> <site name="Default Web Site" id="1"> <bindings> <binding protocol="http" bindingInformation="*:80:" /> <binding protocol="net.pipe" bindingInformation="*" /> <binding protocol="net.tcp" bindingInformation="808:*" /> <binding protocol="net.msmq" bindingInformation="*" /> </bindings> </site> </sites></system.applicationHost>Sunday, December 16, 2012 Arbind
  59. 59. To enable the TCP protocol (in addition to the HTTP protocol) for the “SecureHostingSamples” application, the following command should be run from an administrator shell: %windir%system32inetsrvappcmd.exe set app "Default Web Site/securehostingsamples" /enabledProtocols:http,net.tcpSunday, December 16, 2012 Arbind
  60. 60. Selecting Binding:Criteria to select Bindings:1. Consider the deployment environment whether it is for Internet, Intranet, Federated Environment, Windows only or a Heterogeneous Environment2. Security to be implemented3. Performance IssuesSunday, December 16, 2012 Arbind
  61. 61. A WCF service can be assigned: 1. Transport level security, 2. Message level security or 3. A combination of transport and message level security.Sunday, December 16, 2012 Arbind
  62. 62. A service can be defined with an authentication mode of 1. None, 2. Username, 3. Windows, 4. Certificates and 5. IssuedToken. Authentication process between the client and the service includes the authentication of service to the client as well as the authentication of the client to the service.Sunday, December 16, 2012 Arbind
  63. 63. Deploying a WCF Service over Windows Only Intranet In Windows only Intranet, if all the service clients are WCF clients, the service can be deployed using NetTCPBinding and transport level security to achieve maximum performance.(NetTCPBinding by default uses transport level security along with TCP channel and binary message encoding)ClientCredentialType is set to Windows to enable Windows AuthenticationCode Sample:<bindings> <netTcpBinding> <binding name="Binding1"> <security mode="Transport" /> <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign"/> </security> </binding> </netTcpBinding></bindings>Sunday, December 16, 2012 Arbind
  64. 64. Interoperability with web servicesThe WCF service can be configured to use BasicHttpBinding with transport level security.HTTP/GET metadata should be enabled for the service in the service behavior section.Sunday, December 16, 2012 Arbind
  65. 65. Deploying a WCF Service over Internet or in a Heterogeneous Environment(needs to potentially interact with the clients on non-windows platforms)--BasicHttpBinding or WSHttpBinding can be used depending upon the level of conformance required with the commonly used security standardsIf interoperability is required with web service only BasicHttpBinding should be used.Sunday, December 16, 2012 Arbind
  66. 66. To support SOAP Message Security UserName Token Profile version 1.0, the WCF service should be configured with BasicHttpBinding with security mode of TransportWithMessageCredential and client credential type of UserName.Example:<basicHttpBinding> <binding name="Binding1"> <security mode="TransportWithMessageCredential"> <message clientCredentialType="UserName" /> </security> </binding></basicHttpBinding>Sunday, December 16, 2012 Arbind
  67. 67. Deployment in Federated EnvironmentWCF Service client obtains a security token from Security Token Service (STS) which is trusted by WCF ServiceWCF Service should be configured for WSFederatedHttpBindingThe security token also contains the address of the endpoint to retrieve metadata of STSthe certificate used by STS for signing the security token should be added to the list of known certificates in the service credential section.Sunday, December 16, 2012 Arbind
  68. 68. <bindings><wsFederationHttpBinding> <binding name="Binding1"> <security mode ="Message"> <message issuedKeyType ="SymmetricKey" issuedTokenType ="http://docs.oasis-open.org/wss/oasis- wss-saml-token-profile-1.1#SAMLV1.1" > <issuerMetadata address ="http://localhost:8888/sts/mex" > <identity> <certificateReference storeLocation ="CurrentUser" storeName="TrustedPeople" x509FindType ="FindBySubjectDistinguishedName" findValue ="CN=STS" /> </identity> </issuerMetadata> </message> </security> </binding></wsFederationHttpBinding></bindings><behaviors> <serviceBehaviors> <behavior name ="ServiceBehaviour" > <serviceCredentials> <issuedTokenAuthentication> <knownCertificates> <add storeLocation ="LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectDistinguishedName" findValue="CN=STS" /> </knownCertificates> </issuedTokenAuthentication> <serviceCertificate storeLocation ="LocalMachine" storeName ="My" x509FindType ="FindBySubjectDistinguishedName" findValue ="CN=localhost"/> </serviceCredentials> </behavior> </serviceBehaviors></behaviors>Sunday, December 16, 2012 Arbind
  69. 69. Assignment For All Create a WCF service to convertFahrenheit to Celsius and vice versa and to be hosted in IIS If done: mail it on arbindkumar_tiwari@satyam.comSunday, December 16, 2012 Arbind
  70. 70. Sunday, December 16, 2012 Arbind