Esempio n. 1
0
        /// <summary>
        /// Builds a new instance.
        /// </summary>
        /// <param name="codeGeneratorContext">The code generator context.</param>
        /// <returns>
        /// A new <see cref="XsdDataContractImporter"/> instance.
        /// </returns>
        public XsdDataContractImporter Build(ICodeGeneratorContext codeGeneratorContext)
        {
            CodeGeneratorOptions codeGeneratorOptions = codeGeneratorContext.CodeGeneratorOptions;
            CodeDomProvider      codeDomProvider      = codeGeneratorContext.CodeDomProvider;
            CodeCompileUnit      codeCompileUnit      = codeGeneratorContext.CodeCompileUnit;

            ImportOptions importOptions = new ImportOptions
            {
                GenerateSerializable = codeGeneratorOptions.SerializableAttribute,
                GenerateInternal     = codeGeneratorOptions.InternalTypes,
                ImportXmlType        = codeGeneratorOptions.ImportXmlTypes,
                EnableDataBinding    = codeGeneratorOptions.EnableDataBinding,
                CodeProvider         = codeDomProvider
            };

            foreach (KeyValuePair <string, string> mapping in codeGeneratorOptions.NamespaceMappings)
            {
                importOptions.Namespaces.Add(mapping.Key, mapping.Value);
            }

            return(new XsdDataContractImporter(codeCompileUnit)
            {
                Options = importOptions
            });
        }
Esempio n. 2
0
 public static void ImplementCustomInterface(ICodeGeneratorContext codeGeneratorContext, CodeCompileUnit codeCompileUnit)
 {
     foreach (CodeNamespace @namespace in codeCompileUnit.Namespaces)
     {
         foreach (CodeTypeDeclaration type in @namespace.Types)
         {
             if (type.IsClass || type.IsStruct)
             {
                 bool hasResponseStatus = false;
                 foreach (CodeTypeMember member in type.Members)
                 {
                     var codeMemberProperty = member as CodeMemberProperty;
                     if (codeMemberProperty != null)
                     {
                         if (codeMemberProperty.Name == "ResponseStatus")
                         {
                             hasResponseStatus = true;
                         }
                     }
                 }
                 if (!hasResponseStatus && codeGeneratorContext.ElementName2TypeNameMapping.Values.Contains(type.Name))
                 {
                     type.BaseTypes.Add(codeGeneratorContext.CodeGenOptions.CustomRequestInterface);
                 }
             }
         }
     }
 }
        private static ServiceContractGenerator GetServiceContractGenerator(ICodeGeneratorContext codeGeneratorContext)
        {
            Mock <IServiceContractGenerationOptionsBuilder> generationOptionsBuilder = new Mock <IServiceContractGenerationOptionsBuilder>();
            IServiceContractGeneratorFactory factory = new ServiceContractGeneratorFactory(generationOptionsBuilder.Object);

            return(factory.GetServiceContractGenerator(codeGeneratorContext));
        }
Esempio n. 4
0
        private void ConfigureSerializers(MetadataImporter wsdlImporter, ICodeGeneratorContext codeGeneratorContext)
        {
            CodeGeneratorOptions codeGeneratorOptions = codeGeneratorContext.CodeGeneratorOptions;

            switch (codeGeneratorOptions.Serializer)
            {
            case SerializerMode.Auto:
                AddStateForDataContractSerializerImport(wsdlImporter, codeGeneratorContext);
                AddStateForXmlSerializerImport(wsdlImporter, codeGeneratorContext);
                if (!codeGeneratorOptions.UseXmlSerializerForFaults)
                {
                    break;
                }
                AddStateForFaultSerializerImport(wsdlImporter);
                return;

            case SerializerMode.DataContractSerializer:
                AddStateForDataContractSerializerImport(wsdlImporter, codeGeneratorContext);
                return;

            case SerializerMode.XmlSerializer:
                AddStateForXmlSerializerImport(wsdlImporter, codeGeneratorContext);
                if (!codeGeneratorOptions.UseXmlSerializerForFaults)
                {
                    AddStateForDataContractSerializerImport(wsdlImporter, codeGeneratorContext);
                    return;
                }
                AddStateForFaultSerializerImport(wsdlImporter);
                return;
            }
        }
Esempio n. 5
0
 /// <summary>
 /// Default ctor
 /// </summary>
 private CodeGenerator(TextWriter writer, IDocTypeNameResolver resolver, ICodeGeneratorContext context, TargetFramework target)
 {
     this.writer   = writer;
     this.resolver = resolver;
     this.context  = context;
     this.target   = target;
 }
		private static ServiceContractGenerator PerformBuild(ICodeGeneratorContext codeGeneratorContext)
		{
			Mock<IServiceContractGenerationOptionsBuilder> generationOptionsBuilder = new Mock<IServiceContractGenerationOptionsBuilder>();
			IServiceContractGeneratorBuilder builder = new ServiceContractGeneratorBuilder(generationOptionsBuilder.Object);

			return builder.Build(codeGeneratorContext);
		}
		/// <summary>
		/// Generates the <see cref="CodeCompileUnit"/> based on the provide context.
		/// </summary>
		/// <param name="codeGeneratorContext">The code generator context.</param>
		/// <returns>A <see cref="CodeCompileUnit"/> containing the generated code.</returns>
		public CodeCompileUnit GenerateCode(ICodeGeneratorContext codeGeneratorContext)
		{
			XsdDataContractImporter xsdDataContractImporter = xsdDataContractImporterBuilder.Build(codeGeneratorContext);
			XmlSchemaSet xmlSchemaSet = ExtractXmlSchemas(codeGeneratorContext.MetadataSet.MetadataSections);
			xsdDataContractImporter.Import(xmlSchemaSet);

			return xsdDataContractImporter.CodeCompileUnit;
		}
Esempio n. 8
0
        /// <summary>
        /// Gets a new <see cref="WsdlImporter"/> instance.
        /// </summary>
        /// <param name="codeGeneratorContext">The code generator context.</param>
        /// <returns>
        /// A new <see cref="WsdlImporter"/> instance.
        /// </returns>
        public WsdlImporter GetWsdlImporter(ICodeGeneratorContext codeGeneratorContext)
        {
            WsdlImporter wsdlImporter = new WsdlImporter(codeGeneratorContext.MetadataSet);

            RemoveUnneededSerializers(wsdlImporter, codeGeneratorContext);
            ConfigureSerializers(wsdlImporter, codeGeneratorContext);

            return(wsdlImporter);
        }
Esempio n. 9
0
        /// <summary>
        /// Generates the <see cref="CodeCompileUnit"/> based on the provide context.
        /// </summary>
        /// <param name="codeGeneratorContext">The code generator context.</param>
        /// <returns>A <see cref="CodeCompileUnit"/> containing the generated code.</returns>
        public CodeCompileUnit GenerateCode(ICodeGeneratorContext codeGeneratorContext)
        {
            WsdlImporter             wsdlImporter      = wsdlImporterFactory.GetWsdlImporter(codeGeneratorContext);
            ServiceContractGenerator contractGenerator = serviceContractGeneratorFactory.GetServiceContractGenerator(codeGeneratorContext);

            GenerateCodeDomTree(wsdlImporter, contractGenerator);

            //TODO:Alex:Generate the Configuration information and merge if required.

            //TODO:Alex:Prevent the need to keep all types in the same namespaces for certain code decorators.

            return(contractGenerator.TargetCompileUnit);
        }
		/// <summary>
		/// Generates the <see cref="CodeCompileUnit"/> based on the provide context.
		/// </summary>
		/// <param name="codeGeneratorContext">The code generator context.</param>
		/// <returns>A <see cref="CodeCompileUnit"/> containing the generated code.</returns>
		public CodeCompileUnit GenerateCode(ICodeGeneratorContext codeGeneratorContext)
		{
			WsdlImporter wsdlImporter = wsdlImporterBuilder.Build(codeGeneratorContext);
			ServiceContractGenerator contractGenerator = serviceContractGeneratorBuilder.Build(codeGeneratorContext);

			GenerateCodeDomTree(wsdlImporter, contractGenerator);

			//TODO:Alex:Generate the Configuration information and merge if required.
			
			//TODO:Alex:Prevent the need to keep all types in the same namespaces for certain code decorators.

			return contractGenerator.TargetCompileUnit;
		}
		/// <summary>
		/// Builds a new instance.
		/// </summary>
		/// <param name="codeGeneratorContext">The code generator context.</param>
		/// <returns>
		/// A new <see cref="ServiceContractGenerator"/> instance.
		/// </returns>
		public ServiceContractGenerator Build(ICodeGeneratorContext codeGeneratorContext)
		{
			CodeGeneratorOptions codeGeneratorOptions = codeGeneratorContext.CodeGeneratorOptions;
			CodeCompileUnit codeCompileUnit = codeGeneratorContext.CodeCompileUnit;
			Configuration configuration = InitializeConfiguration();

			ServiceContractGenerator contractGenerator = new ServiceContractGenerator(codeCompileUnit, configuration)
			{
				Options = generationOptionsBuilder.Build(codeGeneratorOptions)
			};

			foreach (KeyValuePair<string, string> mapping in codeGeneratorOptions.NamespaceMappings)
			{
				contractGenerator.NamespaceMappings.Add(mapping.Key, mapping.Value);
			}

			return contractGenerator;
		}
Esempio n. 12
0
        private static void RemoveUnneededSerializers(WsdlImporter wsdlImporter, ICodeGeneratorContext codeGeneratorContext)
        {
            CodeGeneratorOptions codeGeneratorOptions = codeGeneratorContext.CodeGeneratorOptions;

            switch (codeGeneratorOptions.Serializer)
            {
            case SerializerMode.Auto:
                break;

            case SerializerMode.DataContractSerializer:
                RemoveExtension(wsdlImporter, typeof(XmlSerializerMessageContractImporter));
                return;

            case SerializerMode.XmlSerializer:
                RemoveExtension(wsdlImporter, typeof(DataContractSerializerMessageContractImporter));
                return;
            }
        }
        /// <summary>
        /// Gets a new <see cref="ServiceContractGenerator"/> instance.
        /// </summary>
        /// <param name="codeGeneratorContext">The code generator context.</param>
        /// <returns>
        /// A new <see cref="ServiceContractGenerator"/> instance.
        /// </returns>
        public ServiceContractGenerator GetServiceContractGenerator(ICodeGeneratorContext codeGeneratorContext)
        {
            CodeGeneratorOptions codeGeneratorOptions = codeGeneratorContext.CodeGeneratorOptions;
            CodeCompileUnit      codeCompileUnit      = codeGeneratorContext.CodeCompileUnit;
            Configuration        configuration        = InitializeConfiguration();

            ServiceContractGenerator contractGenerator = new ServiceContractGenerator(codeCompileUnit, configuration)
            {
                Options = generationOptionsBuilder.Build(codeGeneratorOptions)
            };

            foreach (KeyValuePair <string, string> mapping in codeGeneratorOptions.NamespaceMappings)
            {
                contractGenerator.NamespaceMappings.Add(mapping.Key, mapping.Value);
            }

            return(contractGenerator);
        }
		/// <summary>
		/// Builds a new instance.
		/// </summary>
		/// <param name="codeGeneratorContext">The code generator context.</param>
		/// <returns>
		/// A new <see cref="XmlSerializerImportOptions"/> instance.
		/// </returns>
		public XmlSerializerImportOptions Build(ICodeGeneratorContext codeGeneratorContext)
		{
			CodeGeneratorOptions codeGeneratorOptions = codeGeneratorContext.CodeGeneratorOptions;
			CodeDomProvider codeDomProvider = codeGeneratorContext.CodeDomProvider;
			CodeCompileUnit codeCompileUnit = codeGeneratorContext.CodeCompileUnit;

			WebReferenceOptions webReferenceOptions = new WebReferenceOptions
			{
				CodeGenerationOptions = CodeGenerationOptions.None
			};

			if (codeGeneratorOptions.OrderMembers)
			{
				webReferenceOptions.CodeGenerationOptions |= CodeGenerationOptions.GenerateOrder;
			}
			if (codeGeneratorOptions.GenerateProperties)
			{
				webReferenceOptions.CodeGenerationOptions |= CodeGenerationOptions.GenerateProperties;
			}
			if (codeGeneratorOptions.EnableDataBinding)
			{
				webReferenceOptions.CodeGenerationOptions |= CodeGenerationOptions.EnableDataBinding;
			}

			string typedDataSetExtension = (codeGeneratorOptions.TargetFrameworkVersion == TargetFrameworkVersion.Version35)
				? typeof(TypedDataSetSchemaImporterExtensionFx35).AssemblyQualifiedName
				: typeof(TypedDataSetSchemaImporterExtension).AssemblyQualifiedName;
			webReferenceOptions.SchemaImporterExtensions.Add(typedDataSetExtension);
			webReferenceOptions.SchemaImporterExtensions.Add(typeof(DataSetSchemaImporterExtension).AssemblyQualifiedName);

			XmlSerializerImportOptions xmlSerializerImportOptions = new XmlSerializerImportOptions(codeCompileUnit)
			{
				WebReferenceOptions = webReferenceOptions,
				CodeProvider = codeDomProvider
			};

			//TODO:Alex:Prevent the need to keep all types in the same namespaces for certain code decorators.
			string namespaceMapping;
			codeGeneratorOptions.NamespaceMappings.TryGetValue("*", out namespaceMapping);
			xmlSerializerImportOptions.ClrNamespace = namespaceMapping;

			return xmlSerializerImportOptions;
		}
        public CreateCodeGenerationPipelineState(ICodeGeneratorContext context, ITypeInstanceActivator typeInstanceActivator)
        {
            Ensure.ArgumentNotNull(context, "context");
            Ensure.ArgumentNotNull(typeInstanceActivator, "typeInstanceActivator");

            Context = context;

            SourcePartialClassDefinitions = new List<TypeDeclaration>();
            AssemblyAttributes = new List<IAttribute>();
            SourcePartialClassAttributes = new Dictionary<TypeDeclaration, IList<IAttribute>>();
            CodeGenerationErrors = new List<CodeGenerationError>();

            TypeInstanceActivator = typeInstanceActivator;
            PartialClassLevelResolvedPMixinAttributes = new Dictionary<TypeDeclaration, IList<pMixinAttributeResolvedResultBase>>();

            CodeGenerationPlans = new Dictionary<TypeDeclaration, CodeGenerationPlan>();

            CodeBehindSyntaxTree = new SyntaxTree();
        }
        public CreateCodeGenerationPipelineState(ICodeGeneratorContext context, ITypeInstanceActivator typeInstanceActivator)
        {
            Ensure.ArgumentNotNull(context, "context");
            Ensure.ArgumentNotNull(typeInstanceActivator, "typeInstanceActivator");

            Context = context;

            SourcePartialClassDefinitions = new List <TypeDeclaration>();
            AssemblyAttributes            = new List <IAttribute>();
            SourcePartialClassAttributes  = new Dictionary <TypeDeclaration, IList <IAttribute> >();
            CodeGenerationErrors          = new List <CodeGenerationError>();

            TypeInstanceActivator = typeInstanceActivator;
            PartialClassLevelResolvedPMixinAttributes = new Dictionary <TypeDeclaration, IList <pMixinAttributeResolvedResultBase> >();

            CodeGenerationPlans = new Dictionary <TypeDeclaration, CodeGenerationPlan>();

            CodeBehindSyntaxTree = new SyntaxTree();
        }
Esempio n. 17
0
        public static void BuildElementName2TargetNamespaceMapping(ICodeGeneratorContext codeGeneratorContext)
        {
            XmlSchemas    xmlSchemas    = codeGeneratorContext.XmlSchemas;
            CodeNamespace codeNamespace = new CodeNamespace();

            const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateProperties;
            var exporter = new XmlCodeExporter(codeNamespace);
            var importer = new XmlSchemaImporter(xmlSchemas, generationOptions, new ImportContext(new CodeIdentifiers(), false));

            IDictionary <string, string> elementName2TargetNamespaceMapping = codeGeneratorContext.ElementName2TargetNamespaceMapping;

            foreach (XmlSchema schema in xmlSchemas)
            {
                foreach (XmlSchemaElement element in schema.Elements.Values)
                {
                    XmlTypeMapping typeMapping = importer.ImportTypeMapping(element.QualifiedName);
                    elementName2TargetNamespaceMapping[element.QualifiedName.Name] = schema.TargetNamespace;
                }
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Generates the <see cref="CodeCompileUnit"/> based on the provide context.
        /// </summary>
        /// <param name="codeGeneratorContext">The code generator context.</param>
        public CodeCompileUnit GenerateDataContractCode(ICodeGeneratorContext codeGeneratorContext)
        {
            CodeCompileUnit codeCompileUnit = CodeExtension.GenerateDataContractCode(codeGeneratorContext.XmlSchemas);

            CodeExtension.RemoveDefaultTypes(codeCompileUnit);

            codeCompileUnit.ImplementsBaijiSerialization(codeGeneratorContext);

            if (codeGeneratorContext.CodeGenOptions.AddCustomRequestInterface)
            {
                DataContractGenerator.BuildElementName2TypeNameMapping(codeGeneratorContext);
                DataContractGenerator.ImplementCustomInterface(codeGeneratorContext, codeCompileUnit);
            }

            if (codeGeneratorContext.CodeGenOptions.ForceElementNamespace)
            {
                DataContractGenerator.BuildElementName2TargetNamespaceMapping(codeGeneratorContext);
            }

            return(codeCompileUnit);
        }
		/// <summary>
		/// Builds a new instance.
		/// </summary>
		/// <param name="codeGeneratorContext">The code generator context.</param>
		/// <returns>
		/// A new <see cref="XsdDataContractImporter"/> instance.
		/// </returns>
		public XsdDataContractImporter Build(ICodeGeneratorContext codeGeneratorContext)
		{
			CodeGeneratorOptions codeGeneratorOptions = codeGeneratorContext.CodeGeneratorOptions;
			CodeDomProvider codeDomProvider = codeGeneratorContext.CodeDomProvider;
			CodeCompileUnit codeCompileUnit = codeGeneratorContext.CodeCompileUnit;

			ImportOptions importOptions = new ImportOptions
			{
				GenerateSerializable = codeGeneratorOptions.SerializableAttribute,
				GenerateInternal = codeGeneratorOptions.InternalTypes,
				ImportXmlType = codeGeneratorOptions.ImportXmlTypes,
				EnableDataBinding = codeGeneratorOptions.EnableDataBinding,
				CodeProvider = codeDomProvider
			};

			foreach (KeyValuePair<string, string> mapping in codeGeneratorOptions.NamespaceMappings)
			{
				importOptions.Namespaces.Add(mapping.Key, mapping.Value);
			}

			return new XsdDataContractImporter(codeCompileUnit) {Options = importOptions};
		}
Esempio n. 20
0
        public pMixinPartialCodeGeneratorResponse GeneratePartialCode(ICodeGeneratorContext codeGeneratorContext)
        {
            var stopwatch = Stopwatch.StartNew();

            try
            {
                _log.InfoFormat("GeneratePartialCode Begin [{0}]", codeGeneratorContext.Source.FileName);

                var logManager = new Log4NetInMemoryStreamAppenderManager();

                var pipelineState = new CreateCodeGenerationPipelineState(codeGeneratorContext);

                new pMixinPartialCodeGeneratorPipeline().PerformTask(pipelineState);

                return(new pMixinPartialCodeGeneratorResponse
                {
                    CodeGeneratorExecutionTime = stopwatch.Elapsed,
                    CreateCodeGeneratorPipelineState = pipelineState,
                    CodeGeneratorContext = codeGeneratorContext,
                    Errors = pipelineState.CodeGenerationErrors,
                    GeneratedCodeSyntaxTree = pipelineState.CodeBehindSyntaxTree,
                    LogMessages = logManager.GetRenderedLoggingEvents(LoggingVerbosity.All)
                });
            }
            catch (Exception e)
            {
                _log.Error(string.Format("Unhandled exception generating [{0}]: {1}",
                                         codeGeneratorContext.Source.FileName, e.Message), e);

                throw;
            }
            finally
            {
                _log.InfoFormat("GeneratePartialCode Complete [{0}] in [{1}] ms",
                                codeGeneratorContext.Source.FileName,
                                stopwatch.ElapsedMilliseconds);
            }
        }
        public pMixinPartialCodeGeneratorResponse GeneratePartialCode(ICodeGeneratorContext codeGeneratorContext)
        {
            var stopwatch = Stopwatch.StartNew();

            try
            {
                _log.InfoFormat("GeneratePartialCode Begin [{0}]", codeGeneratorContext.Source.FileName);

                var logManager = new Log4NetInMemoryStreamAppenderManager();

                var pipelineState = new CreateCodeGenerationPipelineState(codeGeneratorContext);

                new pMixinPartialCodeGeneratorPipeline().PerformTask(pipelineState);

                return new pMixinPartialCodeGeneratorResponse
                       {
                           CodeGeneratorExecutionTime = stopwatch.Elapsed,
                           CreateCodeGeneratorPipelineState = pipelineState,
                           CodeGeneratorContext = codeGeneratorContext,
                           Errors = pipelineState.CodeGenerationErrors,
                           GeneratedCodeSyntaxTree = pipelineState.CodeBehindSyntaxTree,
                           LogMessages = logManager.GetRenderedLoggingEvents(LoggingVerbosity.All)
                       };
            }
            catch (Exception e)
            {
                _log.Error(string.Format("Unhandled exception generating [{0}]: {1}",
                    codeGeneratorContext.Source.FileName, e.Message), e);

                throw;
            }
            finally
            {
                _log.InfoFormat("GeneratePartialCode Complete [{0}] in [{1}] ms",
                    codeGeneratorContext.Source.FileName,
                    stopwatch.ElapsedMilliseconds);
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Executes the code generation workflow.
        /// </summary>
        public CodeWriterOutput GenerateCode(Options.CodeGenOptions options)
        {
            ICodeGeneratorContext codeGeneratorContext = buildCodeGeneratorContext(options);
            ICodeGenerator        codeGenerator        = this.buildCodeGenerator(options);

            CodeWriterOptions writeOptions = CodeGenOptionsParser.GetCodeWriterOptions(options);

            if (options.OnlyUseDataContractSerializer)
            {
                CodeCompileUnit targetCodeCompileUnit = codeGenerator.GenerateDataContractCode(codeGeneratorContext);
                return(CodeWriter.CodeWriter.Write(targetCodeCompileUnit, writeOptions));
            }
            else if (options.GenerateSeparateFilesEachXsd)
            {
                CodeNamespace[] targetCodeNamespaces = codeGenerator.GenerateCodes(codeGeneratorContext);
                return(CodeWriter.CodeWriter.Write(targetCodeNamespaces, writeOptions));
            }
            else
            {
                CodeNamespace targetCodeNamespace = codeGenerator.GenerateCode(codeGeneratorContext);
                return(CodeWriter.CodeWriter.Write(targetCodeNamespace, writeOptions));
            }
        }
Esempio n. 23
0
 private void AddStateForXmlSerializerImport(MetadataImporter wsdlImporter, ICodeGeneratorContext codeGeneratorContext)
 {
     AddState(wsdlImporter, xmlSerializerImportOptionsBuilder.Build(codeGeneratorContext));
     AddState(wsdlImporter, wrappedOptionsBuilder.Build(codeGeneratorContext.CodeGeneratorOptions));
 }
Esempio n. 24
0
        /// <summary>
        /// Generates the <see cref="CodeNamespace"/> based on the provide context.
        /// </summary>
        /// <param name="codeGeneratorContext">The code generator context.</param>
        public CodeNamespace GenerateCode(ICodeGeneratorContext codeGeneratorContext)
        {
            CodeGenOptions codeGenOptions = codeGeneratorContext.CodeGenOptions;
            XmlSchemas     xmlSchemas     = codeGeneratorContext.XmlSchemas;

            CodeNamespace codeNamespace = new CodeNamespace();

            // Generate DataContracts
            const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateProperties;
            var exporter = new XmlCodeExporter(codeNamespace);
            var importer = new XmlSchemaImporter(xmlSchemas, generationOptions, new ImportContext(new CodeIdentifiers(), false));

            // TypeName to XmlSchemaType mapping
            IDictionary <string, XmlSchemaType> typeName2schemaTypeMapping = codeGeneratorContext.TypeName2schemaTypeMapping;

            foreach (XmlSchema schema in xmlSchemas)
            {
                foreach (XmlSchemaElement element in schema.Elements.Values)
                {
                    XmlTypeMapping typeMapping = importer.ImportTypeMapping(element.QualifiedName);
                    if (element.IsAbstract)
                    {
                        continue;
                    }

                    exporter.ExportTypeMapping(typeMapping);
                    typeName2schemaTypeMapping[typeMapping.TypeName] = element.ElementSchemaType;
                }

                foreach (XmlSchemaType complexType in schema.SchemaTypes.Values)
                {
                    XmlTypeMapping typeMapping = importer.ImportSchemaType(complexType.QualifiedName);
                    if (CouldBeAnArray(complexType))
                    {
                        continue;
                    }

                    exporter.ExportTypeMapping(typeMapping);
                    typeName2schemaTypeMapping[typeMapping.TypeName] = complexType;
                }
            }

            if (codeNamespace.Types.Count == 0)
            {
                throw new Exception("No types were generated.");
            }

            // Build type name to code type declaration mapping
            codeGeneratorContext.CodeTypeMap = BuildCodeTypeMap(codeNamespace);
            if (codeGenOptions.ForceElementName)
            {
                DataContractGenerator.BuildElementName2TypeNameMapping(codeGeneratorContext);
            }
            if (codeGenOptions.ForceElementNamespace)
            {
                DataContractGenerator.BuildElementName2TargetNamespaceMapping(codeGeneratorContext);
            }

            // Decorate data contracts code
            ICodeExtension codeExtension = new CodeExtension();

            codeExtension.Process(codeNamespace, codeGeneratorContext);

            CodeExtension.RemoveDefaultTypes(codeNamespace);

            return(codeNamespace);
        }
 public CreateCodeGenerationPipelineState(ICodeGeneratorContext context)
     : this(context, new TypeInstanceActivator())
 {
 }
Esempio n. 26
0
 /// <summary>
 /// Create a header for the source file.
 /// </summary>
 private static void GenerateHeader(TextWriter writer, ICodeGeneratorContext context)
 {
     context.CreateSourceFileHeader(writer);
 }
Esempio n. 27
0
        /// <summary>
        /// Generate code for the given types.
        /// </summary>
        public static void Generate(string folder, List <NetTypeDefinition> types, List <NetCustomAttribute> assemblyAttributes, IDocTypeNameResolver resolver, ICodeGeneratorContext context, TargetFramework target)
        {
            // Clean
            foreach (var iterator in context.PossibleNamespaceRoots)
            {
                var root = iterator;
                var path = Path.Combine(folder, root + ".cs");
                File.Delete(path);
            }

            // Select namespace roots
            var roots = types.Select(context.GetNamespaceRoot).Distinct().ToList();

            // Save
            var addAssemblyAttributes = true;

            foreach (var iterator in roots)
            {
                var root = iterator;
                var path = Path.Combine(folder, root + ".cs");
                using (var writer = new StreamWriter(path, false, Encoding.UTF8, 128 * 1024))
                {
                    GenerateHeader(writer, context);
                    var selectedTypes = types.Where(x => context.GetNamespaceRoot(x) == root);
                    var generator     = new CodeGenerator(writer, resolver, context, target);
                    if (addAssemblyAttributes)
                    {
                        generator.GenerateAssemblyAttributes(assemblyAttributes);
                        addAssemblyAttributes = false;
                    }
                    generator.Generate(selectedTypes);
                }
            }
        }
Esempio n. 28
0
 CodeGeneratorResponse IPartialCodeGenerator.GeneratePartialCode(ICodeGeneratorContext codeGeneratorContext)
 {
     return(GeneratePartialCode(codeGeneratorContext));
 }
 public CreateCodeGenerationPipelineState(ICodeGeneratorContext context)
     : this(context, new TypeInstanceActivator())
 {
 }
 CodeGeneratorResponse IPartialCodeGenerator.GeneratePartialCode(ICodeGeneratorContext codeGeneratorContext)
 {
     return GeneratePartialCode(codeGeneratorContext);
 }
Esempio n. 31
0
        /// <summary>
        /// Generates the <see cref="CodeNamespace"/> based on the provide context.
        /// </summary>
        /// <param name="codeGeneratorContext">The code generator context.</param>
        public CodeNamespace[] GenerateCodes(ICodeGeneratorContext codeGeneratorContext)
        {
            CodeGenOptions codeGenOptions = codeGeneratorContext.CodeGenOptions;
            XmlSchemas     xmlSchemas     = codeGeneratorContext.XmlSchemas;

            // Generate DataContracts
            const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateProperties;

            List <CodeNamespace> codeNamespaces = new List <CodeNamespace>();

            // TypeName to XmlSchemaType mapping
            IDictionary <string, XmlSchemaType> typeName2schemaTypeMapping = codeGeneratorContext.TypeName2schemaTypeMapping;

            foreach (XmlSchema schema in xmlSchemas)
            {
                CodeNamespace codeNamespace = new CodeNamespace();
                codeNamespace.UserData.Add(Constants.SCHEMA, schema);

                XmlCodeExporter   exporter = new XmlCodeExporter(codeNamespace);
                XmlSchemaImporter importer = new XmlSchemaImporter(xmlSchemas, generationOptions, new ImportContext(new CodeIdentifiers(), false));

                foreach (XmlSchemaElement element in schema.Elements.Values)
                {
                    XmlTypeMapping typeMapping = importer.ImportTypeMapping(element.QualifiedName);
                    if (element.IsAbstract)
                    {
                        continue;
                    }

                    exporter.ExportTypeMapping(typeMapping);
                    typeName2schemaTypeMapping[typeMapping.TypeName] = element.ElementSchemaType;
                }

                foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values)
                {
                    if (String.IsNullOrWhiteSpace(schemaType.SourceUri))
                    {
                        schemaType.SourceUri = schema.SourceUri;
                    }
                    XmlTypeMapping typeMapping = importer.ImportSchemaType(schemaType.QualifiedName);
                    if (CouldBeAnArray(schemaType))
                    {
                        continue;
                    }

                    exporter.ExportTypeMapping(typeMapping);
                    typeName2schemaTypeMapping[typeMapping.TypeName] = schemaType;
                }

                if (codeNamespace.Types.Count > 0)
                {
                    codeNamespaces.Add(codeNamespace);
                }
            }

            if (codeNamespaces.Count == 0)
            {
                throw new Exception("No types were generated.");
            }
            // Build type name to code type declaration mapping
            codeGeneratorContext.CodeTypeMap = DataContractGenerator.BuildCodeTypeMap(codeNamespaces.ToArray());
            if (codeGenOptions.ForceElementName)
            {
                DataContractGenerator.BuildElementName2TypeNameMapping(codeGeneratorContext);
            }
            if (codeGenOptions.ForceElementNamespace)
            {
                DataContractGenerator.BuildElementName2TargetNamespaceMapping(codeGeneratorContext);
            }

            for (int i = 0; i < codeNamespaces.Count; i++)
            {
                CodeNamespace codeNamespace = codeNamespaces[i];
                // Decorate data contracts code
                ICodeExtension codeExtension = new CodeExtension();
                codeExtension.Process(codeNamespace, codeGeneratorContext);

                CodeExtension.RemoveDefaultTypes(codeNamespace);

                List <CodeTypeDeclaration> types = new List <CodeTypeDeclaration>();
                XmlSchema schema = codeNamespace.UserData[Constants.SCHEMA] as XmlSchema;

                foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values)
                {
                    foreach (CodeTypeDeclaration codeType in codeNamespace.Types)
                    {
                        if (codeType.Name == schemaType.Name &&
                            schema.SourceUri == schemaType.SourceUri)
                        {
                            types.Add(codeType);
                        }
                    }
                }
                codeNamespace.Types.Clear();
                codeNamespace.Types.AddRange(types.ToArray());

                if (codeNamespace.Types.Count == 0)
                {
                    codeNamespaces.RemoveAt(i--);
                }
            }

            return(codeNamespaces.ToArray());
        }
        private CodeGeneratorResponse GenerateCode(ICodeGeneratorContext context)
        {
            using (new LoggingActivity("GenerateCode " + context.Source.FileName))
            try
            {
                _visualStudioWriter.WriteToStatusBar("pMixin - Generating Code Behind for " + context.Source.FileName);

                var response = _codeGenerator.GeneratePartialCode(context);

                _visualStudioEventProxy.FireOnCodeGenerated(this, response);

                #region Write Errors / Warnings

                foreach (var error in response.Errors)
                    switch (error.Severity)
                    {
                        case CodeGenerationError.SeverityOptions.Error:
                            _visualStudioWriter.GeneratorError(error.Message, error.Line, error.Column);
                            Log.Error("Code Generator Registered Error: " + error.Message);
                            break;

                        case CodeGenerationError.SeverityOptions.Warning:
                            _visualStudioWriter.GeneratorWarning(error.Message, error.Line, error.Column);
                            Log.Warn("Code Generator Registered Warning: " + error.Message);
                            break;

                        case CodeGenerationError.SeverityOptions.Message:
                            _visualStudioWriter.GeneratorMessage(error.Message, error.Line, error.Column);
                            Log.InfoFormat("Code Generator Registered Message: " + error.Message);
                            break;
                    }

                #endregion

                Log.DebugFormat("Generated Code for File [{0}]: {1}{1}{2}{1}{1}",
                    context.Source.FileName,
                    Environment.NewLine,
                    response.GeneratedCodeSyntaxTree.GetText());

                return response;
            }
            catch (Exception e)
            {
                var errorMessage =
                    string.Format("Unhandled Exception Generating Code for File [{0}] in Product [{1}]: {2}",
                        context.Source.FileName,
                        context.Source.Project.FileName,
                        e.Message);

                if (Log.IsInfoEnabled)
                    errorMessage += Environment.NewLine + "File Contents:" + Environment.NewLine + context.Source.OriginalText;

                Log.Error(errorMessage, e);

                return new CodeGeneratorResponse();
            }
            finally
            {
                _visualStudioWriter.WriteToStatusBar("pMixin - Generating Code Behind for " + context.Source.FileName + " ... complete");
            }
        }