Example #1
0
        private void DisallowReturnTypeChange(CodeTypeReference baseType, CodeTypeReference newType)
        {
            if (Helper.IsCollectionType(Item.TypeUsage.EdmType) && GetCollectionKind(Item.TypeUsage) != CollectionKind.None)
            {
                if (newType == null)
                {
                    throw EDesignUtil.InvalidOperation(Strings.CannotChangePropertyReturnTypeToNull(Item.Name, Item.DeclaringType.Name));
                }

                // you can change the return type of collection properties
                // we don't even need to check
                return;
            }


            if (!(baseType == null && newType == null) &&
                (
                    (baseType != null && !baseType.Equals(newType)) ||
                    (newType != null && !newType.Equals(baseType))
                )
                )
            {
                throw EDesignUtil.InvalidOperation(Strings.CannotChangePropertyReturnType(Item.Name, Item.DeclaringType.Name));
            }
        }
Example #2
0
        [ResourceConsumption(ResourceScope.Machine)] //Temp file creation, and passing to InternalGenerateCode
        public IList <EdmSchemaError> GenerateCode(XmlReader sourceEdmSchema, TextWriter target, IEnumerable <XmlReader> additionalEdmSchemas, Version targetEntityFrameworkVersion)
        {
            EDesignUtil.CheckArgumentNull(sourceEdmSchema, "sourceEdmSchema");
            EDesignUtil.CheckArgumentNull(additionalEdmSchemas, "additionalEdmSchemas");
            EDesignUtil.CheckArgumentNull(target, "target");
            EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion");

            Version schemaVersion;

            if (!IsValidSchema(sourceEdmSchema, out schemaVersion))
            {
                return(new List <EdmSchemaError>()
                {
                    CreateSourceEdmSchemaNotValidError()
                });
            }

            using (TempFileCollection collection = new TempFileCollection())
            {
                string tempSourceEdmSchemaPath = collection.AddExtension(XmlConstants.CSpaceSchemaExtension);
                SaveXmlReaderToFile(sourceEdmSchema, tempSourceEdmSchemaPath);
                List <string> additionalTempPaths = new List <string>();
                foreach (XmlReader reader in additionalEdmSchemas)
                {
                    string temp = Path.GetTempFileName() + XmlConstants.CSpaceSchemaExtension;
                    SaveXmlReaderToFile(reader, temp);
                    additionalTempPaths.Add(temp);
                    collection.AddFile(temp, false);
                }
                return(InternalGenerateCode(tempSourceEdmSchemaPath, schemaVersion, new LazyTextWriterCreator(target), additionalTempPaths, targetEntityFrameworkVersion));
            }
        }
        /// <summary>
        /// Returns the stream of the XSD corresponding to the frameworkVersion, and dataSpace passed in.
        /// </summary>
        /// <param name="entityFrameworkVersion">The version of the EntityFramework that you want the Schema XSD for.</param>
        /// <param name="dataSpace">The data space of the schem XSD that you want.</param>
        /// <returns>Stream version of the XSD</returns>
        public static Stream GetSchemaXsd(Version entityFrameworkVersion, DataSpace dataSpace)
        {
            EDesignUtil.CheckTargetEntityFrameworkVersionArgument(entityFrameworkVersion, "entityFrameworkVersion");

            string resourceName = null;

            switch (dataSpace)
            {
            case DataSpace.CSpace:
                resourceName = GetEdmSchemaXsdResourceName(entityFrameworkVersion);
                break;

            case DataSpace.CSSpace:
                resourceName = GetMappingSchemaXsdResourceName(entityFrameworkVersion);
                break;

            case DataSpace.SSpace:
                resourceName = GetStoreSchemaXsdResourceName(entityFrameworkVersion);
                break;

            default:
                throw EDesignUtil.Argument("dataSpace");
            }

            Debug.Assert(!string.IsNullOrEmpty(resourceName), "Did you forget to map something new?");

            Assembly dataEntity = typeof(EdmItemCollection).Assembly;

            return(dataEntity.GetManifestResourceStream(resourceName));
        }
Example #4
0
        public override bool IsSingular(string word)
        {
            EDesignUtil.CheckArgumentNull <string>(word, "word");

            if (this._userDictionary.ExistsInFirst(word))
            {
                return(true);
            }
            if (this._userDictionary.ExistsInSecond(word))
            {
                return(false);
            }

            if (this.IsUninflective(word) || this._knownSingluarWords.Contains(word.ToLower(this.Culture)))
            {
                return(true);
            }
            else if (!IsNoOpWord(word) && this.Singularize(word).Equals(word))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #5
0
        public void Add(string edmNamespace, string objectNamespace)
        {
            EDesignUtil.CheckStringArgument(edmNamespace, "edmNamespace");
            EDesignUtil.CheckArgumentNull(objectNamespace, "objectNamespace");

            _map.Add(edmNamespace, objectNamespace);
        }
 /// <summary>
 /// Create an StoreItemCollection with the passed in parameters.
 /// Add any errors caused during the ItemCollection creation
 /// to the error list passed in.
 /// </summary>
 /// <param name="connection"></param>
 /// <param name="readers"></param>
 /// <param name="targetEntityFrameworkVersion"></param>
 /// <param name="errors"></param>
 /// <returns></returns>
 public static StoreItemCollection CreateStoreItemCollection(
     IEnumerable <XmlReader> readers,
     Version targetEntityFrameworkVersion,
     out IList <EdmSchemaError> errors)
 {
     EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion");
     return(CreateStoreItemCollection(readers, out errors));
 }
Example #7
0
        [ResourceConsumption(ResourceScope.Machine)] // for InternalGenerateCode method call. But the path is not created in this method.
        public IList <EdmSchemaError> GenerateCode(string sourceEdmSchemaFilePath, string targetPath, Version targetEntityFrameworkVersion)
        {
            EntityUtil.CheckStringArgument(sourceEdmSchemaFilePath, "sourceEdmSchemaFilePath");
            EntityUtil.CheckStringArgument(targetPath, "targetPath");
            EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion");

            return(InternalGenerateCode(sourceEdmSchemaFilePath, new LazyTextWriterCreator(targetPath), null, targetEntityFrameworkVersion));
        }
Example #8
0
        public IList <EdmSchemaError> GenerateViews(StorageMappingItemCollection mappingCollection, TextWriter outputWriter)
        {
            EDesignUtil.CheckArgumentNull(mappingCollection, "mappingCollection");

            Version targetEntityFrameworkVersion;
            IList <EdmSchemaError> errorList = GetMinimumTargetFrameworkVersion(mappingCollection, out targetEntityFrameworkVersion);

            return(GenerateViews(mappingCollection, outputWriter, targetEntityFrameworkVersion).Concat(errorList).ToList());
        }
Example #9
0
        public static IList <EdmSchemaError> Validate(StorageMappingItemCollection mappingCollection)
        {
            EDesignUtil.CheckArgumentNull(mappingCollection, "mappingCollection");

            Version targetEntityFrameworkVersion;
            IList <EdmSchemaError> errorList = GetMinimumTargetFrameworkVersion(mappingCollection, out targetEntityFrameworkVersion);

            return(Validate(mappingCollection, targetEntityFrameworkVersion).Concat(errorList).ToList());
        }
Example #10
0
        public IList <EdmSchemaError> GenerateViews(StorageMappingItemCollection mappingCollection, TextWriter outputWriter, Version targetEntityFrameworkVersion)
        {
            EDesignUtil.CheckArgumentNull(mappingCollection, "mappingCollection");
            EDesignUtil.CheckArgumentNull(outputWriter, "outputWriter");

            EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion");
            CheckForCompatibleSchemaAndTarget(mappingCollection, targetEntityFrameworkVersion);

            TextWriter writer;

            return(InternalGenerateViews(mappingCollection, () => outputWriter, out writer));
        }
 /// <summary>
 /// Creates a EntityStoreSchemaFilterEntry
 /// </summary>
 /// <param name="catalog">The pattern to use to select the appropriate catalog or null to not limit by catalog.</param>
 /// <param name="schema">The pattern to use to select the appropriate schema or null to not limit by schema.</param>
 /// <param name="name">The pattern to use to select the appropriate name or null to not limit by name.</param>
 /// <param name="types">The type of objects to apply this filter to.</param>
 /// <param name="effect">The effect that this filter should have on the results.</param>
 public EntityStoreSchemaFilterEntry(string catalog, string schema, string name, EntityStoreSchemaFilterObjectTypes types, EntityStoreSchemaFilterEffect effect)
 {
     if (types == EntityStoreSchemaFilterObjectTypes.None)
     {
         throw EDesignUtil.Argument("types");
     }
     _catalog = catalog;
     _schema  = schema;
     _name    = name;
     _types   = types;
     _effect  = effect;
 }
Example #12
0
        /// <summary>
        /// Factory method for PluralizationService. Only support english pluralization.
        /// Please set the PluralizationService on the System.Data.Entity.Design.EntityModelSchemaGenerator
        /// to extend the service to other locales.
        /// </summary>
        /// <param name="culture">CultureInfo</param>
        /// <returns>PluralizationService</returns>
        public static PluralizationService CreateService(CultureInfo culture)
        {
            EDesignUtil.CheckArgumentNull <CultureInfo>(culture, "culture");

            if (culture.TwoLetterISOLanguageName == "en")
            {
                return(new EnglishPluralizationService());
            }
            else
            {
                throw new NotImplementedException(Strings.UnsupportedLocaleForPluralizationServices(culture.DisplayName));
            }
        }
Example #13
0
 private bool IsUninflective(string word)
 {
     EDesignUtil.CheckArgumentNull <string>(word, "word");
     if (PluralizationServiceUtil.DoesWordContainSuffix(word, _uninflectiveSuffixList, this.Culture) ||
         (!word.ToLower(this.Culture).Equals(word) && word.EndsWith("ese", false, this.Culture)) ||
         this._uninflectiveWordList.Contains(word.ToLowerInvariant()))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Example #14
0
        private static Type CreateCodeGeneratorType(System.CodeDom.Compiler.CodeDomProvider compilerProvider, string resourceName, string typeName)
        {
            string sourceCode = null;

            using (Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
                using (StreamReader reader = new StreamReader(sourceStream))
                {
                    sourceCode = reader.ReadToEnd();
                }

            CompilerParameters compilerParams = new CompilerParameters();

            compilerParams.CompilerOptions    = "/d:PREPROCESSED_TEMPLATE";
            compilerParams.GenerateInMemory   = true;
            compilerParams.GenerateExecutable = false;
            // grab the assemblies by location so that we don't compile against one that we didn't reference
            compilerParams.ReferencedAssemblies.AddRange(new string[] {
                typeof(System.CodeDom.Compiler.CodeDomProvider).Assembly.Location,                      // System.dll
                typeof(System.Linq.Enumerable).Assembly.Location,                                       // System.Core.dll
                typeof(System.Data.Objects.ObjectContext).Assembly.Location,                            // System.Data.Entity.dll
                typeof(System.Data.Entity.Design.EntityCodeGenerator).Assembly.Location,                // System.Data.Entity.Design.dll
                typeof(System.Data.DbType).Assembly.Location,                                           // System.Data.dll
                typeof(System.Xml.XmlAttribute).Assembly.Location,                                      // System.Xml.dll
                typeof(System.Xml.Linq.XElement).Assembly.Location,                                     // System.Xml.Linq.dll
            });

#if !ENABLE_TEMPLATE_DEBUGGING
            CompilerResults results = compilerProvider.CompileAssemblyFromSource(compilerParams, sourceCode);
#else
            // enables debugging
            compilerParams.GenerateInMemory        = false;
            compilerParams.IncludeDebugInformation = true;
            string baseName = Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".";
            compilerParams.OutputAssembly = Path.Combine(Path.GetTempPath(), baseName + typeName + ".Assembly.dll");
            string sourceFileName = Path.Combine(Path.GetTempPath(), baseName + typeName + ".Source." + compilerProvider.FileExtension);
            File.WriteAllText(sourceFileName, sourceCode);
            CompilerResults results = compilerProvider.CompileAssemblyFromFile(compilerParams, sourceFileName);
#warning DO NOT CHECK IN LIKE THIS, Dynamic Assembly Debugging is enabled
#endif


            if (results.Errors.HasErrors)
            {
                string message = results.Errors.OfType <CompilerError>().Aggregate(string.Empty, (accumulated, input) => accumulated == string.Empty ? input.ToString() : accumulated + Environment.NewLine + input.ToString());
                throw EDesignUtil.InvalidOperation(message);
            }

            return(results.CompiledAssembly.GetType(typeName));
        }
        public static EdmItemCollection CreateEdmItemCollection(IEnumerable <XmlReader> readers,
                                                                Version targetEntityFrameworkVersion,
                                                                out IList <EdmSchemaError> errors)
        {
            EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion");

            EdmItemCollection edmItemCollection = CreateEdmItemCollection(readers, out errors);

            if (!errors.Any(e => e.Severity == EdmSchemaErrorSeverity.Error))
            {
                ValidateActualVersionAgainstTarget(targetEntityFrameworkVersion, EntityFrameworkVersionsUtil.ConvertToVersion(edmItemCollection.EdmVersion), errors);
            }

            return(edmItemCollection);
        }
Example #16
0
        private static void CheckForCompatibleSchemaAndTarget(StorageMappingItemCollection mappingCollection, Version targetEntityFrameworkVersion)
        {
            Version mappingVersion = EntityFrameworkVersionsUtil.ConvertToVersion(mappingCollection.MappingVersion);

            if (targetEntityFrameworkVersion < mappingVersion)
            {
                throw EDesignUtil.Argument(Strings.TargetVersionSchemaVersionMismatch(targetEntityFrameworkVersion, mappingVersion), null);
            }

            Version edmVersion = EntityFrameworkVersionsUtil.ConvertToVersion(mappingCollection.EdmItemCollection.EdmVersion);

            if (targetEntityFrameworkVersion < edmVersion)
            {
                throw EDesignUtil.Argument(Strings.TargetVersionSchemaVersionMismatch(targetEntityFrameworkVersion, edmVersion), null);
            }
        }
Example #17
0
        /// <summary>
        /// This method allow you to add word to internal PluralizationService of English.
        /// If the singluar or the plural value was already added by this method, then an ArgumentException will be thrown.
        /// </summary>
        /// <param name="singular"></param>
        /// <param name="plural"></param>
        public void AddWord(string singular, string plural)
        {
            EDesignUtil.CheckArgumentNull <string>(singular, "singular");
            EDesignUtil.CheckArgumentNull <string>(plural, "plural");

            if (this._userDictionary.ExistsInSecond(plural))
            {
                throw new ArgumentException(Strings.DuplicateEntryInUserDictionary("plural", plural), "plural");
            }
            else if (this._userDictionary.ExistsInFirst(singular))
            {
                throw new ArgumentException(Strings.DuplicateEntryInUserDictionary("singular", singular), "singular");
            }
            else
            {
                this._userDictionary.AddValue(singular, plural);
            }
        }
Example #18
0
        public IList <EdmSchemaError> GenerateViews(StorageMappingItemCollection mappingCollection, string outputPath)
        {
            EDesignUtil.CheckArgumentNull(mappingCollection, "mappingCollection");
            EDesignUtil.CheckStringArgument(outputPath, "outputPath");

            TextWriter outputWriter = null;

            try
            {
                return(InternalGenerateViews(mappingCollection, () => new StreamWriter(outputPath), out outputWriter));
            }
            finally
            {
                if (outputWriter != null)
                {
                    outputWriter.Dispose();
                }
            }
        }
Example #19
0
        public static IList <EdmSchemaError> Validate(StorageMappingItemCollection mappingCollection, Version targetEntityFrameworkVersion)
        {
            EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion");
            CheckForCompatibleSchemaAndTarget(mappingCollection, targetEntityFrameworkVersion);

            // purpose of this API is to validate the mappingCollection, it basically will call GetEntitySetViews

            EDesignUtil.CheckArgumentNull(mappingCollection, "mappingCollection");

            // we need a temp var to to pass it to GetViews (since we will directly invoke GetViews)
            Dictionary <EntitySetBase, string> generatedViews;
            // mappingCollection will be validated and schemaErrors will be returned from GetViews API
            IList <EdmSchemaError> schemaErrors;

            // Validate entity set views.
            GetEntitySetViews(mappingCollection, out schemaErrors, out generatedViews);

            // Validate function imports and their mapping.
            foreach (var containerMapping in mappingCollection.GetItems <StorageEntityContainerMapping>())
            {
                foreach (var functionImport in containerMapping.EdmEntityContainer.FunctionImports)
                {
                    FunctionImportMapping functionImportMapping;
                    if (containerMapping.TryGetFunctionImportMapping(functionImport, out functionImportMapping))
                    {
                        if (functionImport.IsComposableAttribute)
                        {
                            ((FunctionImportMappingComposable)functionImportMapping).ValidateFunctionView(schemaErrors);
                        }
                    }
                    else
                    {
                        schemaErrors.Add(new EdmSchemaError(
                                             Strings.UnmappedFunctionImport(functionImport.Identity),
                                             (int)StorageMappingErrorCode.UnmappedFunctionImport,
                                             EdmSchemaErrorSeverity.Warning));
                    }
                }
            }

            Debug.Assert(schemaErrors != null, "schemaErrors is null");
            return(HandleValidationErrors(schemaErrors));
        }
Example #20
0
        [ResourceConsumption(ResourceScope.Machine)] // temp file creation, and passing to InternalGenerateCode
        public IList <EdmSchemaError> GenerateCode(XmlReader sourceEdmSchema, TextWriter target, Version targetEntityFrameworkVersion)
        {
            EDesignUtil.CheckArgumentNull(sourceEdmSchema, "sourceEdmSchema");
            EDesignUtil.CheckArgumentNull(target, "target");
            EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion");

            Version schemaVersion;

            if (!IsValidSchema(sourceEdmSchema, out schemaVersion))
            {
                return(new List <EdmSchemaError>()
                {
                    CreateSourceEdmSchemaNotValidError()
                });
            }

            using (TempFileCollection collection = new TempFileCollection())
            {
                string tempSourceEdmSchemaPath = collection.AddExtension(XmlConstants.CSpaceSchemaExtension);
                SaveXmlReaderToFile(sourceEdmSchema, tempSourceEdmSchemaPath);

                return(InternalGenerateCode(tempSourceEdmSchemaPath, schemaVersion, new LazyTextWriterCreator(target), null, targetEntityFrameworkVersion));
            }
        }
        public static StorageMappingItemCollection CreateStorageMappingItemCollection(
            EdmItemCollection edmCollection,
            StoreItemCollection storeCollection,
            IEnumerable <XmlReader> readers,
            Version targetEntityFrameworkVersion,
            out IList <EdmSchemaError> errors)
        {
            EDesignUtil.CheckArgumentNull(edmCollection, "edmCollection");
            EDesignUtil.CheckArgumentNull(storeCollection, "storeCollection");
            EDesignUtil.CheckArgumentNull(readers, "readers");
            EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion");
            if (EntityFrameworkVersionsUtil.ConvertToVersion(edmCollection.EdmVersion) > targetEntityFrameworkVersion)
            {
                throw EDesignUtil.Argument("edmCollection");
            }

            StorageMappingItemCollection storageMappingItemCollection = CreateStorageMappingItemCollection(edmCollection, storeCollection, readers, out errors);

            if (!errors.Any(e => e.Severity == EdmSchemaErrorSeverity.Error))
            {
                ValidateActualVersionAgainstTarget(targetEntityFrameworkVersion, EntityFrameworkVersionsUtil.ConvertToVersion(storageMappingItemCollection.MappingVersion), errors);
            }
            return(storageMappingItemCollection);
        }
Example #22
0
 static internal void CheckStringArgument(string value, string parameterName)
 {
     EDesignUtil.CheckStringArgument(value, parameterName);
 }
Example #23
0
        private CodeMemberProperty CreateEntitySetProperty(EntitySet set)
        {
            Debug.Assert(set != null, "Property is Null");

            // trying to get
            //
            // [System.ComponentModel.Browsable(false)]
            // public ObjectQuery<Customer> Customers
            // {
            //      get
            //      {
            //          if ((this._Customers == null))
            //          {
            //              this._Customers = base.CreateQuery<Customer>("[Customers]");
            //          }
            //          return this._Customers;
            //      }
            // }
            //
            CodeMemberProperty codeProperty = new CodeMemberProperty();

            Generator.AttributeEmitter.EmitGeneratedCodeAttribute(codeProperty);
            codeProperty.Attributes = MemberAttributes.Final | GetEntitySetPropertyAccessibility(set);
            codeProperty.Name       = set.Name;
            codeProperty.HasGet     = true;
            codeProperty.HasSet     = false;

            // Determine type to use for field/property and name of factory method on ObjectContext
            string typeName         = "ObjectQuery";
            string createMethodName = "CreateQuery";
            // When the EntitySet name is used as CommandText, it should be quoted
            string createMethodArgument = "[" + set.Name + "]";

            CodeTypeReference genericParameter = Generator.GetLeastPossibleQualifiedTypeReference(set.ElementType);

            codeProperty.Type = TypeReference.AdoFrameworkGenericClass(typeName, genericParameter);
            string fieldName = Utils.FieldNameFromPropName(set.Name);

            // raise the PropertyGenerated event before proceeding further
            PropertyGeneratedEventArgs eventArgs = new PropertyGeneratedEventArgs(set, fieldName, codeProperty.Type);

            Generator.RaisePropertyGeneratedEvent(eventArgs);

            if (eventArgs.ReturnType == null || !eventArgs.ReturnType.Equals(codeProperty.Type))
            {
                throw EDesignUtil.InvalidOperation(Strings.CannotChangePropertyReturnType(set.Name, Item.Name));
            }

            List <CodeAttributeDeclaration> additionalAttributes = eventArgs.AdditionalAttributes;

            if (additionalAttributes != null && additionalAttributes.Count > 0)
            {
                try
                {
                    codeProperty.CustomAttributes.AddRange(additionalAttributes.ToArray());
                }
                catch (ArgumentNullException e)
                {
                    Generator.AddError(Strings.InvalidAttributeSuppliedForProperty(Item.Name),
                                       ModelBuilderErrorCode.InvalidAttributeSuppliedForProperty,
                                       EdmSchemaErrorSeverity.Error,
                                       e);
                }
            }

            // we need to insert user-specified code before other/existing code, including
            // the return statement
            List <CodeStatement> additionalGetStatements = eventArgs.AdditionalGetStatements;

            if (additionalGetStatements != null && additionalGetStatements.Count > 0)
            {
                try
                {
                    codeProperty.GetStatements.AddRange(additionalGetStatements.ToArray());
                }
                catch (ArgumentNullException e)
                {
                    Generator.AddError(Strings.InvalidGetStatementSuppliedForProperty(Item.Name),
                                       ModelBuilderErrorCode.InvalidGetStatementSuppliedForProperty,
                                       EdmSchemaErrorSeverity.Error,
                                       e);
                }
            }

            codeProperty.GetStatements.Add(
                new CodeConditionStatement(
                    EmitExpressionEqualsNull(new CodeFieldReferenceExpression(ThisRef, fieldName)),
                    new CodeAssignStatement(
                        new CodeFieldReferenceExpression(ThisRef, fieldName),
                        new CodeMethodInvokeExpression(
                            new CodeMethodReferenceExpression(
                                new CodeBaseReferenceExpression(),
                                createMethodName,
                                new CodeTypeReference[] { genericParameter }
                                ),
                            new CodePrimitiveExpression(createMethodArgument)
                            )
                        )
                    )
                );

            codeProperty.GetStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeFieldReferenceExpression(
                        ThisRef,
                        fieldName
                        )
                    )
                );

            // property summary
            CommentEmitter.EmitSummaryComments(set, codeProperty.Comments);

            return(codeProperty);
        }
Example #24
0
 static internal void CheckArgumentNull <T>(T value, string parameterName) where T : class
 {
     EDesignUtil.CheckArgumentNull <T>(value, parameterName);
 }
Example #25
0
 public EntityCodeGenerator(LanguageOption languageOption)
 {
     _languageOption = EDesignUtil.CheckLanguageOptionArgument(languageOption, "languageOption");
 }
Example #26
0
        private void GenerateCodeCommon(MetadataArtifactLoader sourceLoader,
                                        List <MetadataArtifactLoader> loaders,
                                        LazyTextWriterCreator target,
                                        string sourceEdmSchemaFilePath,
                                        string targetFilePath,
                                        bool closeReaders,
                                        List <EdmSchemaError> errors)
        {
            MetadataArtifactLoaderComposite composite = new MetadataArtifactLoaderComposite(loaders);

            // create the schema manager from the xml readers
            Dictionary <MetadataArtifactLoader, XmlReader> readerSourceMap = new Dictionary <MetadataArtifactLoader, XmlReader>();
            IList <Schema>   schemas;
            List <XmlReader> readers = composite.GetReaders(readerSourceMap);

            try
            {
                IList <EdmSchemaError> schemaManagerErrors =
                    SchemaManager.ParseAndValidate(readers,
                                                   composite.GetPaths(),
                                                   SchemaDataModelOption.EntityDataModel,
                                                   EdmProviderManifest.Instance,
                                                   out schemas);
                errors.AddRange(schemaManagerErrors);
            }
            finally
            {
                if (closeReaders)
                {
                    MetadataUtil.DisposeXmlReaders(readers);
                }
            }
            ThrowOnAnyNonWarningErrors(errors);
            Debug.Assert(readerSourceMap.ContainsKey(sourceLoader), "the source loader didn't produce any of the xml readers...");
            XmlReader sourceReader = readerSourceMap[sourceLoader];


            // use the index of the "source" xml reader as the index of the "source" schema
            Debug.Assert(readers.Contains(sourceReader), "the source reader is not in the list of readers");
            int index = readers.IndexOf(sourceReader);

            Debug.Assert(index >= 0, "couldn't find the source reader in the list of readers");

            Debug.Assert(readers.Count == schemas.Count, "We have a different number of readers than schemas");
            Schema sourceSchema = schemas[index];

            Debug.Assert(sourceSchema != null, "sourceSchema is null");

            // create the EdmItemCollection from the schemas
            EdmItemCollection itemCollection = new EdmItemCollection(schemas);

            if (EntityFrameworkVersionsUtil.ConvertToVersion(itemCollection.EdmVersion) >= EntityFrameworkVersions.Version2)
            {
                throw EDesignUtil.InvalidOperation(Strings.TargetEntityFrameworkVersionToNewForEntityClassGenerator);
            }

            // generate code
            ClientApiGenerator generator = new ClientApiGenerator(sourceSchema, itemCollection, this, errors);

            generator.GenerateCode(target, targetFilePath);
        }
Example #27
0
 public IList <EdmSchemaError> GenerateCode(XmlReader sourceEdmSchema, TextWriter target)
 {
     EDesignUtil.CheckArgumentNull(sourceEdmSchema, "sourceEdmSchema");
     EDesignUtil.CheckArgumentNull(target, "target");
     return(GenerateCode(sourceEdmSchema, target, new XmlReader[] { }));
 }
Example #28
0
        public override string Singularize(string word)
        {
            EDesignUtil.CheckArgumentNull <string>(word, "word");

            return(Capitalize(word, InternalSingularize));
        }
Example #29
0
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] //For GenerateCodeCommon method call. Since we use null as the path, we have not changed the scope of the resource.
        public IList <EdmSchemaError> GenerateCode(XmlReader sourceEdmSchema, TextWriter target, IEnumerable <XmlReader> additionalEdmSchemas)
        {
            EDesignUtil.CheckArgumentNull(sourceEdmSchema, "sourceEdmSchema");
            EDesignUtil.CheckArgumentNull(additionalEdmSchemas, "additionalEdmSchemas");
            EDesignUtil.CheckArgumentNull(target, "target");

            List <EdmSchemaError> errors = new List <EdmSchemaError>();

            try
            {
                MetadataArtifactLoader        sourceLoader = new MetadataArtifactLoaderXmlReaderWrapper(sourceEdmSchema);
                List <MetadataArtifactLoader> loaders      = new List <MetadataArtifactLoader>();
                loaders.Add(sourceLoader);

                int index = 0;
                foreach (XmlReader additionalEdmSchema in additionalEdmSchemas)
                {
                    if (additionalEdmSchema == null)
                    {
                        throw EDesignUtil.Argument(Strings.NullAdditionalSchema("additionalEdmSchema", index));
                    }

                    try
                    {
                        MetadataArtifactLoader loader = new MetadataArtifactLoaderXmlReaderWrapper(additionalEdmSchema);
                        Debug.Assert(loader != null, "when is the loader ever null?");
                        loaders.Add(loader);
                    }
                    catch (Exception e)
                    {
                        if (MetadataUtil.IsCatchableExceptionType(e))
                        {
                            errors.Add(new EdmSchemaError(e.Message,
                                                          (int)ModelBuilderErrorCode.CodeGenAdditionalEdmSchemaIsInvalid,
                                                          EdmSchemaErrorSeverity.Error));
                        }
                        else
                        {
                            throw;
                        }
                    }
                    index++;
                }
                ThrowOnAnyNonWarningErrors(errors);

                GenerateCodeCommon(sourceLoader,
                                   loaders,
                                   new LazyTextWriterCreator(target),
                                   null,  // source path
                                   null,  // target file path
                                   false, // dispose readers?
                                   errors);
            }
            catch (TerminalErrorException)
            {
                // do nothing
                // just a place to jump when errors are detected
            }

            return(errors);
        }
Example #30
0
        [ResourceConsumption(ResourceScope.Machine)] //For MetadataArtifactLoader.Create method call. But the path is not created in this method.
        public IList <EdmSchemaError> GenerateCode(string sourceEdmSchemaFilePath, string targetPath, IEnumerable <string> additionalEdmSchemaFilePaths)
        {
            EDesignUtil.CheckStringArgument(sourceEdmSchemaFilePath, "sourceEdmSchemaFilePath");
            EDesignUtil.CheckArgumentNull(additionalEdmSchemaFilePaths, "additionalEdmSchemaFilePaths");
            EDesignUtil.CheckStringArgument(targetPath, "targetPath");

            List <EdmSchemaError> errors = new List <EdmSchemaError>();

            try
            {
                // create a loader for the source
                HashSet <string>       uriRegistry = new HashSet <string>();
                MetadataArtifactLoader sourceLoader;
                try
                {
                    sourceLoader = MetadataArtifactLoader.Create(sourceEdmSchemaFilePath, MetadataArtifactLoader.ExtensionCheck.Specific,
                                                                 XmlConstants.CSpaceSchemaExtension, uriRegistry);
                }
                catch (MetadataException e)
                {
                    errors.Add(CreateErrorForException(ModelBuilderErrorCode.CodeGenSourceFilePathIsInvalid, e, sourceEdmSchemaFilePath));
                    return(errors);
                }

                if (sourceLoader.IsComposite)
                {
                    throw new ArgumentException(Strings.CodeGenSourceFilePathIsNotAFile, "sourceEdmSchemaPath");
                }

                // create loaders for all the additional schemas
                List <MetadataArtifactLoader> loaders = new List <MetadataArtifactLoader>();
                loaders.Add(sourceLoader);
                int index = 0;
                foreach (string additionalSchemaFilePath in additionalEdmSchemaFilePaths)
                {
                    if (additionalSchemaFilePath == null)
                    {
                        throw EDesignUtil.Argument(Strings.NullAdditionalSchema("additionalEdmSchemaFilePaths", index));
                    }

                    try
                    {
                        MetadataArtifactLoader loader = MetadataArtifactLoader.Create(additionalSchemaFilePath,
                                                                                      MetadataArtifactLoader.ExtensionCheck.Specific,
                                                                                      XmlConstants.CSpaceSchemaExtension, uriRegistry);
                        Debug.Assert(loader != null, "when is the loader ever null?");
                        loaders.Add(loader);
                    }
                    catch (Exception e)
                    {
                        if (MetadataUtil.IsCatchableExceptionType(e))
                        {
                            errors.Add(CreateErrorForException(ModelBuilderErrorCode.CodeGenAdditionalEdmSchemaIsInvalid, e, additionalSchemaFilePath));
                        }
                        else
                        {
                            throw;
                        }
                    }
                    index++;
                }

                ThrowOnAnyNonWarningErrors(errors);
                try
                {
                    using (LazyTextWriterCreator target = new LazyTextWriterCreator(targetPath))
                    {
                        GenerateCodeCommon(sourceLoader, loaders, target, sourceEdmSchemaFilePath, targetPath,
                                           true, // dispose readers
                                           errors);
                    }
                }
                catch (System.IO.IOException ex)
                {
                    errors.Add(CreateErrorForException(System.Data.EntityModel.SchemaObjectModel.ErrorCode.IOException, ex, targetPath));
                    return(errors);
                }
            }
            catch (TerminalErrorException)
            {
                // do nothing
                // just a place to jump when errors are detected
            }
            return(errors);
        }