DotNetUtilities /EntityGenerator/MainForm.cs

Language C# Lines 591
MD5 Hash 39d7aa6035b7c234800850ce4c95fc4a
Repository https://github.com/RickyLin/DotNetUtilities.git View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Configuration;
using System.IO;
using System.Data.Entity.Design.PluralizationServices;
using System.Globalization;

namespace EntityGenerator
{
	public partial class MainForm : Form
	{
		private string _DefaultNamespace;
		private string _OutputPath;
		private ListItem[] _SelectedItems;
		private CodeType _CodeType;
		private string _DbContextName;
		private PluralizationService _PluralizationSvc;

		public MainForm()
		{
			InitializeComponent();
		}

		private void MainForm_Load(object sender, EventArgs e)
		{
			Task.Factory.StartNew(LoadTables);
			Task.Factory.StartNew(LoadViews);
			tbPath.Text = Path.Combine(Environment.CurrentDirectory, "Output");
			_PluralizationSvc = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en-us"));
			tbDefaultNamespace.Text = ConfigurationManager.AppSettings["defaultNamespace"];
		}

		private void LoadViews()
		{
			FillOutDatabaseObjectNames("cmdQueryViews", clbViews, DatabaseObjectType.View);
		}

		private void LoadTables()
		{
			FillOutDatabaseObjectNames("cmdQueryTables", clbTables, DatabaseObjectType.Table);
		}

		private void FillOutDatabaseObjectNames(string cmdName, CheckedListBox clb, DatabaseObjectType objectType)
		{
			string objectName;
			string strCmd = ConfigurationManager.AppSettings[cmdName];
			Database db = DatabaseFactory.CreateDatabase();
			Action beginUpdate = () => clb.BeginUpdate();
			clb.Invoke(beginUpdate);
			using (IDataReader reader = db.ExecuteReader(CommandType.Text, strCmd))
			{
				Action addItem;
				while (reader.Read())
				{
					objectName = reader.GetString(0);
					addItem = () => clb.Items.Add(new ListItem() { Value = objectName, Type = objectType });
					clb.Invoke(addItem);
				}
			}
			Action endUpdate = () => clb.EndUpdate();
			clb.Invoke(endUpdate);
		}

		private void cbAllTables_CheckedChanged(object sender, EventArgs e)
		{
			SetAllDatabaseObjectSelected(clbTables, cbAllTables);
		}

		private void cbAllViews_CheckedChanged(object sender, EventArgs e)
		{
			SetAllDatabaseObjectSelected(clbViews, cbAllViews);
		}

		private void SetAllDatabaseObjectSelected(CheckedListBox dbObjectList, CheckBox chkAll)
		{
			dbObjectList.BeginUpdate();
			for (int i = 0; i < dbObjectList.Items.Count; i++)
			{
				dbObjectList.SetItemChecked(i, chkAll.Checked);
			}
			dbObjectList.EndUpdate();
		}

		private void btnGenerate_Click(object sender, EventArgs e)
		{
			lbOutputs.Items.Clear();
			ListItem[] items = new ListItem[clbTables.CheckedItems.Count + clbViews.CheckedItems.Count];
			int itemIndex = 0;
			foreach (object item in clbTables.CheckedItems)
			{
				items[itemIndex] = item as ListItem;
				itemIndex++;
			}
			foreach (object item in clbViews.CheckedItems)
			{
				items[itemIndex] = item as ListItem;
				itemIndex++;
			}
			_SelectedItems = items;

			_CodeType = rbEntities.Checked ? CodeType.Entities : CodeType.DbContext;
			_DbContextName = tbDbContextName.Text;
			_DefaultNamespace = tbDefaultNamespace.Text;
			_OutputPath = tbPath.Text.EndsWith("\\") ? tbPath.Text : tbPath.Text + "\\";
			if (Directory.Exists(_OutputPath) == false)
				Directory.CreateDirectory(_OutputPath);

			Task.Factory.StartNew(StartToGenerate);
		}

		private void StartToGenerate()
		{
			ParallelLoopResult result;
			switch (_CodeType)
			{
				case CodeType.Entities:
					result = Parallel.ForEach(_SelectedItems, GenerateEntityObject);
					break;
				case CodeType.DbContext:
					//result = Parallel.ForEach(_SelectedItems, GenerateDbContext);
					Task t = Task.Factory.StartNew(GenerateDbContext);
					t.Wait();
					break;
			}
				

			Action addDone = () => lbOutputs.Items.Add("All done.");
			lbOutputs.Invoke(addDone);
		}

		private string GetTypeName(int dbTypeID, bool isNullable)
		{
			DataType[] types = GetDataTypes();
			DataType dt = types.FirstOrDefault(t => t.DbTypeID == dbTypeID);
			if (dt == null)
			{
				return "ERROR_DbType_" + dbTypeID.ToString();
			}
			return isNullable ? dt.NullableTypeName : dt.TypeName;
		}

		private DataType[] GetDataTypes()
		{
			DataType[] types = {
				new DataType(34, "image", "byte[]", "byte[]"), 
				new DataType(35, "text", "string", "string"), 
				new DataType(36, "uniqueidentifier", "Guid", "Guid?"), 
				new DataType(40, "date", "DateTime", "DateTime?"), 
				new DataType(41, "time", "TimeSpan", "TimeSpan?"), 
				//new DataType(42, "datetime2", "", ""), 
				//new DataType(43, "datetimeoffset", "", ""), 
				new DataType(48, "tinyint", "byte", "byte?"), 
				new DataType(52, "smallint", "short", "short?"), 
				new DataType(56, "int", "int", "int?"), 
				new DataType(58, "smalldatetime", "DateTime", "DateTime?"), 
				new DataType(59, "real", "float", "float?"), 
				new DataType(60, "money", "decimal", "decimal?"), 
				new DataType(61, "datetime", "DateTime", "DateTime?"), 
				new DataType(62, "float", "double", "double?"), 
				new DataType(98, "sql_variant", "object", "object"), 
				new DataType(99, "ntext", "string", "string"), 
				new DataType(104, "bit", "bool", "bool?"), 
				new DataType(106, "decimal", "decimal", "decimal?"), 
				new DataType(108, "numeric", "decimal", "decimal?"), 
				//new DataType(122, "smallmoney", "", ""), 
				new DataType(127, "bigint", "long", "long?"), 
				//new DataType(240, "hierarchyid", "", ""), 
				//new DataType(240, "geometry", "", ""), 
				//new DataType(240, "geography", "", ""), 
				new DataType(165, "varbinary", "byte[]", "byte[]"), 
				new DataType(167, "varchar", "string", "string"), 
				//new DataType(173, "binary", "", ""), 
				new DataType(175, "char", "string", "string"), 
				//new DataType(189, "timestamp", "", ""), 
				new DataType(231, "nvarchar", "string", "string"), 
				new DataType(239, "nchar", "string", "string"),
				new DataType(241, "xml", "string", "string")
				//new DataType(231, "sysname", "", "")
			};

			return types;
		}

		#region methods to generate source files

		private void GenerateDbContext()
		{
			string indent = string.Empty;
			using (FileStream fs = File.Create(string.Format("{0}{1}_Generated.cs", _OutputPath, _DbContextName)))
			{
				using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
				{
					// comments
					WriteWarnningComments(sw);

					// namespace declarations
					WriteLine(sw, indent, GetNamespaceDeclarations());
					sw.WriteLine();

					//namespace
					sw.Write("namespace ");
					sw.WriteLine(_DefaultNamespace);

					// the { for namespace
					sw.WriteLine("{");
					PushIndent(ref indent);

					// class name
					WriteLine(sw, indent, string.Format("public partial class {0} : DbContext", _DbContextName));

					// the { for class
					WriteLine(sw, indent, "{");

					PushIndent(ref indent);

					// properties
					GenerateDbContextProperties(sw, indent);
					sw.WriteLine();

					// override methods
					GenerateDbContextMethods(sw, indent);

					PopIndent(ref indent);

					// the } for class
					WriteLine(sw, indent, "}");

					// the } for namespace
					PopIndent(ref indent);
					WriteLine(sw, indent, "}");
				}
			}
		}

		private void GenerateDbContextMethods(StreamWriter sw, string indent)
		{
			// constructor
			/*
			 * the constructor looks like this:
			 * 
				public _DbContactName(string nameOrConnectionString)
					: base(nameOrConnectionString)
				{
			 * 
			 * */
			WriteLine(sw, indent, string.Format("public {0}(string nameOrConnectionString)", _DbContextName));
			PushIndent(ref indent);
			WriteLine(sw, indent, ": base(nameOrConnectionString)");
			PopIndent(ref indent);
			WriteLine(sw, indent, "{");
			WriteLine(sw, indent, "}");
			sw.WriteLine();

			// OnModelCreating method
			/*
			 * The generated OnModelCreating method looks like this:
				protected override void OnModelCreating(DbModelBuilder modelBuilder)
				{
					Configuration.ProxyCreationEnabled = false;
					Database.SetInitializer<RcDbContext>(null);
					modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
					base.OnModelCreating(modelBuilder);
				}
			*/
			WriteLine(sw, indent, "protected override void OnModelCreating(DbModelBuilder modelBuilder)");
			WriteLine(sw, indent, "{");
			PushIndent(ref indent);
			WriteLine(sw, indent, string.Format("Database.SetInitializer<{0}>(null);", _DbContextName));
			WriteLine(sw, indent, "base.OnModelCreating(modelBuilder);");
			WriteLine(sw, indent, "modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();");
			WriteLine(sw, indent, "Configuration.ProxyCreationEnabled = false;");
			PopIndent(ref indent);
			WriteLine(sw, indent, "}");
		}

		private void GenerateDbContextProperties(StreamWriter sw, string indent)
		{
			string className, propertyName, statement;
			foreach (ListItem item in _SelectedItems)
			{
				className = GetClassName(item.Value);
				if (_PluralizationSvc.IsPlural(className))
				{
					propertyName = className;
				}
				else
				{
					propertyName = _PluralizationSvc.Pluralize(className);
				}

				statement = string.Format("public DbSet<{0}> {1} {{ get; set; }}", className, propertyName);
				WriteLine(sw, indent, statement);
			}
		}

		private void GenerateEntityObject(ListItem objectItem)
		{
			string objectName = objectItem.Value;
			string className = GetClassName(objectName);
			string indent = string.Empty;
			using (FileStream fs = File.Create(string.Format("{0}{1}_Generated.cs", _OutputPath, className)))
			{
				using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
				{
					// comments
					WriteWarnningComments(sw);

					// namespace declarations
					WriteLine(sw, indent, GetNamespaceDeclarations());
					sw.WriteLine();

					//namespace
					sw.Write("namespace ");
					sw.WriteLine(_DefaultNamespace);

					// the { for namespace
					sw.WriteLine("{");
					PushIndent(ref indent);

					// class name
					if (className != objectName)
					{
						WriteLine(sw, indent, string.Format("[Table(\"{0}\")]", objectName));
					}
					WriteLine(sw, indent, string.Format("public partial class {0}", className));

					// the { for class
					WriteLine(sw, indent, "{");

					// properties
					PushIndent(ref indent);
					GenerateProperties(objectName, className, sw, indent);
					PopIndent(ref indent);

					// the } for class
					WriteLine(sw, indent, "}");

					// the } for namespace
					PopIndent(ref indent);
					WriteLine(sw, indent, "}");
				}
			}

			Action addDone = () => lbOutputs.Items.Add(objectName + ": done.");
			lbOutputs.Invoke(addDone);
		}

		private void WriteWarnningComments(StreamWriter sw)
		{
			sw.WriteLine("/*");
			sw.WriteLine(" * The code is generated by code generator.");
			sw.WriteLine(" * Do not modify this file. Any modifications will lose when the file is regenerated.");
			sw.WriteLine(" * Please extend these entity classes by taking advantage of the partical class feature.");
			sw.WriteLine(" */");
			sw.WriteLine();
		}

		private void Write(StreamWriter sw, string indent, string statement)
		{
			sw.Write(indent);
			sw.Write(statement);
		}

		private void WriteLine(StreamWriter sw, string indent, string statement)
		{
			sw.Write(indent);
			sw.WriteLine(statement);
		}

		private void GenerateProperties(string tableName, string className, StreamWriter sw, string indent)
		{
			string strCmd = string.Format(
				@"SELECT C.[name] AS ColumnName, C.system_type_id AS DbTypeID, C.is_nullable AS IsNullable, C.max_length AS MaxLength
	, EPA.[value] AS AttributeValue, EPD.[value] AS DescriptionValue
	, Case When EPP.[value] IS NULL Then
			REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(C.[name],'-','_'), '/','_'),'#','Number'),'.','_'),' ','_')
		Else EPP.[value] End AS PropertyName, EPL.[value] AS PropertyLabel, EPDT.[value] AS PropertyDataType
FROM sys.columns C
LEFT JOIN sys.extended_properties EPA ON EPA.major_id = C.[object_id] AND EPA.minor_id = C.column_id AND EPA.name IN ('SYN_EFAttribute')
LEFT JOIN sys.extended_properties EPP ON EPP.major_id = C.[object_id] AND EPP.minor_id = C.column_id AND EPP.name IN ('SYN_EFPropertyName')
LEFT JOIN sys.extended_properties EPD ON EPD.major_id = C.[object_id] AND EPD.minor_id = C.column_id AND EPD.name IN ('MS_Description')
LEFT JOIN sys.extended_properties EPL ON EPL.major_id = C.[object_id] AND EPL.minor_id = C.column_id AND EPL.name IN ('SYN_EFPropertyLabel')
LEFT JOIN sys.extended_properties EPDT ON EPDT.major_id = C.[object_id] AND EPDT.minor_id = C.column_id AND EPDT.name IN ('SYN_EFPropertyDataType')
WHERE [object_id] = Object_ID('{0}') 
ORDER BY column_id", tableName);
			Database db = DatabaseFactory.CreateDatabase();
			using (IDataReader reader = db.ExecuteReader(CommandType.Text, strCmd))
			{
				string propertyName, columnName, attributeValue, descriptionValue, propertyType, propertyLabel, propertyDataType;
				int maxLength, dbTypeID;
				bool isNullable;
				while (reader.Read())
				{
					columnName = reader["ColumnName"].ToString();
					propertyName = reader["PropertyName"].ToString();
					dbTypeID = int.Parse(reader["DbTypeID"].ToString());
					isNullable = (bool)reader["IsNullable"];
					propertyType = GetTypeName(dbTypeID, isNullable);
					propertyLabel = reader["PropertyLabel"].ToString();
					propertyDataType = reader["PropertyDataType"].ToString();
					//if (propertyType == "ERROR")
					//{
					//	MessageBox.Show(string.Format("Cannot get type name for the type id: {0}", dbTypeID));
					//}

					maxLength = int.Parse(reader["MaxLength"].ToString());
					if (string.Compare(propertyName, className + "ID", true) == 0)
					{
						//WriteLine(sw, indent, string.Format("[Column(\"{0}\")]", columnName));
						//propertyName = "Id";
						WriteLine(sw, indent, "[Key]");
					}
					else if (propertyName == className)
						propertyName += "Content";
					else if (propertyName != columnName)
					{
						WriteLine(sw, indent, string.Format("[Column(\"{0}\")]", columnName));
					}
					else if (className.EndsWith("View", StringComparison.CurrentCultureIgnoreCase)
						&& string.Compare(propertyName, className.Substring(0, className.Length - 4) + "ID", true) == 0)
					{
						WriteLine(sw, indent, "[Key]");
					}

					// generate comment
					descriptionValue = reader["DescriptionValue"] is DBNull ? null : reader["DescriptionValue"].ToString();
					if (!string.IsNullOrEmpty(descriptionValue))
					{
						WriteLine(sw, indent, "/// <summary>");
						WriteLine(sw, indent, "/// " + descriptionValue);
						WriteLine(sw, indent, "/// </summary>");
					}

					// generate attributes
					attributeValue = reader["AttributeValue"] is DBNull ? null : reader["AttributeValue"].ToString();
					if (!string.IsNullOrEmpty(attributeValue))
					{
						string[] attributes = attributeValue.Split('|');
						foreach (string attr in attributes)
						{
							WriteLine(sw, indent, string.Format("[{0}]", attr));
						}
					}
					if (propertyType == "string" && maxLength > 0)
						WriteLine(sw, indent, string.Format("[StringLength({0})]", maxLength));

					if (propertyType.StartsWith("DateTime"))
					{
						WriteLine(sw, indent, "[DataType(DataType.Date)]");
						WriteLine(sw, indent, "[DisplayFormat(DataFormatString = \"{0:d}\", ApplyFormatInEditMode = true)]");
					}

					if (!isNullable)
					{
						WriteLine(sw, indent, "[Required]");
					}

					if (!string.IsNullOrEmpty(propertyLabel))
					{
						WriteLine(sw, indent, string.Format("[Display(Name = \"{0}\")]", propertyLabel));
					}

					if (!string.IsNullOrEmpty(propertyDataType))
					{
						WriteLine(sw, indent, string.Format("[DataType(DataType.{0})]", propertyDataType));
					}

					// generate property
					WriteLine(sw, indent, string.Format("public {0} {1} {{ get; set; }}", propertyType, propertyName));
					sw.WriteLine();
				}
			}
		}

		private void PushIndent(ref string indent)
		{
			indent = indent + "\t";
		}

		private void PopIndent(ref string indent)
		{
			indent = indent.Substring(1);
		}

		private string GetNamespaceDeclarations()
		{
			return @"using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;";
		}

		private string GetClassName(string tableName)
		{
			string className = tableName;
			if (char.IsLower(className[0]))
			{
				className = string.Format("{0}{1}", char.ToUpper(className[0]), className.Substring(1));
			}
			if (className.Contains('_'))
			{
				string[] nameParts = className.Split('_');
				if (_PluralizationSvc.IsPlural(nameParts[nameParts.Length - 1]))
					nameParts[1] = _PluralizationSvc.Singularize(nameParts[nameParts.Length - 1]);
				className = string.Join("_", nameParts);
			}
			else
			{
				if (_PluralizationSvc.IsPlural(className))
					className = _PluralizationSvc.Singularize(className);
			}

			if (className.StartsWith("Ref_", StringComparison.CurrentCultureIgnoreCase))
				return className.Substring(4);

			if (className.StartsWith("vw_", StringComparison.CurrentCultureIgnoreCase))
				return className.Substring(3) + "View";
			else if (className.StartsWith("vw", StringComparison.CurrentCultureIgnoreCase))
				return className.Substring(2) + "View";
			return className;
		}

		#endregion

		private void tbTableFilter_TextChanged(object sender, EventArgs e)
		{
			FilterListItem(clbTables, tbTableFilter.Text);
		}

		private void tbViewFilter_TextChanged(object sender, EventArgs e)
		{
			FilterListItem(clbViews, tbViewFilter.Text);
		}

		private void FilterListItem(CheckedListBox clb, string filter)
		{
			if (string.IsNullOrEmpty(filter))
				return;
			ListItem li;
			for (int i = 0; i < clb.Items.Count; i++)
			{
				li = clb.Items[i] as ListItem;
				if (li.Value.StartsWith(filter, StringComparison.CurrentCultureIgnoreCase))
				{
					clb.SetSelected(i, true);
					break;
				}
			}
		}

		private void tbTableFilter_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar == ' ')
			{
				CheckSelectedListItem(clbTables);
				e.Handled = true;
				tbTableFilter.Text = string.Empty;
			}
		}

		private void tbViewFilter_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar == ' ')
			{
				CheckSelectedListItem(clbViews);
				e.Handled = true;
				tbViewFilter.Text = string.Empty;
			}
		}

		private void CheckSelectedListItem(CheckedListBox clb)
		{
			if (clb.SelectedIndex < 0)
				return;
			clb.SetItemChecked(clb.SelectedIndex, !clb.GetItemChecked(clb.SelectedIndex));
		}
	}
}
Back to Top