|
|
|
|
|
|
|
Total page views :
17118
|
|
Total downloads :
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
Introduction
Many developers hate one thing about software development, writing SQL Statements. SQL is a language on its own and it is ubiquitous in today's development environment. When there are changes made to the tables, we have to modify the affected SQL statements, be it in the application codes or in Stored Procedures.
Would it be good if we do not have to write or modify SQL statements, just modify some C# codes, compile and Voila, your application is good to go.
Can it be done?
Sure.
How?
We will be using Attributes that can be used on your objects to map the properties to a Database Table Column. And we will look into Reflection classes to help us to create a simple SELECT Statement Command dynamically, with parameters and values assigned to the parameters.
Attributes
During development, we may have used attributes in our codes, one of the most commonly used attributes is the WebMethod attributes to expose methods in a web service. And who can forget about DllImport when calling Windows API.
For this solution, we will need to create a custom attribute object. To do that, we have to create a class and inherit the Attribute class.
public class DAOAttribute:System.Attribute
{ public DAOAttribute():base() { } }
For this class, we need to declare 3 variables and exposed it through properties.
private string _DatabaseColumn;
private Type _ValueType;
private bool _PrimaryKey;
public string DatabaseColumn { get { return this._DatabaseColumn ; } set { _DatabaseColumn = value; } }
public Type ValueType { get { return this._ValueType ; } set { _ValueType = value } }
public bool PrimaryKey { get { return this._PrimaryKey ; } set { _PrimaryKey = value; } }
-
_DatabaseColumn, this variable stores the database Column name
-
_ValueType, this variable represents the Value Type
-
_PrimaryKey, indicates if the Database Column is a primary key
Next, we need to modify the Constructor to initialize the 3 variables
public DAOAttribute(string databaseColumn,Type valueType,bool primaryKey):base() { _DatabaseColumn = databaseColumn; _ValueType = valueType; _PrimaryKey = primaryKey;
}
And we are ready to get to the next level.
Implementing the Attribute
Below is the code for the object that I will be using for this example
public class Customer
{
private string _CustomerFirstName;
private string _CustomerLastName;
private string _CustomerIDNumber;
public Customer()
{
_CustomerFirstName = "";
_CustomerLastName = "";
_CustomerIDNumber= "";
}
public string CustomerFirstName
{
get
{
return _CustomerFirstName;
}
set
{
_CustomerFirstName = value;
}
}
public string CustomerLastName
{
get
{
return _CustomerLastName;
}
set
{
_CustomerLastName = value;
}
}
public string CustomerIDNumber
{
get
{
return _CustomerIDNumber;
}
set
{
_CustomerIDNumber = value;
}
}
}
Assume you have an existing customer object that you want to generate SQL statement from. All you need now is to add in the attributes to the Get function of each property. Why put it at the GET function? This is because we will be using Reflection to extract the value. We will come to the Reflection Part later.
Below are the codes, you noticed that I set the Primary Key to True for CustomerIDNumber. This means that I have determined that the Customer ID number in the database is the Primary Key. You can determine your own Primary Key(s) , it is advisable to follow the relevant Database Table that the object is representing. If there are no Primary Keys set for the Database Table, you can determine your own for this object.
public string CustomerFirstName
{
[DAO("FirstName", typeof(string), false)]
get
{
return _CustomerFirstName;
}
set
{
_CustomerFirstName = value;
}
}
public string CustomerLastName
{
[DAO("LastName", typeof(string), false)]
get
{
return _CustomerLastName;
}
set
{
_CustomerLastName = value;
}
}
public string CustomerIDNumber
{
[DAO("CustID", typeof(string), true)]
get
{
return _CustomerIDNumber;
}
set
{
_CustomerIDNumber = value;
}
}
Executing it with Reflection
To retrieve the attributes from the object, we have to go deeper into the .NET framework. We are going to use classes in the Reflection namespace to extract the attribute details from the Customer object. Below are the codes to create a generic DbCommand object with a Select Statement with Parameters in place.
private DbCommand CreateSelectCommand(object dataObject, DbProviderFactory factory, string TableName)
{
Type t = dataObject.GetType();
DAOAttribute dao;
DbCommand cmd = factory.CreateCommand();
DbParameter param;
StringCollection Fields = new StringCollection();
StringBuilder sbWhere = new StringBuilder(" WHERE ");
bool HasCondition = false; //Indicates that there is a WHERE Condition
foreach (System.Reflection.MethodInfo mi in t.GetMethods()) //Go thru each method of the object
{
foreach (Attribute att in Attribute.GetCustomAttributes(mi)) //Go thru the attributes for the method
{
if (typeof(DAOAttribute).IsAssignableFrom(att.GetType())) //Checks that the Attribute is of the right type
{
dao = (DAOAttribute)att;
Fields.Add(dao.FieldName); //Append the Fields
if (dao.PrimaryKey)
{
//Append the Conditions
if (HasCondition) sbWhere.Append(" AND ");
sbWhere.AppendFormat("{0} = @{0}", dao.FieldName);
param = factory.CreateParameter();
param.ParameterName = "@" + dao.FieldName;
if (cmd.Parameters.IndexOf(param.ParameterName) == 0)
{
param.DbType = (DbType)Enum.Parse(typeof(DbType), dao.ValueType.Name);
cmd.Parameters.Add(param);
param.Value = mi.Invoke(obj, null);
}
HasCondition = true; //Set the HasCondition flag to true
}
}
}
}
string[] arrField = new string[Fields.Count];
Fields.CopyTo(arrField, 0);
cmd.CommandText = "SELECT " + string.Join(",", arrField) + " FROM " + TableName + (HasCondition ? sbWhere.ToString() : " ");
return cmd;
}
Beyond Select Statements
This is a very practical example of using Attributes and Reflection. You may even create your own Insert Statement Commands with these codes. And also you may want to extend the DAOAttribute object to cater to your requirements.
Besides generating SQL statements, there are a lot of cool stuff that you can do with Attributes and Reflection, you can even create your own XML Attributes and Formatter for the classes you created!!!
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
Edmund H Smith
Edmund is a Tech Lead for .NET Development and he is currently based in Singapore. Edmund have been involved in .NET developement since 2002. He has vast exposure in the IT industry, involved in IT projects for Aviation, Finance,Logistics, Postal and Marketing companies. Some of the technolgy involved in the projects includes ASP.NET C#,VB6 and K2.NET .
|
|
|
|
|
|
|
|
|
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional
consulting company, our consultants are well-known experts in .NET and many of them
are MVPs, authors, and trainers. We specialize in Microsoft .NET development and
utilize Agile Development and Extreme Programming practices to provide fast pace
quick turnaround results. Our software development model is a mix of Agile Development,
traditional SDLC, and Waterfall models.
|
|
Click here to learn more about C# Consulting. |
|
|
|
|
|
|
|
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon.
Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees.
As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
|
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
|
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
|
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|