File: ClientApiGenerator.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (567 lines) | stat: -rw-r--r-- 21,464 bytes parent folder | download
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
//---------------------------------------------------------------------
// <copyright file="ClientApiGenerator.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//
// @owner       [....]
// @backupOwner [....]
//---------------------------------------------------------------------

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.EntityModel.Emitters;
using SOM = System.Data.EntityModel.SchemaObjectModel;
using System.Diagnostics;
using System.Data.Metadata.Edm;
using System.Data.Entity.Design;
using System.IO;
using System.Data.EntityModel.SchemaObjectModel;
using System.Data.Entity.Design.SsdlGenerator;
using System.Linq;
using System.Data.Entity.Design.Common;
using System.Runtime.Versioning;

namespace System.Data.EntityModel
{
    /// <summary>
    /// Summary description for ClientApiGenerator.
    /// </summary>
    internal sealed class ClientApiGenerator
    {
        #region Instance Fields
        private string _codeNamespace = null;
        private CodeCompileUnit _compileUnit = null;
        private bool _isLanguageCaseSensitive = true;

        private EdmItemCollection _edmItemCollection = null;
        private Schema _sourceSchema = null;
        private FixUpCollection _fixUps = null;
        private AttributeEmitter _attributeEmitter = null;
        EntityClassGenerator _generator;
        List<EdmSchemaError> _errors;
        TypeReference _typeReference = new TypeReference();

        #endregion

        #region Public Methods
        public ClientApiGenerator(Schema sourceSchema, EdmItemCollection edmItemCollection, EntityClassGenerator generator, List<EdmSchemaError> errors)
        {
            Debug.Assert(sourceSchema != null, "sourceSchema is null");
            Debug.Assert(edmItemCollection != null, "edmItemCollection is null");
            Debug.Assert(generator != null, "generator is null");
            Debug.Assert(errors != null, "errors is null");

            _edmItemCollection = edmItemCollection;
            _sourceSchema = sourceSchema;
            _generator = generator;
            _errors = errors;
            _attributeEmitter = new AttributeEmitter(_typeReference);
        }

        /// <summary>
        /// Parses a source Schema and outputs client-side generated code to
        /// the output TextWriter.
        /// </summary>
        /// <param name="schema">The source Schema</param>
        /// <param name="output">The TextWriter in which to write the output</param>
        /// <param name="outputUri">The Uri for the output. Can be null.</param>
        /// <returns>A list of GeneratorErrors.</returns>
        [ResourceExposure(ResourceScope.None)] //No resource is exposed.
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] //For Path.GetTempPath method. 
                                                                            //We use tha path to create a temp file stream which is consistent with the resource consumption of machine.

        internal void GenerateCode(LazyTextWriterCreator target, string targetLocation)
        {
            Debug.Assert(target != null, "target parameter is null");

            IndentedTextWriter indentedTextWriter = null;
            System.IO.Stream tempFileStream = null;
            System.IO.StreamReader reader = null;
            System.IO.StreamWriter writer = null;
            TempFileCollection tempFiles = null;
            try
            {
                CodeDomProvider provider = null;
                switch (Language)
                {
                    case LanguageOption.GenerateCSharpCode:
                        provider = new Microsoft.CSharp.CSharpCodeProvider();
                        break;

                    case LanguageOption.GenerateVBCode:
                        provider = new Microsoft.VisualBasic.VBCodeProvider();
                        break;
                }

                _isLanguageCaseSensitive = (provider.LanguageOptions & LanguageOptions.CaseInsensitive) == 0;

                new NamespaceEmitter(this, _codeNamespace, target.TargetFilePath).Emit();

                // if there were errors we don't need the output file
                if (RealErrorsExist)
                {
                    return;
                }

                if (FixUps.Count == 0 || !FixUpCollection.IsLanguageSupported(Language))
                {
                    indentedTextWriter = new IndentedTextWriter(target.GetOrCreateTextWriter(), "\t");
                }
                else
                {
                    // need to write to a temporary file so we can do fixups...
                    tempFiles = new TempFileCollection(Path.GetTempPath());
                    string filename = Path.Combine(tempFiles.TempDir, "EdmCodeGenFixup-" + Guid.NewGuid().ToString() + ".tmp");
                    tempFiles.AddFile(filename, false);
                    tempFileStream = new System.IO.FileStream(filename, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite,
                        System.IO.FileShare.None);
                    indentedTextWriter = new IndentedTextWriter(new System.IO.StreamWriter(tempFileStream), "\t");
                }

                CodeGeneratorOptions styleOptions = new CodeGeneratorOptions();
                styleOptions.BracingStyle = "C";
                styleOptions.BlankLinesBetweenMembers = false;
                styleOptions.VerbatimOrder = true;
                provider.GenerateCodeFromCompileUnit(CompileUnit, indentedTextWriter, styleOptions);

                // if we wrote to a temp file need to post process the file...
                if (tempFileStream != null)
                {
                    indentedTextWriter.Flush();
                    tempFileStream.Seek(0, System.IO.SeekOrigin.Begin);
                    reader = new System.IO.StreamReader(tempFileStream);
                    FixUps.Do(reader, target.GetOrCreateTextWriter(), Language, SourceObjectNamespaceName != string.Empty);
                }
            }
            catch (System.UnauthorizedAccessException ex)
            {
                AddError(ModelBuilderErrorCode.SecurityError, EdmSchemaErrorSeverity.Error, ex);
            }
            catch (System.IO.FileNotFoundException ex)
            {
                AddError(ModelBuilderErrorCode.FileNotFound, EdmSchemaErrorSeverity.Error, ex);
            }
            catch (System.Security.SecurityException ex)
            {
                AddError(ModelBuilderErrorCode.SecurityError, EdmSchemaErrorSeverity.Error, ex);
            }
            catch (System.IO.DirectoryNotFoundException ex)
            {
                AddError(ModelBuilderErrorCode.DirectoryNotFound, EdmSchemaErrorSeverity.Error, ex);
            }
            catch (System.IO.IOException ex)
            {
                AddError(ModelBuilderErrorCode.IOException, EdmSchemaErrorSeverity.Error, ex);
            }
            finally
            {
                if (indentedTextWriter != null)
                {
                    indentedTextWriter.Close();
                }
                if (tempFileStream != null)
                {
                    tempFileStream.Close();
                }
                if (tempFiles != null)
                {
                    tempFiles.Delete();
                    ((IDisposable)tempFiles).Dispose();
                }
                if (reader != null)
                {
                    reader.Close();
                }
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }

        /// <summary>
        /// Verification code invoked for types
        /// </summary>
        /// <param name="item">The type being generated</param>
        internal void VerifyLanguageCaseSensitiveCompatibilityForType(GlobalItem item)
        {
            if (_isLanguageCaseSensitive)
            {
                return; // no validation necessary
            }

            try
            {
                _edmItemCollection.GetItem<GlobalItem>(
                                                        item.Identity,
                                                        true   // ignore case
                                                    );
            }
            catch (InvalidOperationException)
            {
                AddError(Strings.ItemExistsWithDifferentCase(item.BuiltInTypeKind.ToString(), item.Identity), ModelBuilderErrorCode.IncompatibleSettingForCaseSensitiveOption,
                    EdmSchemaErrorSeverity.Error, item.Identity);
            }
        }


        /// <summary>
        /// Verification code invoked for properties
        /// </summary>
        /// <param name="item">The property or navigation property being generated</param>
        internal void VerifyLanguageCaseSensitiveCompatibilityForProperty(EdmMember item)
        {
            if (_isLanguageCaseSensitive)
            {
                return; // no validation necessary
            }

            Debug.Assert(item != null);

            ReadOnlyMetadataCollection<EdmMember> members = item.DeclaringType.Members;
            
            HashSet<string> set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (EdmMember member in members)
            {
                if (set.Contains(member.Identity) &&
                    item.Identity.Equals(member.Identity, StringComparison.OrdinalIgnoreCase))
                {
                    AddError(Strings.PropertyExistsWithDifferentCase(item.Identity), ModelBuilderErrorCode.IncompatibleSettingForCaseSensitiveOption,
                    EdmSchemaErrorSeverity.Error, item.DeclaringType.FullName, item.Identity);
                }
                else
                {
                    set.Add(member.Identity);
                }
            }
        }

        /// <summary>
        /// Verification code invoked for entity sets
        /// </summary>
        /// <param name="item">The entity container being generated</param>
        internal void VerifyLanguageCaseSensitiveCompatibilityForEntitySet(System.Data.Metadata.Edm.EntityContainer item)
        {
            if (_isLanguageCaseSensitive)
            {
                return; // no validation necessary
            }

            Debug.Assert(item != null);

            HashSet<string> set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (EntitySetBase entitySetBase in item.BaseEntitySets)
            {
                if (MetadataUtil.IsEntitySet(entitySetBase))
                {
                    EntitySet entitySet = (EntitySet)entitySetBase;
                    if (set.Contains(entitySet.Identity))
                    {
                        AddError(ModelBuilderErrorCode.IncompatibleSettingForCaseSensitiveOption,
                        EdmSchemaErrorSeverity.Error, new InvalidOperationException(Strings.EntitySetExistsWithDifferentCase(entitySet.Identity)),
                        item.Name);
                    }
                    else
                    {
                        set.Add(entitySet.Identity);
                    }
                }
            }
        }

        internal IEnumerable<EdmType> GetDirectSubTypes(EdmType edmType)
        {
            return _edmItemCollection.GetItems<EdmType>().Where(b => b.BaseType == edmType);
        }

        private static System.Data.EntityModel.SchemaObjectModel.SchemaElement GetSchemaElement(
            System.Data.EntityModel.SchemaObjectModel.Schema schema, string itemIdentity)
        {
            List<System.Data.EntityModel.SchemaObjectModel.SchemaType> schemaTypes =
                           schema.SchemaTypes.Where(p => p.Identity == itemIdentity).ToList();
            if (null != schemaTypes && schemaTypes.Count > 0)
            {
                return (System.Data.EntityModel.SchemaObjectModel.SchemaElement)schemaTypes.First();
            }
            else
            {
                return null;
            }

        }

        internal static void GetElementLocationInfo(System.Data.EntityModel.SchemaObjectModel.Schema schema, string itemIdentity, out int lineNumber, out int linePosition)
        {
            System.Data.EntityModel.SchemaObjectModel.SchemaElement element = GetSchemaElement(schema, itemIdentity);

            if(null != element)
            {
                lineNumber = element.LineNumber;
                linePosition = element.LinePosition;
            }
            else
            {
                lineNumber = linePosition = -1;
            }
        }

        internal static void GetElementLocationInfo(System.Data.EntityModel.SchemaObjectModel.Schema schema, string parentIdentity, string itemIdentity, out int lineNumber, out int linePosition)
        {
            lineNumber = linePosition = -1;

            System.Data.EntityModel.SchemaObjectModel.SchemaElement element = GetSchemaElement(schema, parentIdentity);
            System.Data.EntityModel.SchemaObjectModel.StructuredType elementWithProperty = 
                element as System.Data.EntityModel.SchemaObjectModel.StructuredType;

            if (null != elementWithProperty && elementWithProperty.Properties.ContainsKey(itemIdentity))
            {
                    lineNumber = elementWithProperty.Properties[itemIdentity].LineNumber;
                    linePosition = elementWithProperty.Properties[itemIdentity].LinePosition;
            }
            else if( null != element)
            {
                lineNumber = element.LineNumber;
                linePosition = element.LinePosition;
            }
        }

        #endregion

        #region Internal Properties

        internal LanguageOption Language
        {
            get
            {
                return _generator.LanguageOption;
            }
        }

        internal TypeReference TypeReference
        {
            get { return _typeReference; }
        }

        internal CodeCompileUnit CompileUnit
        {
            get
            {
                if (_compileUnit == null)
                    _compileUnit = new CodeCompileUnit();

                return _compileUnit;
            }
        }

        public void AddError(string message, ModelBuilderErrorCode errorCode, EdmSchemaErrorSeverity severity)
        {
            _errors.Add(new EdmSchemaError(message, (int)errorCode, severity));
        }

        public void AddError(ModelBuilderErrorCode errorCode, EdmSchemaErrorSeverity severity, Exception ex)
        {
            _errors.Add(new EdmSchemaError(ex.Message, (int)errorCode, severity, ex));
        }

        internal void AddError(string message, ModelBuilderErrorCode errorCode, EdmSchemaErrorSeverity severity, Exception ex)
        {
            _errors.Add(new EdmSchemaError(message, (int)errorCode, severity, ex));
        }

        internal void AddError(ModelBuilderErrorCode errorCode, EdmSchemaErrorSeverity severity, Exception ex, string itemIdentity)
        {
            int lineNumber, linePosition;
            ClientApiGenerator.GetElementLocationInfo(this._sourceSchema, itemIdentity, out lineNumber, out linePosition);

            _errors.Add(new EdmSchemaError(ex.Message, (int)errorCode, severity, this._sourceSchema.Location, lineNumber, linePosition, ex));
        }

        internal void AddError(string message, ModelBuilderErrorCode errorCode, EdmSchemaErrorSeverity severity, string itemIdentity)
        {
            int lineNumber, linePosition;
            ClientApiGenerator.GetElementLocationInfo(this._sourceSchema, itemIdentity, out lineNumber, out linePosition);

            _errors.Add(new EdmSchemaError(message, (int)errorCode, severity, this._sourceSchema.Location, lineNumber, linePosition));
        }

        internal void AddError(string message, ModelBuilderErrorCode errorCode, EdmSchemaErrorSeverity severity, string parentIdentity, string itemIdentity)
        {
            int lineNumber, linePosition;
            ClientApiGenerator.GetElementLocationInfo(this._sourceSchema, parentIdentity, itemIdentity, out lineNumber, out linePosition);

            _errors.Add(new EdmSchemaError(message, (int)errorCode, severity, this._sourceSchema.Location, lineNumber, linePosition));
        }

        /// <summary>
        /// Check collection for any real errors (Severity != Warning)
        /// </summary>
        public bool RealErrorsExist
        {
            get
            {
                foreach (EdmSchemaError error in _errors)
                {
                    if (error.Severity != EdmSchemaErrorSeverity.Warning)
                        return true;
                }
                return false;
            }
        }

        public IEnumerable<GlobalItem> GetSourceTypes()
        {
            foreach (SOM.SchemaType type in _sourceSchema.SchemaTypes)
            {
                if (type is SOM.ModelFunction)
                {
                    continue;
                }

                yield return _edmItemCollection.GetItem<GlobalItem>(type.Identity);
            }
        }

        public CodeTypeReference GetFullyQualifiedTypeReference(EdmType type)
        {
            string fullObjectName = CreateFullName(GetObjectNamespace(type.NamespaceName), type.Name);
            return TypeReference.FromString(fullObjectName);
        }

        public CodeTypeReference GetFullyQualifiedTypeReference(EdmType type, bool addGlobalQualifier)
        {
            string fullObjectName = CreateFullName(GetObjectNamespace(type.NamespaceName), type.Name);
            return TypeReference.FromString(fullObjectName, addGlobalQualifier);
        }

        private string CreateFullName(string namespaceName, string name)
        {
            if (string.IsNullOrEmpty(namespaceName))
            {
                return name;
            }

            return namespaceName + "." + name;
        }

        public CodeTypeReference GetLeastPossibleQualifiedTypeReference(EdmType type)
        {
            string typeRef;

            if (type.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType)
            {
                return type.ClrType.IsValueType ? TypeReference.NullableForType(type.ClrType) : TypeReference.ForType(type.ClrType);
            }
            else
            {
                if (type.NamespaceName == SourceEdmNamespaceName)
                {
                    // we are already generating in this namespace, no need to qualify it
                    typeRef = type.Name;
                }
                else
                {
                    typeRef = CreateFullName(GetObjectNamespace(type.NamespaceName), type.Name);
                }
            }

            return TypeReference.FromString(typeRef);
        }

        public string SourceEdmNamespaceName
        {
            get
            {
                return _sourceSchema.Namespace;
            }
        }

        public string SourceObjectNamespaceName
        {
            get
            {
                return GetObjectNamespace(SourceEdmNamespaceName);
            }
        }

        private string GetObjectNamespace(string csdlNamespaceName)
        {
            Debug.Assert(csdlNamespaceName != null, "csdlNamespaceName is null");

            string objectNamespace;
            if (_generator.EdmToObjectNamespaceMap.TryGetObjectNamespace(csdlNamespaceName, out objectNamespace))
            {
                return objectNamespace;
            }

            return csdlNamespaceName;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <value></value>
        internal FixUpCollection FixUps
        {
            get
            {
                if (_fixUps == null)
                    _fixUps = new FixUpCollection();

                return _fixUps;
            }
        }

        internal AttributeEmitter AttributeEmitter
        {
            get { return _attributeEmitter; }
        }

        internal bool IsLanguageCaseSensitive
        {
            get { return _isLanguageCaseSensitive; }
        }

        internal StringComparison LanguageAppropriateStringComparer
        {
            get
            {
                if (IsLanguageCaseSensitive)
                {
                    return StringComparison.Ordinal;
                }
                else
                {
                    return StringComparison.OrdinalIgnoreCase;
                }
            }
        }

        /// <summary>
        /// Helper method that raises the TypeGenerated event
        /// </summary>
        /// <param name="eventArgs">The event arguments passed to the subscriber</param>
        internal void RaiseTypeGeneratedEvent(TypeGeneratedEventArgs eventArgs)
        {
            _generator.RaiseTypeGeneratedEvent(eventArgs);
        }

        /// <summary>
        /// Helper method that raises the PropertyGenerated event
        /// </summary>
        /// <param name="eventArgs">The event arguments passed to the subscriber</param>
        internal void RaisePropertyGeneratedEvent(PropertyGeneratedEventArgs eventArgs)
        {
            _generator.RaisePropertyGeneratedEvent(eventArgs);
        }

        #endregion

    }
}