Download presentation
Presentation is loading. Please wait.
Published byDrusilla Alexander Modified over 6 years ago
1
The Windows Communication Foundation Programming Model - Contracts
Risman Adnan ISV Lead, Microsoft Indonesia
2
Objectives of the Programming Model
Make it easy to build service-oriented software Provide a standard interface to the network vs. today, where programming models are tied to transports System.Messaging to MSMQ ASMX to HTTP Unify existing distributed computing technologies Endure The goal of WCF is to provide a simplified programming model for ALL communications. This removes the application code dependency on the underlying technology used to communicate with another service. Provides support for communicating to existing/”legacy” systems such as COM+/enterprise services, MSMQ, ASMX, WSE 3.0 to allow existing applications to coexist with new applications. Provide a model that is resilient to change by abstracting the network and protocol details out of the programming model. As the industry evolves and protocols change, the framework can change without the application code needing to be updated. Microsoft is committed to making sure the protocols are implemented as close to the letter as possible, and, more importantly, that the implementation is interoperable with other vendor implementations.
3
Delivering Services with WCF
Deploy Program Program Deploy Client Service a b c a b c In the next two presentations, we are going to be focusing on the ABCs of programming WCF. How to program and deploy both services and clients based on the idea of contract generation and metadata sharing. Much of the code that is written will be built in order to shape these contracts and define the ABCs of an endpoint so it can be consumed by a client. Metadata Message
4
Delivery Tasks Define contracts Implement contracts Host the service
Program Define contracts Implement contracts Host the service Configure binding Configure address c E n d p o i t Deploy b a
5
Contracts Structural Behavioral c Program E n d p o i t
We will talk about the structural contracts which define how our messages get serialized and deserialized into SOAP message payloads. Then we will focus on the behavioral aspects of our contracts which impact the communications and operations of the service.
6
Contracts Structural Behavioral c Program DataContract MessageContract
7
Structural Contracts: Data Contracts
Program Defines the serialized representation of the data structure c E n d p o i t using System.Runtime.Serialization; [DataContract(Name=“PersonType”)] public class Person { [DataMember] public string name; [DataMember(Name=“AgeProperty”)] private int age; float salary; int positionCode; } Data contract defines the wire representation of a data structure that will be contained in the body or headers of the message. Use attributes to provide the mapping of the CLR information to XSD schema information. XSD is abstracted from the developer just as all of the protocol details are abstracted. Names and other attributes of the structure can differ between the class and the wire representation as shown in the DataContract attribute where the class “Person” is serialized as “PersonType”. XmlSerializer provides fine grained control of document structure on the wire while the Xml Formatter (data contract default) is geared to abstraction of XSD and the simple case to reduce complexity and speed development. NetDataContractSerializer is a special case serializer for internal applications which includes .NET specific type information into the serialized data.
8
Structural Contracts: Data Contracts
Program Indifferent to language access modifiers c E n d p o i t using System.Runtime.Serialization; [DataContract(Name=“PersonType”)] public class Person { [DataMember] public string name; [DataMember(Name=“AgeProperty”)] private int age; float salary; int positionCode; }
9
Data Contracts DEMO Apps\Basic Service sample
10
Structural Contracts: Data Contracts
Program Dealing with collections: Use the KnownType attribute c E n d p o i t [DataContract] public class book{…} public class magazine{…} [KnownType(typeof(Book))] [KnownType(typeof(Magazine))] public class LibraryCatalog { [DataMember] System.Collections.Hashtable catalog; } Make sure to show the xml messages that get created by this type of contract so that students can understand the resulting serialization. You can also use a methodname in the knowntype attribute. The method is a method on the class that returns an array of types to be used. You can only have one knowntype attribute with a method name. This is only for deserialization. For serialization, the CLR type information is accessible from the base “object” type.
11
Structural Contracts: Data Contracts
Program Uncertainty/Polymorphism: The other use for the KnownType attribute c E n d p o i t [DataContract] public class book{…} public class magazine{…} [KnownType(typeof(Book))] [KnownType(typeof(Magazine))] public class PublishedItem { [DataMember] object catalog; DateTime publicationDate; }
12
Structural Contracts: Data Contracts
Program Flexibility/Versioning: Use IsRequired attribute to add optional values to new versions of a data structure. c E n d p o i t [DataContract] public class Car { [DataMember(IsRequired=true)] public string Model; [DataMember(IsRequired=false)] //IsRequired=false is the default public int HorsePower; } Provides the flexibility to allow missing fields in the message, but the code must be written to either Accept missing values and be able to work around them Detect a missing field and default it Use the deserialization delegates to provide a value, if missing, for the optional member. Note that this translates into the appropriate XSD attribute for optional or required.
13
Structural Contracts: Data Contracts
Program Flexibility/Versioning: implement IExtensibleDataObject c E n d p o i t [DataContract] public class Person : IExtensibleDataObject { public virtual ExtensionDataObject UnknownData get {return this.unknownData;} set {this.unknownData = value;} } [DataMember] public string fullName; private ExtensionDataObject unknownData; IExtensibleDataObject is the answer to the problem of losing data when casting between objects in a hierarchy. For example, if you have a person class and an employee class which derives from person, and the employee class adds another field like employeeID. Before, if employee was serialized as person, the extra information was tossed out and not recoverable. Using IExtensibleDataObject allows that extra information to be stored so that when the person is later deserialized as an employee, the id is retained.
14
Contracts Structural Behavioral c Program DataContract MessageContract
15
Structural Contracts: Message Contracts
Defines the message structure on the wire The MessageBody is typically a DataContract For custom SOAP headers Program c E n d p o i t [DataContract] public class PurchaseOrder { [DataMember] public Customer customer; public Item[] items; } [MessageContract] public class PurchaseOrderMessage [MessageHeader] public int Number; [MessageBodyMember(Order=1)] public PurchaseOrder Order; Provides more control of the structure by allowing you to indicate order for multiple message body parts, but probably more likely because of the ease with which it allows you to program SOAP headers in you service.
16
Contracts Structural Behavioral c Program DataContract MessageContract
ServiceContract OperationContract FaultContract c E n d p o i t
17
Behavioral Contracts: Service Contracts
Program Service Contracts define the service interface to be consumed by clients Complex types as parameters and return values should be types marked with DataContract attribute c E n d p o i t [ServiceContract(Name = “MyContract”,Namespace=” public interface IOrderEntry { [OperationContract(IsOneWay=true)] void PlaceOrder(PurchaseOrder order); void UpdateOrderStatus(Status newStatus); } Service contracts define the interface of the service. This is the interface then defined in WSDL and consumed by clients. Note that this contract defines the operations available on the service and the appropriate messages and message parts to send/receive.
18
Behavioral Contracts: Service Contracts
Program Implementation Simply an implementation of a .NET interface A class that implements a service contract is called a service type. c E n d p o i t [ServiceContract] public interface IOrderEntry { [OperationContract(IsOneWay=true)] void PlaceOrder(PurchaseOrder order); } internal class OrderEntryService: IOrderEntry void IOrderEntry.PlaceOrder(PurchaseOrder order) //Your code goes here
19
Behavioral Contracts: Service Contracts
Program Inheritance for versioning for multiple contracts at one endpoint c E n d p o i t [ServiceContract] public interface IOrderEntry { [OperationContract(IsOneWay=true)] void PlaceOrder(PurchaseOrder order); } public interface IExtendedOrderEntry: IOrderEntry [OperationContract] PurchaseOrder GetOrder(String orderIdentifier); By using .NET interfaces to define the service contracts, we open up possibilties for rich inheritance and implementation options such as one service implementing many contracts.
20
Behavioral Contracts: Service Contracts
Program Controlling how structural contracts serialize c E n d p o i t [ServiceContract] [DataContractFormat(Style=OperationFormatStyle.Document)] //Or Rpc public interface IOrderEntry { … } [XmlSerializerFormat(Style=OperationFormatStyle.Document, Use=OperationFormatUse.Literal)] //Or Encoded Attributes on the service contract are very similar to the old style attributes on ASMX web services to control the WSDL generated. Items include the doc/rpc, literal/encoded. Note that DataContractFormat is used on the first interface while XmlSerializerFormat is used on the second interface. XmlSerializerFormat allows for more control over the Use (encoded vs. literal) which defaults on the data contract format to literal.
21
Behavioral Contracts: Service Contracts
Program Duplex type c E n d p o i t [ServiceContract(SessionMode=SessionMode.Required, CallbackContract=typeof(IOrderEntryCallback))] public interface IOrderEntry { [OperationContract(IsOneWay = true)] void PlaceOrder(PurchaseOrder order); } [ServiceContract] public interface IOrderEntryCallback void PlaceOrderCompleted(PurchaseOrderStatus orderStatus); Note that this was shown in the initial demo on the overview day, and provides a simple mechanism for modeling rich duplex communication between a service and client.
22
Behavioral Contracts: Operation Contracts
Program c E n d p o i t [ServiceContract] public interface IOrderEntry { [OperationContract(IsOneWay=true)] void PlaceOrder(PurchaseOrder order); } Operation contract (similar to old WebMethod attribute) and indicates that a method is part of the service contract. Optionally, characteristics of the method can also be specified using named parameters to the OperationContract attribute One way, Asynch Pattern IsInitiating, IsTerminating Use, Style (overriding the service contract value) Action,ReplyAction Name
23
Behavioral Contracts: Operation Contracts
Program Action Property Matches messages read from the wire to operations in your code Best to default c E n d p o i t [ServiceContract] public interface IOrderEntry { [OperationContract( Action=" ReplyAction=" PurchaseOrder GetOrder(String orderIdentifier); } The infrastructure will generate these for you and it is simplest to leave them, but if you need control of the actions to do specific things, you have it.
24
Behavioral Contracts: Operation Contracts
Program Action Property use a wildcard action to provide a default message handler c E n d p o i t [ServiceContract] public interface MyContract { [OperationContract(IsOneWay = true, Action="urn:crud:insert")] void ProcessInsertMessage(Message message); [OperationContract(IsOneWay = true, Action="urn:crud:update")] void ProcessUpdateMessage(Message message); [OperationContract(IsOneWay = true, Action="urn:crud:delete")] void ProcessDeleteMessage(Message message); [OperationContract(IsOneWay = true, Action="*")] void ProcessUnrecognizedMessage(Message message); }
25
Behavioral Contracts: Operation Contracts
Program Synch vs. async implementations WCF is indifferent Wire contracts identical c E n d p o i t [ServiceContract] public interface IMath { [OperationContract(AsyncPattern=true)] IAsyncResult BeginAdd(int i, int j, AsyncCallback cb, object o); int EndAdd(IAsyncResult result); } Talk to the fact that this is a service specific implementation detail and only affects how the internal processing of the request occurs. The client can call synchronously or asynchronously, it doesn’t matter ,the two are separate processes. [ServiceContract] public interface IMath { [OperationContract] int Add(int I, int j); }
26
Synchronous and Asynchronous Patterns
DEMO Use the generating client proxy demo showing how to use the /a switch on svcutil to generate a client proxy with support for asynch operations.
27
Behavioral Contracts: Fault Contracts
[DataContract] public class MyFault { [DataMember] public string Reason = null; } [ServiceContract] public interface IOrderEntry [OperationContract] [FaultContract(typeof(MyFault))] PurchaseOrder GetOrder(String orderIdentifier); public class OrderEntry: IOrderEntry public PurchaseOrder GetOrder(string orderIdentifier) try{…} catch(Exception exception) MyFault theFault = new MyFault(); theFault.Reason = “Some Reason”; throw new FaultException<MyFault>(theFault); c E n d p o i t Fault contracts provide a clean abstraction over the SOAP Fault mechanism to share a strongly typed exception information.
28
Behavioral Contracts: Fault Contracts
Program Client view: Use the Detail property of the exception to retrieve the strongly typed fault data c E n d p o i t [DataContract(Name=”MyFault”)] public class ClientFault { [DataMember] public string Reason = null; } … try PurchaseOrder order = Service.GetOrder(orderIdentifier); catch (FaultException<ClientFault> clientFault) Console.WriteLine(clientFault.Detail.Reason);
29
Contracts Two programming approaches: c Program Code-First
Contract-First c E n d p o i t
30
Contracts Two programming approaches: c Program Code-First
Contract-First c E n d p o i t //Code-First: [ServiceContract] public class OrderEntry { [OperationContract(IsOneWay=true)] public void PlaceOrder(PurchaseOrder order){return;} }
31
Contracts Two programming approaches: c Program Code-First
Contract-First c E n d p o i t //Contract-First: [ServiceContract] public interface IOrderEntry { [OperationContract(IsOneWay=true)] void PlaceOrder(PurchaseOrder order); } public class OrderEntry: IOrderEntry public void PlaceOrder(PurchaseOrder order){return;} Microsoft’s goal is that writing contracts be as easy as writing .Net code so they provide the ability to create a contract through the .Net interface. However, in some situations, you will need to work with XSD and WSDL as your contracts. You can still do this using the SVCUTIL and XSD.exe programs to generate serializable classes from schema and service interfaces that you can implement.
32
Service Implementation: Hosting
Program WCF services can be hosted in any .Net Application Domain This provides many options out of the box for rich client applications (WPF or WinForms), Windows Services, IIS (WAS) Choosing the hosting model depends on the requirements of your service and applications c E n d p o i t Service
33
Service Implementation: Hosting
In standalone executables Program c E n d p o i t [ServiceContract] public interface ILenderService {…} internal class LenderService: ILenderService {…} public class Program { static void Main(string[] args) using (ServiceHost host = ServiceHost(typeof(LenderService))) host.Open(); Console.WriteLine(“The service is running."); Console.ReadLine(); } Service
34
Service Implementation: Hosting
In an Managed Windows Service Benefits: Process lifetime controlled by O/S Built-in Service Control Manager Program c E n d p o i t [ServiceContract] public interface ILenderService {…} internal class LenderService: ILenderService {…} public partial class MyManagedService : ServiceBase { private ServiceHost host = null; public MyNTService(){ InitializeComponent(); } protected override void OnStart(string[] args) this.host = new ServiceHost(typeof(LenderService )); this.host.Open(); } protected override void OnStop() host.Close(); Service
35
Service Implementation: Hosting
IIS 5.1 & 6 support HTTP only Windows Activation Services supports HTTP, TCP, Named Pipes WAS also provides activation of service classes on the arrival of a request Program c E n d p o i t //LenderService.cs using System.ServiceModel; namespace MyNamespace { [ServiceContract] public interface ILender {…} internal class LenderService: ILender {…} } Remind attendees of the upcoming release of IIS 7 with Longhorn server and the introduction of WAS technology to allow for the same type of activation with TCP and named pipes as well as HTTP. Because hosting in IIS make this a web application, the traditional ASP.Net hosting issues are relevant such as configuration files and assembly loading. We also need an endpoint with a particular extension to map to an HTTPHandler that is specific to WCF services. (.svc) Considerations for IIS hosting Assembly sought in v-dir \bin directory Configuration file must be named web.config Service //LenderService.svc Service="MyNamespace.LenderService" %>
36
Windows Communication Foundation Clients
Program WCF clients can be built a number of ways Generating a proxy class using metadata from the service Sharing service contract type information Building service client proxy dynamically at runtime c E n d p o i t Service
37
Generating Client Proxies
DEMO Optionally show this demo, but users have seen the svcutil tool several times by now and are familiar with this model. It might be a good time to show the “Add Service Reference” option in Visual Studio.
38
Writing Clients by Hand
Code: Method I: One-off “In-line Proxy” Program using System.ServiceModel; namespace MyNamespace { public interface IEcho string Echo(string input); } public class Program public static void Main(string[] arguments) IEcho proxy = new ChannelFactory<IEcho>(“EchoService”).CreateChannel(); Console.WriteLine(proxy.Echo(“Hello, World”)); ((IChannel)proxy).Close(); Note that this still requires the user to have an interface which matches the service. The easiest way to do this is to share metadata, not to share types (physical assemblies or copied class files).
39
Writing Clients by Hand
Code: Method II: Re-usable “Class Proxy” Program using System.ServiceModel; [ServiceContract] public interface IEchoService { [OperationContract] string Echo(string input); } internal class EchoServiceClient: ClientBase<IEchoService>, IEchoService public EchoServiceClient(string configurationName):base(configurationName) public string Echo(string input) return base.Channel.Echo(input); public class Program public static void Main(string[] arguments) EchoServiceClient client = new EchoServiceClient(“EchoService”); client.Echo(“Hello, World!”); client.Close(); This mechanism provides the ability to add extra behavior to the client proxy. A behavior may be more appropriate if the added functionality is something that might be reused.
40
Writing Clients by Hand
Program Configuration Endpoint configuration name corresponds to name used in ChannelFactory<T> constructor <system.serviceModel> <client> <endpoint name=“EchoService"> address=“ binding="basicHttpBinding" contract=“MyNamespace.IEcho"/> </client> </system.serviceModel>
41
Retrieving MetaData on the Fly
DEMO AllSamples Client Sample
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.