private IList <EdmSchemaError> InternalGenerateCode(string sourceEdmSchemaFilePath, Version schemaVersion, LazyTextWriterCreator textWriter, IEnumerable <string> additionalEdmSchemaFilePaths, Version targetFrameworkVersion) { List <EdmSchemaError> errors = new List <EdmSchemaError>(); try { if (targetFrameworkVersion == EntityFrameworkVersions.Version1) { errors.Add(new EdmSchemaError(Strings.EntityCodeGenTargetTooLow, (int)ModelBuilderErrorCode.TargetVersionNotSupported, EdmSchemaErrorSeverity.Error)); return(errors); } if (!MetadataItemCollectionFactory.ValidateActualVersionAgainstTarget(targetFrameworkVersion, schemaVersion, errors)) { return(errors); } if (schemaVersion == EntityFrameworkVersions.EdmVersion1_1) { return(GenerateCodeFor1_1Schema(sourceEdmSchemaFilePath, textWriter, additionalEdmSchemaFilePaths)); } ReflectionAdapter codeGenerator = ReflectionAdapter.Create(_languageOption, targetFrameworkVersion); codeGenerator.SourceCsdlPath = sourceEdmSchemaFilePath; codeGenerator.ReferenceCsdlPaths = additionalEdmSchemaFilePaths; codeGenerator.EdmToObjectNamespaceMap = _edmToObjectNamespaceMap.AsDictionary(); string code = codeGenerator.TransformText(); if (codeGenerator.Errors.Count != 0) { ModelBuilderErrorCode errorCode = ModelBuilderErrorCode.PreprocessTemplateTransformationError; errors.AddRange(codeGenerator.Errors.OfType <CompilerError>().Select(c => ConvertToEdmSchemaError(c, errorCode))); if (codeGenerator.Errors.HasErrors) { return(errors); } } using (TextWriter writer = textWriter.GetOrCreateTextWriter()) { writer.Write(code); } } catch (System.UnauthorizedAccessException ex) { errors.Add(EntityClassGenerator.CreateErrorForException(ModelBuilderErrorCode.SecurityError, ex)); } catch (System.IO.FileNotFoundException ex) { errors.Add(EntityClassGenerator.CreateErrorForException(ModelBuilderErrorCode.FileNotFound, ex)); } catch (System.Security.SecurityException ex) { errors.Add(EntityClassGenerator.CreateErrorForException(ModelBuilderErrorCode.SecurityError, ex)); } catch (System.IO.DirectoryNotFoundException ex) { errors.Add(EntityClassGenerator.CreateErrorForException(ModelBuilderErrorCode.DirectoryNotFound, ex)); } catch (System.IO.IOException ex) { errors.Add(EntityClassGenerator.CreateErrorForException(ModelBuilderErrorCode.IOException, ex)); } catch (Exception e) { if (MetadataUtil.IsCatchableExceptionType(e)) { errors.Add(EntityClassGenerator.CreateErrorForException(ModelBuilderErrorCode.PreprocessTemplateTransformationError, e, sourceEdmSchemaFilePath)); } else { throw; } } return(errors); }
private IList <EdmSchemaError> GenerateCodeFor1_1Schema(string sourceEdmSchemaFilePath, LazyTextWriterCreator textWriter, IEnumerable <string> additionalEdmSchemaFilePaths) { EntityClassGenerator generator = new EntityClassGenerator(_languageOption); string target = textWriter.TargetFilePath; bool cleanUpTarget = false; try { if (textWriter.IsUserSuppliedTextWriter) { cleanUpTarget = true; target = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); } IList <EdmSchemaError> errors = generator.GenerateCode(sourceEdmSchemaFilePath, target, additionalEdmSchemaFilePaths != null ? additionalEdmSchemaFilePaths : Enumerable.Empty <string>()); if (textWriter.IsUserSuppliedTextWriter && !errors.Any(e => e.Severity == EdmSchemaErrorSeverity.Error)) { textWriter.GetOrCreateTextWriter().Write(File.ReadAllText(target)); } return(errors); } finally { if (cleanUpTarget && target != null && File.Exists(target)) { File.Delete(target); } } }
[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(); } } }
// this overload is for entry points that don't pass in readers, so we need to actually create a reader to get the schemaVersion out private IList <EdmSchemaError> InternalGenerateCode(string sourceEdmSchemaFilePath, LazyTextWriterCreator textWriter, IEnumerable <string> additionalEdmSchemaFilePaths, Version targetFrameworkVersion) { // do this check to maintain backwards compatibility with the behavior shipped in // framework v4 if (!File.Exists(sourceEdmSchemaFilePath)) { return(new List <EdmSchemaError>() { new EdmSchemaError(Strings.EdmSchemaFileNotFound(sourceEdmSchemaFilePath), (int)ModelBuilderErrorCode.FileNotFound, EdmSchemaErrorSeverity.Error, sourceEdmSchemaFilePath, 0, 0) }); } using (XmlReader reader = XmlReader.Create(sourceEdmSchemaFilePath)) { Version schemaVersion; if (!IsValidSchema(reader, out schemaVersion)) { return(new List <EdmSchemaError>() { CreateSourceEdmSchemaNotValidError() }); } return(InternalGenerateCode(sourceEdmSchemaFilePath, schemaVersion, textWriter, additionalEdmSchemaFilePaths, targetFrameworkVersion)); } }
private IList<EdmSchemaError> InternalGenerateCode(string sourceEdmSchemaFilePath, Version schemaVersion, LazyTextWriterCreator textWriter, IEnumerable<string> additionalEdmSchemaFilePaths, Version targetFrameworkVersion) { List<EdmSchemaError> errors = new List<EdmSchemaError>(); try { if (targetFrameworkVersion == EntityFrameworkVersions.Version1) { errors.Add(new EdmSchemaError(Strings.EntityCodeGenTargetTooLow, (int)ModelBuilderErrorCode.TargetVersionNotSupported, EdmSchemaErrorSeverity.Error)); return errors; } if (!MetadataItemCollectionFactory.ValidateActualVersionAgainstTarget(targetFrameworkVersion, schemaVersion, errors)) { return errors; } if (schemaVersion == EntityFrameworkVersions.EdmVersion1_1) { return GenerateCodeFor1_1Schema(sourceEdmSchemaFilePath, textWriter, additionalEdmSchemaFilePaths); } ReflectionAdapter codeGenerator = ReflectionAdapter.Create(_languageOption, targetFrameworkVersion); codeGenerator.SourceCsdlPath = sourceEdmSchemaFilePath; codeGenerator.ReferenceCsdlPaths = additionalEdmSchemaFilePaths; codeGenerator.EdmToObjectNamespaceMap = _edmToObjectNamespaceMap.AsDictionary(); string code = codeGenerator.TransformText(); if (codeGenerator.Errors.Count != 0) { ModelBuilderErrorCode errorCode = ModelBuilderErrorCode.PreprocessTemplateTransformationError; errors.AddRange(codeGenerator.Errors.OfType<CompilerError>().Select(c => ConvertToEdmSchemaError(c, errorCode))); if (codeGenerator.Errors.HasErrors) return errors; } using (TextWriter writer = textWriter.GetOrCreateTextWriter()) { writer.Write(code); } } catch (System.UnauthorizedAccessException ex) { errors.Add(EntityClassGenerator.CreateErrorForException(ModelBuilderErrorCode.SecurityError, ex)); } catch (System.IO.FileNotFoundException ex) { errors.Add(EntityClassGenerator.CreateErrorForException(ModelBuilderErrorCode.FileNotFound, ex)); } catch (System.Security.SecurityException ex) { errors.Add(EntityClassGenerator.CreateErrorForException(ModelBuilderErrorCode.SecurityError, ex)); } catch (System.IO.DirectoryNotFoundException ex) { errors.Add(EntityClassGenerator.CreateErrorForException(ModelBuilderErrorCode.DirectoryNotFound, ex)); } catch (System.IO.IOException ex) { errors.Add(EntityClassGenerator.CreateErrorForException(ModelBuilderErrorCode.IOException, ex)); } catch (Exception e) { if (MetadataUtil.IsCatchableExceptionType(e)) { errors.Add(EntityClassGenerator.CreateErrorForException(ModelBuilderErrorCode.PreprocessTemplateTransformationError, e, sourceEdmSchemaFilePath)); } else { throw; } } return errors; }
private IList<EdmSchemaError> GenerateCodeFor1_1Schema(string sourceEdmSchemaFilePath, LazyTextWriterCreator textWriter, IEnumerable<string> additionalEdmSchemaFilePaths) { EntityClassGenerator generator = new EntityClassGenerator(_languageOption); string target = textWriter.TargetFilePath; bool cleanUpTarget = false; try { if (textWriter.IsUserSuppliedTextWriter) { cleanUpTarget = true; target = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); } IList<EdmSchemaError> errors = generator.GenerateCode(sourceEdmSchemaFilePath, target, additionalEdmSchemaFilePaths != null ? additionalEdmSchemaFilePaths : Enumerable.Empty<string>()); if (textWriter.IsUserSuppliedTextWriter && !errors.Any(e => e.Severity == EdmSchemaErrorSeverity.Error)) { textWriter.GetOrCreateTextWriter().Write(File.ReadAllText(target)); } return errors; } finally { if (cleanUpTarget && target != null && File.Exists(target)) { File.Delete(target); } } }
// this overload is for entry points that don't pass in readers, so we need to actually create a reader to get the schemaVersion out private IList<EdmSchemaError> InternalGenerateCode(string sourceEdmSchemaFilePath, LazyTextWriterCreator textWriter, IEnumerable<string> additionalEdmSchemaFilePaths, Version targetFrameworkVersion) { // do this check to maintain backwards compatibility with the behavior shipped in // framework v4 if (!File.Exists(sourceEdmSchemaFilePath)) { return new List<EdmSchemaError>() { new EdmSchemaError(Strings.EdmSchemaFileNotFound(sourceEdmSchemaFilePath), (int)ModelBuilderErrorCode.FileNotFound, EdmSchemaErrorSeverity.Error, sourceEdmSchemaFilePath, 0, 0) }; } using (XmlReader reader = XmlReader.Create(sourceEdmSchemaFilePath)) { Version schemaVersion; if (!IsValidSchema(reader, out schemaVersion)) { return new List<EdmSchemaError>() { CreateSourceEdmSchemaNotValidError() }; } return InternalGenerateCode(sourceEdmSchemaFilePath, schemaVersion, textWriter, additionalEdmSchemaFilePaths, targetFrameworkVersion); } }
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); }
[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); }
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); }
[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; }