Reader Level:
ARTICLE

Enterprise Library 3.0 Data Access Application Block

Posted by Munir Shaikh Articles | C# Language July 12, 2007
Data Access Application Block(DAAB) simplifies development tasks that implement common data access functionality.The DAAB provides access to the most often used features of ADO.NET in simple-to-use classes; this boosts developer productivity.
  • 1
  • 0
  • 23504

Data Access Application Block(DAAB) simplifies development tasks that implement common data access functionality. Developer can use this application block in a variety of situations, such as reading data for display, passing data through application layers, and submitting changed data back to the database system. The application block includes support for both stored procedures and in-line SQL. The Data Access Application Block provides access to the most often used features of ADO.NET in simple-to-use classes; this boosts developer productivity.

ADO.NET 2.0 provides classes such as the DbCommand class and the DbConnection class; these classes help to abstract the data provider from any particular database implementation. The Data Access Application Block takes advantage of these classes and provides a model that further supports encapsulation of database type-specific features, such as parameter discovery and type conversions. Because of this, applications can be ported from one database type to another without modifying the client code. The Data Access Application Block includes an abstract base class that defines a common interface and that provides much of the implementation needed by the data access methods available in ADO.NET 2.0.

The application block also includes classes that are specific to Microsoft SQL Server, Microsoft SQL Server CE, and Oracle. These classes perform operations that are particular to the database type. The code for applications written for one type of database, such as SQL Server, looks much the same as the code for applications written for another type of database, such as Oracle.

Another feature of the Data Access Application Block is that application code can refer to particular databases by an ADO.NET connection string name, such as "Customer" or "Inventory." The application code can specify a named instance of a database and pass this parameter to the DatabaseFactory.CreateDatabase method. Each named database has its connection information stored in a configuration file. By changing the settings in the configuration file, developers can use their applications with different database configurations without recompiling their code.

The Data Access Application Block provides the following benefits:

It uses the functionality provided by ADO.NET 2.0 and with it, you can use ADO.NET functionality along with the application block's.

Functionality

  1. It reduces the need to write boilerplate code to perform standard tasks.
  2. It helps maintain consistent data access practices, both within an application and across the enterprise.
  3. It reduces difficulties in changing the database type.
  4. It relieves developers from learning different programming models for different types of databases.
  5. It reduces the amount of code that developers must write when they port applications to different types of databases.

Configuration of DAAB:

In solution explorer:

  1. Right click on Web.config file.
  2. Click on Edit Enterprise Library Configuration.
  3. Open the configuration file. For more information, see Configuring the Application Blocks.
  4. Right-click Application Configuration, point to New, and then click Data Access Application Block.
  5. The next procedure explains how to configure an instance of the default database. This instance is used if the application calls the DatabaseFactory.CreateDatabase method with no instance name.

    To configure the default database in the right pane, expand the DefaultDatabase property. Enter the connection string name for the DefaultDatabase property or select it from the dropdown box. The default connection string name is ConnectionString (Optional). Set the Name property by typing a new name. The default name is ConnectionString. In the ProviderName property section, change the provider name if you want to. Enter the name of the provider or select it from the drop-down list. The default provider name is System.Data.SqlClient. The ProviderName property must be a provider name specified in a DBProviderFactory class.

As I am using SQLExpress database here is sample as how the web.config will look like

<?xml version="1.0"?>

<configuration>

  <configSections>

    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,

Microsoft.Practices.EnterpriseLibrary.Data, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

  </configSections>

  <dataConfiguration defaultDatabase="ConnectionString" />

  <connectionStrings>

    <add name="ConnectionString" connectionString="Data

Source=(local)\SQLEXPRESS;AttachDbFilename=C:\Inetpub\wwwroot\EntLib\App_Data\Logging.mdf;Integrated Security=True;User Instance=True;"

providerName="System.Data.SqlClient"/>

  </connectionStrings>

  <appSettings />

  <system.web>

    <compilation debug="true">

      <assemblies>

        <add assembly="System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />

        <add assembly="System.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />

        <add assembly="System.Configuration.Install, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />

        <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />

        <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />

      </assemblies>

    </compilation>

    <authentication mode="Windows" />

  </system.web>

</configuration>


Here is SQL Table definition which I am using:

CategoryID int  Primary key Identity(1,1) Not Null
CategoryName varchar(50) Not Null
CategoryDesc varchar(250) Null

Note: Put ASP.NET user full control other wise you will get error unable to open Database.

In my sample I am showing two examples on default.aspx.

  1. which displays all the categories using ObjectDataSource and Grid View.
  2. Another interface which allow me to "add new category".

I have a util.cs class in App_Code which is responsible for providing different database interacting methods.

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using Microsoft.Practices.EnterpriseLibrary.Configuration;

using Microsoft.Practices.EnterpriseLibrary.Data;

using Microsoft.Practices.EnterpriseLibrary.Data.Sql;

using System.Data.Common;

/// <summary>

/// Summary description for Util

/// </summary>

public class Util

{

    // Some of the methods in this class are utilized in the object Datasource

    // GetCategory(): Returns Dataset

    public DataSet GetCategory()

    {

        DataSet customerDataSet = null;

        try

        {

            Database dbLst = DatabaseFactory.CreateDatabase();

            string strSql = "SELECT * FROM Category";

            DbCommand dbCmd = dbLst.GetSqlStringCommand(strSql);

            customerDataSet = dbLst.ExecuteDataSet(dbCmd);

        }

        catch (Exception ex)

        {

            HttpContext.Current.Response.Write(ex.Message);

        }

        return customerDataSet;

    }

    public int AddCategory(string catName, string catDesc)

    {

        int intRetVal = 0;

        try

        {

            Database db = DatabaseFactory.CreateDatabase();

            DbCommand dbCmd = db.GetStoredProcCommand("proInsertCategory");

            db.AddInParameter(dbCmd, "catName", DbType.String, catName.Replace("'", "").Trim());

            db.AddInParameter(dbCmd, "catDesc", DbType.String, catDesc.Replace("'", "").Trim());

            intRetVal = db.ExecuteNonQuery(dbCmd);

        }

        catch (Exception ex)

        {

            HttpContext.Current.Response.Write(ex.Message);

        }

        return intRetVal;

    }

}

Default.aspx page:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:Label ID="lblHeading1" runat="server" Font-Bold="True" Font-Names="Verdana"

            Font-Size="Small" Text="DATA ACCESS APPLICATION BLOCK Sample with inline SQL "

            Width="100%"></asp:Label><br />

        <asp:GridView ID="GrdvwCategory" runat="server" AllowPaging="True" AllowSorting="True"

            DataSourceID="ObjectDataSource1" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3"

CellSpacing="1" GridLines="None">

            <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />

            <RowStyle BackColor="#DEDFDE" ForeColor="Black" />

            <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />

            <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />

            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />                       

            <Columns>

                <asp:CommandField ShowSelectButton="True" />

            </Columns>

        </asp:GridView>

        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetCategory"

            TypeName="Util"></asp:ObjectDataSource>

        &nbsp; &nbsp; &nbsp; &nbsp;        &nbsp;&nbsp;

        <br />

        <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Names="Verdana" Font-Size="Small"

            Text="DATA ACCESS APPLICATION BLOCK Sample with Stored Procedure" Width="100%"></asp:Label><br />

        <asp:Label ID="lblMessage" runat="server" Font-Names="Verdana" Font-Size="Small"

            ForeColor="Red"></asp:Label>

        <table cellpadding=1 cellspacing=1 bgcolor="#dcdcdc" style="width: 53%">

            <tr>

                <td colspan="2" style="height: 21px;font-family:Verdana;font-size:11px;font-weight:bold;">

                    Add New Category

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtCatName"

                        Display="Dynamic" ErrorMessage="Category Name is required field" Font-Names="Verdana"

                        Font-Size="Small"></asp:RequiredFieldValidator></td>

            </tr>

            <tr>

                <td style="width: 106px;font-family:Verdana;font-size:11px;font-weight:bold;">

                    Category Name:</td>

                <td style="width: 138px">

                    <asp:TextBox ID="txtCatName" runat="server" MaxLength="50"></asp:TextBox></td>

            </tr>

            <tr>

                <td style="width: 106px;font-family:Verdana;font-size:11px;font-weight:bold;">

                    Description:</td>

                <td style="width: 138px">

                    <asp:TextBox ID="txtCatDesc" runat="server" MaxLength="250" TextMode="MultiLine"></asp:TextBox></td>

            </tr>

            <tr>

                <td style="width: 106px; height: 26px">

                </td>

                <td style="width: 138px; height: 26px">

                    <asp:Button ID="btnAdd" runat="server" Text="Add New" OnClick="btnAdd_Click" /></td>

            </tr>

        </table>

    </div>

    </form>

</body>
</html>

Default.aspx.cs page:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page

{

    protected Util objUtil = new Util();

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    protected void btnAdd_Click(object sender, EventArgs e)

    {

        if (txtCatName.Text.Trim() != "")

        {

            int insVal = objUtil.AddCategory(txtCatName.Text, txtCatDesc.Text);

            if (insVal == 1)

            {

                lblMessage.Text = "New category addeded successfully!";

                Server.Transfer("./Default.aspx");

            }

            else if (insVal == 2 || insVal == -1)

            {

                lblMessage.Text = "Category with same name already exists!";

            }

            else

            {

                lblMessage.Text = "An error has occured while processing your request!";

            }

        }

    }

}

As shown in the diagram you should have reference added to this project as below:

1.Microsoft.Practices.EnterpriseLibrary.Common.dll
2.Microsoft.Practices.EnterpriseLibrary.Configuration.Design.dll
3.Microsoft.Practices.EnterpriseLibrary.Data.Configuration.Design.dll
4.Microsoft.Practices.EnterpriseLibrary.Data.dll
5.Microsoft.Practices.ObjectBuilder.dll

COMMENT USING

Trending up