Archive

Archive for the ‘WCF’ Category

ASP.NET WEB API – What and Why

Hi Friends,

Microsoft has introduced a helpful framework with ASP.NET MVC4 called WEB API for building the http based services.

In this article we will cover following points about this new framework

1) WHAT
2) WHY  WEB API

WHAT

ASP.net Web API is an api which helps in creating the http based client and server endpoints on top of the ASP.net framework.

The Client side http based programming model has been built in to the System.net and the server side http based programming model has been built in to the WCF.

The First version of WCF did not support the Http based services.
It strongly supported the traditional Soap based service endpoints which really lack in the many other features in http like caching , compression etc.

With the release of the .NET Framework 3.5 in November 2007, Microsoft released the feature to create the simple http based endpoints but it was again more embedded in the WCF.

So Microsoft WCF team has decided to come up with the framework which is completely used for the http based services ,
As ASP.NET team is more engage in the web / http  work , routing , html Microsoft has decided to merge this framework with the ASP.Net
and introduced WEB API with the ASP.NET MVC 4 release.

WHY

If we are implementing an application whether html 5 or mobile , they need services for accessing data or to artifact the system.
In the modern programming land scape services should be created by keeping wide range of clients in mind.

Most of the applications are accessing data as JSON using HTTP based services which is going to be a trend than accessing data from traditional Soap services.

 

This article is the summary of the video by Jon Flander on the pluralsight website.

please refer http://www.asp.net/web-api for details of web api.

 

Thanks

Ganesh Divekar

WCF # 22 Error Handling , Error Logging , ErrorHandlerAttribute using WCF Extensions

March 26, 2013 3 comments

 

In this article , we will see how to write the generic error handler in the WCF which is used for custom error logging and in returning the appropriate fault message to the user if any error comes while processing the user request.

IErrorHandler interface is used for error handling and logging in the WCF.

IErrorHandler
  1. public interface IErrorHandler
  2. {
  3.     bool HandleError(Exception error);
  4.     void ProvideFault(Exception error, MessageVersion version, ref Message fault);
  5. }

HandleError method logs an error.
It returns true if the error is considered as already handled other wise false will be returned and error will be handled as usual.

ProvideFault method can only be used in DUPLEX communication.
This method allows to create the custom FaultException
This method accepts the parameter error which is of type Exception , this exception is the exception occurs during the execution of a service method.

 

Following is the code for IErrorHandler interface Implementation.                                         

IErrorHandler Implementation
  1. [AttributeUsage(AttributeTargets.Class)]
  2. public class ErrorHandlerBehaviorAttribute : Attribute, IErrorHandler, IServiceBehavior
  3. {
  4.     //IErrorHandler Implementation
  5.  
  6.     bool IErrorHandler.HandleError(Exception error)
  7.     {
  8.         try
  9.         {
  10.             //Write your code here for Logging the errors
  11.         }
  12.         catch { }
  13.         return false;
  14.     }
  15.  
  16.     void IErrorHandler.ProvideFault(Exception error, MessageVersion version, ref Message fault)
  17.     {
  18.         if (OperationContext.Current != null && OperationContext.Current.IncomingMessageHeaders != null)
  19.         {
  20.             //Write code here for modifying the Fault Messages to be returned to the USER
  21.         }
  22.  
  23.     }
  24.  
  25.     //IServiceBehavior implementation"
  26.  
  27.     void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase host)
  28.     {
  29.         //attach the object implementing the IErrorHandler interface(this class itself) to each ChannelDisp
  30.  
  31.         foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)
  32.         {
  33.             dispatcher.ErrorHandlers.Add(this);
  34.         }
  35.     }
  36.  
  37.     void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase host)
  38.     {
  39.         //implementation not required at present. Can be added later if required.
  40.     }
  41.     void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase host,
  42.         Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
  43.     {
  44.         //implementation not required at present. Can be added later if required.
  45.     }
  46.  
  47.  
  48. }

 

Brief Summary for the code above

1) It has been derived from the Attribute class so that it can be used as an attribute over the service class directly.

2)It has been also derived from IServiceBehaviour interface which is used to apply this ErrorHandler behavior to the channel dispatcher in the Service

void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase host)

{

    //attach the object implementing the IErrorHandler interface(this class itself) to each ChannelDispatcher

    foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)

    {

        dispatcher.ErrorHandlers.Add(this);

    }

}

 

Now our ErrorHandlerBehavior attribute is ready to use on any WCF service.The benefit of creating the atttribute for this behavior is we can directly use this in the c# code on the service class as below

Add behavior to service
  1. [ErrorHandlerBehavior()]
  2.     public class Service : IService
  3.     {
  4.      //Implement your IService methods here
  5.     }

 

Thanks

Ganesh D

WCF # 21 # – WCF Encoder , Types of WCF Encoders , Choose Appropriate encoder

December 23, 2011 Leave a comment

Hi Geeks,

Today We will see WCF Encoder ,their types and how to chose the appropriate encoder according to the situation.

-> First we will see what does Encoding mean in WCF ????

It is the term used to describe the process of converting a WCF message into an array of bytes. This is done so that the message can be sent across a transport protocol.

Note : Encoding is not something that you work with directly. Instead, it is specified by the binding used to expose a service.

For Ex In this example we have used

Text Encoder Binding Example
  1. <bindings>
  2.  
  3.       <basicHttpBinding>
  4.         <binding name="testBinding"
  5.             messageEncoding="Text">
  6.  
  7.         </binding>
  8.       </basicHttpBinding>
  9.     </bindings>

 

-> Types of WCF Encoders

WCF provides five types of encoding formats:

1.Binary

2.Text

3.Message Transmission Optimization Mechanism(MTOM )

4.JavaScript Object Notation

5.Plain Old XML (POX)

We will go in depth with first three types as those are used the most.

1.Binary Encoding

Binary encoding, the first thing to understand is that it is not a interoperable encoding. If your clients and service are all built with WCF then go ahead and use Binary Encoding.

Binary Encoding is great stuff if you are using Message level security. In message security 90% of the SOAP header is security!

the binary message encoder, uses a compact binary format and is optimized for WCF to WCF communication, and hence is not interoperable. This is also the most performant encoder of all the encoders WCF provides.

2.Text (DataContractSerializer)

The text message encoder, supports both plain XML encoding and SOAP encoding. The plain XML encoding mode of the text message encoder is called "plain old XML" (POX) to distinguish it from text-based SOAP encoding.

Text encoding was acceptable for ASP.NET Web Services because it allowed for interoperability across platforms. WCF abstracts out the encoding mechanism and
allows for bindings that allow for both styles of encoding. This allows WCF to provide functionality that replaces both .NET Remoting and ASP.NET Web Services.

The text encoder converts messages into text-based XML. This is great for interoperability.

3.Message Transmission Optimization Mechanism(MTOM )

The text  encoder converts messages into text-based XML. This is great for interoperability, but it is not efficient at transmitting large chunks of binary data.

MTOM is used to send large amounts of binary data as raw bytes in interoperable scenarios.

As mentioned previously,MTOM refers to Message Transmission Optimization Mechanism.This is standard for optimizing the binary data by sending the binary data

Mtom Encoder Binding Example
  1.     <bindings>
  2.       <basicHttpBinding>
  3.         <binding name="testBinding"
  4.             messageEncoding="Mtom">
  5.         </binding>
  6.       </basicHttpBinding>
  7.     </bindings>

4.JavaScript Object Notation

One of the emerging popular formats for sharing content online is JSON, shorthand for JavaScript Object Notation. Intended to be slightly more efficient than XML, it’s found a home in lots of AJAX powered web applications. Some companies actually require you talk to their APIs in terms of JSON too, so having the ability to parse and emit arbitrary JSON in a strongly typed way is a valuable tool to have. As of .NET 3.5 SP1, we are equipped with the DataContractJsonSerializer.

 

To know more on the WCF classes and for choosing appropriate encoder belonging to each type please visit WCF Encoders.

Thank You.

Hope this Will help you..

Smile

Categories: WCF

WCF #20 – Compare WCF and web services /Difference between WCF and web services / WCF vs. Web services

December 21, 2011 1 comment

Hi Geeks,

In this post we will see measure differences between the WCF and web services and will compare them on important aspects.

WCF [Windows Communication Foundation]

WCF provides a common platform for all .NET communication.

It is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability being one of its fundamental characteristics.   It is a combined set of features including Web Services, Remoting, MSMQ and COM+.

The figure below shows the different technologies combined to form WCF.

image

ASMX Web Services

These are published, described and located over Internet. An ASMX web service is a collection of protocols and standards used for exchanging data between applications or systems with following characteristics:


1. A Web Service is a piece of executable code that is accessible over the Web.

2. A Web Service can communicate using platform-independent and language-neutral Web protocols.

3. A Web Service can share schemas and contracts/interface which in turn can be called from another program.

4. A Web Service can be registered and located through a Web Service Registry.

5. A Web Service supports loosely coupled connections between systems.

Conceptual Differences

The conceptual difference between WCF and ASMX Services can be highlighted under following points

1. Protocols Support

  • WCF
    • HTTP
    • TCP
    • Named pipes
    • MSMQ
    • Custom
    • UDP
  • ASMX

             Http Only

2.Hosting 

  • ASMX
    • Can be hosted only with HttpRuntime on IIS.
  • WCF
    • A WCF component can be hosted in any kind of environment in .NET 3.0, such as a console application, Windows application, or IIS.
    • WCF services are known as ‘services’ as opposed to web services because one can host services outside of a web (HTTP) server.
    • Self-hosting the services gives one the flexibility to use transports other than HTTP

Advantages of WCF over ASMX Services

1. Better Interoperability

WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net.

2. End-to-End Reliability and Security:

WCF services provide better reliability and security in comparison to ASMX web services.

3. Configuration based security and binding:

In WCF, there is no need to make changes in code for implementing the security model or changing the binding. Small configuration changes are all that is needed.

4. Integrated Logging:

WCF has an integrated logging mechanism, changing the configuration file settings provides logging functionality. In ASMX (and other technologies), one has to write logging specific code.

5. Multiple Protocols:

WCF works across multiple protocols including http, tcp, MSMQ etc where as ASMX services can only use http.

6. Transactional Capability:

WCF can create and maintain transactions like com+ .

7. Hosting Options:

WCF services can be hosted on IIS, Self hosting, Windows Services(Windows Application Service) and even console apps, WinForms apps etc.

8. Better Interoperability through Data Contracts

The development of web service with ASP.net relies on defining data and relies on the XMLSerializer to transform data to or from a service.  WCF Uses DataContractAttribute and DataMember attributes to Translate .net types to XML.
DataContract attributes can be used for classes and structures-DataMember Attribute to Field or Property
The differences between DataContractSerailizer and XML Serializer include: 
DCS has better performance over XML Serialization
– XML Serialization doesn’t indicate which field or property of the type is serialized, DCS Explicitly shows which field or property is serialized
– DCS can serialize classes implementing IDictionary interface(Hash Table)

9. Exception Handling

In ASP.NET Web services, Unhandled exceptions are returned to the client as SOAP faults. In WCF Services, unhandled exceptions are not returned to clients as SOAP faults. A configuration setting is provided to have the unhandled exceptions returned to clients for the purpose of debugging.

 

Limitations of ASMX:

An ASMX page doesn’t tell you how to deliver it over the transports or to use a specific type of security.  WCF lets you choose that easily via configuration parameters.

ASMX is tightly coupled to the HTTP runtime and has a strong dependence on IIS to host it. WCF can be hosted by any Windows process that is able to host the .NET Framework 3.0.

ASMX services are instantiated on a per-call basis, while WCF gives one the flexibility by providing various instantiating options such as singleton, private session, per call.

ASMX provides the way for interoperability but it does not provide guaranteed end-to-end security or reliable communication.  WCF provides both end-to-end reliability as well as security.

Summary :

image

 

Thank You.

Smile 

Categories: WCF

WCF # 19 – WCF Security

November 25, 2011 Leave a comment

Hi Friends,

In every application Security is the most important part of concern.

For Example , When we use an online banking service, we trust that the application providers have done their utmost to prevent abuse, corruption of data,hacking, and exposure of our financial details to others. The same is expected of us as we provide WCF-based services to consumers.

This article will focus on the concepts behind security and the practical means by which services are secured (when necessary) using WCF.Today we will focus on We will begin by introducing the major concepts,

WCF Security Concepts

let’s begin by introducing four major tenets of service security:authentication, authorization, confidentiality, and integrity.

Authentication
One of the .most fundamental concepts of security is knowing who is knocking on your door. Authentication is the process of establishing a clear identity for an entity,                              for example, by providing evidence such as username and password.

Although this is clearly important for a service to understand of its callers, it is equally important that callers have an assurance that the service being called is the expected service and not an impostor.

WCF provides several options for this mutual authentication by both the service and the caller—for example, certificates and Windows accounts and groups. By using these and other options, as we’ll show throughout this chapter, each side can have firm trust that they are communicating with an expected party.

Authorization
The next step in .security, after identity has been established, is to determine whether the calling party should be permitted to do what they are requesting. This process is called authorization because the service or resource authorizes a caller to proceed.

Note that you can choose to authorize anonymous users for actions as well, so although authorization is not strictly dependent on authentication, it does normally follow.

Authorization can be performed by custom code in the service, native or custom authorization providers, ASP.NET roles, Windows groups, Active Directory, Authorization Manager, and other mechanisms.

Confidentiality
When dealing with sensitive information, there is little use in establishing identity and authorization if the results of a call will be broadcast to anyone who is interested. Confidentiality is the concept of preventing others from reading the information exchanged between a caller and a service.

This is typically accomplished via encryption, and a variety of mechanisms for this exist within WCF.

Integrity
The final basic concept of security is the assurance that the contents of a message have not been tampered with during transfer between caller and service, and vice versa. This is typically done by digitally signing or generating a signed hash for the contents of the message and having the receiving party validate the signature based on the contents of what it received.

If the computed value does not match the embedded value, the message should be refused.

Note that integrity can be provided even when privacy is not necessary. It may be acceptable to send information in the clear (unencrypted) as long as the receiver can be assured that it is the original data via digital signature verification.

Transport and Message Security     

image

There are two major classifications of security within WCF; both are related to the security of what is transferred between a service and caller (sometimes called transfer security). The first concept is of protecting data as it is sent across the network, or “on the wire.” This is known as transport security.

The other classification is called message security and is concerned with the protection that each message provides for itself, regardless of the transportation mechanism used.

Transport security provides protection for the data sent, without regard to the contents. A common approach for this is to use Secure Sockets Layer (SSL) for encrypting and signing the contents of the packets sent over HTTPS. There are other transport security options as well, and the choice of options will depend on the particular WCF binding used. In fact, you will
see that many options in WCF are configured to be secure by default, such as with TCP.

The option to use transport and message security is typically specified
in configuration; two basic examples are shown below

<bindings>
  <wsHttpBinding>
    <binding name="TransportSecurity">
      <security mode="Transport">
        <transport clientCredentialType="None"/>
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
<bindings>
  <wsHttpBinding>
    <binding name="TransportSecurity">
      <security mode="Windows">
        <transport clientCredentialType="None"/>
      </security>
    </binding>
  </wsHttpBinding>
</bindings>

 

 

Thanks.

Categories: WCF

WCF # 18–WCF Serialization Vs Encoding [XML Information Set,Difference between XML infoset and XML]

Hi Friends,

Today we will start with very interesting feature of WCF called Serialization and Encoding.

We use serialization for transmission of messages in between client and server we need to convert CLR types to standards-based XML.

Encoding is the conversion of WCF message in to the byte array.

Serialization Vs. Encoding

There are important differences between serialization and encoding in WCF.

1) Serialization

-> It is the term often used to describe the process of converting an object graph into an array of bytes.

-> This is a very useful feature for representing the state of an object. Serialization can be used to persist an object’s state to a file or a database, copy an object to the clipboard, or transfer objects across a network to another application. WCF does not follow the standard definition of serialization, though.

-> WCF defines serialization as the process of converting an object graph into an XML Information Set (XML Infoset)

  i) The XML Infoset is the data model WCF uses internally to represent a message.

  ii) The XML Infoset is the data model for representing an XML document.

Difference between XML and XML Infoset

-> XML use only standard text format.XML Infoset doesnt have such restrictions.

For Example

WCF can represent messages in different formats as long as they are based on an XML Infoset. This includes the text format specified by the XML1.1 specification as well as other formats such as a binary XML format.

 

2) Encoding

-> It is the term used to describe the process of converting a WCF message into an array of bytes. This is done so that the message can be sent across a transport protocol.

->WCF provides five types of encoding formats: binary, text, Message Transmission Optimization Mechanism (MTOM), JavaScript Object Notation, and Plain-Old-XML (POX). Which one you use will depend on your application’s requirements

-> For example, you may want to use the BinaryMessageEncoder for optimal performance between .NET applications, use the TextMessageEncoder for interoperability based on WS-* Web services, or use the JSONMessageEncoder  for AJAX-based Web applications.

 

In our coming posts we look at how WCF uses serialization and encoding to transmit messages across a transport. We will examine the different forms of serialization and encoding and present scenarios where each option should be used..

Thanks.

Categories: WCF

WCF # 17 – WCF Operation Behavior (Flowing Transactions Across Operations,What is Transactional Flow?) [Part II]

Hi Geeks,

In our last post Transactional operation within a service we saw how Operation Behavior matters in WCF.

Today we will see another typeof Operation Behavior which is useful for Distributed Systems (where transactions sometimes must span service boundaries)called Flowing Transactions Across Operations.

When working with distributed systems, transactions sometimes must span service boundaries.                                                                                                                                    For Example,if user is transferring the amount from one bank account to other then definitely two services will be called one is Debit and Transfer If the transaction completed, the user would expect that both systems were properly updated which means Transaction should follow ACID Properties.

What is Transactional Flow?

Windows Communication Foundation can propagate transactions across service boundaries. This enables a service to participate in the client’s transaction and for the client to include operation calls on multiple services in the same transaction referred as Transactional Flow.

To flow transactional semantics across service boundaries, the following five steps must be taken:

1) Service Contract [SessionMode.Required]

-> Service contracts must require sessions because this is how information will be shared
between the coordinator (typically the client) and the participating services.

2) Operation Behavior [TransactionScopeRequired = true]

-> Operation behavior must require a transaction scope. This will create a new transaction if one is not already present.

3) Operation Behavior [TransactionFlowOption.Allowed]

-> Operation contracts must allow transaction information to flow in the header of messages.

4) Binding Information [TransactionFlow=true]

-> The binding must enable transaction flow so that the channel can put transaction information into the SOAP header. Also note that the binding must support sessions because wsHttpBinding does but basicHttpBinding does not.

5) Client [TransactionScope]

-> The party that initiates the transaction, typically the client, must use a transaction scope when calling the service operations. It must also call TransactionScope.close() to commit the changes.

The .NET 3.5 documentation on the TransactionScopeRequired attribute includes the following table to describe the relationship between these elements. It is repeated here for convenience.

 

image

To have the best example on Flowing Transactions Across Operations

go to  WCF Flow Transaction Example.

Hope this will help you Smile 

Thank you.

Categories: WCF