Friday, March 12, 2010

WCF – Exception Handling in Asynchronous Operations

Yesterday, I got a query regarding how to handle exceptions in case of asynchronous web service operations. Precise question was,

I am calling a WCF service using Asynchronous way,  the service may execute for some time, meanwhile if any exception occurred in the service side how can I come to know what happened in the service side?

I am not able to get the status in the Async Method.

There is a pretty simple solution available for this problem.

When the asynchronous method throws an exception, proxy catches it and when the client calls End Operation the proxy re-throws that exception object so that client can handle the exception. If a COMPLETION CALLBACK is provided, WCF calls that method immediately after the exception is received. Exception thrown is compliant with the fault contract and type of exception. Following code snippet shows how to do this;

Contract Code

public interface ICalculator
{
[OperationContract]
[FaultContract(typeof(Exception))]
double Add(double n1, double n2);
}



Service Code




public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
throw new FaultException<Exception>(new Exception("Gaurav is sending exception"));
return n1 + n2;
}
}



Client Code




class Client
{
static void Main()
{
Console.WriteLine("Press <ENTER> to terminate client once the output is displayed.");
Console.WriteLine();

GauravCalculator.CalculatorClient calcService = new GauravCalculator.CalculatorClient();
int sum = 0;
AsyncCallback completion = (result) =>
{
try
{
sum = (int)calcService.EndAdd(result);
Console.WriteLine("Sum is :" +sum.ToString());
calcService.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
};
calcService.BeginAdd(10, 10, completion, null);

Console.WriteLine();
}



Using this method you can receive any service side exceptions on client side.

~pEaCe~


Currently Listening to: Bekaraar from Pathshala (new Lucky Ali song)

Wednesday, March 3, 2010

GO – SQL Server

While working on SQL Server we all encounter GO statement quite often. Till today GO statement for me was just an indication sent out to SQL Server utilities about end of a batch of Transact - SQL.

Today while going through MSDN I found a new (surprising) thing about GO. Go can actually take an integer argument. Yes! it is true. Go takes an optional integer argument. Something like this,

GO [count]

As per MSDN,

count is a positive integer. The batch preceding GO will execute the specified number of times.

What this means is, suppose you have a script like the one below,

INSERT INTO TestGO VALUES (10, 'testing go')
GO 5000

Here, INSERT statement will be executed 5000 times and you will end up inserting 5000 records in table.

~eNjOy LiFe~
Currently Listening to: In the summer time - SHAGGY