620 likes | 735 Views
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.
E N D
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. • 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.
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
Unified Model Fast Secure Binary Txns Basic Open Interop Enterprise Services Secure Open Interop Fast Secure Binary Queued Txns ASMX MSMQ WSE Remoting
Before we have • Remote Procedure Call • COM+ • .NET Remoting • ASP.net web service • Hard code TCP Socket • MSMQ • …
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
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
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
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
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.
C C C B B B A A A Address, Binding, Contract Client Service Message Address Binding Contract (Where) (How) (What)
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
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>
Some tools to debug, and test WCF WCF Test Client WCF Service Configuration Editor
Transport Encoder Protocol(s) Transport Encoder Protocol(s) WCF Architecture: Messaging Runtime Service Contract andBehaviors Client Dispatcher Binding Address
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.
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.
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; } }
Demo • Basic data type data contract • Class data type data contract • Hierarchy data type data contract • Collection data contract C:\WCF\Contracts\HRService
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) { } }
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)
Service Contract using System.ServiceModel; [ServiceContract] public interface ICalculate { [OperationContract] double Add( double a, double b); [OperationContract] double Subtract( double a, double b); }
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));
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
Duplex Communication Use wsDualHttpBinding Since two endpoints are used, we can define two different bindings, protocol for each channels
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); }
Service Contract: Duplex Symmetric [ServiceContract(Session=true, CallbackContract=typeof(IChat)] public interface IChat { [OperationContract(IsOneWay=true)] void Talk(string text); }
Demo • Request –Reply • One Way • One Service many EndPoints
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); }
Message Contract [MessageContract] public class ComplexProblem { [MessageHeader] public string operation; [MessageBody]public ComplexNumber n1; [MessageBody]public ComplexNumber n2; [MessageBody]public ComplexNumber solution; // Constructors… }
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
Standard Bindings in WCF.net 3.0 N = None | T = Transport | M = Message | B = Both | RS = Reliable Sessions
New bindings in WCF.net 3.5 • ws2007HttpBinding • ws2007FederationBinding
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
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).
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
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>
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>
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>
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>
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