Click here to Skip to main content
15,881,803 members
Articles / Database Development / SQL Server
Article

Tier Generator 1.0

Rate me:
Please Sign up or sign in to vote.
4.89/5 (140 votes)
26 Jul 2008CPOL2 min read 253K   13.3K   297   113
A powerful tool for rapid application development.

Setup

Introduction

Tier Generator is a powerful tool for generating business and data layers in C#. It is a code generation tool that helps users to rapidly generate and deploy business and data layers for their applications. The idea behind this is to provide a utility (tool) to the developer that has the capabilities of quickly generating consistent and tested source code that will help to get projects started sooner and finished faster.

Tier Generator connects to a Microsoft SQL Server database server and generates business and data layers in C#. It also generates Stored Procedures for DML operations.

Business layer

Tier Generator generates code in two layers (business and data). It generates some classes for the each table in the database in the business layer. E.g., our database contains the table Employee. Tier Generator will generate the following files:

  • Employee
  • EmployeeKeys
  • EmployeeFactory

The Employee (business object) class contains the declaration of all instance fields along with properties. It also overrides the AddValidationRules method to associate the validation rules to the properties of the business object. It also contains an enum of all the fields.

C#
public class Employee: BusinessObjectBase
{
   #region InnerClass

   public enum EmployeeFields
   {
     EmployeeID, Name, Password, Email, TeamID,DepartmentID, IsAdmin    
   }
    
   #endregion

   #region Data Members

   int _employeeID;
   string _name;
   string _password;
   string _email;
   int _teamID;
   int _departmentID;
   bool _isAdmin;

   #endregion

   #region Properties

   public int  EmployeeID
   {
     get { return _employeeID; }
     set
     {
        if (_employeeID != value)
        {
           _employeeID = value;
           PropertyHasChanged("EmployeeID");
        }
     }
   }

   public string  Name
   {
     get { return _name; }
     set
     {
       if (_name != value)
       {
         _name = value;
         PropertyHasChanged("Name");
       }
     }
   }
    .
    .
    .
    
   #endregion

   #region Validation

   internal override void AddValidationRules()
   {
     ValidationRules.AddRules(new Validation.ValidateRuleNotNull("EmployeeID", 
                                                                 "EmployeeID"));
     ValidationRules.AddRules(new Validation.ValidateRuleNotNull("Name", 
                                                                 "Name"));
     ValidationRules.AddRules(new Validation.ValidateRuleStringMaxLength("Name", 
                                                                    "Name",50));
     ValidationRules.AddRules(new Validation.ValidateRuleStringMaxLength("Password", 
                                                                         "Password",50));
     ValidationRules.AddRules(new Validation.ValidateRuleStringMaxLength("Email", 
                                                                         "Email",100));
     ValidationRules.AddRules(new Validation.ValidateRuleNotNull("TeamID", 
                                                                 "TeamID"));
     ValidationRules.AddRules(new Validation.ValidateRuleNotNull("DepartmentID", 
                                                                 "DepartmentID"));
     ValidationRules.AddRules(new Validation.ValidateRuleNotNull("IsAdmin", 
                                                                 "IsAdmin"));
   }

   #endregion
}

The EmpolyeesKeys (business object keys) class contains the list of primary keys of the table.

C#
public class EmployeeKeys
{
    #region Data Members

    int _employeeID;

    #endregion

    #region Constructor

    public EmployeeKeys(int employeeID)
    {
      _employeeID = employeeID; 
    }

    #endregion

    #region Properties

    public int  EmployeeID
    {
      get { return _employeeID; }
    }

    #endregion

}

The EmployeeFactory (business factory) class contains the methods for the Insert, Delete, Update, and Select operations. It provides the following methods for the DML operations:

  • public bool Insert(Employee businessObject)
  • public bool Update(Employee businessObject)
  • public Employee GetByPrimaryKey(EmployeeKeys keys)
  • public List<Employee> GetAll()
  • public List<Employee> GetAllBy(Employee.EmployeeFields fieldName, object value)
  • public bool Delete(EmployeeKeys keys)
  • public bool Delete(Employee.EmployeeFields fieldName, object value)

The factory class performs the DML operations with the help of the data layer.

C#
public class EmployeeFactory
{
    #region data Members

    EmployeeSql _dataObject = null;

    #endregion

    #region Constructor

    public EmployeeFactory()
    {
      _dataObject = new EmployeeSql();
    }

    #endregion

    #region Public Methods

    public bool Insert(Employee businessObject)
    {
       if (!businessObject.IsValid)
       {
          throw new InvalidBusinessObjectException(
                           businessObject.BrokenRulesList.ToString());
       }

        return _dataObject.Insert(businessObject);

    }

    
    public bool Update(Employee businessObject)
    {
      if (!businessObject.IsValid)
      {
        throw new InvalidBusinessObjectException(
                         businessObject.BrokenRulesList.ToString());
      }
      
      return _dataObject.Update(businessObject);
    }

    public Employee GetByPrimaryKey(EmployeeKeys keys)
    {
       return _dataObject.SelectByPrimaryKey(keys); 
    }

     
    public List<Employee> GetAll()
    {
       return _dataObject.SelectAll(); 
    }

    public List<Employee> GetAllBy(Employee.EmployeeFields fieldName, 
                                         object value)
    {
      return _dataObject.SelectByField(fieldName.ToString(), value);  
    }

    public bool Delete(EmployeeKeys keys)
    {
       return _dataObject.Delete(keys); 
    }

    public bool Delete(Employee.EmployeeFields fieldName, object value)
    {
       return _dataObject.DeleteByField(fieldName.ToString(), value); 
    }

    #endregion

}

Data Layer

The data access file generated by the Tier Generator contains the methods for DML operations. It uses Stored Procedures for DML operations. The factory class methods call the data layer methods for insertion and deletion.

C#
class EmployeeSql : DataLayerBase 
{
  
   #region Public Methods

   /// <summary>
   /// insert new row in the table
   /// </summary>
   /// <param name="businessObject">business object</param>
   /// <returns>true of successfully insert</returns>
   public bool Insert(Employee businessObject)
   {
     SqlCommand    sqlCommand = new SqlCommand();
       sqlCommand.CommandText = "dbo.[sp_Employee_Insert]";
       sqlCommand.CommandType = CommandType.StoredProcedure;

     // Use base class' connection object
     sqlCommand.Connection = MainConnection;

     try
     {                
       sqlCommand.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 4, 
                                                  ParameterDirection.Output, 
                                                  false, 0, 0, "", 
                                                  DataRowVersion.Proposed, 
                                                  businessObject.EmployeeID));
       sqlCommand.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar, 
                                                  50, ParameterDirection.Input, 
                                                  false, 0, 0, "", 
                                                  DataRowVersion.Proposed, 
                                                  businessObject.Name));
       sqlCommand.Parameters.Add(new SqlParameter("@password", SqlDbType.NVarChar, 
                                                  50, ParameterDirection.Input, 
                                                  false, 0, 0, "", 
                                                  DataRowVersion.Proposed, 
                                                  businessObject.Password));
       sqlCommand.Parameters.Add(new SqlParameter("@Email", SqlDbType.NVarChar, 
                                                  100, ParameterDirection.Input, 
                                                  false, 0, 0, "", 
                                                  DataRowVersion.Proposed, 
                                                  businessObject.Email));
       sqlCommand.Parameters.Add(new SqlParameter("@TeamID", SqlDbType.Int, 
                                                  4, ParameterDirection.Input, 
                                                  false, 0, 0, "", 
                                                  DataRowVersion.Proposed, 
                                                  businessObject.TeamID));
       sqlCommand.Parameters.Add(new SqlParameter("@DepartmentID", SqlDbType.Int, 
                                                  4, ParameterDirection.Input, 
                                                  false, 0, 0, "", 
                                                  DataRowVersion.Proposed, 
                                                  businessObject.DepartmentID));
       sqlCommand.Parameters.Add(new SqlParameter("@IsAdmin", SqlDbType.Bit, 
                                                  1, ParameterDirection.Input, 
                                                  false, 0, 0, "", 
                                                  DataRowVersion.Proposed, 
                                                  businessObject.IsAdmin));
       MainConnection.Open();
       
       sqlCommand.ExecuteNonQuery();
       businessObject.EmployeeID = 
         (int)sqlCommand.Parameters["@EmployeeID"].Value;

       return true;
     }
     catch(Exception ex)
     {
       throw new Exception("Employee::Insert::Error occured.", ex);
     }
     finally
     {
       MainConnection.Close();
       sqlCommand.Dispose();
     }
  }

  #endregion
}

How to use

The code generated by the Tier Generator is easy to use. Open the generated project in Visual Studio 2005 and compile it. Run the Stored Procedures script in the the database which is generated by the Tier Generator. You can find the SQL script file in the generated folder.

Add a new Windows/web project in the existing project and add the DLL of the generated code to it. Add app.config for Windows applications and web.config for web applications. Get the connection string from the generated app.config file. You will get this file in the generated folder.

XML
<appSettings>
   <add key="Main.ConnectionString"
           value="Data Source=localhost;Initial Catalog=School;
                  User Id=sa;Password=sa" />
</appSettings>

Here is the code sample for inserting a new record:

C#
public void AddNewRecord()
{
    Employee emp = new Employee();
    emp.EmployeeID = 1;
    emp.FirstName = "Shakeel";
    emp.LastName = "Iqbal";
    .
    .
    .
    .
    
    EmployeeFactory empFact = new EmployeeFactory();
    empFact.Insert(emp);
}

The code sample for selecting all the records:

C#
public void SelectAll()
{
     EmployeeFactory empFact = new EmployeeFactory();
     List<Employee> list = empFact.GetAll();   
    
    dataGrid1.DataSource = list;
}

Future enhancements

I have some future enhancements planned for the Tier Generator, and I have plans to launch the next version of the Tier generator. In this version, I will improve my business and data layers, and I will also provide the following features:

  • Generate Windows application.
  • Generate Web application.
  • Generate Web Services.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer
Pakistan Pakistan
Passion and positive dedication is essential part of success. I believe on hardworking and sharing knowledge with others. I always try to be a better than I am and think positive for positive result.

My Blogs

My Linked-In Profile

Comments and Discussions

 
AnswerRe: Nice work and 2 questions? Pin
Shakeel Iqbal10-Oct-08 4:39
Shakeel Iqbal10-Oct-08 4:39 
GeneralShould ignore timestamp field Pin
mac Moraleja23-Sep-08 22:27
mac Moraleja23-Sep-08 22:27 
GeneralRe: Should ignore timestamp field Pin
Shakeel Iqbal24-Sep-08 0:13
Shakeel Iqbal24-Sep-08 0:13 
GeneralDatabase Case Sensitivity Issue Pin
DaveHerron8-Sep-08 8:01
DaveHerron8-Sep-08 8:01 
GeneralExcellent! Pin
sirhe8-Sep-08 4:18
sirhe8-Sep-08 4:18 
GeneralNice work ;-) Pin
Asif Qadri3-Sep-08 17:24
Asif Qadri3-Sep-08 17:24 
GeneralNice! Pin
Spiff Dog2-Sep-08 21:48
Spiff Dog2-Sep-08 21:48 
Generalyou got my 5 Pin
black_zero27-Aug-08 19:29
black_zero27-Aug-08 19:29 
just forget to tell you that you got my 5

When you stop learning you stop leading

GeneralRe: you got my 5 Pin
Shakeel Iqbal28-Aug-08 0:53
Shakeel Iqbal28-Aug-08 0:53 
GeneralVery nice tool , But Pin
black_zero27-Aug-08 19:28
black_zero27-Aug-08 19:28 
GeneralGreat Work n Congrats on winning prize Pin
Aftab Zaheer Satti26-Aug-08 19:58
Aftab Zaheer Satti26-Aug-08 19:58 
GeneralError when building the database tables Pin
mokles19-Aug-08 5:11
mokles19-Aug-08 5:11 
GeneralWhere Clause Error Pin
mtone15-Aug-08 4:23
mtone15-Aug-08 4:23 
GeneralRe: Where Clause Error Pin
Shakeel Iqbal15-Aug-08 19:06
Shakeel Iqbal15-Aug-08 19:06 
GeneralRe: Where Clause Error Pin
Kent K17-Jan-09 8:57
professionalKent K17-Jan-09 8:57 
Generalmodify Pin
zhaojicheng14-Aug-08 21:24
zhaojicheng14-Aug-08 21:24 
GeneralA very tiny correction Pin
CreF11-Aug-08 21:29
professionalCreF11-Aug-08 21:29 
GeneralRe: A very tiny correction Pin
Shakeel Iqbal11-Aug-08 21:33
Shakeel Iqbal11-Aug-08 21:33 
GeneralRe: A very tiny correction Pin
CreF11-Aug-08 21:40
professionalCreF11-Aug-08 21:40 
General2 select questions Pin
Member 313878511-Aug-08 10:26
Member 313878511-Aug-08 10:26 
GeneralRe: 2 select questions Pin
Shakeel Iqbal11-Aug-08 18:13
Shakeel Iqbal11-Aug-08 18:13 
GeneralWell done! Pin
Kanwal Shehzad10-Aug-08 21:32
professionalKanwal Shehzad10-Aug-08 21:32 
Generalbang bang.... Pin
gunsmoke3-Aug-08 22:19
gunsmoke3-Aug-08 22:19 
QuestionSchema bug [modified] Pin
mm-2k31-Jul-08 23:11
mm-2k31-Jul-08 23:11 
QuestionVery nice, but I have a request Pin
tvlep30-Jul-08 10:52
tvlep30-Jul-08 10:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.