-
Notifications
You must be signed in to change notification settings - Fork 22
/
NetTiers.cst
5465 lines (4666 loc) · 348 KB
/
NetTiers.cst
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
<%@ CodeTemplate Src="TemplateLib/CommonSqlCode.cs" Inherits="MoM.Templates.CommonSqlCode" Language="C#" TargetLanguage="Text" Description="NetTiers main template." Debug="True" ResponseEncoding="UTF-8" NoWarn="0108,0618,1572,1573,1574,0162,2002" CompilerVersion="v3.5"%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="System.Design" %>
<%@ Assembly Name="System.DirectoryServices" %>
<%@ Assembly Name="System.Web" %>
<%@ Assembly Name="System.Xml" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Import NameSpace="System.IO" %>
<%@ Import NameSpace="System.Text" %>
<%@ Import NameSpace="System.Text.RegularExpressions" %>
<%@ Import NameSpace="System.Diagnostics" %>
<%@ Import NameSpace="System.Xml" %>
<%@ Import NameSpace="System.Xml.Xsl" %>
<%@ Import NameSpace="System.Xml.XPath" %>
<%-- 1. Datasource --%>
<%@ Property Name="ChooseSourceDatabase" Type="SchemaExplorer.DatabaseSchema" DeepLoad="True" Optional="False" Category="01. Getting Started - Required" Description="Database that the tables views, and stored procedures should be based on. IMPORTANT!!! If SourceTables and SourceViews are left blank, the Entire Database will then be generated." %>
<%-- 2. Framework Generation Category --%>
<%@ Property Name="ExecuteSql" Type="System.Boolean" Default="False" Category="02. Framework Generation - Optional" Description="If true the stored procedures are installed on the sql server. (The SQL file is generated in all cases)" %>
<%@ Property Name="ExecuteViews" Type="System.Boolean" Default="False" Category="02. Framework Generation - Optional" Description="If true the views are re-run on the sql server. This helps to re-generate the meta data for views, and catch views that no longer compile. This causes a double hit to the sql server so generation speed will take a hit. (The SQL View file is generated in all cases)" %>
<%@ Property Name="ExtractSprocs" Type="System.Boolean" Default="False" Category="02. Framework Generation - Optional" Description="If true the custom stored procedures are extracted and written to individual sql files. Useful for source control history." %>
<%@ Property Name="ExtractViews" Type="System.Boolean" Default="False" Category="02. Framework Generation - Optional" Description="If true the database views are extracted and written to individual sql files. Useful for source control history." %>
<%@ Property Name="ExtractTables" Type="System.Boolean" Default="False" Category="02. Framework Generation - Optional" Description="If true the database tables are extracted and written to individual sql files. Useful for source control history." %>
<%@ Property Name="SQLFolderName" Type="System.String" Category="02. Framework Generation - Optional" Description="The sub folder to output the SQL scripts" Default="SQL" Optional="False"%>
<%@ Property Name="ViewReport" Type="System.Boolean" Default="True" Category="02. Framework Generation - Optional" Description="Indicates if the html report should launched at the end of the generation." %>
<%@ Property Name="AutoIncrementBuildVersion" Type="System.Boolean" Default="True" Category="02. Framework Generation - Optional" Description="Indicates if assembley build version should be auto incremented." %>
<%@ Property Name="LaunchVisualStudio" Type="System.Boolean" Default="True" Category="02. Framework Generation - Optional" Description="Attempts to launch visual studio with the generated solution only if there are no instances already open." %>
<%@ Property Name="IncludeUnitTest" Type="MoM.Templates.UnitTestStyle" Default="None" Category="02. Framework Generation - Optional" Description="Indicates type of Unit tests to be generated." %>
<%@ Property Name="IncludeComponentLayer" Type="MoM.Templates.ComponentPatternType" Category="02. Framework Generation - Optional" Description="The pattern type to implement in the Component Layer." Default="None" %>
<%@ Property Name="IncludeWCFDataAttributes" Type="System.Boolean" Default="False" Category="02. Framework Generation - Optional" Description="Indicates if the WCF attributes, [DataContract] and [DataMember], should be included on the entity classes." %>
<%@ Property Name="SerializeEntityState" Type="System.Boolean" Default="False" Category="02. Framework Generation - Optional" Description="Indicates if the EntityState property should be included during serialization. Useful if needing to know what state the entity is in over webservices." %>
<%@ Property Name="EntLibVersion" Type="MoM.Templates.EntLibVersion" Default="v6_0" Category="02. Framework Generation - Optional" Description="Indicates the Enterprise Library version to use. Options include v3.1, v5.0" %>
<%@ Property Name="VisualStudioVersion" Type="MoM.Templates.VSNetVersion" Default="v2013" Category="02. Framework Generation - Optional" Description="Indicates the Version of Visual Studio to target. Options include v2005, v2008 and v2010" %>
<%@ Property Name="DotNetVersion" Type="MoM.Templates.DotNetFrameworkVersion" Default="v4_5" Category="02. Framework Generation - Optional" Description="Indicates the Version of Dot Net to target. Options include v2, v3 and v3.5" %>
<%@ Property Name="IncludeXmlAttributes" Type="System.Boolean" Default="False" Category="02. Framework Generation - Optional" Description="Indicates if the Xml attributes, [XmlElement(IsNullable=true)], should be included on the entity classes." %>
<%@ Property Name="CustomCodeFolderName" Type="System.String" Category="02. Framework Generation - Optional" Description="If specified, indicates the name of a folder that can contains custom classes to dynamically add to each project." Default="App_Code" %>
<%@ Property Name="EqualitySemantics" Type="MoM.Templates.EqualitySemantics" Default="Value" Category="02. Framework Generation - Optional" Description="Equality semantics used for Entity instances. If 'Reference', default reference type semantics will be used (based on object identity). If 'Value', Equals() and GetHashCode() will be overridden to use value semantics (based on object contents)." %>
<%@ Property Name="TimeStandard" Type="TimeStandardEnum" Default="Local" Category="02. Framework Generation - Optional" Description="Standard used for generating DateTime values. If 'UTC' DateTime is generated based on UtcNow. If 'Local' DateTime is generated based on DateTime.Now" %>
<%@ Property Name="IsConnectionStringAzure" Type="System.Boolean" Default="False" Category="02. Framework Generation - Optional" Description="Indicates if at runtime the netTiersConnectionString is read from Window Azure's ServiceConfiguration.cscfg or from Web.config/app.config." %>
<%@ Property Name="EntityCacheLayer" Type="MoM.Templates.CacheLayer" Default="None" Category="02. Framework Generation - Optional" Description="Indicates if the Cache code should be written for the enabled CacheTables entities using Enterprise Library or System.Runtime.Caching." %>
<%@ Property Name="EnableViewCache" Type="System.Boolean" Default="True" Category="02. Framework Generation - Optional" Description="If a cache layer has been chosen, then also create cache methods for all views" %>
<%-- 3. Namespaces Category --%>
<%@ Property Name="BusinessLogicLayerNameSpace" Type="System.String" Category="03. Namespaces - Required" Description="The sub namespace that is added to the root namespace for the entities." Default="Entities" Optional="False" %>
<%@ Property Name="DataAccessLayerNameSpace" Type="System.String" Category="03. Namespaces - Required" Description="The sub namespace for the Data access layer components classes." Default="Data" Optional="False"%>
<%@ Property Name="UnitTestsNameSpace" Type="System.String" Category="03. Namespaces - Required" Description="The sub namespace for the UnitTests classes." Default="UnitTests" %>
<%-- End Required, The Rest Optional --%>
<%-- General Category --%>
<%@ Property Name="CompanyName" Optional="True" Type="System.String" Category="04. General - Advanced" Description="The name of your company. This is only for documenation." %>
<%@ Property Name="CompanyURL" Optional="True" Type="System.String" Category="04. General - Advanced" Description="The URL of your company. This is only for documenation." %>
<%@ Property Name="SignAssembly" Type="System.Boolean" Category="04. General - Advanced" Description="If true, projects will try to sign the assemblies and search for the snk in the local directory." Default="false" %>
<%-- 5.0 Web Library --%>
<%@ Property Name="GenerateWebLibrary" Type="System.Boolean" Default="true" Category="05. WebLibrary - Advanced" Description="Indicates if the web library should be generated. This contains the EntityDataSource and Other Helpful ASP.net utility classes." %>
<%@ Property Name="IncludeDesignTimeSupport" Type="System.Boolean" Default="true" Category="05. WebLibrary - Advanced" Description="Indicates if Visual Studio design-time support should be provided for the Web Library controls." %>
<%@ Property Name="DataSourceEnableTransactionDefault" Type="System.Boolean" Default="true" Category="05. WebLibrary - Advanced" Description="Sets the default for the EnableTransaction property on the data source controls." %>
<%-- 6.0 ASP.Net Admin Controls --%>
<%-- 6.0 webservice --%>
<%@ Property Name="WebServiceClassName" Type="System.String" Optional="True" Default="" Category="06. Web - Advanced" Description="The class name of the Web Services. Defaults to Namespace + 'Services' if not specified." %>
<%@ Property Name="GenerateWebservice" Type="System.Boolean" Default="false" Category="06. Web - Advanced" Description="Indicates if the webservice dataaccesslayer should be generated" %>
<%@ Property Name="AttemptCreateLocalVirtualDirectory" Type="System.Boolean" Default="false" Category="06. Web - Advanced" Description="Indicates if you would like the generator to attempt to create the virtual directory for the url specified in WebServiceUrl if it doesn't exist for the WebserviceOutput directory." %>
<%-- 6.5 ASP.Net Website --%>
<%@ Property Name="GenerateWebsite" Type="System.Boolean" Default="true" Category="06b. Website - Advanced" Description="Indicates if a complete website should be generated." %>
<%@ Property Name="UseWebAppProject" Type="System.Boolean" Default="false" Category="06b. Website - Advanced" Description="Indicates if a Web Application Project file should be generated. Note: you must have the Visual Studio extension installed in order to open the project." %>
<%@ Property Name="OverwriteWebConfig" Type="System.Boolean" Default="false" Category="06b. Website - Advanced" Description="Indicates if the Web.config should be overwritten." %>
<%@ Property Name="IncludeAtlasLibrary" Type="System.Boolean" Default="false" Category="06b. Website - Advanced" Description="Indicates whether to include a reference to the Atlas component library." %>
<%@ Property Name="IncludeAtlasToolkit" Type="System.Boolean" Default="false" Category="06b. Website - Advanced" Description="Indicates whether to include a reference to the Atlas Control Toolkit. This property is only taken into account when IncludeAtlasLibrary is true." %>
<%@ Property Name="GenerateWebsiteAdmin" Type="System.Boolean" Default="true" Category="06b. Website - Advanced" Description="Indicates if the web admin should be generated." %>
<%@ Property Name="DateFormat" Type="System.String" Default="MM/dd/yyyy" Category="06b. Website - Advanced" Description="The format to be used when displaying dates in the web site." %>
<%-- 7.0 Retry of SQL statements --%>
<%@ Property Name="RetryEnabled" Optional="False" Type="System.Boolean" Category="07. CRUD - Advanced" Default="false" Description="Enabling Retry will add code retry the queries that failed with data exceptions. Useful to if your database becomes temporarily unavailable." %>
<%@ Property Name="RetryMaxAttempts" Optional="True" Type="System.Int32" Category="07. CRUD - Advanced" Description="The number of attempts that will be made." Default="5" %>
<%@ Property Name="RetrySleepTime" Optional="True" Type="System.Int32" Category="07. CRUD - Advanced" Description="The number of milliseconds that the current thread will sleep between attempts. Sleep only occurs if an exception is thrown." Default="1000" %>
<%@ Property Name="RetrySleepStyle" Optional="True" Type="MoM.Templates.SleepStyle" Category="07. CRUD - Advanced" Description="" %>
<%-- 7.0 CRUD Options --%>
<%@ Property Name="LibraryPath" Type="System.String" Default="References" Category="07. CRUD - Advanced" Description="Path of the assembly library directory from the project output directory root." %>
<%@ Property Name="IncludeCustoms" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If true custom stored procedures (that starts with '_TableName_') will be detected and generated." %>
<%@ Property Name="CustomNonMatchingReturnType" Type="CustomNonMatchingReturnType" Default="DataSet" Category="07. CRUD - Advanced" Description="When using custom stored procedures, if the returned rows do not match the fields in an entity, a DataSet or IDataReader will be returned. Choose One. This is useful if you've returned more than one resultset in a custom procedure; you can use a ConvertToDataSet(IDataReader) method in the Utility class to convert that to a DataSet." %>
<%@ Property Name="CustomDataException" Optional="False" Type="System.Boolean" Category="07. CRUD - Advanced" Default="true" Description="Enabling this option will cause the NetTiers data later to wrap its exceptions in a custom NetTiersDataException object with additional information." %>
<%@ Property Name="DbExecutionTimer" Optional="False" Type="System.Boolean" Category="07. CRUD - Advanced" Default="true" Description="Enabling this option will add a Stopwatch timer count to the custom NetTiersDataException timing how long the database execution was running for." %>
<%@ Property Name="IncludeDrop" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If True then drop statements will be generated in accordance with the DropStyle. If False then no procedures will be droppped" %>
<%@ Property Name="DropStyle" Type="DropStyleEnum" Default="Entity" Category="07. CRUD - Advanced" Description="If Entity then drop statements will be generated to drop existing stored procedures for procedures being generated. If All then all existing netTiers procedures that match the ProcedurePrefix (one must be specified) and do not match the CustomProceduresStartsWith will be droppped." %>
<%@ Property Name="IncludeInsert" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If true insert procedures will be generated." %>
<%@ Property Name="IncludeUpdate" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If true update procedures will be generated." %>
<%@ Property Name="IncludeSave" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If true combined insert/update/delete procedures will be generated. In consequence, if this option is selected IncludeInsert, IncludeUpdate and IncludeDelete are automatically activated." %>
<%@ Property Name="IncludeDelete" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If true delete procedures will be generated." %>
<%@ Property Name="IncludeGet" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If true get procedures will be generated." %>
<%@ Property Name="IncludeGetList" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If true getlist procedures will be generated." %>
<%@ Property Name="IncludeGetListByFK" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If true get statements will be generated." %>
<%@ Property Name="IncludeGetListByIX" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If true getlist statements will be generated." %>
<%@ Property Name="IncludeFind" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If true find statements will be generated." %>
<%@ Property Name="IncludeManyToMany" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If true select statements will be generated for any many to many relationship." %>
<%@ Property Name="IncludeRelations" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If true select statements will be generated for any many to many relationship." %>
<%@ Property Name="IsolationLevel" Type="TransactionIsolationLevelEnum" Default="None" Category="07. CRUD - Advanced" Description="Isolation level to use in generated procedures." %>
<%@ Property Name="UseTimestampConcurrency" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If this is set to True, Update and Delete will throw DbConcurrencyException when the timestamp doesn't match current." %>
<%@ Property Name="SetAnsiNullsOn" Type="System.Boolean" Default="False" Category="07. CRUD - Advanced" Description="If this is set to True, SET ANSI_NULLS will be ON instead of OFF. Applies to SqlClient and eventually SqlCeClient" %>
<%@ Property Name="VoidProcTransaction" Type="System.Boolean" Default="True" Category="07. CRUD - Advanced" Description="If this is set to True, then automatically wrap all calls to stored procedures that have no return data in transactions; this way sprocs that only perform work will get all that work rolled back if they fail." %>
<%@ Property Name="ExtendedPropertyPrefix" Type="System.String" Default="netxp_" Category="07. CRUD - Advanced" Description="In SQL it is possible to add extended properties to columns. If the extended property name has this prefix, then it will be added as a custom attribute in the column enum. If this value is blank, extended properties will be ignored." %>
<%-- Style of stored procedures --%>
<%@ Property Name="InsertSuffix" Type="System.String" Default="_Insert" Category="08. Stored procedures - Advanced" Description="Suffix to use for all generated INSERT stored procedures." %>
<%@ Property Name="UpdateSuffix" Type="System.String" Default="_Update" Category="08. Stored procedures - Advanced" Description="Suffix to use for all generated UPDATE stored procedures." %>
<%@ Property Name="DeleteSuffix" Type="System.String" Default="_Delete" Category="08. Stored procedures - Advanced" Description="Suffix to use for all generated DELETE stored procedures." %>
<%@ Property Name="SelectSuffix" Type="System.String" Default="_Get" Category="08. Stored procedures - Advanced" Description="Suffix to use for all generated SELECT stored procedures." %>
<%@ Property Name="SelectAllSuffix" Type="System.String" Default="_List" Category="08. Stored procedures - Advanced" Description="Suffix to use for all generated SELECT stored procedures." %>
<%@ Property Name="FindSuffix" Type="System.String" Default="_Find" Category="08. Stored procedures - Advanced"Description="Suffix to use for all generated selective SELECT stored procedures." %>
<%@ Property Name="GrantReadUser" Type="System.String" Category="08. Stored procedures - Advanced" Description="Optional user or role to GRANT EXEC Procedure permissions to (for all generated read only procedures)" Default="" Optional="True" %>
<%@ Property Name="GrantUser" Type="System.String" Category="08. Stored procedures - Advanced" Description="Optional user or role to GRANT EXEC Procedure permissions to (for all generated procedures)" Default="" Optional="True" %>
<%-- 9.0 windows forms Library --%>
<%@ Property Name="GenerateWinLibrary" Type="System.Boolean" Default="false" Category="09. Winforms Library - Advanced" Description="Indicates if the WindowsForms library should be generated. This contains grids and edit controls for each entity generated." %>
<%-- Register Templates in framework --%>
<!-- #include file="TemplateLib/FrameworkTemplates.cst" -->
<%-- Register User Templates --%>
<!-- #include file="UserLib/UserTemplates.cst" -->
<script runat="template">
#region Fields
private string templateOutputDirectory = String.Empty;
private string templateMappingFile = string.Empty;
private string _WebServiceOutputPath = String.Empty;
private string _WebServiceUrl = String.Empty;
private string _ApplicationName = String.Empty;
private string _VisualStudioRefVersion = String.Empty;
private MoM.Templates.ValidationType _ValidationType = MoM.Templates.ValidationType.NetTiers;
private TableSchemaCollection templateSourceTables;
private ViewSchemaCollection templateSourceViews;
private TableSchemaCollection templateEnumTables;
private TableSchemaCollection templateCacheTables;
#endregion
#region Properties
private string rootNamespace = "";
[CodeTemplateProperty(CodeTemplatePropertyOption.Required)]
[Category("01. Getting Started - Required")]
[Description("Root namespace for generated c# classes. This will be the prefix for the other project namespaces. Example: If you enter [NetTiers.Northwind] here, and you enter [Entities] in BLLNamespace, then you will see NetTiers.Northwind.Entities for your BLL Layer.")]
[DefaultValue("")]
public string RootNameSpace
{
get
{
if (rootNamespace.Length == 0)
{
rootNamespace = (ChooseSourceDatabase != null ? ChooseSourceDatabase.Name : "");
}
return rootNamespace;
}
set
{
rootNamespace = value;
}
}
[Browsable(false)]
public DatabaseSchema SourceDatabase
{
get
{
return ChooseSourceDatabase;
}
set
{
ChooseSourceDatabase = value;
}
}
[Category("01. Getting Started - Required")]
[Description("Root namespace for generated c# classes. This will be the prefix for the other project namespaces. Example: If you enter [NetTiers.Northwind] here, and you enter [Entities] in BLLNamespace, then you will see NetTiers.Northwind.Entities for your BLL Layer.")]
[Browsable(false)]
public string NameSpace
{
get
{
return RootNameSpace;
}
set
{
RootNameSpace = value;
}
}
[Editor(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))]
[Optional, NotChecked]
[Category("01. Getting Started - Required")]
[Description("The directory to output the results to.")]
[DefaultValue("")]
public string OutputDirectory
{
get
{
if (string.IsNullOrEmpty(templateOutputDirectory))
{
return Path.Combine(CodeSmith.Engine.Configuration.Instance.CodeSmithTemplatesDirectory, Path.Combine("NetTiers", (ChooseSourceDatabase != null ? SourceDatabase.Name : "Output")));
}
else
{
return templateOutputDirectory;
}
}
set
{
if (value.EndsWith("\\")) value = value.Substring(0, value.Length - 1);
templateOutputDirectory = value;
}
}
[Editor(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]
[Category("01. Getting Started - Required")]
[Optional, NotChecked]
[Description("Optional File Path to a table/object alias file.")]
public string MappingFile
{
get
{
if (string.IsNullOrEmpty(templateMappingFile))
{
return OutputDirectory + "\\" + (ChooseSourceDatabase != null ? SourceDatabase.Name : "") + "Mapping.config";
}
else
{
return templateMappingFile;
}
}
set
{
templateMappingFile = value;
}
}
private string componentLayerNameSpace = null;
[Category("03. Namespaces - Required")]
[Description("Is the namespace for the given business layer you choose in the IncludeComponentLayer property.")]
public string ComponentLayerNameSpace
{
get
{
if (componentLayerNameSpace == null && IncludeComponentLayer.ToString() != "None")
{
return IncludeComponentLayer.ToString() == "ServiceLayer" ? "Services" : "Domain";
}
else
{
if (componentLayerNameSpace == null)
return "";
return componentLayerNameSpace;
}
}
set
{
componentLayerNameSpace = value;
}
}
[Category("01b. Filter by Individual Objects - Optional")]
[Description("The tables you wish to generate, if you do not select any SourceTables or SourceViews, and SourceDatabase is completed, then the entire database will be generated.")]
[Optional, NotChecked]
public TableSchemaCollection SourceTables
{
get
{
if (this.templateSourceTables != null && this.templateSourceTables.Count > 0 )
return this.templateSourceTables;
else
return null;
}
set
{
this.templateSourceTables = value;
}
}
[Category("01b. Filter by Individual Objects - Optional")]
[Description("The tables to generate as enums. Your columns must meet the following rules. The first column must be a primary key and an Identity column, the second column must have a unique column constraint index, the optional third column will be the description of the generated enum. You must select this as a SourceTable as well in order to generate the enum.")]
[Optional, NotChecked]
public TableSchemaCollection EnumTables
{
get
{
if (this.templateEnumTables != null && this.templateEnumTables.Count > 0 )
return this.templateEnumTables;
else
return null;
}
set
{
this.templateEnumTables = value;
}
}
[Category("01b. Filter by Individual Objects - Optional")]
[Description("The tables to tag for caching. Or for use by Entity tracking code.")]
[Optional, NotChecked]
public TableSchemaCollection CacheTables
{
get
{
if (this.templateCacheTables != null && this.templateCacheTables.Count > 0 )
return this.templateCacheTables;
else
return null;
}
set
{
this.templateCacheTables = value;
}
}
[Category("01b. Filter by Individual Objects - Optional")]
[Description("The views you wish to generate, if you do not select any SourceViews or SourceTables, and SourceDatabase is completed, then the entire database will be generated.")]
[Optional, NotChecked]
public ViewSchemaCollection SourceViews
{
get
{
if (this.templateSourceViews != null && this.templateSourceViews.Count > 0 )
return this.templateSourceViews;
else
return null;
}
set
{
this.templateSourceViews = value;
}
}
[Category("General")]
[Description("Should we use partials when generating .net 2.0 code?")]
[Optional, NotChecked]
[Browsable(false)]
[Obsolete("Partial class are now automatically where targetting .net2 framework.")]
public bool UsePartialClass
{
get
{
return _UsePartialClass;
}
set
{
_UsePartialClass = value;
}
}
private bool _UsePartialClass = true;
[Category("General")]
[Description("Should overwrite partial stubs?")]
[Optional, NotChecked]
[Browsable(false)]
public bool OverwritePartialClassStub
{
get
{
return _OverwritePartialClassStub;
}
set
{
_OverwritePartialClassStub = value;
}
}
private bool _OverwritePartialClassStub = false;
[Editor(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))]
[Optional, NotChecked]
[Category("06. Web - Advanced")]
[Description("The full path for the the WebService files. this path match with the webservice url.")]
[DefaultValue("c:\\inetpub\\wwwroot\\WebServices")]
public string WebServiceOutputPath
{
get
{
if (_WebServiceOutputPath.Length == 0)
{
return OutputDirectory + "\\WebServices";
}
return _WebServiceOutputPath;
}
set
{
if (value.EndsWith("\\")) value = value.Substring(0, value.Length - 1);
_WebServiceOutputPath = value;
}
}
[Optional, NotChecked]
[Category("06. Web - Advanced")]
[Description("The IIS virtual directory path for the WebService files. This path should match with the WebserviceOutputPath.")]
[DefaultValue("http://localhost/NetTiersWS")]
public string WebServiceUrl
{
get
{
if (_WebServiceUrl.Length == 0)
{
return "http://localhost/" + _webServiceClassName;
}
return _WebServiceUrl;
}
set
{
_WebServiceUrl = value;
}
}
[Optional, NotChecked]
[Category("06b. Website - Advanced")]
[Description("Indicates the web admin site name.")]
[DefaultValue("Application Name")]
public string WebAdminSiteName
{
get
{
if (_ApplicationName.Length == 0)
{
if (ChooseSourceDatabase != null)
{
return GetClassName(ChooseSourceDatabase) + " Application";
}
else
{
return "";
}
}
return _ApplicationName;
}
set
{
_ApplicationName = value;
}
}
[Category("02. Framework Generation - Optional")]
[Description("Choice to either use .netTiers validation framework, or Enterprise Library VAB")]
[DefaultValue("NetTiers")]
public MoM.Templates.ValidationType ValidationType
{
get { return _ValidationType; }
set { _ValidationType = value; }
}
#endregion Properties
#region OnPropertyChanged
#if CodeSmith40
protected override void OnPropertyChanged(string propertyName)
{
if((this.State == TemplateState.Default || this.State == TemplateState.Validating)
&& propertyName == "ChooseSourceDatabase")
{
//MappingFile = "";
//OutputDirectory = "";
//RootNameSpace = "";
//vWebServiceOutputPath = "";
//WebServiceUrl = "";
WebAdminSiteName = "";
}
base.OnPropertyChanged(propertyName);
}
#endif
#endregion
private bool _generateWebSecurity = false;
[Category("10. WebLibrary.Security - Optional")]
[Description("Indicates if the Web.Security library should be generated. This contains the EntityMembershipProvider class and other classes helpful to ASP.NET Membership services.")]
[CodeTemplateProperty(CodeTemplatePropertyOption.Optional)]
public bool GenerateWebSecurity
{
get
{
return _generateWebSecurity;
}
set
{
_generateWebSecurity = value;
}
}
private ColumnSchema _entityMembershipUserPKCol = null;
[Category("10. WebLibrary.Security - Optional")]
[Description("Primary key column from the table that will become the EntityMembershipUser's user entity.")]
[CodeTemplateProperty(CodeTemplatePropertyOption.Optional)]
public ColumnSchema EntityMembershipUserPKCol
{
get
{
return this._entityMembershipUserPKCol;
}
set
{
_entityMembershipUserPKCol = value;
}
}
private string _membershipUserMapFile;
[Editor(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]
[Category("10. WebLibrary.Security - Optional")]
[Description("Optional File Path to a MembershipUserProperty/EntityProperty alias file")]
[CodeTemplateProperty(CodeTemplatePropertyOption.Optional)]
public string MembershipUserMapFile
{
get
{
return this._membershipUserMapFile;
}
set
{
_membershipUserMapFile = value;
}
}
private bool _membershipUseMD5 = false;
[Category("10. WebLibrary.Security - Optional")]
[Description("Use MD5 hash for passwords. False defaults to SHA1.")]
[CodeTemplateProperty(CodeTemplatePropertyOption.Optional)]
public bool UseMD5Hash
{
get
{
return this._membershipUseMD5;
}
set
{
_membershipUseMD5 = value;
}
}
#region Properties used by the wizard to report progression
private int _counter = 0;
[Browsable(false)]
public int Counter
{
get {return this._counter;}
}
private int _errorMessageCount = 0;
[Browsable(false)]
public int ErrorMessageCount
{
get {return this._errorMessageCount;}
}
private int _CurrentObjectIndex = 0;
[Browsable(false)]
public int CurrentObjectIndex
{
get {return this._CurrentObjectIndex;}
}
private string _CurrentPhase = string.Empty;
[Browsable(false)]
public string CurrentPhase
{
get {return this._CurrentPhase;}
}
[Browsable(false)]
public int TotalObjects
{
get {return (SourceTables != null ? SourceTables.Count : 0) + (SourceViews != null ? SourceViews.Count : 0);}
}
private string _CurrentFileName = string.Empty;
[Browsable(false)]
public string CurrentFileName
{
get {return this._CurrentFileName;}
}
private StringBuilder _CompileErrors = new StringBuilder();
[Browsable(false)]
public string CompileErrors
{
get {return this._CompileErrors.ToString();}
}
private StringBuilder _CompileWarnings = new StringBuilder();
[Browsable(false)]
public string CompileWarnings
{
get {return this._CompileWarnings.ToString();}
}
[Browsable(false)]
public int TotalTemplates
{
get {return CodeTemplates.Count;}
}
[Browsable(false)]
public int CurrentTemplateIndex
{
get {return CodeTemplates.Count;}
}
[Browsable(false)]
[Obsolete("Visual studio 2005 is the only solution type for .net2 framework.")]
public bool IsTargetingVisualStudio2003
{
get { return false; }
//get {return this.vsnetVersion == VSNetVersion.v2003;}
//set
//{
// if (value == true)
// {
// this.vsnetVersion = VSNetVersion.v2003;
// }
// else
// {
// this.vsnetVersion = VSNetVersion.v2005;
// }
//}
}
#endregion
#region Enums
public enum TransactionIsolationLevelEnum
{
None,
ReadCommitted,
ReadUncommitted,
RepeatableRead,
Serializable,
Snapshot
}
[Obsolete("Separated project is automatically used.")]
public enum VSNetIntegration
{
None,
SingleProject,
SeparatedProjects
}
public enum DbProviderFactory
{
SqlClient
, OracleClient
, OdbcClient
, OleDbClient
, SqlCeClient
}
// Used to determine the style of drop statement to be used (if any)
public enum DropStyleEnum
{
Entity,
All
}
public enum TimeStandardEnum
{
Utc,
Local
}
#endregion Enums
</script>
<script runat="template">
#region Fields
private string sdkInstallRoot;
VSNetIntegration vsnetIntegration = VSNetIntegration.SeparatedProjects;
public bool GenerateBusinessLogicLayer = true;
public bool GenerateDataAccessLayer = true;
public bool GenerateSql = true;
#endregion Fields
#region xml report fields
public XmlDocument docOutput;
public DateTime startTime = DateTime.Now;
public DateTime lastTime = DateTime.Now;
#endregion xml report fields
//TextPad Regex for template listing array. Used to convert to FrameWorkTemplates.cst
//\t\t\t\t\t\t\t\t\t\t\t\t\t\t"\(.*\\\\\)?\(.*\).cst",
//Include the User Engine Methods
<!-- #include file="UserLib/CustomMethods.cs" -->
public enum AccessibilityEnum
{
Public,
Protected,
Internal,
ProtectedInternal,
Private
}
#region Template related methods
protected override void OnInit()
{
#if CodeSmith50
this.SetPropertyAttribute("SourceTables", "DeepLoad", "True");
this.SetPropertyAttribute("EnumTables", "DeepLoad", "True");
this.SetPropertyAttribute("CacheTables", "DeepLoad", "True");
this.SetPropertyAttribute("SourceViews", "DeepLoad", "True");
#endif
base.OnInit();
}
public void RenderToFile(string templateName, string path, bool overwrite)
{
this._CurrentFileName = path;
this.GetTemplate(templateName).RenderToFile(path, overwrite);
this._counter++;
}
public void RenderToFile(CodeTemplate template, string path, bool overwrite)
{
this._CurrentFileName = path;
template.RenderToFile(path, overwrite);
this._counter++;
}
// load all the templates and put them into an hashtable
public void LoadTemplates()
{
//Expression can creates matches for template name and template key from /TemplateLib/FrameworkTemplates.cst
//Name=\"(.*)\".*Template=\"\.\.(.*)?/(.*).cst
//System.Text.RegularExpressions.Regex exp = new System.Text.RegularExpressions.Regex("Name=\"(.*)\".*Template=\"\.\.(.*)?/(.*).cst");
//Include the Create Statement of all the Framework Templates
<!-- #include file="TemplateLib/CreateTemplates.cs" -->
//Include the Create Statement of all the User Templates
<!-- #include file="UserLib/CreateTemplates.cs" -->
foreach(CodeSmith.Engine.CodeTemplate template in CodeTemplates.Values)
{
try
{
this.CopyPropertiesTo(template);
template.SetProperty("CurrentNetTiersMap", base.CurrentNetTiersMap);
template.SetProperty("CodeTemplates", base.CodeTemplates);
this.PerformStep();
}
catch ( Exception ex )
{
Trace.WriteLine("\tWARNING: " + ex);
}
}
}
public CodeTemplate GetTemplate(string templateType)
{
return CodeTemplates[templateType];
}
public MoM.Templates.CommonSqlCode GetTemplateBase(string templateType)
{
return (MoM.Templates.CommonSqlCode) GetTemplate(templateType);
}
#endregion Template related methods
/// <summary>
/// The main function that does the generation process for each table and view.
/// </summary>
public void Go()
{
#region Initialisation - including building list of tables to process
this.vsnetIntegration = VSNetIntegration.SeparatedProjects;
RelationshipDictionary.Clear();
_CurrentPhase = "Initialization";
DebugWriteLine("Current Phase: " + _CurrentPhase);
MoM.Templates.ComponentPatternType ComponentPattern = IncludeComponentLayer;
DebugWriteLine("ComponentPattern: "+ ComponentPattern.ToString());
#region NetTiersProvider Detection : based upon the current SchemaExplorer
bool _netTiersSqlProvider = true;
ProviderInvariantName = "System.Data.SqlClient";
SchemaExplorer.IDbSchemaProvider schemaProvider = SourceDatabase.Provider;
if (SourceDatabase.Provider.Name != "SqlSchemaProvider" )
{
_netTiersSqlProvider = false;
if (SourceDatabase.Provider.Name == "SQLiteSchemaProvider")
{
ProviderInvariantName = "System.Data.SQLite";
}
else if(SourceDatabase.Provider.Name == "MySQLSchemaProvider")
{
ProviderInvariantName = "MySql.Data.MySqlClient";
}
else if (SourceDatabase.Provider.Name == "ADOXSchemaProvider")
{
ProviderInvariantName = "System.Data.OleDb";
}
else if (SourceDatabase.Provider.Name == "OracleSchemaProvider")
{
ProviderInvariantName = "System.Data.OracleClient";
ParameterPrefix = "";
}
else if (SourceDatabase.Provider.Name == "SqlCompactSchemaProvider")
{
ProviderInvariantName = "System.Data.SqlServerCe.3.5";
ParameterPrefix = "@";
}
else if(SourceDatabase.Provider.Name == "VistaDB Schema Provider")
{
//TODO: Update .netTiers to use the VistaDB Provider.
//NOTE: This is a temp fix.
ProviderInvariantName = "System.Data.OleDb";
}
}
#endregion
#region Build Namespaces
if (BusinessLogicLayerNameSpace == null) BusinessLogicLayerNameSpace = string.Empty;
string BLLNameSpace = NameSpace + (BusinessLogicLayerNameSpace.Length>0 ? "." + GetCleanName(BusinessLogicLayerNameSpace) : string.Empty);
string ComponentsNameSpace = NameSpace + (this.ComponentLayerNameSpace.Length> 0 ? "." + GetCleanName(ComponentLayerNameSpace) : string.Empty);
string DALNameSpace = NameSpace + "." + (DataAccessLayerNameSpace.Length>0 ? GetCleanName(DataAccessLayerNameSpace) : "DataAccessLayer");
string DALSqlNameSpace = DALNameSpace + ".SqlClient";
string DALOracleNameSpace = DALNameSpace + ".OracleClient";
string DALSqlCeNameSpace = DALNameSpace + ".SqlCeClient";
string DALGenericNameSpace = DALNameSpace + ".GenericClient";
string DALWSNameSpace = DALNameSpace + ".WebServiceClient";
string UTNameSpace = NameSpace + "." + (UnitTestsNameSpace.Length>0 ? GetCleanName(UnitTestsNameSpace) : "UnitTests");
string WSNameSpace = DALNameSpace + ".WebService";
string WebLibNameSpace = NameSpace + ".Web";
string WebsiteNameSpace = NameSpace + ".Website";
string WinLibNameSpace = NameSpace + ".Windows.Forms";
string SQLNamespace = NameSpace + "." + (SQLFolderName.Length > 0 ? SQLFolderName : "SQL");
string WebSecurityLibNameSpace = WebLibNameSpace + ".Security";
string factoryType = (ComponentPattern == MoM.Templates.ComponentPatternType.DomainModel ? string.Format("{0}.{1}", ComponentsNameSpace, "ComponentEntityFactory") : string.Format("{0}.{1}", BLLNameSpace, "EntityFactory"));
#endregion Build Namespaces
#region Build output paths
string rootPathBLL = OutputDirectory + "\\" + BLLNameSpace;
string rootPathComponents = OutputDirectory + "\\" + ComponentsNameSpace;
string rootPathDAL = OutputDirectory + "\\" + DALNameSpace;
string rootPathDALSql = OutputDirectory + "\\" + DALSqlNameSpace;
string rootPathDALOracle = OutputDirectory + "\\" + DALOracleNameSpace;
string rootPathDALSqlCe = OutputDirectory + "\\" + DALSqlCeNameSpace;
string rootPathDALGeneric = OutputDirectory + "\\" + DALGenericNameSpace;
string rootPathDALWS = OutputDirectory + "\\" + DALWSNameSpace;
string rootPathWebLib = OutputDirectory + "\\" + WebLibNameSpace;
string rootPathWebSecurityLib = OutputDirectory + "\\" + WebLibNameSpace + ".Security";
string rootPathWinLib = OutputDirectory + "\\" + WinLibNameSpace;
string rootPathWebsite = OutputDirectory + "\\" + WebsiteNameSpace;
string rootPathUT = OutputDirectory + "\\" + UTNameSpace;
string rootPathSQL = OutputDirectory + "\\" + SQLNamespace;
string rootPathWS = WebServiceOutputPath;
string specialPath = vsnetIntegration == VSNetIntegration.SeparatedProjects ? ((IncludeUnitTest != MoM.Templates.UnitTestStyle.None) ? rootPathUT : rootPathDAL) : OutputDirectory;
#endregion Build output paths
bool HasCustomCode = (CustomCodeFolderName != null && CustomCodeFolderName.Trim().Length > 0 );
if (ProcedurePrefix == null) ProcedurePrefix = string.Empty;
if (WebServiceUrl == null) WebServiceUrl = string.Empty;
docOutput = new XmlDocument();
docOutput.AppendChild(docOutput.CreateElement("NetTiersReport"));
XmlAttribute att = docOutput.CreateAttribute("startTime");
att.Value = DateTime.Now.ToFileTime().ToString();
docOutput.DocumentElement.Attributes.Append(att);
XmlAttribute attDALNS = docOutput.CreateAttribute("DALNameSpace");
attDALNS.Value = DALNameSpace;
docOutput.DocumentElement.Attributes.Append(attDALNS);
XmlAttribute attSolution = docOutput.CreateAttribute("SolutionLink");
attSolution.Value = GetSolutionFileLink();
docOutput.DocumentElement.Attributes.Append(attSolution);
XmlAttribute attConn = docOutput.CreateAttribute("ConnectionString");
attConn.Value = SourceDatabase.ConnectionString;
docOutput.DocumentElement.Attributes.Append(attConn);
XmlAttribute attFact = docOutput.CreateAttribute("FactoryType");
attFact.Value = (ComponentPattern == MoM.Templates.ComponentPatternType.DomainModel ? ComponentLayerNameSpace + ".ComponentEntityFactory" : BLLNameSpace + ".EntityFactory");
docOutput.DocumentElement.Attributes.Append(attFact);
XmlElement initNode = docOutput.CreateElement("initialization");
initNode.Attributes.Append(att);
docOutput.DocumentElement.AppendChild(initNode);
XmlElement customProcsNode = docOutput.CreateElement("customStoredProcedures");
XmlAttribute attIncludeCustoms = docOutput.CreateAttribute("includeCustoms");
attIncludeCustoms.Value = IncludeCustoms.ToString().ToLower();
customProcsNode.Attributes.Append(attIncludeCustoms);
docOutput.DocumentElement.AppendChild(customProcsNode);
if (IncludeSave)
{
IncludeInsert = true;
IncludeUpdate = true;
IncludeDelete = true;
}
try
{
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework");
sdkInstallRoot = string.Format("{0}\\Bin\\", key.GetValue("sdkInstallRootv2.0"));
key.Close();
}
catch
{
sdkInstallRoot = @"c:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\";
}
DebugWriteLine(string.Format("sdkInstallRoot: {0}", sdkInstallRoot));
//Validate necessary parameters
_CurrentPhase = "Parameter Validation";
DebugWriteLine("Current Phase: "+_CurrentPhase);
XmlElement parametersNode = AddMessageNode(initNode, 0, "Validating parameters.", false);
if ( GenerateWebSecurity )
{
// make sure MembershipUser primary key column is selected
if ( EntityMembershipUserPKCol == null )
{
AddMessageNode(parametersNode, 1, "EntityMembershipUserPKCol has not been specified, so the Web.Security library will not be generated.", true);
GenerateWebSecurity = false;
}
}
//Set the Correct WebServiceClassName
string _webServiceClassName = WebServiceClassName;
if(string.IsNullOrEmpty(_webServiceClassName))
{
_webServiceClassName = NameSpace + "Services";
}
#region Build the correct list of used tables (filtering tables without primary key)
_CurrentPhase = "Check datasource";
DebugWriteLine("Current Phase: "+_CurrentPhase);
//Entire Database
if (SourceDatabase != null && (SourceTables == null || SourceTables.Count == 0) && (SourceViews == null || SourceViews.Count == 0))
{
templateSourceTables = new TableSchemaCollection();
templateSourceViews = new ViewSchemaCollection();
for (int i=0; i < SourceDatabase.Tables.Count; i++)
{
templateSourceTables.Add(SourceDatabase.Tables[i]);
}
for (int i=0; i < SourceDatabase.Views.Count; i++)
{
templateSourceViews.Add(SourceDatabase.Views[i]);
}
}
else
{
if (SourceTables == null) templateSourceTables = new TableSchemaCollection();
if (SourceViews == null) templateSourceViews = new ViewSchemaCollection();
}
#endregion Build the correct list of used tables (filtering tables without primary key)
#region Remove tables with no primary key
TableSchemaCollection _tmp = (TableSchemaCollection)templateSourceTables.Clone();
for (int i=0; i < _tmp.Count; i++)
{
try
{
//in sql 2005, sysdiagrams is added as dbo, and a user table, not a system table.
if (_tmp[i].Name == "sysdiagrams")
{
templateSourceTables.Remove(_tmp[i]);
}
//throwing a NullReferenceException on the following line, changed to use HasPrimaryKey property