This repository has been archived by the owner on Jun 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
EdmGenDataSet.cs
2624 lines (2358 loc) · 142 KB
/
EdmGenDataSet.cs
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
#if ENTITIES6
using System.Data.Entity.Core.Common;
using System.Data.Entity.Core.Metadata.Edm;
#else
using System.Data.Metadata.Edm;
#endif
using EdmGen06.Properties;
using Store;
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace EdmGen06 {
public class EdmGenDataSet : EdmGenBase {
static readonly XNamespace xxs = "http://www.w3.org/2001/XMLSchema";
static readonly XNamespace xmsdata = "urn:schemas-microsoft-com:xml-msdata";
static readonly XNamespace xmsprop = "urn:schemas-microsoft-com:xml-msprop";
public void DataSet(String connectionString, String providerName, String modelName, String targetSchema) {
String baseDir = Environment.CurrentDirectory;
Trace.TraceEvent(TraceEventType.Information, 101, "Getting System.Data.Common.DbProviderFactory from '{0}'", providerName);
var fac = System.Data.Common.DbProviderFactories.GetFactory(providerName);
if (fac == null) throw new ApplicationException();
Trace.TraceEvent(TraceEventType.Information, 101, fac.GetType().AssemblyQualifiedName);
Trace.TraceEvent(TraceEventType.Information, 101, "Ok");
using (var db = fac.CreateConnection()) {
Trace.TraceEvent(TraceEventType.Information, 101, "Connecting");
db.ConnectionString = connectionString;
db.Open();
Trace.TraceEvent(TraceEventType.Information, 101, "Connected");
Trace.TraceEvent(TraceEventType.Information, 101, "Getting System.Data.Entity.Core.Common.DbProviderServices from '{0}'", providerName);
var providerServices = ((IServiceProvider)fac).GetService(typeof(DbProviderServices)) as DbProviderServices;
if (providerServices == null) providerServices = DbProviderServices.GetProviderServices(db);
Trace.TraceEvent(TraceEventType.Information, 101, providerServices.GetType().AssemblyQualifiedName);
Trace.TraceEvent(TraceEventType.Information, 101, "Ok");
Trace.TraceEvent(TraceEventType.Information, 101, "Get ProviderManifestToken");
var providerManifestToken = providerServices.GetProviderManifestToken(db);
Trace.TraceEvent(TraceEventType.Information, 101, "Get ProviderManifest");
var providerManifest = providerServices.GetProviderManifest(providerManifestToken) as DbProviderManifest;
Trace.TraceEvent(TraceEventType.Information, 101, "Get StoreSchemaDefinition");
var storeSchemaDefinition = providerManifest.GetInformation("StoreSchemaDefinition") as XmlReader;
Trace.TraceEvent(TraceEventType.Information, 101, "Get StoreSchemaMapping");
var storeSchemaMapping = providerManifest.GetInformation("StoreSchemaMapping") as XmlReader;
Trace.TraceEvent(TraceEventType.Information, 101, "Write temporary ProviderManifest ssdl");
XDocument tSsdl;
String fpssdl = Path.Combine(baseDir, "__" + providerName + ".ssdl");
String fpssdl2 = Path.Combine(baseDir, "__" + providerName + ".ssdl.xml");
{
tSsdl = XDocument.Load(storeSchemaDefinition);
tSsdl.Save(fpssdl);
tSsdl.Save(fpssdl2);
}
Trace.TraceEvent(TraceEventType.Information, 101, "Write temporary ProviderManifest msl");
XDocument tMsl;
String fpmsl = Path.Combine(baseDir, "__" + providerName + ".msl");
String fpmsl2 = Path.Combine(baseDir, "__" + providerName + ".msl.xml");
{
tMsl = XDocument.Load(storeSchemaMapping);
tMsl.Save(fpmsl);
tMsl.Save(fpmsl2);
}
Trace.TraceEvent(TraceEventType.Information, 101, "Checking ProviderManifest version.");
XmlReader xrCsdl = null;
if (false) { }
else if (tSsdl.Element("{" + NS.SSDLv1 + "}" + "Schema") != null && tMsl.Element("{" + NS.MSLv1 + "}" + "Mapping") != null) {
pCSDL = "{" + NS.CSDLv1 + "}";
pMSL = "{" + NS.MSLv1 + "}";
pSSDL = "{" + NS.SSDLv1 + "}";
#if ENTITIES6
xrCsdl = DbProviderServices.GetConceptualSchemaDefinition(DbProviderManifest.ConceptualSchemaDefinition);
#else
xrCsdl = XmlReader.Create(new MemoryStream(Resources.ConceptualSchemaDefinition));
#endif
Trace.TraceEvent(TraceEventType.Information, 101, "ProviderManifest v1");
}
else if (tSsdl.Element("{" + NS.SSDLv3 + "}" + "Schema") != null && tMsl.Element("{" + NS.MSLv3 + "}" + "Mapping") != null) {
pCSDL = "{" + NS.CSDLv3 + "}";
pMSL = "{" + NS.MSLv3 + "}";
pSSDL = "{" + NS.SSDLv3 + "}";
#if ENTITIES6
xrCsdl = DbProviderServices.GetConceptualSchemaDefinition(DbProviderManifest.ConceptualSchemaDefinitionVersion3);
#else
xrCsdl = XmlReader.Create(new MemoryStream(Resources.ConceptualSchemaDefinitionVersion3));
#endif
Trace.TraceEvent(TraceEventType.Information, 101, "ProviderManifest v3");
}
else {
Trace.TraceEvent(TraceEventType.Error, 101, "ProviderManifest version unknown");
throw new ApplicationException("ProviderManifest version unknown");
}
Trace.TraceEvent(TraceEventType.Information, 101, "Write temporary ProviderManifest csdl");
String fpcsdl = Path.Combine(baseDir, "__" + providerName + ".csdl");
XDocument tCsdl;
{
tCsdl = XDocument.Load(xrCsdl);
tCsdl.Save(fpcsdl);
}
var entityConnectionString = ""
+ "Provider=" + providerName + ";"
+ "Provider Connection String=\"" + db.ConnectionString + "\";"
+ "Metadata=" + fpcsdl + "|" + fpssdl + "|" + fpmsl + ";"
;
Trace.TraceEvent(TraceEventType.Information, 101, "Getting SchemaInformation");
using (var Context = new SchemaInformation(entityConnectionString)) {
Trace.TraceEvent(TraceEventType.Information, 101, "Ok");
DataTable dtMetaDataCollections = db.GetSchema("MetaDataCollections");
DataTable dtDataSourceInformation = db.GetSchema("DataSourceInformation");
//DataTable dtDataTypes = db.GetSchema("DataTypes");
DataTable dtReservedWords = db.GetSchema("ReservedWords");
XDocument xsd = new XDocument();
XNamespace nsMSTNS = "http://tempuri.org/DataSet1.xsd";
String dbn = db.Database;
String dataSet1 = modelName;
dut.providerManifest = providerManifest;
dut.modelName = modelName;
dut.providerName = providerName;
dut.targetSchema = targetSchema;
foreach (DataRow dr in dtDataSourceInformation.Rows) {
dut.CompositeIdentifierSeparatorPattern = (String)dr["CompositeIdentifierSeparatorPattern"];
dut.IdentifierPattern = (String)dr["IdentifierPattern"];
dut.ParameterMarkerFormat = (String)dr["ParameterMarkerFormat"];
dut.ParameterMarkerPattern = (String)dr["ParameterMarkerPattern"];
dut.ParameterNamePattern = (String)dr["ParameterNamePattern"];
dut.QuotedIdentifierPattern = (String)dr["QuotedIdentifierPattern"];
dut.StringLiteralPattern = (String)dr["StringLiteralPattern"];
dut.IdentifierCase = (IdentifierCase)dr["IdentifierCase"];
dut.ParameterNameMaxLength = (int)dr["ParameterNameMaxLength"];
}
// http://d.hatena.ne.jp/gsf_zero1/20121219/p1
XElement xSchema;
xsd.Add(xSchema = new XElement(xxs + "schema"
, new XAttribute(XNamespace.Xmlns + "xs", xxs)
, new XAttribute(XNamespace.Xmlns + "mstns", nsMSTNS)
, new XAttribute(XNamespace.Xmlns + "msdata", xmsdata)
, new XAttribute(XNamespace.Xmlns + "msprop", xmsprop)
, new XAttribute("id", dataSet1)
, new XAttribute("targetNamespace", nsMSTNS)
, new XAttribute("attributeFormDefault", "qualified")
, new XAttribute("elementFormDefault", "qualified")
));
{
XElement xAnn, xTables;
xSchema.Add(xAnn = new XElement(xxs + "annotation"
, new XElement(xxs + "appinfo"
, new XAttribute("source", nsDS)
, new XElement(nsDS + "DataSource"
, new XAttribute("DefaultConnectionIndex", "0")
, new XAttribute("FunctionsComponentName", "QueriesTableAdapter")
, new XAttribute("Modifier", "AutoLayout, AnsiClass, Class, Public")
, new XAttribute("SchemaSerializationMode", "IncludeSchema")
, new XElement(nsDS + "Connections"
, new XElement(nsDS + "Connection"
, new XAttribute("AppSettingsObjectName", "Settings")
, new XAttribute("AppSettingsPropertyName", dbn + "ConnectionString")
, new XAttribute("ConnectionStringObject", "")
, new XAttribute("IsAppSettingsProperty", "true")
, new XAttribute("Modifier", "Assembly")
, new XAttribute("Name", dbn + "ConnectionString (Settings)")
, new XAttribute("ParameterPrefix", "@")
, new XAttribute("Provider", providerName)
)
)
, xTables = new XElement(nsDS + "Tables"
)
)
)
)
);
XElement xchoice, xelt;
xSchema.Add(xelt = new XElement(xxs + "element"
, new XAttribute("name", dataSet1)
, new XAttribute(xmsdata + "IsDataSet", "true")
, new XAttribute(xmsdata + "UseCurrentLocale", "true")
, new XAttribute(xmsdata + "EnableTableAdapterManager", "true")
, new XAttribute(xmsprop + "Generator_DataSetName", dut.Generator_DataSetName(dbn))
, new XAttribute(xmsprop + "Generator_UserDSName", dut.Generator_UserDSName(dbn))
, new XElement(xxs + "complexType"
, xchoice = new XElement(xxs + "choice"
, new XAttribute("minOccurs", "0")
, new XAttribute("maxOccurs", "unbounded")
)
)
)
);
foreach (var Table in Context.Tables) {
DbDataAdapter da = fac.CreateDataAdapter();
DbCommandBuilder cb = fac.CreateCommandBuilder();
da.SelectCommand = db.CreateCommand();
da.SelectCommand.CommandText = String.Format("SELECT " + String.Join(", ", Table.Columns.Select(p => dut.SColumn(p, cb)).ToArray()) + " FROM " + dut.STable(Table, cb));
cb.DataAdapter = da;
try {
da.DeleteCommand = cb.GetDeleteCommand();
}
catch (InvalidOperationException) { }
try {
da.InsertCommand = cb.GetInsertCommand();
}
catch (InvalidOperationException) { }
try {
da.UpdateCommand = cb.GetUpdateCommand();
}
catch (InvalidOperationException) { }
XElement xDbSource;
XElement xTableAdapter, xMappings;
xTables.Add(xTableAdapter = new XElement(nsDS + "TableAdapter"
, new XAttribute("BaseClass", "System.ComponentModel.Component")
, new XAttribute("DataAccessorModifier", "AutoLayout, AnsiClass, Class, Public")
, new XAttribute("DataAccessorName", dut.DataAccessorName(Table))
, new XAttribute("GeneratorDataComponentClassName", dut.GeneratorDataComponentClassName(Table))
, new XAttribute("Name", Table.Name)
, new XAttribute("UserDataComponentName", dut.UserDataComponentName(Table))
, new XElement(nsDS + "MainSource"
, xDbSource = new XElement(nsDS + "DbSource"
, new XAttribute("ConnectionRef", dbn + "ConnectionString (Settings)")
, new XAttribute("DbObjectName", dut.DbObjectName(Table, cb))
, new XAttribute("DbObjectType", "Table")
, new XAttribute("FillMethodName", "Fill")
, new XAttribute("GenerateMethods", "Both")
, new XAttribute("GenerateShortCommands", "true")
, new XAttribute("GeneratorGetMethodName", "GetData")
, new XAttribute("GeneratorSourceName", "Fill")
, new XAttribute("GetMethodModifier", "Public")
, new XAttribute("GetMethodName", "GetData")
, new XAttribute("QueryType", "Rowset")
, new XAttribute("ScalarCallRetval", typeof(object).AssemblyQualifiedName)
, new XAttribute("UseOptimisticConcurrency", "true")
, new XAttribute("UserGetMethodName", "GetData")
, new XAttribute("UserSourceName", "Fill")
)
)
, xMappings = new XElement(nsDS + "Mappings"
)
, new XElement(nsDS + "Sources"
)
)
);
if (da.DeleteCommand != null) xDbSource.Add(
new XElement(nsDS + "DeleteCommand", GetCommandEl(Table, da.DeleteCommand, cb, nsDS))
);
if (da.InsertCommand != null) xDbSource.Add(
new XElement(nsDS + "InsertCommand", GetCommandEl(Table, da.InsertCommand, cb, nsDS))
);
if (da.SelectCommand != null) xDbSource.Add(
new XElement(nsDS + "SelectCommand", GetCommandEl(Table, da.SelectCommand, cb, nsDS))
);
if (da.UpdateCommand != null) xDbSource.Add(
new XElement(nsDS + "UpdateCommand", GetCommandEl(Table, da.UpdateCommand, cb, nsDS))
);
XElement xsequence;
xchoice.Add(new XElement(xxs + "element"
, new XAttribute("name", dut.xsname(Table))
, new XAttribute(xmsprop + "Generator_TableClassName", dut.Generator_TableClassName(Table))
, new XAttribute(xmsprop + "Generator_TableVarName", dut.Generator_TableVarName(Table))
, new XAttribute(xmsprop + "Generator_TablePropName", dut.Generator_TablePropName(Table))
, new XAttribute(xmsprop + "Generator_RowDeletingName", dut.Generator_RowDeletingName(Table))
, new XAttribute(xmsprop + "Generator_RowChangingName", dut.Generator_RowChangingName(Table))
, new XAttribute(xmsprop + "Generator_RowEvHandlerName", dut.Generator_RowEvHandlerName(Table))
, new XAttribute(xmsprop + "Generator_RowDeletedName", dut.Generator_RowDeletedName(Table))
, new XAttribute(xmsprop + "Generator_UserTableName", dut.Generator_UserTableName(Table))
, new XAttribute(xmsprop + "Generator_RowChangedName", dut.Generator_RowChangedName(Table))
, new XAttribute(xmsprop + "Generator_RowEvArgName", dut.Generator_RowEvArgName(Table))
, new XAttribute(xmsprop + "Generator_RowClassName", dut.Generator_RowClassName(Table))
, new XElement(xxs + "complexType"
, xsequence = new XElement(xxs + "sequence"
)
)
));
foreach (var dbc in Table.Columns) {
xMappings.Add(new XElement(nsDS + "Mapping"
, new XAttribute("SourceColumn", dut.SourceColumn(dbc))
, new XAttribute("DataSetColumn", dut.DataSetColumn(dbc))
));
XElement xce;
xsequence.Add(xce = new XElement(xxs + "element"
, new XAttribute("name", dut.xsname(dbc))
));
if (dbc.IsIdentity) {
xce.SetAttributeValue(xmsdata + "ReadOnly", "true");
xce.SetAttributeValue(xmsdata + "AutoIncrement", "true");
xce.SetAttributeValue(xmsdata + "AutoIncrementSeed", "-1");
xce.SetAttributeValue(xmsdata + "AutoIncrementStep", "-1");
}
xce.SetAttributeValue(xmsprop + "Generator_ColumnVarNameInTable", dut.Generator_ColumnVarNameInTable(dbc));
xce.SetAttributeValue(xmsprop + "Generator_ColumnPropNameInRow", dut.Generator_ColumnPropNameInRow(dbc));
xce.SetAttributeValue(xmsprop + "Generator_ColumnPropNameInTable", dut.Generator_ColumnPropNameInTable(dbc));
xce.SetAttributeValue(xmsprop + "Generator_UserColumnName", dut.Generator_UserColumnName(dbc));
xce.SetAttributeValue("type", dut.xstype(dbc));
if (dbc.IsNullable) {
xce.SetAttributeValue("minOccurs", "0");
}
int? MaxLen = dbc.ColumnType.MaxLength;
if (MaxLen.HasValue) {
xce.Add(new XElement(xxs + "simpleType"
, new XElement(xxs + "restriction"
, new XAttribute("base", dut.xstype(dbc))
, new XElement(xxs + "maxLength"
, new XAttribute("value", MaxLen.Value + "")
)
)
));
xce.Attribute("type").Remove();
}
}
}
foreach (var Tcc in Context.TableConstraints.OfType<TableOrViewColumnConstraint>()) {
XElement xunique;
xelt.Add(xunique = new XElement(xxs + "unique"
, new XAttribute("name", dut.xsname(Tcc))
, new XElement(xxs + "selector"
, new XAttribute("xpath", ".//mstns:" + dut.xsname(Tcc.Parent))
)
));
foreach (var tcol in Tcc.Columns) {
xunique.Add(new XElement(xxs + "field"
, new XAttribute("xpath", "mstns:" + dut.xsname(tcol))
)
);
}
var pk = Tcc as PrimaryKeyConstraint;
if (pk != null) {
xunique.SetAttributeValue(xmsdata + "PrimaryKey", "true");
}
}
XElement xrel;
xSchema.Add(new XElement(xxs + "annotation"
, xrel = new XElement(xxs + "appinfo")
));
foreach (var Tfk in Context.TableForeignKeys) {
xrel.Add(new XElement(xmsdata + "Relationship"
, new XAttribute("name", dut.xsname(Tfk.Constraint))
, new XAttribute(xmsdata + "parent", dut.xsname(Tfk.ToColumn.Parent))
, new XAttribute(xmsdata + "child", dut.xsname(Tfk.FromColumn.Parent))
, new XAttribute(xmsdata + "parentkey", dut.xsname(Tfk.ToColumn))
, new XAttribute(xmsdata + "childkey", dut.xsname(Tfk.FromColumn))
, new XAttribute(xmsprop + "Generator_UserChildTable", dut.Generator_UserChildTable(Tfk.FromColumn.Parent))
, new XAttribute(xmsprop + "Generator_ChildPropName", dut.Generator_ChildPropName(Tfk.FromColumn))
, new XAttribute(xmsprop + "Generator_UserRelationName", dut.Generator_UserRelationName(Tfk))
, new XAttribute(xmsprop + "Generator_RelationVarName", dut.Generator_RelationVarName(Tfk))
, new XAttribute(xmsprop + "Generator_UserParentTable", dut.Generator_UserParentTable(Tfk.ToColumn.Parent))
, new XAttribute(xmsprop + "Generator_ParentPropName", dut.Generator_ParentPropName(Tfk.ToColumn))
));
}
}
String fpxsd = Path.Combine(baseDir, modelName + ".xsd");
xsd.Save(fpxsd);
}
}
}
private XElement GetCommandEl(Table Table, DbCommand dbco, DbCommandBuilder cb, XNamespace nsDS) {
XElement xParameters = new XElement(nsDS + "Parameters");
foreach (DbParameter dbp in dbco.Parameters) {
bool AllowDbNull = true;
Column dbc = Table.Columns.Where(p => p.Name == dbp.SourceColumn).FirstOrDefault();
if (dbc != null) {
AllowDbNull = dbc.IsNullable;
}
xParameters.Add(new XElement(nsDS + "Parameter"
, new XAttribute("AllowDbNull", AllowDbNull ? "true" : "false")
, new XAttribute("AutogeneratedName", "")
, new XAttribute("DataSourceName", "")
, new XAttribute("DbType", dbp.DbType + "")
, new XAttribute("Direction", dbp.Direction + "")
, new XAttribute("ParameterName", dbp.ParameterName)
, new XAttribute("Precision", dut.Precision(dbc))
, new XAttribute("ProviderType", dut.ProviderType(dbp, dbc))
, new XAttribute("Scale", dut.Scale(dbc))
, new XAttribute("Size", dut.Size(dbc))
, new XAttribute("SourceColumn", dbp.SourceColumn)
, new XAttribute("SourceColumnNullMapping", dbp.SourceColumnNullMapping ? "true" : "false")
, new XAttribute("SourceVersion", dbp.SourceVersion)
)
);
}
return new XElement(nsDS + "DbCommand"
, new XAttribute("CommandType", "Text")
, new XAttribute("ModifiedByUser", "false")
, new XElement(nsDS + "CommandText"
, new XText(dbco.CommandText)
)
, xParameters
);
}
DUt dut = new DUt();
class DUt {
public DbProviderManifest providerManifest { get; set; }
public String providerName { get; set; }
public String modelName { get; set; }
public String targetSchema { get; set; }
public String StringLiteralPattern { get; set; }
public String QuotedIdentifierPattern { get; set; }
public String ParameterNamePattern { get; set; }
public int ParameterNameMaxLength { get; set; }
public String ParameterMarkerPattern { get; set; }
public String ParameterMarkerFormat { get; set; }
public IdentifierCase IdentifierCase { get; set; }
public String IdentifierPattern { get; set; }
public String CompositeIdentifierSeparatorPattern { get; set; }
internal string STable(Table Table, DbCommandBuilder cb) {
if (cb.CatalogLocation != CatalogLocation.Start) throw new NotSupportedException("CatalogLocation: " + cb.CatalogLocation);
return ""
+ cb.QuoteIdentifier(Table.CatalogName)
+ cb.CatalogSeparator
+ cb.QuoteIdentifier(Table.SchemaName)
+ cb.SchemaSeparator
+ cb.QuoteIdentifier(Table.Name)
;
}
public String DbObjectName(Table Table, DbCommandBuilder cb) {
return ""
+ cb.QuoteIdentifier(Table.CatalogName)
+ cb.CatalogSeparator
+ cb.QuoteIdentifier(Table.SchemaName)
+ cb.SchemaSeparator
+ cb.QuoteIdentifier(Table.Name)
;
}
internal String SColumn(Column p, DbCommandBuilder cb) {
return cb.QuoteIdentifier(p.Name);
}
public String Precision(Column dbc) {
int? v = new int?();
if (dbc != null) v = dbc.ColumnType.Precision;
return Convert.ToString(v ?? 0);
}
public String Scale(Column dbc) {
int? v = new int?();
if (dbc != null) v = dbc.ColumnType.Scale;
return Convert.ToString(v ?? 0);
}
public String Size(Column dbc) {
int? v = new int?();
if (dbc != null) {
v = dbc.ColumnType.MaxLength;
if (v.HasValue && v.Value == -1) v = null;
}
return Convert.ToString(v ?? 0);
}
public String ProviderType(DbParameter dbp, Column dbc) {
if (dbc != null)
return dbc.ColumnType.TypeName;
foreach (var storeType in providerManifest.GetStoreTypes()) {
if (storeType.ClrEquivalentType.Name == dbp.DbType + "") {
if (storeType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType) {
return storeType.Name;
}
}
}
return null;
}
private string CLRSafe(TableOrView Table) { return TSimpleIdentifier(Table.Name, ""); }
private string CLRSafe(TableOrView Table, string prefix) { return TSimpleIdentifier(Table.Name, prefix); }
private string CLRSafe(Column dbc) { return TSimpleIdentifier(dbc.Name, ""); }
private string CLRSafe(Column dbc, string prefix) { return TSimpleIdentifier(dbc.Name, prefix); }
private string CLRSafe(String s, string prefix) { return TSimpleIdentifier(s, prefix); }
private string CLRSafe(ForeignKey Tfk) { return TSimpleIdentifier(Tfk.Constraint.Name, ""); }
public String Generator_TableClassName(Table Table) { return String.Format("{0}DataTable", CLRSafe(Table, "_")); }
public String Generator_TableVarName(Table Table) { return String.Format("table{0}", CLRSafe(Table)); }
public String Generator_TablePropName(Table Table) { return String.Format("{0}", CLRSafe(Table, "_")); }
public String Generator_RowDeletingName(Table Table) { return String.Format("{0}RowDeleting", CLRSafe(Table, "_")); }
public String Generator_RowChangingName(Table Table) { return String.Format("{0}RowChanging", CLRSafe(Table, "_")); }
public String Generator_RowEvHandlerName(Table Table) { return String.Format("{0}RowChangeEventHandler", CLRSafe(Table, "_")); }
public String Generator_RowDeletedName(Table Table) { return String.Format("{0}RowDeleted", CLRSafe(Table, "_")); }
public String Generator_UserTableName(Table Table) { return String.Format("{0}", CLRSafe(Table)); }
public String Generator_RowChangedName(Table Table) { return String.Format("{0}RowChanged", CLRSafe(Table, "_")); }
public String Generator_RowEvArgName(Table Table) { return String.Format("{0}RowChangeEvent", CLRSafe(Table, "_")); }
public String Generator_RowClassName(Table Table) { return String.Format("{0}Row", CLRSafe(Table, "_")); }
public String Generator_ColumnVarNameInTable(Column dbc) { return String.Format("column{0}", CLRSafe(dbc)); }
public String Generator_ColumnPropNameInRow(Column dbc) { return String.Format("{0}", CLRSafe(dbc, "_")); }
public String Generator_ColumnPropNameInTable(Column dbc) { return String.Format("Id{0}", CLRSafe(dbc)); }
public String Generator_UserColumnName(Column dbc) { return String.Format("{0}", (dbc.Name)); } // raw
public String Generator_DataSetName(string dbn) { return "DataSet1"; }
public String Generator_UserDSName(string dbn) { return "DataSet1"; }
public String xstype(Column dbc) {
foreach (var storeType in providerManifest.GetStoreTypes()) {
if (storeType.Name == dbc.ColumnType.TypeName) {
if (storeType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType) {
if (storeType.ClrEquivalentType == typeof(string)) return "xs:string";
if (storeType.ClrEquivalentType == typeof(int)) return "xs:int";
if (storeType.ClrEquivalentType == typeof(long)) return "xs:long";
if (storeType.ClrEquivalentType == typeof(bool)) return "xs:boolean";
if (storeType.ClrEquivalentType == typeof(DateTime)) return "xs:dateTime";
if (storeType.ClrEquivalentType == typeof(double)) return "xs:double";
if (storeType.ClrEquivalentType == typeof(decimal)) return "xs:decimal";
if (storeType.ClrEquivalentType == typeof(float)) return "xs:float";
if (storeType.ClrEquivalentType == typeof(short)) return "xs:short";
if (storeType.ClrEquivalentType == typeof(byte)) return "xs:unsignedByte";
}
}
}
if (false) { }
else if (dbc.ColumnType.TypeName == "time") return "xs:duration";
else if (dbc.ColumnType.TypeName == "oid") return "xs:long";
else if (dbc.ColumnType.TypeName == "bytea") return "xs:hexBinary";
else return "xs:string";
}
public String TSimpleIdentifier(String s, String defaultPrefix) {
s = Regex.Replace(s, "[\\[\\]\\/\\-\\.\\\\:]+", "_").TrimStart('_');
if (s.Length >= 1 && char.IsNumber(s[0])) s = defaultPrefix + s;
return s;
}
public String DataAccessorName(Table Table) { return String.Format("{0}TableAdapter", Table.Name); }
public String GeneratorDataComponentClassName(Table Table) { return CLRSafe(DataAccessorName(Table), "_"); }
public String UserDataComponentName(Table Table) { return DataAccessorName(Table); }
public String xsname(Column dbc) { return XSafe(dbc.Name); }
public String xsname(TableOrView Table) { return XSafe(Table.Name); }
public String xsname(Store.Constraint Tc) { return XSafe(Tc.Name); }
private string XSafe(String p) { // xs:name safe
String s = null;
if (!String.IsNullOrEmpty(p)) {
s = String.Empty;
for (int x = 0; x < p.Length; x++) {
char c = p[x];
if ((x == 0 && !char.IsLetter(c)) || c == ':' || (c < 256 && c != '_' && c != '#' && !char.IsLetterOrDigit(c))) {
s += String.Format("_x{0:X4}_", (int)c);
}
else {
s += c;
}
}
}
return s;
}
public String Generator_UserChildTable(TableOrView tableOrView) { return CLRSafe(tableOrView); }
public String Generator_ChildPropName(Column column) { return String.Format("Get{0}Rows", CLRSafe(column.Parent)); }
public String Generator_UserRelationName(ForeignKey Tfk) { return CLRSafe(Tfk); }
public String Generator_RelationVarName(ForeignKey Tfk) { return String.Format("relation{0}", CLRSafe(Tfk)); }
public String Generator_UserParentTable(TableOrView tableOrView) { return CLRSafe(tableOrView); }
public String Generator_ParentPropName(Column column) { return String.Format("{0}Row", CLRSafe(column.Parent, "_")); }
public String SourceColumn(Column dbc) { return dbc.Name; }
public String DataSetColumn(Column dbc) { return dbc.Name; }
}
XNamespace nsDS = "urn:schemas-microsoft-com:xml-msdatasource";
public void DataSet_cs(String fpxsd, String fpcs) {
//XDocument xsd = XDocument.Load(fpxsd);
CodeNamespace csns = new CodeNamespace("Test");
DataSet ds = new System.Data.DataSet();
ds.ReadXmlSchema(fpxsd);
String targetNamespace = ds.Namespace;
{
String Generator_DataSetName = "" + ds.ExtendedProperties["Generator_DataSetName"];
var dataSet1 = new CodeTypeDeclaration(Generator_DataSetName);
csns.Types.Add(dataSet1);
dataSet1.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(SerializableAttribute))
));
dataSet1.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(DesignerCategoryAttribute))
, new CodeAttributeArgument(new CodePrimitiveExpression("code"))
));
dataSet1.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(ToolboxItemAttribute))
, new CodeAttributeArgument(new CodePrimitiveExpression(true))
));
dataSet1.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(XmlSchemaProviderAttribute))
, new CodeAttributeArgument(new CodePrimitiveExpression("GetTypedDataSetSchema"))
));
dataSet1.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(XmlRootAttribute))
, new CodeAttributeArgument(new CodePrimitiveExpression("vs.data.DataSet"))
));
dataSet1.BaseTypes.Add(new CodeTypeReference(typeof(DataSet)));
foreach (DataTable dt in ds.Tables) {
String Generator_TableClassName = "" + dt.ExtendedProperties["Generator_TableClassName"];
String Generator_TableVarName = "" + dt.ExtendedProperties["Generator_TableVarName"];
var privateTable = new CodeMemberField(Generator_TableClassName, Generator_TableVarName);
dataSet1.Members.Add(privateTable);
}
foreach (DataRelation rel in ds.Relations) {
String Generator_RelationVarName = "" + rel.ExtendedProperties["Generator_RelationVarName"];
var privateRel = new CodeMemberField(typeof(DataRelation), Generator_RelationVarName);
dataSet1.Members.Add(privateRel);
}
dataSet1.Members.Add(new CodeMemberField(typeof(SchemaSerializationMode), "_schemaSerializationMode") { InitExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(SchemaSerializationMode)), "IncludeSchema") });
// ctor()
{
var ctor = new CodeConstructor();
ctor.Attributes = MemberAttributes.Public;
dataSet1.Members.Add(ctor);
ctor.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "BeginInit"));
ctor.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "InitClass"));
ctor.Statements.Add(new CodeVariableDeclarationStatement(typeof(CollectionChangeEventHandler), "schemaChangedHandler") {
InitExpression = new CodeObjectCreateExpression(typeof(CollectionChangeEventHandler), new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "SchemaChanged"))
});
ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Tables"), "CollectionChanged"), new CodeVariableReferenceExpression("schemaChangedHandler")));
ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Relations"), "CollectionChanged"), new CodeVariableReferenceExpression("schemaChangedHandler")));
ctor.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "EndInit"));
}
foreach (DataTable dt in ds.Tables) {
String Generator_TableClassName = "" + dt.ExtendedProperties["Generator_TableClassName"];
String Generator_TableVarName = "" + dt.ExtendedProperties["Generator_TableVarName"];
String Generator_TablePropName = "" + dt.ExtendedProperties["Generator_TablePropName"];
var publicTable = new CodeMemberProperty();
publicTable.Attributes = MemberAttributes.Public | MemberAttributes.Final;
publicTable.Type = new CodeTypeReference(Generator_TableClassName);
publicTable.Name = Generator_TablePropName;
publicTable.GetStatements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), Generator_TableVarName)));
publicTable.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute))
));
publicTable.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(BrowsableAttribute))
, new CodeAttributeArgument(new CodePrimitiveExpression(false))
));
publicTable.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(DesignerSerializationVisibilityAttribute))
, new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(DesignerSerializationVisibility)), "Content"))
));
dataSet1.Members.Add(publicTable);
}
// SchemaSerializationMode
{
var mem = new CodeMemberProperty();
mem.Attributes = MemberAttributes.Public | MemberAttributes.Override;
mem.Type = new CodeTypeReference(typeof(SchemaSerializationMode));
mem.Name = "SchemaSerializationMode";
mem.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_schemaSerializationMode")));
mem.SetStatements.Add(new CodeAssignStatement(
new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_schemaSerializationMode"),
new CodePropertySetValueReferenceExpression()
));
mem.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute))
));
mem.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(BrowsableAttribute))
, new CodeAttributeArgument(new CodePrimitiveExpression(true))
));
mem.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(DesignerSerializationVisibilityAttribute))
, new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(DesignerSerializationVisibility)), "Visible"))
));
dataSet1.Members.Add(mem);
}
// Tables
// Relations
// InitializeDerivedDataSet
{
var mem = new CodeMemberMethod();
dataSet1.Members.Add(mem);
mem.Attributes = MemberAttributes.Public | MemberAttributes.Override;
mem.Name = "InitializeDerivedDataSet";
mem.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute))
));
mem.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "BeginInit"));
mem.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "InitClass"));
mem.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "EndInit"));
}
// Clone
{
var mem = new CodeMemberMethod();
dataSet1.Members.Add(mem);
mem.Attributes = MemberAttributes.Public | MemberAttributes.Override;
mem.ReturnType = new CodeTypeReference(typeof(DataSet));
mem.Name = "Clone";
mem.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute))
));
mem.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(dataSet1.Name), "cln") {
InitExpression = new CodeCastExpression(
new CodeTypeReference(dataSet1.Name)
, new CodeMethodInvokeExpression(
new CodeBaseReferenceExpression(), "Clone")
)
});
mem.Statements.Add(
new CodeMethodInvokeExpression(
new CodeVariableReferenceExpression("cln"), "InitVars")
);
mem.Statements.Add(new CodeAssignStatement(
new CodePropertyReferenceExpression(
new CodeVariableReferenceExpression("cln"), "SchemaSerializationMode")
, new CodePropertyReferenceExpression(
new CodeThisReferenceExpression(), "SchemaSerializationMode")
));
mem.Statements.Add(new CodeMethodReturnStatement(
new CodeVariableReferenceExpression("cln")
));
}
// ShouldSerializeTables
{
var mem = new CodeMemberMethod();
dataSet1.Members.Add(mem);
mem.Attributes = MemberAttributes.Family | MemberAttributes.Override;
mem.ReturnType = new CodeTypeReference(typeof(bool));
mem.Name = "ShouldSerializeTables";
mem.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute))
));
mem.Statements.Add(
new CodeMethodReturnStatement(new CodePrimitiveExpression(false))
);
}
// ShouldSerializeRelations
{
var mem = new CodeMemberMethod();
dataSet1.Members.Add(mem);
mem.Attributes = MemberAttributes.Family | MemberAttributes.Override;
mem.ReturnType = new CodeTypeReference(typeof(bool));
mem.Name = "ShouldSerializeRelations";
mem.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute))
));
mem.Statements.Add(
new CodeMethodReturnStatement(new CodePrimitiveExpression(false))
);
}
// ReadXmlSerializable
{
var mem = new CodeMemberMethod();
dataSet1.Members.Add(mem);
mem.Attributes = MemberAttributes.Family | MemberAttributes.Override;
mem.Name = "ReadXmlSerializable";
mem.CustomAttributes.Add(new CodeAttributeDeclaration(
new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute))
));
mem.Parameters.Add(new CodeParameterDeclarationExpression(typeof(XmlReader), "reader"));
CodeStatement insertAt;
var if1 = new CodeConditionStatement(
// condition
new CodeBinaryOperatorExpression(
// left
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression(),
"DetermineSchemaSerializationMode",
new CodeVariableReferenceExpression("reader")
)
// op
, CodeBinaryOperatorType.ValueEquality
// right
, new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(SchemaSerializationMode))
, "IncludeSchema"
)
)
// true
, new CodeStatement[] {
new CodeExpressionStatement(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression()
, "Reset"
)
)
, new CodeVariableDeclarationStatement(
typeof(DataSet)
, "ds"
, new CodeObjectCreateExpression(
typeof(DataSet)
)
)
, new CodeExpressionStatement(
new CodeMethodInvokeExpression(
new CodeVariableReferenceExpression("ds")
, "ReadXml"
, new CodeVariableReferenceExpression("reader")
)
)
, insertAt = new CodeAssignStatement(
new CodePropertyReferenceExpression(
new CodeThisReferenceExpression()
, "DataSetName"
)
, new CodePropertyReferenceExpression(
new CodeVariableReferenceExpression("ds")
, "DataSetName"
)
)
, new CodeAssignStatement(
new CodePropertyReferenceExpression(
new CodeThisReferenceExpression()
, "Prefix"
)
, new CodePropertyReferenceExpression(
new CodeVariableReferenceExpression("ds")
, "Prefix"
)
)
, new CodeAssignStatement(
new CodePropertyReferenceExpression(
new CodeThisReferenceExpression()
, "Namespace"
)
, new CodePropertyReferenceExpression(
new CodeVariableReferenceExpression("ds")
, "Namespace"
)
)
, new CodeAssignStatement(
new CodePropertyReferenceExpression(
new CodeThisReferenceExpression()
, "Locale"
)
, new CodePropertyReferenceExpression(
new CodeVariableReferenceExpression("ds")
, "Locale"
)
)
, new CodeAssignStatement(
new CodePropertyReferenceExpression(
new CodeThisReferenceExpression()
, "CaseSensitive"
)
, new CodePropertyReferenceExpression(
new CodeVariableReferenceExpression("ds")
, "CaseSensitive"
)
)
, new CodeAssignStatement(
new CodePropertyReferenceExpression(
new CodeThisReferenceExpression()
, "EnforceConstraints"
)
, new CodePropertyReferenceExpression(
new CodeVariableReferenceExpression("ds")
, "EnforceConstraints"
)
)
, new CodeExpressionStatement(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression()
, "Merge"
, new CodeVariableReferenceExpression("ds")
, new CodePrimitiveExpression(false)
, new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(MissingSchemaAction))
, "Add"
)
)
)
, new CodeExpressionStatement(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression()
, "InitVars"
)
),
}
// false
, new CodeStatement[] {
new CodeExpressionStatement(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression()
, "ReadXml"
, new CodeVariableReferenceExpression("reader")
)
)
, new CodeExpressionStatement(
new CodeMethodInvokeExpression(
new CodeThisReferenceExpression()
, "InitVars"
)
),
}
);
mem.Statements.Add(if1);
foreach (DataTable dt in ds.Tables) {
String Generator_TablePropName = "" + dt.ExtendedProperties["Generator_TablePropName"];
String Generator_TableClassName = "" + dt.ExtendedProperties["Generator_TableClassName"];
if1.TrueStatements.Insert(
if1.TrueStatements.IndexOf(insertAt)
, new CodeConditionStatement(
new CodeBinaryOperatorExpression(
new CodeIndexerExpression( // left
new CodePropertyReferenceExpression(
new CodeVariableReferenceExpression("ds")
, "Tables"
)
, new CodePrimitiveExpression(Generator_TablePropName)
)
, CodeBinaryOperatorType.IdentityInequality // op
, new CodePrimitiveExpression(null) // right
)
, new CodeStatement[] { // true
new CodeExpressionStatement(
new CodeMethodInvokeExpression(
new CodePropertyReferenceExpression(
new CodeBaseReferenceExpression()
, "Tables"
)
, "Add"