-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathD365ODataClient.ttinclude
5142 lines (4709 loc) · 231 KB
/
D365ODataClient.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
<#
/*
OData Client T4 Template ver. 2.4.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#>
<#@ template debug="true" hostSpecific="true" visibility="internal" linePragmas="false"#>
<#@ output extension=".cs" #>
<#@ Assembly Name="System.Core.dll" #>
<#@ Assembly Name="System.Xml.dll" #>
<#@ Assembly Name="System.Xml.Linq.dll" #>
<#@ Assembly Name="System.Windows.Forms.dll" #>
<#@ Assembly Name="Microsoft.OData.Client.dll" #>
<#@ Assembly Name="Microsoft.OData.Core.dll" #>
<#@ Assembly Name="Microsoft.OData.Edm.dll" #>
<#@ Assembly Name="Microsoft.Spatial.dll" #>
<#@ Import Namespace="System" #>
<#@ Import Namespace="System.IO" #>
<#@ Import Namespace="System.Diagnostics" #>
<#@ Import Namespace="System.Globalization" #>
<#@ Import Namespace="System.Linq" #>
<#@ Import Namespace="System.Xml"#>
<#@ Import Namespace="System.Xml.Linq" #>
<#@ Import Namespace="System.Collections.Generic" #>
<#@ Import Namespace="Microsoft.OData.Edm.Csdl" #>
<#@ Import Namespace="Microsoft.OData.Edm" #>
<#@ Import Namespace="Microsoft.OData.Edm.Annotations" #>
<#@ Import Namespace="Microsoft.OData.Edm.Expressions" #>
<#@ Import Namespace="Microsoft.OData.Edm.Library" #>
<#@ Import Namespace="Microsoft.OData.Edm.Values" #>
<#@ Import Namespace="Microsoft.OData.Edm.Vocabularies.V1" #>
<#@ Import Namespace="Microsoft.OData.Edm.Vocabularies.Community.V1" #>
<#@ Import Namespace="System.Text"#>
<#@ Import Namespace="System.Net"#>
<#@include file="MultipleOutputHelper.ttinclude"#>
<#
CodeGenerationContext context;
if (!string.IsNullOrWhiteSpace(this.Edmx))
{
context = new CodeGenerationContext(this.Edmx, this.NamespacePrefix)
{
UseDataServiceCollection = this.UseDataServiceCollection,
TargetLanguage = this.TargetLanguage,
EnableNamingAlias = this.EnableNamingAlias,
IgnoreUnexpectedElementsAndAttributes = this.IgnoreUnexpectedElementsAndAttributes
};
}
else
{
this.ApplyParametersFromCommandLine();
if (string.IsNullOrEmpty(metadataDocumentUri))
{
this.ApplyParametersFromConfigurationClass();
}
context = new CodeGenerationContext(new Uri(this.MetadataDocumentUri, UriKind.Absolute), this.NamespacePrefix)
{
UseDataServiceCollection = this.UseDataServiceCollection,
TargetLanguage = this.TargetLanguage,
EnableNamingAlias = this.EnableNamingAlias,
IgnoreUnexpectedElementsAndAttributes = this.IgnoreUnexpectedElementsAndAttributes
};
}
if(this.GetReferencedModelReaderFunc != null)
{
context.GetReferencedModelReaderFunc = this.GetReferencedModelReaderFunc;
}
ODataClientTemplate template;
switch(this.TargetLanguage)
{
case LanguageOption.CSharp:
template = new ODataClientCSharpTemplate(context);
break;
case LanguageOption.VB:
template = new ODataClientVBTemplate(context);
break;
default:
throw new NotSupportedException(string.Format("Code gen for the target language '{0}' is not supported.", this.TargetLanguage.ToString()));
}
template.initXxceManager(Host);
template.xxceGenerateFiles();
#>
<#=template.TransformText() #>
<#
foreach (string warning in context.Warnings)
{
this.Warning(warning);
}
#><#+
/// <summary>
/// The string for the edmx content.
/// </summary>
public string Edmx
{
get;
set;
}
/// <summary>
/// The Uri string to the metadata document.
/// </summary>
public string MetadataDocumentUri
{
get
{
return this.metadataDocumentUri;
}
set
{
value = Uri.UnescapeDataString(value);
Uri uri;
if (!Uri.TryCreate(value, UriKind.Absolute, out uri))
{
// ********************************************************************************************************
// To fix this error, if the current text transformation is run by the TextTemplatingFileGenerator
// custom tool inside Visual Studio, update the .odata.config file in the project with a valid parameter
// value then hit Ctrl-S to save the .tt file to refresh the code generation.
// ********************************************************************************************************
throw new ArgumentException(string.Format("The value \"{0}\" is not a valid MetadataDocumentUri because is it not a valid absolute Uri. The MetadataDocumentUri must be set to an absolute Uri referencing the $metadata endpoint of an OData service.", value));
}
if (uri.Scheme == "http" || uri.Scheme == "https")
{
value = uri.Scheme + "://" + uri.Authority + uri.AbsolutePath;
value = value.TrimEnd('/');
if (!value.EndsWith("$metadata"))
{
value += "/$metadata";
}
}
this.metadataDocumentUri = value;
}
}
private string metadataDocumentUri;
/// <summary>
/// The Func to get referenced model's XmlReader. Must have value when the this.Edmx xml or this.metadataDocumentUri's model has referneced model.
/// </summary>
public Func<Uri,XmlReader> GetReferencedModelReaderFunc
{
get;
set;
}
/// <summary>
/// The NamespacePrefix is used as the only namespace for types in the same namespace as the default container,
/// and as a prefix for the namespace from the model for everything else. If this argument is null, the
/// namespaces from the model are used for all types.
/// </summary>
public string NamespacePrefix
{
get
{
return this.namespacePrefix;
}
set
{
if (string.IsNullOrWhiteSpace(value))
{
this.namespacePrefix = null;
}
else
{
this.namespacePrefix = value;
}
}
}
private string namespacePrefix;
/// <summary>
/// true to use DataServiceCollection in the generated code, false otherwise.
/// </summary>
public bool UseDataServiceCollection
{
get;
set;
}
/// <summary>
/// Specifies which specific .Net Framework language the generated code will target.
/// </summary>
public LanguageOption TargetLanguage
{
get;
set;
}
/// <summary>
/// true to use Upper camel case for all class and property names, false otherwise.
/// </summary>
public bool EnableNamingAlias
{
get;
set;
}
/// <summary>
/// true to ignore unknown elements or attributes in metadata, false otherwise.
/// </summary>
public bool IgnoreUnexpectedElementsAndAttributes
{
get;
set;
}
/// <summary>
/// Generate code targeting a specific .Net Framework language.
/// </summary>
public enum LanguageOption
{
/// <summary>Generate code for C# language.</summary>
CSharp = 0,
/// <summary>Generate code for Visual Basic language.</summary>
VB = 1,
}
/// <summary>
/// Set the UseDataServiceCollection property with the given value.
/// </summary>
/// <param name="stringValue">The value to set.</param>
public void ValidateAndSetUseDataServiceCollectionFromString(string stringValue)
{
bool boolValue;
if (!bool.TryParse(stringValue, out boolValue))
{
// ********************************************************************************************************
// To fix this error, if the current text transformation is run by the TextTemplatingFileGenerator
// custom tool inside Visual Studio, update the .odata.config file in the project with a valid parameter
// value then hit Ctrl-S to save the .tt file to refresh the code generation.
// ********************************************************************************************************
throw new ArgumentException(string.Format("The value \"{0}\" cannot be assigned to the UseDataServiceCollection parameter because it is not a valid boolean value.", stringValue));
}
this.UseDataServiceCollection = boolValue;
}
/// <summary>
/// Tries to set the TargetLanguage property with the given value.
/// </summary>
/// <param name="stringValue">The value to set.</param>
public void ValidateAndSetTargetLanguageFromString(string stringValue)
{
LanguageOption option;
if (!Enum.TryParse(stringValue, true, out option))
{
// ********************************************************************************************************
// To fix this error, if the current text transformation is run by the TextTemplatingFileGenerator
// custom tool inside Visual Studio, update the .odata.config file in the project with a valid parameter
// value then hit Ctrl-S to save the .tt file to refresh the code generation.
// ********************************************************************************************************
throw new ArgumentException(string.Format("The value \"{0}\" cannot be assigned to the TargetLanguage parameter because it is not a valid LanguageOption. The supported LanguageOptions are \"CSharp\" and \"VB\".", stringValue));
}
this.TargetLanguage = option;
}
/// <summary>
/// Set the EnableNamingAlias property with the given value.
/// </summary>
/// <param name="stringValue">The value to set.</param>
public void ValidateAndSetEnableNamingAliasFromString(string stringValue)
{
bool boolValue;
if (!bool.TryParse(stringValue, out boolValue))
{
// ********************************************************************************************************
// To fix this error, if the current text transformation is run by the TextTemplatingFileGenerator
// custom tool inside Visual Studio, update the .odata.config file in the project with a valid parameter
// value then hit Ctrl-S to save the .tt file to refresh the code generation.
// ********************************************************************************************************
throw new ArgumentException(string.Format("The value \"{0}\" cannot be assigned to the EnableNamingAlias parameter because it is not a valid boolean value.", stringValue));
}
this.EnableNamingAlias = boolValue;
}
/// <summary>
/// Set the IgnoreUnexpectedElementsAndAttributes property with the given value.
/// </summary>
/// <param name="stringValue">The value to set.</param>
public void ValidateAndSetIgnoreUnexpectedElementsAndAttributesFromString(string stringValue)
{
bool boolValue;
if (!bool.TryParse(stringValue, out boolValue))
{
// ********************************************************************************************************
// To fix this error, if the current text transformation is run by the TextTemplatingFileGenerator
// custom tool inside Visual Studio, update the .odata.config file in the project with a valid parameter
// value then hit Ctrl-S to save the .tt file to refresh the code generation.
// ********************************************************************************************************
throw new ArgumentException(string.Format("The value \"{0}\" cannot be assigned to the IgnoreUnexpectedElementsAndAttributes parameter because it is not a valid boolean value.", stringValue));
}
this.IgnoreUnexpectedElementsAndAttributes = boolValue;
}
/// <summary>
/// Reads the parameter values from the Configuration class and applies them.
/// </summary>
private void ApplyParametersFromConfigurationClass()
{
this.MetadataDocumentUri = Configuration.MetadataDocumentUri;
this.NamespacePrefix = Configuration.NamespacePrefix;
this.UseDataServiceCollection = Configuration.UseDataServiceCollection;
this.ValidateAndSetTargetLanguageFromString(Configuration.TargetLanguage);
this.EnableNamingAlias = Configuration.EnableNamingAlias;
this.IgnoreUnexpectedElementsAndAttributes = Configuration.IgnoreUnexpectedElementsAndAttributes;
}
/// <summary>
/// Reads the parameter values from the command line (TextTransform.exe) and applies them.
/// </summary>
private void ApplyParametersFromCommandLine()
{
if (this.Host == null)
{
return;
}
string metadataDocumentUri = this.Host.ResolveParameterValue("notempty", "notempty", "MetadataDocumentUri");
if (!string.IsNullOrEmpty(metadataDocumentUri))
{
this.MetadataDocumentUri = metadataDocumentUri;
}
string namespacePrefix = this.Host.ResolveParameterValue("notempty", "notempty", "NamespacePrefix");
if (!string.IsNullOrEmpty(namespacePrefix))
{
this.NamespacePrefix = namespacePrefix;
}
string useDataServiceCollection = this.Host.ResolveParameterValue("notempty", "notempty", "UseDataServiceCollection");
if (!string.IsNullOrEmpty(useDataServiceCollection))
{
this.ValidateAndSetUseDataServiceCollectionFromString(useDataServiceCollection);
}
string targetLanguage = this.Host.ResolveParameterValue("notempty", "notempty", "TargetLanguage");
if (!string.IsNullOrEmpty(targetLanguage))
{
this.ValidateAndSetTargetLanguageFromString(targetLanguage);
}
string enableNamingAlias = this.Host.ResolveParameterValue("notempty", "notempty", "EnableNamingAlias");
if (!string.IsNullOrEmpty(enableNamingAlias))
{
this.ValidateAndSetEnableNamingAliasFromString(enableNamingAlias);
}
string ignoreUnexpectedElementsAndAttributes = this.Host.ResolveParameterValue("notempty", "notempty", "IgnoreUnexpectedElementsAndAttributes");
if (!string.IsNullOrEmpty(ignoreUnexpectedElementsAndAttributes))
{
this.ValidateAndSetIgnoreUnexpectedElementsAndAttributesFromString(ignoreUnexpectedElementsAndAttributes);
}
}
/// <summary>
/// Context object to provide the model and configuration info to the code generator.
/// </summary>
public class CodeGenerationContext
{
/// <summary>
/// The namespace of the term to use when building value annotations for indicating the conventions used.
/// </summary>
private const string ConventionTermNamespace = "Com.Microsoft.OData.Service.Conventions.V1";
/// <summary>
/// The name of the term to use when building value annotations for indicating the conventions used.
/// </summary>
private const string ConventionTermName = "UrlConventions";
/// <summary>
/// The string value for indicating that the key-as-segment convention is being used in annotations and headers.
/// </summary>
private const string KeyAsSegmentConventionName = "KeyAsSegment";
/// <summary>
/// The XElement for the edmx
/// </summary>
private readonly XElement edmx;
/// <summary>
/// The namespacePrefix is used as the only namespace in generated code when there's only one schema in edm model,
/// and as a prefix for the namespace from the model with multiple schemas. If this argument is null, the
/// namespaces from the model are used for all types.
/// </summary>
private readonly string namespacePrefix;
/// <summary>
/// The EdmModel to generate code for.
/// </summary>
private IEdmModel edmModel;
/// <summary>
/// The array of namespaces in the current edm model.
/// </summary>
private string[] namespacesInModel;
/// <summary>
/// The array of warnings occured when parsing edm model.
/// </summary>
private string[] warnings;
/// <summary>
/// true if the model contains any structural type with inheritance, false otherwise.
/// </summary>
private bool? modelHasInheritance;
/// <summary>
/// If the namespacePrefix is not null, this contains the mapping of namespaces in the model to the corresponding prefixed namespaces.
/// Otherwise this is an empty dictionary.
/// </summary>
private Dictionary<string, string> namespaceMap;
/// <summary>
/// Maps the element type of a navigation source to the navigation source.
/// </summary>
private Dictionary<IEdmEntityType, List<IEdmNavigationSource>> elementTypeToNavigationSourceMap;
/// <summary>
/// HashSet contains the pair of Names and Namespaces of EntityContainers using KeyAsSegment url convention
/// </summary>
private HashSet<string> keyAsSegmentContainers;
/// <summary>
/// Constructs an instance of <see cref="CodeGenerationContext"/>.
/// </summary>
/// <param name="metadataUri">The Uri to the metadata document. The supported scheme are File, http and https.</param>
public CodeGenerationContext(Uri metadataUri, string namespacePrefix)
: this(GetEdmxStringFromMetadataPath(metadataUri), namespacePrefix)
{
}
/// <summary>
/// Constructs an instance of <see cref="CodeGenerationContext"/>.
/// </summary>
/// <param name="edmx">The string for the edmx.</param>
/// <param name="namespacePrefix">The namespacePrefix is used as the only namespace in generated code
/// when there's only one schema in edm model, and as a prefix for the namespace from the model with multiple
/// schemas. If this argument is null, the namespaces from the model are used for all types.</param>
public CodeGenerationContext(string edmx, string namespacePrefix)
{
this.edmx = XElement.Parse(edmx);
this.namespacePrefix = namespacePrefix;
}
/// <summary>
/// The EdmModel to generate code for.
/// </summary>
public XElement Edmx
{
get { return this.edmx; }
}
/// <summary>
/// The EdmModel to generate code for.
/// </summary>
public IEdmModel EdmModel
{
get
{
if (this.edmModel == null)
{
Debug.Assert(this.edmx != null, "this.edmx != null");
IEnumerable<Microsoft.OData.Edm.Validation.EdmError> errors;
EdmxReaderSettings edmxReaderSettings = new EdmxReaderSettings()
{
GetReferencedModelReaderFunc = this.GetReferencedModelReaderFuncWrapper,
IgnoreUnexpectedAttributesAndElements = this.IgnoreUnexpectedElementsAndAttributes
};
if (!EdmxReader.TryParse(this.edmx.CreateReader(ReaderOptions.None), Enumerable.Empty<IEdmModel>(), edmxReaderSettings, out this.edmModel, out errors))
{
Debug.Assert(errors != null, "errors != null");
throw new InvalidOperationException(errors.FirstOrDefault().ErrorMessage);
}
else if (this.IgnoreUnexpectedElementsAndAttributes)
{
if (errors != null && errors.Any())
{
this.warnings = errors.Select(e => e.ErrorMessage).ToArray();
}
}
}
return this.edmModel;
}
}
/// <summary>
/// The func for user code to overwrite and provide referenced model's XmlReader.
/// </summary>
public Func<Uri,XmlReader> GetReferencedModelReaderFunc
{
get { return getReferencedModelReaderFunc; }
set { this.getReferencedModelReaderFunc = value; }
}
/// <summary>
/// Basic setting for XmlReader.
/// </summary>
private static readonly XmlReaderSettings settings = new XmlReaderSettings() { IgnoreWhitespace = true };
/// <summary>
/// The func for user code to overwrite and provide referenced model's XmlReader.
/// </summary>
private Func<Uri, XmlReader> getReferencedModelReaderFunc = uri => XmlReader.Create(GetEdmxStreamFromUri(uri), settings);
/// <summary>
/// The Wrapper func for user code to overwrite and provide referenced model's stream.
/// </summary>
public Func<Uri, XmlReader> GetReferencedModelReaderFuncWrapper
{
get
{
return (uri) =>
{
using (XmlReader reader = GetReferencedModelReaderFunc(uri))
{
if (reader == null)
{
return null;
}
XElement element = XElement.Load(reader);
if (this.ReferencesMap == null)
{
this.ReferencesMap = new Dictionary<Uri, XElement>();
}
this.ReferencesMap.Add(uri, element);
return element.CreateReader(ReaderOptions.None);
}
};
}
}
/// <summary>
/// Dictionary that stores uri and referenced xml mapping.
/// </summary>
public Dictionary<Uri, XElement> ReferencesMap
{
get;
set;
}
/// <summary>
/// The array of namespaces in the current edm model.
/// </summary>
public string[] NamespacesInModel
{
get
{
if (this.namespacesInModel == null)
{
Debug.Assert(this.EdmModel != null, "this.EdmModel != null");
this.namespacesInModel = GetElementsFromModelTree(this.EdmModel, (m) => m.SchemaElements.Select(e => e.Namespace)).Distinct().ToArray();
}
return this.namespacesInModel;
}
}
/// <summary>
/// The array of warnings occured when parsing edm model.
/// </summary>
public string[] Warnings
{
get { return this.warnings ?? (this.warnings = new string[] {}); }
}
/// <summary>
/// true if the model contains any structural type with inheritance, false otherwise.
/// </summary>
public bool ModelHasInheritance
{
get
{
if (!this.modelHasInheritance.HasValue)
{
Debug.Assert(this.EdmModel != null, "this.EdmModel != null");
this.modelHasInheritance = this.EdmModel.SchemaElementsAcrossModels().OfType<IEdmStructuredType>().Any(t => t.BaseType != null);
}
return this.modelHasInheritance.Value;
}
}
/// <summary>
/// true if we need to generate the ResolveNameFromType method, false otherwise.
/// </summary>
public bool NeedResolveNameFromType
{
get { return this.ModelHasInheritance || this.NamespaceMap.Count > 0 || this.EnableNamingAlias; }
}
/// <summary>
/// true if we need to generate the ResolveTypeFromName method, false otherwise.
/// </summary>
public bool NeedResolveTypeFromName
{
get { return this.NamespaceMap.Count > 0 || this.EnableNamingAlias; }
}
/// <summary>
/// If the namespacePrefix is not null, this contains the mapping of namespaces in the model to the corresponding prefixed namespaces.
/// Otherwise this is an empty dictionary.
/// </summary>
public Dictionary<string, string> NamespaceMap
{
get
{
if (this.namespaceMap == null)
{
if (!string.IsNullOrEmpty(this.namespacePrefix))
{
if (this.NamespacesInModel.Count() == 1)
{
IEdmEntityContainer container = this.EdmModel.EntityContainer;
string containerNamespace = container == null ? null : container.Namespace;
this.namespaceMap = this.NamespacesInModel
.Distinct()
.ToDictionary(
ns => ns,
ns => ns == containerNamespace ?
this.namespacePrefix :
this.namespacePrefix + "." + (this.EnableNamingAlias ? Customization.CustomizeNamespace(ns) : ns));
}
else
{
this.namespaceMap = this.NamespacesInModel
.Distinct()
.ToDictionary(
ns => ns,
ns => this.namespacePrefix + "." + (this.EnableNamingAlias ? Customization.CustomizeNamespace(ns) : ns));
}
}
else if (this.EnableNamingAlias)
{
this.namespaceMap = this.NamespacesInModel
.Distinct()
.ToDictionary(
ns => ns,
ns => Customization.CustomizeNamespace(ns));
}
else
{
this.namespaceMap = new Dictionary<string, string>();
}
}
return this.namespaceMap;
}
}
/// <summary>
/// true to use DataServiceCollection in the generated code, false otherwise.
/// </summary>
public bool UseDataServiceCollection
{
get;
set;
}
/// <summary>
/// Specifies which specific .Net Framework language the generated code will target.
/// </summary>
public LanguageOption TargetLanguage
{
get;
set;
}
/// <summary>
/// true to use Upper camel case for all class and property names, false otherwise.
/// </summary>
public bool EnableNamingAlias
{
get;
set;
}
/// <summary>
/// true to ignore unknown elements or attributes in metadata, false otherwise.
/// </summary>
public bool IgnoreUnexpectedElementsAndAttributes
{
get;
set;
}
/// <summary>
/// Maps the element type of an entity set to the entity set.
/// </summary>
public Dictionary<IEdmEntityType, List<IEdmNavigationSource>> ElementTypeToNavigationSourceMap
{
get
{
return this.elementTypeToNavigationSourceMap ?? (this.elementTypeToNavigationSourceMap = new Dictionary<IEdmEntityType, List<IEdmNavigationSource>>(EqualityComparer<IEdmEntityType>.Default));
}
}
/// <summary>
/// true if this EntityContainer need to set the UrlConvention to KeyAsSegment, false otherwise.
/// </summary>
public bool UseKeyAsSegmentUrlConvention(IEdmEntityContainer currentContainer)
{
if (this.keyAsSegmentContainers == null)
{
this.keyAsSegmentContainers = new HashSet<string>();
Debug.Assert(this.EdmModel != null, "this.EdmModel != null");
IEnumerable<IEdmVocabularyAnnotation> annotations = this.EdmModel.VocabularyAnnotations;
foreach(IEdmValueAnnotation valueAnnotation in annotations.OfType<IEdmValueAnnotation>())
{
IEdmEntityContainer container = valueAnnotation.Target as IEdmEntityContainer;
IEdmValueTerm valueTerm = valueAnnotation.Term as IEdmValueTerm;
IEdmStringConstantExpression expression = valueAnnotation.Value as IEdmStringConstantExpression;
if (container != null && valueTerm != null && expression != null)
{
if (valueTerm.Namespace == ConventionTermNamespace &&
valueTerm.Name == ConventionTermName &&
expression.Value == KeyAsSegmentConventionName)
{
this.keyAsSegmentContainers.Add(container.FullName());
}
}
}
}
return this.keyAsSegmentContainers.Contains(currentContainer.FullName());
}
/// <summary>
/// Gets the enumeration of schema elements with the given namespace.
/// </summary>
/// <param name="ns">The namespace of the schema elements to get.</param>
/// <returns>The enumeration of schema elements with the given namespace.</returns>
public IEnumerable<IEdmSchemaElement> GetSchemaElements(string ns)
{
Debug.Assert(ns != null, "ns != null");
Debug.Assert(this.EdmModel != null, "this.EdmModel != null");
return GetElementsFromModelTree(this.EdmModel, m => m.SchemaElements.Where(e => e.Namespace == ns));
}
/// <summary>
/// Gets the namespace qualified name for the given <paramref name="schemaElement"/> with the namespace prefix applied if this.NamespacePrefix is specified.
/// </summary>
/// <param name="schemaElement">The schema element to get the full name for.</param>
/// <param name="schemaElementFixedName">The fixed name of this schemaElement.</param>
/// <param name="template">The current code generate template.</param>
/// <returns>The namespace qualified name for the given <paramref name="schemaElement"/> with the namespace prefix applied if this.NamespacePrefix is specified.</returns>
public string GetPrefixedFullName(IEdmSchemaElement schemaElement, string schemaElementFixedName, ODataClientTemplate template, bool needGlobalPrefix = true)
{
if (schemaElement == null)
{
return null;
}
return this.GetPrefixedNamespace(schemaElement.Namespace, template, true, needGlobalPrefix) + "." + schemaElementFixedName;
}
/// <summary>
/// Gets the prefixed namespace for the given <paramref name="ns"/>.
/// </summary>
/// <param name="ns">The namespace without the prefix.</param>
/// <param name="template">The current code generate template.</param>
/// <param name="needFix">The flag indicates whether the namespace need to be fixed now.</param>
/// <param name="needGlobalPrefix">The flag indicates whether the namespace need to be added by gloabal prefix.</param>
/// <returns>The prefixed namespace for the given <paramref name="ns"/>.</returns>
public string GetPrefixedNamespace(string ns, ODataClientTemplate template, bool needFix, bool needGlobalPrefix)
{
if (ns == null)
{
return null;
}
string prefixedNamespace;
if (!this.NamespaceMap.TryGetValue(ns, out prefixedNamespace))
{
prefixedNamespace = ns;
}
if (needFix)
{
string[] segments = prefixedNamespace.Split('.');
prefixedNamespace = string.Empty;
int n = segments.Length;
for (int i = 0; i < n; ++i)
{
if (template.LanguageKeywords.Contains(segments[i]))
{
prefixedNamespace += string.Format(template.FixPattern, segments[i]);
}
else
{
prefixedNamespace += segments[i];
}
prefixedNamespace += (i == n - 1 ? string.Empty : ".");
}
}
if (needGlobalPrefix)
{
prefixedNamespace = template.GlobalPrefix + prefixedNamespace;
}
return prefixedNamespace;
}
/// <summary>
/// Reads the edmx string from a file path or a http/https path.
/// </summary>
/// <param name="metadataUri">The Uri to the metadata document. The supported scheme are File, http and https.</param>
private static string GetEdmxStringFromMetadataPath(Uri metadataUri)
{
string content = null;
using (StreamReader streamReader = new StreamReader(GetEdmxStreamFromUri(metadataUri)))
{
content = streamReader.ReadToEnd();
}
return content;
}
/// <summary>
/// Get the metadata stream from a file path or a http/https path.
/// </summary>
/// <param name="metadataUri">The Uri to the stream. The supported scheme are File, http and https.</param>
private static Stream GetEdmxStreamFromUri(Uri metadataUri)
{
Debug.Assert(metadataUri != null, "metadataUri != null");
Stream metadataStream = null;
if (metadataUri.Scheme == "file")
{
metadataStream = new FileStream(Uri.UnescapeDataString(metadataUri.AbsolutePath), FileMode.Open, FileAccess.Read);
}
else if (metadataUri.Scheme == "http" || metadataUri.Scheme == "https")
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(metadataUri);
WebResponse webResponse = webRequest.GetResponse();
metadataStream = webResponse.GetResponseStream();
}
catch (WebException e)
{
HttpWebResponse webResponse = e.Response as HttpWebResponse;
if (webResponse != null && webResponse.StatusCode == HttpStatusCode.Unauthorized)
{
throw new WebException("Failed to access the metadata document. The OData service requires authentication for accessing it. Please download the metadata, store it into a local file, and set the value of “MetadataDocumentUri” in the .odata.config file to the file path. After that, run custom tool again to generate the OData Client code.");
}
else
{
throw e;
}
}
}
else
{
throw new ArgumentException("Only file, http, https schemes are supported for paths to metadata source locations.");
}
return metadataStream;
}
private static IEnumerable<T> GetElementsFromModelTree<T>(IEdmModel mainModel, Func<IEdmModel, IEnumerable<T>> getElementFromOneModelFunc)
{
List<T> ret = new List<T>();
if(mainModel is EdmCoreModel || mainModel.FindDeclaredValueTerm(CoreVocabularyConstants.OptimisticConcurrencyControl) != null)
{
return ret;
}
ret.AddRange(getElementFromOneModelFunc(mainModel));
foreach (var tmp in mainModel.ReferencedModels)
{
if (tmp is EdmCoreModel ||
tmp.FindDeclaredValueTerm(CoreVocabularyConstants.OptimisticConcurrencyControl) != null ||
tmp.FindDeclaredValueTerm(CapabilitiesVocabularyConstants.ChangeTracking) != null ||
tmp.FindDeclaredValueTerm(AlternateKeysVocabularyConstants.AlternateKeys) != null)
{
continue;
}
ret.AddRange(getElementFromOneModelFunc(tmp));
}
return ret;
}
}
/// <summary>
/// The template class to generate the OData client code.
/// </summary>
public abstract class ODataClientTemplate : TemplateBase
{
protected readonly string singleSuffix = "Single";
protected const string T4Version = "2.4.0";
//<xxce>
public Manager xxceManager;
int xxceAutoGenFileNum = 0;
public void initXxceManager(ITextTemplatingEngineHost host)
{
xxceManager = Manager.Create(host, this.GenerationEnvironment);
}
//</xxce>
/// <summary>
/// The code generation context.
/// </summary>
protected readonly CodeGenerationContext context;
/// <summary>
/// The Dictionary to store identifier mappings when there are duplicate names between properties and Entity/Complex types
/// </summary>
protected Dictionary<string, string> IdentifierMappings = new Dictionary<string, string>(StringComparer.Ordinal);
/// <summary>
/// Creates an instance of the ODataClientTemplate.
/// </summary>
/// <param name="context">The code generation context.</param>
public ODataClientTemplate(CodeGenerationContext context)
{
this.context = context;
}
#region Get Language specific keyword names.
internal abstract string GlobalPrefix { get; }
internal abstract string SystemTypeTypeName { get; }
internal abstract string AbstractModifier { get; }
internal abstract string DataServiceActionQueryTypeName { get; }
internal abstract string DataServiceActionQuerySingleOfTStructureTemplate { get; }
internal abstract string DataServiceActionQueryOfTStructureTemplate { get; }
internal abstract string NotifyPropertyChangedModifier { get; }
internal abstract string ClassInheritMarker { get; }
internal abstract string ParameterSeparator { get; }
internal abstract string KeyParameterSeparator { get; }
internal abstract string KeyDictionaryItemSeparator { get; }
internal abstract string SystemNullableStructureTemplate { get; }
internal abstract string ICollectionOfTStructureTemplate { get; }
internal abstract string DataServiceCollectionStructureTemplate { get; }
internal abstract string DataServiceQueryStructureTemplate { get; }
internal abstract string DataServiceQuerySingleStructureTemplate { get; }
internal abstract string ObservableCollectionStructureTemplate { get; }
internal abstract string ObjectModelCollectionStructureTemplate { get; }
internal abstract string DataServiceCollectionConstructorParameters { get; }
internal abstract string NewModifier { get; }
internal abstract string GeoTypeInitializePattern { get; }
internal abstract string Int32TypeName { get; }
internal abstract string StringTypeName { get; }
internal abstract string BinaryTypeName { get; }
internal abstract string DecimalTypeName { get; }
internal abstract string Int16TypeName { get; }
internal abstract string SingleTypeName { get; }
internal abstract string BooleanTypeName { get; }
internal abstract string DoubleTypeName { get; }
internal abstract string GuidTypeName { get; }
internal abstract string ByteTypeName { get; }
internal abstract string Int64TypeName { get; }
internal abstract string SByteTypeName { get; }
internal abstract string DataServiceStreamLinkTypeName { get; }
internal abstract string GeographyTypeName { get; }
internal abstract string GeographyPointTypeName { get; }
internal abstract string GeographyLineStringTypeName { get; }
internal abstract string GeographyPolygonTypeName { get; }
internal abstract string GeographyCollectionTypeName { get; }
internal abstract string GeographyMultiPolygonTypeName { get; }
internal abstract string GeographyMultiLineStringTypeName { get; }
internal abstract string GeographyMultiPointTypeName { get; }
internal abstract string GeometryTypeName { get; }
internal abstract string GeometryPointTypeName { get; }
internal abstract string GeometryLineStringTypeName { get; }
internal abstract string GeometryPolygonTypeName { get; }
internal abstract string GeometryCollectionTypeName { get; }
internal abstract string GeometryMultiPolygonTypeName { get; }
internal abstract string GeometryMultiLineStringTypeName { get; }
internal abstract string GeometryMultiPointTypeName { get; }
internal abstract string DateTypeName { get; }
internal abstract string DateTimeOffsetTypeName { get; }
internal abstract string DurationTypeName { get; }
internal abstract string TimeOfDayTypeName { get; }
internal abstract string XmlConvertClassName { get; }
internal abstract string EnumTypeName { get; }