从数据库模型图自动生成代码





5.00/5 (4投票s)
这是一个RAD工具,可以根据数据库模型图自动生成ASP.NET和C#的CRUD操作代码。
引言
在本文中,我将讨论自动代码生成器的开发。该RAD工具可以根据数据库模型图自动生成软件代码。用户可以使用MS Visio绘制数据库模型图,并上传Visio文件(文件必须为.vdx扩展名;Visio图必须包含物理数据类型。请参阅示例输入文件),以生成指定表中CRUD操作所需的代码。生成的代码将以ASP.NET和C#编写,数据库将使用MS SQL Server。用户无需创建任何项目或解决方案,该工具还将根据模板在指定目录中创建完整的解决方案。该工具还将根据数据库中的数据模型自动生成表和存储过程。用户也可以通过该工具的用户界面指定数据库表,如果他们不想绘制图表。
背景
本文的受众应该对使用以下技术进行软件开发有所了解:
- ASP.NET/C#。
- MS SQL Server
使用代码
该工具的用户界面将是这样的
在此用户界面中,用户将上传在MS Visio中绘制的数据库模型图(文件必须为.vdx扩展名;Visio图必须包含物理数据类型)。请参阅示例输入文件。该工具将从文件中提取表信息,并将表名加载到下拉列表中。当从下拉列表中选择一个表时,列信息将显示在网格中。用户将能够从网格中添加/修改列信息。然后,用户将提供项目位置或项目的目录以及数据库信息。之后,用户将选择要生成的输出对象,例如:表、存储过程、类和用户界面。最后,用户将单击“生成”按钮,一切就绪。所有必要的数据库对象、代码和用户界面都将在一次单击中自动生成。
该项目使用几个类进行开发——Entity, Attribute, DBOperationManager, FileOperationManager, SQLOperation, FileOperationProvider
。类Entity
和Attribute
是项目中的DTO类。这些类用于在应用程序中传输数据。类Entity
的对象将包含有关输入中定义的实体的信息,而类Attribute
的对象将包含这些实体的属性信息。
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; } }
类DBOperationManager
和FileOperationManager
是项目中的业务逻辑层。DBOperationManager
类负责生成所有必要的数据库SQL命令,以便在数据库中创建数据库对象。另一方面,FileOperationManager
类负责生成所有必要的文件内容,以便写入项目位置。
DBOperationManager
类
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
类
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; } } }
类SQLOperation
和FileOperationProvider
是项目中的数据访问层。SQLOperation
负责将所有SQL命令执行到数据库中。该类将从DBOperationManager
类接收SQL命令,并通过建立与用户界面中指定的数据库的连接来执行这些命令。另一方面,FileOperationProvider
负责将内容写入文件。文件内容将由FileOperationManager
提供,目标文件的位置将从用户界面获取。
FileOperationProvider
类
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; } } }
用户界面的代码隐藏将仅创建业务逻辑层类的实例并相应地调用方法。用户界面的代码隐藏
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 } }
该项目使用了一些实用类,例如:ErrorManager,用于处理错误并将错误写入文本文件。所有实用类和完整的源代码都可以在项目源代码文件夹中找到。
结论
我们已经了解了如何开发一个简单的代码生成器,它可以根据数据库模型自动生成代码。这类工具可以减少重复性工作并最小化开发工作量。每个人都应该站出来开发这类工具来自动化软件开发过程。
历史
第一个版本