Wcf

Share Embed Donate


Short Description

wcf...

Description

WCF

WCF WCF Contracts ---------------------A contract is at name implies is a standard way of describing what a service can do. Meanwhile, it is platform independent. In WCF we have 4 types of contract: .Net uses "System.ServiceModel" Name space to work with WCF services. · Service Contract: It defines what a client can do with the service. · Data Contract: It defines which data types can be transferred in the service. ( by default you can pass basic types like int, string however for custom types like a custom class you need to define the class as a Data Contract to be able to pass object of that class in the service) · Fault Contract: It defines what are the errors raised by service. · Message Contract: It is an extra functionality allows you to send message in a customized way (It means that you need to send a message in a specific way because let’s say there is an existing system that just understands messages in a specific way. As a user of WCF you should not usually use this as you do not need it except you are working with very specific system that needs specific messaging system) Service Contract: To allow a WCF Client to understand what they can do with the service you need to use Service Contract which is an attribute you need to add to the class. Also for each method that you wish WCF client to access you need add OperationContract attribute take a look at this sample [ServiceContract] Class MyService { [OperationContract] public string MyOperation() { return “hello World”; } }

As you see in above example we have ServiceContract for the class and we have OperationContract for the methods. Some Points: · You can apply ServiceContract to a class or interface · You have to apply OperatoinContract for methods otherwise it will not be accessible to clients · You can only apply OperationContract to methods · It is highly recommended first you better create an interface and apply the servicecontract then create a class that implements the interface (the reason will be discussed further) · Methods accessibility is not important to WCF (public, private or internal) since they are CLR concepts not WCF · Always the default constructor will be called (avoid parameterized constructors) · You can define a Namespace for the ServiceContract (and it is suggested to do so) to avoid collision Please see the same sample by using interface and namespace [ServiceContract(Namespace=”mycompany.com”)] interface IMyService { [OperationContract] string MyOperation(); } Class MyService:IMyService { public string MyOperation() { return “hello World”; } }

WCF defines four types of contracts.

1. Service contracts Describe which operations the client can perform on the service. There are two types of Service Contracts. ServiceContract - This attribute is used to define the Interface. OperationContract - This attribute is used to define the method inside Interface.

2. Data contracts Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types

such as int and string, but we can easily define explicit opt-in data contracts for custom types. There are two types of Data Contracts. DataContract - attribute used to define the class DataMember - attribute used to define the properties. If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service.

3. Fault contracts Define which errors are raised by the service, and how the service handles and propagates errors to its clients.

4. Message contracts Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.

Creating and Consuming a Sample WCF Service: Three major steps are involved while creating and consuming the WCF services. Those are: 1. Create the Service.(Creating) 2. Binding an address to the service and host the Service. (Hosting) 3. Consuming the Service.(Consuming) Step 1: Creating the Service In WCF, all services are exposed as contracts. Contract is a neutral way of describing the service what it does. Mainly we have four types of contracts:

1. Service Contract This contract describes all the available operations that client can perform on the service. .Net uses "System.ServiceModel" Name space to work with WCF services.

ServiceContract attribute is used to define the service contract. We can apply this attribute on class or interface. Servicecontract attribute exposes a CLR interface (or a class) as a WCF contract. OperationContract attribute, is used to indicate explicitly which method is used to expose as part of WCF contract. We can apply OperationContract attribute only on methods, not on properties or indexers. [ServiceContract] applies at the class or interface level. [OperatiContract] applies at the method level.

2. Data Contract This contract defines the data types that passed in and out to the service. [DataContract] attribute is used at the custom data type definition level, i.e. at class or structure level. [DataMember] attribute is used to fields, properties, and events.

3. Fault Contract This contract describes about the error raised by the services. [FaultContract()] attribute is used for defining the fault contracts.

4. Message Contracts This contract provides the direct control over the SOAP message structure. This is useful in inter operability cases and when there is an existing message format you have to comply with. [MessageContract] attribute is used to define a type as a Message type. [MessageHeader] attribute is used to those members of the type we want to make into SOAP headers [MessageBodyMember] attribute is used to those members we want to make into parts of the SOAP body of the message. Sample Service Creation : [ServiceContract]

public interface IFirstWCFService { [OperationContract] int Add(int x, int y);

[OperationContract] string Hello(string strName);

int Multiplication(int x, int y); } Here "IFirstWCFService" is a service exposed by using the servicecontract attribute. This service exposes two methods "Add","Hello" by using the [OperationContract] attribute. The method "Multiplication" is not exposed by using the [OperationContract] attribute. So it wnt be avlible in the WCF service. public class FrtWCFService : IFirstWCFService { public int Add(int x, int y) { return x + y; }

public string Hello(string strName) { return "WCF program : " + strName; }

public int Multiplication(int x, int y) { return x * y; }

} "FrtWCFService" is a class,which implements the interface "IFirstWCFService". This class definse the functionality of methods exposed as services.

STEP 2: Binding and Hosting Each service has an end point. Clients communicates with this end points only. End point describes 3 things : 1. Address 2. Binding type 3. Contract Name (which was defined in STEP 1) Address Every service must be associated with a unique address. Address mainly contains the following two key factors : 1. Transport protocal used to communicate between the client proxy and service. WCF supports the following transport machinisams:  HTTP

(ex : http:// or https:// )

 TCP

(ex : net.tcp :// )

 Peer network

(ex: net.p2p://)

 IPC (Inter-Process Communication over named pipes) (ex: net.pipe://)  MSMQ (ex: net.msmq://) 2.

Location of the service. Location of the service describes the targeted machine(where service is hosted) complete name (or) path and optionally port / pipe /queue name. Example :

localhost:8081

Here local host is the target machine name. 8081 is the optional port number. Example 2: localchost This is with out optional parameter. Here are a few sample addresses: http://localhost:8001 http://localhost:8001/MyFirstService net.tcp://localhost:8002/MyFirstService net.pipe://localhost/MyFirstPipe net.msmq://localhost/MyFirstService net.msmq://localhost/MyFirstService Binding is nothing but a set of choices regarding the transport protocol (which transport protocal we have to use : http /tcp /pipe etc.) ,message encoding (tells about the message encdong /

decoidng technique) ,communication pattern (whether communication is asynchronous, synchronous, message queued etc.) , reliability, security, transaction propagation, and interoperability. WCF defines the nine basic bindings: Binding Type

.Net Class implements this binding

Transport Encoding Inter Comments operable

Basic Binding

BasicHttpBinding

Http / Https

Text / MTOM

Yes

Used to expose a WCF service as a legacy ASMX web service.

TCP binding NetTcpBinding

TCP

Binary

NO

TCP is used for crossmachine communication on the intranet.

Peer network binding

P2P

Binary

NO

In this peer network transport schema is used to communicate.

IPC binding NetNamedPipeBinding

IPC

Binary

NO

This uses named pipes as a transport for samemachine communication. It is the most secure binding since it cannot accept calls from outside the machine.

WSbinding WSHttpBinding

Http / Https

Text / MTOM

Yes

This uses Http / Https as a communication schema.

Federated WSFederationHttpBinding Http / WS binding Https

Text / MTOM

Yes

This is a specialization of the WS binding. This offers the support for federated security

Duplex WS WSDualHttpBinding binding

Http

Text / MTOM

Yes

This is a WS binding with bidirectional communication support from the service to the client.

MSMQ binding

MSMQ

Binary

NO

This supports for disconnected queued calls

MSMQ

Binary

Yes

This is designed to interoperate with legacy MSMQ clients.

NetPeerTcpBinding

NetMsmqBinding

MSMQ MsmqIntegrationBinding integration binding Hosting:

Every service must be hosted in a host process. Hosting can be done by using the  IIS  Windows Activation Service (WAS)  Self hosting

Hosting Type

Advantages

Limitations

IIS Hosting

IIS manages the life cycle of host process. ( like application pooling, recycling, idle time management, identity management, and isolation)

Only HTTP transport schemas WCF service are hosted in IIS.

WAS  WAS supports for all available WCF transports, ports, Hosting and queues.

Some adv of self hosted processing is missing.

 WAS manages the life cycle of host process. Self Hosting

 Developer can have explicit control over opening and closing the host.

Missing the host process life cycle management.

 In-Proc hosting can be done.

STEP 3: Consuming the Service ServiceReference1.FirstWCFServiceClient obj = new UsingWCFService.ServiceReference1.FirstWCFServiceClient();

Console.WriteLine(obj.Add(2, 3).ToString()); obj.Close(); WCF Programs WCF programs are basically divided into 3 different types of programs. They are common known as

 Clients Clients are program that consumes the services, they are normally the ones that initiate the messaging to the service. Depending on the designed architecture of your application, it is possible that a service behaves as a client as well.

 Services Services are the programs that offers the services to the consumers. They are the ones that react and process the messages, similar to the backend of the application. They can be viewed as the equivalence of web services in .Net 2.0. All services have to have endpoints specified in order to work. A good way to remember proper endpoint configurations is ABC. A being Address, B being Binding and C being Contracts.

 Address(Where) Address are the expose points of services. Services have to tell the world that where they are via addresses.

 Bindings(How) Bindings will describe to the world on how they will communicate with the world. They contain information such as transport way, how they are encoded, are they reliable etc.

 Contracts(What) are of (but not necessary all have to be present) 3 different kinds  Service Contract Describes what the service does.

 Data Contract Define custom messaging structure.

 Message Contract Define the message format that is passed between services.

 Intermediaries Intermediaries are programs that act as "middle-man", their basic roles can be similar to providing a firewall, routing, gateway etc. They are commonly invisible to the client and services.

Messages All services and clients communicate via messages, which are made up of one body, and one or more header. All WCF messages are XML formatted and transport neutral. In other words, you can specify different forms of transport (HTTP, MSMQ, Named Pipes etc) for different messages. Within each application, you can specify different messaging transport depending on the communication needs of the system. Basically, messages can be divided into

 Simplex One way messaging. Simplex in short means "fire and forget"

 Duplex Asynchronous two-way messaging. In short this means that once fired, the application will carry on doing its own thing. Upon the return results, it will then handle it.

 Request Reply Synchronous 2 way messaging. This is the common communicate method whereby you'll fire a request, and wait for the response before continuing.

Channels Before a client and service can talk to each other, they have to go through a channel. Imagine a channel as a pipe, with one end being the input message and the other end with the results of the

message. There're different channels that can be stacked onto each other, they are commonly known as Channel Stacks. They can be of these different types:  Reliable Sessions  TCP Transport  Binary Message Encoder  Windows Security  Request Reply The way in which messages are sent through the pipe (Channel) is known as a Transport and they way at which they are encoded are known asEncodings. Transport can be made up of the following:  HTTP  TCP  MSMQ  Named Pipes

Application @SimpleWCFAPplication Transactions in Windows Communication Foundation Transactions provide a way to group a set of actions or operations into a single indivisible unit of execution. A transaction is a collection of operations with the following properties:  Atomicity. This ensures that either all of the updates completed under a specific transaction are committed and made durable or they are all aborted and rolled back to their previous state.  Consistency. This guarantees that the changes made under a transaction represent a transformation from one consistent state to another. For example, a transaction that transfers money from a checking account to a savings account does not change the amount of money in the overall bank account.  Isolation. This prevents a transaction from observing uncommitted changes belonging to other concurrent transactions. Isolation provides an abstraction of concurrency while ensuring one transaction cannot have an unexpected impact on the execution of another transaction.  Durability. This means that once committed, updates to managed resources (such as a database record) will be persistent in the face of failures. Windows Communication Foundation (WCF) provides a rich set of features that enable you to create distributed transactions in your Web service application. WCF implements support for the WS-AtomicTransaction (WS-AT) protocol that enables WCF applications to flow transactions to interoperable applications, such as interoperable Web services built using third-party technology. WCF also implements support for the OLE Transactions protocol, which can be used in scenarios where you do not need interop functionality to enable transaction flow.

You can use an application configuration file to configure bindings to enable or disable transaction flow, as well as set the desired transaction protocol on a binding. In addition, you can set transaction time-outs at the service level using the configuration file. see Enabling Transaction Flow. Implementation Transactions in wcf:

 Step 1: Create Two WCF Services  Step 2: Attribute Interface Methods with TransactionFlow  Step 3: Attribute the Implementation with TransactionScopeRequired  Step 4: Enable Transaction Flow using WCF Service Config File  Step 5: Call the 2 Services in One Transaction  Step 6: Test If Your Transaction Works Application @WCFTransactions Folder

Comparison between .Net Remoting, Web services, WCF: Windows Communication Foundation (WCF) is a technology combined with the features of XML Web Services and .NET Remoting, along with some improvements. This article is a comparison of WCF with Web Services and .NET Remoting. Interoperability .NET Remoting works in a homogenous environment. A consuming application is also required to be in .NET. Web Services are platform and language independent, and don't care about the consuming application. But it has restrictions of the HTTP protocol. Performance-wise, they are considered slow. WCF can be hosted under the Windows environment, but it can be utilized by clients of different languages and different platforms. Protocol Utilization .NET Remoting applications can use the HTTP, TCP, and SMTP protocols. XML Web Services use SOAP, i.e., XML via HTTP. WCF, along with all these protocols, can use named pipes and MSMQ as well. Session Management Web Services don't keep session values by default. A new instance of Web Service is created on each call. The EnableSession attribute is used with each web method to implement a session. By default, it is false, so we define it explicitly. This attribute allows a Web Service to access session values directly from the HttpContext.Current.Session property. For example: [WebMethod(EnableSession = true)] public string KeepSessionValue(bool SendValue) { string strSessionValue;

if (SendValue) { rSessionValue = Session["newValue"].ToString(); } else { if (null==Session["oldValue"]) Session["oldValue"] = System.DateTime.Now.ToLongTimeString(); strSessionValue = Session["oldValue"].ToString(); } return strSessionValue; } WCF Sessions: In WCF, sessions are explicitly defined and closed from client side applications, unlike ASP.NET applications where sessions are server initiated. There are two kinds of sessions in WCF: 1. Reliable session which is responsible for transactions 2. The other type keeps session values for objects. We choose endpoint bindings which support session. For example,BasicHttpBinding does not support sessions. To start, theServiceContract attribute's SessionMode property is set. It can be:

 SessionMode.Required: Session is required to be implemented.  SessionMode.Allowed: Session is allowed to be implemented.  SessionMode.NotAllowed: Session implementation is not allowed. It will not keep the session values. By default, it is set to Allowed, so we do not need to set it to Allowed. ASP.NET Sessions are: 1. Always server-initiated. 2. Implicitly unordered. 3. Provide a way to preserve data across multiple requests. There is unique session id generated at the server and passed back and forth between client and server via URL or cookies. WCF Sessions are 1. Initiated and terminated by the calling application. 2. Ordered message delivery 3. Sessions correlate a group of messages into a conversation. This correlation depending upon the binding can be taken care at message or transport level. 4. No data storage is involved with WCF Session Using an AJAX-Enabled WCF Service

The WCF service can be called directly from JavaScript using Ajx-Enabled WCF service Template. 1. Using Ajax-Enable WCF Service item template 2. Using Service Interface defined in a class library D:\PracticeProjects\WcfNew\05032010\WcfAjax

• •

Using JSON WCF Service (JavaScript Object Notation) JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. • Format for bridging JavaScript and object • JSON easier for browsers than xml • Asp.net Ajax & other Ajax Toolkit use it JSON is built on two structures: • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. What Is WCF? Windows Communication Foundation (WCF) is a unified framework for creating secure, reliable, transacted, and interoperable distributed applications. In earlier versions of Visual Studio, there were several technologies that could be used for communicating between applications. If you wanted to share information in a way that enabled it to be accessed from any platform, you would use a Web service (also known as an ASMX Web service). If you wanted to just move data between a client and server that were running on the Windows operating system, you would use .NET Remoting. If you wanted transacted communications, you would use Enterprise Services (DCOM), or if you wanted a queued model you would use Message Queuing (also known as MSMQ). WCF brings together the functionality of all those technologies under a unified programming model. This simplifies the experience of developing distributed applications. •

WCF Programming Model The WCF Programming model is based on communication between two entities: a WCF service and a WCF client. The programming model is encapsulated in the System.ServiceModelnamespace in the .NET Framework.



WCF Service A WCF service is based on an interface that defines a contract between the service and the client. It is marked with aServiceContractAttribute attribute, as shown in the following code:

You define functions or methods that are exposed by a WCF service by marking them with a OperationContractAttributeattribute. In addition, you can expose serialized data by marking a composite type with a DataContractAttributeattribute. This enables data binding in a client. After an interface and its methods are defined, they are encapsulated in a class that implements the interface. A single WCF service class can implement multiple service contracts. A WCF service is exposed for consumption through what is known as an endpoint. The endpoint provides the only way to communicate with the service; you cannot access the service through a direct reference as you would with other classes. An endpoint consists of an address, a binding, and a contract. The address defines where the service is located; this could be a URL, an FTP address, or a network or local path. A binding defines the way that you communicate with the service. WCF bindings provide a versatile model for specifying a protocol such as HTTP or FTP, a security mechanism such as Windows Authentication or user names and passwords, and much more. A contract includes the operations that are exposed by the WCF service class. Multiple endpoints can be exposed for a single WCF service. This enables different clients to communicate with the same service in different ways. For example, a banking service might provide one endpoint for employees and another for external customers, each using a different address, binding, and/or contract. Windows Communication Foundation (WCF) is the latest service execution environment from Microsoft that enables you to seamlessly expose CLR types as services and consume services as CLR types. WCF is a unified programming model that combines the best of breed features from XML Web Services, .NET Remoting, MSMQ, and COM+ into an integrated platform that is completely based on a set of open industry standards. Because of that, WCF provides interoperability between services, and it promotes productivity, including the essential off-the-shelf plumbing required by almost any application. This article series will discuss the essential building blocks of WCF describing the concepts and architecture of WCF. The first installment focuses on the basics of WCF by introducing you to the WCF through simple examples and discussion. The future installments will go into more specific features of WCF such as transactions, security, instance management techniques and so on.



WCF Client A WCF client consists of a proxy that enables an application to communicate with a WCF service, and an endpoint that matches an endpoint defined for the service. The proxy is generated on the client side in the app.config file and includes information about the types and methods that are exposed by the service. For services that expose multiple endpoints, the client can select the one that best fits its needs, for example, to communicate over HTTP and use Windows Authentication. After a WCF client has been created, you reference the service in your code just as you would any other object. For example, to call the GetData method shown earlier, you would write code that resembles the following:

 After Creating new WCF Service application by default we will get the following files

 IService1.cs(Interface)  Service1.svc  Service1.svc.cs  Web.config 1. What is a service contract (In WCF)? In every service oriented architecture, services share schemas and contracts, not classes and types. What this means is that you don't share class definitions neither any implementation details about your service to consumers. Everything your consumer has to know is your service interface, and how to talk to it. In order to know this, both parts (service and consumer) have to share something that is called a Contract. In WCF, there are 3 kinds of contracts: Service Contract, Data Contract and Message Contract.

A Service Contract describes what the service can do. It defines some properties about the service, and a set of actions called Operation Contracts. Operation Contracts are equivalent to web methods in ASMX technology

2. Operation Contract Indicates that a method defines an operation that is part of a service contract in a Windows Communication Foundation (WCF) application. Namespace: System.ServiceModel Assembly: System.ServiceModel (in System.ServiceModel.dll)

3. DataContract A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged. 4. Data Member Default Values

In the .NET Framework, types have a concept of default values. For example, for any reference type the default value is null, and for an integer type it is zero. It is occasionally desirable to omit a data member from serialized data when it is set to its default value. Because the member has a default value, an actual value need not be serialized; this has a performance advantage. To omit a member from serialized data, set the EmitDefaultValue property of theDataMemberAttribute attribute to false (the default is true).



Wcf architecture:

1. 2. 3. 4. 5.

Service Model Connector Hosting Environments Message Services System Services

 Key Components of a WCF Service A WCF service program contains four elements: • Contract definitions - A service must have at least one service contract, and it might contain multiple service contracts, data contracts, or message contracts • Endpoint definitions - One or more address-binding-contract endpoints must be declared • Hosting code - Some code is needed to create and start the service • Implementation code - The service contracts in a service need code to implement their service operations  Understanding Contracts Contracts are one of the fundamental concepts in WCF. They allow clients and services to have a common understanding of available operations, data structures, and message structures while remaining loosely coupled and platform independent. WCF includes four kinds of contracts: • Service contract - Describes the operations a service can perform. A service contract is defined with the [ServiceContract] and [OperationContract] attributes.

Binding requirements can be specified for the contract with a [BindingRequirements] attribute. • Data contract - Describes a data structure. A data contract is defined primarily with the [DataContract] and [DataMember] attributes. • Message contract - Defines what goes where in a message. A message contract is defined primarily with the [MessageContract], [MessageBodyMember], and [MessageHeader] attributes. • Fault contract - Allows you to document the errors that WCF code is likely to produce. A fault contract is specified along with the operation contract at the time of declaring the method. A fault contract is defined using the [FaultContract] attribute. All four types of contracts translate between Microsoft .NET types used internally and the XML representations shared externally: • A service contract converts between the CLR and Web Services Description Language (WSDL) • A data contract converts between the CLR and XML Schema Definition (XSD) • A message contract converts between the CLR and Simple Object Access Protocol (SOAP) • A fault contract converts the CLR exceptions and to SOAP faults

 Hosting WCF Services As for where to put your code and what it compiles to, you have some choices. You can host your service in Internet Information Services (IIS), or you can write a small amount of extra code to host a service yourself. You can self-host a service from just about any environment that supports managed code, including a WinForms application, console application, library assembly (DLL), or Windows Service controlled through SCM (Service Control Manager). The following lists show the common hosting mechanisms for WCF services. • IIS (Internet Information Services) - IIS provides a number of advantages if the service uses HTTP as its transport. The nice thing about using IIS is that you don't have to write any hosting code as part of the application since IIS automatically activates service code as required. Services also benefit from IIS features such as process lifetime management and automatic restart after configuration changes. To run services using IIS, you create the service code along with its configuration file and simply save them in an IIS virtual directory. • WAS (Windows Activation Service) - (WAS) is the new process activation mechanism that ships with IIS 7.0. WAS builds on the existing IIS 6.0 process and hosting models, but is no longer dependent on HTTP. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes. This helps WCF applications to take advantage of WAS features, such as process recycling, rapid fail protection, and the common configuration system, which were previously available only to HTTP-based applications. • Self-hosting - WCF services can be hosted inside any managed application, such as console applications and Windows Forms or Windows Presentation Foundation (WPF) graphical applications. To accomplish this, you need to create a class that implements a WCF service contract interface, and specify binding information in the application configuration file. The application code can then use an instance of System.ServiceModel.ServiceHost to make the service available at a particular location. To start the service, you call the ServiceHost.Open() method.





Managed Windows Service - A WCF service can be registered as a Windows Service, so that it is under control of the Service Control Manager (SCM). This is suitable for long-running WCF services that are hosted outside of IIS in a secure environment and are not message-activated. By hosting a WCF service with Windows Services, you take advantage of Windows service features such as automatic start at start time and control by the SCM. To host a WCF service in this way, the application must be written as a Managed Windows Service by inheriting from System.ServiceProcess.ServiceBase. It must also implement a WCF service contract interface and then create and open a ServiceHost to manage the WCF service.

Security: Windows Communication Foundation (WCF) security has three common security modes that are found on most predefined bindings: transport, message, and "transport with message credential." 1. Transport: 2. Message:

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF