Component based programming has one major advantage that it allows your code to be more organized, consistent and reusable. A component, in its simplest form, may be defined as one or more classes that are compiled into a separate DLL assembly file. You can use these components in one application or share between multiple applications, the best part of using component is encapsulation, which means all the massy part of your class will be hidden to user but all the features your code requires. When combined with the careful organization, component based programming is the basis of good ASP.NET application design.
For example, if you want to retrieve data from a SQL Server Database, you need to weave database details such as query directly into code behind class, and if the structure of you database changes in the period of time then you have to update lots of pages across your .net application. To escape from this situation you have to use an extra layer between your .net coding page and database, this layer can be a well-structured component or compiled DLL which contains database related information. This database scenario is just one of the reasons which let you to use your own component. To understand Component Programming, we would create a simple Data Access component for retrieving and inserting data into database in following section of this article.
Before building Data Access component you should follow these 2 guidlines –
1) Data Connention should be closed before ending of the current method. User should be unaware how the connection is opening and closing. It should be remembered that Connection is a finite resource, it may cost your site’s performance if using it few more seconds.
2) Try to use WHERE keyword in your queries to select only desired result, or use TOP to select only top few result instead of getting all table data. without these safeguards your website may work well in starting but will suffer as the time goes on.
Data Access Component –
using System; using System.Data; using System.Data.SqlClient; using System.Net.Mail; using System.Net; using System.Web.UI.WebControls; using System.Collections.Specialized; using System.Web.Security; using System.Web; /// <summary> /// provides all database connections for accessing data. /// </summary> public class Connections { private string ConStrng; private SqlCommand cmdOb = new SqlCommand(); private SqlConnection conOb; private SqlDataAdapter SevaAdapter; private DataSet ds; public string Query; public CommandType type = CommandType.Text; public Connections() { // get connection string from web.config file ConStrng = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConString"].ConnectionString; } public enum DataType { NVarchar, Varchar, Int, VarBinary, Bit, DateTime, Float, UniqueIdentifier } /// <summary> /// Executes SELECT commands and stored procedures, use to retrieve recordes in datatable /// </summary> /// <returns>Datatable</returns> public DataTable GetRecords() { conOb = new SqlConnection(ConStrng); cmdOb.Connection = conOb; cmdOb.CommandText = Query; cmdOb.CommandType = type; cmdOb.CommandTimeout = 560; SevaAdapter = new SqlDataAdapter(cmdOb); ds = new DataSet(); using (conOb) { conOb.Open(); SevaAdapter.Fill(ds, "tbl"); } conOb.Close(); return ds.Tables["tbl"]; } /// <summary> /// Executes INSERT,UPDATE,DELETE commands and stored procedures /// </summary> /// <returns>No of affacted rows</returns> public int Update() { int i = 0; conOb = new SqlConnection(ConStrng); cmdOb.Connection = conOb; cmdOb.CommandText = Query; cmdOb.CommandType = type; try { using (conOb) { conOb.Open(); i = cmdOb.ExecuteNonQuery(); } } catch { i = 0; } return i; } /// <summary> /// this method can be used to define and initialize command parameters /// </summary> /// <param name="varName"></param> /// <param name="varValue"></param> /// <param name="dataType"></param> public void AddParameter(string varName, object varValue, DataType? dataType) { if (dataType.ToString() == "NVarchar") { cmdOb.Parameters.Add("@" + varName, SqlDbType.NVarChar); cmdOb.Parameters["@" + varName].Value = varValue; } else if (dataType.ToString() == "Varchar") { cmdOb.Parameters.Add("@" + varName, SqlDbType.VarChar); cmdOb.Parameters["@" + varName].Value = varValue; } else if (dataType.ToString() == "Bit") { cmdOb.Parameters.Add("@" + varName, SqlDbType.Bit); cmdOb.Parameters["@" + varName].Value = varValue; } else if (dataType.ToString() == "Int") { cmdOb.Parameters.Add("@" + varName, SqlDbType.BigInt); cmdOb.Parameters["@" + varName].Value = varValue; } else if (dataType.ToString() == "DateTime") { cmdOb.Parameters.Add("@" + varName, SqlDbType.DateTime); cmdOb.Parameters["@" + varName].Value = varValue; } else if (dataType.ToString() == "VarBinary") { cmdOb.Parameters.Add("@" + varName, SqlDbType.VarBinary); cmdOb.Parameters["@" + varName].Value = varValue; } else if (dataType.ToString() == "Float") { cmdOb.Parameters.Add("@" + varName, SqlDbType.Float); cmdOb.Parameters["@" + varName].Value = varValue; } else if (dataType.ToString() == "UniqueIdentifier") { cmdOb.Parameters.Add("@" + varName, SqlDbType.UniqueIdentifier); cmdOb.Parameters["@" + varName].Value = varValue; } } }
Above data access component uses 3 public methods – one for getting records into Data Table, second for inserting, updating and deleting records from tables and third for adding parameters to command object. These 3 methods are sufficiant to perform all database operations easily without error. Now use following example to use this component into your code –
//Initialize component class Connections con = new Connections(); // write your query con.Query = "your query"; // add parameter if any con.AddParameter("parameter", paraName, Connections.DataType.NVarchar); // get result in Data Table Object DataTable dt = con.GetRecords(); if (dt.Rows.Count != 0) { // write code here }
I am Samith Jhon a content writer and a Professional Blogger. Certified with JN0-632 Exam test questions which is very
popular these days and have a great scope in the field of IT Certification. I always like to take JN0-343 Exam test questions to pass the Exam. These kinds of Exam questions could secure your future as well as your job.