1 / 62

Advance WCF In .NET 3.5

Advance WCF In .NET 3.5. Windows Communication Foundation - ABC. Architecture ABC Contract Binding – Custom Binding WCF for SilverLight , JSON Behaviors. .NET 2.0 ASMX Web Service. Rehearse how to create a ASP.net 2.0 web service. Let’s do a simple WCF web service.

paloma
Download Presentation

Advance WCF In .NET 3.5

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advance WCF In .NET 3.5

  2. Windows Communication Foundation - ABC • Architecture • ABC • Contract • Binding – Custom Binding • WCF for SilverLight, JSON • Behaviors

  3. .NET 2.0 ASMX Web Service • Rehearse how to create a ASP.net 2.0 web service. • Let’s do a simple WCF web service. • Not much different at basic level: • [WebMethod] vs [Operation] • Both can be hosted in IIS7 • But WCF can do more than that… • Support different transport protocols: HTTP, TPC, NamePipe, MSMQ,… • Concurrency and Instancing modes.

  4. WCF Design Goals • Unifies today’s distributed technology stacks • Composable functionality • Appropriate for use on-machine, in the intranet, and cross the Internet Unification Productive Service-Oriented Programming • Service-oriented programming model • Supports 4 tenets of service-orientation • Maximized developer productivity “The unified programming model for rapidly building service-oriented applications on the Windows • WS-* interoperability with applications running on other platforms • Interoperability with today’s distributed stacks Interoperability & Integration

  5. Unified Model Fast Secure Binary Txns Basic Open Interop Enterprise Services Secure Open Interop Fast Secure Binary Queued Txns ASMX MSMQ WSE Remoting

  6. Before we have • Remote Procedure Call • COM+ • .NET Remoting • ASP.net web service • Hard code TCP Socket • MSMQ • …

  7. With WCF .net 3.5

  8. Unified Model Benefits • Programming model • Learning curve • Consistency • Write less code when using multiple technologies • Flexibility • Environments • Productivity in development environment • Simplify Automated Integration Testing • Deployment options in production • Design for distribution, run local

  9. Elements in WCF

  10. Before we go further • WCF Service can be configured in code • WCF Service can be configured in XML or mix. • 03 different ways to host WCF • Self Hosting • IIS Hosting • Windows Service

  11. Implement WCF in code ServiceHostserviceHost = new ServiceHost(typeof(StockService), new Uri("http://localhost:8000/EssentialWCF")); serviceHost.AddServiceEndpoint( typeof(IStockService), new BasicHttpBinding(), ""); ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; serviceHost.Description.Behaviors.Add(behavior); serviceHost.AddServiceEndpoint( typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); serviceHost.Open(); // The service can now be accessed. Console.WriteLine("The services is ready. Press <ENTER> to terminate.\n\n"); Console.ReadLine(); // Close the ServiceHostBase to shutdown the service. serviceHost.Close(); Demo C:\WCF\SomeWebServices\SimpleService\Code

  12. WCF Configuration File <system.serviceModel> <services> <servicename="EssentialWCF.StockService" behaviorConfiguration="myServiceBehavior"> <host> <baseAddresses> <addbaseAddress="http://localhost:8000/EssentialWCF"/> </baseAddresses> </host> <endpointaddress="" binding="basicHttpBinding" contract="EssentialWCF.IStockService" /> <endpointaddress="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behaviorname="myServiceBehavior"> <serviceMetadatahttpGetEnabled="True"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> Demo C:\WCF\SomeWebServices\SimpleService\Config\Service

  13. Services and Clients

  14. Endpoint Endpoint Endpoint Endpoints Client Service Message The service endpoint contains the information about the Address, Binding, Contract, and Behavior required by a client to find and interact with the service at this endpoint.

  15. C C C B B B A A A Address, Binding, Contract Client Service Message Address Binding Contract (Where) (How) (What)

  16. How client knows WCF service mex • Metadata tells client how to connect & communicate to web service. • Design time, client sends request defined in WS-Metadata exchange standard and get WSDL in return. • WSDL is then used to create proxy class and create config file at client

  17. Expose mex endpoint by code or config file httpGetEnabled allows client to query mex through Http Get method. <system.serviceModel> <services> <servicename="WCFServiceApplication.Service1" behaviorConfiguration="WCFServiceApplication.Service1Behavior"> <endpointaddress="" binding="wsHttpBinding" contract="WCFServiceApplication.IService1"> <identity> <dnsvalue="localhost"/> </identity> </endpoint> <endpointaddress="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behaviorname="WCFServiceApplication.Service1Behavior"> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadatahttpGetEnabled="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>

  18. Some tools to debug, and test WCF WCF Test Client WCF Service Configuration Editor

  19. Transport Encoder Protocol(s) Transport Encoder Protocol(s) WCF Architecture: Messaging Runtime Service Contract andBehaviors Client Dispatcher Binding Address

  20. Security Channel TCP Transport Security Channel FormatterBehavior FormatterBehavior Transaction Behavior Message Inspector Instancing Behavior TCP Transport WCF Architecture: Composition & Behaviors Service Code Messaging Layer Service Model Layer Influences system operation based on incoming and outgoing messages. Effects of behaviors are local. Moves messages back and forth and adds transfer semantics. Channels are symmetric.

  21. Contracts

  22. Three Types of Contracts • Service Contract • Maps the class methods of a .NET type to WSDL services, port types, and operations. Operation contracts within service contracts describe the service operations, which are the methods that implement functions of the service. • Data Contract • Describe data structures that are used by the service to communicate with clients. A data contract maps CLR types to XML Schema Definitions (XSD) and defines how they are serialized and deserialized. Data contracts describe all the data that is sent to or from service operations. • Message Contract • Map CLR types to SOAP messages and describe the format of the SOAP messages and affect the WSDL and XSD definitions of those messages. Message contracts provide precise control over the SOAP headers and bodies.

  23. Data Contract [DataContract] public class ComplexNumber { [DataMember] public double Real = 0.0D;[DataMember] public double Imaginary = 0.0D; public ComplexNumber(double r, double i) { this.Real = r; this.Imaginary = i; } }

  24. Demo • Basic data type data contract • Class data type data contract • Hierarchy data type data contract • Collection data contract C:\WCF\Contracts\HRService

  25. Multiple Contracts in an EndPoint [ServiceContract] public interface IGoodStockService { [OperationContract] double GetStockPrice(string ticker); } [ServiceContract] public interface IGreatStockService { [OperationContract] double GetStockPriceFast(string ticker); } [ServiceContract] public interface IAllStockServices : IGoodStockService, IGreatStockService { }; public class AllStockServices : IAllStockServices { public double GetStockPrice(string ticker) { } public double GetStockPriceFast(string ticker) { } }

  26. Ways to Talk / Service Contract • One Way: • Datagram-style delivery • Request-Reply • Immediate Reply on same logical thread • Duplex • Reply “later” and on backchannel (callback-style) One Way Client Service Request-Reply Duplex (Dual)

  27. Service Contract using System.ServiceModel; [ServiceContract] public interface ICalculate { [OperationContract] double Add( double a, double b); [OperationContract] double Subtract( double a, double b); }

  28. Synchronous vs Asynchronous Request Response Main Thread Service BeginOperation New Thread EndOperation client.AddCompleted += new EventHandler<MathPlayer. MathService.AddCompletedEventArgs>(client_AddCompleted); client.AddAsync(int.Parse(txtA.Text), int.Parse(txtB.Text));

  29. Service Contract: OneWay [ OperationContract(IsOneWay = true)] void DoBigAnalysisFast(string ticker); [OperationContract] void DoBigAnalysisSlow(string ticker); The client just needs acknowledgement of successful delivery; it does not need an actual response from the service Demo C:\WCF\03_OneWay

  30. Duplex Communication Use wsDualHttpBinding Since two endpoints are used, we can define two different bindings, protocol for each channels

  31. Service Contract: Duplex Asymmetric [ServiceContract(Session=true, CallbackContract=typeof(ICalculatorResults)] public interface ICalculatorProblems { [OperationContract(IsOneWay=true)] void SolveProblem (ComplexProblem p); } public interface ICalculatorResults { [OperationContract(IsOneWay=true)] void Results(ComplexProblem p); }

  32. Service Contract: Duplex Symmetric [ServiceContract(Session=true, CallbackContract=typeof(IChat)] public interface IChat { [OperationContract(IsOneWay=true)] void Talk(string text); }

  33. Demo • Request –Reply • One Way • One Service many EndPoints

  34. Service Contract: Faults [ServiceContract(Session=true)] public interface ICalculator { [OperationContract] [FaultContract(typeof(DivideByZero))] ComplexProblem SolveProblem (ComplexProblem p); } try { return n1 / n2; } catch (DivideByZeroException e){ DivideByZero f = new DivideByZero (“Calculator”); throw new FaultException<DivideByZero>(f); }

  35. Message Contract [MessageContract] public class ComplexProblem { [MessageHeader] public string operation; [MessageBody]public ComplexNumber n1; [MessageBody]public ComplexNumber n2; [MessageBody]public ComplexNumber solution; // Constructors… }

  36. Bindings

  37. Bindings & Binding Elements Binding HTTP Text Security Reliability TX Transport Protocol Encoders TCP HTTP Security Reliability Text Binary MSMQ IPC TX .NET Custom Custom Custom

  38. Standard Bindings in WCF.net 3.0 N = None | T = Transport | M = Message | B = Both | RS = Reliable Sessions

  39. New bindings in WCF.net 3.5 • ws2007HttpBinding • ws2007FederationBinding

  40. Supported Features of Each Binding

  41. Choose a binding that suits your need

  42. End-to-end Reliable messaging In-order guarantees Exactly once guarantees Transport-Independent Sessions Integration with ASP.NET Sessions in IIS-Hosted compatibility mode Transactions Guaranteed atomic success or failure across services Reliability and Transactions

  43. A A A B B B C C C C B A Bindings & Behaviors: Reliable Sessions Client Service Bindings provide Session and Guarantees Reliable Messaging: in-order and exactly once (similar to MSMQ and MQSeries guarantees).

  44. A A A B B B C C C C B A Bindings & Behaviors: Transactions Client Service Be Be Bindings Flow Transactions Behaviors AutoEnlist and AutoComplete 1- Multistep business process : Long running transaction WF integrates with WCF 2- Short running transaction In next training, I will talk more detail with demo for transactions

  45. Defining Endpoints <?xml version="1.0" encoding="utf-8" ?> <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <system.serviceModel> <services> <service serviceType="CalculatorService"> <endpoint address="Calculator" bindingSectionName="basicProfileBinding" contractType="ICalculator" /> </service> </services> </system.serviceModel> </configuration>

  46. Configuring Bindings <endpoint address="Calculator" bindingSectionName="basicProfileBinding" bindingConfiguration="Binding1" contractType="ICalculator" /> <bindings> <basicProfileBinding> <binding configurationName="Binding1" hostnameComparisonMode="StrongWildcard" transferTimeout="00:10:00" maxMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" </binding></basicProfileBinding></bindings>

  47. Custom Bindings <bindings> <customBinding> <binding configurationName="Binding1"> <reliableSession bufferedMessagesQuota="32" inactivityTimeout="00:10:00" maxRetryCount="8"ordered="true" /> <httpsTransport manualAddressing="false" maxMessageSize="65536" hostnameComparisonMode="StrongWildcard"/> <textMessageEncoding maxReadPoolSize="64"maxWritePoolSize="16"messageVersion="Default"encoding="utf-8" /> </binding> </customBinding> </bindings>

  48. Multiple EndPoints in a Service • Scenarior: SilverLight app can connect to basicHttpBinding while WPF app can connect to wsHttpBinding. If we have one service how can we serve two types of clients. <servicebehaviorConfiguration="MathWCFServiceApplication.MathServiceBehavior" name="MathWCFServiceApplication.MathService"> <!--EndPoint này sử dụng cho WPF client--> <endpointname="wsHttpMath" address="ws" binding="wsHttpBinding" contract="MathWCFServiceApplication.IMathService"> <identity> <dnsvalue="localhost"/> </identity> </endpoint> <!--EndPoint này sử dụng cho SilverLight client--> <endpointname="basicHttpMath" address="basic" binding="basicHttpBinding" contract="MathWCFServiceApplication.IMathService"> <identity> <dnsvalue="localhost"/> </identity> </endpoint> <endpointaddress="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service>

  49. Example: SilverLight consumes WCF

  50. WCF returns JSON JSON short for JavaScript Object Notation, is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects). <services> <servicename="Wcf2Ajax.Service1" behaviorConfiguration="Wcf2Ajax.Service1Behavior"> <endpointaddress="" behaviorConfiguration="AjaxBehavior" binding="webHttpBinding" contract="Wcf2Ajax.IService1"> <identity> <dnsvalue="localhost"/> </identity> </endpoint> <endpointaddress="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <endpointBehaviors> <behaviorname="AjaxBehavior"> <enableWebScript/> </behavior> </endpointBehaviors> C:\WCF\GadgetDemo_WCFReturnJSON

More Related