Click here to Skip to main content
Click here to Skip to main content

Tier Generator 1.0

By , 26 Jul 2008
 
Prize winner in Competition "Code Generation 2008 Competition" (First Prize level)

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.

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.

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.

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.

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.

  <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:

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:

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)

About the Author

Shakeel Iqbal
Software Developer (Senior) TEO
Pakistan Pakistan
Member
i have been working in software house as senior software engineer. i have worked on many web and windows projects. My hobbies are to read books and develop my own small utilities.
 

My Blogs
Follow me on Twitter

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionusing validation rulememberparviz8616 Dec '12 - 9:36 
hi this is very useful tool and tnx for it but i have two questions:
1.how can i use getbyprimarykey()
2.how is using validation rules and validation input ex:
we define a field should be digit how can we control valid or invalid input to this field
 
tnx to your greate work and for response
GeneralMy vote of 5memberxilione29 Nov '12 - 2:44 
Great Work!!!
QuestionNice work buddymembervmrosario17 Jul '12 - 21:43 
Thanks for your tool...We are all waiting for your enhancement....
QuestionGreat application! Everyone is waiting for new updates.memberxeno802 Jul '12 - 0:18 
Your application is really fantastic. Helped me a lot to deepen my knowledge. I read that you are very busy in other works, but it would be really nice if you write the DAL with the Entity Framework. Laugh | :laugh:
 
My vote is 5
QuestionFantastic! please return the proyectmembersquirerafa12 Mar '12 - 1:33 
The Future enhancements are great. Please return the proyect!
GeneralMy vote of 5membersquirerafa12 Mar '12 - 1:32 
clear oop tier generator! thanks
QuestionNicememberhendog988 Jan '12 - 19:08 
Nice Generator...Do you have any preliminary dates on when some of your stated enhancements might be included?
GeneralMy vote of 4memberPankaj Garg MCA24 Nov '10 - 0:45 
Good, keep it up.
GeneralMy vote of 5memberthatraja7 Oct '10 - 1:22 
Good Tool mate....Waiting for the future enhancements of this article
Generaldatagridgroupkolisa28 Jul '10 - 1:49 
how do you show things that on a datagrid to be show on the textboxes when you click the field
GeneralMy vote of 5memberKronass14 Jul '10 - 0:04 
Simple and do the work
GeneralTier Generator and MySQLmemberipadilla11 Jun '10 - 23:38 
Hi Nishantha,
I would like to check your version using with MySQL. Please, can you send me a copy? at:
 
ipadillar@telefonica.net.
Thank you
ipadilla
 

 

 

 

 

 

 

 

adult streming cms

 

 

 

 

 

 

 

 

 

 

 

 
adult streming cms

GeneralRe: Tier Generator and MySQLmembernishantha bandara2 Nov '10 - 23:52 
Sorry I was late to notice your message. Please contact me over nsbandara@gmail.com I'll send you details.
GeneralTierGeneratormembernishantha bandara2 Mar '10 - 18:37 
Hi Sakeel,
 
I have been using your code generation tool for some time and find it very useful for rapid application development. I did convert (did some minor changes ) and use it now even with mysql. What about your second version you planned.
 
I would like to join with you and enhance this with advance features such as transaction support.
 
Please mail me at nsbandara@gmail.com we can discuss.
 
Thanks,
Nishantha
GeneralAbandoned? [modified]memberipadilla2 Jan '10 - 0:29 
Definitily this project is abandoned?, what a pity...
ipadilla

modified on Saturday, June 12, 2010 10:18 AM

GeneralRe: Abandoned?memberShakeel Iqbal2 Jan '10 - 5:48 
Dear friend, it was my plan that i would write the second version of Tier Generator, but unfortunately i could not complete it in time. Although i had started work on it 6 month ago and i completed almost 30 percent of my second version. but i stopped it because of my some other commitments.
 
Sorry for delay dear Frown | :(
 
Shakeel Iqbal

GeneralRe: Abandoned?memberipadilla3 Jan '10 - 1:10 
Hi Shakeel Iqbal,
thank you very much for answering, I hope you can find time in the future.
ipadilla
GeneralHave you abandoned this projectmemberVenerableBede16 Dec '09 - 3:38 
Have you abandoned this project Shakeel?
GeneralRe: Have you abandoned this projectmemberShakeel Iqbal2 Jan '10 - 5:50 
Dear friend, it was my plan that i would write the second version of Tier Generator, but unfortunately i could not complete it in time. Although i had started work on it 6 month ago and i completed almost 30 percent of my second version. but i stopped it because of my some other commitments.
 
Sorry for delay dear Frown | :(
 
Shakeel Iqbal

GeneralRe: Have you abandoned this projectmembergravbox8 Jan '10 - 16:37 
I have looked at this and it is impressive. Many of these concepts are also implemented in the nHydrate generator as well.
 
http://nhydrate.codeplex.com/[^]
GeneralAdapted for SQL CompactmemberAtlas20024 Dec '09 - 4:34 
First I would like to say excellent job on the framework and tier generator. You have my vote of 5.
 
I have made some modifications to your template code and Tier Generator to support Tier generation for a SQL Compact database. The only major change I had to make was seperating connection management and generation of SQL statements. Instead of entering the database information in the config file I moved the connection object so that the sdf file could be provided by the user and managed similar to a connection pool. This was a minor change. Instead of using stored procedures which SSCE does not support I had to use embedded SQL with the SQLCEParameter support.
 
The final change was to support simulated views with entity generation. The tier generator now takes a SQL statement and analyzes the resulting dataset to generate a read only entity collection similar to a regular table. Support for select by field and select by key are still supported and generated based on the underlying tables.
GeneralImpressivememberVenerableBede25 Nov '09 - 2:28 
Nice job. Thanks for sharing.
 
Any idea when your new version will come out?
GeneralPlease Include BugList toomemberMember 159112717 Aug '09 - 1:14 
Yep as i have already mentioned its best solution over internet cloud, so please include known bugs
in your article. Wink | ;)
Suggest to post it on codeplex and let the people join you to help and enhance.
Smile | :)
GeneralGreat Solution but few bugs and enhancements requiredmemberMember 159112717 Aug '09 - 1:08 
Dear Shakeel,
I have to design i new lightwieght project, i was looking for a code generation solution which provides entity, collection and use of generics, from past few days i googled a lot to find out best one. i tried LLBGenPro, Codesmith and plenty other, though LLbGenpro and Codesmith are good enough but paid and providing few advance features like lazy loading, unit of work pattern(LLbGenpro only) to handle transactions, My application has to be any open source external lib independent as it belong to Banking app so cant use Nhibernate stuff too, finally came across your application which is "best suitable" Smile | :) for light weigted application and for big one too, so thanks a lot, I found one bug,
You are using SqlDatabSchema.cs to populate tables and vies through PopulateTables function, heres a bug, if tables or views are badly named like having spaces "View view ViEw" then application crashes as you have used string(0) reader.GetString(0) instead of column names which fails in this case, so please fix.
I found your business layer cosist of both entity and data access layer which you have merged in same solution.In a real n Tier application these are seperate layers like BLL,ENTITY,DAL let me know how could to modify generated code to build these layers and this is expected as enhancements.
One more point in real application a select statement is never made from a single table so could you provide feature to include columns from more than one tables to generate entity. (other orm does these
through deep loading which is nothing just load all realted tables in one go but why to load unnecessary columns if heavy transactions are not required)
 
Five from me as you have included ValidationSupport too You van Include Nullable Types and attributes support from Evil entity validation library(Codeplex) .
GeneralSQL 2005membermtone15 Jul '09 - 9:21 
I am getting an empty Where clause in the Stored procedures. I have primary keys but this is running against a SQL 2005 database, could that be an issue?
 
Is there something I can fix opposed to completeing the sql WHERE by hand on a bunch of tables.

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 26 Jul 2008
Article Copyright 2008 by Shakeel Iqbal
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid