Tuesday, July 7, 2009

A Handy Code to Get Your Project Connected to Any Database by ADO.NET


I found out in the course of ADO.NET application development that developers were not at ease generalising their database utility classes so that they can work with any database provided at the backend. Very useful when you are implementing SOA.


This utility uses the concepts of basic OOP such as Dynamic Method Dispatching (DMD), Operator Overloading, Inheritance, structs, enums etc., and also the concept of custom exceptions and collections.

Using the Code

Although understanding this code is a bit complex, using it is really simple (a matter of just two lines of code). I have tested this code on SQL Server, Access, Excel, Oracle, and some databases that can be connected via OLE DB.

The code consists of a governor class, DataAccess, which helps wrap up data access logic. The governor class uses DMD to dynamically call the appropriate method from the appropriate derived class. This class was made for use with ASP.NET, but is made fit for Windows applications by adding another constructor in DataAccess, like:

public DataAccess(string conStr, string providerName) {     connectionString = conStr;     provider = providerName; }

You may add more such specialised classes to the utility as I have added for SQL Server (SQLFactory). The specialised classes are far better performing than general classes (ProviderAgnosticFactory). Note that since I have used DMD, while adding specialised classes, you need to add the method to FactoryGoverner too. Another point worth noting is that in the case of ASP.NET, you need to use another constructor of the wrapper class DataAccess, in which you have to provide the configuration name that you have specified in the web.config for the connection string.

See full detail: http://www.codeproject.com/KB/database/SmartDBUtility.aspx