Using anonymous method to safely retrieve data reader passed from DAL

Some time you are forced to create a method just for the sake of using a delegate, for example there is no need for multiple targets or the code involved too short and simple. Anonymous method is a new feature in C# 2.0 that allows you to define an anonymous method called by a delegate. while they are new to c# world its widely used as “Closers” in functional programming language like lisp.

Download Source code

When we pass DataReader from DAL to business layer or UI we are also passing responsibility of closing connection to client, in case of unexpected error or if some body working on UI forgets to close reader then connection will remain open.

Few months ago “Teemu Keiski” came up with excellent way of using delegates to Control DAL responsibility you can read more about that technique here. Lots of people shyed away from using his technique because it needs additional method to be declared to retrieve DataReader passed as delegate parameter. But with introduction of anonymous methods there is no need to write additional method.

I am using “Northwind” database to show sample code.

Following is DAL code with DataReaderHandler delegate and GetCustomer method that takes delegate. DAL code takes care of closing reader and connection.

public class CustomerDB {
    public delegate void DataReaderHandler(IDataReader reader);
    public static void GetCustomer(DataReaderHandler handler, string customerID) {
        string connectionString = "server=localhost;Trusted_Connection=true;database=NorthWind";
        using (SqlConnection conn = new SqlConnection(connectionString)) {
            SqlCommand sqlCommand = new SqlCommand("Select * from Customers WHERE CustomerID = @CustomerID", conn);
            sqlCommand.Parameters.AddWithValue("@CustomerID", customerID);
            conn.Open();

            using (SqlDataReader rdr = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection)){
                handler(rdr);
            }
        }
    }
}

How to access GetCustomer from client side.

CustomerDB.GetCustomer(delegate(IDataReader reader){
    If(reader.Read()){
       // do some this with code.
    }
    reader.Close()
}, "ALFKI");

Read more about new features in c# 2.0 here

Attached code contains sample DAL class and method code, for simplicity I have kept both on same aspx page.

Bookmark with:
Technorati   Digg   Delicious   StumbleUpon   Facebook
My name is Jigar Desai I share my ideas on this site and you can contact me by filling contact form.