├── .gitattributes ├── .gitignore ├── PocoSqlGenerator.sln ├── PocoSqlGenerator ├── App.config ├── AppUtility.cs ├── CSharpCodeGenerator.cs ├── MainForm.Designer.cs ├── MainForm.cs ├── MainForm.resx ├── PocoSqlGenerator.csproj ├── Program.cs ├── Properties │ ├── AssemblyInfo.cs │ ├── Resources.Designer.cs │ ├── Resources.resx │ ├── Settings.Designer.cs │ └── Settings.settings ├── Resources │ ├── App.config │ ├── AssemblyInfo.txt │ ├── ColumnQuery.sql │ ├── Project.xml │ ├── TableQuery.sql │ └── User.sql └── SqlScriptGenerator.cs └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | [Xx]64/ 19 | [Xx]86/ 20 | [Bb]uild/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | 85 | # Visual Studio profiler 86 | *.psess 87 | *.vsp 88 | *.vspx 89 | *.sap 90 | 91 | # TFS 2012 Local Workspace 92 | $tf/ 93 | 94 | # Guidance Automation Toolkit 95 | *.gpState 96 | 97 | # ReSharper is a .NET coding add-in 98 | _ReSharper*/ 99 | *.[Rr]e[Ss]harper 100 | *.DotSettings.user 101 | 102 | # JustCode is a .NET coding add-in 103 | .JustCode 104 | 105 | # TeamCity is a build add-in 106 | _TeamCity* 107 | 108 | # DotCover is a Code Coverage Tool 109 | *.dotCover 110 | 111 | # NCrunch 112 | _NCrunch_* 113 | .*crunch*.local.xml 114 | nCrunchTemp_* 115 | 116 | # MightyMoose 117 | *.mm.* 118 | AutoTest.Net/ 119 | 120 | # Web workbench (sass) 121 | .sass-cache/ 122 | 123 | # Installshield output folder 124 | [Ee]xpress/ 125 | 126 | # DocProject is a documentation generator add-in 127 | DocProject/buildhelp/ 128 | DocProject/Help/*.HxT 129 | DocProject/Help/*.HxC 130 | DocProject/Help/*.hhc 131 | DocProject/Help/*.hhk 132 | DocProject/Help/*.hhp 133 | DocProject/Help/Html2 134 | DocProject/Help/html 135 | 136 | # Click-Once directory 137 | publish/ 138 | 139 | # Publish Web Output 140 | *.[Pp]ublish.xml 141 | *.azurePubxml 142 | 143 | # TODO: Un-comment the next line if you do not want to checkin 144 | # your web deploy settings because they may include unencrypted 145 | # passwords 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # NuGet Packages 150 | *.nupkg 151 | # The packages folder can be ignored because of Package Restore 152 | **/packages/* 153 | # except build/, which is used as an MSBuild target. 154 | !**/packages/build/ 155 | # Uncomment if necessary however generally it will be regenerated when needed 156 | #!**/packages/repositories.config 157 | # NuGet v3's project.json files produces more ignoreable files 158 | *.nuget.props 159 | *.nuget.targets 160 | 161 | # Microsoft Azure Build Output 162 | csx/ 163 | *.build.csdef 164 | 165 | # Microsoft Azure Emulator 166 | ecf/ 167 | rcf/ 168 | 169 | # Microsoft Azure ApplicationInsights config file 170 | ApplicationInsights.config 171 | 172 | # Windows Store app package directory 173 | AppPackages/ 174 | BundleArtifacts/ 175 | 176 | # Visual Studio cache files 177 | # files ending in .cache can be ignored 178 | *.[Cc]ache 179 | # but keep track of directories ending in .cache 180 | !*.[Cc]ache/ 181 | 182 | # Others 183 | ClientBin/ 184 | [Ss]tyle[Cc]op.* 185 | ~$* 186 | *~ 187 | *.dbmdl 188 | *.dbproj.schemaview 189 | *.pfx 190 | *.publishsettings 191 | node_modules/ 192 | orleans.codegen.cs 193 | 194 | # RIA/Silverlight projects 195 | Generated_Code/ 196 | 197 | # Backup & report files from converting an old project file 198 | # to a newer Visual Studio version. Backup files are not needed, 199 | # because we have git ;-) 200 | _UpgradeReport_Files/ 201 | Backup*/ 202 | UpgradeLog*.XML 203 | UpgradeLog*.htm 204 | 205 | # SQL Server files 206 | *.mdf 207 | *.ldf 208 | 209 | # Business Intelligence projects 210 | *.rdl.data 211 | *.bim.layout 212 | *.bim_*.settings 213 | 214 | # Microsoft Fakes 215 | FakesAssemblies/ 216 | 217 | # GhostDoc plugin setting file 218 | *.GhostDoc.xml 219 | 220 | # Node.js Tools for Visual Studio 221 | .ntvs_analysis.dat 222 | 223 | # Visual Studio 6 build log 224 | *.plg 225 | 226 | # Visual Studio 6 workspace options file 227 | *.opt 228 | 229 | # Visual Studio LightSwitch build output 230 | **/*.HTMLClient/GeneratedArtifacts 231 | **/*.DesktopClient/GeneratedArtifacts 232 | **/*.DesktopClient/ModelManifest.xml 233 | **/*.Server/GeneratedArtifacts 234 | **/*.Server/ModelManifest.xml 235 | _Pvt_Extensions 236 | 237 | # LightSwitch generated files 238 | GeneratedArtifacts/ 239 | ModelManifest.xml 240 | 241 | # Paket dependency manager 242 | .paket/paket.exe 243 | 244 | # FAKE - F# Make 245 | .fake/ -------------------------------------------------------------------------------- /PocoSqlGenerator.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25123.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PocoSqlGenerator", "PocoSqlGenerator\PocoSqlGenerator.csproj", "{6D3FC7F7-BA0F-4E44-AEB2-EBD754FC2816}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {6D3FC7F7-BA0F-4E44-AEB2-EBD754FC2816}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {6D3FC7F7-BA0F-4E44-AEB2-EBD754FC2816}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {6D3FC7F7-BA0F-4E44-AEB2-EBD754FC2816}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {6D3FC7F7-BA0F-4E44-AEB2-EBD754FC2816}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /PocoSqlGenerator/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /PocoSqlGenerator/AppUtility.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Data; 5 | using System.Data.SqlClient; 6 | using System.IO; 7 | using System.Reflection; 8 | 9 | namespace PocoSqlGenerator 10 | { 11 | /// 12 | /// This class is used by the application internally for doind common operations 13 | /// like creating folders, Getting resources etc. 14 | /// 15 | internal static class AppUtility 16 | { 17 | /// 18 | /// Creates the specified sub-directory, if it doesn't exist. 19 | /// 20 | /// The name of the sub-directory to be created. 21 | internal static void CreateSubDirectory(string name) 22 | { 23 | if (Directory.Exists(name) == false) 24 | { 25 | Directory.CreateDirectory(name); 26 | } 27 | } 28 | 29 | /// 30 | /// Creates the specified sub-directory, if it doesn't exist. 31 | /// 32 | /// The name of the sub-directory to be created. 33 | /// Indicates if the directory should be deleted if it exists. 34 | internal static void CreateSubDirectory(string name, bool deleteIfExists) 35 | { 36 | if (Directory.Exists(name)) 37 | { 38 | Directory.Delete(name, true); 39 | } 40 | 41 | Directory.CreateDirectory(name); 42 | } 43 | 44 | /// 45 | /// Retrieves the specified manifest resource stream from the executing assembly. 46 | /// 47 | /// Name of the resource to retrieve. 48 | /// A stream that contains the resource. 49 | internal static Stream GetResourceAsStream(string name) 50 | { 51 | return Assembly.GetExecutingAssembly().GetManifestResourceStream(name); 52 | } 53 | 54 | /// 55 | /// Retrieves the specified manifest resource stream from the executing assembly as a string. 56 | /// 57 | /// Name of the resource to retrieve. 58 | /// The value of the specified manifest resource. 59 | internal static string GetResource(string name) 60 | { 61 | using (var streamReader = new StreamReader(GetResourceAsStream(name))) 62 | { 63 | return streamReader.ReadToEnd(); 64 | } 65 | } 66 | 67 | /// 68 | /// Retrieves the specified manifest resource stream from the executing assembly as a string, replacing the specified old value with the specified new value. 69 | /// 70 | /// Name of the resource to retrieve. 71 | /// A string to be replaced. 72 | /// A string to replace all occurrences of oldValue. 73 | /// The value of the specified manifest resource, with all instances of oldValue replaced with newValue. 74 | internal static string GetResource(string name, string oldValue, string newValue) 75 | { 76 | string returnValue = GetResource(name); 77 | return returnValue.Replace(oldValue, newValue); 78 | } 79 | 80 | /// 81 | /// Writes a compiled resource to a file. 82 | /// 83 | /// The name of the resource. 84 | /// The name of the file to write to. 85 | internal static void WriteResourceToFile(string resourceName, string fileName) 86 | { 87 | using (var fileStream = new FileStream(fileName, FileMode.Create)) 88 | { 89 | using (var stream = GetResourceAsStream(resourceName)) 90 | { 91 | while (true) 92 | { 93 | var intValue = stream.ReadByte(); 94 | if (intValue < 0) 95 | { 96 | break; 97 | } 98 | var byteValue = (byte)intValue; 99 | fileStream.WriteByte(byteValue); 100 | } 101 | } 102 | } 103 | } 104 | /// 105 | /// Retrieves the column, primary key, and foreign key information for the specified table. 106 | /// 107 | /// The SqlConnection to be used when querying for the table information. 108 | /// The table instance that information should be retrieved for. 109 | internal static void QueryTable(SqlConnection connection, Table table) 110 | { 111 | // Get a list of the entities in the database 112 | DataTable dataTable = new DataTable(); 113 | SqlDataAdapter dataAdapter = new SqlDataAdapter(AppUtility.GetColumnQuery(table.Name), connection); 114 | dataAdapter.Fill(dataTable); 115 | 116 | foreach (DataRow columnRow in dataTable.Rows) 117 | { 118 | Column column = new Column(); 119 | column.Name = columnRow["COLUMN_NAME"].ToString(); 120 | column.Type = columnRow["DATA_TYPE"].ToString(); 121 | column.Precision = columnRow["NUMERIC_PRECISION"].ToString(); 122 | column.Scale = columnRow["NUMERIC_SCALE"].ToString(); 123 | 124 | // Determine the column's length 125 | if (columnRow["CHARACTER_MAXIMUM_LENGTH"] != DBNull.Value) 126 | { 127 | column.Length = columnRow["CHARACTER_MAXIMUM_LENGTH"].ToString(); 128 | } 129 | else 130 | { 131 | column.Length = columnRow["COLUMN_LENGTH"].ToString(); 132 | } 133 | 134 | // Is the column a RowGuidCol column? 135 | if (columnRow["IS_ROWGUIDCOL"].ToString() == "1") 136 | { 137 | column.IsRowGuidCol = true; 138 | } 139 | 140 | // Is the column an Identity column? 141 | if (columnRow["IS_IDENTITY"].ToString() == "1") 142 | { 143 | column.IsIdentity = true; 144 | } 145 | 146 | // Is columnRow column a computed column? 147 | if (columnRow["IS_COMPUTED"].ToString() == "1") 148 | { 149 | column.IsComputed = true; 150 | } 151 | 152 | table.Columns.Add(column); 153 | } 154 | 155 | // Get the list of primary keys 156 | DataTable primaryKeyTable = AppUtility.GetPrimaryKeyList(connection, table.Name); 157 | foreach (DataRow primaryKeyRow in primaryKeyTable.Rows) 158 | { 159 | string primaryKeyName = primaryKeyRow["COLUMN_NAME"].ToString(); 160 | 161 | foreach (Column column in table.Columns) 162 | { 163 | if (column.Name == primaryKeyName) 164 | { 165 | table.PrimaryKeys.Add(column); 166 | break; 167 | } 168 | } 169 | } 170 | 171 | // Get the list of foreign keys 172 | DataTable foreignKeyTable = AppUtility.GetForeignKeyList(connection, table.Name); 173 | foreach (DataRow foreignKeyRow in foreignKeyTable.Rows) 174 | { 175 | string name = foreignKeyRow["FK_NAME"].ToString(); 176 | string columnName = foreignKeyRow["FKCOLUMN_NAME"].ToString(); 177 | 178 | if (table.ForeignKeys.ContainsKey(name) == false) 179 | { 180 | table.ForeignKeys.Add(name, new List()); 181 | } 182 | 183 | List foreignKeys = table.ForeignKeys[name]; 184 | 185 | foreach (Column column in table.Columns) 186 | { 187 | if (column.Name == columnName) 188 | { 189 | foreignKeys.Add(column); 190 | break; 191 | } 192 | } 193 | } 194 | } 195 | /// 196 | /// Retrives the list of all the tables selected with their Column and other details. 197 | /// 198 | /// The directory where the C# and SQL code should be created. 199 | /// The connection string to be used to connect the to the database. 200 | /// ArrayList of Table names whose whole details have to be fetched has to be created. 201 | /// Reference parameter which is used to get DB name from the method 202 | /// 203 | internal static List GetTableList(string connectionString, string outputDirectory, ArrayList tableNames, ref String databaseName) 204 | { 205 | List
tableList = new List
(); 206 | string sqlPath; 207 | sqlPath = Path.Combine(outputDirectory, "SQL"); 208 | using (SqlConnection connection = new SqlConnection(connectionString)) 209 | { 210 | databaseName = AppUtility.FormatPascal(connection.Database); 211 | connection.Open(); 212 | // Process each table 213 | for (int iCount = 0; iCount < tableNames.Count; iCount++) 214 | { 215 | Table table = new Table(); 216 | table.Name = (string)tableNames[iCount]; 217 | QueryTable(connection, table); 218 | tableList.Add(table); 219 | } 220 | } 221 | return tableList; 222 | } 223 | 224 | /// 225 | /// Returns the query that should be used for retrieving the list of tables for the specified database. 226 | /// 227 | /// The database to be queried for. 228 | /// The query that should be used for retrieving the list of tables for the specified database. 229 | internal static string GetTableQuery(string databaseName) 230 | { 231 | return GetResource("PocoSqlGenerator.Resources.TableQuery.sql", "#DatabaseName#", databaseName); 232 | } 233 | 234 | /// 235 | /// Returns the query that should be used for retrieving the list of columns for the specified table. 236 | /// 237 | /// The query that should be used for retrieving the list of columns for the specified table. 238 | internal static string GetColumnQuery(string tableName) 239 | { 240 | return GetResource("PocoSqlGenerator.Resources.ColumnQuery.sql", "#TableName#", tableName); 241 | } 242 | 243 | /// 244 | /// Retrieves the specified manifest resource stream from the executing assembly as a string, replacing the specified old value with the specified new value. 245 | /// 246 | /// The name of the database to be used. 247 | /// The name of the user to be used. 248 | /// The queries that should be used to create the specified database login. 249 | internal static string GetUserQueries(string databaseName, string grantLoginName) 250 | { 251 | string returnValue = GetResource("PocoSqlGenerator.Resources.User.sql"); 252 | returnValue = returnValue.Replace("#DatabaseName#", databaseName); 253 | returnValue = returnValue.Replace("#UserName#", grantLoginName); 254 | return returnValue; 255 | } 256 | 257 | /// 258 | /// Returns the query that should be used for retrieving the list of tables for the specified database. 259 | /// 260 | /// The database to be queried for. 261 | /// The query that should be used for retrieving the list of tables for the specified database. 262 | internal static string Get(string databaseName) 263 | { 264 | return GetResource("PocoSqlGenerator.Resources.TableQuery.sql", "#DatabaseName#", databaseName); 265 | } 266 | 267 | /// 268 | /// Retrieves the foreign key information for the specified table. 269 | /// 270 | /// The SqlConnection to be used when querying for the table information. 271 | /// Name of the table that foreign keys should be checked for. 272 | /// DataReader containing the foreign key information for the specified table. 273 | internal static DataTable GetForeignKeyList(SqlConnection connection, string tableName) 274 | { 275 | using (var command = new SqlCommand("sp_fkeys", connection)) 276 | { 277 | command.CommandType = CommandType.StoredProcedure; 278 | 279 | var parameter = new SqlParameter("@pktable_name", SqlDbType.NVarChar, 128, ParameterDirection.Input, true, 0, 0, "pktable_name", DataRowVersion.Current, DBNull.Value); 280 | command.Parameters.Add(parameter); 281 | parameter = new SqlParameter("@pktable_owner", SqlDbType.NVarChar, 128, ParameterDirection.Input, true, 0, 0, "pktable_owner", DataRowVersion.Current, DBNull.Value); 282 | command.Parameters.Add(parameter); 283 | parameter = new SqlParameter("@pktable_qualifier", SqlDbType.NVarChar, 128, ParameterDirection.Input, true, 0, 0, "pktable_qualifier", DataRowVersion.Current, DBNull.Value); 284 | command.Parameters.Add(parameter); 285 | parameter = new SqlParameter("@fktable_name", SqlDbType.NVarChar, 128, ParameterDirection.Input, true, 0, 0, "fktable_name", DataRowVersion.Current, tableName); 286 | command.Parameters.Add(parameter); 287 | parameter = new SqlParameter("@fktable_owner", SqlDbType.NVarChar, 128, ParameterDirection.Input, true, 0, 0, "fktable_owner", DataRowVersion.Current, DBNull.Value); 288 | command.Parameters.Add(parameter); 289 | parameter = new SqlParameter("@fktable_qualifier", SqlDbType.NVarChar, 128, ParameterDirection.Input, true, 0, 0, "fktable_qualifier", DataRowVersion.Current, DBNull.Value); 290 | command.Parameters.Add(parameter); 291 | 292 | var dataAdapter = new SqlDataAdapter(command); 293 | var dataTable = new DataTable(); 294 | dataAdapter.Fill(dataTable); 295 | 296 | return dataTable; 297 | } 298 | } 299 | 300 | /// 301 | /// Retrieves the primary key information for the specified table. 302 | /// 303 | /// The SqlConnection to be used when querying for the table information. 304 | /// Name of the table that primary keys should be checked for. 305 | /// DataReader containing the primary key information for the specified table. 306 | internal static DataTable GetPrimaryKeyList(SqlConnection connection, string tableName) 307 | { 308 | using (var command = new SqlCommand("sp_pkeys", connection)) 309 | { 310 | command.CommandType = CommandType.StoredProcedure; 311 | 312 | var parameter = new SqlParameter("@table_name", SqlDbType.NVarChar, 128, ParameterDirection.Input, false, 0, 0, "table_name", DataRowVersion.Current, tableName); 313 | command.Parameters.Add(parameter); 314 | parameter = new SqlParameter("@table_owner", SqlDbType.NVarChar, 128, ParameterDirection.Input, true, 0, 0, "table_owner", DataRowVersion.Current, DBNull.Value); 315 | command.Parameters.Add(parameter); 316 | parameter = new SqlParameter("@table_qualifier", SqlDbType.NVarChar, 128, ParameterDirection.Input, true, 0, 0, "table_qualifier", DataRowVersion.Current, DBNull.Value); 317 | command.Parameters.Add(parameter); 318 | 319 | var dataAdapter = new SqlDataAdapter(command); 320 | var dataTable = new DataTable(); 321 | dataAdapter.Fill(dataTable); 322 | 323 | return dataTable; 324 | } 325 | } 326 | 327 | /// 328 | /// Creates a string containing the parameter declaration for a stored procedure based on the parameters passed in. 329 | /// 330 | /// Object that stores the information for the column the parameter represents. 331 | /// Indicates if the created parameter should be checked to see if it should be created as an output parameter. 332 | /// String containing parameter information of the specified column for a stored procedure. 333 | internal static string CreateParameterString(Column column, bool checkForOutputParameter) 334 | { 335 | string parameter; 336 | 337 | switch (column.Type.ToLower()) 338 | { 339 | case "binary": 340 | parameter = "@" + column.Name + " " + column.Type + "(" + column.Length + ")"; 341 | break; 342 | case "bigint": 343 | parameter = "@" + column.Name + " " + column.Type; 344 | break; 345 | case "bit": 346 | parameter = "@" + column.Name + " " + column.Type; 347 | break; 348 | case "char": 349 | parameter = "@" + column.Name + " " + column.Type + "(" + column.Length + ")"; 350 | break; 351 | case "datetime": 352 | parameter = "@" + column.Name + " " + column.Type; 353 | break; 354 | case "date": 355 | parameter = "@" + column.Name + " " + column.Type; 356 | break; 357 | case "time": 358 | parameter = "@" + column.Name + " " + column.Type; 359 | break; 360 | case "decimal": 361 | if (column.Scale.Length == 0) 362 | parameter = "@" + column.Name + " " + column.Type + "(" + column.Precision + ")"; 363 | else 364 | parameter = "@" + column.Name + " " + column.Type + "(" + column.Precision + ", " + column.Scale + ")"; 365 | break; 366 | case "float": 367 | parameter = "@" + column.Name + " " + column.Type + "(" + column.Precision + ")"; 368 | break; 369 | case "image": 370 | parameter = "@" + column.Name + " " + column.Type; 371 | break; 372 | case "int": 373 | parameter = "@" + column.Name + " " + column.Type; 374 | break; 375 | case "money": 376 | parameter = "@" + column.Name + " " + column.Type; 377 | break; 378 | case "nchar": 379 | parameter = "@" + column.Name + " " + column.Type + "(" + column.Length + ")"; 380 | break; 381 | case "ntext": 382 | parameter = "@" + column.Name + " " + column.Type; 383 | break; 384 | case "nvarchar": 385 | parameter = "@" + column.Name + " " + column.Type + "(" + column.Length + ")"; 386 | break; 387 | case "numeric": 388 | if (column.Scale.Length == 0) 389 | parameter = "@" + column.Name + " " + column.Type + "(" + column.Precision + ")"; 390 | else 391 | parameter = "@" + column.Name + " " + column.Type + "(" + column.Precision + ", " + column.Scale + ")"; 392 | break; 393 | case "real": 394 | parameter = "@" + column.Name + " " + column.Type; 395 | break; 396 | case "smalldatetime": 397 | parameter = "@" + column.Name + " " + column.Type; 398 | break; 399 | case "smallint": 400 | parameter = "@" + column.Name + " " + column.Type; 401 | break; 402 | case "smallmoney": 403 | parameter = "@" + column.Name + " " + column.Type; 404 | break; 405 | case "sql_variant": 406 | parameter = "@" + column.Name + " " + column.Type; 407 | break; 408 | case "sysname": 409 | parameter = "@" + column.Name + " " + column.Type; 410 | break; 411 | case "text": 412 | parameter = "@" + column.Name + " " + column.Type; 413 | break; 414 | case "timestamp": 415 | parameter = "@" + column.Name + " " + column.Type; 416 | break; 417 | case "tinyint": 418 | parameter = "@" + column.Name + " " + column.Type; 419 | break; 420 | case "varbinary": 421 | parameter = "@" + column.Name + " " + column.Type + "(" + column.Length + ")"; 422 | break; 423 | case "varchar": 424 | parameter = "@" + column.Name + " " + column.Type + "(" + column.Length + ")"; 425 | break; 426 | case "uniqueidentifier": 427 | parameter = "@" + column.Name + " " + column.Type; 428 | break; 429 | case "xml": 430 | parameter = "@" + column.Name + " " + column.Type; 431 | break; 432 | default: // Unknow data type 433 | throw (new Exception("Invalid SQL Server data type specified: " + column.Type)); 434 | } 435 | 436 | // Return the new parameter string 437 | if (checkForOutputParameter && (column.IsIdentity || column.IsRowGuidCol)) 438 | { 439 | return parameter + " OUTPUT"; 440 | } 441 | return parameter; 442 | } 443 | 444 | /// 445 | /// Creates a string for a method parameter representing the specified column. 446 | /// 447 | /// Object that stores the information for the column the parameter represents. 448 | /// String containing parameter information of the specified column for a method call. 449 | internal static string CreateMethodParameter(Column column) 450 | { 451 | return GetCsType(column) + " " + FormatCamel(column.Name); 452 | } 453 | 454 | /// 455 | /// Creates the name of the method to call on a SqlDataReader for the specified column. 456 | /// 457 | /// The column to retrieve data for. 458 | /// The name of the method to call on a SqlDataReader for the specified column. 459 | internal static string GetCsType(Column column) 460 | { 461 | switch (column.Type.ToLower()) 462 | { 463 | case "binary": 464 | return "byte[]"; 465 | case "bigint": 466 | return "long"; 467 | case "bit": 468 | return "bool"; 469 | case "char": 470 | return "string"; 471 | case "date": 472 | return "DateTime"; 473 | case "time": 474 | return "DateTime"; 475 | case "datetime": 476 | return "DateTime"; 477 | case "decimal": 478 | return "decimal"; 479 | case "float": 480 | return "Double"; 481 | case "image": 482 | return "byte[]"; 483 | case "int": 484 | return "int"; 485 | case "money": 486 | return "decimal"; 487 | case "nchar": 488 | return "string"; 489 | case "ntext": 490 | return "string"; 491 | case "nvarchar": 492 | return "string"; 493 | case "numeric": 494 | return "decimal"; 495 | case "real": 496 | return "decimal"; 497 | case "smalldatetime": 498 | return "DateTime"; 499 | case "smallint": 500 | return "short"; 501 | case "smallmoney": 502 | return "float"; 503 | case "sql_variant": 504 | return "byte[]"; 505 | case "sysname": 506 | return "string"; 507 | case "text": 508 | return "string"; 509 | case "timestamp": 510 | return "DateTime"; 511 | case "tinyint": 512 | return "byte"; 513 | case "varbinary": 514 | return "byte[]"; 515 | case "varchar": 516 | return "string"; 517 | case "uniqueidentifier": 518 | return "Guid"; 519 | case "xml": 520 | return "string"; 521 | default: // Unknow data type 522 | throw (new Exception("Invalid SQL Server data type specified: " + column.Type)); 523 | } 524 | } 525 | /// 526 | /// Create a string of SQLDbType with value. 527 | /// 528 | /// The column to retrieve data for 529 | /// string 530 | internal static string GetSqlType(Column column) 531 | { 532 | switch (column.Type.ToLower()) 533 | { 534 | case "binary": 535 | return "DbType.Binary"; 536 | case "bigint": 537 | return "DbType.Int64"; 538 | case "bit": 539 | return "DbType.Boolean"; 540 | case "char": 541 | return "DbType.String"; 542 | case "date": 543 | return "DbType.Date"; 544 | case "time": 545 | return "DbType.Time"; 546 | case "datetime": 547 | return "DbType.DateTime"; 548 | case "decimal": 549 | return "DbType.Decimal"; 550 | case "float": 551 | return "DbType.Double"; 552 | case "image": 553 | return "DbType.Binary"; 554 | case "int": 555 | return "DbType.Int32"; 556 | case "money": 557 | return "DbType.Decimal"; 558 | case "nchar": 559 | return "DbType.StringFixedLength"; 560 | case "ntext": 561 | return "DbType.String"; 562 | case "nvarchar": 563 | return "DbType.String"; 564 | case "numeric": 565 | return "DbType.Decimal"; 566 | case "real": 567 | return "DbType.Single"; 568 | case "smalldatetime": 569 | return "DbType.DateTime"; 570 | case "smallint": 571 | return "DbType.Int16"; 572 | case "smallmoney": 573 | return "DbType.Decimal"; 574 | case "sql_variant": 575 | return "DbType.Object"; 576 | case "sysname": 577 | return "DbType.String"; 578 | case "text": 579 | return "DbType.String"; 580 | case "timestamp": 581 | return "DbType.Binary"; 582 | case "tinyint": 583 | return "DbType.Byte"; 584 | case "varbinary": 585 | return "DbType.Binary"; 586 | case "varchar": 587 | return "DbType.String"; 588 | case "uniqueidentifier": 589 | return "DbType.Guid"; 590 | case "xml": 591 | return "DbType.Xml"; 592 | default: // Unknow data type 593 | throw (new Exception("Invalid data type specified: " + column.Type)); 594 | } 595 | } 596 | 597 | /// 598 | /// Creates the GetXxx method to use for the specified column. 599 | /// 600 | /// The column to retrieve data for. 601 | /// The name of the method to call on a SqlDataReader for the specified column. 602 | internal static string GetXxxMethod(Column column) 603 | { 604 | switch (column.Type.ToLower()) 605 | { 606 | case "binary": 607 | return "Convert.ToByte"; 608 | case "bigint": 609 | return "Convert.ToInt64"; 610 | case "bit": 611 | return "Convert.ToBoolean"; 612 | case "char": 613 | return "Convert.ToString"; 614 | case "date": 615 | return "Convert.ToDateTime"; 616 | case "time": 617 | return "Convert.ToDateTime"; 618 | case "datetime": 619 | return "Convert.ToDateTime"; 620 | case "decimal": 621 | return "Convert.ToDecimal"; 622 | case "float": 623 | return "Convert.ToDouble"; 624 | case "image": 625 | return "Convert.ToByte"; 626 | case "int": 627 | return "Convert.ToInt32"; 628 | case "money": 629 | return "Convert.ToDouble"; 630 | case "nchar": 631 | return "Convert.ToString"; 632 | case "ntext": 633 | return "Convert.ToString"; 634 | case "nvarchar": 635 | return "Convert.ToString"; 636 | case "numeric": 637 | return "Convert.ToDecimal"; 638 | case "real": 639 | return "Convert.ToDecimal"; 640 | case "smalldatetime": 641 | return "Convert.ToDateTime"; 642 | case "smallint": 643 | return "Convert.ToInt16"; 644 | case "smallmoney": 645 | return "Convert.ToDouble"; 646 | case "sql_variant": 647 | return "Convert.ToByte"; 648 | case "sysname": 649 | return "Convert.ToString"; 650 | case "text": 651 | return "Convert.ToString"; 652 | case "timestamp": 653 | return "Convert.ToDateTime"; 654 | case "tinyint": 655 | return "Convert.ToByte"; 656 | case "varbinary": 657 | return "Convert.ToByte"; 658 | case "varchar": 659 | return "Convert.ToString"; 660 | case "uniqueidentifier": 661 | return "Convert.ToString"; 662 | case "xml": 663 | return "Convert.ToString"; 664 | default: // Unknow data type 665 | throw (new Exception("Invalid data type specified: " + column.Type)); 666 | } 667 | } 668 | 669 | /// 670 | /// Creates a string for the default value of a column's data type. 671 | /// 672 | /// The column to get a default value for. 673 | /// The default value for the column. 674 | internal static string GetDefaultValue(Column column) 675 | { 676 | switch (column.Type.ToLower()) 677 | { 678 | case "binary": 679 | return "new byte[0]"; 680 | case "bigint": 681 | return "0"; 682 | case "bit": 683 | return "false"; 684 | case "char": 685 | return "String.Empty"; 686 | case "date": 687 | return "DateTime.Now"; 688 | case "datetime": 689 | return "DateTime.Now"; 690 | case "decimal": 691 | return "Decimal.Zero"; 692 | case "float": 693 | return "0.0F"; 694 | case "image": 695 | return "new byte[0]"; 696 | case "int": 697 | return "0"; 698 | case "money": 699 | return "Decimal.Zero"; 700 | case "nchar": 701 | return "String.Empty"; 702 | case "ntext": 703 | return "String.Empty"; 704 | case "nvarchar": 705 | return "String.Empty"; 706 | case "numeric": 707 | return "Decimal.Zero"; 708 | case "real": 709 | return "Decimal.Zero"; 710 | case "smalldatetime": 711 | return "DateTime.Now"; 712 | case "smallint": 713 | return "0"; 714 | case "smallmoney": 715 | return "0.0F"; 716 | case "sql_variant": 717 | return "new byte[0]"; 718 | case "sysname": 719 | return "String.Empty"; 720 | case "text": 721 | return "String.Empty"; 722 | case "timestamp": 723 | return "DateTime.Now"; 724 | case "tinyint": 725 | return "0x00"; 726 | case "varbinary": 727 | return "new byte[0]"; 728 | case "varchar": 729 | return "String.Empty"; 730 | case "uniqueidentifier": 731 | return "Guid.Empty"; 732 | case "xml": 733 | return "String.Empty"; 734 | default: // Unknow data type 735 | throw (new Exception("Invalid data type specified: " + column.Type)); 736 | } 737 | } 738 | 739 | /// 740 | /// Formats a string in Camel case (the first letter is in lower case). 741 | /// 742 | /// A string to be formatted. 743 | /// A string in Camel case. 744 | internal static string FormatCamel(string original) 745 | { 746 | if (original.Length > 0) 747 | { 748 | return Char.ToLower(original[0]) + original.Substring(1); 749 | } 750 | return String.Empty; 751 | } 752 | 753 | /// 754 | /// Formats a string in Pascal case (the first letter is in upper case). 755 | /// 756 | /// A string to be formatted. 757 | /// A string in Pascal case. 758 | internal static string FormatPascal(string original) 759 | { 760 | if (original.Length > 0) 761 | { 762 | return Char.ToUpper(original[0]) + original.Substring(1); 763 | } 764 | return String.Empty; 765 | } 766 | 767 | /// 768 | /// Formats the table name for use as a data transfer object. 769 | /// 770 | /// The name of the table to format. 771 | /// The table name, formatted for use as a data transfer object. 772 | internal static string FormatClassName(string tableName) 773 | { 774 | var className = Char.IsUpper(tableName[0]) ? tableName : FormatCamel(tableName); 775 | 776 | // Attept to removing a trailing 's' or 'S', unless, the last two characters are both 's' or 'S'. 777 | if (className[className.Length - 1] == 'S' && className[className.Length - 2] != 'S') 778 | { 779 | className = className.Substring(0, className.Length - 1); 780 | } 781 | else if (className[className.Length - 1] == 's' && className[className.Length - 2] != 's') 782 | { 783 | className = className.Substring(0, className.Length - 1); 784 | } 785 | 786 | return className; 787 | } 788 | 789 | /// 790 | /// Matches a SQL Server data type to a SqlClient.SqlDbType. 791 | /// 792 | /// A string representing a SQL Server data type. 793 | /// A string representing a SqlClient.SqlDbType. 794 | internal static string GetSqlDbType(string sqlDbType) 795 | { 796 | switch (sqlDbType.ToLower()) 797 | { 798 | case "binary": 799 | return "Binary"; 800 | case "bigint": 801 | return "BigInt"; 802 | case "bit": 803 | return "Bit"; 804 | case "char": 805 | return "Char"; 806 | case "datetime": 807 | return "DateTime"; 808 | case "decimal": 809 | return "Decimal"; 810 | case "float": 811 | return "Float"; 812 | case "image": 813 | return "Image"; 814 | case "int": 815 | return "Int"; 816 | case "money": 817 | return "Money"; 818 | case "nchar": 819 | return "NChar"; 820 | case "ntext": 821 | return "NText"; 822 | case "nvarchar": 823 | return "NVarChar"; 824 | case "numeric": 825 | return "Decimal"; 826 | case "real": 827 | return "Real"; 828 | case "smalldatetime": 829 | return "SmallDateTime"; 830 | case "smallint": 831 | return "SmallInt"; 832 | case "smallmoney": 833 | return "SmallMoney"; 834 | case "sql_variant": 835 | return "Variant"; 836 | case "sysname": 837 | return "VarChar"; 838 | case "text": 839 | return "Text"; 840 | case "timestamp": 841 | return "Timestamp"; 842 | case "tinyint": 843 | return "TinyInt"; 844 | case "varbinary": 845 | return "VarBinary"; 846 | case "varchar": 847 | return "VarChar"; 848 | case "uniqueidentifier": 849 | return "UniqueIdentifier"; 850 | case "xml": 851 | return "Xml"; 852 | default: // Unknow data type 853 | throw (new Exception("Invalid SQL Server data type specified: " + sqlDbType)); 854 | } 855 | } 856 | 857 | /// 858 | /// Creates a string for a SqlParameter representing the specified column. 859 | /// 860 | /// 861 | /// Object that stores the information for the column the parameter represents. 862 | /// String containing SqlParameter information of the specified column for a method call. 863 | internal static string CreateSqlParameter(Table table, Column column) 864 | { 865 | string className = FormatClassName(table.Name); 866 | var variableName = FormatCamel(className); 867 | 868 | return "new SqlParameter(\"@" + column.Name + "\", " + variableName + "." + FormatPascal(column.Name) + ")"; 869 | } 870 | } 871 | } 872 | -------------------------------------------------------------------------------- /PocoSqlGenerator/CSharpCodeGenerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Text; 6 | using System.Xml; 7 | 8 | namespace PocoSqlGenerator 9 | { 10 | internal static class CSharpCodeGenerator 11 | { 12 | public static string GenerateClassFiles(string outputDirectory, string connectionString, string storedProcedurePrefix, string targetNamespace, string daoSuffix, ArrayList tableNames) 13 | { 14 | string databaseName = ""; 15 | string csPath; 16 | csPath = Path.Combine(outputDirectory, "CS"); 17 | List
tableList = AppUtility.GetTableList(connectionString, outputDirectory, tableNames, ref databaseName); 18 | // Generate the necessary SQL and C# code for each table 19 | if (tableList.Count <= 0) return csPath; 20 | // Create the necessary directories 21 | AppUtility.CreateSubDirectory(csPath, true); 22 | foreach (Table table in tableList) 23 | { 24 | CreateModelClass(databaseName, table, targetNamespace, storedProcedurePrefix, csPath); 25 | } 26 | CreateAssemblyInfo(csPath, targetNamespace, databaseName); 27 | CreateProjectFile(csPath, targetNamespace, tableList, daoSuffix); 28 | return csPath; 29 | } 30 | 31 | public static string GenerateRepoFiles(string outputDirectory, string connectionString, string storedProcedurePrefix, string targetNamespace, string daoSuffix, ArrayList tableNames) 32 | { 33 | string databaseName = ""; 34 | string csPath = Path.Combine(outputDirectory, "Repo"); 35 | List
tableList = AppUtility.GetTableList(connectionString, outputDirectory, tableNames, ref databaseName); 36 | // Generate the necessary SQL and C# code for each table 37 | if (tableList.Count <= 0) return csPath; 38 | // Create the necessary directories 39 | AppUtility.CreateSubDirectory(csPath, true); 40 | // Create the CRUD stored procedures and data access code for each table 41 | foreach (Table table in tableList) 42 | { 43 | CreateRepoClass(databaseName, table, targetNamespace, storedProcedurePrefix, csPath); 44 | } 45 | CreateAssemblyInfo(csPath, targetNamespace, databaseName); 46 | CreateProjectFile(csPath, targetNamespace, tableList, daoSuffix); 47 | return csPath; 48 | } 49 | /// 50 | /// Creates a project file that references each generated C# code file for data access. 51 | /// 52 | /// The path where the project file should be created. 53 | /// The name of the project. 54 | /// The list of tables code files were created for. 55 | /// The suffix to append to the name of each data access class. 56 | internal static void CreateProjectFile(string path, string projectName, List
tableList, string daoSuffix) 57 | { 58 | string projectXml = AppUtility.GetResource("PocoSqlGenerator.Resources.Project.xml"); 59 | var document = new XmlDocument(); 60 | document.LoadXml(projectXml); 61 | 62 | XmlNamespaceManager namespaceManager = new XmlNamespaceManager(document.NameTable); 63 | namespaceManager.AddNamespace(String.Empty, "http://schemas.microsoft.com/developer/msbuild/2003"); 64 | namespaceManager.AddNamespace("msbuild", "http://schemas.microsoft.com/developer/msbuild/2003"); 65 | 66 | var selectSingleNode = document.SelectSingleNode("/msbuild:Project/msbuild:PropertyGroup/msbuild:ProjectGuid", namespaceManager); 67 | if (selectSingleNode != 68 | null) 69 | selectSingleNode.InnerText = "{" + Guid.NewGuid().ToString() + "}"; 70 | var singleNode = document.SelectSingleNode("/msbuild:Project/msbuild:PropertyGroup/msbuild:RootNamespace", namespaceManager); 71 | if (singleNode != 72 | null) 73 | singleNode.InnerText = projectName; 74 | var xmlNode = document.SelectSingleNode("/msbuild:Project/msbuild:PropertyGroup/msbuild:AssemblyName", namespaceManager); 75 | if (xmlNode != 76 | null) 77 | xmlNode.InnerText = projectName; 78 | 79 | XmlNode itemGroupNode = document.SelectSingleNode("/msbuild:Project/msbuild:ItemGroup[msbuild:Compile]", namespaceManager); 80 | foreach (Table table in tableList) 81 | { 82 | string className = AppUtility.FormatClassName(table.Name); 83 | 84 | XmlNode dtoCompileNode = document.CreateElement("Compile", "http://schemas.microsoft.com/developer/msbuild/2003"); 85 | XmlAttribute dtoAttribute = document.CreateAttribute("Include"); 86 | dtoAttribute.Value = className + ".cs"; 87 | if (dtoCompileNode.Attributes != null) dtoCompileNode.Attributes.Append(dtoAttribute); 88 | if (itemGroupNode != null) itemGroupNode.AppendChild(dtoCompileNode); 89 | } 90 | 91 | document.Save(Path.Combine(path, projectName + ".csproj")); 92 | } 93 | 94 | /// 95 | /// Creates the AssemblyInfo.cs file for the project. 96 | /// 97 | /// The root path of the project. 98 | /// The title of the assembly. 99 | /// The name of the database the assembly provides access to. 100 | internal static void CreateAssemblyInfo(string path, string assemblyTitle, string databaseName) 101 | { 102 | string assemblyInfo = AppUtility.GetResource("PocoSqlGenerator.Resources.AssemblyInfo.txt"); 103 | assemblyInfo.Replace("#AssemblyTitle", assemblyTitle); 104 | assemblyInfo.Replace("#DatabaseName", databaseName); 105 | 106 | string propertiesDirectory = Path.Combine(path, "Properties"); 107 | if (Directory.Exists(propertiesDirectory) == false) 108 | { 109 | Directory.CreateDirectory(propertiesDirectory); 110 | } 111 | 112 | File.WriteAllText(Path.Combine(propertiesDirectory, "AssemblyInfo.cs"), assemblyInfo); 113 | } 114 | 115 | /// 116 | /// Creates a C# Model /POCO class for all of the table's of Database. 117 | /// 118 | /// The name of the database. 119 | /// Instance of the Table class that represents the table this class will be created for. 120 | /// The namespace that the generated C# classes should contained in. 121 | /// Prefix to be appended to the name of the stored procedure. 122 | /// Path where the class should be created. 123 | internal static void CreateModelClass(string databaseName, Table table, string targetNamespace, string storedProcedurePrefix, string path) 124 | { 125 | var className = AppUtility.FormatClassName(table.Name); 126 | using (var streamWriter = new StreamWriter(Path.Combine(path, className + ".cs"))) 127 | { 128 | #region Create the header for the class 129 | streamWriter.WriteLine("using System;"); 130 | streamWriter.WriteLine(); 131 | streamWriter.WriteLine("namespace " + targetNamespace); 132 | streamWriter.WriteLine("{"); 133 | 134 | streamWriter.WriteLine("\tpublic class " + className); 135 | streamWriter.WriteLine("\t{"); 136 | #endregion 137 | 138 | #region Append the public properties 139 | streamWriter.WriteLine("\t\t#region Properties"); 140 | for (var i = 0; i < table.Columns.Count; i++) 141 | { 142 | var column = table.Columns[i]; 143 | var parameter = AppUtility.CreateMethodParameter(column); 144 | var type = parameter.Split(' ')[0]; 145 | var name = parameter.Split(' ')[1]; 146 | streamWriter.WriteLine("\t\t/// "); 147 | streamWriter.WriteLine("\t\t/// Gets or sets the " + AppUtility.FormatPascal(name) + " value."); 148 | streamWriter.WriteLine("\t\t/// "); 149 | streamWriter.WriteLine("\t\tpublic " + type + " " + AppUtility.FormatPascal(name)); 150 | streamWriter.WriteLine("\t\t{ get; set; }"); 151 | if (i < (table.Columns.Count - 1)) 152 | { 153 | streamWriter.WriteLine(); 154 | } 155 | } 156 | 157 | streamWriter.WriteLine(); 158 | streamWriter.WriteLine("\t\t#endregion"); 159 | #endregion 160 | // Close out the class and namespace 161 | streamWriter.WriteLine("\t}"); 162 | streamWriter.WriteLine("}"); 163 | } 164 | } 165 | 166 | internal static void CreateRepoClass(string databaseName, Table table, string targetNamespace, string storedProcedurePrefix, string path) 167 | { 168 | var className = AppUtility.FormatClassName(table.Name); 169 | using (var streamWriter = new StreamWriter(Path.Combine(path, className + ".cs"))) 170 | { 171 | #region Add References & Declare Class 172 | streamWriter.WriteLine("using System.Collections.Generic;"); 173 | streamWriter.WriteLine("using System.Data;"); 174 | streamWriter.WriteLine("using System.Linq;"); 175 | streamWriter.WriteLine("using Dapper;"); 176 | streamWriter.WriteLine(); 177 | streamWriter.WriteLine("namespace " + targetNamespace); 178 | streamWriter.WriteLine("{"); 179 | streamWriter.WriteLine("\t public class " + className + "Repo : BaseRepository"); 180 | streamWriter.WriteLine("\t\t {"); 181 | #endregion 182 | 183 | #region Append the access methods 184 | streamWriter.WriteLine("\t\t#region Methods"); 185 | streamWriter.WriteLine(); 186 | CreateInsertMethod(table, streamWriter); 187 | CreateUpdateMethod(table, streamWriter); 188 | CreateSelectMethod(table, streamWriter); 189 | CreateSelectAllMethod(table, streamWriter); 190 | CreateSelectAllByMethods(table, storedProcedurePrefix, streamWriter); 191 | #endregion 192 | 193 | streamWriter.WriteLine(); 194 | streamWriter.WriteLine("\t\t#endregion"); 195 | 196 | // Close out the class and namespace 197 | streamWriter.WriteLine("\t\t}"); 198 | streamWriter.WriteLine("}"); 199 | } 200 | } 201 | 202 | /// 203 | /// Creates a string that represents the insert functionality of the data access class. 204 | /// 205 | /// The Table instance that this method will be created for. 206 | /// The StreamWriter instance that will be used to create the method. 207 | private static void CreateInsertMethod(Table table, TextWriter streamWriter) 208 | { 209 | var className = AppUtility.FormatClassName(table.Name); 210 | var variableName = "a" + className; 211 | 212 | // Append the method header 213 | streamWriter.WriteLine("\t\t/// "); 214 | streamWriter.WriteLine("\t\t/// Saves a record to the " + table.Name + " table."); 215 | streamWriter.WriteLine("\t\t/// returns True if value saved successfullyelse false"); 216 | streamWriter.WriteLine("\t\t/// Throw exception with message value 'EXISTS' if the data is duplicate"); 217 | streamWriter.WriteLine("\t\t/// "); 218 | streamWriter.WriteLine("\t\tpublic bool Insert(" + className + " " + variableName + ")"); 219 | streamWriter.WriteLine("\t\t{"); 220 | streamWriter.WriteLine("\t\t var blResult = false;"); 221 | streamWriter.WriteLine("\t\t\t using (var vConn = OpenConnection())"); 222 | streamWriter.WriteLine("\t\t\t\t {"); 223 | streamWriter.WriteLine("\t\t\t\t var vParams = new DynamicParameters();"); 224 | foreach (var column in table.Columns) 225 | { streamWriter.WriteLine("\t\t\t\t\t vParams.Add(\"@" + column.Name + "\"," + variableName + "." + AppUtility.FormatPascal(column.Name) + ");"); } 226 | streamWriter.WriteLine("\t\t\t\t\t int iResult = vConn.Execute(\"" + table.Name + "Insert\", vParams, commandType: CommandType.StoredProcedure);"); 227 | streamWriter.WriteLine("\t\t\t if (iResult == -1) blResult = true;"); 228 | streamWriter.WriteLine("\t\t\t }"); 229 | streamWriter.WriteLine("\t\t\t return blResult;"); 230 | streamWriter.WriteLine("\t\t}"); 231 | streamWriter.WriteLine(); 232 | } 233 | 234 | /// 235 | /// Creates a string that represents the update functionality of the data access class. 236 | /// 237 | /// The Table instance that this method will be created for. 238 | /// The StreamWriter instance that will be used to create the method. 239 | private static void CreateUpdateMethod(Table table, TextWriter streamWriter) 240 | { 241 | if (table.PrimaryKeys.Count <= 0 || table.Columns.Count == table.PrimaryKeys.Count || 242 | table.Columns.Count == table.ForeignKeys.Count) return; 243 | var className = AppUtility.FormatClassName(table.Name); 244 | var variableName = "a" + className; 245 | 246 | // Append the method header 247 | streamWriter.WriteLine("\t\t/// "); 248 | streamWriter.WriteLine("\t\t/// Updates record to the " + table.Name + " table."); 249 | streamWriter.WriteLine("\t\t/// returns True if value saved successfullyelse false"); 250 | streamWriter.WriteLine("\t\t/// Throw exception with message value 'EXISTS' if the data is duplicate"); 251 | streamWriter.WriteLine("\t\t/// "); 252 | streamWriter.WriteLine("\t\tpublic bool Update(" + className + " " + variableName + ")"); 253 | streamWriter.WriteLine("\t\t{"); 254 | streamWriter.WriteLine("\t\t var blResult = false;"); 255 | streamWriter.WriteLine("\t\t\t using (var vConn = OpenConnection())"); 256 | streamWriter.WriteLine("\t\t\t\t {"); 257 | streamWriter.WriteLine("\t\t\t\t var vParams = new DynamicParameters();"); 258 | foreach (var column in table.Columns) 259 | { streamWriter.WriteLine("\t\t\t\t\t vParams.Add(\"@" + column.Name + "\"," + variableName + "." + AppUtility.FormatPascal(column.Name) + ");"); } 260 | streamWriter.WriteLine("\t\t\t\t\t int iResult = vConn.Execute(\"" + table.Name + "Update\", vParams, commandType: CommandType.StoredProcedure);"); 261 | streamWriter.WriteLine("\t\t\t\t if (iResult == -1) blResult = true;"); 262 | streamWriter.WriteLine("\t\t\t\t }"); 263 | streamWriter.WriteLine("\t\t\treturn blResult;"); 264 | streamWriter.WriteLine("\t\t}"); 265 | streamWriter.WriteLine(); 266 | } 267 | 268 | /// 269 | /// Creates a string that represents the "select" functionality of the data access class. 270 | /// 271 | /// The Table instance that this method will be created for. 272 | /// The StreamWriter instance that will be used to create the method. 273 | private static void CreateSelectMethod(Table table, TextWriter streamWriter) 274 | { 275 | if (table.PrimaryKeys.Count <= 0 || table.Columns.Count == table.PrimaryKeys.Count || 276 | table.Columns.Count == table.ForeignKeys.Count) return; 277 | var className = AppUtility.FormatClassName(table.Name); 278 | var variableName = "a" + table.PrimaryKeys[0].Name; 279 | 280 | // Append the method header 281 | streamWriter.WriteLine("\t\t/// "); 282 | streamWriter.WriteLine("\t\t/// Selects the Single object of " + table.Name + " table."); 283 | streamWriter.WriteLine("\t\t/// "); 284 | streamWriter.WriteLine("\t\tpublic "+ className + " Get"+ className +"(" + AppUtility.GetCsType(table.PrimaryKeys[0]) + " " + variableName + ")"); 285 | streamWriter.WriteLine("\t\t{"); 286 | streamWriter.WriteLine("\t\t\t using (var vConn = OpenConnection())"); 287 | streamWriter.WriteLine("\t\t\t\t {"); 288 | streamWriter.WriteLine("\t\t\t\t var vParams = new DynamicParameters();"); 289 | streamWriter.WriteLine("\t\t\t\t\t vParams.Add(\"@" + table.PrimaryKeys[0].Name + "\"," + variableName + ");"); 290 | streamWriter.WriteLine("\t\t\t\t\t return vConn.Query<"+ className + ">(\"" + table.Name + "Select\", vParams, commandType: CommandType.StoredProcedure);"); 291 | streamWriter.WriteLine("\t\t\t\t }"); 292 | streamWriter.WriteLine("\t\t}"); 293 | streamWriter.WriteLine(); 294 | 295 | 296 | } 297 | 298 | /// 299 | /// Creates a string that represents the select functionality of the data access class. 300 | /// 301 | /// The Table instance that this method will be created for. 302 | /// The StreamWriter instance that will be used to create the method. 303 | private static void CreateSelectAllMethod(Table table, TextWriter streamWriter) 304 | { 305 | if (table.Columns.Count == table.PrimaryKeys.Count || table.Columns.Count == table.ForeignKeys.Count) 306 | return; 307 | var className = AppUtility.FormatClassName(table.Name); 308 | // Append the method header 309 | streamWriter.WriteLine("\t\t/// "); 310 | streamWriter.WriteLine("\t\t/// Selects all records from the " + table.Name + " table."); 311 | streamWriter.WriteLine("\t\t/// "); 312 | streamWriter.WriteLine("\t\t public IEnumerable<" + className + "> SelectAll()"); 313 | streamWriter.WriteLine("\t\t{"); 314 | // Append the stored procedure execution 315 | streamWriter.WriteLine("\t\t\t using (var vConn = OpenConnection())"); 316 | streamWriter.WriteLine("\t\t\t{"); 317 | streamWriter.WriteLine("\t\t\t\t return vConn.Query<" + className + ">(\"" + table.Name + "SelectAll\", commandType: CommandType.StoredProcedure).ToList();"); 318 | streamWriter.WriteLine("\t\t\t}"); 319 | streamWriter.WriteLine("\t\t}"); 320 | } 321 | 322 | /// 323 | /// Creates a string that represents the "select by" functionality of the data access class. 324 | /// 325 | /// The Table instance that this method will be created for. 326 | /// The prefix that is used on the stored procedure that this method will call. 327 | /// The StreamWriter instance that will be used to create the method. 328 | private static void CreateSelectAllByMethods(Table table, string storedProcedurePrefix, TextWriter streamWriter) 329 | { 330 | string className = AppUtility.FormatClassName(table.Name); 331 | string dtoVariableName = AppUtility.FormatCamel(className); 332 | 333 | // Create a stored procedure for each foreign key 334 | foreach (List compositeKeyList in table.ForeignKeys.Values) 335 | { 336 | // Create the stored procedure name 337 | StringBuilder stringBuilder = new StringBuilder(255); 338 | stringBuilder.Append("SelectAllBy"); 339 | for (var i = 0; i < compositeKeyList.Count; i++) 340 | { 341 | var column = compositeKeyList[i]; 342 | 343 | if (i > 0) 344 | { 345 | stringBuilder.Append("_" + AppUtility.FormatPascal(column.Name)); 346 | } 347 | else 348 | { 349 | stringBuilder.Append(AppUtility.FormatPascal(column.Name)); 350 | } 351 | } 352 | string methodName = stringBuilder.ToString(); 353 | string procedureName = storedProcedurePrefix + table.Name + methodName; 354 | 355 | // Create the select function based on keys 356 | // Append the method header 357 | streamWriter.WriteLine("\t\t/// "); 358 | streamWriter.WriteLine("\t\t/// Selects all records from the " + table.Name + " table by a foreign key."); 359 | streamWriter.WriteLine("\t\t/// "); 360 | 361 | streamWriter.Write("\t\tpublic List<" + className + "> " + methodName + "("); 362 | for (int i = 0; i < compositeKeyList.Count; i++) 363 | { 364 | Column column = compositeKeyList[i]; 365 | streamWriter.Write(AppUtility.CreateMethodParameter(column)); 366 | if (i < (compositeKeyList.Count - 1)) 367 | { 368 | streamWriter.Write(","); 369 | } 370 | } 371 | streamWriter.WriteLine(")"); 372 | streamWriter.WriteLine("\t\t{"); 373 | 374 | streamWriter.WriteLine("\t\t\t using (var vConn = OpenConnection())"); 375 | streamWriter.WriteLine("\t\t\t\t {"); 376 | streamWriter.WriteLine("\t\t\t\t var vParams = new DynamicParameters();"); 377 | for (var i = 0; i < compositeKeyList.Count; i++) 378 | { 379 | var column = compositeKeyList[i]; 380 | streamWriter.WriteLine("\t\t\t\t\t vParams.Add(\"@" + column.Name + "\"," + AppUtility.FormatCamel(column.Name) + ");"); 381 | } 382 | streamWriter.WriteLine("\t\t\t\t return vConn.Query<" + className + ">(\"" + table.Name + "SelectAll\", vParams, commandType: CommandType.StoredProcedure).ToList();"); 383 | streamWriter.WriteLine("\t\t\t\t }"); 384 | streamWriter.WriteLine("\t\t}"); 385 | streamWriter.WriteLine(); 386 | } 387 | } 388 | 389 | } 390 | } 391 | -------------------------------------------------------------------------------- /PocoSqlGenerator/MainForm.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace PocoSqlGenerator 2 | { 3 | partial class MainForm 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); 32 | this.btnSQLNClasses = new System.Windows.Forms.Button(); 33 | this.btnCancel = new System.Windows.Forms.Button(); 34 | this.btnGenClasses = new System.Windows.Forms.Button(); 35 | this.cbxMultipleFiles = new System.Windows.Forms.CheckBox(); 36 | this.txtConnectionString = new System.Windows.Forms.TextBox(); 37 | this.lblConString = new System.Windows.Forms.Label(); 38 | this.btnGenSQL = new System.Windows.Forms.Button(); 39 | this.cboDatabases = new System.Windows.Forms.ComboBox(); 40 | this.sqlServerGroupBox = new System.Windows.Forms.GroupBox(); 41 | this.lblSelectDataBase = new System.Windows.Forms.Label(); 42 | this.label6 = new System.Windows.Forms.Label(); 43 | this.label5 = new System.Windows.Forms.Label(); 44 | this.txtSPPrefix = new System.Windows.Forms.TextBox(); 45 | this.txtgrantUser = new System.Windows.Forms.TextBox(); 46 | this.txtNamespace = new System.Windows.Forms.TextBox(); 47 | this.label2 = new System.Windows.Forms.Label(); 48 | this.txtQueryFilePath = new System.Windows.Forms.TextBox(); 49 | this.label4 = new System.Windows.Forms.Label(); 50 | this.txtFilesPath = new System.Windows.Forms.TextBox(); 51 | this.label3 = new System.Windows.Forms.Label(); 52 | this.label7 = new System.Windows.Forms.Label(); 53 | this.grpOutPut = new System.Windows.Forms.GroupBox(); 54 | this.groupBox1 = new System.Windows.Forms.GroupBox(); 55 | this.btnGetDBList = new System.Windows.Forms.Button(); 56 | this.cblTableList = new System.Windows.Forms.CheckedListBox(); 57 | this.sqlServerGroupBox.SuspendLayout(); 58 | this.grpOutPut.SuspendLayout(); 59 | this.groupBox1.SuspendLayout(); 60 | this.SuspendLayout(); 61 | // 62 | // btnSQLNClasses 63 | // 64 | this.btnSQLNClasses.Location = new System.Drawing.Point(410, 304); 65 | this.btnSQLNClasses.Name = "btnSQLNClasses"; 66 | this.btnSQLNClasses.Size = new System.Drawing.Size(174, 24); 67 | this.btnSQLNClasses.TabIndex = 18; 68 | this.btnSQLNClasses.Text = "Generate &Both SQL && Classes"; 69 | this.btnSQLNClasses.UseVisualStyleBackColor = true; 70 | this.btnSQLNClasses.Click += new System.EventHandler(this.btnSQLNClasses_Click); 71 | // 72 | // btnCancel 73 | // 74 | this.btnCancel.Location = new System.Drawing.Point(590, 304); 75 | this.btnCancel.Name = "btnCancel"; 76 | this.btnCancel.Size = new System.Drawing.Size(94, 24); 77 | this.btnCancel.TabIndex = 16; 78 | this.btnCancel.Text = "&Close"; 79 | this.btnCancel.UseVisualStyleBackColor = true; 80 | this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); 81 | // 82 | // btnGenClasses 83 | // 84 | this.btnGenClasses.Location = new System.Drawing.Point(289, 304); 85 | this.btnGenClasses.Name = "btnGenClasses"; 86 | this.btnGenClasses.Size = new System.Drawing.Size(115, 24); 87 | this.btnGenClasses.TabIndex = 15; 88 | this.btnGenClasses.Text = "&Generate Classes"; 89 | this.btnGenClasses.UseVisualStyleBackColor = true; 90 | this.btnGenClasses.Click += new System.EventHandler(this.btnGenClasses_Click); 91 | // 92 | // cbxMultipleFiles 93 | // 94 | this.cbxMultipleFiles.FlatStyle = System.Windows.Forms.FlatStyle.System; 95 | this.cbxMultipleFiles.Location = new System.Drawing.Point(14, 39); 96 | this.cbxMultipleFiles.Name = "cbxMultipleFiles"; 97 | this.cbxMultipleFiles.Size = new System.Drawing.Size(318, 24); 98 | this.cbxMultipleFiles.TabIndex = 8; 99 | this.cbxMultipleFiles.Text = "Create multiple files for stored procedures/ Queries"; 100 | // 101 | // txtConnectionString 102 | // 103 | this.txtConnectionString.Location = new System.Drawing.Point(128, 19); 104 | this.txtConnectionString.Name = "txtConnectionString"; 105 | this.txtConnectionString.Size = new System.Drawing.Size(420, 20); 106 | this.txtConnectionString.TabIndex = 3; 107 | // 108 | // lblConString 109 | // 110 | this.lblConString.AutoSize = true; 111 | this.lblConString.Location = new System.Drawing.Point(11, 22); 112 | this.lblConString.Name = "lblConString"; 113 | this.lblConString.Size = new System.Drawing.Size(116, 13); 114 | this.lblConString.TabIndex = 3; 115 | this.lblConString.Text = "Connection String :"; 116 | // 117 | // btnGenSQL 118 | // 119 | this.btnGenSQL.Location = new System.Drawing.Point(168, 304); 120 | this.btnGenSQL.Name = "btnGenSQL"; 121 | this.btnGenSQL.Size = new System.Drawing.Size(115, 24); 122 | this.btnGenSQL.TabIndex = 17; 123 | this.btnGenSQL.Text = "Generate &SQL"; 124 | this.btnGenSQL.UseVisualStyleBackColor = true; 125 | this.btnGenSQL.Click += new System.EventHandler(this.btnGenSQL_Click); 126 | // 127 | // cboDatabases 128 | // 129 | this.cboDatabases.FormattingEnabled = true; 130 | this.cboDatabases.Location = new System.Drawing.Point(119, 19); 131 | this.cboDatabases.Name = "cboDatabases"; 132 | this.cboDatabases.Size = new System.Drawing.Size(283, 21); 133 | this.cboDatabases.TabIndex = 14; 134 | this.cboDatabases.SelectedIndexChanged += new System.EventHandler(this.cboDatabases_SelectedIndexChanged); 135 | // 136 | // sqlServerGroupBox 137 | // 138 | this.sqlServerGroupBox.Controls.Add(this.cboDatabases); 139 | this.sqlServerGroupBox.Controls.Add(this.lblSelectDataBase); 140 | this.sqlServerGroupBox.Controls.Add(this.label6); 141 | this.sqlServerGroupBox.Controls.Add(this.label5); 142 | this.sqlServerGroupBox.Controls.Add(this.txtSPPrefix); 143 | this.sqlServerGroupBox.Controls.Add(this.txtgrantUser); 144 | this.sqlServerGroupBox.Location = new System.Drawing.Point(6, 93); 145 | this.sqlServerGroupBox.Name = "sqlServerGroupBox"; 146 | this.sqlServerGroupBox.Size = new System.Drawing.Size(414, 110); 147 | this.sqlServerGroupBox.TabIndex = 10; 148 | this.sqlServerGroupBox.TabStop = false; 149 | this.sqlServerGroupBox.Text = "SQL Server"; 150 | // 151 | // lblSelectDataBase 152 | // 153 | this.lblSelectDataBase.AutoSize = true; 154 | this.lblSelectDataBase.Location = new System.Drawing.Point(5, 22); 155 | this.lblSelectDataBase.Name = "lblSelectDataBase"; 156 | this.lblSelectDataBase.Size = new System.Drawing.Size(109, 13); 157 | this.lblSelectDataBase.TabIndex = 13; 158 | this.lblSelectDataBase.Text = "Select Database :"; 159 | // 160 | // label6 161 | // 162 | this.label6.AutoSize = true; 163 | this.label6.Location = new System.Drawing.Point(5, 84); 164 | this.label6.Name = "label6"; 165 | this.label6.Size = new System.Drawing.Size(67, 13); 166 | this.label6.TabIndex = 12; 167 | this.label6.Text = "SP Prefix :"; 168 | // 169 | // label5 170 | // 171 | this.label5.AutoSize = true; 172 | this.label5.Location = new System.Drawing.Point(5, 54); 173 | this.label5.Name = "label5"; 174 | this.label5.Size = new System.Drawing.Size(76, 13); 175 | this.label5.TabIndex = 11; 176 | this.label5.Text = "Grant User :"; 177 | // 178 | // txtSPPrefix 179 | // 180 | this.txtSPPrefix.Location = new System.Drawing.Point(119, 81); 181 | this.txtSPPrefix.Name = "txtSPPrefix"; 182 | this.txtSPPrefix.Size = new System.Drawing.Size(283, 20); 183 | this.txtSPPrefix.TabIndex = 7; 184 | // 185 | // txtgrantUser 186 | // 187 | this.txtgrantUser.Location = new System.Drawing.Point(119, 51); 188 | this.txtgrantUser.Name = "txtgrantUser"; 189 | this.txtgrantUser.Size = new System.Drawing.Size(283, 20); 190 | this.txtgrantUser.TabIndex = 6; 191 | // 192 | // txtNamespace 193 | // 194 | this.txtNamespace.Location = new System.Drawing.Point(128, 67); 195 | this.txtNamespace.Name = "txtNamespace"; 196 | this.txtNamespace.Size = new System.Drawing.Size(283, 20); 197 | this.txtNamespace.TabIndex = 14; 198 | // 199 | // label2 200 | // 201 | this.label2.AutoSize = true; 202 | this.label2.Location = new System.Drawing.Point(423, 44); 203 | this.label2.Name = "label2"; 204 | this.label2.Size = new System.Drawing.Size(93, 13); 205 | this.label2.TabIndex = 9; 206 | this.label2.Text = "Select Tables :"; 207 | // 208 | // txtQueryFilePath 209 | // 210 | this.txtQueryFilePath.Location = new System.Drawing.Point(119, 43); 211 | this.txtQueryFilePath.Name = "txtQueryFilePath"; 212 | this.txtQueryFilePath.Size = new System.Drawing.Size(283, 20); 213 | this.txtQueryFilePath.TabIndex = 7; 214 | // 215 | // label4 216 | // 217 | this.label4.AutoSize = true; 218 | this.label4.Location = new System.Drawing.Point(5, 46); 219 | this.label4.Name = "label4"; 220 | this.label4.Size = new System.Drawing.Size(100, 13); 221 | this.label4.TabIndex = 6; 222 | this.label4.Text = "SQL Query File :"; 223 | // 224 | // txtFilesPath 225 | // 226 | this.txtFilesPath.Location = new System.Drawing.Point(119, 16); 227 | this.txtFilesPath.Name = "txtFilesPath"; 228 | this.txtFilesPath.Size = new System.Drawing.Size(283, 20); 229 | this.txtFilesPath.TabIndex = 5; 230 | // 231 | // label3 232 | // 233 | this.label3.AutoSize = true; 234 | this.label3.Location = new System.Drawing.Point(5, 19); 235 | this.label3.Name = "label3"; 236 | this.label3.Size = new System.Drawing.Size(105, 13); 237 | this.label3.TabIndex = 4; 238 | this.label3.Text = "Class Files Path :"; 239 | // 240 | // label7 241 | // 242 | this.label7.AutoSize = true; 243 | this.label7.Location = new System.Drawing.Point(11, 70); 244 | this.label7.Name = "label7"; 245 | this.label7.Size = new System.Drawing.Size(115, 13); 246 | this.label7.TabIndex = 15; 247 | this.label7.Text = "Class Namespace :"; 248 | // 249 | // grpOutPut 250 | // 251 | this.grpOutPut.Controls.Add(this.txtQueryFilePath); 252 | this.grpOutPut.Controls.Add(this.label4); 253 | this.grpOutPut.Controls.Add(this.txtFilesPath); 254 | this.grpOutPut.Controls.Add(this.label3); 255 | this.grpOutPut.Location = new System.Drawing.Point(6, 209); 256 | this.grpOutPut.Name = "grpOutPut"; 257 | this.grpOutPut.Size = new System.Drawing.Size(414, 70); 258 | this.grpOutPut.TabIndex = 8; 259 | this.grpOutPut.TabStop = false; 260 | this.grpOutPut.Text = "Output Details"; 261 | this.grpOutPut.Visible = false; 262 | // 263 | // groupBox1 264 | // 265 | this.groupBox1.Controls.Add(this.btnGetDBList); 266 | this.groupBox1.Controls.Add(this.label7); 267 | this.groupBox1.Controls.Add(this.grpOutPut); 268 | this.groupBox1.Controls.Add(this.txtNamespace); 269 | this.groupBox1.Controls.Add(this.label2); 270 | this.groupBox1.Controls.Add(this.cblTableList); 271 | this.groupBox1.Controls.Add(this.sqlServerGroupBox); 272 | this.groupBox1.Controls.Add(this.cbxMultipleFiles); 273 | this.groupBox1.Controls.Add(this.txtConnectionString); 274 | this.groupBox1.Controls.Add(this.lblConString); 275 | this.groupBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); 276 | this.groupBox1.Location = new System.Drawing.Point(9, 9); 277 | this.groupBox1.Name = "groupBox1"; 278 | this.groupBox1.Size = new System.Drawing.Size(675, 289); 279 | this.groupBox1.TabIndex = 14; 280 | this.groupBox1.TabStop = false; 281 | // 282 | // btnGetDBList 283 | // 284 | this.btnGetDBList.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); 285 | this.btnGetDBList.Location = new System.Drawing.Point(554, 16); 286 | this.btnGetDBList.Name = "btnGetDBList"; 287 | this.btnGetDBList.Size = new System.Drawing.Size(111, 24); 288 | this.btnGetDBList.TabIndex = 19; 289 | this.btnGetDBList.Text = "Get &Database List"; 290 | this.btnGetDBList.UseVisualStyleBackColor = true; 291 | this.btnGetDBList.Click += new System.EventHandler(this.btnGetDBList_Click); 292 | // 293 | // cblTableList 294 | // 295 | this.cblTableList.FormattingEnabled = true; 296 | this.cblTableList.Location = new System.Drawing.Point(426, 67); 297 | this.cblTableList.Name = "cblTableList"; 298 | this.cblTableList.Size = new System.Drawing.Size(239, 214); 299 | this.cblTableList.TabIndex = 8; 300 | // 301 | // MainForm 302 | // 303 | this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); 304 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 305 | this.ClientSize = new System.Drawing.Size(692, 336); 306 | this.Controls.Add(this.btnSQLNClasses); 307 | this.Controls.Add(this.btnCancel); 308 | this.Controls.Add(this.btnGenClasses); 309 | this.Controls.Add(this.btnGenSQL); 310 | this.Controls.Add(this.groupBox1); 311 | this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; 312 | this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); 313 | this.Name = "MainForm"; 314 | this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; 315 | this.Text = "POCO SQL Generator"; 316 | this.Load += new System.EventHandler(this.MainForm_Load); 317 | this.sqlServerGroupBox.ResumeLayout(false); 318 | this.sqlServerGroupBox.PerformLayout(); 319 | this.grpOutPut.ResumeLayout(false); 320 | this.grpOutPut.PerformLayout(); 321 | this.groupBox1.ResumeLayout(false); 322 | this.groupBox1.PerformLayout(); 323 | this.ResumeLayout(false); 324 | 325 | } 326 | 327 | #endregion 328 | 329 | private System.Windows.Forms.Button btnSQLNClasses; 330 | private System.Windows.Forms.Button btnCancel; 331 | private System.Windows.Forms.Button btnGenClasses; 332 | private System.Windows.Forms.CheckBox cbxMultipleFiles; 333 | private System.Windows.Forms.TextBox txtConnectionString; 334 | private System.Windows.Forms.Label lblConString; 335 | private System.Windows.Forms.Button btnGenSQL; 336 | private System.Windows.Forms.ComboBox cboDatabases; 337 | private System.Windows.Forms.GroupBox sqlServerGroupBox; 338 | private System.Windows.Forms.Label lblSelectDataBase; 339 | private System.Windows.Forms.Label label6; 340 | private System.Windows.Forms.Label label5; 341 | private System.Windows.Forms.TextBox txtSPPrefix; 342 | private System.Windows.Forms.TextBox txtgrantUser; 343 | private System.Windows.Forms.TextBox txtNamespace; 344 | private System.Windows.Forms.Label label2; 345 | private System.Windows.Forms.TextBox txtQueryFilePath; 346 | private System.Windows.Forms.Label label4; 347 | private System.Windows.Forms.TextBox txtFilesPath; 348 | private System.Windows.Forms.Label label3; 349 | private System.Windows.Forms.Label label7; 350 | private System.Windows.Forms.GroupBox grpOutPut; 351 | private System.Windows.Forms.GroupBox groupBox1; 352 | private System.Windows.Forms.CheckedListBox cblTableList; 353 | private System.Windows.Forms.Button btnGetDBList; 354 | } 355 | } 356 | 357 | -------------------------------------------------------------------------------- /PocoSqlGenerator/MainForm.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Collections; 4 | using System.Data; 5 | using System.Windows.Forms; 6 | using System.Data.SqlClient; 7 | using System.Configuration; 8 | 9 | namespace PocoSqlGenerator 10 | { 11 | public partial class MainForm : Form 12 | { 13 | #region Module Variables 14 | string mSSqlDatabase = ""; 15 | #endregion 16 | #region Constructors 17 | public MainForm() 18 | { 19 | InitializeComponent(); 20 | } 21 | #endregion 22 | 23 | #region Event Handlers 24 | private void btnGetDBList_Click(object sender, EventArgs e) 25 | { 26 | String conxString = txtConnectionString.Text.Trim(); 27 | using (var sqlConx = new SqlConnection(conxString)) 28 | { 29 | sqlConx.Open(); 30 | var tblDatabases = sqlConx.GetSchema("Databases"); 31 | sqlConx.Close(); 32 | foreach (DataRow row in tblDatabases.Rows) 33 | { 34 | cboDatabases.Items.Add(row["database_name"]); 35 | } 36 | } 37 | cboDatabases.Items.Add("Select Database"); 38 | cboDatabases.SelectedIndex = cboDatabases.Items.Count - 1; 39 | } 40 | 41 | private void btnGenSQL_Click(object sender, EventArgs e) 42 | { 43 | try 44 | { 45 | GenerateSQLScripts(); 46 | MessageBox.Show("SQL file(s) created Successfully at path mentioned in 'SQL Query File'", "Success"); 47 | grpOutPut.Visible = true; 48 | } 49 | catch (Exception ex) 50 | { 51 | MessageBox.Show("Error : " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 52 | } 53 | } 54 | 55 | private void btnGenClasses_Click(object sender, EventArgs e) 56 | { 57 | try 58 | { 59 | GenerateCSharpClasses(); 60 | MessageBox.Show("Class file(s) created Successfully at path mentioned in 'Class Files Path'", "Success"); 61 | grpOutPut.Visible = true; 62 | } 63 | catch (Exception ex) 64 | { 65 | MessageBox.Show("Error : " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 66 | } 67 | } 68 | 69 | private void btnSQLNClasses_Click(object sender, EventArgs e) 70 | { 71 | try 72 | { 73 | GenerateSQLScripts(); 74 | GenerateCSharpClasses(); 75 | MessageBox.Show("SQL file(s) & Class file(s) created Successfully at path mentioned in 'SQL Query File' & 'Class Files Path' respectively", "Success"); 76 | grpOutPut.Visible = true; 77 | } 78 | catch (Exception ex) 79 | { 80 | MessageBox.Show("Error : " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 81 | } 82 | } 83 | 84 | private void btnCancel_Click(object sender, EventArgs e) 85 | { 86 | Close(); 87 | } 88 | 89 | private void cboDatabases_SelectedIndexChanged(object sender, EventArgs e) 90 | { 91 | try 92 | { 93 | if (cboDatabases.Text.Trim() != "Select Database") 94 | { 95 | //if ((cboCustomerName.SelectedValue.ToString().Trim() != "System.Data.DataRowView")) 96 | mSSqlDatabase = cboDatabases.Text.Trim(); 97 | string strConn = txtConnectionString.Text.Trim() + ";Initial Catalog=" + mSSqlDatabase; 98 | SqlConnection cbConnection = null; 99 | try 100 | { 101 | DataTable dtSchemaTable = new DataTable("Tables"); 102 | using (cbConnection = new SqlConnection(strConn)) 103 | { 104 | SqlCommand cmdCommand = cbConnection.CreateCommand(); 105 | cmdCommand.CommandText = "select table_name as Name from INFORMATION_SCHEMA.Tables where TABLE_TYPE ='BASE TABLE'"; 106 | cbConnection.Open(); 107 | dtSchemaTable.Load(cmdCommand.ExecuteReader(CommandBehavior.CloseConnection)); 108 | } 109 | cblTableList.Items.Clear(); 110 | for (int iCount = 0; iCount < dtSchemaTable.Rows.Count; iCount++) 111 | { 112 | cblTableList.Items.Add(dtSchemaTable.Rows[iCount][0].ToString()); 113 | } 114 | } 115 | finally 116 | { 117 | // ReSharper disable once PossibleNullReferenceException 118 | cbConnection.Close(); 119 | } 120 | } 121 | } 122 | catch (Exception ex) 123 | { 124 | MessageBox.Show("Error : " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 125 | } 126 | } 127 | 128 | private void MainForm_Load(object sender, EventArgs e) 129 | { 130 | txtConnectionString.Text = ConfigurationManager.AppSettings["ConnString"]; 131 | } 132 | 133 | #endregion 134 | 135 | #region Private Methods 136 | private string CreateOutputDir(string aSDirName) 137 | { 138 | string sRootDirPath = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + aSDirName; 139 | if (!Directory.Exists(sRootDirPath)) Directory.CreateDirectory(sRootDirPath); 140 | return sRootDirPath; 141 | } 142 | private void GenerateSQLScripts() 143 | { 144 | string sFolderPath = CreateOutputDir(txtNamespace.Text.Trim() != "" ? txtNamespace.Text.Trim() : mSSqlDatabase); 145 | var objTableNames = new ArrayList(); 146 | string sConString = txtConnectionString.Text + ";Initial Catalog=" + mSSqlDatabase; 147 | for (int iTableCount = 0; iTableCount < cblTableList.CheckedItems.Count; iTableCount++) 148 | { 149 | objTableNames.Add(cblTableList.CheckedItems[iTableCount].ToString()); 150 | } 151 | txtQueryFilePath.Text = SqlScriptGenerator.GenerateSQLFiles(sFolderPath, sConString, txtgrantUser.Text.Trim(), txtSPPrefix.Text.Trim(), cbxMultipleFiles.Checked, objTableNames); 152 | } 153 | private void GenerateCSharpClasses() 154 | { 155 | string sFolderPath, sNameSpace; 156 | if (txtNamespace.Text.Trim() != "") 157 | { 158 | sFolderPath = CreateOutputDir(txtNamespace.Text.Trim()); 159 | sNameSpace = txtNamespace.Text.Trim(); 160 | } 161 | else 162 | { 163 | sFolderPath = CreateOutputDir(mSSqlDatabase); 164 | sNameSpace = mSSqlDatabase; 165 | } 166 | CreateBaseRepoClass(sFolderPath + "\\BaseRepository.cs", sNameSpace); 167 | var objTableNames = new ArrayList(); 168 | string sConString = ""; 169 | sConString = txtConnectionString.Text + ";Initial Catalog=" + mSSqlDatabase; 170 | 171 | for (int iTableCount = 0; iTableCount < cblTableList.CheckedItems.Count; iTableCount++) 172 | { 173 | objTableNames.Add(cblTableList.CheckedItems[iTableCount].ToString()); 174 | } 175 | txtFilesPath.Text = CSharpCodeGenerator.GenerateClassFiles(sFolderPath, sConString, txtSPPrefix.Text.Trim(), sNameSpace, "", objTableNames); 176 | CSharpCodeGenerator.GenerateRepoFiles(sFolderPath, sConString, txtSPPrefix.Text.Trim(), sNameSpace, "", objTableNames); 177 | 178 | } 179 | private void CreateBaseRepoClass(string aSFilePath, string targetNamespace) 180 | { 181 | using (var streamWriter = new StreamWriter(aSFilePath)) 182 | { 183 | #region Add Referances 184 | 185 | streamWriter.WriteLine("using System;"); 186 | streamWriter.WriteLine("using System.Data;"); 187 | streamWriter.WriteLine("using System.Data.SqlClient;"); 188 | streamWriter.WriteLine("using System.Linq;"); 189 | streamWriter.WriteLine("using System.Web.Configuration;"); 190 | streamWriter.WriteLine(); 191 | streamWriter.WriteLine("namespace " + targetNamespace); 192 | streamWriter.WriteLine("{"); 193 | 194 | #endregion 195 | 196 | #region Create Base Repository Class 197 | 198 | streamWriter.WriteLine("\t public abstract class BaseRepository "); 199 | streamWriter.WriteLine("\t\t {"); 200 | streamWriter.WriteLine( 201 | "\t\t\t protected static void SetIdentity(IDbConnection connection, Action setId) "); 202 | streamWriter.WriteLine("\t\t\t {"); 203 | streamWriter.WriteLine( 204 | "\t\t\t dynamic identity = connection.Query(\"SELECT @@IDENTITY AS Id\").Single(); "); 205 | streamWriter.WriteLine("\t\t\t T newId = (T)identity.Id; "); 206 | streamWriter.WriteLine("\t\t\t setId(newId); "); 207 | streamWriter.WriteLine("\t\t\t }"); 208 | 209 | streamWriter.WriteLine( 210 | "\t\t\t protected static IDbConnection OpenConnection() "); 211 | streamWriter.WriteLine("\t\t\t {"); 212 | streamWriter.WriteLine( 213 | "\t\t\t IDbConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings[\"DBConString\"].ConnectionString); "); 214 | streamWriter.WriteLine("\t\t\t connection.Open(); "); 215 | streamWriter.WriteLine("\t\t\t return connection; "); 216 | streamWriter.WriteLine("\t\t\t }"); 217 | streamWriter.WriteLine("\t\t }"); 218 | 219 | #endregion 220 | } 221 | } 222 | #endregion 223 | 224 | 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /PocoSqlGenerator/MainForm.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | 122 | 123 | AAABAAMAEBAAAAAAIABoBAAANgAAACAgAAAAACAAqBAAAJ4EAAAwMAAAAAAgAKglAABGFQAAKAAAABAA 124 | AAAgAAAAAQAgAAAAAABABAAAAAAAAAAAAAAAAAAAAAAAAP///wH///8B////Af///wH///8B////AbWg 125 | gyHhqGSn4ahkp7SfgyH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8BqJuMDdil 126 | an/zq1bz/65P//+uT//0q1bz2KVqf6ibjA3///8B////Af///wH///8B////Af///wGbm5sDzaNyWe2q 127 | W9/+rU///65P//SsWP/0rFn//65P//6tT//tqlvfzaNzWZubmwP///8B////Af///wHConsz5qlgweuv 128 | af/jy6X//a1Q//6tT//j6N3/4+ba//6tT///rk//5MOW/+q1dP/mqWDBwqJ7M////wH///8B6ale3/+u 129 | T//5rVT/5t7H/+PHn//9rVD/5+7k/+bs4f/+rU//5MGS/+fk0v/2rln//65P/+mpXt////8B////Aeup 130 | XN//rk///65P//atV//n49D/4sKW/+Xs4v/m7OH/572I/+fn2P/0r1///65P//+uT//rql3f////Af// 131 | /wHqqV3f7LNt//OtWv//rk//9K9e/+rq2v/0/vT/8fvx/+ns3v/xsWb//65P//KsWv/rsm7/66pd3/// 132 | /wH///8B4Kdl3+m2dv/j4dD/58aa/+bBkf/hx6P/8e3a//Hs2f/iza7/5sKT/+bDlf/i4M7/6bNy/+Ko 133 | ZN////8B////AeKoY9/puX3/4tzJ/+fBkP/ouoT/4r+X/+/iyP/u277/4cCY/+e4gf/mtX3/4t3J/+m8 134 | g//gqGbf////Af///wHrqVzf661k//etVv//rk//77Jo/+bq3f/YuZD/2r6Y/+fp2//ysWP//65P//at 135 | V//srmT/66pd3////wH///8B66lc3/+uT///rk//87Bi/+fp2v/pvIL/665m/+yxa//nv4z/5+bU//Wu 136 | Wv//rk///65P/+uqXd////8B////AempXt//rk//9q9c/+fm1P/mwI3//65P/+uuZv/ssWv//65P/+TF 137 | mf/m4cz/+K1V//+uT//oqV/f////Af///wG9oH0t5Khhueqzcf/lwZH//65P//+uT//suXn/7Ll6//+u 138 | T//+rU//5ced/+uwa//kqGG5vaB9Lf///wH///8B////AZ2dnQPKonRR66lc2f6tT///rk//7L+F/+y/ 139 | hf//rk///q1P/+upXNnKo3RRpKSkA////wH///8B////Af///wH///8B////AaSekQvVpWx38qtX7/au 140 | WP/1rVj/8qtX79WlbHeknpEL////Af///wH///8B////Af///wH///8B////Af///wH///8B////AbKe 141 | hRvfp2Wf36dln7KehRv///8B////Af///wH///8B////Af///wEAAP//AAD//wAA//8AAP//AAD//wAA 142 | //8AAP//AAD//wAA//8AAP//AAD//wAA//8AAP//AAD//wAA//8AAP//KAAAACAAAABAAAAAAQAgAAAA 143 | AACAEAAAAAAAAAAAAAAAAAAAAAAAAP///wH///8B////Af///wH///8B////Af///wH///8B////Af// 144 | /wH///8B////Af///wGfn58FtZ6DN8ujc5fLo3SXtZ6DN5+fnwX///8B////Af///wH///8B////Af// 145 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 146 | /wH///8B////Af///wH///8Bo56RE7iggGniqGPX9qxV+fasVfniqGPXuKCAaaOdkhX///8B////Af// 147 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 148 | /wH///8B////Af///wH///8Bq5yKFb6gflXapmjT9axV+/+uT///rk///65P//+uT//2rFb72qZo072g 149 | fVWpnIoV////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 150 | /wH///8B////Af///wH///8BnZ2dA6mbjC/Po3Cp7Kpc6/ytUP//rk///65P//+uT///rk///65P//+u 151 | T//8rVD/66pc68+jcKmpm4wvnZ2dA////wH///8B////Af///wH///8B////Af///wH///8B////Af// 152 | /wH///8B////Af///wH///8Bm5ubBbOfiCvMo3OX5qhh6/6tT///rk///65P//+uT///rk///65P//+u 153 | T///rk///65P//+uT///rk///q1P/+aoYevMo3OXs5+IK5ubmwX///8B////Af///wH///8B////Af// 154 | /wH///8B////Af///wH///8B////AZubmwu8oH5t3KZnyfasVfv+rU///65P//+uT///rk///65P//Ss 155 | V//dqW3/3alt//SsWP//rk///65P//+uT///rk///q1P//asVfvcpmfJvKB+bZubmwv///8B////Af// 156 | /wH///8B////Af///wH///8B////AaGhmA/Bonxb1aVtwfWsVv/mqWT/2L6Z/++uYv//rk///65P//+u 157 | T//+rU//zMi5//L99P/y/PP/zca1//6tT///rk///65P//+uT//1rFb/37mI/+itZ//0q1f/1aVtwcGi 158 | fFuhoZgP////Af///wH///8B////Af///wGznoknyaN1leyqXO37rVH9+61R/9a8mf/v+O7/2Mis//is 159 | U///rk///65P//ytUf/b3NH/9P/2//T/9v/Z2cz//a1Q//+uT///rk///65P/9W5k//n7+b/3NC3//Gs 160 | W//7rVH97Kpc7cmjdZWznokn////Af///wH///8B////Ac6jcsH5rFL//65P//+uT///rk//56pk/+Hi 161 | 1P/z/fT/18Gh//WtWf//rk//+61R/9vd0v/0//b/9P/2/9nZzf/9rVD//65P//itVP/Xt47/7/jw/+nv 162 | 4//hsHX//a1Q//+uT///rk//+q1S/86jcMH///8B////Af///wH///8B1aVsv/ytUP//rk///65P//+u 163 | T///rk//37J7/+Pn2v/s9Or/1byY//6uT//7rVH/293S//T/9v/0//b/2dnN//2tUP//rk//27aI/+fr 164 | 3//q8OX/3LuP//ytUf//rk///65P//+uT//8rVH/1KVtv////wH///8B////Af///wHVpWy//K1Q//+u 165 | T///rk///65P//+uT//+rU//36xu/+bs4P/w+/L/17mR//SsV//b3dL/9P/2//T/9v/Z2c3/+a1T/9+0 166 | gP/p8ef/7PPp/922hf/6rVP//65P//+uT///rk///65P//ytUf/UpW2/////Af///wH///8B////AdWl 167 | bL/8rVD//65P//+uT///rk///65P//+uT//9rVD/3biJ/+nv4//o7eH/1LWN/9PWzP/0//b/9P/2/9fY 168 | zP/fsnv/5OPT/+317P/cxKL/+a1U//+uT///rk///65P//+uT///rk///K1R/9Slbb////8B////Af// 169 | /wH///8B1aVsv/ytUP/+rU///a1P//+uT///rk///65P//+uT//7rVL/3bWD/+zz6f/0/PD/9Pvw//T/ 170 | 9v/z/vX/6/Dk/+3y5f/v+O//28Ca//asV///rk///65P//+uT///rk///q1Q//6uT//8rVH/1KVtv/// 171 | /wH///8B////Af///wHVpWy/+axS/9ivfv/dwJj/2q13//esVf//rk///65P//+uT//5rVT/28Sk/+32 172 | 7f/0//b/9P/2//T/9v/0//b/8Prx/9jMtf/0rFj//65P//+uT///rk//96xV/9Wqdv/dwJj/1K6A//ut 173 | Uv/UpW2/////Af///wH///8B////AdOlbb/Vpm7/2LWJ/9vIq//o7uT/38qq/+y2dP/stXP/7LZ0/+y2 174 | dP/gtH7/3djG//T+9f/0/vX/9P/1//T/9f/e3tD/3bSB/+y2dP/stnT/7LVz/+u1c//eyaj/5Org/9rE 175 | o//Wr4D/3qho/9Olbb////8B////Af///wH///8B1aVsv/ytUP//rk//9axX/9LRw//y+/H/5ebX/+HJ 176 | qv/gxqX/4tK5/+DEov/oyqX/8OzY/+vMp//v4Mb/7NSz/+3hyf/gwp7/4MWl/+PXwf/gyan/49nE//L7 177 | 8f/V0MD/96xV//+uT//8rVH/1KVtv////wH///8B////Af///wHVpWy//K1Q//6tT//yrFn/2NTF/+nx 178 | 6P/k5dj/4L2X/+HCn//iyKf/4at3/+rSsv/s1bX/68qj/+zPrP/qw5j/6cuo/9+7k//hw6H/4L6Z/+C+ 179 | mP/fuI//6fHo/9TVyv/vq1z//K1R//qtUv/UpW2/////Af///wH///8B////AdWlbL/dqGj/2buT/93Q 180 | t//o7OH/3r+V/+yybf/ur2b/7q9m/+6uZf/gqGz/3tnI//L15//y8+L/8vDf//Dp1P/cy7D/3650/+6v 181 | Zv/ur2b/7q9m/+2vZv/iv5L/6e/j/93Vv//bw5//16Zv/9Slbb////8B////Af///wH///8B1aVsv/yt 182 | UP/ZqnH/17CB/+Osa//8rVH//65P//+uT///rk//8qxZ/9jQvP/x+/L/3dXA/8Sxlv/JuaH/49zG//D6 183 | 8P/ZzLP/9qxX//+uT///rk///65P//utUv/hq2v/2bKB/9yrcf/8rVH/1KVtv////wH///8B////Af// 184 | /wHVpWy//K1Q//+uT///rk///65P//+uT///rk///65P//OsWP/aw6L/8Prx/+Di1v/ormr/1a9//9a1 185 | iv/msHD/5Ojd/+737v/dvJP/+K1V//+uT///rk///65P//+uT///rk///65P//ytUf/UpW2/////Af// 186 | /wH///8B////AdWlbL/8rVD//65P//+uT///rk///65P//+uT//3rFb/2sir/+737v/h3sz/57Fx//+u 187 | T//Xr37/2bWI//+uT//htHz/5ebY/+vz6P/cvpb/+61R//+uT///rk///65P//+uT///rk///K1R/9Sl 188 | bb////8B////Af///wH///8B1aVsv/ytUP//rk///65P//+uT///rk//+K1U/927jv/t9uz/5+3i/+Ky 189 | eP/7rVH//65P/9evfv/ZtYj//65P//qtU//atof/7fbt/+nw5f/dr3f//a1Q//+uT///rk///65P//+u 190 | T//8rVH/1KVtv////wH///8B////Af///wHUpW2//K1Q//+uT///rk///65P//utUv/cv5f/6/Po/+Xn 191 | 2v/ftYH//65P//+uT///rk//169+/9m1iP//rk///65P//+uT//XuZH/6vHm/+br4P/etIH//q1P//+u 192 | T///rk///65P//ytUf/UpW2/////Af///wH///8B////Ac6jcrv5rFP//65P//+uT//8rVH/4bR9/+rx 193 | 5v/s9e3/2raH//mtU///rk///65P//+uT//Xr37/2bWI//+uT///rk///65P//etVv/WvJj/8v30/+To 194 | 3P/jq2n//65P//+uT///rk//+KxT/82kc7v///8B////Af///wH///8Brp6KIcOheIfpqV7n+axS/fOs 195 | Wf/ZzLL/5erg/9e3j///rk///65P//+uT///rk///q1P/9m5jv/ZupH//q1P//+uT///rk///65P//yt 196 | UP/WwKD/7PTq/9fBoP/6rVP/+axS/empXefEoXeHrp6KIf///wH///8B////Af///wH///8BmJiYC76h 197 | f0/Ro2618qtX++mqYf/ktn//96xV//+uT///rk///65P//+uT//4rVX/4dCx/+HQsf/4rVX//65P//+u 198 | T///rk///65P//OtW//fu43/6Kpg//KrV/vRo261vqF/T5mZmQv///8B////Af///wH///8B////Af// 199 | /wH///8B////AZ2dnQe3noJd2aZpwfSrVvf9rU///65P//+uT///rk///65P//KsWv/l3MT/5dzD//Ks 200 | Wv//rk///65P//+uT///rk///a1P//SrVvfZpmnBt56CXaSkpAf///8B////Af///wH///8B////Af// 201 | /wH///8B////Af///wH///8B////AZubmwWvnIYhyaJ1ieKoY+P9rVD//65P//+uT///rk//+61S/97H 202 | pP/ex6T/+61S//+uT///rk///65P//2tUP/iqGPjyaJ1ibCehyOenp4F////Af///wH///8B////Af// 203 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wGqqqoDpJ6QJcqjc53pqV7j+61R//+u 204 | T///rk//365z/9mqcv//rk///65P//utUf/pqV7jyqNznaSekCWqqqoD////Af///wH///8B////Af// 205 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8Bq56QEbug 206 | gEnXpWvH8qtX+f+uT//8rVH//K1R//+uT//yq1f516Vrx7uggEmrnpAR////Af///wH///8B////Af// 207 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 208 | /wH///8B////AZ6elA21noNb3qdmzfSrVvf0q1b33qdmzbWeg1uenpQN////Af///wH///8B////Af// 209 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 210 | /wH///8B////Af///wH///8B////AZ+fnwOznoctyaN1h8mjdYeznoctn5+fA////wH///8B////Af// 211 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 212 | AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 213 | AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAwAAAAYAAAAAEA 214 | IAAAAAAAgCUAAAAAAAAAAAAAAAAAAAAAAAD///8B////Af///wH///8B////Af///wH///8B////Af// 215 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8Bl5eXIbSe 216 | hY+0n4aPl5eXIf///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 217 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 218 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AZ+f 219 | nxGsnYpryKN20e+rW//vq1v/yKN20aydimufn58R////Af///wH///8B////Af///wH///8B////Af// 220 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 221 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 222 | /wGZmZkFpZ+RS76hfL3mqmH5/q5Q//+uT///rk///q1Q/+aqYfm+oXy9o5yPS6qqqgf///8B////Af// 223 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 224 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 225 | /wH///8B////AZubmy+4n4Kl26do7fqtUv//rk///65P//+uT///rk///65P//+uT//7rVP/3ado7bif 226 | gqWYmJgv////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 227 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 228 | /wH///8B////Af///wGXl5cbs56Fh9Gkcd/0q1b//65P//+uT///rk///65P//+uT///rk///65P//+u 229 | T///rk///65P//SrVv/RpHHfsZ6Fh5eXlxv///8B////Af///wH///8B////Af///wH///8B////Af// 230 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 231 | /wH///8B////Af///wH///8BnZ2dDaqbi2PGoXjN7atc//+uT///rk///65P//+uT///rk///65P//+u 232 | T///rk///65P//+uT///rk///65P//+uT///rk//7atc/8aheM2qm4tjnZ2dDf///wH///8B////Af// 233 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 234 | /wH///8B////Af///wH///8B////Ab+/vwWknJRDvJ99ueSpZPf9rVD//65P//+uT///rk///65P//+u 235 | T///rk///65P//+uT///rk///65P//+uT///rk///65P//+uT///rk///65P//2tUP/kqWT3vJ99uaSc 236 | lEO/v78F////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 237 | /wH///8B////Af///wH///8B////Af///wH///8Bm5ubKbaeg5/Zpmrp+a1U//+uT///rk///65P//+u 238 | T///rk///65P//+uT///rk///65P//+uT///rk///65P//+uT///rk///65P//+uT///rk///65P//+u 239 | T///rk//+a1U/9mmaum2noOfm5ubKf///wH///8B////Af///wH///8B////Af///wH///8B////Af// 240 | /wH///8B////Af///wH///8B////Af///wH///8B////AZubmxevnYd9zqVy2fKrWP//rk///65P//+u 241 | T///rk///65P//+uT///rk///65P//+uT//9rVD/1al1/8ingP/JqIH/06d2//6tUP//rk///65P//+u 242 | T///rk///65P//+uT///rk///65P//+uT//yq1j/zqVz2a+dh32bm5sX////Af///wH///8B////Af// 243 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wGZmZkLqp+OW8Ohesfrql/9/65P//Sr 244 | WP/Hp4D/6api//+uT///rk///65P//+uT///rk///65P//+uT/+xoo//7fjv//T/9v/0//b/6/Ts/7aj 245 | jP//rk///65P//+uT///rk///65P//+uT///rk///a1Q/9ipcv/0q1j//65P/+uqX/3DoXrHqp+OW5mZ 246 | mQv///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////A6Cglzu8oICz4qlm8/yt 247 | Uf//rk///K1S/6ahm//z/vX/ycS2/+qrYv//rk///65P//+uT///rk///65P//ytUf/Oybv/9P/2//T/ 248 | 9v/0//b/9P/2/8vEs//+rVD//65P//+uT///rk///65P//+uT//+rlD/r6KR/+jy6v+4saT/7qtc//+u 249 | T//8rVH/4qlm87yggLOgoJc7////A////wH///8B////Af///wH///8B////Af///wGqqqoNtJyDl9am 250 | bOX3rFT//65P//+uT///rk//8qta/9fXy//0//b/9P/2/8a8qv/xq1r//65P//+uT///rk///65P//qt 251 | U//PzcH/9P/2//T/9v/0//b/9P/2/8zHuf/9rVH//65P//+uT///rk///65P//+uUP+/p4r/7Pbt//T/ 252 | 9v/z/vX/yad///+uT///rk///65P//esVP/WpmzltJyDl6qqqg3///8B////Af///wH///8B////Af// 253 | /wGynoej6qle//+uT///rk///65P//+uT///rk///65P/8mnf//n7uT/9P/2//T/9v/As6D/96xW//+u 254 | T///rk///65P//qtU//PzcH/9P/2//T/9v/0//b/9P/2/8zHuf/9rVH//65P//+uT///rk///65P/8Kn 255 | h//p8en/9P/2//T/9v/FtZ//+a1U//+uT///rk///65P//+uT///rk//76tb/7GchaP///8B////Af// 256 | /wH///8B////Af///wG6oIGf96xU//+uT///rk///65P//+uT///rk///65P//+uT//Bpof/6/Pr//T/ 257 | 9v/y/fT/va2X//utUv//rk///65P//qtU//PzcH/9P/2//T/9v/0//b/9P/2/8zHuf/9rVH//65P//+u 258 | T///rk//xqaB/+Xs4//0//b/9P/2/8O3pP/zq1n//65P//+uT///rk///65P//+uT///rk//+K1V/7ig 259 | gZ////8B////Af///wH///8B////Af///wG6oIGf96xU//+uT///rk///65P//+uT///rk///65P//+u 260 | T//+rVD/vKiN/+758P/0//b/8Pvy/7ypkP/+rlD//65P//qtU//PzcH/9P/2//T/9v/0//b/9P/2/8zH 261 | uf/9rVH//65P//+uT//MqHz/4ube//T/9v/0//b/x76s/++rXf//rk///65P//+uT///rk///65P//+u 262 | T///rk//+K1V/7iggZ////8B////Af///wH///8B////Af///wG6oIGf96xU//+uT///rk///65P//+u 263 | T///rk///65P//+uT///rk///K1R/7yrk//x/PP/9P/2/+z37v+/p4r//65P//qtU//PzcH/9P/2//T/ 264 | 9v/0//b/9P/2/8zHuf/9rVH//65P/9Sodv/d4Nb/9P/2//T/9v/MxbX/6qti//+uT///rk///65P//+u 265 | T///rk///65P//+uT///rk//+K1V/7iggZ////8B////Af///wH///8B////Af///wG6oIGf96xU//+u 266 | T///rk///65P//+uT///rk///65P//+uT///rk///65P//mtVP+/sJv/9P/2//T/9v/p8ej/xKeE//mt 267 | VP/PzcH/9P/2//T/9v/0//b/9P/2/8zHuf/9rlH/2qlv/9naz//0//b/9P/2/9HNv//kqmb//65P//+u 268 | T///rk///65P//+uT///rk///65P//+uT///rk//+K1V/7iggZ////8B////Af///wH///8B////Af// 269 | /wG6oIGf96xU//+uT///rk///65P//+uT///rk///65P//+uT///rk///65P//+uT//0q1n/w7ek//T/ 270 | 9v/0//b/5Org/76khP++vLT/9P/2//T/9v/0//b/9P/2/8jEt//Yp2//1NLF//T/9v/0//b/19bK/96p 271 | bP//rk///65P//+uT///rk///65P//+uT///rk///65P//+uT///rk//+K1V/7iggZ////8B////Af// 272 | /wH///8B////Af///wG6oIGf96xU//+uT///rk///65P//+uT///rk///65P//+uT///rk///65P//+u 273 | T///rk//7qtf/8nCsf/0//b/9P/2//X56v/1+On/9P/2//T/9v/0//b/8/71/+Hez//m49H/9P/2//T/ 274 | 9v/a3NL/2Klz//+uT///rk///65P//+uT///rk///65P//+uT///rk///65P//+uT///rk//+K1V/7ig 275 | gZ////8B////Af///wH///8B////Af///wG6oIGf96xU//+uT///rk///q1Q//qtUv//rk///65P//+u 276 | T///rk///65P//+uT///rk///65P/+arZv/Rzb//9P/2//T/9v/0//b/9P/2//T/9v/0//b/9P/2//T/ 277 | 9v/0//b/9P/2/9/j2f/QqHn//65P//+uT///rk///65P//+uT///rk///65P//+uT//7rVP//q5Q//+u 278 | T///rk//+K1V/7iggZ////8B////Af///wH///8B////Af///wG6oIGf96xU//mtVP/DqIj/ysOz/9HO 279 | wP++r5v/3Klt//+uT///rk///65P//+uT///rk///65P//+uT//cqG3/2NnO//T/9v/0//b/9P/2//T/ 280 | 9v/0//b/9P/2//T/9v/0//b/4+ng/8mnfv//rk///65P//+uT///rk///65P//+uT///rk//3Kht/7Sp 281 | mf/RzsH/ycKz/7qki//8rVL/+K1V/7iggZ////8B////Af///wH///8B////Af///wG6oIGf86tW/6qe 282 | kP/FuKT/xr2t/+Hm3f/0//b/1dPH/9qobf/8rVL//K1R//ytUf/8rVH//K1R//ytUf/7rVL/x6V9/+Hl 283 | 2//0//b/9P/2//T/9v/0//b/9P/2//T/9v/p8Oj/uaSK//utUf/8rVH//K1R//ytUf/8rVH//K1R//ut 284 | Uf/bqG3/zszB//T/9v/e4db/v7Ke/8Owl/+8ooT/9qxW/7iggZ////8B////Af///wH///8B////Af// 285 | /wG6oIGf96xU//+uT///rk///65P/9Kndf/f4tb/9P/2/+vu4f/MyLr/zMi6/83HuP/MyLr/zMi6/8zI 286 | uv/MyLr/z8y9//X56v/0//b/9P70//T/9v/0//b/9P/1//T/9v/1+u7/1tLC/8zHuf/MyLr/zMi6/8zI 287 | uv/MyLr/zMe5/8zIuv/s7uH/9P/2/9bXzP/cqW3//65P//+uT///rk//+K1V/7iggZ////8B////Af// 288 | /wH///8B////Af///wG6oIGf96xU//+uT///rk///65P//+uT/+0ppT/9P/2//T/9v/0//b/8OHH/+q/ 289 | kv/sy6X/6LmJ//Do0v/ryKD/6LWC/+m+kP/z/PD/57F9/+i0gv/t1bX/7Mqj/+i6i//w4cf/7NCt/+i1 290 | gv/pvpH/7dGv//Dn0P/ryqL/68mi//Hv3f/0//b/9P/2/7+rkv//rk///65P//+uT///rk//+K1V/7ig 291 | gZ////8B////Af///wH///8B////Af///wG6oIGf96xU//+uT///rk///65P//+uT/++rJX/9P/2//T/ 292 | 9v/0//b/8vHg/+arc//s0a7/6r+S/+/fw//kn2D/6sad/+3Usv/rzan/7dOy/+m3hf/t0a//6sOY/+rA 293 | lP/v3sL/6b6Q/+m+kP/rxp7/7tm6/+m7jP/ryqL/6LqK/+m8jf/0//b/9P/2/7Gnmf//rk///65P//+u 294 | T///rk//+K1V/7iggZ////8B////Af///wH///8B////Af///wG6oIGf96xU//6uUP/+rlD/+q1S/8im 295 | ff/j597/9P/2/8bEuf/GvKv/xryr/8+ujP/NspT/y7Sa/8+vjv/YoW//1bma//Hp0//u3L//8fHf/+7W 296 | tf/w69f/5qtz/+7Vtf/qv5P/0rmb/8u1m//QrYr/xryp/8+ujP/LtZv/z62J/8q1nP/Fw7j/9P/2/+vz 297 | 6v++pYf/86xa//itVv/3rFb/9qxX/7iggZ////8B////Af///wH///8B////Af///wG6oIGf96xU/7ui 298 | hP/GwLL/y8m8/+vz6//0//b/z8Wx/+6rXv//rk///65P//+uT///rk///65P//+uT//8qlD/tqSN/+v0 299 | 7P/0//b/9P/2//X88f/1/vX/9P3y//P57f/o6dr/vaSG//+uT///rk///65P//+uT///rk///65P//+u 300 | T//3rVj/zsOu//T/9v/s9+7/1djO/8vKv/+voI7/+K1W/7iggZ////8B////Af///wH///8B////Af// 301 | /wG6oIGf96xU//+uT//Mp3v/u6uU/8e2n//Fqon/9a1Z//+uT///rk///65P//+uT///rk///65P//+u 302 | T//Dp4b/6fHo//T/9v/0//b/wrai/7uxoP+9tqn/1smy//T/9v/0//b/4+nf/8yofP//rk///65P//+u 303 | T///rk///65P//+uT///rk//76td/8Wqif/Htp//xbCU/86nev/+rVD/+K1V/7iggZ////8B////Af// 304 | /wH///8B////Af///wG6oIGf96xU//+uT///rk///65P//+uT///rk///65P//+uT///rk///65P//+u 305 | T///rk///65P/8engP/l6+P/9P/2//T/9v/DuKX/8ata/8Owl//FuaX/7Ktf/8rCsP/0//b/9P/2/9zf 306 | 1P/XqXP//65P//+uT///rk///65P//+uT///rk///65P//+uT///rk///65P//+uT///rk//+K1V/7ig 307 | gZ////8B////Af///wH///8B////Af///wG6oIGf96xU//+uT///rk///65P//+uT///rk///65P//+u 308 | T///rk///65P//+uT///rk//zad6/+Hl3P/0//b/9P/2/8i/rv/uq1///65P/8Owlv/GuaX//65P/+aq 309 | Zf/QzL7/9P/2//T/9v/W1Mj/4apr//+uT///rk///65P//+uT///rk///65P//+uT///rk///65P//+u 310 | T///rk//+K1V/7iggZ////8B////Af///wH///8B////Af///wG6oIGf96xU//+uT///rk///65P//+u 311 | T///rk///65P//+uT///rk///65P//+uT//VqHX/3N/U//T/9v/0//b/zce4/+mrYv//rk///65P/8Ow 312 | lv/GuaX//65P//+uT//cqG3/2NnN//T/9v/0//b/zsm5/+mrYv//rk///65P//+uT///rk///65P//+u 313 | T///rk///65P//+uT///rk//+K1V/7iggZ////8B////Af///wH///8B////Af///wG6oIGf96xU//+u 314 | T///rk///65P//+uT///rk///65P//+uT///rk///65P/9ypb//Y2Mz/9P/2//T/9v/Sz8H/46po//+u 315 | T///rk///65P/8Owlv/GuaX//65P//+uT///rk//06h3/9/j2f/0//b/9P/2/8a8q//wq1z//65P//+u 316 | T///rk///65P//+uT///rk///65P//+uT///rk//+K1V/7iggZ////8B////Af///wH///8B////Af// 317 | /wG6oIGf96xU//+uT///rk///65P//+uT///rk///65P//+uT///rk//4qpo/9PQwv/0//b/9P/2/9fX 318 | y//dqW3//65P//+uT///rk///65P/8Owlv/GuaX//65P//+uT///rk///65P/8inf//l7OP/9P/2//T/ 319 | 9v/As6D/96xX//+uT///rk///65P//+uT///rk///65P//+uT///rk//+K1V/7iggZ////8B////Af// 320 | /wH///8B////Af///wG6oIGf96xU//+uT///rk///65P//+uT///rk///65P//+uT//oqmP/zsm5//T/ 321 | 9v/0//b/293T/9epc///rk///65P//+uT///rk///65P/8Owlv/GuaX//65P//+uT///rk///65P//+u 322 | T//Bpof/6/Ps//T/9v/z/vX/va2Y//utU///rk///65P//+uT///rk///65P//+uT///rk//+K1V/7ig 323 | gZ////8B////Af///wH///8B////Af///wG4n4Kf96xU//+uT///rk///65P//+uT///rk///65P/+2r 324 | X//JwbD/9P/2//T/9v/g5Nr/zqd5//+uT///rk///65P//+uT///rk///65P/8Owlv/GuaX//65P//+u 325 | T///rk///65P//+uT///rlD/vqiN/+758P/0//b/8Pvy/7ypkP/9rVD//65P//+uT///rk///65P//+u 326 | T///rk//+K1V/7ifgp////8B////Af///wH///8B////Af///wGynoaZ6alf/f+uT///rk///65P//+u 327 | T///rk//9KtZ/8y/qv/0//b/9P/2/+Tq4v/Ip3///65P//+uT///rk///65P//+uT///rk///65P/8Ow 328 | lv/GuaX//65P//+uT///rk///65P//+uT///rk///a5R/72rk//x/PP/9P/2/+758P/DqYr//65P//+u 329 | T///rk///65P//+uT///rk//5qli/bKfiJn///8B////Af///wH///8B////Af///wGfn58JsJ6If86k 330 | cdvzq1j//65P//+uT///rk//zKh8//H88//0//b/6O/n/8OmhP//rk///65P//+uT///rk///65P//+u 331 | T///rk///65P/8S2ov/Euqj//65P//+uT///rk///65P//+uT///rk///65P//msU/+/sJv/8/71//T/ 332 | 9v/e4tn/6qph//+uT///rk///65P//OrV//Oo3DbsJ6If5+fnwn///8B////Af///wH///8B////Af// 333 | /wH///8B////AZiYmCu3n4Sf2qdq6/msU///rk//+axT/6mimP/c4tv/t6SM//+uT///rk///65P//+u 334 | T///rk///65P//+uT///rk//+K1W/9HQxP/R0MT/+K1W//+uT///rk///65P//+uT///rk///65P//+u 335 | T//0q1j/vbOi/+347/+moJj//a1R//+uT//5rFP/2qZp67efhJ+ampor////Af///wH///8B////Af// 336 | /wH///8B////Af///wH///8B////Af///wG/v78FoZqSRbyffbnkqWL3/a1Q//ytUv/mqmb//65P//+u 337 | T///rk///65P//+uT///rk///65P//+uT///rk//5Kpo/+Ps5P/j7OT/5Kto//+uT///rk///65P//+u 338 | T///rk///65P//+uT///rk//9qxW/9aoc//7rVH//a1Q/+SpYve8n325o5uURb+/vwX///8B////Af// 339 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AZ2dnQ2rnIxlxqF4ze2r 340 | XP//rk///65P//+uT///rk///65P//+uT///rk///65P//+uT///rk//0ql4//L99P/y/fT/0qh3//+u 341 | T///rk///65P//+uT///rk///65P//+uT///rk///65P//+uT//tq1z/xqF3zaucjGWkpKQP////Af// 342 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 343 | /wH///8Bm5ubHbKdhIfRpG/f9axW//+uT///rk///65P//+uT///rk///65P//+uT///rk//6Ktk/+Dn 344 | 4f/g5+D/6Ktk//+uT///rk///65P//+uT///rk///65P//+uT///rk//9axW/9Gkb9+ynoWJnp6eHf// 345 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 346 | /wH///8B////Af///wH///8B////Af///wGampoxuZ+Cp92nZ+37rVP//65P//+uT///rk///65P//+u 347 | T///rk//+q1S/87Mv//Oy7//+q1S//+uT///rk///65P//+uT///rk///65P//utU//dp2ftuZ+Cp5qa 348 | mjH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 349 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8BqqqqB6SekE2/oHu/5qpg+f6t 350 | UP//rk///65P//+uT///rk///65P/7+xnP+xqJr//65P//+uT///rk///65P//+uT//+rVD/5qpg+b+g 351 | e7+knpBNqqqqB////wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 352 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 353 | /wGlpaURrZ2KbcmjdtHvqlr//65P//+uT///rk///65P//OrWf/zq1n//65P//+uT///rk///65P/++q 354 | Wv/Jo3bRrZ2KbaWlpRH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 355 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 356 | /wH///8B////Af///wH///8B////AZubmyGznoWR1KRt4/esVf//rk///65P//+uT///rk///65P//+u 357 | T//3rFX/1KRt47OehZGbm5sh////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 358 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 359 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8Bnp6UN7qfgK3fp2bx/K1S//+u 360 | T///rk///K1S/9+nZvG6n4Ctnp6UN////wH///8B////Af///wH///8B////Af///wH///8B////Af// 361 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 362 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////AZ+f 363 | nwmonJBVwqF7w+mqXvvpql77wqF7w6ickFWfn58J////Af///wH///8B////Af///wH///8B////Af// 364 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 365 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 366 | /wH///8B////Af///wH///8Bnp6eFbCfiXewn4l3np6eFf///wH///8B////Af///wH///8B////Af// 367 | /wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af///wH///8B////Af// 368 | /wEAAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAA 369 | AAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA 370 | //8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAA 371 | AAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA 372 | //8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAA 373 | AAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8AAAAAAAD//wAAAAAAAP//AAAAAAAA 374 | //8AAAAAAAD//wAAAAAAAP//AAAAAAAA//8= 375 | 376 | 377 | -------------------------------------------------------------------------------- /PocoSqlGenerator/PocoSqlGenerator.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {6D3FC7F7-BA0F-4E44-AEB2-EBD754FC2816} 8 | WinExe 9 | Properties 10 | PocoSqlGenerator 11 | PocoSqlGenerator 12 | v4.5.2 13 | 512 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | Form 55 | 56 | 57 | MainForm.cs 58 | 59 | 60 | 61 | 62 | MainForm.cs 63 | 64 | 65 | ResXFileCodeGenerator 66 | Resources.Designer.cs 67 | Designer 68 | 69 | 70 | True 71 | Resources.resx 72 | 73 | 74 | SettingsSingleFileGenerator 75 | Settings.Designer.cs 76 | 77 | 78 | True 79 | Settings.settings 80 | True 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 102 | -------------------------------------------------------------------------------- /PocoSqlGenerator/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using System.Windows.Forms; 6 | 7 | namespace PocoSqlGenerator 8 | { 9 | static class Program 10 | { 11 | /// 12 | /// The main entry point for the application. 13 | /// 14 | [STAThread] 15 | static void Main() 16 | { 17 | Application.EnableVisualStyles(); 18 | Application.SetCompatibleTextRenderingDefault(false); 19 | Application.Run(new MainForm()); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /PocoSqlGenerator/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("PocoSqlGenerator")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("PocoSqlGenerator")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("6d3fc7f7-ba0f-4e44-aeb2-ebd754fc2816")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /PocoSqlGenerator/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace PocoSqlGenerator.Properties 12 | { 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources 26 | { 27 | 28 | private static global::System.Resources.ResourceManager resourceMan; 29 | 30 | private static global::System.Globalization.CultureInfo resourceCulture; 31 | 32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 33 | internal Resources() 34 | { 35 | } 36 | 37 | /// 38 | /// Returns the cached ResourceManager instance used by this class. 39 | /// 40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 41 | internal static global::System.Resources.ResourceManager ResourceManager 42 | { 43 | get 44 | { 45 | if ((resourceMan == null)) 46 | { 47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PocoSqlGenerator.Properties.Resources", typeof(Resources).Assembly); 48 | resourceMan = temp; 49 | } 50 | return resourceMan; 51 | } 52 | } 53 | 54 | /// 55 | /// Overrides the current thread's CurrentUICulture property for all 56 | /// resource lookups using this strongly typed resource class. 57 | /// 58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 59 | internal static global::System.Globalization.CultureInfo Culture 60 | { 61 | get 62 | { 63 | return resourceCulture; 64 | } 65 | set 66 | { 67 | resourceCulture = value; 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /PocoSqlGenerator/Properties/Resources.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | text/microsoft-resx 107 | 108 | 109 | 2.0 110 | 111 | 112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 113 | 114 | 115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | -------------------------------------------------------------------------------- /PocoSqlGenerator/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace PocoSqlGenerator.Properties 12 | { 13 | 14 | 15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] 17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase 18 | { 19 | 20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 21 | 22 | public static Settings Default 23 | { 24 | get 25 | { 26 | return defaultInstance; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /PocoSqlGenerator/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /PocoSqlGenerator/Resources/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /PocoSqlGenerator/Resources/AssemblyInfo.txt: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("#AssemblyTitle")] 9 | [assembly: AssemblyDescription("Provides programmatic access to the #DatabaseName database.")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("")] 13 | [assembly: AssemblyCopyright("")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // Version information for an assembly consists of the following four values: 23 | // 24 | // Major Version 25 | // Minor Version 26 | // Build Number 27 | // Revision 28 | // 29 | // You can specify all the values or you can default the Revision and Build Numbers 30 | // by using the '*' as shown below: 31 | [assembly: AssemblyVersion("1.0.0.0")] 32 | [assembly: AssemblyFileVersion("1.0.0.0")] 33 | -------------------------------------------------------------------------------- /PocoSqlGenerator/Resources/ColumnQuery.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | INFORMATION_SCHEMA.COLUMNS.*, 3 | COL_LENGTH('#TableName#', INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME) AS COLUMN_LENGTH, 4 | COLUMNPROPERTY(OBJECT_ID('#TableName#'), INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME, 'IsComputed') AS IS_COMPUTED, 5 | COLUMNPROPERTY(OBJECT_ID('#TableName#'), INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME, 'IsIdentity') AS IS_IDENTITY, 6 | COLUMNPROPERTY(OBJECT_ID('#TableName#'), INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME, 'IsRowGuidCol') AS IS_ROWGUIDCOL 7 | FROM 8 | INFORMATION_SCHEMA.COLUMNS 9 | WHERE 10 | INFORMATION_SCHEMA.COLUMNS.TABLE_NAME = '#TableName#' 11 | -------------------------------------------------------------------------------- /PocoSqlGenerator/Resources/Project.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | Debug 4 | AnyCPU 5 | 8.0.50727 6 | 2.0 7 | {} 8 | Library 9 | Properties 10 | 11 | 12 | 13 | 14 | true 15 | full 16 | false 17 | bin\Debug\ 18 | DEBUG;TRACE 19 | prompt 20 | 4 21 | 22 | 23 | pdbonly 24 | true 25 | bin\Release\ 26 | TRACE 27 | prompt 28 | 4 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /PocoSqlGenerator/Resources/TableQuery.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | TABLE_CATALOG, 3 | TABLE_SCHEMA, 4 | TABLE_NAME, 5 | TABLE_TYPE 6 | FROM 7 | INFORMATION_SCHEMA.TABLES 8 | WHERE 9 | TABLE_TYPE = 'BASE TABLE' 10 | AND TABLE_NAME != 'dtProperties' 11 | AND TABLE_CATALOG = '#DatabaseName#' 12 | ORDER BY TABLE_NAME 13 | -------------------------------------------------------------------------------- /PocoSqlGenerator/Resources/User.sql: -------------------------------------------------------------------------------- 1 | USE #DatabaseName# 2 | 3 | /****************************************************************************************** 4 | Create the #UserName# login. 5 | ******************************************************************************************/ 6 | IF NOT EXISTS(SELECT * FROM master..syslogins WHERE name = '#UserName#') 7 | EXEC sp_addlogin '#UserName#', '', '#DatabaseName#' 8 | GO 9 | 10 | /****************************************************************************************** 11 | Grant the #UserName# login access to the #DatabaseName# database. 12 | ******************************************************************************************/ 13 | IF NOT EXISTS (SELECT * FROM [dbo].sysusers WHERE NAME = N'#UserName#' AND uid < 16382) 14 | EXEC sp_grantdbaccess N'#UserName#', N'#UserName#' 15 | GO 16 | -------------------------------------------------------------------------------- /PocoSqlGenerator/SqlScriptGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Text; 5 | 6 | namespace PocoSqlGenerator 7 | { 8 | /// 9 | /// Generates DML SQL Scripts for basic CRUD operations of selected database tables. 10 | /// 11 | internal static class SqlScriptGenerator 12 | { 13 | /// 14 | /// Generate CRUD SP SQL scripts for the DB selected Tables 15 | /// 16 | /// The directory where the SQL code should be created. 17 | /// The connection string to be used to connect the to the database. 18 | /// The SQL Server login name that should be granted execute rights on the generated stored procedures. 19 | /// The prefix that should be used when creating stored procedures. 20 | /// A flag indicating if the generated stored procedures should be created in one file or separate files. 21 | /// ArrayList of Table names whose SPs has to be created. 22 | /// 23 | public static string GenerateSQLFiles(string outputDirectory, string connectionString, string grantLoginName, string storedProcedurePrefix, bool createMultipleFiles, ArrayList tableNames) 24 | { 25 | 26 | string databaseName = ""; 27 | string sqlPath; 28 | sqlPath = Path.Combine(outputDirectory, "SQL"); 29 | List
tableList = AppUtility.GetTableList(connectionString, outputDirectory, tableNames, ref databaseName); 30 | // Generate the necessary SQL for each table 31 | int count = 0; 32 | if (tableList.Count > 0) 33 | { 34 | // Create the necessary directories 35 | AppUtility.CreateSubDirectory(sqlPath, true); 36 | // Create the necessary database logins 37 | CreateUserQueries(databaseName, grantLoginName, sqlPath, createMultipleFiles); 38 | 39 | // Create the CRUD stored procedures and data access code for each table 40 | foreach (Table table in tableList) 41 | { 42 | CreateInsertStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles); 43 | CreateUpdateStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles); 44 | CreateDeleteStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles); 45 | CreateDeleteAllByStoredProcedures(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles); 46 | CreateSelectStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles); 47 | CreateSelectAllStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles); 48 | CreateSelectAllByStoredProcedures(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles); 49 | count++; 50 | } 51 | } 52 | 53 | return sqlPath; 54 | } 55 | 56 | /// 57 | /// Creates the SQL script that is responsible for granting the specified login access to the specified database. 58 | /// 59 | /// The name of the database that the login will be created for. 60 | /// Name of the SQL Server user that should have execute rights on the stored procedure. 61 | /// Path where the script should be created. 62 | /// Indicates the script should be created in its own file. 63 | internal static void CreateUserQueries(string databaseName, string grantLoginName, string path, bool createMultipleFiles) 64 | { 65 | if (grantLoginName.Length > 0) 66 | { 67 | string fileName; 68 | 69 | // Determine the file name to be used 70 | if (createMultipleFiles) 71 | { 72 | fileName = Path.Combine(path, "GrantUserPermissions.sql"); 73 | } 74 | else 75 | { 76 | fileName = Path.Combine(path, "StoredProcedures.sql"); 77 | } 78 | 79 | using (StreamWriter writer = new StreamWriter(fileName, true)) 80 | { 81 | writer.Write(AppUtility.GetUserQueries(databaseName, grantLoginName)); 82 | } 83 | } 84 | } 85 | 86 | /// 87 | /// Creates an insert stored procedure SQL script for the specified table 88 | /// 89 | /// Instance of the Table class that represents the table this stored procedure will be created for. 90 | /// Name of the SQL Server user that should have execute rights on the stored procedure. 91 | /// Prefix to be appended to the name of the stored procedure. 92 | /// Path where the stored procedure script should be created. 93 | /// Indicates the procedure(s) generated should be created in its own file. 94 | internal static void CreateInsertStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles) 95 | { 96 | // Create the stored procedure name 97 | string procedureName = storedProcedurePrefix + table.Name + "Insert"; 98 | string fileName; 99 | 100 | // Determine the file name to be used 101 | if (createMultipleFiles) 102 | { 103 | fileName = Path.Combine(path, procedureName + ".sql"); 104 | } 105 | else 106 | { 107 | fileName = Path.Combine(path, "StoredProcedures.sql"); 108 | } 109 | 110 | using (StreamWriter writer = new StreamWriter(fileName, true)) 111 | { 112 | // Create the seperator 113 | if (createMultipleFiles == false) 114 | { 115 | writer.WriteLine(); 116 | writer.WriteLine("/******************************************************************************"); 117 | writer.WriteLine("******************************************************************************/"); 118 | } 119 | 120 | // Create the drop statment 121 | writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)"); 122 | writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]"); 123 | writer.WriteLine("GO"); 124 | writer.WriteLine(); 125 | 126 | // Create the SQL for the stored procedure 127 | writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]"); 128 | writer.WriteLine("("); 129 | 130 | // Create the parameter list 131 | for (int i = 0; i < table.Columns.Count; i++) 132 | { 133 | Column column = table.Columns[i]; 134 | if (column.IsIdentity == false && column.IsRowGuidCol == false) 135 | { 136 | writer.Write("\t" + AppUtility.CreateParameterString(column, true)); 137 | if (i < (table.Columns.Count - 1)) 138 | { 139 | writer.Write(","); 140 | } 141 | writer.WriteLine(); 142 | } 143 | } 144 | writer.WriteLine(")"); 145 | 146 | writer.WriteLine(); 147 | writer.WriteLine("AS"); 148 | writer.WriteLine(); 149 | writer.WriteLine("SET NOCOUNT ON"); 150 | writer.WriteLine(); 151 | 152 | // Initialize all RowGuidCol columns 153 | foreach (Column column in table.Columns) 154 | { 155 | if (column.IsRowGuidCol) 156 | { 157 | writer.WriteLine("SET @" + column.Name + " = NEWID()"); 158 | writer.WriteLine(); 159 | break; 160 | } 161 | } 162 | 163 | writer.WriteLine("INSERT INTO [" + table.Name + "]"); 164 | writer.WriteLine("("); 165 | 166 | // Create the parameter list 167 | for (int i = 0; i < table.Columns.Count; i++) 168 | { 169 | Column column = table.Columns[i]; 170 | 171 | // Ignore any identity columns 172 | if (column.IsIdentity == false) 173 | { 174 | // Append the column name as a parameter of the insert statement 175 | if (i < (table.Columns.Count - 1)) 176 | { 177 | writer.WriteLine("\t[" + column.Name + "],"); 178 | } 179 | else 180 | { 181 | writer.WriteLine("\t[" + column.Name + "]"); 182 | } 183 | } 184 | } 185 | 186 | writer.WriteLine(")"); 187 | writer.WriteLine("VALUES"); 188 | writer.WriteLine("("); 189 | 190 | // Create the values list 191 | for (int i = 0; i < table.Columns.Count; i++) 192 | { 193 | Column column = table.Columns[i]; 194 | 195 | // Is the current column an identity column? 196 | if (column.IsIdentity == false) 197 | { 198 | // Append the necessary line breaks and commas 199 | if (i < (table.Columns.Count - 1)) 200 | { 201 | writer.WriteLine("\t@" + column.Name + ","); 202 | } 203 | else 204 | { 205 | writer.WriteLine("\t@" + column.Name); 206 | } 207 | } 208 | } 209 | 210 | writer.WriteLine(")"); 211 | 212 | // Should we include a line for returning the identity? 213 | foreach (Column column in table.Columns) 214 | { 215 | // Is the current column an identity column? 216 | if (column.IsIdentity) 217 | { 218 | writer.WriteLine(); 219 | writer.WriteLine("SELECT SCOPE_IDENTITY()"); 220 | break; 221 | } 222 | if (column.IsRowGuidCol) 223 | { 224 | writer.WriteLine(); 225 | writer.WriteLine("SELECT @" + column.Name); 226 | break; 227 | } 228 | } 229 | 230 | writer.WriteLine("GO"); 231 | 232 | // Create the grant statement, if a user was specified 233 | if (grantLoginName.Length > 0) 234 | { 235 | writer.WriteLine(); 236 | writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]"); 237 | writer.WriteLine("GO"); 238 | } 239 | } 240 | } 241 | 242 | /// 243 | /// Creates an update stored procedure SQL script for the specified table 244 | /// 245 | /// Instance of the Table class that represents the table this stored procedure will be created for. 246 | /// Name of the SQL Server user that should have execute rights on the stored procedure. 247 | /// Prefix to be appended to the name of the stored procedure. 248 | /// Path where the stored procedure script should be created. 249 | /// Indicates the procedure(s) generated should be created in its own file. 250 | internal static void CreateUpdateStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles) 251 | { 252 | if (table.PrimaryKeys.Count > 0 && table.Columns.Count != table.PrimaryKeys.Count && table.Columns.Count != table.ForeignKeys.Count) 253 | { 254 | // Create the stored procedure name 255 | string procedureName = storedProcedurePrefix + table.Name + "Update"; 256 | string fileName; 257 | 258 | // Determine the file name to be used 259 | if (createMultipleFiles) 260 | { 261 | fileName = Path.Combine(path, procedureName + ".sql"); 262 | } 263 | else 264 | { 265 | fileName = Path.Combine(path, "StoredProcedures.sql"); 266 | } 267 | 268 | using (StreamWriter writer = new StreamWriter(fileName, true)) 269 | { 270 | // Create the seperator 271 | if (createMultipleFiles == false) 272 | { 273 | writer.WriteLine(); 274 | writer.WriteLine("/******************************************************************************"); 275 | writer.WriteLine("******************************************************************************/"); 276 | } 277 | 278 | // Create the drop statment 279 | writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)"); 280 | writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]"); 281 | writer.WriteLine("GO"); 282 | writer.WriteLine(); 283 | 284 | // Create the SQL for the stored procedure 285 | writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]"); 286 | writer.WriteLine("("); 287 | 288 | // Create the parameter list 289 | for (int i = 0; i < table.Columns.Count; i++) 290 | { 291 | Column column = table.Columns[i]; 292 | 293 | if (i == 0) 294 | { 295 | 296 | } 297 | if (i < (table.Columns.Count - 1)) 298 | { 299 | writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ","); 300 | } 301 | else 302 | { 303 | writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false)); 304 | } 305 | } 306 | writer.WriteLine(")"); 307 | 308 | writer.WriteLine(); 309 | writer.WriteLine("AS"); 310 | writer.WriteLine(); 311 | writer.WriteLine("SET NOCOUNT ON"); 312 | writer.WriteLine(); 313 | writer.WriteLine("UPDATE [" + table.Name + "]"); 314 | writer.Write("SET"); 315 | 316 | // Create the set statement 317 | bool firstLine = true; 318 | for (int i = 0; i < table.Columns.Count; i++) 319 | { 320 | var column = table.Columns[i]; 321 | 322 | // Ignore Identity and RowGuidCol columns 323 | if (table.PrimaryKeys.Contains(column) == false) 324 | { 325 | if (firstLine) 326 | { 327 | writer.Write(" "); 328 | firstLine = false; 329 | } 330 | else 331 | { 332 | writer.Write("\t"); 333 | } 334 | 335 | writer.Write("[" + column.Name + "] = @" + column.Name); 336 | 337 | if (i < (table.Columns.Count - 1)) 338 | { 339 | writer.Write(","); 340 | } 341 | 342 | writer.WriteLine(); 343 | } 344 | } 345 | 346 | writer.Write("WHERE"); 347 | 348 | // Create the where clause 349 | for (int i = 0; i < table.PrimaryKeys.Count; i++) 350 | { 351 | Column column = table.PrimaryKeys[i]; 352 | 353 | if (i == 0) 354 | { 355 | writer.Write(" [" + column.Name + "] = @" + column.Name); 356 | } 357 | else 358 | { 359 | writer.Write("\tAND [" + column.Name + "] = @" + column.Name); 360 | } 361 | } 362 | writer.WriteLine(); 363 | 364 | writer.WriteLine("GO"); 365 | 366 | // Create the grant statement, if a user was specified 367 | if (grantLoginName.Length > 0) 368 | { 369 | writer.WriteLine(); 370 | writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]"); 371 | writer.WriteLine("GO"); 372 | } 373 | } 374 | } 375 | } 376 | 377 | /// 378 | /// Creates an delete stored procedure SQL script for the specified table 379 | /// 380 | /// Instance of the Table class that represents the table this stored procedure will be created for. 381 | /// Name of the SQL Server user that should have execute rights on the stored procedure. 382 | /// Prefix to be appended to the name of the stored procedure. 383 | /// Path where the stored procedure script should be created. 384 | /// Indicates the procedure(s) generated should be created in its own file. 385 | internal static void CreateDeleteStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles) 386 | { 387 | if (table.PrimaryKeys.Count > 0) 388 | { 389 | // Create the stored procedure name 390 | string procedureName = storedProcedurePrefix + table.Name + "Delete"; 391 | string fileName; 392 | 393 | // Determine the file name to be used 394 | if (createMultipleFiles) 395 | { 396 | fileName = Path.Combine(path, procedureName + ".sql"); 397 | } 398 | else 399 | { 400 | fileName = Path.Combine(path, "StoredProcedures.sql"); 401 | } 402 | 403 | using (StreamWriter writer = new StreamWriter(fileName, true)) 404 | { 405 | // Create the seperator 406 | if (createMultipleFiles == false) 407 | { 408 | writer.WriteLine(); 409 | writer.WriteLine("/******************************************************************************"); 410 | writer.WriteLine("******************************************************************************/"); 411 | } 412 | 413 | // Create the drop statment 414 | writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)"); 415 | writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]"); 416 | writer.WriteLine("GO"); 417 | writer.WriteLine(); 418 | 419 | // Create the SQL for the stored procedure 420 | writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]"); 421 | writer.WriteLine("("); 422 | 423 | // Create the parameter list 424 | for (int i = 0; i < table.PrimaryKeys.Count; i++) 425 | { 426 | Column column = table.PrimaryKeys[i]; 427 | 428 | if (i < (table.PrimaryKeys.Count - 1)) 429 | { 430 | writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ","); 431 | } 432 | else 433 | { 434 | writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false)); 435 | } 436 | } 437 | writer.WriteLine(")"); 438 | 439 | writer.WriteLine(); 440 | writer.WriteLine("AS"); 441 | writer.WriteLine(); 442 | writer.WriteLine("SET NOCOUNT ON"); 443 | writer.WriteLine(); 444 | writer.WriteLine("DELETE FROM [" + table.Name + "]"); 445 | writer.Write("WHERE"); 446 | 447 | // Create the where clause 448 | for (int i = 0; i < table.PrimaryKeys.Count; i++) 449 | { 450 | Column column = table.PrimaryKeys[i]; 451 | 452 | if (i == 0) 453 | { 454 | writer.WriteLine(" [" + column.Name + "] = @" + column.Name); 455 | } 456 | else 457 | { 458 | writer.WriteLine("\tAND [" + column.Name + "] = @" + column.Name); 459 | } 460 | } 461 | 462 | writer.WriteLine("GO"); 463 | 464 | // Create the grant statement, if a user was specified 465 | if (grantLoginName.Length > 0) 466 | { 467 | writer.WriteLine(); 468 | writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]"); 469 | writer.WriteLine("GO"); 470 | } 471 | } 472 | } 473 | } 474 | 475 | /// 476 | /// Creates one or more delete stored procedures SQL script for the specified table and its foreign keys 477 | /// 478 | /// Instance of the Table class that represents the table this stored procedure will be created for. 479 | /// Name of the SQL Server user that should have execute rights on the stored procedure. 480 | /// Prefix to be appended to the name of the stored procedure. 481 | /// Path where the stored procedure script should be created. 482 | /// Indicates the procedure(s) generated should be created in its own file. 483 | internal static void CreateDeleteAllByStoredProcedures(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles) 484 | { 485 | // Create a stored procedure for each foreign key 486 | foreach (List compositeKeyList in table.ForeignKeys.Values) 487 | { 488 | // Create the stored procedure name 489 | StringBuilder stringBuilder = new StringBuilder(255); 490 | stringBuilder.Append(storedProcedurePrefix + table.Name + "DeleteAllBy"); 491 | 492 | // Create the parameter list 493 | for (int i = 0; i < compositeKeyList.Count; i++) 494 | { 495 | Column column = compositeKeyList[i]; 496 | if (i > 0) 497 | { 498 | stringBuilder.Append("_" + AppUtility.FormatPascal(column.Name)); 499 | } 500 | else 501 | { 502 | stringBuilder.Append(AppUtility.FormatPascal(column.Name)); 503 | } 504 | } 505 | 506 | string procedureName = stringBuilder.ToString(); 507 | string fileName; 508 | 509 | // Determine the file name to be used 510 | if (createMultipleFiles) 511 | { 512 | fileName = Path.Combine(path, procedureName + ".sql"); 513 | } 514 | else 515 | { 516 | fileName = Path.Combine(path, "StoredProcedures.sql"); 517 | } 518 | 519 | using (StreamWriter writer = new StreamWriter(fileName, true)) 520 | { 521 | // Create the seperator 522 | if (createMultipleFiles == false) 523 | { 524 | writer.WriteLine(); 525 | writer.WriteLine("/******************************************************************************"); 526 | writer.WriteLine("******************************************************************************/"); 527 | } 528 | 529 | // Create the drop statment 530 | writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)"); 531 | writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]"); 532 | writer.WriteLine("GO"); 533 | writer.WriteLine(); 534 | 535 | // Create the SQL for the stored procedure 536 | writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]"); 537 | writer.WriteLine("("); 538 | 539 | // Create the parameter list 540 | for (int i = 0; i < compositeKeyList.Count; i++) 541 | { 542 | Column column = compositeKeyList[i]; 543 | 544 | if (i < (compositeKeyList.Count - 1)) 545 | { 546 | writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ","); 547 | } 548 | else 549 | { 550 | writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false)); 551 | } 552 | } 553 | writer.WriteLine(")"); 554 | 555 | writer.WriteLine(); 556 | writer.WriteLine("AS"); 557 | writer.WriteLine(); 558 | writer.WriteLine("SET NOCOUNT ON"); 559 | writer.WriteLine(); 560 | writer.WriteLine("DELETE FROM [" + table.Name + "]"); 561 | writer.Write("WHERE"); 562 | 563 | // Create the where clause 564 | for (int i = 0; i < compositeKeyList.Count; i++) 565 | { 566 | Column column = compositeKeyList[i]; 567 | 568 | if (i == 0) 569 | { 570 | writer.WriteLine(" [" + column.Name + "] = @" + column.Name); 571 | } 572 | else 573 | { 574 | writer.WriteLine("\tAND [" + column.Name + "] = @" + column.Name); 575 | } 576 | } 577 | 578 | writer.WriteLine("GO"); 579 | 580 | // Create the grant statement, if a user was specified 581 | if (grantLoginName.Length > 0) 582 | { 583 | writer.WriteLine(); 584 | writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]"); 585 | writer.WriteLine("GO"); 586 | } 587 | } 588 | } 589 | } 590 | 591 | /// 592 | /// Creates an select stored procedure SQL script for the specified table 593 | /// 594 | /// Instance of the Table class that represents the table this stored procedure will be created for. 595 | /// Name of the SQL Server user that should have execute rights on the stored procedure. 596 | /// Prefix to be appended to the name of the stored procedure. 597 | /// Path where the stored procedure script should be created. 598 | /// Indicates the procedure(s) generated should be created in its own file. 599 | internal static void CreateSelectStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles) 600 | { 601 | if (table.PrimaryKeys.Count > 0 && table.ForeignKeys.Count != table.Columns.Count) 602 | { 603 | // Create the stored procedure name 604 | string procedureName = storedProcedurePrefix + table.Name + "Select"; 605 | string fileName; 606 | 607 | // Determine the file name to be used 608 | if (createMultipleFiles) 609 | { 610 | fileName = Path.Combine(path, procedureName + ".sql"); 611 | } 612 | else 613 | { 614 | fileName = Path.Combine(path, "StoredProcedures.sql"); 615 | } 616 | 617 | using (StreamWriter writer = new StreamWriter(fileName, true)) 618 | { 619 | // Create the seperator 620 | if (createMultipleFiles == false) 621 | { 622 | writer.WriteLine(); 623 | writer.WriteLine("/******************************************************************************"); 624 | writer.WriteLine("******************************************************************************/"); 625 | } 626 | 627 | // Create the drop statment 628 | writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)"); 629 | writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]"); 630 | writer.WriteLine("GO"); 631 | writer.WriteLine(); 632 | 633 | // Create the SQL for the stored procedure 634 | writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]"); 635 | writer.WriteLine("("); 636 | 637 | // Create the parameter list 638 | for (int i = 0; i < table.PrimaryKeys.Count; i++) 639 | { 640 | Column column = table.PrimaryKeys[i]; 641 | 642 | if (i == (table.PrimaryKeys.Count - 1)) 643 | { 644 | writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false)); 645 | } 646 | else 647 | { 648 | writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ","); 649 | } 650 | } 651 | 652 | writer.WriteLine(")"); 653 | 654 | writer.WriteLine(); 655 | writer.WriteLine("AS"); 656 | writer.WriteLine(); 657 | writer.WriteLine("SET NOCOUNT ON"); 658 | writer.WriteLine(); 659 | writer.Write("SELECT"); 660 | 661 | // Create the list of columns 662 | for (int i = 0; i < table.Columns.Count; i++) 663 | { 664 | Column column = table.Columns[i]; 665 | 666 | if (i == 0) 667 | { 668 | writer.Write(" "); 669 | } 670 | else 671 | { 672 | writer.Write("\t"); 673 | } 674 | 675 | writer.Write("[" + column.Name + "]"); 676 | 677 | if (i < (table.Columns.Count - 1)) 678 | { 679 | writer.Write(","); 680 | } 681 | 682 | writer.WriteLine(); 683 | } 684 | 685 | writer.WriteLine("FROM [" + table.Name + "]"); 686 | writer.Write("WHERE"); 687 | 688 | // Create the where clause 689 | for (int i = 0; i < table.PrimaryKeys.Count; i++) 690 | { 691 | Column column = table.PrimaryKeys[i]; 692 | 693 | if (i == 0) 694 | { 695 | writer.WriteLine(" [" + column.Name + "] = @" + column.Name); 696 | } 697 | else 698 | { 699 | writer.WriteLine("\tAND [" + column.Name + "] = @" + column.Name); 700 | } 701 | } 702 | 703 | writer.WriteLine("GO"); 704 | 705 | // Create the grant statement, if a user was specified 706 | if (grantLoginName.Length > 0) 707 | { 708 | writer.WriteLine(); 709 | writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]"); 710 | writer.WriteLine("GO"); 711 | } 712 | } 713 | } 714 | } 715 | 716 | /// 717 | /// Creates an select all stored procedure SQL script for the specified table 718 | /// 719 | /// Instance of the Table class that represents the table this stored procedure will be created for. 720 | /// Name of the SQL Server user that should have execute rights on the stored procedure. 721 | /// Prefix to be appended to the name of the stored procedure. 722 | /// Path where the stored procedure script should be created. 723 | /// Indicates the procedure(s) generated should be created in its own file. 724 | internal static void CreateSelectAllStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles) 725 | { 726 | if (table.PrimaryKeys.Count > 0 && table.ForeignKeys.Count != table.Columns.Count) 727 | { 728 | // Create the stored procedure name 729 | string procedureName = storedProcedurePrefix + table.Name + "SelectAll"; 730 | string fileName; 731 | 732 | // Determine the file name to be used 733 | if (createMultipleFiles) 734 | { 735 | fileName = Path.Combine(path, procedureName + ".sql"); 736 | } 737 | else 738 | { 739 | fileName = Path.Combine(path, "StoredProcedures.sql"); 740 | } 741 | 742 | using (StreamWriter writer = new StreamWriter(fileName, true)) 743 | { 744 | // Create the seperator 745 | if (createMultipleFiles == false) 746 | { 747 | writer.WriteLine(); 748 | writer.WriteLine("/******************************************************************************"); 749 | writer.WriteLine("******************************************************************************/"); 750 | } 751 | 752 | // Create the drop statment 753 | writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)"); 754 | writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]"); 755 | writer.WriteLine("GO"); 756 | writer.WriteLine(); 757 | 758 | // Create the SQL for the stored procedure 759 | writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]"); 760 | writer.WriteLine(); 761 | writer.WriteLine("AS"); 762 | writer.WriteLine(); 763 | writer.WriteLine("SET NOCOUNT ON"); 764 | writer.WriteLine(); 765 | writer.Write("SELECT"); 766 | 767 | // Create the list of columns 768 | for (int i = 0; i < table.Columns.Count; i++) 769 | { 770 | Column column = table.Columns[i]; 771 | 772 | if (i == 0) 773 | { 774 | writer.Write(" "); 775 | } 776 | else 777 | { 778 | writer.Write("\t"); 779 | } 780 | 781 | writer.Write("[" + column.Name + "]"); 782 | 783 | if (i < (table.Columns.Count - 1)) 784 | { 785 | writer.Write(","); 786 | } 787 | 788 | writer.WriteLine(); 789 | } 790 | 791 | writer.WriteLine("FROM [" + table.Name + "]"); 792 | 793 | writer.WriteLine("GO"); 794 | 795 | // Create the grant statement, if a user was specified 796 | if (grantLoginName.Length > 0) 797 | { 798 | writer.WriteLine(); 799 | writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]"); 800 | writer.WriteLine("GO"); 801 | } 802 | } 803 | } 804 | } 805 | 806 | /// 807 | /// Creates one or more select stored procedures SQL script for the specified table and its foreign keys 808 | /// 809 | /// Instance of the Table class that represents the table this stored procedure will be created for. 810 | /// Name of the SQL Server user that should have execute rights on the stored procedure. 811 | /// Prefix to be appended to the name of the stored procedure. 812 | /// Path where the stored procedure script should be created. 813 | /// Indicates the procedure(s) generated should be created in its own file. 814 | internal static void CreateSelectAllByStoredProcedures(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles) 815 | { 816 | // Create a stored procedure for each foreign key 817 | foreach (List compositeKeyList in table.ForeignKeys.Values) 818 | { 819 | // Create the stored procedure name 820 | StringBuilder stringBuilder = new StringBuilder(255); 821 | stringBuilder.Append(storedProcedurePrefix + table.Name + "SelectAllBy"); 822 | 823 | // Create the parameter list 824 | for (int i = 0; i < compositeKeyList.Count; i++) 825 | { 826 | Column column = compositeKeyList[i]; 827 | if (i > 0) 828 | { 829 | stringBuilder.Append("_" + AppUtility.FormatPascal(column.Name)); 830 | } 831 | else 832 | { 833 | stringBuilder.Append(AppUtility.FormatPascal(column.Name)); 834 | } 835 | } 836 | 837 | string procedureName = stringBuilder.ToString(); 838 | string fileName; 839 | 840 | // Determine the file name to be used 841 | if (createMultipleFiles) 842 | { 843 | fileName = Path.Combine(path, procedureName + ".sql"); 844 | } 845 | else 846 | { 847 | fileName = Path.Combine(path, "StoredProcedures.sql"); 848 | } 849 | 850 | using (StreamWriter writer = new StreamWriter(fileName, true)) 851 | { 852 | // Create the seperator 853 | if (createMultipleFiles == false) 854 | { 855 | writer.WriteLine(); 856 | writer.WriteLine("/******************************************************************************"); 857 | writer.WriteLine("******************************************************************************/"); 858 | } 859 | 860 | // Create the drop statment 861 | writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)"); 862 | writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]"); 863 | writer.WriteLine("GO"); 864 | writer.WriteLine(); 865 | 866 | // Create the SQL for the stored procedure 867 | writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]"); 868 | writer.WriteLine("("); 869 | 870 | // Create the parameter list 871 | for (int i = 0; i < compositeKeyList.Count; i++) 872 | { 873 | Column column = compositeKeyList[i]; 874 | 875 | if (i < (compositeKeyList.Count - 1)) 876 | { 877 | writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ","); 878 | } 879 | else 880 | { 881 | writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false)); 882 | } 883 | } 884 | writer.WriteLine(")"); 885 | 886 | writer.WriteLine(); 887 | writer.WriteLine("AS"); 888 | writer.WriteLine(); 889 | writer.WriteLine("SET NOCOUNT ON"); 890 | writer.WriteLine(); 891 | writer.Write("SELECT"); 892 | 893 | // Create the list of columns 894 | for (int i = 0; i < table.Columns.Count; i++) 895 | { 896 | Column column = table.Columns[i]; 897 | 898 | if (i == 0) 899 | { 900 | writer.Write(" "); 901 | } 902 | else 903 | { 904 | writer.Write("\t"); 905 | } 906 | 907 | writer.Write("[" + column.Name + "]"); 908 | 909 | if (i < (table.Columns.Count - 1)) 910 | { 911 | writer.Write(","); 912 | } 913 | 914 | writer.WriteLine(); 915 | } 916 | 917 | writer.WriteLine("FROM [" + table.Name + "]"); 918 | writer.Write("WHERE"); 919 | 920 | // Create the where clause 921 | for (int i = 0; i < compositeKeyList.Count; i++) 922 | { 923 | Column column = compositeKeyList[i]; 924 | 925 | if (i == 0) 926 | { 927 | writer.WriteLine(" [" + column.Name + "] = @" + column.Name); 928 | } 929 | else 930 | { 931 | writer.WriteLine("\tAND [" + column.Name + "] = @" + column.Name); 932 | } 933 | } 934 | 935 | writer.WriteLine("GO"); 936 | 937 | // Create the grant statement, if a user was specified 938 | if (grantLoginName.Length > 0) 939 | { 940 | writer.WriteLine(); 941 | writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]"); 942 | writer.WriteLine("GO"); 943 | } 944 | } 945 | } 946 | } 947 | } 948 | 949 | /// 950 | /// Class that stores information for tables in a database. 951 | /// 952 | public class Table 953 | { 954 | string name; 955 | List columns; 956 | List primaryKeys; 957 | Dictionary> foreignKeys; 958 | 959 | /// 960 | /// Default constructor. All collections are initialized. 961 | /// 962 | public Table() 963 | { 964 | columns = new List(); 965 | primaryKeys = new List(); 966 | foreignKeys = new Dictionary>(); 967 | } 968 | 969 | /// 970 | /// Contains the list of Column instances that define the table. 971 | /// 972 | public List Columns 973 | { 974 | get { return columns; } 975 | } 976 | 977 | /// 978 | /// Contains the list of Column instances that define the table. The Dictionary returned 979 | /// is keyed on the foreign key name, and the value associated with the key is an 980 | /// List of Column instances that compose the foreign key. 981 | /// 982 | public Dictionary> ForeignKeys 983 | { 984 | get { return foreignKeys; } 985 | } 986 | 987 | /// 988 | /// Name of the table. 989 | /// 990 | public string Name 991 | { 992 | get { return name; } 993 | set { name = value; } 994 | } 995 | 996 | /// 997 | /// Contains the list of primary key Column instances that define the table. 998 | /// 999 | public List PrimaryKeys 1000 | { 1001 | get { return primaryKeys; } 1002 | } 1003 | } 1004 | 1005 | /// 1006 | /// Class that stores information for columns in a database table. 1007 | /// 1008 | public class Column 1009 | { 1010 | // Private variable used to hold the property values 1011 | private string name; 1012 | private string type; 1013 | private string length; 1014 | private string precision; 1015 | private string scale; 1016 | private bool isRowGuidCol; 1017 | private bool isIdentity; 1018 | private bool isComputed; 1019 | 1020 | /// 1021 | /// Name of the column. 1022 | /// 1023 | public string Name 1024 | { 1025 | get { return name; } 1026 | set { name = value; } 1027 | } 1028 | 1029 | /// 1030 | /// Data type of the column. 1031 | /// 1032 | public string Type 1033 | { 1034 | get { return type; } 1035 | set { type = value; } 1036 | } 1037 | 1038 | /// 1039 | /// Length in bytes of the column. 1040 | /// 1041 | public string Length 1042 | { 1043 | get { return length; } 1044 | set { length = value; } 1045 | } 1046 | 1047 | /// 1048 | /// Precision of the column. Applicable to decimal, float, and numeric data types only. 1049 | /// 1050 | public string Precision 1051 | { 1052 | get { return precision; } 1053 | set { precision = value; } 1054 | } 1055 | 1056 | /// 1057 | /// Scale of the column. Applicable to decimal, and numeric data types only. 1058 | /// 1059 | public string Scale 1060 | { 1061 | get { return scale; } 1062 | set { scale = value; } 1063 | } 1064 | 1065 | /// 1066 | /// Flags the column as a uniqueidentifier column. 1067 | /// 1068 | public bool IsRowGuidCol 1069 | { 1070 | get { return isRowGuidCol; } 1071 | set { isRowGuidCol = value; } 1072 | } 1073 | 1074 | /// 1075 | /// Flags the column as an identity column. 1076 | /// 1077 | public bool IsIdentity 1078 | { 1079 | get { return isIdentity; } 1080 | set { isIdentity = value; } 1081 | } 1082 | 1083 | /// 1084 | /// Flags the column as being computed. 1085 | /// 1086 | public bool IsComputed 1087 | { 1088 | get { return isComputed; } 1089 | set { isComputed = value; } 1090 | } 1091 | } 1092 | } 1093 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PocoSqlGenerator 2 | 3 | A simple windows forms application which creates 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 desktop and web applications) and basic stored procedures scripts (like insert, update, delete etc) for the selected database tables 4 | 5 | A simple guide on how to use this tool can be found at my blog : https://www.codeproject.com/Articles/1089855/Simple-POCO-N-SQL-Generator-in-Csharp 6 | 7 | # Contributing 8 | 9 | Altough I have tried to make this tool simple and easy to use but it might be missing feature X, or Y. If you want something that it can't currently provide, I love pull requests. If it's a bigger change, you can also create new tool using this code. 10 | 11 | 12 | # License 13 | 14 | [Microsoft Public License (Ms-PL)](http://www.microsoft.com/en-us/openness/licenses.aspx#MPL) 15 | 16 | --------------------------------------------------------------------------------