Monday, October 1, 2012

WCF Service Exception Handling Best Practice

I was working on a WCF service and I needed a way to handle uncaught exception raised during any service operation in a controlled way e.g. I wanted to log or email unhandled exception and send a valid response to client with information required to trace the problem.

One way was to have a try catch in each method and return the fault from there. This approach is simple and works however in case of lots of service operations or lots of services it become very tedious to repeat the same code block everywhere.

So I searched and finally implemented a new common error handler for my service based on WCF interface IErrorHandler. This interface provides two methods HandleError and ProvideFault which you can override to implement your own logic. Once hooked into your service, for any uncaught exception HandleError and ProvideFault methods are invoked. HandleError is the method where you log the errors, and ProvideFault creates a new fault message which becomes your service response.

There are two ways you can hook this handler to your service:
1) using Service Behavior attributes by implementing IServiceBehavior interface and inheriting from Attribute class. and then use the attribute on your service class similar to any other attribute

2) Use service behavior extension by inheriting from BehaviorExtensionElement, which allows to configure common error handler via service web.config file

I have attached here the complete code of this common handler. In order to use this either use method 1 or 2. A sample on how to use is given in ErrorBehaviorAttribute and ErrorBehaviorExtension classes as well.


Please note, this sample code also gives you a common ServiceException class which you need to use as faultContract type in your service contract e.g.
[FaultContract(typeof(ServiceException), Name = "serviceFault")]

If you decide to use this Common Error Handler, The same ServiceException should be used to return your business exceptions. You can always change implementation of these anytime you want, this code only gives you an idea on how to implement these.

Also last but not least, in order to upload the sample to make it available to all of you, I made some changes e.g. namespace and all you may want to change them as per your need.

Happy coding :-)









Monday, May 7, 2012

Convert ASMX web services to WCF


WCF provided much more features and functionality than asmx service out of the box e.g. it implements standards like WS Security, WS Addressing, WS Transaction etc. Performance wise its better than asmx services. See following links for WCF benefits:

http://msdn.microsoft.com/en-us/library/ff648122.aspx

http://msdn.microsoft.com/en-us/library/bb310550.aspx

http://msdn.microsoft.com/en-us/library/aa480190.aspx

For converting an asmx service to WCF we need to take following steps, This approach will choose appropriate serializer depending on the types defined in your asmx service.
  • Create a .wsdl file from current asmx service, you can do this by typing the service url?wsdl in IE and then save the file as .wsdl extension
  • Go to Visual Studio Command Prompt
  • Go to the directory where you saved wsdl file and run svcutil.exe with wsdl file name as argument e.g. svcutil.exe Queue.wsdl
  • The svcutil will generate two files .cs file and .config file. The .cs file will contain your service contract.



  • Create a new WCF Service Application in your solution, This template creates a service1.svc in your project, remove all files associated with Service1
  • Add a new WCF Service by using add item and name it as your own service e.g. Queue
  • Delete the interface file created in above step.
  • Copy your .cs file generated by svcutil to your WCF service application folder and include it in your project. Change the file name to indicate it as an interface e.g. IQueue.cs. You need to change the class name also and its references in the class.
  • In your generated interface file, remove , ReplyAction = “*” string for each operation, see the screen shot:




  • Implement the above interface in your implementation class
  • Build your project, and you should be good to go. 
  • You can now implement your methods by copying your old code to new one or by writing it new.
  • In order test, browse your service in browser or add a service reference to a test project, and it should generate similar interface at your end.

Migrate VB.NET code to C#


There are various reasons to migrate the code to C#, few of them are listed below:

  • C# is an ECMA standards compliant language with a formal definition and a corresponding abundance of third party and open source tools. VB.NET is at Microsoft’s mercy to do whatever they want with it – and they do. VB.NET makes it easy for VB programmer to move to .NET.
  • C# code is faster as generated MSIL from C# and VB.NET is not same always
  • Terseness and readability of code. C# follows the C, C++, Java syntax tradition, while VB is more verbose.
  • IDE Responsiveness – It is difficult to work with a large VB.Net project in Visual Studio
  • Improved Code Quality – C# catches many errors allowed in VB.Net, such as variable use before initialization and dead code. It also doesn’t allow undeclared variables, untyped variables, and untyped methods that are allowed in VB.Net.

We will be using an open source tool SharpDevelop developed by IC# (http://www.icsharpcode.net/). This tool is an open source IDE to develop .NET applications similar to Visual Studio and also gives the ability to convert your entire project from VB.NET to C#. We did a POC to convert eService application to C# and its results are very promising. The only compiler issues I found was the implicit type casting issues which C# does not allow. The steps to convert are listed below:


Note: A web site project first need to be converted to a web application project before you can convert the code to C#. You should also upgrade .NET framework before migrating the code to C#

Convert ASP.NET Web Site project to Web Application project

Web sites projects use visual studio template of web site project which has certain limitation in terms of managing it e.g. its difficult to maintain web.config file for different environments. Web Application template gives the ability to manage web.config file for different environment using transformation file. In this way, you only need to manage the differences in different environment, and do not copy entire web.config for different environment.
To read more about this go to this link http://msdn.microsoft.com/en-us/library/dd465326.aspx

In order to convert a web site to web application project follow the below steps:
  • Create a new Empty Web Application Project (.NET 4.0) in your solution
  • Add all assembly references and web references to the project. Make sure web references use the same name as in old project.
  • Copy all your files from old web site project to new project directory. Do not copy obj & bin directory and your old web.config files.
  • Include all copied files in your project
  • Right click on your new project and click on Convert to Web Application as shown below:
  • Visual Studio will convert your web site to web application project, after this you will notice that there will be a designer.vb or designer.cs will be created for each asp.net page or user control.
  • Compile your project and resolve any issues you have.
  • Copy the relevant and required section of web.config from your old project to the web.config of your new project. Do not copy paste entire stuff
  • You are done for your local development and testing
  • In the project you will notice two extra config files once you expand web.config file. As shown below, you should see two files by default 1) Web.Debug.config and 2) Web.Release.config. These two files are there to manage configuration differences in different build of the project. E.g. in release build you remove compilation attribute debug=true
  • In order to add new config for your test, production environment. Create a new Build Configuration from Configuration Manager.
  • o Right click on your solution, select Configuration Manager
  • o Select New from Active solution configuration drop down
  • o Type your configuration name e.g. QA and copy the settings from Release Configuration
  • o Once you have added the configuration, right click on web.config file and select Add Config Transforms. This option is only enabled if there is an extra configuration for which transformation can be added. As soon as you click on this it will create the web.QA.config file within web.config.
  • To add transformation rule or change configuration in different environments use transformation syntax. You can use msdn link http://msdn.microsoft.com/en-us/library/dd465326.aspx to learn more about those.
  • Once above step is completed, you can publish your web application (right click on project->publish) and web.config file will have the correct settings based on build configuration you selected from configuration manager.