Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Wednesday, 27 February 2013

WCF : An introduction



  1. What is WCF?
ü  WCF stands for Windows Communication Foundation (WCF).
ü  This is considered as the Microsoft Service-Oriented Architecture (SOA) platform for building distributed and interoperable applications. 
ü  WCF unifies ASMX, Remoting, and Enterprise Services stacks and provides a single programming model.
ü  WCF services are interoperable and supports all the core Web services standards. 
ü  A WCF service also provide extension points to quickly adapt to new protocols and updates and integrates very easily with the earlier Microsoft technologies like Enterprise Services, COM and MSMQ.


  1. Why should I use WCF?
ü  WCF is interoperable with other services when compared to .Net Remoting, where the client and service have to be .Net.
ü  WCF services provide better reliability and security in compared to ASMX web services.
ü  In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
ü  WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.
3.    What is difference between WCF and Web Services?
ü  Protocol: Web services can only be invoked by HTTP (traditional web service with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type. 
ü  Flexibility: web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends. 
ü  Ease of Development: We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc 
ü  XmlSerializer and DataContractSerializer
That Web Services Use XmlSerializer But WCF Uses
DataContractSerializer which is better in Performance as Compared to XmlSerializer.
Key issues with XmlSerializer to serialize .NET types to XML

* Only Public fields or Properties of .NET types can be translated into XML.
* Only the classes which implement IEnumerable interface.
* Classes that implement the IDictionary interface, such as Hash table can not be serialized.

The DataContractAttribute can be applied to the class or a structure. DataMemberAttribute can be applied to field or a property and theses fields or properties can be either public or private. A practical benefit of the design of the DataContractSerializer is better performance over XmlSerializer. 




  1. What is service and client in perspective of data communication?
ü  A service is a unit of functionality exposed to the world.
The client of a service is merely the party consuming the service.
  1. What is SOA Service?
ü  SOA is Service Oriented Architecture. SOA service is the encapsulation of a high level business concept. A SOA service is composed of three parts.
Any Service that fulfills above three requirements is SOA
  1. What are the core components of WCF?
ü  Like any other SOA Service the three core components of WCF are:
a.       A service class
b.       A hosting service
c.       Endpoints to expose the service

  1. What is ABC in WCF?



8.    What is an endpoint?
ü  WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.
ü  All the WCF communications are take place through end point. End point consists of three components.
a.       Address
b.       Binding
c.       Contract
ü  The Endpoint is the fusion of Address, Contract and Binding.









Saturday, 26 January 2013

How to host wcf rest services on IIS

Configuring a WCF service and WCF REST service on IIS differs a little why because,
WCF does not understand the REST address so you need to configure the endpoint behavior as webHttp.

Generally we encounter exceptions when hosting WCF REST services on IIS.


The message with To <address> cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree.

Following is a sample of configuration file that should be used to resolve this.

<system.serviceModel>
<behaviors>
<endpointBehaviors>
          <behavior name="WebBehavior">
            <webHttp/>
          </behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="FullName">
<endpoint address="js" binding="webHttpBinding" behaviorConfiguration="WebBehavior" contract="ServiceContractName"/>
</service>
</services>
</system.serviceModel>

Friday, 31 August 2012

WCF - Notes 7 Tools


Tool Support: WCF and Visual Studio

WCF has a tight relationship with Visual Studio, which provides a number of WCF-specific capabilities. They include the following:
·         Several WCF-specific project types to make it easier for developers to get started creating typical WCF applications. These include projects for building:
·         A Website or Web application that hosts a WCF service;
·         A library implementation of a WCF service;
·         A WCF application that exposes syndication feeds using RSS or ATOM;
·         A WCF service designed for use by an AJAX client. This service is automatically configured to use the WebHttpBinding with JSON encoding.
·         An AddServiceReference function that lets a developer specify an existing service’s endpoint, then let Visual Studio automatically generate a WCF proxy for that service.
·         The ability to generate a client for testing new WCF-based Web services.
·         A WCF Autohost that can automatically host a library-based WCF service.
·         The Service Configuration Editor, a tool that makes creating and modifying WCF configuration files easier.
·         IntelliSense for WCF configuration, allowing statement completion when creating XML elements in configuration files

WCF - Notes 5 Security and Transactions


Security

  • Exposing services on a network, even an internal network, usually requires some kind of security. How can the service be certain of its client’s identity? How can messages sent to and from a service be kept safe from malicious changes and prying eyes? And how can access to a service be limited to only those authorized to use it? Without some solution to these problems, it’s too dangerous to expose many kinds of services. Yet building secure distributed applications is difficult. Ideally, there should be straightforward ways to address common security scenarios, along with more fine-grained control for applications that need it.
  • To help achieve this, WCF provides the core security functions of authentication, message integrity, message confidentiality, and authorization. All of these depend fundamentally on the notion of identity: who is this user? Establishing an identity for a client or service requires supplying information such as a username and password, an X.509 certificate, or something else. A client or service can do this by directly invoking a WCF function, by using a config file, or in other ways, such as by referencing a certificate store. However it’s done, establishing an identity is an essential part of using WCF security.
  • Distributed security can get very complicated very fast. A primary goal of WCF’s designers was to make building secure applications easier. To allow this, WCF’s approach to authentication, data integrity and data privacy relies on bindings. Rather than require developers to insert the right attributes to secure each class and method, they can instead just use a binding that provides the right set of security services. A developer’s choices include the following:
  • Use a standard binding that directly supports security. For example, applications that require end-to-end security for messages that go through multiple SOAP intermediaries can use a binding that supports WS-Security, such as WsHttpBinding.
  • Use a standard binding that optionally supports security, then configure it as needed. For example, applications that need only transport-based security can choose BasicHttpBinding, configuring it to use HTTPS rather than HTTP. It’s also possible to customize other more-advanced security behaviors. For example, the authentication mechanism used by a binding such as WsHttpBinding can be changed if desired.
  • Create a custom binding that provides exactly the security behavior a developer needs. Doing this is not for the faint of heart, but it can be the right solution for some problems.
  • Use a standard binding that provides no support for security, such as BasicHttpBinding. While using no security is often a risky thing to do, it can sometimes be the only option.
<configuration>
  <system.serviceModel>
    <services>
      <service
        type="RentalReservations,RentalApp"
        <endpoint
          contract="IReservations"
          binding="basicHttpBinding"
          bindingConfiguration="UsingHttps"
          address=
            ”http://www.fabrikam.com/reservation/reserve.svc"/>
      </service>
    </services>
    <bindings>
        <basicHttpBinding>
        <binding
          configurationName="UsingHttps"
          securityMode="Https"/>
      </basicHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>
  • A WCF service can also control which clients are authorized to use its services. To do this, WCF relies on existing authorization mechanisms in the .NET Framework. A service can use the standard PrincipalPermission attribute, for example, to define who is allowed to access it. Alternatively, a WCF application that needed role-based authorization could use Windows Authorization Manager to implement this.
  • Transactions
  • Handling transactions is an important aspect of building many kinds of business logic. Yet using transactions in a service-oriented world can be problematic. Distributed transactions assume a high level of trust among the participants, so it often isn’t appropriate for a transaction to span a service boundary. Still, since there are situations where combining transactions and services makes sense, WCF includes support for this important aspect of application design.
  • Transactions in the .NET Framework: System.Transactions
  • The transaction support in WCF builds on System.Transactions, a .NET Framework namespace focused solely on controlling transactional behaviors. Although it’s not required, developers commonly use the services of System.Transactions in concert with an execution context. An execution context allows the specification of common information, such as a transaction, that applies to all code contained within a defined scope. Here’s an example of how an application can use this approach to group a set of operations into a single transaction:
using System.Transactions;
using (TransactionScope ts =
   new TransactionScope(TransactionScopeOption.Required)) {
   // Do work, e.g., update different DBMSs
   ts.Complete();
}
  • All of the operations within the using block will become part of a single transaction, since they share the transactional execution context it defines. The last line in this example, calling the TransactionScope‘s Complete method, will result in a request to commit the transaction when the block is exited. This approach also provides built-in error handling, aborting the transaction if an exception is raised.
  • Specifying TransactionScopeOption.Required for the new TransactionScope, as this example does, means that this code will always run as part of a transaction: joining its caller’s transaction if one exists, creating a new one if it does not.
  • Unlike Enterprise Services and its predecessors Microsoft Transaction Server (MTS) and COM+, however, System.Transactions is focused entirely on controlling transactional behavior. There is no required connection between a transaction and the internal state of an object, for example. While Enterprise Services requires an object to be deactivated when it ends a transaction, System.Transactions makes no such demand. Since WCF builds on System.Transaction, WCF-based applications are also free to manage transactions and object state independently.
  • WCF-based applications can use the types in System.Transactions directly, or they can control transactions using WCF-defined attributes that rely on System.Transactions under the covers. 
  •  A service’s methods can control transactional behavior via an attribute. Rather than explicitly relying on System.Transactions, a service can use the OperationBehavior attribute described earlier.
[OperationContract]
[OperationBehavior(TransactionScopeRequired=true,
                   TransactionAutoComplete=true)]
private int Reserve(int vehicleClass, int location, string dates)
{
  int confirmationNumber;
  // logic to reserve rental car goes here
  return confirmationNumber;
}
  • Finally, it’s worth emphasizing that applications built on WCF can participate in transactions that include applications running on non-WCF platforms. For example, a WCF-based application might start a transaction, update a record in a local SQL Server database, then invoke a Web service implemented on a Java EE-based application server that updates a record in another database. If this service is transactional and the platform it’s running on supports the WS-AtomicTransaction specification, both database updates can be part of the same transaction. Like security and reliable messaging, WCF transactions can work in the heterogeneous world that Web services make possible.

WCF - Notes 4 WCF Client


Creating a WCF Client

WCF Client talks to WCF service with a proxy.


A WCF client can use a proxy to access a service.
  • Creating a proxy requires knowing what contract is exposed by the target endpoint, and then using the contract’s definition to generate the proxy. In WCF, this process can be performed using either Visual Studio or the command-line svcutil tool.
  • If the service is implemented using WCF, these tools can access the service’s DLL to learn about the contract and generate a proxy. If only the service’s WSDL definition is available, the tools can read this to produce a proxy.
  •  If only the service itself is available, Visual Studio and svcutil can access it directly using either WS-MetadataExchange or a simple HTTP GET to acquire the service’s WSDL interface definition, and then generate the proxy.
  • However it’s generated, the client can create a new instance of the proxy, and then invoke the service’s methods using it.
  • Good programming practice to clean up the communications infrastructure that has been created.
  • One more thing remains to be specified by the client: the exact endpoint on which it wishes to invoke operations. Like a service, the client must specify the endpoint’s contract, its binding and its address, and this is typically done in a config file. In fact, if enough information is available, svcutil will automatically generate an appropriate client configuration file for the target service.
WCF supports several possibilities along with traditional RPC, including the following:
·         Asynchronous RPC, with non-blocking paired calls carrying lists of typed parameters.
·         Traditional messaging, with non-blocking calls carrying a single message parameter. Working directly with channels exposes methods to send and receive messages, and WCF defines a standard Message class that can be used to work directly with XML messages.
·         Direct manipulation of SOAP messages using the WCF-defined attribute MessageContract. Using two related attributes, MessageHeader and MessageBodyMember, an application can explicitly access the contents of a SOAP message’s header and body.
  • To allow creating a method that sends information but doesn’t block waiting for a response, the OperationContract attribute has a property called IsOneWay. Methods marked with this attribute and property can have only input parameters and must return void.
[OperationContract(IsOneWay=true)]
void NewCarAvailable(int vehicleClass, int location);
  • With this method, the caller gets nothing in return—it’s one-way communication. A typical use of one-way methods like this is to send unsolicited events.
  • It’s also possible to link together calls to methods, whether one-way or normal two-way methods, allowing both sides of the communication to act as client and service. To do this, each side implements a contract that’s linked with its partner, resulting in what are called duplex contracts. WCF provides special bindings for handling this case, such as WsDualHttpBinding for duplex contracts that use standard interoperable SOAP.

Controlling Local Behavior

  • How is concurrent access to a service instance managed, for example, and how is that instance’s lifetime controlled? To allow developers to set local behaviors like these, WCF defines two primary attributes, both of which have a number of properties. One of these attributes, ServiceBehavior, can be applied to any service class. The other, OperationBehavior, can be applied to any method in a service class that is also marked with the OperationContract attribute.
  • The ServiceBehavior attribute has various properties that affect the behavior of the service as a whole. For example, a property called ConcurrencyMode can be used to control concurrent access to the service. If set to Single, WCF will deliver only one client request at a time to this service, i.e., the service will be single-threaded. If this property is set to Multiple, WCF will deliver more than one client request at a time to the service, each running on a different thread. Similarly, ServiceBehavior’s InstanceContextMode property can be used to control how instances of a service are created and destroyed. If InstanceMode is set to PerCall, a new instance of the service will be created to handle each client request, and then destroyed when the request is completed. If it’s set to PerSession, however, the same instance of the service will be used to handle all requests from a particular client. (Doing this also requires setting ServiceContract‘s Session attribute to true and choosing a binding that supports sessions.) InstanceContextMode can also be set to Single, which causes a single instance of the service to handle all requests from all clients.
using System.ServiceModel;
[ServiceContract]
[ServiceBehavior(
   ConcurrencyMode=Multiple,
   InstanceContextMode=Single)]
class RentalReservations { ... }
  • Similarly, properties on the OperationBehavior attribute allow controlling the impersonation behavior of the method that implements a particular operation, its transactional requirements (described later), and other things.
  • Another aspect of local behavior is how a request from a client is routed within a WCF service. WCF in the .NET Framework 4 adds a standard content-based routing service that a developer can use with SOAP-based services. The routing service sits in front of other WCF services, routing each incoming message to one of those services based on the message’s content. 

WCF- Notes 3 Hosting


Selecting a Host

·         A WCF service class is typically compiled into a library. By definition, all libraries need a host Windows process to run in. WCF provides two main options for hosting libraries that implement services. One is to use a host process created by either:
ü  Internet Information Services (IIS) or a
ü  Related technology called the Windows Activation Service (WAS).
ü  The other allows a service to be hosted in an arbitrary process. 

Hosting a Service Using IIS or WAS

·         The simplest way to host a WCF service is to rely on IIS or WAS. Both rely on the notion of a virtual directory, which is just a shorter alias for an actual directory path in the Windows file system.
·         IIS-hosted WCF services can only be accessed using SOAP over HTTP. No other transport protocols are supported.
·         Although WAS doesn’t require a Web server to be installed on the system, WCF services hosted in IIS obviously do.
·         Whatever choice is made, both WAS and IIS provide WCF services with a range of support, such as the ability to configure automatic process recycling.
·         To allow a WCF service to take requests from its clients, the process that hosts it must remain running. With WAS-hosted services, the standard process ensures the host remains running, but a hosting application must solve this problem on its own. A WCF service hosted console would be running in a Windows service, allowing it to be started when a system boots, or be hosted in a GUI application, such as one built with Windows Presentation Foundation.

WCF : Notes 2 Service class


Implementing a Service Class

A service class is a class like any other, but it has a few additions. These additions allow the class’s creator to define one or more contracts that this class implements. Each service class implements at least one service contract, which defines the operations this service exposes. The class might also provide an explicit data contract, which defines the data those operations convey.


Defining Service Contracts

·         Every service class implements methods for its clients to use. The creator of the class determines which of its methods are exposed as client-callable operations by specifying that they are part of some service contract. To do this, a developer uses the WCF-defined attribute ServiceContract. In fact, a service class is just a class that either is itself marked with the ServiceContract attribute or implements an interface marked with this attribute. 
·         Namespace used here is using System.ServiceModel;

        Class should be decorated as [ServiceContract] attribute

using System.ServiceModel;
[ServiceContract]
class RentalReservations
{
}
·             

       Each method in a service class that can be invoked by a client must be marked with another attribute named OperationContract. All the methods in a service class that are preceded by the OperationContract attribute are automatically exposed by WCF as services.
[ServiceContract]
class RentalReservations
{
   [OperationContract]
   public bool Check(int vehicleClass, int location,
                     string dates)
   {
      bool availability;
      // code to check availability goes here
      return availability;
   }
}
·   

      Any methods in a service class that aren’t marked with OperationContract aren’t included in the service contract, and so can’t be called by clients of this WCF service.
·         It’s better to specify service contracts explicitly using a language’s interface type. class might look like this:

using System.ServiceModel;
[ServiceContract]
interface IReservations
{
   [OperationContract]
   bool Check(int vehicleClass, int location, string dates);
}
class RentalReservations : IReservations
{
   public bool Check(int vehicleClass, int location,
                     string dates)
   {
     bool availability;
     // logic to check availability goes here
     return availability;
   }
}
·     

            Using explicit interfaces like this is slightly more complicated, but it allows more flexibility. For example, a class can implement more than one interface, which means that it can also implement more than one service contract. By exposing multiple endpoints, each with a different service contract, a service class can present different groups of services to different clients.
·         Marking a class or interface with ServiceContract and one or more of its methods with OperationContract also allows automatically generating service contract definitions in WSDL. Accordingly, the externally visible definition of every WCF service contract can be accessed as a standard WSDL document specifying the operations in that contract. This style of development, commonly called code-first, allows creating a standard interface definition directly from types defined in programming languages such as C# or Visual Basic.
·         An alternative approach is contract-first development, an option that WCF also supports. In this case, a developer typically starts with a WSDL document describing the interface (i.e., the contract) that a service class must implement. Using a tool called svcutil, the developer can generate a skeleton service class directly from a WSDL definition.

Defining Data Contracts


·         A WCF service class specifies a service contract defining which of its methods are exposed to clients of that service. Each of those operations will typically convey some data, which means that a service contract also implies some kind of data contract describing the information that will be exchanged. In some cases, this data contract is defined implicitly as part of the service contract.
·          For services where every operation uses only simple types, it makes sense to define the data aspects of their contract implicitly within the service contract. There’s no need for anything else.
·         But services can also have parameters of more complex types, such as structures. In cases like this, an explicit data contract is required. Data contracts define how in-memory types are converted to a form suitable for transmission across the wire, a process known as serialization. In effect, data contracts are a mechanism for controlling how data is serialized.
·         In a WCF service class, a data contract is defined using the DataContract attribute. A class, structure, or other type marked with DataContract can have one or more of its members preceded by the DataMember attribute, indicating that this member should be included in a serialized value of this type. 


using System.Runtime.Serialization;
[DataContract]
struct ReservationInfo {
   [DataMember] public int vehicleClass;
   [DataMember] public int location;
   [DataMember] public string dates;
}
·    

            Nothing becomes part of either a service contract or a data contract by default. Instead, a developer must explicitly use the ServiceContract and DataContract attributes to indicate which types have WCF-defined contracts, and then explicitly specify which parts of those types are exposed to clients of this service using the OperationContract and DataMember attributes. One of WCF’s design tenets was that services should have explicit boundaries, so WCF is an opt-in technology. Everything a service makes available to its clients is expressly specified in the code.

Performance comparison between distributed technologies:


When we migrate distributed applications made with ASP.NET Web Services, WSE, .NET Enterprise Services and .NET Remoting to WCF, it will in almost all cases result in a performance boost:
Other Distributed Technologies
WCF Performance Advantage
ASP.NET Web Service
25%—50% faster
.NET Remoting
25% faster
WSE 2.0/3.0 implementations.
400% faster
.NET Enterprise Service
100% faster subject to the load.




WCF - Notes 1



·         Windows Communication Foundation (WCF) is a platform rich in features necessary for building distributed service-oriented applications. 
·         WCF is a service that exposes one or more endpoints.
·         Each of which exposes one or more service operations.
·         The endpoint of a service specifies an address where the service can be found.
·         A binding that contains the information that describes how a client must communicate with the service, and
·         A contract that defines the functionality provided by the service to its clients.
·         WCF allows creating clients that access services. Both the client and the service can run in pretty much any Windows process—WCF doesn’t define a required host. Wherever they run, clients and services can interact via SOAP, via a WCF-specific binary protocol, and in other ways.

WCF-based clients and services can run in any Windows process.

·         As the scenario described earlier suggests, WCF addresses a range of problems for communicating applications. Three things stand out, however, as WCF’s most important aspects:
·         Unification of the original .NET Framework communication technologies
·         Interoperability with applications built on other technologies
·         Explicit support for service-oriented development.

Rather than requiring different technologies for different communication styles, WCF provides a single unified solution.
·         An application built on WCF can interact with all of the following:
·         WCF-based applications running in a different process on the same Windows machine
·         WCF-based applications running on another Windows machine
·         Applications built on other technologies, such as Java EE application servers, that support standard Web services. These applications can be running on Windows machines or on machines running other operating systems, such as Sun Solaris, IBM z/OS, or Linux.
·         Messaging: SOAP is the foundation protocol for Web services, defining a basic envelope containing a header and a body. WS-Addressing defines additions to the SOAP header for addressing SOAP messages, which frees SOAP from relying on the underlying transport protocol, such as HTTP, to carry addressing information. The Message Transmission Optimization Mechanism (MTOM) defines an optimized transmission format for SOAP messages based on the XML-binary Optimized Packaging (XOP) specification.
·         Metadata: The Web Services Description Language (WSDL) defines a standard language for specifying services and various aspects of how those services can be used. WS-Policy allows specification of more dynamic aspects of a service’s behavior that cannot be expressed in WSDL, such as a preferred security option. WS-MetadataExchange allows a client to request descriptive information about a service, such as its WSDL and its policies, via SOAP. Beginning with the .NET Framework 4 release, WCF also supports WS-Discovery. This broadcast-based protocol lets an application find services available elsewhere on its local network.
·         Security: WS-Security, WS-Trust and WS-SecureConversation all define additions to SOAP messages for providing authentication, data integrity, data privacy and other security features.
·         Reliability: WS-ReliableMessaging defines additions to the SOAP header that allow reliable end-to-end communication, even when one or more SOAP intermediaries must be traversed.
·         Transactions: Built on WS-Coordination, WS-AtomicTransaction allows using two-phase commit transactions with SOAP-based exchanges.
·         Only WSE 3.0 can interoperate with WCF—earlier versions cannot. 

Every WCF service has three primary components:
·         A service class, implemented in C# or Visual Basic or another CLR-based language, that implements one or more methods.
·         A host process in which the service runs.
·         One or more endpoints that allow clients to access the service. All communication with a WCF service happens via the service’s endpoints.




References: