-
Notifications
You must be signed in to change notification settings - Fork 0
/
EF.Reverse.POCO.Core.ttinclude
1694 lines (1510 loc) · 78.3 KB
/
EF.Reverse.POCO.Core.ttinclude
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
// Copyright © Simon Hughes 2012
// v1.10.0
#>
<#@ template hostspecific="true" language="C#" #>
<#@ assembly name="EnvDTE" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Configuration" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ include file="EF.Utility.CS.ttinclude"#>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.Data.Common" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Globalization" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#@ import namespace="System.Configuration" #>
<#@ import namespace="System.Windows.Forms" #>
<#@ output extension=".cs"#>
<#
var code = new CodeGenerationTools(this);
string Namespace = code.VsNamespaceSuggestion();
var fileManager = EntityFrameworkTemplateFileManager.Create(this);
#>
<#+
// Settings
string ConnectionStringName = "";
bool IncludeViews = true;
string DbContextName = "MyDbContext";
bool MakeClassesPartial = true;
bool GenerateSeparateFiles = false;
bool UseCamelCase = true;
bool AddWcfDataAttributes = false;
string ExtraWcfDataContractAttributes = "";
string SchemaName = null;
Regex TableFilterExclude = null;
Regex TableFilterInclude = null;
string[] ConfigFilenameSearchOrder = null;
private string _connectionString = "";
private string _providerName = "";
private string _configFilePath = "";
private static readonly Regex RxCleanUp = new Regex(@"[^\w\d_]", RegexOptions.Compiled);
private static readonly Func<string, string> CleanUp = (str) =>
{
// Replace punctuation and symbols in variable names as these are not allowed.
int len = str.Length;
if (len == 0)
return str;
var sb = new StringBuilder();
bool replacedCharacter = false;
for(int n = 0; n < len; ++n )
{
char c = str[n];
if (c != '_' && (char.IsSymbol(c) || char.IsPunctuation(c)))
{
int ascii = c;
sb.AppendFormat("{0}", ascii);
replacedCharacter = true;
continue;
}
sb.Append(c);
}
if (replacedCharacter)
str = sb.ToString();
// Remove non alphanumerics
str = RxCleanUp.Replace(str, "");
if(char.IsDigit(str[0]))
str = "C" + str;
return str;
};
public string ConnectionString
{
get
{
return _connectionString;
}
}
public string ProviderName
{
get
{
return _providerName;
}
}
private static string CheckNullable(Column col)
{
string result = "";
if(col.IsNullable &&
col.PropertyType != "byte[]" &&
col.PropertyType != "string" &&
col.PropertyType != "Microsoft.SqlServer.Types.SqlGeography" &&
col.PropertyType != "Microsoft.SqlServer.Types.SqlGeometry")
result = "?";
return result;
}
private string GetConnectionString(ref string connectionStringName, out string providerName, out string configFilePath)
{
providerName = null;
configFilePath = String.Empty;
string result = "";
var paths = GetConfigPaths();
// Find a configuration file with the named connection string
foreach (var path in paths)
{
var configFile = new ExeConfigurationFileMap { ExeConfigFilename = path };
var config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
var connSection = config.ConnectionStrings;
if (string.IsNullOrEmpty(connectionStringName))
continue;
// Get the named connection string
try
{
result = connSection.ConnectionStrings[connectionStringName].ConnectionString;
providerName = connSection.ConnectionStrings[connectionStringName].ProviderName;
configFilePath = path;
return result; // found it
}
catch
{
result = "There is no connection string name called '" + connectionStringName + "'";
}
}
return result;
}
private void InitConnectionString()
{
if(!String.IsNullOrEmpty(_connectionString))
return;
_connectionString = GetConnectionString(ref ConnectionStringName, out _providerName, out _configFilePath);
if(!_connectionString.Contains("|DataDirectory|"))
return;
// Replace data directory path
string dataFilePath = GetDataDirectory();
_connectionString = _connectionString.Replace("|DataDirectory|", dataFilePath);
}
public EnvDTE.Solution GetSolution()
{
var serviceProvider = (IServiceProvider)Host;
if(serviceProvider == null)
throw new Exception("Host property returned unexpected value (null)");
var dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE));
if(dte == null)
throw new Exception("Unable to retrieve EnvDTE.DTE");
return dte.Solution;
}
public EnvDTE.Projects GetAllProjects()
{
return GetSolution().Projects;
}
public EnvDTE.Project GetCurrentProject()
{
var serviceProvider = (IServiceProvider)Host;
if(serviceProvider == null)
throw new Exception("Host property returned unexpected value (null)");
var dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE));
if(dte == null)
throw new Exception("Unable to retrieve EnvDTE.DTE");
var activeSolutionProjects = (Array)dte.ActiveSolutionProjects;
if(activeSolutionProjects == null)
throw new Exception("DTE.ActiveSolutionProjects returned null");
var dteProject = (EnvDTE.Project)activeSolutionProjects.GetValue(0);
if(dteProject == null)
throw new Exception("DTE.ActiveSolutionProjects[0] returned null");
return dteProject;
}
private string GetProjectPath(EnvDTE.Project project)
{
var info = new FileInfo(project.FullName);
return info.Directory == null ? string.Empty : info.Directory.FullName;
}
private List<string> GetConfigPaths()
{
var paths = new List<string>();
// Local project first
EnvDTE.Project project = GetCurrentProject();
paths.AddRange(GetConfigPathsInProject(project));
// Then other projects next
var projects = GetAllProjects();
foreach (EnvDTE.Project dteProject in projects)
{
paths.AddRange(GetConfigPathsInProject(dteProject));
}
return paths;
}
private List<string> GetConfigPathsInProject(EnvDTE.Project project)
{
var paths = new List<string>();
foreach (string filename in ConfigFilenameSearchOrder)
{
paths.AddRange(GetConfigPathsInProjectForFile(project, filename));
}
return paths;
}
private List<string> GetConfigPathsInProjectForFile(EnvDTE.Project project, string filename)
{
var paths = new List<string>();
foreach (EnvDTE.ProjectItem item in project.ProjectItems)
{
if (item.Name.Equals(filename, StringComparison.InvariantCultureIgnoreCase))
paths.Add(Path.Combine(GetProjectPath(project), item.Name));
}
return paths;
}
public string GetDataDirectory()
{
var project = GetCurrentProject();
return Path.GetDirectoryName(project.FileName) + "\\App_Data\\";
}
private static string ZapPassword(string connectionString)
{
var rx = new Regex("password=.*;", RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase);
return rx.Replace(connectionString, "password=**zapped**;");
}
private Tables LoadTables()
{
InitConnectionString();
string solutionPath = Path.GetDirectoryName(GetSolution().FileName) + "\\";
WriteLine("// This file was automatically generated.");
WriteLine("// Do not make changes directly to this file - edit the template instead.");
WriteLine("// ");
WriteLine("// The following connection settings were used to generate this file");
WriteLine("// ");
WriteLine("// Configuration file: \"{0}\"", _configFilePath.Replace(solutionPath, String.Empty));
WriteLine("// Connection String Name: \"{0}\"", ConnectionStringName);
WriteLine("// Connection String: \"{0}\"", ZapPassword(ConnectionString));
WriteLine("");
DbProviderFactory factory;
try
{
factory = DbProviderFactories.GetFactory(ProviderName);
}
catch(Exception x)
{
string error = x.Message.Replace("\r\n", "\n").Replace("\n", " ");
Warning(string.Format("Failed to load provider \"{0}\" - {1}", ProviderName, error));
WriteLine("");
WriteLine("// -----------------------------------------------------------------------------------------");
WriteLine("// Failed to load provider \"{0}\" - {1}", ProviderName, error);
WriteLine("// -----------------------------------------------------------------------------------------");
WriteLine("");
return new Tables();
}
try
{
using(DbConnection conn = factory.CreateConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
var reader = new SqlServerSchemaReader(conn, factory) { Outer = this };
var result = reader.ReadSchema(TableFilterExclude, UseCamelCase);
// Remove unrequired tables/views
for(int i = result.Count - 1; i >= 0; i--)
{
if(SchemaName != null && String.Compare(result[i].Schema, SchemaName, StringComparison.OrdinalIgnoreCase) != 0)
{
result.RemoveAt(i);
continue;
}
if(!IncludeViews && result[i].IsView)
{
result.RemoveAt(i);
continue;
}
if(TableFilterInclude != null && !TableFilterInclude.IsMatch(result[i].Name))
{
result.RemoveAt(i);
continue;
}
if(string.IsNullOrEmpty(result[i].PrimaryKeyNameHumanCase()))
{
result.RemoveAt(i);
}
}
result = reader.ReadForeignKeys(result, UseCamelCase);
result.SetPrimaryKeys();
conn.Close();
return result;
}
}
catch(Exception x)
{
string error = x.Message.Replace("\r\n", "\n").Replace("\n", " ");
Warning(string.Format("Failed to read database schema - {0}", error));
WriteLine("");
WriteLine("// -----------------------------------------------------------------------------------------");
WriteLine("// Failed to read database schema - {0}", error);
WriteLine("// -----------------------------------------------------------------------------------------");
WriteLine("");
return new Tables();
}
}
public enum Relationship
{
OneToOne,
OneToMany,
ManyToOne,
ManyToMany,
}
public static Relationship CalcRelationship(Table pkTable, Table fkTable, Column fkCol, Column pkCol)
{
bool fkTableSinglePrimaryKey = (fkTable.PrimaryKeys.Count() == 1);
bool pkTableSinglePrimaryKey = (pkTable.PrimaryKeys.Count() == 1);
// 1:1
if(fkCol.IsPrimaryKey && pkCol.IsPrimaryKey && fkTableSinglePrimaryKey && pkTableSinglePrimaryKey)
return Relationship.OneToOne;
// 1:n
if(fkCol.IsPrimaryKey && !pkCol.IsPrimaryKey && fkTableSinglePrimaryKey)
return Relationship.OneToMany;
// n:1
if(!fkCol.IsPrimaryKey && pkCol.IsPrimaryKey && pkTableSinglePrimaryKey)
return Relationship.ManyToOne;
// n:n
return Relationship.ManyToMany;
}
#region Nested type: Column
public class Column
{
public string Name;
public int DateTimePrecision;
public string Default;
public int MaxLength;
public int Precision;
public string PropertyName;
public string PropertyNameHumanCase;
public string PropertyType;
public int Scale;
public int Ordinal;
public bool IsIdentity;
public bool IsNullable;
public bool IsPrimaryKey;
public bool IsStoreGenerated;
public string Config;
public string ConfigFk;
public string Entity;
public string EntityFk;
private void SetupEntity()
{
Entity = string.Format("public {0}{1} {2} {3} // {4}{5}", PropertyType, CheckNullable(this), PropertyNameHumanCase, "{ get; set; }", Name, IsPrimaryKey ? " (Primary key)" : string.Empty);
}
private void SetupConfig()
{
bool hasDatabaseGeneratedOption = false;
switch(PropertyType.ToLower())
{
case "long":
case "short":
case "int":
case "double":
case "float":
case "decimal":
hasDatabaseGeneratedOption = true;
break;
}
string databaseGeneratedOption = string.Empty;
if (hasDatabaseGeneratedOption)
{
if (IsIdentity)
databaseGeneratedOption = ".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)";
if(IsStoreGenerated)
databaseGeneratedOption = ".HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)";
if(IsPrimaryKey && !IsIdentity && !IsStoreGenerated)
databaseGeneratedOption = ".HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)";
}
Config = string.Format("Property(x => x.{0}).HasColumnName(\"{1}\"){2}{3}{4}{5};", PropertyNameHumanCase, Name,
(IsNullable) ? ".IsOptional()" : ".IsRequired()",
(MaxLength > 0) ? ".HasMaxLength(" + MaxLength + ")" : string.Empty,
(Scale > 0) ? ".HasPrecision(" + Precision + "," + Scale + ")" : string.Empty,
databaseGeneratedOption);
}
public void SetupEntityAndConfig()
{
SetupEntity();
SetupConfig();
}
public void CleanUpDefault()
{
if (string.IsNullOrEmpty(Default))
return;
while (Default.First() == '(' && Default.Last() == ')')
{
Default = Default.Substring(1, Default.Length - 2);
}
if (Default.First() == '\'' && Default.Last() == '\'' && Default.Length > 1)
Default = string.Format("\"{0}\"", Default.Substring(1, Default.Length - 2));
switch (PropertyType.ToLower())
{
case "bool":
Default = (Default == "0") ? "false" : "true";
break;
case "string":
case "datetime":
case "timespan":
case "datetimeoffset":
if(Default.First() != '"')
Default = string.Format("\"{0}\"", Default);
if(Default.Contains('\\'))
Default = "@" + Default;
break;
case "long":
case "short":
case "int":
case "double":
case "float":
case "decimal":
case "byte":
case "guid":
if(Default.First() == '\"' && Default.Last() == '\"' && Default.Length > 1)
Default = Default.Substring(1, Default.Length - 2);
break;
case "byte[]":
case "System.Data.Spatial.DbGeography":
case "System.Data.Spatial.DbGeometry":
Default = string.Empty;
break;
}
if (string.IsNullOrWhiteSpace(Default))
return;
// Validate default
switch(PropertyType.ToLower())
{
case "long":
long l;
if (!long.TryParse(Default, out l))
Default = string.Empty;
break;
case "short":
short s;
if (!short.TryParse(Default, out s))
Default = string.Empty;
break;
case "int":
int i;
if(!int.TryParse(Default, out i))
Default = string.Empty;
break;
case "datetime":
DateTime dt;
if (!DateTime.TryParse(Default, out dt))
Default = Default.ToLower().Contains("getdate()") ? "DateTime.Now" : string.Empty;
else
Default = string.Format("DateTime.Parse({0})", Default);
break;
case "datetimeoffset":
DateTimeOffset dto;
if(!DateTimeOffset.TryParse(Default, out dto))
Default = Default.ToLower().Contains("sysdatetimeoffset()") ? "DateTimeOffset.Now" : string.Empty;
else
Default = string.Format("DateTimeOffset.Parse({0})", Default);
break;
case "timespan":
TimeSpan ts;
if(!TimeSpan.TryParse(Default, out ts))
Default = string.Empty;
else
Default = string.Format("TimeSpan.Parse({0})", Default);
break;
case "double":
double d;
if(!double.TryParse(Default, out d))
Default = string.Empty;
break;
case "float":
float f;
if(!float.TryParse(Default, out f))
Default = string.Empty;
break;
case "decimal":
decimal dec;
if(!decimal.TryParse(Default, out dec))
Default = string.Empty;
break;
case "byte":
byte b;
if(!byte.TryParse(Default, out b))
Default = string.Empty;
break;
case "bool":
bool x;
if(!bool.TryParse(Default, out x))
Default = string.Empty;
break;
case "guid":
if(Default.ToLower() == "newid()" || Default.ToLower() == "newsequentialid()")
Default = "Guid.NewGuid()";
break;
}
// Append type letters
switch(PropertyType.ToLower())
{
case "decimal":
Default = Default + "m";
break;
}
}
}
#endregion
#region Nested type: Inflector
/// <summary>
/// Summary for the Inflector class
/// </summary>
public static class Inflector
{
private static readonly List<InflectorRule> Plurals = new List<InflectorRule>();
private static readonly List<InflectorRule> Singulars = new List<InflectorRule>();
private static readonly List<string> Uncountables = new List<string>();
/// <summary>
/// Initializes the <see cref="Inflector"/> class.
/// </summary>
static Inflector()
{
AddPluralRule("$", "s");
AddPluralRule("s$", "s");
AddPluralRule("(ax|test)is$", "$1es");
AddPluralRule("(octop|vir)us$", "$1i");
AddPluralRule("(alias|status)$", "$1es");
AddPluralRule("(bu)s$", "$1ses");
AddPluralRule("(buffal|tomat)o$", "$1oes");
AddPluralRule("([ti])um$", "$1a");
AddPluralRule("sis$", "ses");
AddPluralRule("(?:([^f])fe|([lr])f)$", "$1$2ves");
AddPluralRule("(hive)$", "$1s");
AddPluralRule("([^aeiouy]|qu)y$", "$1ies");
AddPluralRule("(x|ch|ss|sh)$", "$1es");
AddPluralRule("(matr|vert|ind)ix|ex$", "$1ices");
AddPluralRule("([m|l])ouse$", "$1ice");
AddPluralRule("^(ox)$", "$1en");
AddPluralRule("(quiz)$", "$1zes");
AddSingularRule("s$", String.Empty);
AddSingularRule("ss$", "ss");
AddSingularRule("(n)ews$", "$1ews");
AddSingularRule("([ti])a$", "$1um");
AddSingularRule("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis");
AddSingularRule("(^analy)ses$", "$1sis");
AddSingularRule("([^f])ves$", "$1fe");
AddSingularRule("(hive)s$", "$1");
AddSingularRule("(tive)s$", "$1");
AddSingularRule("([lr])ves$", "$1f");
AddSingularRule("([^aeiouy]|qu)ies$", "$1y");
AddSingularRule("(s)eries$", "$1eries");
AddSingularRule("(m)ovies$", "$1ovie");
AddSingularRule("(x|ch|ss|sh)es$", "$1");
AddSingularRule("([m|l])ice$", "$1ouse");
AddSingularRule("(bus)es$", "$1");
AddSingularRule("(o)es$", "$1");
AddSingularRule("(shoe)s$", "$1");
AddSingularRule("(cris|ax|test)es$", "$1is");
AddSingularRule("(octop|vir)i$", "$1us");
AddSingularRule("(alias|status)$", "$1");
AddSingularRule("(alias|status)es$", "$1");
AddSingularRule("^(ox)en", "$1");
AddSingularRule("(vert|ind)ices$", "$1ex");
AddSingularRule("(matr)ices$", "$1ix");
AddSingularRule("(quiz)zes$", "$1");
AddIrregularRule("person", "people");
AddIrregularRule("man", "men");
AddIrregularRule("child", "children");
AddIrregularRule("sex", "sexes");
AddIrregularRule("tax", "taxes");
AddIrregularRule("move", "moves");
AddUnknownCountRule("equipment");
AddUnknownCountRule("information");
AddUnknownCountRule("rice");
AddUnknownCountRule("money");
AddUnknownCountRule("species");
AddUnknownCountRule("series");
AddUnknownCountRule("fish");
AddUnknownCountRule("sheep");
}
/// <summary>
/// Adds the irregular rule.
/// </summary>
/// <param name="singular">The singular.</param>
/// <param name="plural">The plural.</param>
private static void AddIrregularRule(string singular, string plural)
{
AddPluralRule(String.Concat("(", singular[0], ")", singular.Substring(1), "$"), String.Concat("$1", plural.Substring(1)));
AddSingularRule(String.Concat("(", plural[0], ")", plural.Substring(1), "$"), String.Concat("$1", singular.Substring(1)));
}
/// <summary>
/// Adds the unknown count rule.
/// </summary>
/// <param name="word">The word.</param>
private static void AddUnknownCountRule(string word)
{
Uncountables.Add(word.ToLower());
}
/// <summary>
/// Adds the plural rule.
/// </summary>
/// <param name="rule">The rule.</param>
/// <param name="replacement">The replacement.</param>
private static void AddPluralRule(string rule, string replacement)
{
Plurals.Add(new InflectorRule(rule, replacement));
}
/// <summary>
/// Adds the singular rule.
/// </summary>
/// <param name="rule">The rule.</param>
/// <param name="replacement">The replacement.</param>
private static void AddSingularRule(string rule, string replacement)
{
Singulars.Add(new InflectorRule(rule, replacement));
}
/// <summary>
/// Makes the plural.
/// </summary>
/// <param name="word">The word.</param>
/// <returns></returns>
public static string MakePlural(string word)
{
return ApplyRules(Plurals, word);
}
/// <summary>
/// Makes the singular.
/// </summary>
/// <param name="word">The word.</param>
/// <returns></returns>
public static string MakeSingular(string word)
{
return ApplyRules(Singulars, word);
}
/// <summary>
/// Applies the rules.
/// </summary>
/// <param name="rules">The rules.</param>
/// <param name="word">The word.</param>
/// <returns></returns>
private static string ApplyRules(IList<InflectorRule> rules, string word)
{
string result = word;
if(!Uncountables.Contains(word.ToLower()))
{
for(int i = rules.Count - 1; i >= 0; i--)
{
string currentPass = rules[i].Apply(word);
if(currentPass != null)
{
result = currentPass;
break;
}
}
}
return result;
}
/// <summary>
/// Converts the string to title case.
/// </summary>
/// <param name="word">The word.</param>
/// <returns></returns>
public static string ToTitleCase(string word)
{
string s = Regex.Replace(ToHumanCase(AddUnderscores(word)), @"\b([a-z])", match => match.Captures[0].Value.ToUpper());
bool digit = false;
string a = string.Empty;
foreach(char c in s)
{
if(Char.IsDigit(c))
{
digit = true;
a = a + c;
}
else
{
if(digit && Char.IsLower(c))
a = a + Char.ToUpper(c);
else
a = a + c;
digit = false;
}
}
return a;
}
/// <summary>
/// Converts the string to human case.
/// </summary>
/// <param name="lowercaseAndUnderscoredWord">The lowercase and underscored word.</param>
/// <returns></returns>
public static string ToHumanCase(string lowercaseAndUnderscoredWord)
{
return MakeInitialCaps(Regex.Replace(lowercaseAndUnderscoredWord, @"_", " "));
}
/// <summary>
/// Adds the underscores.
/// </summary>
/// <param name="pascalCasedWord">The pascal cased word.</param>
/// <returns></returns>
public static string AddUnderscores(string pascalCasedWord)
{
return
Regex.Replace(Regex.Replace(Regex.Replace(pascalCasedWord, @"([A-Z]+)([A-Z][a-z])", "$1_$2"), @"([a-z\d])([A-Z])", "$1_$2"), @"[-\s]", "_").ToLower();
}
/// <summary>
/// Makes the initial caps.
/// </summary>
/// <param name="word">The word.</param>
/// <returns></returns>
public static string MakeInitialCaps(string word)
{
return String.Concat(word.Substring(0, 1).ToUpper(), word.Substring(1).ToLower());
}
/// <summary>
/// Makes the initial lower case.
/// </summary>
/// <param name="word">The word.</param>
/// <returns></returns>
public static string MakeInitialLowerCase(string word)
{
return String.Concat(word.Substring(0, 1).ToLower(), word.Substring(1));
}
/// <summary>
/// Determine whether the passed string is numeric, by attempting to parse it to a double
/// </summary>
/// <param name="str">The string to evaluated for numeric conversion</param>
/// <returns>
/// <c>true</c> if the string can be converted to a number; otherwise, <c>false</c>.
/// </returns>
public static bool IsStringNumeric(string str)
{
double result;
return (double.TryParse(str, NumberStyles.Float, NumberFormatInfo.CurrentInfo, out result));
}
/// <summary>
/// Adds the ordinal suffix.
/// </summary>
/// <param name="number">The number.</param>
/// <returns></returns>
public static string AddOrdinalSuffix(string number)
{
if(IsStringNumeric(number))
{
int n = int.Parse(number);
int nMod100 = n % 100;
if(nMod100 >= 11 && nMod100 <= 13)
return String.Concat(number, "th");
switch(n % 10)
{
case 1:
return String.Concat(number, "st");
case 2:
return String.Concat(number, "nd");
case 3:
return String.Concat(number, "rd");
default:
return String.Concat(number, "th");
}
}
return number;
}
/// <summary>
/// Converts the underscores to dashes.
/// </summary>
/// <param name="underscoredWord">The underscored word.</param>
/// <returns></returns>
public static string ConvertUnderscoresToDashes(string underscoredWord)
{
return underscoredWord.Replace('_', '-');
}
#region Nested type: InflectorRule
/// <summary>
/// Summary for the InflectorRule class
/// </summary>
private class InflectorRule
{
private readonly Regex _regex;
private readonly string _replacement;
/// <summary>
/// Initializes a new instance of the <see cref="InflectorRule"/> class.
/// </summary>
/// <param name="regexPattern">The regex pattern.</param>
/// <param name="replacementText">The replacement text.</param>
public InflectorRule(string regexPattern, string replacementText)
{
_regex = new Regex(regexPattern, RegexOptions.IgnoreCase);
_replacement = replacementText;
}
/// <summary>
/// Applies the specified word.
/// </summary>
/// <param name="word">The word.</param>
/// <returns></returns>
public string Apply(string word)
{
if(!_regex.IsMatch(word))
return null;
string replace = _regex.Replace(word, _replacement);
if(word == word.ToUpper())
replace = replace.ToUpper();
return replace;
}
}
#endregion
}
#endregion
#region Nested type: SchemaReader
private abstract class SchemaReader
{
protected readonly DbCommand Cmd;
protected SchemaReader(DbConnection connection, DbProviderFactory factory)
{
Cmd = factory.CreateCommand();
if(Cmd != null)
Cmd.Connection = connection;
}
public GeneratedTextTransformation Outer;
public abstract Tables ReadSchema(Regex TableFilterExclude, bool useCamelCase);
public abstract Tables ReadForeignKeys(Tables result, bool useCamelCase);
protected void WriteLine(string o)
{
Outer.WriteLine(o);
}
}
#endregion
private class SqlServerSchemaReader : SchemaReader
{
private const string TableSQL = @"
SELECT [Extent1].[SchemaName],
[Extent1].[Name] AS TableName,
[Extent1].[TABLE_TYPE] AS TableType,
[UnionAll1].[Ordinal],
[UnionAll1].[Name] AS ColumnName,
[UnionAll1].[IsNullable],
[UnionAll1].[TypeName],
ISNULL([UnionAll1].[MaxLength],0) AS MaxLength,
ISNULL([UnionAll1].[Precision], 0) AS Precision,
ISNULL([UnionAll1].[Default], '') AS [Default],
ISNULL([UnionAll1].[DateTimePrecision], '') AS [DateTimePrecision],
ISNULL([UnionAll1].[Scale], 0) AS Scale,
[UnionAll1].[IsIdentity],
[UnionAll1].[IsStoreGenerated],
CASE WHEN ([Project5].[C2] IS NULL) THEN CAST(0 AS BIT)
ELSE [Project5].[C2]
END AS PrimaryKey
FROM (
SELECT QUOTENAME(TABLE_SCHEMA) + QUOTENAME(TABLE_NAME) [Id],
TABLE_SCHEMA [SchemaName],
TABLE_NAME [Name],
TABLE_TYPE
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE IN ('BASE TABLE', 'VIEW')
) AS [Extent1]
INNER JOIN (
SELECT [Extent2].[Id] AS [Id],
[Extent2].[Name] AS [Name],
[Extent2].[Ordinal] AS [Ordinal],
[Extent2].[IsNullable] AS [IsNullable],
[Extent2].[TypeName] AS [TypeName],
[Extent2].[MaxLength] AS [MaxLength],
[Extent2].[Precision] AS [Precision],
[Extent2].[Default],
[Extent2].[DateTimePrecision] AS [DateTimePrecision],
[Extent2].[Scale] AS [Scale],
[Extent2].[IsIdentity] AS [IsIdentity],
[Extent2].[IsStoreGenerated] AS [IsStoreGenerated],
0 AS [C1],
[Extent2].[ParentId] AS [ParentId]
FROM (
SELECT QUOTENAME(c.TABLE_SCHEMA) + QUOTENAME(c.TABLE_NAME) + QUOTENAME(c.COLUMN_NAME) [Id],
QUOTENAME(c.TABLE_SCHEMA) + QUOTENAME(c.TABLE_NAME) [ParentId],
c.COLUMN_NAME [Name],
c.ORDINAL_POSITION [Ordinal],
CAST(CASE c.IS_NULLABLE
WHEN 'YES' THEN 1
WHEN 'NO' THEN 0
ELSE 0
END AS BIT) [IsNullable],
CASE WHEN c.DATA_TYPE IN ('varchar', 'nvarchar', 'varbinary')
AND c.CHARACTER_MAXIMUM_LENGTH = -1 THEN c.DATA_TYPE + '(max)'
ELSE c.DATA_TYPE
END AS [TypeName],
c.CHARACTER_MAXIMUM_LENGTH [MaxLength],
CAST(c.NUMERIC_PRECISION AS INTEGER) [Precision],
CAST(c.DATETIME_PRECISION AS INTEGER) [DateTimePrecision],
CAST(c.NUMERIC_SCALE AS INTEGER) [Scale],
c.COLLATION_CATALOG [CollationCatalog],
c.COLLATION_SCHEMA [CollationSchema],