Thursday, November 19, 2015

WCF - Exception handling

A WCF service developer may encounter some unforeseen errors which require reporting to the client in a suitable manner. Such errors, known as exceptions, are normally handled by using try/catch blocks, but again, this is very technology specific.
Since a client's concern area is not about how an error occurred or the factors contributing to an error, SOAP Fault contract is used to communicate the error message from the service to the client in WCF.
A Fault contract enables the client to have a documented view of the errors occurred in a service. The following example gives a better understanding.
Step-1: An easy calculator service is created with divide operation which will generate general exceptions.
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Runtime.Serialization;
usingSystem.ServiceModel;
usingSystem.Text;

namespace Calculator
{
   // NOTE: You can use the "Rename" command on the "Refactor" menu to change 
   // the interface name "IService1" in both code and config file together.
   
   [ServiceContract]
   
   public interface IService1
   {
      [OperationContract]
      int divide(int num1, int num2);
      // TODO: Add your service operations here
   }
}
The coding for the class file is show below:
Wcf Exception Handling 2
Now, when we try to divide the number 10 by zero, the calculator service will throw an exception.
Wcf Exception Handling 3Wcf Exception Handling 4
The exception can be handled by try/catch block.
Wcf Exception Handling 5
Now, when we try to divide any integer number by 0, it will return the value 10 because we have handled it in the catch block.
Wcf Exception Handling 6
Step-2: FaultException is used in this step to communicate the exception information to the client from the service.
public int Divide(int num1, int num2) 
{ 
   //Do something 
   throw new FaultException("Error while dividing number"); 
}
Wcf Exception Handling 7

WCF - Security

A WCF service boasts of a robust security system with two security modes or levels so that only an intended client can access the services. The security threats that are common in a distributed transaction are moderated to a large extent by WCF.

Key Security Features

WCF service has four key security features as depicted in the figure below.
Wcf Security
  • Authentication - Here, authentication is not limited to identifying the sender of the message, but is mutual, i.e., authentication of the message receiver is required to rule out the possibility of any kind of middleman attack.
  • Authorization - This is the next step taken by a WCF service to ensure security and it is here determined whether the service should authorize the caller to proceed further or not. Although authorization is not dependent on authentication, it normally follows authentication.
  • Confidentiality - The exchange of information between a caller and a service is kept confidential to restrict its interpretation by others for whom the message is not intended. To make this possible, encryption is used along with a wide variety of other mechanisms.
  • Integrity - The final key concept is maintaining integrity, i.e., offering the assurance that the message has not been tampered by anyone in its journey from the sender to the receiver.

Transfer Security Mode

WCF offers the following transfer security modes to ensure a secured communication between a client and a server. The diverse transfer security modes are mentioned below.
  • None - This mode does not guarantee any kind of message security and the service does not get any credentials about the client. This mode is highly risky, as it may allow message tampering and hence not recommended.
<wsHttpBinding>
   <binding name="WCFSecurityExample">
      <security mode="None"/>
   </binding>
</wsHttpBinding>
  • Transport - This mode is the easiest way to achieve a secured transfer of message via the use of communication protocols such as TCP, IPC, Https, and MSMQ. This mode is more effective when the transfer is point-to-point and is used mostly in a controlled environment, i.e., intranet applications.
<wsHttpBinding>
   <binding name="WCFSecurityExample">
      <security mode="Transport"/>
   </binding>
</wsHttpBinding>
  • Message - The security mode allows mutual authentication and offers privacy to a great extent as the messages are encrypted and can be transported through http, which is not considered as a secure protocol. Here the security is provided end-to-end without considering how many intermediaries are involved in a message transfer and whether there is a secured transport or not. The mode is used typically by internet applications.
 
<wsHttpBinding>
   <binding name="WCFSecurityExample">
      <security mode="Message"/>
   </binding>
</wsHttpBinding>
  • Mixed - This security mode is not used frequently and client authentication is offered only at the client level.
 
<wsHttpBinding>
   <binding name="WCFSecurityExample">
      <security mode="TransportWithMessageCredential"/>
   </binding>
</wsHttpBinding>
  • Both - This security mode comprises of both transport security and message security to offer a robust security cover, but often results in overloading the overall performance. This one is supported by only MSMQ.
 
<netMsmqBinding>
   <binding name="WCFSecurityExample">
      <security mode="Both"/>
   </binding>
</netMsmqBinding>
All WCF bindings except BasicHttpBinding have some extent of transfer security by default.

Message Security Level

Message level security is not dependent on WCF protocols. It is employed with message data itself by encrypting the data by using a standard algorithm. A number of client credentials are available for different bindings for the message security level and these are discussed below.
Client credentials for message level security in WCF
None : Here, encryption is used to secure the message, whereas no client authentication is performed which means that the service can be accessed by an anonymous client. Except for BasicHttpBinding, all WCF bindings support this client credential. However it should be noted that for NetNamedPipeBinding, this client credential is not available at all.
  • Windows - Here, both message encryption and client authentication take place for a real-time logged-in user. In this case too, unlike all other WCF bindings, NetNamedPipeBinding is not available and BasicHttpBinding does not lend its support.
  • UserName - Here, messages are encrypted as well as secured by offering a UserName, and clients are authenticated as they need to offer a password. BasicHttpBinding just like the above two client credentials, does not support UserName and it is not available for NetNamedPipeBinding.
  • Certificate - Along with message encryption, both the client and the service get an authentication with certificate. This client credential is available and is supported by all WCF bindings except NetNamedPipeBinding.
  • IssuedToken - Issued Tokens from an authority like Cardspace are used to authenticate the messages. Encryption of messages are also performed here.
The following code shows how client credentials are configured in the WCF message security level/mode.
<netTcpBinding>
   <binding name="WCFMessageSecurityExample">
      <security mode="Message">
         <message clientCredentialType="None"/>
      </security>   
   </binding>
</netTcpBinding>

<netMsmqBinding>...</netMsmqBinding>
</bindings>
<behaviors>...</behaviors>
Here, it must be noted that the transport security mode has an edge over the message security level, as the former is faster. It does not require any additional coding and offers interoperability support, and thus does not reduce the overall performance.
However, from security point of view, the message security mode is more robust and is independent of protocols and offers end-to end security.

WCF - Ria services

WCF RIA Service is a higher-level framework and a new component of frameworks like .NET 4 and Silverlight 4 that eases the procedure of building a complex business application in Silverlight by offering client-side validation. RIA stands for Rich Internet Applications.
It must be noted here that Silverlight is a framework offered by Microsoft, ideal for rich internet applications and is available for use as a browser plug-in, just like Adobe Flash.
WCF RIA Service is mainly based on the standard version of WCF service. The following figure illustrates a part of the WCF architecture, where WCF RIA services has its focus in general.
Wcf RIA Services 1
Creating a WCF RIA Service is the next step to have a better understanding of the concept. The step-by-step procedure is given below.
Step-1: Create a new web project of the name SLWCFRiaServices.Web using Silverlight 5 and then add a new item by selecting ADO.NET Entity Data Model to the same.
Wcf RIA Services 2Wcf RIA Services 3
Step-2: Now choose model contents from the Entity Data Model Wizard by generating the model from the database.
Wcf RIA Services 4
Step-3: From the same wizard, choose your data connection and database objects.
Wcf RIA Services 5Wcf RIA Services 6
Step-4: Build the solution so that in future, recognizing the data model will not a problem for the domain service you are going to create.
Wcf RIA Services 7
Step-5: Now create a domain service in the web project by adding a new item and make sure to enable client access.
Wcf RIA Services 8Wcf RIA Services 9
Step-6: In the very next step, some classes will be generated and it is essential to build them again.
Wcf RIA Services 10Wcf RIA Services 11
Step-7: In this step, DataDomainContext is displayed by the Data Sources Panel.
Wcf RIA Services 12
Step-8: In this step, the article below the DataDomainContext should be selected and customized.
Wcf RIA Services 13
Step-9: Attaching the DataGrid Control with the Data Source is the step committed here, along with selection of themes. Here BureauBlue theme has been selected.
Wcf RIA Services 14Wcf RIA Services 15
Step-10: The last and the final step comprises of going to the design screen and adding entity in the layout area of the MainPage by simple drag and drop. It is also vital to ensure AutoGenerateColumns = "True" and to run it to view the output.
Wcf RIA Services 16Wcf RIA Services 17

Prerequisites

There are some prerequisites for experiencing the full potential of WCF RIA services:
  • Visual Studio 2010 / Visual Studio 2012
  • Silverlight Developer Runtime
  • Latest version of RIA Services Toolkit
  • SDK (Software Development Kit)

WCF RIA Domain Service

A domain service comprises of a set of data operations related to business. It is nothing but a WCF service that exposes any WCF RIA Service application’s business logic.
A WCF RIA Domain Service has the hosting class DomainServiceHost internally, which in turn uses the WCF ServiceHost class for hosting the application. To make the domain service accessible for the client project, it should have the EnableClientAccessAttribute attribute. The attribute is applied automatically whenever a new domain service class is added.
The following figure shows the architecture of a WCF RIA Domain Service:
Wcf RIA Services 18

WCF RIA Services – Querying Data

The following figure shows how a query is created on the client side and executed on the server side to return queryable results. DAL stands for Data Access Layer.
Wcf RIA Services 19

WCF RIA Services – Updating Data

The following figure shows how data is updated by executing the CUD (Create Update Delete) operation on the server side. It should be noted here that WCF RIA service is always stateless on the server side.
Wcf RIA Services 20

WCF - Transactions

A transaction in WCF is a set of operations that follow some properties, collectively known as ACID. Here, if a single operation fails, the entire system fails automatically. When an order is placed online, a transaction takes place. The following example can be helpful to understand the process of transaction in simpler terms.

Example

Suppose you have ordered an LCD television from an online store and you are going to pay the amount by your credit card. When you enter the requisite information to place the order, two operations occur simultaneously.
One, the specified amount gets debited from your bank account and second, the vendor account is credited with the same amount. Both the operations must execute successfully in order to have a successful transaction.

WCF Transaction Properties

The four properties followed by a WCF transaction are the following:
  • Atomic - All the operations must act as a single indivisible operation at the completion of a transaction.
  • Consistency - Whatever may be the operation set, the system is always in a state of consistency, i.e., the outcome of the transaction is always as per the expectation.
  • Isolation - The intermediary state of system is not visible to any entities of the outer world till the transaction is completed.
  • Durability - Committed state is maintained regardless of any kind of failure (hardware, power outage, etc.)
While configuring a WCF transaction, there are some factors that demand consideration. These are binding and operation behavior.
Binding - The bindings that support transaction in WCF are only a few and it is vital to make a choice from only these bindings, which remain disabled by default and should be enabled to get the requisite support for transaction. These bindings are as follows:
  • NetTcpBinding
  • NetNamedPipeBinding
  • WSHttpBinding
  • WSDualHttpBinding
  • WSFederationHttpBinding
Operation behavior - While a binding facilitates the path for transaction propagation, an operation takes care of transaction processing as well as operation configuration. Operation behavior primarily uses two attributes: TransactionFlow and TransactionScopeRequired. Here, it should be noted that TransactionFlow has mainly three values and these are: Allowed, Mandatory, and NotAllowed.
The following code shows whether or not changing the configuration of binding and operation contract facilitates the propagation of client.
<bindings> 
   <wsHttpBinding> 
      <binding name ="MandatoryTransBinding" transactionFlow ="true"> 
         <reliableSession enabled ="true"/>
      </binding>
   </wsHttpBinding> 
</bindings>

Transaction Protocol

WCF uses three types of protocols for transaction:
  • Lightweight
  • Ole Transaction
  • WS-Atomic Transaction (WS-AT)
Of all the three, WS-AT is an interoperable protocol and enables the flow of distributed transaction across firewalls. However, this protocol should not be used when the transaction is strictly based on Microsoft technology.

Phases of WCF Transaction

There are two phases in a WCF transaction as shown in the following figure.
Wcf Transaction Phases 1
  • Prepare Phase - In this phase, the transaction manager checks whether all the entities are ready to commit for the transaction or not.
  • Commit Phase - In this phase, the commitment of entities get started in reality.
The following figure illustrates the functions of both the phases of a WCF transaction.
Wcf Transaction Phases 2

Enabling a WCF Transaction

To enable a WCF transaction successfully, one needs to follow a series of six steps in a sequential manner. The requisite steps are discussed below.
Step-1: Creation of two WCF Services
The foremost step in this regard is to build two service projects in WCF to participate in a single transaction. Database transactions will be performed on both these services and it will be understood that how they are unified by a WCF transaction. A web application of WCFTransactions has also been created to consume the two created services in a single transaction scope.
Wcf Transaction Enable 1
Step-2: Method creation and its attribution with TransactionFlow attribute
Here, an UpdateData method will be created for both the WCF services to insert into the database with OperationContract attribute. To accomplish this task, an interface class is first created with the help of the ServiceContract attribute. For enabling the transaction in the newly created method, it is attributed with TransactionFlow and transactions are permitted using is Allowed value.
[ServiceContract]
public interface IService1
{
   [OperationContract]
   [TransactionFlow(TransactionFlowOption.Allowed)]
   void UpdateData();
}
Step-3: Implementation of WCF service with TransactionScopeRequired attribute
It is done by using the code shown below:
[OperationBehavior(TransactionScopeRequired = true)]
public void UpdateData()
{
   try
   {
      SqlConnection objConnection = new SqlConnection(strConnection);
      objConnection.Open();
      
      using(SqlTransaction transaction = Program.dbConnection.BeginTransaction())
      {
         Boolean doRollback = false;
         using(SqlCommand cmd = new SqlCommand("insert into Customer (Customer name, Customer code) values ('sss', 'sss')"objConnection))
         
         try
         {
            cmd.ExecuteNonQuery();
         }
         
         catch(SqlException)
         {
            doRollback = true;
            break;
         }
      }
      
      if(doRollback)
         transaction.Rollback();
      else
         transaction.Commit();  
   }
   
   finally
   {
      objConection.Close();
   }
}
Step-4: Enabling Transaction Flow by WCF Service Config File
Its coding is done as follows:
<bindings>
   <wsHttpBinding>
      <binding name="TransactionalBind" transactionFlow="true"/>
   </wsHttpBinding>
</bindings>
It is vital to attach the transaction permissible binding with the endpoint to expose the WCF service.
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="TransactionalBind" contract="WcfService1.IService1">
Step-5: Calling both the services in a single transaction
Here, the above two services are called in one transaction and for this purpose, the TransactionScope object is used to group both the services. The Complete method of the above object is called to commit a WCF transaction. To rollback, the Dispose method is to be called.
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))
{
   try
   {
      // Call your webservice transactions here
      ts.Complete();
   }
   
   catch (Exception ex)
   {
      ts.Dispose();
   }
}
The small piece of the complete code in which WCF transactions have been grouped in one scope is depicted below:
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))
{
   try
   {
      ServiceReference1.Service1Client obj = newServiceReference1.Service1Client();
      obj.UpdateData();
      ServiceReference2.Service1Client obj1 = new ServiceReference2.Service1Client();
      obj1.UpdateData();
      ts.Complete();
   }
   
   catch (Exception ex)
   {
      ts.Dispose();
   }
}
Step-6: Testing WCF transaction
Testing is done in the 6th and final step and after calling the 1st WCF service, an exception is forced.
Wcf Transaction Enable 2