home » articles » Creating a Simple Data Access Framework in ASP.NET

Creating a Simple Data Access Framework in ASP.NET

change text size: A A A

4/16/2009 by Vinz

Introduction:

This article describes on how to create a data access architecture using sqlclient objects with ADO.NET that will returns a DataTable. It also discusses here on how to use and access a certain method in a particular class for you to manipulate the data into your codes.

Please note that I am using the Northwind database here and all codes in this article is written in C# language.

STEP1: Creating a Class


First, I added some folders under my App_Code folder to store some classes. These class includes the following below:

CommonQueries.cs - is class that contains all the sql string queries which can be reference in the DAL.cs class.
DAL.cs - is class that executes the request from the user. Its basically executes the Insert, Update, Delete and Fetching of data from the database.
DBConnection.cs - is a class that contains the connection string

See the figure below.

STEP 2: Setting up the Connection string

In this article I am setting the connection string under the ConnectionString tag in the web config file like below.

<connectionStrings>

     <add name="MyDBConnection" connectionString="Data Source=WPHVD185022-9O0;Initial Catalog=Northwind;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>

 </connectionStrings>


Note that the attribute “key” will serves as the identifier for the connection string.

STEP 3: Calling the connection string in the class


After setting up the connection string in the web config, the next step is to call that connection string in the DBConnection.cs class that I have been added earlier in the App_Code folder. This is to achieve reusability in accessing the connection string and to reduce writing codes in our application.

 

The DBConnection Class

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;

 

/// <summary>
/// Summary description for Connection
/// </summary>

public class Connection
{

    public string Connstr()
    {

   return System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString

//gets the connection string from your web config file

    }

}

 

Note: MyDBConnection is the name of the connectionstring that was set up in the webconfig.

 

STEP 4: Creating the DAL.cs Class


Data Access Layer (DAL) is basically a class that contains the methods for Insert,Update,Delete and Fetch execution. This will help developers minimize their efforts for manipulating data back and forth because the DAL class in intended to obtain a reusable codes.

The DAL Class

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 System.Data.SqlClient;
/// <summary>
/// Summary description for DAL
/// </summary>


public class DAL
{

    // Executes the INSERT/UPDATES
    public void InsertWithParam(string statement, SqlParameter[] param)
    {
        Connection constring = new Connection();
        using (SqlConnection conn = new SqlConnection(constring.Connstr()))
        {
            try
            {

                conn.Open();
                SqlConnection CStr = new SqlConnection(constring.Connstr());
                SqlCommand cmd = new SqlCommand(statement, CStr);                              cmd.CommandType = CommandType.Text;

                for (int i = 0; i < param.Length; i++)
                {
                    cmd.Parameters.Add(param[i]);
                }

                cmd.Connection.Open();
                cmd.ExecuteNonQuery();
                cmd.Connection.Close();
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                string msg = "Insertion Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
            finally
            {

                conn.Close();
            }
        }
    }

    // Executes for FETCHING/SELECTING Data
    //Fetches the data from the database with paramters
    public DataTable FetchDataWithParam(string statement, SqlParameter[] param)
    {

        Connection constring = new Connection();
        using (SqlConnection conn = new SqlConnection(constring.Connstr()))
        {
            DataTable dt = new DataTable();
            try
            {
                conn.Open();
                SqlConnection CStr = new SqlConnection(constring.Connstr());
                SqlCommand cmd = new SqlCommand(statement, CStr);

                cmd.CommandType = CommandType.Text;

                for (int i = 0; i < param.Length; i++)
                {
                    cmd.Parameters.Add(param[i]);
                }

                cmd.Connection.Open();
                cmd.ExecuteNonQuery();


                SqlDataAdapter adapter = new SqlDataAdapter(cmd);

                adapter.Fill(dt);

                cmd.Connection.Close();
                return dt;

            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                string msg = "Fetching Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
            finally
            {
                conn.Close();
            }
        }
    }

    //Fetches the data from the database WITHOUT paramters
    public DataTable FetchData(string statement)
    {

        Connection constring = new Connection();
        using (SqlConnection conn = new SqlConnection(constring.Connstr()))
        {
            DataTable dt = new DataTable();
            try
            {
                conn.Open();
                SqlConnection CStr = new SqlConnection(constring.Connstr());
                SqlCommand cmd = new SqlCommand(statement, CStr);

                cmd.Connection.Open();
                cmd.ExecuteNonQuery();

                SqlDataAdapter adapter = new SqlDataAdapter(cmd);

                adapter.Fill(dt);

                cmd.Connection.Close();
                return dt;

            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                string msg = "Fetching Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
            finally
            {
                conn.Close();
            }
        }
    }
    //Executes for DELETING data
    public void DeleteWithParam(string statement, SqlParameter[] param)
    {
        Connection constring = new Connection();
        using (SqlConnection conn = new SqlConnection(constring.Connstr()))
        {
            try
            {
                conn.Open();
                SqlConnection CStr = new SqlConnection(constring.Connstr());
                SqlCommand cmd = new SqlCommand(statement, CStr);                cmd.CommandType = CommandType.Text;

                for (int i = 0; i < param.Length; i++)
                {
                    cmd.Parameters.Add(param[i]);
                }
                cmd.Connection.Open();
                cmd.ExecuteNonQuery();
                cmd.Connection.Close();

            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                string msg = "Deletion Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
            finally
            {

                conn.Close();
            }
        }

    }
}

using System.Data.SqlClient;

The following are the names of the DAL methods with its corresponding descriptions.

Note that you should declare the namespace below in your class fro you to use SqlClient libraries.

 

InsertWithParam()                                 A method that executes for Inserting/Updating data into the database with a specified paramater
 FetchDataWithParam() A method that executes for Fetching data into the database with a specified paramater
 FetchData() A method that executes for fetching data into the database
 DeleteWithParam()  A method that executes for deleting data into the database with a specified paramater

 

 

STEP 5: Creating the CommonQueries.cs Class

CommonQueries Class basically contains all the SELECT, UPDATE, INSERT and DELETE sql string queries. What I mean is that all the queries are set up in this class. You can write or add any methods this class based on your requirements.

Basically CommonQueries class calls the DAL class with or without the paramaters. The DAL class will then executes the commands being requested and returns it to the Methods under CommonQueries that calls for it.

In this article, I will just show to you on how are we going to add a simple methods within the CommonQueries class. I also include a methods here for Fetching,Inserting and deleting data to the database. Take a look at  the following code blocks below

The CommonQueries Class

 

 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 System.Data.SqlClient;

 
 ///
 /// A class that contains the connection string
 ///

 public class CommonQueries
 {

 //A method that Gets all the cutomers from the database

         public DataTable GetAllCustomers()
         {

         DataTable dt = new DataTable();
         string sql = string.Empty;

             try
             {
                 sql = "SELECT * FROM Customers";
                 DAL dal = new DAL();
                 dt = dal.FetchData(sql);

                 return dt;
             }
             catch (System.Exception ex)
             {
                throw new Exception(ex.Message);
             }
         }

         //A methods that gets all the orders per customer
         //GetOrdersPerCustomer is a method with a reqiured parameter

         public DataTable GetCustomerDetails(string cusid)
         {

         DataTable dt = new DataTable();
         string sql = string.Empty;

             try
             {

                 sql = "SELECT * FROM Customers WHERE CustomerID =@id";

                 SqlParameter[] param = new SqlParameter[1];           
                 param[0] = new SqlParameter("@id", SqlDbType.NChar,5);
                 param[0].Value = cusid;

                 DAL dal = new DAL();
                 dt = dal.FetchDataWithParam(sql,param);

                 return dt;

             }
             catch (System.Exception ex)
             {
                throw new Exception(ex.Message); 
             }

         }
 
         //A methods that Deletes the record per customer in the databae
         //DeleteOrdersPerCustomer is a method with a reqiured parameter

         public void DeleteCustomer(string cusid)
         {

         string sql = string.Empty;
             try
             { 
                 sql = "DELETE FROM Customers WHERE WHERE CustomerID =@id"; 
                 SqlParameter[] param = new SqlParameter[2];

                 param[0] = new SqlParameter("@id",SqlDbType.NChar, 5);
                 param[0].Value = cusid; 

                 DAL dal = new DAL();
                 dal.DeleteWithParam(sql, param);
             }

             catch (System.Exception ex)
             {

                throw new Exception(ex.Message); 

             }
         }

         //A methods thatInserts new cutomer to the database
         //AddNewCustomer is a method with a reqiured parameter

         public void AddNewCustomer(int id, string name, string address, string city)
         {

         string sql = string.Empty;

             try
             {

                 sql = "INSERT INTO Customers (CustomerID,ContactName,ContactAddress,City)VALUES(@account,@contact,@nick,@msg)";

                 SqlParameter[] param = new SqlParameter[4];
                 param[0] = new SqlParameter("@id",SqlDbType.NChar, 5);
                 param[1] = new SqlParameter("@name",SqlDbType.NVarChar, 30);
                 param[2] = new SqlParameter("@address",SqlDbType.NVarChar, 60);
                 param[3] = new SqlParameter("@city",SqlDbType.NVarChar, 15);

                 param[0].Value = id;
                 param[1].Value = name;
                 param[2].Value = address;
                 param[3].Value = city;

                 DA Ldal = new DAL();
                 dal.InsertWithParam(sql, param);

             }
             catch (System.Exception ex)
             {
               throw new Exception(ex.Message);
             }

         }
 }

 

The following are the names of the CommonQueries method with its correspondin descriptions.

GetAllCustomers() Gets all the customers from the database
GetCustomerDetails() Gets the customer details from the database based on the customer id
DeleteCustomer()  Delete the records of the customer in the database
AddNewCustomer()  Insert new customer in the database


STEP 6: Accessing the Class in the Page

After creating those classes then we can now test for it. In this article I will be calling the GetAllCustomer() and
GetCustomerDetails() methods in the CommonQueries and populate my DropDownList and GridView. Basically the DropDownList will be populated by the CustomersID and the GridView will be populated based on the selected ID from the DropDownList.

Here's the sample code blocks below:

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
{
    private void PopulateDropDownList()
    {
        //first we need to instatiate the CommonQueries.cs Class so that we can access all the methods in that class.
        CommonQueries getcustomers = new CommonQueries();
        //I define a new datatable as my datasource for populating the DropDownList
        DataTable dt = getcustomers.GetAllCustomers(); // GetAllCustomers is a method under the CommonQueries.cs class

        if (dt.Rows.Count > 0)// validates id dt has a returned value
        {
            DropDownList1.Items.Add("Select Customer ID"); // adds the word select before the dropdownlist is being populated
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string id = dt.Rows[i]["CustomerID"].ToString(); //gets the customer id
                string customername = dt.Rows[i]["ContactName"].ToString(); //gets the customer name
                DropDownList1.Items.Add(id + "-" + customername); // combine the two values and add it in the dropdown lists
            }
        }
        else
        {
            Response.Write("Record is empty");
        }
    }

    private void PopulateGridView()
    {
        CommonQueries getdetails = new CommonQueries();
        DataTable dt =  getdetails.GetCustomerDetails(DropDownList1.SelectedItem.Text);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            PopulateDropDownList();
        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        PopulateGridView();
    }
}


The ASPX Source:

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Default</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <div>
            <asp:DropDownList AutoPostBack="true" ID="DropDownList1" runat="server" Width="216px" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
            </asp:DropDownList>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
                <Columns>
                    <asp:BoundField DataField="CompanyName" HeaderText="Company" />
                    <asp:BoundField DataField="ContactName" HeaderText="Full Name" />
                    <asp:BoundField DataField="ContactTitle" HeaderText="Position/Title" />
                    <asp:BoundField DataField="Address" HeaderText="Address" />
                    <asp:BoundField DataField="City" HeaderText="City" />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>



OUTPUT:
here's the output below for that query.




That's it.

To rate this article please register or login

Author

Vinz Vinz (Member since:4/15/2009)
Working as a SDE at NCR Corporation and specializing on ASP.NET technologies. I am an active forum member and a regular contributor at the official ASP.NET forum site and one of the Top Community member with All- Star recognition level.I voluntarily spent my extra time helping other geeks through forums, blogs and articles. I have been awarded as Microsoft MVP - ASP/ASP.NET for 2009.

Comments (no comments yet)

Post a comment

Comment (No HTML)  

Type the characters:
 *
 
   

Related articles

Join CodeAsp.Net for FREE Today!

It's fast, easy and free! Submit articles, get your own blog, ask questions & give answers in the forums, and become a better developer, faster.

enter your email address:

Latest Articles RSS Feed

Latest Articles

  • Hi Friends, Many times we came cross the requirement when we need to access the dropdownlist's selectedindexchanged event inside the gridview, like in a shopping cart changing the item's quantity or binding the other dropdown based on the first dropdown.
  • This is the approach that I have adopted to develop Expandable / Collapsible Panel Control through JavaScript. Please report bugs, errors and suggestions to improve this control.
  • This is my approach to develop custom JavaScript ListBox control. Although it is only a subset of existing HTML ListBox element, it is more user friendly than the existing one. It can be further customized for different requirements. Please let me know about bugs and/or errors & give suggestions to improve this ListBox control.
  • I have tried my best to make this user control code error free. I will most welcome suggestions for further improvement in this user control. I have tested this user control on various browsers and it works fine.
  • So, this is my approach to implement an ASP.NET slide show using the DataList. I have tried my best to keep it bug free. I will most welcome suggestions and criticism for further improvements of this user control. I have tested this user control on various browsers and it works fine.
  • As we all knows that Repeater and DataList does not have auto paging support technique like Gridview or Datagrid, but we can achieve this through PagedDataSource. By using PagedDataSource we can implement paging in Repeater or DataList. Now in our mind there is question arise what is PagedDataSource. PagedDataSource is a class which encapsulates
  • So this is my approach. I was working for a long time to create C# like event handlers for JavaScript classes and finally, I’ve done it. Please let me know of any bugs and suggestions to improve this context menu control.
  • So this is my solution. If you have some other ideas about this functionality, please share them with me.
  • I have tried my best to make this code error free. Suggestions and criticism for further improvements of this code are most welcome.
  • So this is the approach that I've adopted to solve the Hover Delay problem. Although originally I developed Hover Delay to deactivate the click event for 1 second on a GridView row, later I also used Hover Delay to deactivate Drag n Drop of GridView rows. Kindly let me know if any one has some other better or different solution.
  • In this article I will explain how to import data from EXCEL to SQL in ASP.NET . In many situations we have data in the form of excel sheet but we have the requirement to have that data in SQL SERVER DB. I have explained importing data both from Excel 97-2003 as well as Excel 2007 format.
  • The source code shows how to use Regular Expressions in C#. The code Functions written for Validation Alphabet, AlphaNumeric, Integer, Postive Integer, Floating point numbers. You just cut copy these functions and use in any program.
  • That’s all about this technique. Just download the sample application and happy CSS! I have tested this application on various browsers and it worked fine.
  • This script is cross-browser compatible and fast as it iterates elements of a specific tag inside a target element [GridView] rather than iterating in a whole form. It searches the elements of a specific type in a particular column of the target element [GridView].
  • This Article is used to insert a numeric value on the sever control(text box) This is a java script code for the the client side validation. On Page Load Event You can change the events in txtNoOfQuestion.Attributes.Add("onkeypress", "return numericOnly(this);"); like onfocus events like other according to needs.
  • I have toggled visibility of all TD elements of a GridView column in order to create an illusion of smooth dynamic effect with the help of setTimeout method through recursion. Different browsers have different effects of Expanding / Collapsing GridView Columns. In Internet Explorer 7/8, Safari, Google Chrome and Opera, it seems that columns are Exp
  • In this article, I've used the setTimeout method in order to achieve a smooth expand/collapse functionality.
  • Introduction I am going to present here a functionality that selects / deselects all checkboxes of a particular column inside a GridView control, provided the header checkbox of that column is checked or unchecked using JavaScript. This functionality also has a feature that when all checkboxes of a particular column inside the GridView are check
  • This article describes how to toggle the states of all CheckBoxes inside a particular DataGridView column.
  • This article describes how to apply client-side mouse over & mouse out effects on the GridView’s rows.