While starting to code for any new application we are required to write POCO (Plain Old CLR Objects) classes for our database tables as Models (if you are using any ORM for data access) and we also need the stored procedures for our database tables. The process is simple but most of time repetitive and just like other developers I try to avoid it, so I wrote this simple windows forms application which helps me create database tables of POCO/model classes, base repository and related repository classes for the database tables in order to use Dapper ORM framework (which I mostly use in my web applications) and basic stored procedures scripts (like insert, update, delete etc) for the selected database tables. This saves time and helps me to avoid writing repetitive code.

This application is primarily targeting databases designed in SQL Server.

This is how the application looks:

string

Let's look into the code of the application and how it works. The flow of the application can be understood by the following diagram:

diagram

As you can see from the diagram, the first event occurs when the application is started and user clicks on ‘Get Database List’ button after entering the DB server connection string. The code of that event is as follows:

  1. private void btnGetDBList_Click(object sender, EventArgs e)
  2. {
  3. String conxString = txtConnectionString.Text.Trim();
  4. using (var sqlConx = new SqlConnection(conxString))
  5. {
  6. sqlConx.Open();
  7. var tblDatabases = sqlConx.GetSchema("Databases");
  8. sqlConx.Close();
  9. foreach (DataRow row in tblDatabases.Rows)
  10. {
  11. cboDatabases.Items.Add(row["database_name"]);
  12. }
  13. }
  14. cboDatabases.Items.Add("Select Database");
  15. cboDatabases.SelectedIndex = cboDatabases.Items.Count - 1;
  16. }
As per above source code the application is getting the list of databases using ‘GetSchema(“Databases”)’ method of ‘SqlConnection’ object and then adding each item of the list to ‘Select Database’ dropdown. As per application flow (above diagram) the next user action is to select the database from the ‘Select Database’ drop down.

On the selection of database from dropdown application will fire ‘cboDatabases_SelectedIndexChanged’ event to get the tables list from the database and show it in the application checkbox list like following Image.

database

The source code of the dropdown selected index change event is as follows:
  1. private void cboDatabases_SelectedIndexChanged(object sender, EventArgs e)
  2. {
  3. try
  4. {
  5. if (cboDatabases.Text.Trim() != "Select Database")
  6. {
  7. //if ((cboCustomerName.SelectedValue.ToString().Trim() != "System.Data.DataRowView"))
  8. mSSqlDatabase = cboDatabases.Text.Trim();
  9. string strConn = txtConnectionString.Text.Trim() + ";Initial Catalog=" + mSSqlDatabase;
  10. SqlConnection cbConnection = null;
  11. try
  12. {
  13. DataTable dtSchemaTable = new DataTable("Tables");
  14. using (cbConnection = new SqlConnection(strConn))
  15. {
  16. SqlCommand cmdCommand = cbConnection.CreateCommand();
  17. cmdCommand.CommandText = "select table_name as Name from INFORMATION_SCHEMA.Tables where TABLE_TYPE ='BASE TABLE'";
  18. cbConnection.Open();
  19. dtSchemaTable.Load(cmdCommand.ExecuteReader(CommandBehavior.CloseConnection));
  20. }
  21. cblTableList.Items.Clear();
  22. for (int iCount = 0; iCount < dtSchemaTable.Rows.Count; iCount++)
  23. {
  24. f
  25. cblTableList.Items.Add(dtSchemaTable.Rows[iCount][0].ToString());
  26. }
  27. }
  28. finally
  29. {
  30. // ReSharper disable once PossibleNullReferenceException
  31. cbConnection.Close();
  32. }
  33. }
  34. }
  35. catch (Exception ex)
  36. {
  37. MessageBox.Show("Error : " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
  38. }
The next action taken by user as per application flow is to either click on ‘Generate SQL’ / ‘Generate Classes’ / ‘Generate Both SQL & Classes’ button. Lets understand the code of ‘Generate SQL’ button click event handler first given as bellow:
  1. private void btnGenSQL_Click(object sender, EventArgs e)
  2. {
  3. try
  4. {
  5. GenerateSQLScripts();
  6. MessageBox.Show("SQL file(s) created Successfully at path mentioned in 'SQL Query Files'", "Success");
  7. grpOutPut.Visible = true;
  8. }
  9. catch (Exception ex)
  10. {
  11. MessageBox.Show("Error : " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  12. }
  13. }
The above written code use the following methods in order to generate SQL scripts of selected tables:
  1. private void GenerateSQLScripts()
  2. {
  3. string sFolderPath = CreateOutputDir(txtNamespace.Text.Trim() != "" ? txtNamespace.Text.Trim() : mSSqlDatabase);
  4. var objTableNames = new ArrayList();
  5. string sConString = txtConnectionString.Text + ";Initial Catalog=" + mSSqlDatabase;
  6. for (int iTableCount = 0; iTableCount < cblTableList.CheckedItems.Count; iTableCount++)
  7. {
  8. objTableNames.Add(cblTableList.CheckedItems[iTableCount].ToString());
  9. }
  10. txtQueryFilePath.Text = SqlScriptGenerator.GenerateSQLFiles(sFolderPath, sConString, txtgrantUser.Text.Trim(), txtSPPrefix.Text.Trim(), cbxMultipleFiles.Checked, objTableNames);
  11. }
  12. private string CreateOutputDir(string aSDirName)
  13. {
  14. string sRootDirPath = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + aSDirName;
  15. if (!Directory.Exists(sRootDirPath)) Directory.CreateDirectory(sRootDirPath);
  16. return sRootDirPath;
  17. }
‘GenerateSQLScripts’ method uses ‘CreateOutputDir’ method to first create the folder to store the SQL scripts and then loops through each selected table of the list and generate the SQL files using ‘GenerateSQLFiles’ method of ‘SqlScriptGenerator’ class.

The code of ‘GenerateSQLFiles’ method of ‘SqlScriptGenerator’ is as follows:
  1. public static string GenerateSQLFiles(string outputDirectory, string connectionString, string grantLoginName, string storedProcedurePrefix, bool createMultipleFiles, ArrayList tableNames)
  2. {
  3. string databaseName = "";
  4. string sqlPath;
  5. sqlPath = Path.Combine(outputDirectory, "SQL");
  6. List
  7. <Table> tableList = AppUtility.GetTableList(connectionString, outputDirectory, tableNames, ref databaseName);
  8. // Generate the necessary SQL for each table
  9. int count = 0;
  10. if (tableList.Count > 0)
  11. {
  12. // Create the necessary directories
  13. AppUtility.CreateSubDirectory(sqlPath, true);
  14. // Create the necessary database logins
  15. CreateUserQueries(databaseName, grantLoginName, sqlPath, createMultipleFiles);
  16. // Create the CRUD stored procedures and data access code for each table
  17. foreach (Table table in tableList)
  18. {
  19. CreateInsertStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
  20. CreateUpdateStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
  21. CreateDeleteStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
  22. CreateDeleteAllByStoredProcedures(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
  23. CreateSelectStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
  24. CreateSelectAllStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
  25. CreateSelectAllByStoredProcedures(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
  26. count++;
  27. }
  28. }
  29. return sqlPath;
  30. }
In above ‘GenerateSQLFiles’ method, the application is first getting the table list of the given database using ‘GetTableList’ and then generating the SQL script for CRUD operations of those tables by looping through each table. Apart from general Insert,Update,Delete stored procedures the application create Select stored procedures based on all Primary and Foreign keys using ‘CreateSelectAllByStoredProcedures’ method similarly it creates stored procedure to delete rows on the basis of all Primary and Foreign keys using ‘CreateDeleteAllByStoredProcedures’ method. The code of all these methods are as follows:
  1. internal static void CreateInsertStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles)
  2. {
  3. // Create the stored procedure name
  4. string procedureName = storedProcedurePrefix + table.Name + "Insert";
  5. string fileName;
  6. // Determine the file name to be used
  7. if (createMultipleFiles)
  8. {
  9. fileName = Path.Combine(path, procedureName + ".sql");
  10. }
  11. else
  12. {
  13. fileName = Path.Combine(path, "StoredProcedures.sql");
  14. }
  15. using (StreamWriter writer = new StreamWriter(fileName, true))
  16. {
  17. // Create the seperator
  18. if (createMultipleFiles == false)
  19. {
  20. writer.WriteLine();
  21. writer.WriteLine("/******************************************************************************");
  22. writer.WriteLine("******************************************************************************/");
  23. }
  24. // Create the drop statment
  25. writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
  26. writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]");
  27. writer.WriteLine("GO");
  28. writer.WriteLine();
  29. // Create the SQL for the stored procedure
  30. writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]");
  31. writer.WriteLine("(");
  32. // Create the parameter list
  33. for (int i = 0; i < table.Columns.Count; i++)
  34. {
  35. Column column = table.Columns[i];
  36. if (column.IsIdentity == false && column.IsRowGuidCol == false)
  37. {
  38. writer.Write("\t" + AppUtility.CreateParameterString(column, true));
  39. if (i < (table.Columns.Count - 1))
  40. {
  41. writer.Write(",");
  42. }
  43. writer.WriteLine();
  44. }
  45. }
  46. writer.WriteLine(")");
  47. writer.WriteLine();
  48. writer.WriteLine("AS");
  49. writer.WriteLine();
  50. writer.WriteLine("SET NOCOUNT ON");
  51. writer.WriteLine();
  52. // Initialize all RowGuidCol columns
  53. foreach (Column column in table.Columns)
  54. {
  55. if (column.IsRowGuidCol)
  56. {
  57. writer.WriteLine("SET @" + column.Name + " = NEWID()");
  58. writer.WriteLine();
  59. break;
  60. }
  61. }
  62. writer.WriteLine("INSERT INTO [" + table.Name + "]");
  63. writer.WriteLine("(");
  64. // Create the parameter list
  65. for (int i = 0; i < table.Columns.Count; i++)
  66. {
  67. Column column = table.Columns[i];
  68. // Ignore any identity columns
  69. if (column.IsIdentity == false)
  70. {
  71. // Append the column name as a parameter of the insert statement
  72. if (i < (table.Columns.Count - 1))
  73. {
  74. writer.WriteLine("\t[" + column.Name + "],");
  75. }
  76. else
  77. {
  78. writer.WriteLine("\t[" + column.Name + "]");
  79. }
  80. }
  81. }
  82. writer.WriteLine(")");
  83. writer.WriteLine("VALUES");
  84. writer.WriteLine("(");
  85. // Create the values list
  86. for (int i = 0; i < table.Columns.Count; i++)
  87. {
  88. Column column = table.Columns[i];
  89. // Is the current column an identity column?
  90. if (column.IsIdentity == false)
  91. {
  92. // Append the necessary line breaks and commas
  93. if (i < (table.Columns.Count - 1)) { writer.WriteLine("\t@" + column.Name + ","); } else { writer.WriteLine("\t@" + column.Name); } } } writer.WriteLine(")"); // Should we include a line for returning the identity? foreach (Column column in table.Columns) { // Is the current column an identity column? if (column.IsIdentity) { writer.WriteLine(); writer.WriteLine("SELECT SCOPE_IDENTITY()"); break; } if (column.IsRowGuidCol) { writer.WriteLine(); writer.WriteLine("SELECT @" + column.Name); break; } } writer.WriteLine("GO"); // Create the grant statement, if a user was specified if (grantLoginName.Length > 0)
  94. {
  95. writer.WriteLine();
  96. writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]");
  97. writer.WriteLine("GO");
  98. }
  99. }
  100. }
  101. ///
  102. <summary>
  103. /// Creates an update stored procedure SQL script for the specified table
  104. /// </summary>
  105. /// <param name="table">Instance of the Table class that represents the table this stored procedure will be created for.</param>
  106. /// <param name="grantLoginName">Name of the SQL Server user that should have execute rights on the stored procedure.</param>
  107. /// <param name="storedProcedurePrefix">Prefix to be appended to the name of the stored procedure.</param>
  108. /// <param name="path">Path where the stored procedure script should be created.</param>
  109. /// <param name="createMultipleFiles">Indicates the procedure(s) generated should be created in its own file.</param>
  110. internal static void CreateUpdateStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles)
  111. {
  112. if (table.PrimaryKeys.Count > 0 && table.Columns.Count != table.PrimaryKeys.Count && table.Columns.Count != table.ForeignKeys.Count)
  113. {
  114. // Create the stored procedure name
  115. string procedureName = storedProcedurePrefix + table.Name + "Update";
  116. string fileName;
  117. // Determine the file name to be used
  118. if (createMultipleFiles)
  119. {
  120. fileName = Path.Combine(path, procedureName + ".sql");
  121. }
  122. else
  123. {
  124. fileName = Path.Combine(path, "StoredProcedures.sql");
  125. }
  126. using (StreamWriter writer = new StreamWriter(fileName, true))
  127. {
  128. // Create the seperator
  129. if (createMultipleFiles == false)
  130. {
  131. writer.WriteLine();
  132. writer.WriteLine("/******************************************************************************");
  133. writer.WriteLine("******************************************************************************/");
  134. }
  135. // Create the drop statment
  136. writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
  137. writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]");
  138. writer.WriteLine("GO");
  139. writer.WriteLine();
  140. // Create the SQL for the stored procedure
  141. writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]");
  142. writer.WriteLine("(");
  143. // Create the parameter list
  144. for (int i = 0; i < table.Columns.Count; i++)
  145. {
  146. Column column = table.Columns[i];
  147. if (i == 0)
  148. {
  149. }
  150. if (i < (table.Columns.Count - 1))
  151. {
  152. writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ",");
  153. }
  154. else
  155. {
  156. writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false));
  157. }
  158. }
  159. writer.WriteLine(")");
  160. writer.WriteLine();
  161. writer.WriteLine("AS");
  162. writer.WriteLine();
  163. writer.WriteLine("SET NOCOUNT ON");
  164. writer.WriteLine();
  165. writer.WriteLine("UPDATE [" + table.Name + "]");
  166. writer.Write("SET");
  167. // Create the set statement
  168. bool firstLine = true;
  169. for (int i = 0; i < table.Columns.Count; i++)
  170. {
  171. var column = table.Columns[i];
  172. // Ignore Identity and RowGuidCol columns
  173. if (table.PrimaryKeys.Contains(column) == false)
  174. {
  175. if (firstLine)
  176. {
  177. writer.Write(" ");
  178. firstLine = false;
  179. }
  180. else
  181. {
  182. writer.Write("\t");
  183. }
  184. writer.Write("[" + column.Name + "] = @" + column.Name);
  185. if (i < (table.Columns.Count - 1))
  186. {
  187. writer.Write(",");
  188. }
  189. writer.WriteLine();
  190. }
  191. }
  192. writer.Write("WHERE");
  193. // Create the where clause
  194. for (int i = 0; i < table.PrimaryKeys.Count; i++) { Column column = table.PrimaryKeys[i]; if (i == 0) { writer.Write(" [" + column.Name + "] = @" + column.Name); } else { writer.Write("\tAND [" + column.Name + "] = @" + column.Name); } } writer.WriteLine(); writer.WriteLine("GO"); // Create the grant statement, if a user was specified if (grantLoginName.Length > 0)
  195. {
  196. writer.WriteLine();
  197. writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]");
  198. writer.WriteLine("GO");
  199. }
  200. }
  201. }
  202. }
  203. ///
  204. <summary>
  205. /// Creates an delete stored procedure SQL script for the specified table
  206. /// </summary>
  207. /// <param name="table">Instance of the Table class that represents the table this stored procedure will be created for.</param>
  208. /// <param name="grantLoginName">Name of the SQL Server user that should have execute rights on the stored procedure.</param>
  209. /// <param name="storedProcedurePrefix">Prefix to be appended to the name of the stored procedure.</param>
  210. /// <param name="path">Path where the stored procedure script should be created.</param>
  211. /// <param name="createMultipleFiles">Indicates the procedure(s) generated should be created in its own file.</param>
  212. internal static void CreateDeleteStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles)
  213. {
  214. if (table.PrimaryKeys.Count > 0)
  215. {
  216. // Create the stored procedure name
  217. string procedureName = storedProcedurePrefix + table.Name + "Delete";
  218. string fileName;
  219. // Determine the file name to be used
  220. if (createMultipleFiles)
  221. {
  222. fileName = Path.Combine(path, procedureName + ".sql");
  223. }
  224. else
  225. {
  226. fileName = Path.Combine(path, "StoredProcedures.sql");
  227. }
  228. using (StreamWriter writer = new StreamWriter(fileName, true))
  229. {
  230. // Create the seperator
  231. if (createMultipleFiles == false)
  232. {
  233. writer.WriteLine();
  234. writer.WriteLine("/******************************************************************************");
  235. writer.WriteLine("******************************************************************************/");
  236. }
  237. // Create the drop statment
  238. writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
  239. writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]");
  240. writer.WriteLine("GO");
  241. writer.WriteLine();
  242. // Create the SQL for the stored procedure
  243. writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]");
  244. writer.WriteLine("(");
  245. // Create the parameter list
  246. for (int i = 0; i < table.PrimaryKeys.Count; i++)
  247. {
  248. Column column = table.PrimaryKeys[i];
  249. if (i < (table.PrimaryKeys.Count - 1))
  250. {
  251. writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ",");
  252. }
  253. else
  254. {
  255. writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false));
  256. }
  257. }
  258. writer.WriteLine(")");
  259. writer.WriteLine();
  260. writer.WriteLine("AS");
  261. writer.WriteLine();
  262. writer.WriteLine("SET NOCOUNT ON");
  263. writer.WriteLine();
  264. writer.WriteLine("DELETE FROM [" + table.Name + "]");
  265. writer.Write("WHERE");
  266. // Create the where clause
  267. for (int i = 0; i < table.PrimaryKeys.Count; i++) { Column column = table.PrimaryKeys[i]; if (i == 0) { writer.WriteLine(" [" + column.Name + "] = @" + column.Name); } else { writer.WriteLine("\tAND [" + column.Name + "] = @" + column.Name); } } writer.WriteLine("GO"); // Create the grant statement, if a user was specified if (grantLoginName.Length > 0)
  268. {
  269. writer.WriteLine();
  270. writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]");
  271. writer.WriteLine("GO");
  272. }
  273. }
  274. }
  275. }
  276. ///
  277. <summary>
  278. /// Creates one or more delete stored procedures SQL script for the specified table and its foreign keys
  279. /// </summary>
  280. /// <param name="table">Instance of the Table class that represents the table this stored procedure will be created for.</param>
  281. /// <param name="grantLoginName">Name of the SQL Server user that should have execute rights on the stored procedure.</param>
  282. /// <param name="storedProcedurePrefix">Prefix to be appended to the name of the stored procedure.</param>
  283. /// <param name="path">Path where the stored procedure script should be created.</param>
  284. /// <param name="createMultipleFiles">Indicates the procedure(s) generated should be created in its own file.</param>
  285. internal static void CreateDeleteAllByStoredProcedures(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles)
  286. {
  287. // Create a stored procedure for each foreign key
  288. foreach (List<Column> compositeKeyList in table.ForeignKeys.Values)
  289. {
  290. // Create the stored procedure name
  291. StringBuilder stringBuilder = new StringBuilder(255);
  292. stringBuilder.Append(storedProcedurePrefix + table.Name + "DeleteAllBy");
  293. // Create the parameter list
  294. for (int i = 0; i < compositeKeyList.Count; i++) { Column column = compositeKeyList[i]; if (i > 0)
  295. {
  296. stringBuilder.Append("_" + AppUtility.FormatPascal(column.Name));
  297. }
  298. else
  299. {
  300. stringBuilder.Append(AppUtility.FormatPascal(column.Name));
  301. }
  302. }
  303. string procedureName = stringBuilder.ToString();
  304. string fileName;
  305. // Determine the file name to be used
  306. if (createMultipleFiles)
  307. {
  308. fileName = Path.Combine(path, procedureName + ".sql");
  309. }
  310. else
  311. {
  312. fileName = Path.Combine(path, "StoredProcedures.sql");
  313. }
  314. using (StreamWriter writer = new StreamWriter(fileName, true))
  315. {
  316. // Create the seperator
  317. if (createMultipleFiles == false)
  318. {
  319. writer.WriteLine();
  320. writer.WriteLine("/******************************************************************************");
  321. writer.WriteLine("******************************************************************************/");
  322. }
  323. // Create the drop statment
  324. writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
  325. writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]");
  326. writer.WriteLine("GO");
  327. writer.WriteLine();
  328. // Create the SQL for the stored procedure
  329. writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]");
  330. writer.WriteLine("(");
  331. // Create the parameter list
  332. for (int i = 0; i < compositeKeyList.Count; i++)
  333. {
  334. Column column = compositeKeyList[i];
  335. if (i < (compositeKeyList.Count - 1))
  336. {
  337. writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ",");
  338. }
  339. else
  340. {
  341. writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false));
  342. }
  343. }
  344. writer.WriteLine(")");
  345. writer.WriteLine();
  346. writer.WriteLine("AS");
  347. writer.WriteLine();
  348. writer.WriteLine("SET NOCOUNT ON");
  349. writer.WriteLine();
  350. writer.WriteLine("DELETE FROM [" + table.Name + "]");
  351. writer.Write("WHERE");
  352. // Create the where clause
  353. for (int i = 0; i < compositeKeyList.Count; i++) { Column column = compositeKeyList[i]; if (i == 0) { writer.WriteLine(" [" + column.Name + "] = @" + column.Name); } else { writer.WriteLine("\tAND [" + column.Name + "] = @" + column.Name); } } writer.WriteLine("GO"); // Create the grant statement, if a user was specified if (grantLoginName.Length > 0)
  354. {
  355. writer.WriteLine();
  356. writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]");
  357. writer.WriteLine("GO");
  358. }
  359. }
  360. }
  361. }
  362. ///
  363. <summary>
  364. /// Creates an select stored procedure SQL script for the specified table
  365. /// </summary>
  366. /// <param name="table">Instance of the Table class that represents the table this stored procedure will be created for.</param>
  367. /// <param name="grantLoginName">Name of the SQL Server user that should have execute rights on the stored procedure.</param>
  368. /// <param name="storedProcedurePrefix">Prefix to be appended to the name of the stored procedure.</param>
  369. /// <param name="path">Path where the stored procedure script should be created.</param>
  370. /// <param name="createMultipleFiles">Indicates the procedure(s) generated should be created in its own file.</param>
  371. internal static void CreateSelectStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles)
  372. {
  373. if (table.PrimaryKeys.Count > 0 && table.ForeignKeys.Count != table.Columns.Count)
  374. {
  375. // Create the stored procedure name
  376. string procedureName = storedProcedurePrefix + table.Name + "Select";
  377. string fileName;
  378. // Determine the file name to be used
  379. if (createMultipleFiles)
  380. {
  381. fileName = Path.Combine(path, procedureName + ".sql");
  382. }
  383. else
  384. {
  385. fileName = Path.Combine(path, "StoredProcedures.sql");
  386. }
  387. using (StreamWriter writer = new StreamWriter(fileName, true))
  388. {
  389. // Create the seperator
  390. if (createMultipleFiles == false)
  391. {
  392. writer.WriteLine();
  393. writer.WriteLine("/******************************************************************************");
  394. writer.WriteLine("******************************************************************************/");
  395. }
  396. // Create the drop statment
  397. writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
  398. writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]");
  399. writer.WriteLine("GO");
  400. writer.WriteLine();
  401. // Create the SQL for the stored procedure
  402. writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]");
  403. writer.WriteLine("(");
  404. // Create the parameter list
  405. for (int i = 0; i < table.PrimaryKeys.Count; i++)
  406. {
  407. Column column = table.PrimaryKeys[i];
  408. if (i == (table.PrimaryKeys.Count - 1))
  409. {
  410. writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false));
  411. }
  412. else
  413. {
  414. writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ",");
  415. }
  416. }
  417. writer.WriteLine(")");
  418. writer.WriteLine();
  419. writer.WriteLine("AS");
  420. writer.WriteLine();
  421. writer.WriteLine("SET NOCOUNT ON");
  422. writer.WriteLine();
  423. writer.Write("SELECT");
  424. // Create the list of columns
  425. for (int i = 0; i < table.Columns.Count; i++)
  426. {
  427. Column column = table.Columns[i];
  428. if (i == 0)
  429. {
  430. writer.Write(" ");
  431. }
  432. else
  433. {
  434. writer.Write("\t");
  435. }
  436. writer.Write("[" + column.Name + "]");
  437. if (i < (table.Columns.Count - 1))
  438. {
  439. writer.Write(",");
  440. }
  441. writer.WriteLine();
  442. }
  443. writer.WriteLine("FROM [" + table.Name + "]");
  444. writer.Write("WHERE");
  445. // Create the where clause
  446. for (int i = 0; i < table.PrimaryKeys.Count; i++) { Column column = table.PrimaryKeys[i]; if (i == 0) { writer.WriteLine(" [" + column.Name + "] = @" + column.Name); } else { writer.WriteLine("\tAND [" + column.Name + "] = @" + column.Name); } } writer.WriteLine("GO"); // Create the grant statement, if a user was specified if (grantLoginName.Length > 0)
  447. {
  448. writer.WriteLine();
  449. writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]");
  450. writer.WriteLine("GO");
  451. }
  452. }
  453. }
  454. }
  455. ///
  456. <summary>
  457. /// Creates an select all stored procedure SQL script for the specified table
  458. /// </summary>
  459. /// <param name="table">Instance of the Table class that represents the table this stored procedure will be created for.</param>
  460. /// <param name="grantLoginName">Name of the SQL Server user that should have execute rights on the stored procedure.</param>
  461. /// <param name="storedProcedurePrefix">Prefix to be appended to the name of the stored procedure.</param>
  462. /// <param name="path">Path where the stored procedure script should be created.</param>
  463. /// <param name="createMultipleFiles">Indicates the procedure(s) generated should be created in its own file.</param>
  464. internal static void CreateSelectAllStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles)
  465. {
  466. if (table.PrimaryKeys.Count > 0 && table.ForeignKeys.Count != table.Columns.Count)
  467. {
  468. // Create the stored procedure name
  469. string procedureName = storedProcedurePrefix + table.Name + "SelectAll";
  470. string fileName;
  471. // Determine the file name to be used
  472. if (createMultipleFiles)
  473. {
  474. fileName = Path.Combine(path, procedureName + ".sql");
  475. }
  476. else
  477. {
  478. fileName = Path.Combine(path, "StoredProcedures.sql");
  479. }
  480. using (StreamWriter writer = new StreamWriter(fileName, true))
  481. {
  482. // Create the seperator
  483. if (createMultipleFiles == false)
  484. {
  485. writer.WriteLine();
  486. writer.WriteLine("/******************************************************************************");
  487. writer.WriteLine("******************************************************************************/");
  488. }
  489. // Create the drop statment
  490. writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
  491. writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]");
  492. writer.WriteLine("GO");
  493. writer.WriteLine();
  494. // Create the SQL for the stored procedure
  495. writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]");
  496. writer.WriteLine();
  497. writer.WriteLine("AS");
  498. writer.WriteLine();
  499. writer.WriteLine("SET NOCOUNT ON");
  500. writer.WriteLine();
  501. writer.Write("SELECT");
  502. // Create the list of columns
  503. for (int i = 0; i < table.Columns.Count; i++)
  504. {
  505. Column column = table.Columns[i];
  506. if (i == 0)
  507. {
  508. writer.Write(" ");
  509. }
  510. else
  511. {
  512. writer.Write("\t");
  513. }
  514. writer.Write("[" + column.Name + "]");
  515. if (i < (table.Columns.Count - 1)) { writer.Write(","); } writer.WriteLine(); } writer.WriteLine("FROM [" + table.Name + "]"); writer.WriteLine("GO"); // Create the grant statement, if a user was specified if (grantLoginName.Length > 0)
  516. {
  517. writer.WriteLine();
  518. writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]");
  519. writer.WriteLine("GO");
  520. }
  521. }
  522. }
  523. }
  524. ///
  525. <summary>
  526. /// Creates one or more select stored procedures SQL script for the specified table and its foreign keys
  527. /// </summary>
  528. /// <param name="table">Instance of the Table class that represents the table this stored procedure will be created for.</param>
  529. /// <param name="grantLoginName">Name of the SQL Server user that should have execute rights on the stored procedure.</param>
  530. /// <param name="storedProcedurePrefix">Prefix to be appended to the name of the stored procedure.</param>
  531. /// <param name="path">Path where the stored procedure script should be created.</param>
  532. /// <param name="createMultipleFiles">Indicates the procedure(s) generated should be created in its own file.</param>
  533. internal static void CreateSelectAllByStoredProcedures(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles)
  534. {
  535. // Create a stored procedure for each foreign key
  536. foreach (List<Column> compositeKeyList in table.ForeignKeys.Values)
  537. {
  538. // Create the stored procedure name
  539. StringBuilder stringBuilder = new StringBuilder(255);
  540. stringBuilder.Append(storedProcedurePrefix + table.Name + "SelectAllBy");
  541. // Create the parameter list
  542. for (int i = 0; i < compositeKeyList.Count; i++) { Column column = compositeKeyList[i]; if (i > 0)
  543. {
  544. stringBuilder.Append("_" + AppUtility.FormatPascal(column.Name));
  545. }
  546. else
  547. {
  548. stringBuilder.Append(AppUtility.FormatPascal(column.Name));
  549. }
  550. }
  551. string procedureName = stringBuilder.ToString();
  552. string fileName;
  553. // Determine the file name to be used
  554. if (createMultipleFiles)
  555. {
  556. fileName = Path.Combine(path, procedureName + ".sql");
  557. }
  558. else
  559. {
  560. fileName = Path.Combine(path, "StoredProcedures.sql");
  561. }
  562. using (StreamWriter writer = new StreamWriter(fileName, true))
  563. {
  564. // Create the seperator
  565. if (createMultipleFiles == false)
  566. {
  567. writer.WriteLine();
  568. writer.WriteLine("/******************************************************************************");
  569. writer.WriteLine("******************************************************************************/");
  570. }
  571. // Create the drop statment
  572. writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
  573. writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]");
  574. writer.WriteLine("GO");
  575. writer.WriteLine();
  576. // Create the SQL for the stored procedure
  577. writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]");
  578. writer.WriteLine("(");
  579. // Create the parameter list
  580. for (int i = 0; i < compositeKeyList.Count; i++)
  581. {
  582. Column column = compositeKeyList[i];
  583. if (i < (compositeKeyList.Count - 1))
  584. {
  585. writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ",");
  586. }
  587. else
  588. {
  589. writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false));
  590. }
  591. }
  592. writer.WriteLine(")");
  593. writer.WriteLine();
  594. writer.WriteLine("AS");
  595. writer.WriteLine();
  596. writer.WriteLine("SET NOCOUNT ON");
  597. writer.WriteLine();
  598. writer.Write("SELECT");
  599. // Create the list of columns
  600. for (int i = 0; i < table.Columns.Count; i++)
  601. {
  602. Column column = table.Columns[i];
  603. if (i == 0)
  604. {
  605. writer.Write(" ");
  606. }
  607. else
  608. {
  609. writer.Write("\t");
  610. }
  611. writer.Write("[" + column.Name + "]");
  612. if (i < (table.Columns.Count - 1))
  613. {
  614. writer.Write(",");
  615. }
  616. writer.WriteLine();
  617. }
  618. writer.WriteLine("FROM [" + table.Name + "]");
  619. writer.Write("WHERE");
  620. // Create the where clause
  621. for (int i = 0; i < compositeKeyList.Count; i++) { Column column = compositeKeyList[i]; if (i == 0) { writer.WriteLine(" [" + column.Name + "] = @" + column.Name); } else { writer.WriteLine("\tAND [" + column.Name + "] = @" + column.Name); } } writer.WriteLine("GO"); // Create the grant statement, if a user was specified if (grantLoginName.Length > 0)
  622. {
  623. writer.WriteLine();
  624. writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]");
  625. writer.WriteLine("GO");
  626. }
  627. }
  628. }
  629. }
Now lets understand the code of ‘Generate Classes’ button click event handler given as below:
  1. private void btnGenClasses_Click(object sender, EventArgs e)
  2. {
  3. try
  4. {
  5. GenerateCSharpClasses();
  6. MessageBox.Show("Class file(s) created Successfully at path mentioned in 'Class Files Path'", "Success");
  7. grpOutPut.Visible = true;
  8. }
  9. catch (Exception ex)
  10. {
  11. MessageBox.Show("Error : " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  12. }
  13. }
The above written code uses following methods in order to generate C# POCO classes and Dapper Repo classes of selected tables:
  1. private void GenerateCSharpClasses()
  2. {
  3. string sFolderPath, sNameSpace;
  4. if (txtNamespace.Text.Trim() != "")
  5. {
  6. sFolderPath = CreateOutputDir(txtNamespace.Text.Trim());
  7. sNameSpace = txtNamespace.Text.Trim();
  8. }
  9. else
  10. {
  11. sFolderPath = CreateOutputDir(mSSqlDatabase);
  12. sNameSpace = mSSqlDatabase;
  13. }
  14. CreateBaseRepoClass(sFolderPath + "\\BaseRepository.cs", sNameSpace);
  15. var objTableNames = new ArrayList();
  16. string sConString = "";
  17. sConString = txtConnectionString.Text + ";Initial Catalog=" + mSSqlDatabase;
  18. for (int iTableCount = 0; iTableCount < cblTableList.CheckedItems.Count; iTableCount++)
  19. {
  20. objTableNames.Add(cblTableList.CheckedItems[iTableCount].ToString());
  21. }
  22. txtFilesPath.Text = CSharpCodeGenerator.GenerateClassFiles(sFolderPath, sConString, txtSPPrefix.Text.Trim(), sNameSpace, "", objTableNames);
  23. CSharpCodeGenerator.GenerateRepoFiles(sFolderPath, sConString, txtSPPrefix.Text.Trim(), sNameSpace, "", objTableNames);
  24. }
  25. private void CreateBaseRepoClass(string aSFilePath, string targetNamespace)
  26. {
  27. using (var streamWriter = new StreamWriter(aSFilePath))
  28. {
  29. #region Add Referances
  30. streamWriter.WriteLine("using System;");
  31. streamWriter.WriteLine("using System.Data;");
  32. streamWriter.WriteLine("using System.Data.SqlClient;");
  33. streamWriter.WriteLine("using System.Linq;");
  34. streamWriter.WriteLine("using System.Web.Configuration;");
  35. streamWriter.WriteLine();
  36. streamWriter.WriteLine("namespace " + targetNamespace);
  37. streamWriter.WriteLine("{");
  38. #endregion
  39. #region Create Base Repository Class
  40. streamWriter.WriteLine("\t public abstract class BaseRepository ");
  41. streamWriter.WriteLine("\t\t {");
  42. streamWriter.WriteLine(
  43. "\t\t\t protected static void SetIdentity<T>(IDbConnection connection, Action<T> setId) ");
  44. streamWriter.WriteLine("\t\t\t {");
  45. streamWriter.WriteLine(
  46. "\t\t\t dynamic identity = connection.Query(\"SELECT @@IDENTITY AS Id\").Single(); ");
  47. streamWriter.WriteLine("\t\t\t T newId = (T)identity.Id; ");
  48. streamWriter.WriteLine("\t\t\t setId(newId); ");
  49. streamWriter.WriteLine("\t\t\t }");
  50. streamWriter.WriteLine(
  51. "\t\t\t protected static IDbConnection OpenConnection() ");
  52. streamWriter.WriteLine("\t\t\t {");
  53. streamWriter.WriteLine(
  54. "\t\t\t IDbConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings[\"DBConString\"].ConnectionString); ");
  55. streamWriter.WriteLine("\t\t\t connection.Open(); ");
  56. streamWriter.WriteLine("\t\t\t return connection; ");
  57. streamWriter.WriteLine("\t\t\t }");
  58. streamWriter.WriteLine("\t\t }");
  59. #endregion
  60. }
  61. }
‘GenerateCSharpClasses’ method first creates the folder to save the output files using ” method, then it creates the BaseRepository class using ‘CreateBaseRepoClass’ method (this is used as base class for all the Dapper Repo Classes) and then it loops through each selected table of the list and generate the C# POCO class files using ‘GenerateClassFiles’ and Dapper Repo files using ‘GenerateRepoFiles’ method of ‘CSharpCodeGenerator’ class.
The code of ‘GenerateClassFiles’ method of ‘CSharpCodeGenerator’ is as follows:
  1. public static string GenerateClassFiles(string outputDirectory, string connectionString, string storedProcedurePrefix, string targetNamespace, string daoSuffix, ArrayList tableNames)
  2. {
  3. string databaseName = "";
  4. string csPath;
  5. csPath = Path.Combine(outputDirectory, "CS");
  6. List
  7. <Table> tableList = AppUtility.GetTableList(connectionString, outputDirectory, tableNames, ref databaseName);
  8. // Generate the necessary SQL and C# code for each table
  9. if (tableList.Count <= 0) return csPath;
  10. // Create the necessary directories
  11. AppUtility.CreateSubDirectory(csPath, true);
  12. foreach (Table table in tableList)
  13. {
  14. CreateModelClass(databaseName, table, targetNamespace, storedProcedurePrefix, csPath);
  15. }
  16. return csPath;
  17. }
In above ‘GenerateClassFiles’ method, the application is first getting the table list of the given database using ‘GetTableList’ method and then it generates the C# POCO class definition files of all the tables present in tables list by looping through each table and using ‘CreateModelClass’ method. The code of ‘CreateModelClass’ method is as follows:
  1. internal static void CreateModelClass(string databaseName, Table table, string targetNamespace, string storedProcedurePrefix, string path)
  2. {
  3. var className = AppUtility.FormatClassName(table.Name);
  4. using (var streamWriter = new StreamWriter(Path.Combine(path, className + ".cs")))
  5. {
  6. #region Create the header for the class
  7. streamWriter.WriteLine("using System;");
  8. streamWriter.WriteLine();
  9. streamWriter.WriteLine("namespace " + targetNamespace);
  10. streamWriter.WriteLine("{");
  11. streamWriter.WriteLine("\tpublic class " + className);
  12. streamWriter.WriteLine("\t{");
  13. #endregion
  14. #region Append the public properties
  15. streamWriter.WriteLine("\t\t#region Properties");
  16. for (var i = 0; i < table.Columns.Count; i++)
  17. {
  18. var column = table.Columns[i];
  19. var parameter = AppUtility.CreateMethodParameter(column);
  20. var type = parameter.Split(' ')[0];
  21. var name = parameter.Split(' ')[1];
  22. streamWriter.WriteLine("\t\t///
  23. <summary>");
  24. streamWriter.WriteLine("\t\t/// Gets or sets the " + AppUtility.FormatPascal(name) + " value.");
  25. streamWriter.WriteLine("\t\t/// </summary>
  26. ");
  27. streamWriter.WriteLine("\t\tpublic " + type + " " + AppUtility.FormatPascal(name));
  28. streamWriter.WriteLine("\t\t{ get; set; }");
  29. if (i < (table.Columns.Count - 1))
  30. {
  31. streamWriter.WriteLine();
  32. }
  33. }
  34. streamWriter.WriteLine();
  35. streamWriter.WriteLine("\t\t#endregion");
  36. #endregion
  37. // Close out the class and namespace
  38. streamWriter.WriteLine("\t}");
  39. streamWriter.WriteLine("}");
  40. }
  41. }
The code of ‘GenerateRepoFiles’ method of ‘CSharpCodeGenerator’ is as follows:
  1. public static string GenerateRepoFiles(string outputDirectory, string connectionString, string storedProcedurePrefix, string targetNamespace, string daoSuffix, ArrayList tableNames)
  2. {
  3. string databaseName = "";
  4. string csPath = Path.Combine(outputDirectory, "Repo");
  5. List
  6. <Table> tableList = AppUtility.GetTableList(connectionString, outputDirectory, tableNames, ref databaseName);
  7. // Generate the necessary SQL and C# code for each table
  8. if (tableList.Count <= 0) return csPath;
  9. // Create the necessary directories
  10. AppUtility.CreateSubDirectory(csPath, true);
  11. // Create the CRUD stored procedures and data access code for each table
  12. foreach (Table table in tableList)
  13. {
  14. CreateRepoClass(databaseName, table, targetNamespace, storedProcedurePrefix, csPath);
  15. }
  16. return csPath;
  17. }
In above ‘GenerateRepoFiles’ method, the application is first getting the tables list of the given database using ‘AppUtility.GetTableList’ method and then it loops through each table present in tables list to generate Dapper Repo files containing CRUD operation methods using ‘CreateRepoClass’ method. The code of ‘CreateRepoClass’ method is as follows:
  1. internal static void CreateRepoClass(string databaseName, Table table, string targetNamespace, string storedProcedurePrefix, string path)
  2. {
  3. var className = AppUtility.FormatClassName(table.Name);
  4. using (var streamWriter = new StreamWriter(Path.Combine(path, className + ".cs")))
  5. {
  6. #region Add References & Declare Class
  7. streamWriter.WriteLine("using System.Collections.Generic;");
  8. streamWriter.WriteLine("using System.Data;");
  9. streamWriter.WriteLine("using System.Linq;");
  10. streamWriter.WriteLine("using Dapper;");
  11. streamWriter.WriteLine();
  12. streamWriter.WriteLine("namespace " + targetNamespace);
  13. streamWriter.WriteLine("{");
  14. streamWriter.WriteLine("\t public class " + className + "Repo : BaseRepository");
  15. streamWriter.WriteLine("\t\t {");
  16. #endregion
  17. #region Append the access methods
  18. streamWriter.WriteLine("\t\t#region Methods");
  19. streamWriter.WriteLine();
  20. CreateInsertMethod(table, streamWriter);
  21. CreateUpdateMethod(table, streamWriter);
  22. CreateSelectMethod(table, streamWriter);
  23. CreateSelectAllMethod(table, streamWriter);
  24. CreateSelectAllByMethods(table, storedProcedurePrefix, streamWriter);
  25. #endregion
  26. streamWriter.WriteLine();
  27. streamWriter.WriteLine("\t\t#endregion");
  28. // Close out the class and namespace
  29. streamWriter.WriteLine("\t\t}");
  30. streamWriter.WriteLine("}");
  31. }
  32. }
In above ‘CreateRepoClass’ the application generates a class which is named as ‘Repo’ containing methods for Insert,Update,Select & Select All operations for the given table. The code of methods used in ‘CreateRepoClass’ method are as follows:
  1. /// <summary>
  2. /// Creates a string that represents the insert functionality of the data access class.
  3. /// </summary>
  4. /// <param name="table">The Table instance that this method will be created for.</param>
  5. /// <param name="streamWriter">The StreamWriter instance that will be used to create the method.</param>
  6. private static void CreateInsertMethod(Table table, TextWriter streamWriter)
  7. {
  8. var className = AppUtility.FormatClassName(table.Name);
  9. var variableName = "a" + className;
  10. // Append the method header
  11. streamWriter.WriteLine("\t\t/// <summary>");
  12. streamWriter.WriteLine("\t\t/// Saves a record to the " + table.Name + " table.");
  13. streamWriter.WriteLine("\t\t/// returns True if value saved successfullyelse false");
  14. streamWriter.WriteLine("\t\t/// Throw exception with message value 'EXISTS' if the data is duplicate");
  15. streamWriter.WriteLine("\t\t/// </summary>");
  16. streamWriter.WriteLine("\t\tpublic bool Insert(" + className + " " + variableName + ")");
  17. streamWriter.WriteLine("\t\t{");
  18. streamWriter.WriteLine("\t\t var blResult = false;");
  19. streamWriter.WriteLine("\t\t\t using (var vConn = OpenConnection())");
  20. streamWriter.WriteLine("\t\t\t\t {");
  21. streamWriter.WriteLine("\t\t\t\t var vParams = new DynamicParameters();");
  22. foreach (var column in table.Columns)
  23. { streamWriter.WriteLine("\t\t\t\t\t vParams.Add(\"@" + column.Name + "\"," + variableName + "." + AppUtility.FormatPascal(column.Name) + ");"); }
  24. streamWriter.WriteLine("\t\t\t\t\t int iResult = vConn.Execute(\"" + table.Name + "Insert\", vParams, commandType: CommandType.StoredProcedure);");
  25. streamWriter.WriteLine("\t\t\t if (iResult == -1) blResult = true;");
  26. streamWriter.WriteLine("\t\t\t }");
  27. streamWriter.WriteLine("\t\t\t return blResult;");
  28. streamWriter.WriteLine("\t\t}");
  29. streamWriter.WriteLine();
  30. }
  31. /// <summary>
  32. /// Creates a string that represents the update functionality of the data access class.
  33. /// </summary>
  34. /// <param name="table">The Table instance that this method will be created for.</param>
  35. /// <param name="streamWriter">The StreamWriter instance that will be used to create the method.</param>
  36. private static void CreateUpdateMethod(Table table, TextWriter streamWriter)
  37. {
  38. if (table.PrimaryKeys.Count <= 0 || table.Columns.Count == table.PrimaryKeys.Count ||
  39. table.Columns.Count == table.ForeignKeys.Count) return;
  40. var className = AppUtility.FormatClassName(table.Name);
  41. var variableName = "a" + className;
  42. // Append the method header
  43. streamWriter.WriteLine("\t\t/// <summary>");
  44. streamWriter.WriteLine("\t\t/// Updates record to the " + table.Name + " table.");
  45. streamWriter.WriteLine("\t\t/// returns True if value saved successfullyelse false");
  46. streamWriter.WriteLine("\t\t/// Throw exception with message value 'EXISTS' if the data is duplicate");
  47. streamWriter.WriteLine("\t\t/// </summary>");
  48. streamWriter.WriteLine("\t\tpublic bool Update(" + className + " " + variableName + ")");
  49. streamWriter.WriteLine("\t\t{");
  50. streamWriter.WriteLine("\t\t var blResult = false;");
  51. streamWriter.WriteLine("\t\t\t using (var vConn = OpenConnection())");
  52. streamWriter.WriteLine("\t\t\t\t {");
  53. streamWriter.WriteLine("\t\t\t\t var vParams = new DynamicParameters();");
  54. foreach (var column in table.Columns)
  55. { streamWriter.WriteLine("\t\t\t\t\t vParams.Add(\"@" + column.Name + "\"," + variableName + "." + AppUtility.FormatPascal(column.Name) + ");"); }
  56. streamWriter.WriteLine("\t\t\t\t\t int iResult = vConn.Execute(\"" + table.Name + "Update\", vParams, commandType: CommandType.StoredProcedure);");
  57. streamWriter.WriteLine("\t\t\t\t if (iResult == -1) blResult = true;");
  58. streamWriter.WriteLine("\t\t\t\t }");
  59. streamWriter.WriteLine("\t\t\treturn blResult;");
  60. streamWriter.WriteLine("\t\t}");
  61. streamWriter.WriteLine();
  62. }
  63. /// <summary>
  64. /// Creates a string that represents the "select" functionality of the data access class.
  65. /// </summary>
  66. /// <param name="table">The Table instance that this method will be created for.</param>
  67. /// <param name="streamWriter">The StreamWriter instance that will be used to create the method.</param>
  68. private static void CreateSelectMethod(Table table, TextWriter streamWriter)
  69. {
  70. if (table.PrimaryKeys.Count <= 0 || table.Columns.Count == table.PrimaryKeys.Count ||
  71. table.Columns.Count == table.ForeignKeys.Count) return;
  72. var className = AppUtility.FormatClassName(table.Name);
  73. var variableName = "a" + table.PrimaryKeys[0].Name;
  74. // Append the method header
  75. streamWriter.WriteLine("\t\t/// <summary>");
  76. streamWriter.WriteLine("\t\t/// Selects the Single object of " + table.Name + " table.");
  77. streamWriter.WriteLine("\t\t/// </summary>");
  78. streamWriter.WriteLine("\t\tpublic "+ className + " Get"+ className +"(" + AppUtility.GetCsType(table.PrimaryKeys[0]) + " " + variableName + ")");
  79. streamWriter.WriteLine("\t\t{");
  80. streamWriter.WriteLine("\t\t\t using (var vConn = OpenConnection())");
  81. streamWriter.WriteLine("\t\t\t\t {");
  82. streamWriter.WriteLine("\t\t\t\t var vParams = new DynamicParameters();");
  83. streamWriter.WriteLine("\t\t\t\t\t vParams.Add(\"@" + table.PrimaryKeys[0].Name + "\"," + variableName + ");");
  84. streamWriter.WriteLine("\t\t\t\t\t return vConn.Query<"+ className + ">(\"" + table.Name + "Select\", vParams, commandType: CommandType.StoredProcedure);");
  85. streamWriter.WriteLine("\t\t\t\t }");
  86. streamWriter.WriteLine("\t\t}");
  87. streamWriter.WriteLine();
  88. }
  89. /// <summary>
  90. /// Creates a string that represents the select functionality of the data access class.
  91. /// </summary>
  92. /// <param name="table">The Table instance that this method will be created for.</param>
  93. /// <param name="streamWriter">The StreamWriter instance that will be used to create the method.</param>
  94. private static void CreateSelectAllMethod(Table table, TextWriter streamWriter)
  95. {
  96. if (table.Columns.Count == table.PrimaryKeys.Count || table.Columns.Count == table.ForeignKeys.Count)
  97. return;
  98. var className = AppUtility.FormatClassName(table.Name);
  99. // Append the method header
  100. streamWriter.WriteLine("\t\t/// <summary>");
  101. streamWriter.WriteLine("\t\t/// Selects all records from the " + table.Name + " table.");
  102. streamWriter.WriteLine("\t\t/// </summary>");
  103. streamWriter.WriteLine("\t\t public IEnumerable<" + className + "> SelectAll()");
  104. streamWriter.WriteLine("\t\t{");
  105. // Append the stored procedure execution
  106. streamWriter.WriteLine("\t\t\t using (var vConn = OpenConnection())");
  107. streamWriter.WriteLine("\t\t\t{");
  108. streamWriter.WriteLine("\t\t\t\t return vConn.Query<" + className + ">(\"" + table.Name + "SelectAll\", commandType: CommandType.StoredProcedure).ToList();");
  109. streamWriter.WriteLine("\t\t\t}");
  110. streamWriter.WriteLine("\t\t}");
  111. }
  112. /// <summary>
  113. /// Creates a string that represents the "select by" functionality of the data access class.
  114. /// </summary>
  115. /// <param name="table">The Table instance that this method will be created for.</param>
  116. /// <param name="storedProcedurePrefix">The prefix that is used on the stored procedure that this method will call.</param>
  117. /// <param name="streamWriter">The StreamWriter instance that will be used to create the method.</param>
  118. private static void CreateSelectAllByMethods(Table table, string storedProcedurePrefix, TextWriter streamWriter)
  119. {
  120. string className = AppUtility.FormatClassName(table.Name);
  121. string dtoVariableName = AppUtility.FormatCamel(className);
  122. // Create a stored procedure for each foreign key
  123. foreach (List<Column> compositeKeyList in table.ForeignKeys.Values)
  124. {
  125. // Create the stored procedure name
  126. StringBuilder stringBuilder = new StringBuilder(255);
  127. stringBuilder.Append("SelectAllBy");
  128. for (var i = 0; i < compositeKeyList.Count; i++)
  129. {
  130. var column = compositeKeyList[i];
  131. if (i > 0)
  132. {
  133. stringBuilder.Append("_" + AppUtility.FormatPascal(column.Name));
  134. }
  135. else
  136. {
  137. stringBuilder.Append(AppUtility.FormatPascal(column.Name));
  138. }
  139. }
  140. string methodName = stringBuilder.ToString();
  141. string procedureName = storedProcedurePrefix + table.Name + methodName;
  142. // Create the select function based on keys
  143. // Append the method header
  144. streamWriter.WriteLine("\t\t/// <summary>");
  145. streamWriter.WriteLine("\t\t/// Selects all records from the " + table.Name + " table by a foreign key.");
  146. streamWriter.WriteLine("\t\t/// </summary>");
  147. streamWriter.Write("\t\tpublic List<" + className + "> " + methodName + "(");
  148. for (int i = 0; i < compositeKeyList.Count; i++)
  149. {
  150. Column column = compositeKeyList[i];
  151. streamWriter.Write(AppUtility.CreateMethodParameter(column));
  152. if (i < (compositeKeyList.Count - 1))
  153. {
  154. streamWriter.Write(",");
  155. }
  156. }
  157. streamWriter.WriteLine(")");
  158. streamWriter.WriteLine("\t\t{");
  159. streamWriter.WriteLine("\t\t\t using (var vConn = OpenConnection())");
  160. streamWriter.WriteLine("\t\t\t\t {");
  161. streamWriter.WriteLine("\t\t\t\t var vParams = new DynamicParameters();");
  162. for (var i = 0; i < compositeKeyList.Count; i++)
  163. {
  164. var column = compositeKeyList[i];
  165. streamWriter.WriteLine("\t\t\t\t\t vParams.Add(\"@" + column.Name + "\"," + AppUtility.FormatCamel(column.Name) + ");");
  166. }
  167. streamWriter.WriteLine("\t\t\t\t return vConn.Query<" + className + ">(\"" + table.Name + "SelectAll\", vParams, commandType: CommandType.StoredProcedure).ToList();");
  168. streamWriter.WriteLine("\t\t\t\t }");
  169. streamWriter.WriteLine("\t\t}");
  170. streamWriter.WriteLine();
  171. }
  172. }
The ‘Generate Both SQL & Classes’ button click will execute both ‘GenerateSQLScripts’ & ‘GenerateCSharpClasses’ methods together and show the output files path after success message like given screenshot.

genrate

The source code of this application can be downloaded from Github. I always use this application in order to generate POCO classes, DML SQL Scripts and Dapper Repo classes. I hope that it will be as useful for other people as it is to me, let me know if I have missed anything or you have any queries/suggestions. Happy coding!
Read more articles on SQL Server: