Click here to Skip to main content
14,302,993 members

Automatic Code Generation from Database Model Diagram

Rate this:
5.00 (3 votes)
Please Sign up or sign in to vote.
5.00 (3 votes)
21 Feb 2016CPOL
This is a RAD tool which can be used to generate codes for CRUD operation in ASP.NET and C# automatically based on Database Model Diagram.

Introduction

Here in this article, I will discuss on development of an automatic code generator. This RAD tool can be used to generate software codes automatically based on Database Model Diagram. Users can draw a Database Model Diagram using MS Visio and upload the visio file (file must be .vdx extension; the visio diagram must contain physical data types. Please see the example input file) to generate the necessary codes for the CRUD operation in the specified tables. The generated codes will be written in ASP.NET and C# and the database will be in MS SQL Server. Users dont need to create any project or solution, this tool will also create the full solution in the specified directory based on a template. This tool will automatically generate the tables and stored procedures based on the data model in the database as well. Users can also specify the database tables from the user interface of this tool if he/she does not want to draw the diagram.

Background

Audiences of this article should have knowledge on software development using

 - ASP.NET/C#.

- MS SQL Server

Using the code

User Interface of the tool will be like this:

User Interface of Automatic Code Generator

Here in this user interface, user will upload a Database Model Diagram drawn in MS Visio (file must be .vdx extension; the visio diagram must contain physical data types). Please see the example input file. This tool will take the table information from the file and load the table names in the dropdown list. When a table is selected from the dropdown, the column information is displayed in the grid. Users will be able to add/modify column information from the grid. Users will then provide the project location or the directory of the project and database information. After that users will select the output objects to be generated like- tables, stored procedures, classes and user interfaces. Finally, users will click on the Generate button, all done. All the necessary database objects, codes and user interfaces are generated automatically within a single click.

The project is developed using several classes – Entity, Attribute, DBOperationManager, FileOperationManager, SQLOperation, FileOperationProvider. The classes Entiry and Attribute are DTO classes in this project. These classes are used to transfer data throughout the application. The objects of class Entity will contain information about the entities defined in the input and the objects of class Attribute will contain information of the attributes of those entities. 

public class Attribute
   {
       public bool? PrimaryKey { get; set; }
       public string Name { get; set; }
       public string Type { get; set; }
       public int? Size { get; set; }

   }

public class Entity
   {
       public string Name { get; set; }
       public List<Attribute> Attributes { get; set; }
   }

The classes DBOperationManager and FileOperationManger are the Business Logic Layer of this project. The class DBOperationManager is responsible for generating all the necessary database SQL commands to create the database objects in the database. On the other hand, the class FileOperationManger is responsible for generating all the necessary file contents to write into the project location.

DBOperationManager class:

using AutomaticCodeGenerator.Class.DAL;
using System;
using System.Windows.Forms;

namespace AutomaticCodeGenerator.Class.BLL
{
    /// <summary>
    /// Automatic Code Generator
    /// Developed by: Abdullah Al-Muzahid
    /// </summary>
    /// 
    public class DBOperationManager:IDisposable
    {
        private SQLOperation provider;
        private DataGridView grdColumns;      
        private string table;

        public DBOperationManager(string connectionString, DataGridView grdColumns, string table)
        {
            this.provider = new SQLOperation(connectionString);
            this.grdColumns = grdColumns;          
            this.table = table;
        }

        public bool createTable(out string message)
        {
            message = string.Empty;

            try
            {

                string ts = "CREATE TABLE [dbo].[" + table + "]("
                + "[" + table + "ID] [int] IDENTITY(1,1) NOT NULL, "
                + "[" + table + "Name] [varchar](256) NOT NULL, ";

                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;
                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        if (dr.Cells[1].Value.ToString() == "int" || dr.Cells[1].Value.ToString() == "float" || dr.Cells[1].Value.ToString() == "DateTime" || dr.Cells[1].Value.ToString() == "ntext")
                        {
                            ts += "[" + dr.Cells[0].Value.ToString() + "] [" + dr.Cells[1].Value.ToString() + "], ";
                        }
                        else
                        {
                            ts += "[" + dr.Cells[0].Value.ToString() + "] [" + dr.Cells[1].Value.ToString() + "](" + dr.Cells[2].Value.ToString() + "), ";
                        }
                    }
                }

                ts += "[ActiveStatus] [char](1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, "
                    + "[InsertedBy] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, "
                    + "[InsertedOn] [datetime] NULL, "
                    + "[UpdatedBy] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, "
                    + "[UpdatedOn] [datetime] NULL, "
                    + "CONSTRAINT [PK_" + table + "] PRIMARY KEY CLUSTERED "
                    + "([" + table + "ID] ASC"
                    + ") WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]"
                    + ") ON [PRIMARY]";

                if (this.provider.executeQuery(ts))
                    return true;
                else
                    return false;
            }
            catch (Exception Ex)
            {
                ErrorManager errL = new ErrorManager();
                errL.WriteError("", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString());
                message  = "\n\n" + Ex.Message + "\n\n";
                return false;
            }
        }

        public bool createStoredProcedures(out string message)
        {
            message = string.Empty;

            try
            {
                int err = 0;

                string sp = ""
                    + "-- =============================================\n"
                    + "-- Author: Abdullah Al-Muzahid, Agradut IT       \n"
                    + "-- Generated On: " + DateTime.Now.ToString() + " \n"
                    + "-- Generated By: Automatic Code Generator (V 1.0.0.0)\n"
                    + "-- Description:    This procedure is automatically generated by Code Gnerator\n"
                    + "-- It is used to insert and update record in the " + table + "table\n"
                    + "-- =============================================\n"
                    + "CREATE PROCEDURE [dbo].[Proc_InsertUpdate_" + table + "]\n"
                    + "-- The parameters for the stored procedure\n"
                    + "(\n"
                    + "@ID int OUTPUT,\n"
                    + "@Name VARCHAR(256),\n";

                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;
                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        if (dr.Cells[1].Value.ToString() == "int" || dr.Cells[1].Value.ToString() == "float" || dr.Cells[1].Value.ToString() == "DateTime" || dr.Cells[1].Value.ToString() == "ntext")
                        {
                            sp += "@" + dr.Cells[0].Value.ToString() + " " + dr.Cells[1].Value.ToString() + "=null,\n ";
                        }
                        else
                        {
                            sp += "@" + dr.Cells[0].Value.ToString() + " " + dr.Cells[1].Value.ToString() + " (" + dr.Cells[2].Value.ToString() + ")=null, \n";
                        }
                    }
                }

                sp += "@ActiveStatus char(1)='A',\n"
                   + "@User varchar(50)=null\n"
                   + ")\n"
                   + "AS\n"
                   + "BEGIN\n"
                   + "SET NOCOUNT ON;\n"
                   + "IF NOT EXISTS (SELECT 1 FROM [dbo].[" + table + "] WHERE [" + table + "ID]=@ID)\n"
                   + "BEGIN\n"
                   + "INSERT INTO [dbo].[" + table + "]\n"
                   + "(\n"
                   + "[" + table + "Name],\n";
                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;
                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        sp += "[" + dr.Cells[0].Value.ToString() + "],\n";
                    }
                }
                sp += "[ActiveStatus], \n [InsertedBy], \n [InsertedOn] \n ) \n VALUES \n ( \n @Name, \n";
                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;
                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        sp += "@" + dr.Cells[0].Value.ToString() + ",\n";
                    }
                }
                sp += "@ActiveStatus, \n @User, \n GETDATE() \n )"
                    + "SET @ID = @@IDENTITY \n"
                    + "END \n ELSE \n BEGIN \n"
                    + "UPDATE  [dbo].[" + table + "] \n"
                    + "SET \n"
                    + "[" + table + "Name]=@Name,\n";
                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;
                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        sp += "[" + dr.Cells[0].Value.ToString() + "] = " + "@" + dr.Cells[0].Value.ToString() + ", \n";
                    }
                }
                sp += "[ActiveStatus]=@ActiveStatus, \n"
                    + "[UpdatedBy]=@User, \n"
                    + "[UpdatedOn]=GETDATE() \n"
                    + "WHERE [" + table + "ID] = @ID \n"
                    + "END \n"
                    + "END \n";

                if (!this.provider.executeQuery(sp))
                    err += 1;

                sp = ""
                     + "-- =============================================\n"
                    + "-- Author: Abdullah Al-Muzahid, Agradut IT        \n"
                    + "-- Generated On: " + DateTime.Now.ToString() + " \n"
                    + "-- Generated By: Automatic Code Generator (V 1.0.0.0)\n"
                    + "-- Description:    This procedure is automatically generated by Code Gnerator\n"
                    + "-- It is used to retrieve records from the " + table + "table\n"
                    + "-- =============================================\n"
                    + "CREATE PROCEDURE [dbo].[Proc_Retrieve_" + table + "]\n"
                    + "-- The parameters for the stored procedure\n"
                    + "(\n @ID INT=NULL \n ,@ActiveStatus char(1)=NULL \n ) \n"
                    + "AS \n BEGIN \n SET NOCOUNT ON; \n"
                    + "SELECT   [" + table + "ID] AS 'ID', [" + table + "Name] AS 'Name', \n";

                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;
                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        sp += "[" + dr.Cells[0].Value.ToString() + "],\n";
                    }
                }

                sp += "[ActiveStatus], \n [InsertedBy] \n, [InsertedOn] \n"
                    + "FROM [dbo].[" + table + "] \n"
                    + "WHERE [" + table + "ID]=ISNULL(@ID,[" + table + "ID]) \n"
                    + "AND [ActiveStatus]=ISNULL(@ActiveStatus,[ActiveStatus]) \n END ";

                if (!this.provider.executeQuery(sp))
                    err += 1;

                sp = ""
                     + "-- =============================================\n"
                    + "-- Author: Abdullah Al-Muzahid, Agradut IT       \n"
                    + "-- Generated On: " + DateTime.Now.ToString() + " \n"
                    + "-- Generated By: Automatic Code Generator (V 1.0.0.0)\n"
                    + "-- Description:    This procedure is automatically generated by Code Gnerator\n"
                    + "-- It is used to delete record from the " + table + "table\n"
                    + "-- =============================================\n"
                    + "CREATE PROCEDURE [dbo].[Proc_Delete_" + table + "]\n"
                     + "-- The parameters for the stored procedure\n"
                    + "(\n @ID INT \n) \n"
                    + "AS \n BEGIN \n "
                    + "DELETE [" + table + "] WHERE [" + table + "ID] = @ID; \n END";

                if (!this.provider.executeQuery(sp))
                    err += 1;

                if (err > 0)
                    return false;
                else
                    return true;
            }
            catch (Exception Ex)
            {
                ErrorManager errL = new ErrorManager();
                errL.WriteError("", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString());
                message = "\n\n" + Ex.Message + "\n\n";
                return false;
            }
        }

        public void Dispose()
        {
            provider = null;
            grdColumns = null;
            table = null;
        }
    }
}

FileOperationManager Class:

using AutomaticCodeGenerator.Class.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AutomaticCodeGenerator.Class.BLL
{
    /// <summary>
    /// Automatic Code Generator
    /// Developed by: Abdullah Al-Muzahid
    /// </summary>
    /// 
    public class FileOperationManager:IDisposable
    {
        private FileOperationProvider provider;
        private DataGridView grdColumns;
        private string project;
        private string table;
        private string namespaces;
        private string exceptionbody;

        public FileOperationManager(DataGridView grdColumns, string project, string table)
        {
            provider = new FileOperationProvider();
            this.grdColumns = grdColumns;
            this.project = project;
            this.table = table;
            this.namespaces = " using System; \n using System.Data; \n using System.Data.SqlClient; \n using System.Configuration; \n using System.Collections; \n using System.Collections.Generic; \n "
                          + "using System.Linq; \n using System.Web; \n using System.Web.Security; \n using System.Web.UI; \n "
                          + "using System.Web.UI.HtmlControls; \n using System.Web.UI.WebControls; \n using System.Web.UI.WebControls.WebParts; \n "
                          + "using System.Xml.Linq; \n \n \n";
            this.exceptionbody = "catch (Exception Ex) \n"
                            + "{  \n"
                            + "ErrorManager errL = new ErrorManager(); \n"
                            + "errL.WriteError(\"\", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString()); \n"
                            + "} \n";
        }

        public bool createProjectTemplate()
        {
            return provider.createProjectTemplate(this.project);
        }

        public List<Entity> extractERDDiagram(string path, out string message)
        {
            return provider.extractERDDiagram(path, out message);
        }

        public bool createPropertyClass(out string message)
        {
            message = string.Empty;

            try
            {
                string pc = namespaces
                        + "\n\n"
                        + "/************************************************************************************\n"
                        + "* Class : " + table + "\n"
                        + "* Author: Abdullah Al-Muzahid, Agradut IT        \n"
                        + "* Generated On: " + DateTime.Now.ToString() + " \n"
                        + "* Generated By: Agradut Code Generator (V 1.0.0.0)\n"
                        + "* Description:    This calss is automatically generated by Code Gnerator\n"
                        + "* It is used to define the properties of " + table + "object\n"
                        + "* **********************************************************************************/\n"
                        + "\n\n\n"
                        + "public class " + table + ":CommonEntity \n{\n";

                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;

                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        if (dr.Cells[1].Value.ToString() == "varchar" || dr.Cells[1].Value.ToString() == "nvarchar" || dr.Cells[1].Value.ToString() == "ntext")
                        {
                            pc += "private string " + dr.Cells[0].Value.ToString().ToLower() + ";\n ";
                        }
                        else
                        {
                            pc += "private " + dr.Cells[1].Value.ToString() + " " + dr.Cells[0].Value.ToString().ToLower() + "; \n";
                        }
                    }
                }

                pc += "\n\n\n";
                pc += "public " + table + "() \n { \n";

                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;

                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        if (dr.Cells[1].Value.ToString() == "DateTime")
                        {
                            pc += dr.Cells[0].Value.ToString().ToLower() + " = " + " DateTime.Now;\n ";
                        }
                        else if (dr.Cells[1].Value.ToString() == "int" || dr.Cells[1].Value.ToString() == "float")
                        {
                            pc += dr.Cells[0].Value.ToString().ToLower() + " = " + " 0;\n ";
                        }
                        else
                        {
                            pc += dr.Cells[0].Value.ToString().ToLower() + " = " + " \"\"; \n ";
                        }
                    }
                }

                pc += "}\n\n\n"
                    + "public " + table + "("
                    + "int id, string name, ";

                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;

                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        if (dr.Cells[1].Value.ToString() == "varchar" || dr.Cells[1].Value.ToString() == "nvarchar" || dr.Cells[1].Value.ToString() == "ntext")
                        {
                            pc += " string " + dr.Cells[0].Value.ToString().ToLower() + " ,";
                        }
                        else
                        {
                            pc += " " + dr.Cells[1].Value.ToString() + " " + dr.Cells[0].Value.ToString().ToLower() + " ,";
                        }
                    }
                }

                pc += "char activestatus, string insertedBy, DateTime insertedOn";

                pc += ") \n { \n"
                    + "this.id = id; \n"
                    + "this.name = name; \n";

                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;
                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        pc += "this." + dr.Cells[0].Value.ToString().ToLower() + " = " + dr.Cells[0].Value.ToString().ToLower() + "; \n ";
                    }
                }

                pc += "this.activeStatus = activestatus; \n"
                    + "this.insertedBy = insertedBy; \n"
                    + "this.updatedBy = updatedBy; \n"
                    + "insertedOn = DateTime.Now; \n"
                    + "updatedOn = DateTime.Now; \n";
                pc += "} \n\n\n";
                pc += " #region Properties \n\n";

                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;
                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        if (dr.Cells[1].Value.ToString() == "varchar" || dr.Cells[1].Value.ToString() == "nvarchar" || dr.Cells[1].Value.ToString() == "ntext")
                        {
                            pc += "public string " + dr.Cells[0].Value.ToString() + "\n { \n"
                                + "get \n { \n return " + dr.Cells[0].Value.ToString().ToLower() + "; \n } \n"
                                + "set \n { \n " + dr.Cells[0].Value.ToString().ToLower() + " = value; \n } \n} \n";

                        }
                        else
                        {
                            pc += "public " + dr.Cells[1].Value.ToString() + " " + dr.Cells[0].Value.ToString() + "\n { \n"
                                + "get \n { \n return " + dr.Cells[0].Value.ToString().ToLower() + "; \n } \n"
                                + "set \n { \n " + dr.Cells[0].Value.ToString().ToLower() + " = value; \n } \n} \n";
                        }
                    }
                }

                pc += " \n\n #endregion \n \n }";

                this.provider.createFile(project + "\\App_Code\\BLL\\", table + ".cs", pc);

                return true;
            }
            catch (Exception Ex)
            {
                ErrorManager errL = new ErrorManager();
                errL.WriteError("", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString());
                message += "\n\n" + Ex.Message + "\n\n";
                return false;
            }
        }

        public bool createProviderClass(out string message)
        {
            message = string.Empty;
            try
            {
                string pc = namespaces
                        + "\n\n"
                        + "/************************************************************************************\n"
                        + "* Class : " + table + "Provider \n"
                        + "* Author: Abdullah Al-Muzahid, Agradut IT        \n"
                        + "* Generated On: " + DateTime.Now.ToString() + " \n"
                        + "* Generated By: Agradut Code Generator (V 1.0.0.0)\n"
                        + "* Description:    This calss is automatically generated by Code Gnerator\n"
                        + "* It is used to manupulate the data of " + table + " object\n"
                        + "* **********************************************************************************/\n"
                        + "\n\n\n"
                        + "public class " + table + "Provider : CommonEntityProvider \n{\n\n";

                pc += "\n\n\n";
                pc += "public " + table + "Provider() \n { \n \n";
                pc += "}\n\n\n";

                pc += " #region Methods \n\n";

                pc += "public int save(" + table + " o) \n { \n try \n { \n"
                    + "SqlCommand inscmd = new SqlCommand(\"[dbo].[Proc_InsertUpdate_" + table + "]\", DBCon.Connection);\n"
                    + "inscmd.CommandType = CommandType.StoredProcedure;\n"
                    + "inscmd.Parameters.Add(\"@ID\", SqlDbType.Int).Value = o.ID;\n"
                    + "inscmd.Parameters[\"@ID\"].Direction = ParameterDirection.InputOutput;\n"
                    + "inscmd.Parameters.Add(\"@Name\", SqlDbType.NVarChar, 256).Value = o.Name;\n";

                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;

                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        //if (dr.Cells[1].Value.ToString() == "varchar" || dr.Cells[1].Value.ToString() == "nvarchar" || dr.Cells[1].Value.ToString() == "char")
                        //{
                        //    pc += "inscmd.Parameters.Add(\"@" + dr.Cells[0].Value.ToString() + "\", SqlDbType." + dr.Cells[1].Value.ToString() + ", " + dr.Cells[2].Value.ToString() + ").Value = o." + dr.Cells[0].Value.ToString() + "; \n";

                        //}
                        //else
                        //{
                        //    pc += "inscmd.Parameters.Add(\"@" + dr.Cells[0].Value.ToString() + "\", SqlDbType." + dr.Cells[1].Value.ToString() + ").Value = o." + dr.Cells[0].Value.ToString() + "; \n";
                        //}
                        if (dr.Cells[1].Value.ToString() == "varchar")
                        {
                            pc += "inscmd.Parameters.Add(\"@" + dr.Cells[0].Value.ToString() + "\", SqlDbType.VarChar" + ", " + dr.Cells[2].Value.ToString() + ").Value = o." + dr.Cells[0].Value.ToString() + "; \n";

                        }
                        else if (dr.Cells[1].Value.ToString() == "nvarchar")
                        {
                            pc += "inscmd.Parameters.Add(\"@" + dr.Cells[0].Value.ToString() + "\", SqlDbType.NVarChar" + ", " + dr.Cells[2].Value.ToString() + ").Value = o." + dr.Cells[0].Value.ToString() + "; \n";

                        }
                        else if (dr.Cells[1].Value.ToString() == "ntext")
                        {
                            pc += "inscmd.Parameters.Add(\"@" + dr.Cells[0].Value.ToString() + "\", SqlDbType.NText" + ", " + dr.Cells[2].Value.ToString() + ").Value = o." + dr.Cells[0].Value.ToString() + "; \n";

                        }
                        else if (dr.Cells[1].Value.ToString() == "char")
                        {
                            pc += "inscmd.Parameters.Add(\"@" + dr.Cells[0].Value.ToString() + "\", SqlDbType.Char" + ", " + dr.Cells[2].Value.ToString() + ").Value = o." + dr.Cells[0].Value.ToString() + "; \n";

                        }
                        else if (dr.Cells[1].Value.ToString() == "int")
                        {
                            pc += "inscmd.Parameters.Add(\"@" + dr.Cells[0].Value.ToString() + "\", SqlDbType.Int" + ").Value = o." + dr.Cells[0].Value.ToString() + "; \n";

                        }
                        else if (dr.Cells[1].Value.ToString() == "float")
                        {
                            pc += "inscmd.Parameters.Add(\"@" + dr.Cells[0].Value.ToString() + "\", SqlDbType.Float" + ").Value = o." + dr.Cells[0].Value.ToString() + "; \n";

                        }
                        else
                        {
                            pc += "inscmd.Parameters.Add(\"@" + dr.Cells[0].Value.ToString() + "\", SqlDbType." + dr.Cells[1].Value.ToString() + ").Value = o." + dr.Cells[0].Value.ToString() + "; \n";
                        }
                    }
                }

                pc += "inscmd.Parameters.Add(\"@ActiveStatus\", SqlDbType.Char, 1).Value = o.ActiveStatus; \n"
                    + "inscmd.Parameters.Add(\"@User\", SqlDbType.VarChar, 50).Value = o.InsertedBy; \n"
                + "if (DBCon.Connection.State != ConnectionState.Open) \n"
                + "DBCon.Connection.Open(); \n"
                + "inscmd.ExecuteNonQuery(); \n"
                + "if (DBCon.Connection.State == ConnectionState.Open) \n"
                + "DBCon.Connection.Close(); \n"
                + "int id = (int)inscmd.Parameters[\"@ID\"].Value; \n"
                + "return id; \n"
                + "} \n"
                + "catch (SqlException sqlEx) \n"
                + "{ \n"
                + "ErrorManager errL = new ErrorManager(); \n"
                + "errL.WriteError(sqlEx.Number.ToString(), sqlEx.Message.ToString(), sqlEx.Source.ToString(), sqlEx.StackTrace.ToString()); \n"
                + "if (DBCon.Connection.State != ConnectionState.Closed) \n"
                + "{ \n"
                + "DBCon.Connection.Close(); \n"
                + "} \n"
                + "return 0; \n"
                + "} \n"
                + "catch (Exception Ex) \n"
                + "{ \n"
                + "ErrorManager errL = new ErrorManager(); \n"
                + "errL.WriteError(\"\", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString()); \n"
                + "if (DBCon.Connection.State != ConnectionState.Closed) \n"
                + "{ \n"
                + "DBCon.Connection.Close(); \n"
                + "} \n"
                + "return 0; \n"
                + "} \n";

                pc += "} \n\n #endregion \n \n }";

                this.provider.createFile(project + "\\App_Code\\DAL\\", table + "Provider.cs", pc);

                return true;
            }
            catch (Exception Ex)
            {
                ErrorManager errL = new ErrorManager();
                errL.WriteError("", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString());
                message = "\n\n" + Ex.Message + "\n\n";
                return false;
            }
        }

        public bool createManagerClass(out string message)
        {
            message = string.Empty;

            try
            {
                string pc = namespaces
                        + "\n\n"
                        + "/************************************************************************************\n"
                        + "* Class : " + table + "Manager \n"
                        + "* Author: Abdullah Al-Muzahid, Agradut IT        \n"
                        + "* Generated On: " + DateTime.Now.ToString() + " \n"
                        + "* Generated By: Agradut Code Generator (V 1.0.0.0)\n"
                        + "* Description:    This calss is automatically generated by Code Gnerator\n"
                        + "* It is used to manupulate the data of " + table + "object\n"
                        + "* **********************************************************************************/\n"
                        + "\n\n\n"
                        + "public class " + table + "Manager \n{\n\n";

                pc += "\n\n\n";
                pc += "public " + table + "Manager() \n { \n \n";
                pc += "}\n\n\n";

                pc += " #region Methods \n\n";

                pc += "public static int save(" + table + " o) \n { \n try \n { \n"
                    + table + "Provider np = new " + table + "Provider(); \n"
                    + "int id = np.save(o); \n"
                    + "return id; \n"
                    + "} \n"
                    + "catch (Exception ex) \n"
                    + "{ \n"
                    + "Utilities.LogError(ex); \n"
                    + "return 0; \n"
                    + "} \n } \n \n";

                pc += "public static " + table + " GetFromReader(IDataReader reader) \n"
                    + "{ \n"
                    + "try \n"
                    + "{ \n"
                    + table + " o = new " + table
                    + "\n( \n"
                    + "(int)reader[\"ID\"], \n"
                    + "reader[\"Name\"].ToString(), \n";

                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;
                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        if (dr.Cells[1].Value.ToString() == "varchar" || dr.Cells[1].Value.ToString() == "nvarchar" || dr.Cells[1].Value.ToString() == "ntext")
                        {
                            pc += "reader[\"" + dr.Cells[0].Value.ToString() + "\"].ToString(), \n";
                        }
                        else if (dr.Cells[1].Value.ToString() == "DateTime")
                        {
                            pc += "Convert.ToDateTime(" + "reader[\"" + dr.Cells[0].Value.ToString() + "\"].ToString()), \n";
                        }
                        else if (dr.Cells[1].Value.ToString() == "char")
                        {
                            pc += "Convert.ToChar(" + "reader[\"" + dr.Cells[0].Value.ToString() + "\"].ToString()), \n";
                        }
                        else if (dr.Cells[1].Value.ToString() == "float")
                        {
                            pc += "(float)Convert.ToDouble(" + "reader[\"" + dr.Cells[0].Value.ToString() + "\"].ToString()), \n";
                        }
                        else
                        {
                            pc += "(" + dr.Cells[1].Value.ToString() + ")" + "reader[\"" + dr.Cells[0].Value.ToString() + "\"], \n";
                        }
                    }
                }

                pc += "Convert.ToChar(reader[\"ActiveStatus\"].ToString()), \n"
                   + "reader[\"InsertedBy\"].ToString(), \n"
                   + "Convert.ToDateTime(reader[\"InsertedOn\"].ToString()) \n"
                   + "); \n"
                   + "return o; \n"
                   + "} \n"
                   + "catch (Exception ex) \n"
                   + "{ \n"
                   + "Utilities.LogError(ex); \n"
                   + "return null; \n"
                   + "} \n"
                   + "} \n";

                pc += "public static List<" + table + "> retrieve(string procName) \n"
                    + "{ \n"
                    + "try \n"
                    + "{ \n"
                    + "List<" + table + "> o = new List<" + table + ">(); \n"
                    + table + "Provider np = new " + table + "Provider(); \n"
                    + "IDataReader reader = np.retrieve(procName); \n"
                    + "while (reader.Read()) \n"
                    + "{ \n"
                    + "o.Add(GetFromReader(reader)); \n"
                    + "} \n"
                    + "reader.Close(); \n"
                    + "reader.Dispose(); \n"
                    + "return o; \n"
                    + "} \n"
                    + "catch (Exception ex) \n"
                    + "{ \n"
                    + "Utilities.LogError(ex); \n"
                    + "return null; \n"
                    + "} \n"
                    + "} \n";

                pc += "public static " + table + " retrieve(string procName, int id) \n"
                    + "{ \n"
                    + "try \n"
                    + "{ \n"
                    + table + " o = new " + table + "(); \n"
                    + table + "Provider np = new " + table + "Provider(); \n"
                    + "IDataReader reader = np.retrieve(procName, id, 'N'); \n"
                    + "while (reader.Read()) \n"
                    + "{ \n"
                    + "o = GetFromReader(reader); \n"
                    + "} \n"
                    + "reader.Close(); \n"
                    + "reader.Dispose(); \n"
                    + "return o; \n"
                    + "} \n"
                    + "catch (Exception ex) \n"
                    + "{ \n"
                    + "Utilities.LogError(ex); \n"
                    + "return null; \n"
                    + "} \n"
                    + "} \n";

                pc += "public static List<" + table + "> retrieve(string procName, int id, char status) \n"
                    + "{ \n"
                    + "try \n"
                    + "{ \n"
                    + "List<" + table + "> o = new List<" + table + ">(); \n"
                    + table + "Provider np = new " + table + "Provider(); \n"
                    + "IDataReader reader = np.retrieve(procName, id, status); \n"
                    + "while (reader.Read()) \n"
                    + "{ \n"
                    + "o.Add(GetFromReader(reader)); \n"
                    + "} \n"
                    + "reader.Close(); \n"
                    + "reader.Dispose(); \n"
                    + "return o; \n"
                    + "} \n"
                    + "catch (Exception ex) \n"
                    + "{ \n"
                    + "Utilities.LogError(ex); \n"
                    + "return null; \n"
                    + "} \n"
                    + "} \n";

                pc += " \n\n #endregion \n \n }";

                this.provider.createFile(project + "\\App_Code\\BLL\\Manager\\", table + "Manager.cs", pc);

                return true;
            }
            catch (Exception Ex)
            {
                ErrorManager errL = new ErrorManager();
                errL.WriteError("", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString());
                message += "\n\n" + Ex.Message + "\n\n";
                return false;
            }
        }

        public bool createAdminViewPage(out string message)
        {
            message = string.Empty;

            try
            {
                string pc = ""
                    + "<%@ Page Language=\"C#\" MasterPageFile=\"~/Admin/AdminMasterPage.master\" AutoEventWireup=\"true\""
                    + "CodeFile=\"AdminView" + table + ".aspx.cs\" Inherits=\"Admin_AdminView" + table + "\"  %>"
                    + "\n\n\n"
                    + "<asp:Content ID=\"Content2\" ContentPlaceHolderID=\"ContentPlaceHolder1\" runat=\"Server\"> \n"
                    + "<div> \n"
                    + "<asp:Button ID=\"btnAdd\" runat=\"server\" Text=\"Add New\" CssClass=\"save\" OnClick=\"btnAdd_Click\" /> \n <br/> \n"
                    + "</div> \n"
                    + "<div> \n"
                    + "<asp:GridView ID=\"GridView" + table + "\" runat=\"server\" OnRowCommand=\"GridView" + table + "_RowCommand\"\n"
                    + "DataKeyNames=\"ID\" AutoGenerateColumns=\"False\" AllowPaging=\"True\" Width=\"100%\"\n"
                    + "BackColor=\"White\" BorderColor=\"#CC9966\" BorderStyle=\"None\" BorderWidth=\"1px\"\n"
                    + "CellPadding=\"4\" GridLines=\"Horizontal\" onpageindexchanged=\"GridView" + table + "_PageIndexChanged\"\n"
                    + "onpageindexchanging=\"GridView" + table + "_PageIndexChanging\" PageSize=\"5\"> \n"
                    + "<RowStyle BackColor=\"White\" ForeColor=\"#330099\" HorizontalAlign=\"Center\" /> \n"
                    + "<Columns> \n"
                    + "<asp:ButtonField CommandName=\"change\" Text=\"Edit\" ButtonType=\"Button\"> \n"
                    + "<ItemStyle Width=\"70px\" BackColor=\"White\" /> \n"
                    + "</asp:ButtonField> \n"
                    + "<asp:BoundField DataField=\"ID\" HeaderText=\"ID\"> \n"
                    + "<ItemStyle Width=\"50px\" BackColor=\"White\" /> \n"
                    + "</asp:BoundField> \n"
                    + "<asp:TemplateField HeaderText=\"Title\"> \n"
                    + "<ItemTemplate> \n"
                    + "    <asp:Label ID=\"lbltitle\" runat=\"server\" Text='<%#Eval(\"Name\") %>'></asp:Label> \n"
                    + "</ItemTemplate> \n"
                    + "<ItemStyle Width=\"150px\" BackColor=\"White\"  /> \n"
                    + "</asp:TemplateField> \n"
                    + "<asp:ButtonField ButtonType=\"Button\" CommandName=\"vacant\" Text=\"Delete\"> \n"
                    + "<ItemStyle HorizontalAlign=\"Center\" Width=\"60px\" /> \n"
                    + "</asp:ButtonField> \n"
                    + "</Columns> \n"
                    + "<FooterStyle BackColor=\"#FFFFCC\" ForeColor=\"#330099\" /> \n"
                    + "<PagerStyle BackColor=\"#FFFFCC\" ForeColor=\"#330099\" HorizontalAlign=\"Center\" /> \n"
                    + "<EmptyDataTemplate> \n"
                    + "Sorry, No Results Found. \n"
                    + "</EmptyDataTemplate> \n"
                    + "<SelectedRowStyle BackColor=\"#FFCC66\" Font-Bold=\"True\" ForeColor=\"#663399\" /> \n"
                    + "<HeaderStyle BackColor=\"#990000\" Font-Bold=\"True\" ForeColor=\"#FFFFCC\" HorizontalAlign=\"Center\" Height=\"30px\" /> \n"
                    + "</asp:GridView> \n"
                    + "<i>You are viewing page </i> \n"
                    + "<%=GridView" + table + ".PageIndex + 1%> \n"
                    + "<i>of</i> \n"
                    + "<%=GridView" + table + ".PageCount%> \n"
                    + "<br /> \n"
                    + "<br /> \n"
                    + "</div> \n"
                    + "</asp:Content> \n";

                this.provider.createFile(project + "\\Admin\\", "AdminView" + table + ".aspx", pc);

                return true;

            }
            catch (Exception Ex)
            {
                ErrorManager errL = new ErrorManager();
                errL.WriteError("", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString());
                message += "\n\n" + Ex.Message + "\n\n";
                return false;
            }
        }

        public bool createAdminViewCodeBehindPage(out string message)
        {
            message = string.Empty;

            try
            {
                string pc = namespaces
                     + "\n\n"
                        + "/************************************************************************************\n"
                        + "* Code Behind Class : Admin_AdminView" + table + " \n"
                        + "* Author: Abdullah Al-Muzahid, Agradut IT        \n"
                        + "* Generated On: " + DateTime.Now.ToString() + " \n"
                        + "* Generated By: Agradut Code Generator (V 1.0.0.0)\n"
                        + "* Description:    This calss is automatically generated by Code Gnerator\n"
                        + "* It is used to view the data of " + table + " table by Admin \n"
                        + "* **********************************************************************************/\n"
                        + "\n\n\n"
                        + "public partial class Admin_AdminView" + table + " : System.Web.UI.Page"
                        + "{ \n"
                        + "protected void Page_Load(object sender, EventArgs e) \n"
                        + "{ \n"
                        + "if (!Page.IsPostBack) \n"
                        + "{ \n"
                        + "ViewDetails(); \n"
                        + "} \n"
                        + "} \n\n"
                        + "private void ViewDetails() \n"
                        + "{ \n"
                        + "try \n"
                        + "{ \n"
                        + "List<" + table + "> o = new List<" + table + ">(); \n"
                        + "o = " + table + "Manager.retrieve(\"[dbo].[Proc_Retrieve_" + table + "]\",0,'N'); \n"
                        + "GridView" + table + ".DataSource =  o; \n"
                        + "GridView" + table + ".DataBind();"
                        + "} \n"
                        + exceptionbody
                        + "} \n\n"
                        + "protected void GridView" + table + "_RowCommand(object sender, GridViewCommandEventArgs e)"
                        + "{ \n"
                        + "try \n"
                        + "{ \n"
                        + "int index = Convert.ToInt32(e.CommandArgument); \n"
                        + "GridViewRow gvRow =  GridView" + table + ".Rows[index]; \n"
                        + "if (e.CommandName == \"change\")"
                        + "{ \n"
                        + "Response.Redirect(\"AdminInsertUpdate" + table + ".aspx?ID=\" + Convert.ToInt32(gvRow.Cells[1].Text), false); \n"
                        + "} \n"
                        + "else if (e.CommandName == \"vacant\") \n"
                        + "{ \n"
                        + "CommonEntityManager.delete(Convert.ToInt32(gvRow.Cells[1].Text), \"[dbo].[Proc_Delete_" + table + "]\"); \n"
                        + "ViewDetails(); \n"
                        + "} \n"
                        + "} \n"
                        + exceptionbody
                        + "} \n"
                        + "// Add New \n"
                        + "protected void btnAdd_Click(object sender, EventArgs e) \n"
                        + "{ \n"
                        + "Response.Redirect(\"AdminInsertUpdate" + table + ".aspx\",false); \n"
                        + "} \n"
                        + "//Paging \n"
                        + "protected void GridView" + table + "_PageIndexChanging(object sender, GridViewPageEventArgs e) \n"
                        + "{ \n"
                        + "GridView" + table + ".PageIndex = e.NewPageIndex; \n"
                        + "} \n"
                        + "protected void GridView" + table + "_PageIndexChanged(object sender, EventArgs e) \n"
                        + "{ \n"
                        + "ViewDetails(); \n"
                        + "} \n"
                        + "///// \n"
                        + "} \n";

                this.provider.createFile(project + "\\Admin\\", "AdminView" + table + ".aspx.cs", pc);

                return true;
            }
            catch (Exception Ex)
            {
                ErrorManager errL = new ErrorManager();
                errL.WriteError("", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString());
                message = "\n\n" + Ex.Message + "\n\n";
                return false;
            }

        }

        public bool createAdminInsertUpdatePage(out string message)
        {
            message = string.Empty;

            try
            {
                string pc = ""
                    + "<%@ Page Language=\"C#\" MasterPageFile=\"~/Admin/AdminMasterPage.master\" AutoEventWireup=\"true\" \n"
                    + "CodeFile=\"AdminInsertUpdate" + table + ".aspx.cs\" Inherits=\"Admin_AdminInsertUpdate" + table + "\" %> \n\n\n"
                    + "<asp:Content ID=\"Content2\" ContentPlaceHolderID=\"ContentPlaceHolder1\" runat=\"Server\"> \n"
                    + "<div class=\"mainForm\"> \n"
                    + "<div> </div>\n"
                    + "<div class=\"labelBox\"> \n"
                    + "<asp:Label ID=\"lblTitle\" runat=\"server\" Text=\"Title : \"></asp:Label></div> \n"
                    + "<div style=\"width:90%; height:25px;\"> \n"
                    + "<asp:TextBox ID=\"txtTitle\" runat=\"server\" TabIndex=\"1\" CausesValidation=\"True\"></asp:TextBox></div> \n"
                    + "<div class=\"validation\"> \n"
                    + "<asp:RequiredFieldValidator ID=\"RequiredFieldValidatorTitle\" runat=\"server\" \n"
                    + "ControlToValidate=\"txtTitle\" ErrorMessage=\"Enter Title\">*</asp:RequiredFieldValidator> \n"
                    + "</div> \n"
                    + "<div class=\"clear\"></div> \n";

                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;
                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        //pc += "reader[\"" + dr.Cells[0].Value.ToString() + "\"].ToString(), \n";  
                        pc += "<div class=\"labelBox\"> \n"
                            + "<asp:Label ID=\"lbl" + dr.Cells[0].Value.ToString() + "\" runat=\"server\" Text=\"" + dr.Cells[0].Value.ToString() + " : \"></asp:Label></div> \n"
                            + "<div class=\"input\"> \n"
                            + "<asp:TextBox ID=\"txt" + dr.Cells[0].Value.ToString() + "\" runat=\"server\" CausesValidation=\"True\"></asp:TextBox> \n"
                            + "</div> \n"
                            + "<div class=\"validation\"> \n"
                            + "</div> \n"
                            + "<div class=\"clear\"></div> \n";
                    }
                }

                pc += "<div class=\"labelBox\"> \n"
                    + "</div> \n"
                    + "<div class=\"input\"> \n"
                    + "<asp:CheckBox ID=\"chkActive\" runat=\"server\" Text=\"Active\" /> \n"
                    + "</div> \n"
                    + "<div class=\"validation\"> \n"
                    + "</div> \n"
                    + "<div class=\"clear\"> \n"
                    + "</div> \n"
                    + "<div class=\"labelBox\"> \n"
                    + "</div> \n"
                    + "<div class=\"input\"> \n"
                    + "<asp:Button ID=\"btnSave\" runat=\"server\" Text=\"Save\" TabIndex=\"11\" OnClick=\"btnSave_Click\" /> \n"
                    //+ "<asp:Button ID=\"btnClear\" runat=\"server\" Text=\"Clear\" TabIndex=\"12\" CausesValidation=\"False\" OnClick=\"btnClear_Click\" /> \n"
                    + "<asp:Button ID=\"btnBack\" runat=\"server\" Text=\"<< Back\" CausesValidation=\"False\" OnClick=\"btnBack_Click\" /> \n"
                    + "</div> \n"
                    + "<div class=\"validation\"> \n"
                    + "</div> \n"
                    + "<div class=\"clear\"></div> \n"
                    + "<div class=\"labelBox\"> \n"
                    + "</div> \n"
                    + "<div class=\"input\"> \n"
                    + "<asp:Label ID=\"lblMessage\" runat=\"server\" ForeColor=\"red\"></asp:Label> \n"
                    + "<br /> \n"
                    + "<asp:ValidationSummary ID=\"ValidationSummary1\" runat=\"server\" /> \n"
                    + "</div> \n"
                    + "</div> \n"
                    + "</asp:Content> \n";

                this.provider.createFile(project + "\\Admin\\", "AdminInsertUpdate" + table + ".aspx", pc);

                return true;
            }
            catch (Exception Ex)
            {
                ErrorManager errL = new ErrorManager();
                errL.WriteError("", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString());
                message = "\n\n" + Ex.Message + "\n\n";
                return false;
            }
        }

        public bool createAdminInsertUpdateCodeBehind(out string message)
        {
            message = string.Empty;

            try
            {
                string pc = namespaces
                    + "\n\n"
                        + "/************************************************************************************\n"
                        + "* Code Behind Class : AdminInsertUpdate" + table + " \n"
                        + "* Author: Abdullah Al-Muzahid, Agradut IT        \n"
                        + "* Generated On: " + DateTime.Now.ToString() + " \n"
                        + "* Generated By: Agradut Code Generator (V 1.0.0.0)\n"
                        + "* Description:    This calss is automatically generated by Code Gnerator\n"
                        + "* It is used to insert update data into " + table + " table by Admin \n"
                        + "* **********************************************************************************/\n"
                        + "\n\n\n"
                        + "public partial class Admin_AdminInsertUpdate" + table + " : System.Web.UI.Page \n"
                        + "{ \n"
                        + "private int id; \n\n"
                        + "protected void Page_Load(object sender, EventArgs e) \n"
                        + "{ \n"
                        + "if(Request.QueryString[\"ID\"]!=null) \n"
                        + "{ \n"
                        + "id = Convert.ToInt32(Request.QueryString[\"ID\"]); \n"
                        + "} \n\n"
                        + "if (!Page.IsPostBack) \n"
                        + "{ \n"
                        + "if (id > 0) \n"
                        + "{ \n"
                        + "ShowDetails(); \n"
                        + "} \n"
                        + "} \n"
                        + "} \n\n\n"
                        + "protected void btnSave_Click(object sender, EventArgs e) \n"
                        + "{ \n"
                        + "try \n"
                        + "{ \n"
                        + table + " o = new " + table + " (); \n\n"
                        + "o.ID = id; \n"
                        + "o.Name = txtTitle.Text.Trim(); \n";

                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;
                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        if (dr.Cells[1].Value.ToString() == "varchar" || dr.Cells[1].Value.ToString() == "nvarchar" || dr.Cells[1].Value.ToString() == "ntext")
                        {
                            pc += "o." + dr.Cells[0].Value.ToString() + " = txt" + dr.Cells[0].Value.ToString() + ".Text.Trim(); \n";
                        }
                        else if (dr.Cells[1].Value.ToString() == "int")
                        {
                            pc += "o." + dr.Cells[0].Value.ToString() + " = Convert.ToInt32(txt" + dr.Cells[0].Value.ToString() + ".Text.Trim()); \n";
                        }
                        else if (dr.Cells[1].Value.ToString() == "DateTime")
                        {
                            pc += "o." + dr.Cells[0].Value.ToString() + " = Convert.ToDateTime(txt" + dr.Cells[0].Value.ToString() + ".Text.Trim()); \n";
                        }
                        else if (dr.Cells[1].Value.ToString() == "float")
                        {
                            pc += "o." + dr.Cells[0].Value.ToString() + " = (float)Convert.ToDouble(txt" + dr.Cells[0].Value.ToString() + ".Text.Trim()); \n";
                        }
                        else if (dr.Cells[1].Value.ToString() == "char")
                        {
                            pc += "o." + dr.Cells[0].Value.ToString() + " = Convert.ToChar(txt" + dr.Cells[0].Value.ToString() + ".Text.Trim()); \n";
                        }
                        else
                        {
                            pc += "o." + dr.Cells[0].Value.ToString() + " = txt" + dr.Cells[0].Value.ToString() + ".Text.Trim(); \n";
                        }

                    }
                }

                pc += "o.ActiveStatus = chkActive.Checked == true ? 'A' : 'I'; \n"
                    + "o.InsertedBy = User.Identity.Name; \n"
                    + "int inid = " + table + "Manager.save(o); \n"
                    + "if (inid > 0) \n"
                    + "{ \n"
                    + "Response.Redirect(\"AdminView" + table + ".aspx\", false); \n"
                    + "} \n"
                    + "else \n"
                    + "{ \n"
                    + "lblMessage.Text = \"An error occured during the operation! Please, refresh the page and try again.\"; \n"
                    + "} \n"
                    + "} \n"
                    + exceptionbody
                    + "\n} \n\n\n"
                    + "private void ShowDetails() \n"
                    + "{ \n"
                    + "try \n"
                    + "{ \n"
                    + table + " o = new " + table + "(); \n"
                    + "o = " + table + "Manager.retrieve(\"Proc_Retrieve_" + table + "\", id); \n"
                    + "if (o != null) \n"
                    + "{ \n"
                    + "id = o.ID; \n"
                    + "txtTitle.Text = o.Name; \n";

                foreach (DataGridViewRow dr in grdColumns.Rows)
                {
                    if (dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                    {
                        //Ignoring the attibutes which are defined as ID
                        string idCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (idCol.Equals("id") || idCol.Equals(table.Trim().ToLower() + "id"))
                            continue;
                        string nameCol = dr.Cells[0].Value.ToString().Trim().ToLower();
                        if (nameCol.Equals("name") || idCol.Equals(table.Trim().ToLower() + "name"))
                            continue;

                        pc += "txt" + dr.Cells[0].Value.ToString() + ".Text = o." + dr.Cells[0].Value.ToString() + ".ToString(); \n";
                    }
                }

                pc += "if (o.ActiveStatus == 'A') \n"
                    + "chkActive.Checked = true; \n"
                    + "else \n"
                    + "chkActive.Checked = false; \n"
                    + "} \n"
                    + "} \n"
                    + exceptionbody
                    + "\n}\n"
                    + "// Back to AdminView page \n"
                    + "protected void btnBack_Click(object sender, EventArgs e) \n"
                    + "{ \n"
                    + "Response.Redirect(\"AdminView" + table + ".aspx\",false); \n"
                    + "} \n"
                    + "} \n";

                this.provider.createFile(project + "\\Admin\\", "AdminInsertUpdate" + table + ".aspx.cs", pc);

                return true;
            }
            catch (Exception Ex)
            {
                ErrorManager errL = new ErrorManager();
                errL.WriteError("", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString());
                message = "\n\n" + Ex.Message + "\n\n";
                return false;
            }

        }

        public bool createViewPage(out string message)
        {
            message = string.Empty;

            try
            {
                string pc = "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" MasterPageFile=\"~/MainMasterPage.master\" \n"
                         + "CodeFile=\"View" + table + ".aspx.cs\" Inherits=\"View" + table + "\"%> \n"
                         + "<asp:Content ID=\"Content2\" ContentPlaceHolderID=\"ContentPlaceHolder1\" runat=\"Server\"> \n"
                         + "<asp:HiddenField ID=\"hdfID\" runat=\"server\" /> \n"
                         + "<asp:Repeater ID=\"rptrContent\" runat=\"server\"> \n"
                         + "<ItemTemplate> \n"
                         + "<div> \n"
                         + "<div> \n"
                         + "<%# Eval(\"Name\") %> \n </div> \n"
                         + "</div> \n"
                         + "<div> \n"
                         + "<div> \n"
                         + "<asp:Label ID=\"lblDescription\" Text='<%# Eval(\"Details\") %>' runat=\"server\"></asp:Label> \n"
                         + "</div> \n"
                         + "</div> \n"
                         + "</ItemTemplate> \n"
                         + "</asp:Repeater> \n"
                         + "<div class=\"clear\"> \n"
                         + "</div> \n"
                         + "</asp:Content> \n";

                this.provider.createFile(project, "\\View" + table + ".aspx", pc);

                return true;

            }
            catch (Exception Ex)
            {
                ErrorManager errL = new ErrorManager();
                errL.WriteError("", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString());
                message = "\n\n" + Ex.Message + "\n\n";
                return false;
            }
        }

        public bool createViewCodeBehindPage(out string message)
        {
            message = string.Empty;

            try
            {
                string pc = namespaces
                   + "\n\n"
                        + "/************************************************************************************\n"
                        + "* Code Behind Class : View" + table + " \n"
                        + "* Author: Abdullah Al-Muzahid, Agradut IT        \n"
                        + "* Generated On: " + DateTime.Now.ToString() + " \n"
                        + "* Generated By: Agradut Code Generator (V 1.0.0.0)\n"
                        + "* Description:    This calss is automatically generated by Code Gnerator\n"
                        + "* It is used to view the data of " + table + " table by user \n"
                        + "* **********************************************************************************/\n"
                        + "\n\n\n"
                        + "public partial class View" + table + " : System.Web.UI.Page"
                        + "{ \n\n"
                        + "protected void Page_Load(object sender, EventArgs e) \n"
                        + "{ \n"
                        + "ViewDetails();  \n"
                        + "} \n"
                        + "private void ViewDetails() \n"
                        + "{ \n"
                        + "try \n"
                        + "{ \n"
                        + "List<" + table + "> o = new List<" + table + ">(); \n"
                        + "o = " + table + "Manager.retrieve(\"[dbo].[Proc_Retrieve_" + table + "]\", 0, 'A'); \n"
                        + "rptrContent.DataSource = o; \n"
                        + "rptrContent.DataBind(); \n"
                        + "} \n"
                        + exceptionbody + "\n"
                        + "} \n"
                        + "} \n";

                this.provider.createFile(project, "\\View" + table + ".aspx.cs", pc);

                return true;

            }
            catch (Exception Ex)
            {
                ErrorManager errL = new ErrorManager();
                errL.WriteError("", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString());
                message += "\n\n" + Ex.Message + "\n\n";
                return false;
            }
        }

        public void Dispose()
        {
            project = null;
            namespaces = null;
            exceptionbody = null;
            provider = null;
            grdColumns = null;
            table = null;
        }

    }
}

The classes SQLOperation and FileOperationProvider are the Data Access Layer of this project. SQLOperation is responsible for executing all the SQL commands into the database. This class will receive SQL commands form the DBOperationManager class and execute those commands in the database by establishing a connection to the database specified in the user interface. On the other hand, FileOperationProvider is responsible for writing the contents of into files. The contents of the files will be provided by FileOperationManger and location of the destination files will be taken from user interface. 

FileOperationProvider class:

using MODI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Linq;

namespace AutomaticCodeGenerator.Class.DAL
{
    /// <summary>
    /// Automatic Code Generator
    /// Developed by: Abdullah Al-Muzahid
    /// </summary>
    /// 
    internal class FileOperationProvider
    {

        internal bool createFile(string filePath, string fileName, string content)
        {
          
            try
            {
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                using (StreamWriter w = File.AppendText(filePath + "\\" + fileName))
                {
                    w.Write(content);
                    w.Flush();
                    w.Close();
                }
              
            }
            catch (Exception Ex)
            {
                throw Ex;
            }

            return true;
        }

        internal bool createProjectTemplate(string projectPath)
        {
            try
            {
                //If the template does not exist
                if (!Directory.Exists(Path.Combine(projectPath, "App_Code")))
                {
                    string templatesPath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Templates");
                    string templateProject = Path.Combine(templatesPath, "ProjectTemplate.zip");

                    ///System.IO.Compression.ZipFile.CreateFromDirectory(startPath, zipPath);
                    System.IO.Compression.ZipFile.ExtractToDirectory(templateProject, projectPath);
                }
            }
            catch(Exception Ex)
            {
                throw Ex;
            }

            return true;

        }

        internal List<Entity> extractERDDiagram(string path, out string message)
        {
            message = string.Empty;
          

            if (string.IsNullOrEmpty(path))
            {
                message = "Must select a file";
                return null;
            }

            List<Entity> entities = new List<Entity>();

            string extension = Path.GetExtension(path);

            //Parsing From Image
            if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp")
            {
                Document modiDocument = new Document();
                modiDocument.Create(path);
                modiDocument.OCR(MiLANGUAGES.miLANG_ENGLISH);
                MODI.Image modiImage = (modiDocument.Images[0] as MODI.Image);
                string extractedText = modiImage.Layout.Text;
                modiDocument.Close();
                entities.Add(parseStringToEntity(extractedText));                
            }
            else if (extension == ".vdx")
            {             

                //MS VISIO XML Parsing 
                XDocument xdoc = XDocument.Load(path);
                var elements = xdoc.Elements().Elements();
                XName pageXName = XName.Get("Page", "http://schemas.microsoft.com/visio/2003/core");
                var pages = elements.Elements(pageXName);

                foreach (XElement page in pages)
                {
                    XName shapeXName = XName.Get("Shape", "http://schemas.microsoft.com/visio/2003/core");
                    var shapes = from shape in page.Elements().Elements(shapeXName)
                                 where shape.Attribute("Type").Value == "Group"
                                 select shape;

                    foreach (XElement shape in shapes)
                    {
                        try
                        {
                            Entity entity = new Entity();

                            var shapeShapes = shape.Elements();
                            List<XElement> textShapes = shapeShapes.Elements(shapeXName).ToList();

                            XName textXName = XName.Get("Text", "http://schemas.microsoft.com/visio/2003/core");
                            XName cpXName = XName.Get("Text", "http://schemas.microsoft.com/visio/2003/core");

                            string tableName = textShapes[0].Elements(textXName).SingleOrDefault().Value;
                            string columns = textShapes[1].Elements(textXName).SingleOrDefault().Value;

                            entity.Name = tableName.Replace("\n", "");
                            entity.Attributes = parseStringToAttributes(columns);
                            entities.Add(entity);
                        }
                        catch { }
                    }
                }
               
            }
            else
            {
                message = "File format invalid!";
                return null;
            }

            return entities;
        }

        private Entity parseStringToEntity(string text)
        {
            Entity entity = new Entity();

            string[] lineSeperators = { Environment.NewLine };
            string[] wordSeperator = { " " };

            string[] lines = text.Split(lineSeperators, StringSplitOptions.RemoveEmptyEntries);

            entity.Name = lines[0];

            for (int i = 1; i < lines.Count(); i++)
            {
                Attribute attr = new Attribute();

                string[] words = lines[i].Split(wordSeperator, StringSplitOptions.RemoveEmptyEntries);

                attr.Name = words[0];
                attr.Type = words[1].ToLower();

                if (words.Count() >= 3)
                {
                    attr.Size = Convert.ToInt32(words[2]);
                }

                entity.Attributes.Add(attr);
            }

            return entity;
        }

        private List<Attribute> parseStringToAttributes(string attriburesInText)
        {
            List<Attribute> attributes = new List<Attribute>();

            string[] lineSeperators = { Environment.NewLine, "\n" };
            string[] wordSeperator = { " ", "\t", "(", ")" };

            string[] lines = attriburesInText.Split(lineSeperators, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < lines.Count(); i++)
            {
                try
                {
                    int fromCount = 0;

                    Attribute attr = new Attribute();

                    string[] words = lines[i].Split(wordSeperator, StringSplitOptions.RemoveEmptyEntries);

                    if (words[0].ToUpper() == "PK")
                    {
                        fromCount = 1;
                        attr.PrimaryKey = true;
                    }
                    else 
                    {
                        attr.PrimaryKey = false;
                    }

                    if (words[0].ToUpper().Contains("FK"))
                    {
                        fromCount = 1;
                    }

                    attr.Name = words[fromCount];

                    if (words.Count() >= 2)
                    {
                        attr.Type = words[fromCount + 1].ToLower();
                    }

                    if (words.Count() >= 3)
                    {
                        attr.Size = Convert.ToInt32(words[fromCount + 2]);
                    }

                    attributes.Add(attr);
                }
                catch { }
            }

            return attributes;

        }

    }
}

The code behind of the user interface will just create instances of the Business Logic Layer classes and call the methods accordingly. The code behind of the user interface:

using AutomaticCodeGenerator.Class.BLL;
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace AutomaticCodeGenerator
{
    public partial class MainForm : Form
    {
        /// <summary>
        /// Automatic Code Generator
        /// Developed by: Abdullah Al-Muzahid
        /// </summary>
        /// 
        //private SqlConnection con;
        private string table;
        private string project;
        private string connectionString;
        private List<Entity> entities;
              
        public MainForm()
        {
            InitializeComponent();          
        }
               
        #region Methods
        private void extractERDDiagram(string path)
        {
            string message = string.Empty;

            if (string.IsNullOrEmpty(path))
            {
                MessageBox.Show("Must select an image file", "Select File", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            string extension = Path.GetExtension(path);

            //Parsing From Image
            if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp" || extension == ".vdx")
            {
                using (FileOperationManager fop = new FileOperationManager(grdColumns, project, table))
                {
                    entities = fop.extractERDDiagram(path, out message);
                    loadTableDropDownList();
                }
            }
            else
            {
                MessageBox.Show("File format invalid!", "Select File", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
        }

        private void loadTableDropDownList()
        {
            ddlTables.Items.Clear();

            foreach (Entity ent in entities)
            {
                ddlTables.Items.Add(ent.Name);
            }
            ddlTables.Text = "Select Table";
        }
        
        private bool valid(out string message)
        {
            message = string.Empty;

            bool valid = true;

            if (txtDatabaseServer.Text == "")
            {
                valid = false;
                message += "Enter Database Server Name! \n";
            }

            if (txtDatabaseName.Text == "")
            {
                valid = false;
                message += "Enter Database Name! \n";
            }

            if (txtDatabaseUser.Text == "")
            {
                valid = false;
                message += "Enter Database User! \n";
            }

            if (txtDatabasePassword.Text == "")
            {
                valid = false;
                message += "Enter Database Password! \n";
            }

            if (table == "")
            {
                valid = false;
                message += "Enter Table Name! \n";
            }

            if (project == "")
            {
                valid = false;
                message += "Enter Project Location! \n";
            }

            return valid;
        }
        #endregion

        #region Events
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {

            }
            catch (Exception Ex)
            {
                ErrorManager errL = new ErrorManager();
                errL.WriteError("", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString());
                txtLog.Text += "\n\n" + Ex.Message + "\n\n";
            }
        }

        private void cmdBrowse_Click(object sender, EventArgs e)
        {
            if (openFileDialogImage.ShowDialog() == DialogResult.OK)
            {
                txtFileName.Text = openFileDialogImage.FileName;
                extractERDDiagram(txtFileName.Text);
            }
        }

        private void cmdBrowseProjectLocation_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialogProjectLocation.ShowDialog() == DialogResult.OK)
            {
                txtProjectLocation.Text = folderBrowserDialogProjectLocation.SelectedPath;
            }
        }

        private void ddlTables_SelectedIndexChanged(object sender, EventArgs e)
        {
            grdColumns.Rows.Clear();

            var ent = from en in entities
                      where en.Name == ddlTables.Text
                      select en;

            foreach (Entity en in ent.ToList())
            {
                txtTableName.Text = en.Name.Trim();

                for (int i = 0; i < en.Attributes.Count; i++)
                {
                    try
                    {
                        grdColumns.Rows.Add();
                        grdColumns.Rows[i].Cells[0].Value = en.Attributes[i].Name;

                        if (!string.IsNullOrWhiteSpace(en.Attributes[i].Type) && en.Attributes[i].Type.Trim().ToUpper() == "INTEGER")
                            grdColumns.Rows[i].Cells[1].Value = "int";

                        else if (!string.IsNullOrWhiteSpace(en.Attributes[i].Type) && en.Attributes[i].Type.Trim().ToUpper() == "DATETIME")
                            grdColumns.Rows[i].Cells[1].Value = "DateTime";
                        else
                            grdColumns.Rows[i].Cells[1].Value = en.Attributes[i].Type;

                        if (en.Attributes[i].Size.HasValue)
                        {
                            grdColumns.Rows[i].Cells[2].Value = en.Attributes[i].Size.ToString();
                        }

                        if (en.Attributes[i].PrimaryKey.HasValue)
                        {
                            grdColumns.Rows[i].Cells[3].Value = en.Attributes[i].PrimaryKey.Value;
                        }
                    }
                    catch
                    {
                        txtLog.Text += "\n\n" + "Error Parsing Fields." + "\n\n";
                    }
                }
            }

        }

        private void cmdGenerate_Click(object sender, EventArgs e)
        {
            try
            {
                string message = string.Empty;

                if (!valid(out message))
                {
                    MessageBox.Show(message, "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    return;
                }

                table = txtTableName.Text.Trim();
                project = txtProjectLocation.Text.Trim();
                connectionString = string.Format("data source={0};database={1};Integrated Security=false;user id={2};password={3};", txtDatabaseServer.Text.Trim(), txtDatabaseName.Text.Trim(), txtDatabaseUser.Text.Trim(), txtDatabasePassword.Text.Trim());

                cmdGenerate.Enabled = false;
                cmdClear.Enabled = false;
                cmdExit.Enabled = false;

                //SqlConnection con = new SqlConnection("Persist Security Info=False;User ID=CGUser; Password=AITAgradut123; Initial Catalog=CodeGenerator;Data Source=AGRADUT3\\SQLEXPRESS");
                //SqlCommand cmd = new SqlCommand();
                //cmd.CommandType = CommandType.Text;
                //cmd.CommandText = "INSERT INTO [GenerateLog] VALUES ('" + frmLogin.userName + "', '" + Environment.MachineName + "', '" + DateTime.Now + "', '" + project + "', '" + txtConnectionString.Text.Trim() + "', '" + table + "')";
                //cmd.Connection = con;
                //con.Open();

                //int res = cmd.ExecuteNonQuery();

                //con.Close();

                if (1 == 1) //(res > 0)
                {

                    using (DBOperationManager dbop = new DBOperationManager(connectionString, grdColumns, table))
                    {
                        if (chkTable.Checked)
                        {
                            txtLog.Text += "\n\n" + "Creating Table ......" + "\n\n";
                            if (dbop.createTable(out message))
                                txtLog.Text += "\n\n" + "Table Created Successfully." + "\n\n";
                            else
                                txtLog.Text += "\n\n" + "Error Creating Table." + "\n\n" + message;
                        }

                        if (chkSp.Checked)
                        {
                            txtLog.Text += "\n\n" + "Creating Stored Procedures ......" + "\n\n";

                            if (dbop.createStoredProcedures(out message))
                                txtLog.Text += "\n\n" + "Stored Procedures Created Successfully." + "\n\n";
                            else
                                txtLog.Text += "\n\n" + "Error Creating Stored Procedures." + "\n\n" + message;
                        }
                    }

                    using (FileOperationManager fop = new FileOperationManager(grdColumns, project, table))
                    {
                        txtLog.Text += "\n\n" + "Creating Project Template ......" + "\n\n";
                        fop.createProjectTemplate();
                        txtLog.Text += "\n\n" + "Project Template Created Successfully ......" + "\n\n";

                        if (chkClasses.Checked)
                        {
                            txtLog.Text += "\n\n" + "Creating Property Class ......" + "\n\n";

                            if (fop.createPropertyClass(out message))
                                txtLog.Text += "\n\n" + "Property Class Created Successfully." + "\n\n";
                            else
                                txtLog.Text += "\n\n" + "Error Creating Property Class." + "\n\n" + message;

                            txtLog.Text += "\n\n" + "Creating Provider Class ......" + "\n\n";

                            if (fop.createProviderClass(out message))
                                txtLog.Text += "\n\n" + "Provider Class Created Successfully." + "\n\n";
                            else
                                txtLog.Text += "\n\n" + "Error Creating Provider Class." + "\n\n" + message;

                            txtLog.Text += "\n\n" + "Creating Manager Class ......" + "\n\n";
                            if (fop.createManagerClass(out message))
                                txtLog.Text += "\n\n" + "Manager Class Created Successfully." + "\n\n";
                            else
                                txtLog.Text += "\n\n" + "Error Creating Manager Class." + "\n\n" + message;
                        }

                        if (chkAdminPages.Checked)
                        {
                            txtLog.Text += "\n\n" + "Creating Admin View Page ......" + "\n\n";
                            if (fop.createAdminViewPage(out message))
                                txtLog.Text += "\n\n" + "Admin View Page Created Successfully." + "\n\n";
                            else
                                txtLog.Text += "\n\n" + "Error Creating Admin View Page." + "\n\n" + message;

                            txtLog.Text += "\n\n" + "Creating Admin View Code Behind Class ......" + "\n\n";
                            if (fop.createAdminViewCodeBehindPage(out message))
                                txtLog.Text += "\n\n" + "Admin View Code Behind Class Created Successfully." + "\n\n";
                            else
                                txtLog.Text += "\n\n" + "Error Creating Admin View Code Behind Class." + "\n\n" + message;

                            txtLog.Text += "\n\n" + "Creating Admin Insert Update Page ......" + "\n\n";
                            if (fop.createAdminInsertUpdatePage(out message))
                                txtLog.Text += "\n\n" + "Admin Insert Update Page Created Successfully." + "\n\n";
                            else
                                txtLog.Text += "\n\n" + "Error Creating Admin Insert Update Page." + "\n\n" + message;

                            txtLog.Text += "\n\n" + "Creating Admin Insert Update Code Behind Class ......" + "\n\n";
                            if (fop.createAdminInsertUpdateCodeBehind(out message))
                                txtLog.Text += "\n\n" + "Admin Insert Update Code Behind Class Created Successfully." + "\n\n";
                            else
                                txtLog.Text += "\n\n" + "Error Creating Admin Insert Update Code Behind Class." + "\n\n" + message;
                        }

                        if (chkVPages.Checked)
                        {
                            txtLog.Text += "\n\n" + "Creating View Page ......" + "\n\n";
                            if (fop.createViewPage(out message))
                                txtLog.Text += "\n\n" + "View Page Created Successfully." + "\n\n";
                            else
                                txtLog.Text += "\n\n" + "Error Creating View Page." + "\n\n" + message;

                            txtLog.Text += "\n\n" + "Creating View Page Code Behind Class ......" + "\n\n";
                            if (fop.createViewCodeBehindPage(out message))
                                txtLog.Text += "\n\n" + "View Page Code Behind Class Created Successfully." + "\n\n";
                            else
                                txtLog.Text += "\n\n" + "Error Creating View Page Code Behind Class." + "\n\n" + message;

                        }
                    }

                    MessageBox.Show("Process Completed. Please check the log for details.", "Process Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    cmdGenerate.Enabled = true;
                    cmdClear.Enabled = true;
                    cmdExit.Enabled = true;
                }
            }
            catch (Exception Ex)
            {
                ErrorManager errL = new ErrorManager();
                errL.WriteError("", Ex.Message.ToString(), Ex.Source.ToString(), Ex.StackTrace.ToString());
                txtLog.Text += "\n\n" + Ex.Message + "\n\n";
                //if (con.State != ConnectionState.Closed)
                //    con.Close();
            }
        }

        private void cmdClear_Click(object sender, EventArgs e)
        {
            txtLog.Text = "";
            txtTableName.Text = "";
            grdColumns.Rows.Clear();            
            table = string.Empty;
            project = string.Empty;
            connectionString = string.Empty;
            entities = new List<Entity>();
        }

        private void cmdExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        #endregion
    }
}

This project use some utility classes like: ErrorManager for handling errors and writting errors into text files. All the utility classes and the full source code is available in the project source folder.

Conclusion

We have learned how to develop a simple code generator which can automatically generate codes based on database model. This kind of tool can reduce repeatative work and minimize development effort. Everyone should come forward to develop such kind of tools to automate the process of software development.

History

First Version 

License

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

Share

About the Author

Abdullah Al-Muzahid
Software Developer (Senior) BRAC IT Services
Bangladesh Bangladesh
Application Developer, Database Designer, and Project Manager in a wide variety applications. Currently working at BRAC IT Services, Bangladesh as a Senior Software Engineer. Particularly interested in financial application development.

Comments and Discussions

 
QuestionBut.... Pin
super22-Feb-16 4:46
professionalsuper22-Feb-16 4:46 
QuestionMDriven Designer, MDriven Framework, ... Pin
Member 374629221-Feb-16 2:51
memberMember 374629221-Feb-16 2:51 
AnswerRe: MDriven Designer, MDriven Framework, ... Pin
Abdullah Al-Muzahid21-Feb-16 4:45
professionalAbdullah Al-Muzahid21-Feb-16 4:45 

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.

Article
Posted 21 Feb 2016

Stats

11.6K views
769 downloads
10 bookmarked