Tuesday, August 17, 2010

LINQ to SQL – Generic Insert

Currently I’m working on a project’s data layer code. I’ve chosen LINQ to SQL for this purpose and created a helper library to perform CRUD operations in an easy and generic way.

Following is the code which insert any database object using LINQ:

   1: public static void Insert<T>(T entityData) where T : class
   2: {
   3:     using (TransactionScope trans = new TransactionScope())
   4:     {
   5:         using (App_Data.DBDataContext db = new App_Data.DBDataContext())
   6:         {
   7:             db.GetTable<T>().InsertOnSubmit(entityData);
   8:             db.SubmitChanges();
   9:             trans.Complete();
  10:         }
  11:     }
  12: }

Technorati Tags:

Few noteworthy points:

  • I’m using transaction scope but we can omit that, because for single update or insert, LINQ already provides transaction support. This is only required while making multiple inserts or updates
  • Conditional generics are used because GetTable<T>() requires T to be a reference type
  • Just like above method, update and delete can also be implemented


  • Suppose you have a database table Order
  • In LINQ to SQL, this table is represented as a class, in which table columns are represented as properties
  • To insert a new record for Order
    • Create new object of Order – Order orderNewObject = new Order();
    • Fill orderNewObject properties with desired values
    • Pass this new object to Insert method like this - Insert<Order>(orderNewObject);

Using above method we can easily perform database operation without even writing a single T-SQL statement.


Wednesday, August 11, 2010

SQL Server - NULL

There is a bit of inconsistency in the way SQL Server treats (read it as implements) NULLs. Following are some noteworthy points related to implementation and usage of NULL values in SQL Server:

  • 3 possible values of logical expression
    • TRUE
    • FALSE
  • UNKNOWN occurs when a logical expression involves NULL
    • NULL > 2 is UNKNOWN
    • X + NULL is UNKNOWN
  • Query filters (ON, WHERE, HAVING) treat UNKNOWN as FALSE
  • CHECK constraint treat UNKNOWN as TRUE
  • During comparison NULL = NULL is treated as not equal
  • UNIQUE constraint, UNION, EXCEPT, SORTING and GROUPING treats NULLs as equal

This information is quite handy when you are writing TSQL queries targeting data with NULL values.

Currently Playing – Not Afraid by Eminem

Technorati Tags: ,,

del.icio.us Tags: ,,

Thursday, June 24, 2010

Windows Azure – Custom configuration settings

Few days back, I received a question on our internal Azure discussion DL regarding, how we can have settings defined in a web configuration file implemented in a web role. In simple terms, how we can have configuration file in a Windows Azure application.

This is how we can do this;

During development

  • ServiceDefinition.csdef – Add name of your custom configuration


  • ServiceConfiguration.cscfg – Add value to your custom configuration


  • Now, use this custom configuration in code


When you publish this project, generated ServiceConfiguration.cscfg will have your custom configuration key value pair. You can also modify this after you deploy your app in the cloud.

Technorati Tags: ,


Saturday, May 1, 2010

Post Back from AJAX Update Panel

Recently, while working on a dev assignment I needed to make a complete post back (with page refresh) from a button control placed inside AJAX Update Panel. Exact problem was like this. There is a webpage on which I require AJAX functionality. Also, there is one button on whose click I want to make a post back. That button is also placed inside AJAX update panel and anything placed inside update panel by default does a Ajax callback. Sample web page is shown below:


Initially I thought of moving my Post Back Call button outside of AJAX update panel but that would have ruined my UI design. I was trying different options when I stumbled upon UpdatePanel’s child element <Triggers>. <Triggers> provides another child element <asp:PostBackTrigger /> with an attribute ControlID. We can specify from which control we want to make a post back call using this ControlID. Below code sample shows how to do this in ASP.NET.


This is quite simple to understand. Button btnPostBackCall will now make a complete call back. I recommend further reading on this topic from:

Currently Listening To: Heartbreak Warfare by John Mayer

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
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.");

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


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


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