Data Access Application Block

Recently, I worked on a project that deal with SQL and for a change I thought I’d give Microsoft Enterprise library a try and since then , I never looked back. To show you how quickly it is to do Data Access using Data Access Block from Microsoft Enterprise Library I have put together a quick tutorial:

1. You need to download the Library here , this is under Microsoft Patterns and Practices.

2. Next is to open your Visual Dev Studio (VS 2008 or Express).

3. Create a Web Application

4. Once you have setup a project , right click on the project name and Add Web configuration file, but if you are developing a DLL component you should see “Application configuration file” instead.

5. Now normally, we would have to insert our own xml but luckily the Enterprise library can do this thing for us.Do this by right clicking on your web config or application config file, the select Enterprise Library Configuration it will look something like this:

Microsoft Library

You can edit the entry, or Add a new entry on the data block, and setup your data source properly, you can do an attach database to your mdf file or use an actual sql server.

Then back to your Default.aspx

Before we go to Default.aspx, make sure that you include the call to this assembly by using “using” keyword for example:

using Microsoft.Practice.Patterns.Data;

and you can do the following code on your default.aspx and on your Page_Load() method you can call this method:

DisplayData();

public string DisplayData()
        {
            string rData = string.Empty;
 
            Database db = DatabaseFactory.CreateDatabase("MyDB");
            IDataReader reader = db.ExecuteReader("getProducts");
 
            while(reader.Read())
            {
                rData = reader["FIRST_NAME"].ToString();
            }
 
            return rData;
 
        }

That’s it! wasn’t that easy? this would normally entail long codes but because of the application block methods wrapped under this component you can easily create your Data layer.