コード例 #1
0
        private void WriteClassFile(Project project, String name, CodeNamespace ns, CodeDomProvider provider)
        {
            String filename = String.Format("{0}.{1}", name, provider.FileExtension);

            FileInfo fileInfo = new FileInfo(Path.Combine(project.LastOutDir, filename));

            if (fileInfo.Exists && !project.OverwriteFiles)
            {
                Log(String.Format("Skipping {0} as it already exists", filename));
            }
            else
            {
                Log(String.Format("Writing {0}...", filename));

                try
                {
                    using (FileStream stream = new FileStream(fileInfo.FullName, FileMode.Create, FileAccess.Write))
                    {
                        StreamWriter         writer = new StreamWriter(stream);
                        CodeGeneratorOptions opts   = new CodeGeneratorOptions();
                        opts.BracingStyle             = "C";
                        opts.BlankLinesBetweenMembers = true;
                        provider.CreateGenerator().GenerateCodeFromNamespace(ns, writer, opts);
                        writer.Flush();
                        writer.Close();
                    }
                }
                catch (Exception ex)
                {
                    Log(String.Format("Error Writing {0} []", filename, ex.Message));
                }
            }
        }
コード例 #2
0
        private string GenerateTables(CodeDomProvider codeDomProvider, CodeGeneratorOptions options, CodeGenerationInfo generationInfo)
        {
            var sb = new StringBuilder();

            using (var sw = new StringWriter(sb))
            {
                var codeGenerator = codeDomProvider.CreateGenerator(sw);
                var compileUnit   = new CodeCompileUnit();

                compileUnit.AddCustomInclude($"{generationInfo.RelativePath}reader/include/crema/inidata");
                compileUnit.AddCustomInclude($"{generationInfo.Prefix}types{generationInfo.Postfix}");
                compileUnit.AddCustomInclude($"{generationInfo.RelativePath}crema_base");

                var codeNamespace = new CodeNamespace(generationInfo.Namespace);
                codeNamespace.Imports.Add(new CodeNamespaceImport(generationInfo.ReaderNamespace));

                CremaDataClassCreator.Create(codeNamespace, generationInfo);

                compileUnit.Namespaces.Add(codeNamespace);

                codeGenerator.GenerateCodeFromCompileUnit(compileUnit, sw, options);
            }

            return(sb.ToString());
        }
コード例 #3
0
        private string GenerateTables(CodeDomProvider codeDomProvider, CodeGeneratorOptions options, CodeGenerationInfo generationInfo)
        {
            var sb = new StringBuilder();

            ColumnInfoExtensions.TypeNamespace = "types";
            using (var writer = new StringWriter(sb))
            {
                var codeGenerator = codeDomProvider.CreateGenerator(writer);
                var compileUnit   = new CodeCompileUnit();
                var codeNamespace = new CodeNamespace();

                this.AppendLint(sb, generationInfo);

                codeNamespace.Imports.Add(new CodeNamespaceImport($"reader = require(\"./{generationInfo.RelativePath}{generationInfo.Namespace}-reader\")"));
                codeNamespace.Imports.Add(new CodeNamespaceImport($"base = require(\"./{generationInfo.RelativePath}{generationInfo.Namespace}-base\")"));
                if (generationInfo.Types.Any() == true)
                {
                    codeNamespace.Imports.Add(new CodeNamespaceImport($"types = require(\"./{generationInfo.Namespace}-types\")"));
                }

                CremaDataClassCreator.Create(codeNamespace, generationInfo);
                compileUnit.Namespaces.Add(codeNamespace);
                codeGenerator.GenerateCodeFromCompileUnit(compileUnit, writer, options);
            }

            return(System.Text.RegularExpressions.Regex.Replace(sb.ToString(), "^\\s+$", string.Empty, System.Text.RegularExpressions.RegexOptions.Multiline));
        }
コード例 #4
0
        private string GenerateTables(CodeDomProvider codeDomProvider, CodeGeneratorOptions options, CodeGenerationInfo generationInfo)
        {
            StringBuilder sb = new StringBuilder();

            using (StringWriter sw = new StringWriter(sb))
            {
                var             codeGenerator = codeDomProvider.CreateGenerator(sw);
                CodeCompileUnit compileUnit   = new CodeCompileUnit();

                //compileUnit.AddCustomInclude("reader/include/crema/inidata");
                compileUnit.AddInclude("crema/inidata");
                compileUnit.AddCustomInclude("crema_datatypes");
                //compileUnit.AddCustomInclude("crema_base");

                CodeNamespace codeNamespace = new CodeNamespace(generationInfo.Namespace);
                codeNamespace.Imports.Add(new CodeNamespaceImport(generationInfo.ReaderNamespace));

                foreach (var item in generationInfo.GetTables())
                {
                    H3RowClassCreator.Create(codeNamespace, item, generationInfo);
                }

                compileUnit.Namespaces.Add(codeNamespace);

                codeGenerator.GenerateCodeFromCompileUnit(compileUnit, sw, options);
            }

            return(sb.ToString());
        }
コード例 #5
0
            public CompilerInfo(LanguageId languageId, CodeDomProvider provider)
            {
                _lang = languageId;

                Compiler = provider.CreateCompiler();
                CodeGen  = provider.CreateGenerator();
            }
コード例 #6
0
ファイル: Application.cs プロジェクト: orf53975/stetic
        public CodeGenerationResult GenerateProjectCode(string file, string namespaceName, CodeDomProvider provider, GenerationOptions options, params Project[] projects)
        {
            ArrayList            files = new ArrayList();
            CodeGenerationResult res   = GenerateProjectCode(options, projects);

            ICodeGenerator gen      = provider.CreateGenerator();
            string         basePath = Path.GetDirectoryName(file);
            string         ext      = Path.GetExtension(file);

            foreach (SteticCompilationUnit unit in res.Units)
            {
                string fname;
                if (unit.Name.Length == 0)
                {
                    fname = file;
                }
                else
                {
                    fname = Path.Combine(basePath, unit.Name) + ext;
                }
                files.Add(fname);
                unit.Name = fname;
                StreamWriter fileStream = new StreamWriter(fname);
                try {
                    gen.GenerateCodeFromCompileUnit(unit, fileStream, new CodeGeneratorOptions());
                } finally {
                    fileStream.Close();
                }
            }
            return(res);
        }
コード例 #7
0
        /******/

        void CheckCompilerErrors(CompilerResults results)
        {
            if (results.NativeCompilerReturnValue == 0)
            {
                return;
            }

            string fileText = null;
            CompilerErrorCollection errors = results.Errors;
            CompilerError           ce     = (errors != null && errors.Count > 0) ? errors [0] : null;
            string inFile = (ce != null) ? ce.FileName : null;

            if (inFile != null && File.Exists(inFile))
            {
                using (StreamReader sr = File.OpenText(inFile)) {
                    fileText = sr.ReadToEnd();
                }
            }
            else
            {
                StringWriter writer = new StringWriter();
                provider.CreateGenerator().GenerateCodeFromCompileUnit(unit, writer, null);
                fileText = writer.ToString();
            }
            throw new CompilationException(parser.InputFile, errors, fileText);
        }
コード例 #8
0
        public static void GenerateProjectCode(string file, CodeDomProvider provider, GenerationOptions options, ProjectBackend[] projects)
        {
            CodeGenerationResult res = GenerateProjectCode(options, projects);

            ICodeGenerator gen      = provider.CreateGenerator();
            string         basePath = Path.GetDirectoryName(file);

            foreach (SteticCompilationUnit unit in res.Units)
            {
                string fname;
                if (unit.Name.Length == 0)
                {
                    fname = file;
                }
                else
                {
                    fname = Path.Combine(basePath, unit.Name);
                }
                StreamWriter fileStream = new StreamWriter(fname);
                try {
                    gen.GenerateCodeFromCompileUnit(unit, fileStream, new CodeGeneratorOptions());
                } finally {
                    fileStream.Close();
                }
            }
        }
コード例 #9
0
    // Define the build provider implementation of the GenerateCode method.
    public override void GenerateCode(AssemblyBuilder assemBuilder)
    {
        // Generate a code compile unit, and add it to
        // the assembly builder.

        TextWriter tw = assemBuilder.CreateCodeFile(this);

        if (tw != null)
        {
            try
            {
                // Generate the code compile unit from the virtual path.
                CodeCompileUnit compileUnit = SampleClassGenerator.BuildCompileUnitFromPath(VirtualPath);

                // Generate the source for the code compile unit,
                // and write it to a file specified by the assembly builder.
                CodeDomProvider provider = assemBuilder.CodeDomProvider;
                provider.CreateGenerator().GenerateCodeFromCompileUnit(compileUnit, tw, null);
            }
            finally
            {
                tw.Close();
            }
        }
    }
コード例 #10
0
        public string GenerateCode(string projectName, string tableName,
                                   Dictionary <String, Type> columnMappings)
        {
            CodeDomProvider provider = CreateProvider("C#");

            System.CodeDom.Compiler.ICodeGenerator codeGenerator = null;

            System.CodeDom.Compiler.CodeGeneratorOptions codeGeneratorOptions =
                new CodeGeneratorOptions();
            codeGeneratorOptions.BlankLinesBetweenMembers = true;
            codeGeneratorOptions.BracingStyle             = "C";
            codeGeneratorOptions.IndentString             = "   "; // 3 spaces.

            codeGenerator = provider.CreateGenerator();

            System.Text.StringBuilder code         = new StringBuilder();
            System.IO.StringWriter    stringWriter = new StringWriter(code);

            CodeNamespace gencode = GenerateSkeleton(projectName, tableName, columnMappings);

            codeGenerator.GenerateCodeFromNamespace(gencode,
                                                    stringWriter, codeGeneratorOptions);

            return(stringWriter.ToString());
        }
コード例 #11
0
        void GenerateCode(HttpContext context, string langId)
        {
            context.Response.ContentType = "text/plain; charset=utf-8";
            CodeNamespace   codeNamespace = new CodeNamespace();
            CodeCompileUnit codeUnit      = new CodeCompileUnit();

            codeUnit.Namespaces.Add(codeNamespace);

            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

            foreach (ServiceDescription sd in GetDescriptions())
            {
                importer.AddServiceDescription(sd, null, null);
            }

            foreach (XmlSchema sc in GetSchemas())
            {
                importer.Schemas.Add(sc);
            }

            importer.Import(codeNamespace, codeUnit);

            if (langId == null || langId == "")
            {
                langId = "cs";
            }
            CodeDomProvider      provider  = GetProvider(langId);
            ICodeGenerator       generator = provider.CreateGenerator();
            CodeGeneratorOptions options   = new CodeGeneratorOptions();

            generator.GenerateCodeFromCompileUnit(codeUnit, context.Response.Output, options);
        }
コード例 #12
0
        public static string Generate(string inputFileContent, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeDomProvider codeProvider)
        {
            var dataSet = new DataSet();

            dataSet.ReadXmlSchema(inputFileContent);
            T.Generate(dataSet, mainNamespace, codeProvider.CreateGenerator());
            return(null);
        }
コード例 #13
0
        protected bool Supports(CodeDomProvider provider, GeneratorSupport support)
        {
#if WHIDBEY
            return(provider.Supports(support));
#else
            return((provider.CreateGenerator()).Supports(support));
#endif
        }
コード例 #14
0
 /// <summary>
 /// Creates an <c>ExtendedCodeProvider</c> using a <c>CodeDomProvider</c>.
 /// </summary>
 public ExtendedCodeProvider(CodeDomProvider provider)
 {
     if (provider == null)
     {
         throw new ArgumentNullException("provider");
     }
     Provider  = provider;
     Generator = provider.CreateGenerator();
 }
コード例 #15
0
        private CodeCompileUnit PrepareCodeGenerator()
        {
            _codeStream = new MemoryStream();
            _codeWriter = new StreamWriter(_codeStream);
            _generator  = _codeDomProvider.CreateGenerator(_codeWriter);
            CodeCompileUnit generationUnit = new CodeCompileUnit();

            return(generationUnit);
        }
コード例 #16
0
        private void WriteFile(string file, CodeTypeDeclaration resources, string language, bool isCSharp, IEnumerable <string> aliases)
        {
            CodeDomProvider provider = CodeDomProvider.CreateProvider(language);

            string code = null;

            using (var o = new StringWriter()) {
                var options = new CodeGeneratorOptions()
                {
                    BracingStyle = "C",
                    IndentString = "\t",
                };

                var ns = string.IsNullOrEmpty(Namespace)
                                        ? new CodeNamespace()
                                        : new CodeNamespace(Namespace);

                if (resources != null)
                {
                    ns.Types.Add(resources);
                }

                var unit = new CodeCompileUnit();
                unit.Namespaces.Add(ns);

                var resgenatt = new CodeAttributeDeclaration(new CodeTypeReference("Android.Runtime.ResourceDesignerAttribute", CodeTypeReferenceOptions.GlobalReference));
                resgenatt.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(Namespace.Length > 0 ? Namespace + ".Resource" : "Resource")));
                resgenatt.Arguments.Add(new CodeAttributeArgument("IsApplication", new CodePrimitiveExpression(IsApplication)));
                unit.AssemblyCustomAttributes.Add(resgenatt);

                // Add Pragma to disable warnings about no Xml documentation
                if (isCSharp)
                {
                    foreach (var alias in aliases)
                    {
                        provider.GenerateCodeFromStatement(new CodeSnippetStatement($"extern alias {alias};"), o, options);
                    }
                    provider.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit("#pragma warning disable 1591"), o, options);
                }

                provider.CreateGenerator(o).GenerateCodeFromCompileUnit(unit, o, options);

                // Add Pragma to re-enable warnings about no Xml documentation
                if (isCSharp)
                {
                    provider.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit("#pragma warning restore 1591"), o, options);
                }

                code = o.ToString();
            }

            if (MonoAndroidHelper.CopyIfStringChanged(code, file))
            {
                Log.LogDebugMessage($"Writing to: {file}");
            }
        }
コード例 #17
0
        protected virtual ICodeGenerator GetCodeWriter()
        {
            CodeDomProvider codeComProvider = CodeProvider;

            if (null != codeComProvider)
            {
                return(codeComProvider.CreateGenerator());
            }

            return(null);
        }
コード例 #18
0
        /// <summary>
        /// Method to get an ICodeGenerator with which this class can create code.
        /// </summary>
        /// <returns></returns>
        protected virtual ICodeGenerator GetCodeWriter()
        {
            CodeDomProvider codeDom = CodeProvider;

            if (codeDom != null)
            {
                return(codeDom.CreateGenerator());
            }

            return(null);
        }
コード例 #19
0
        public String ToCode(CodeCompileUnit compileunit, CodeDomProvider provider, IDomainMap domainMap)
        {
            StringBuilder      sb = new StringBuilder();
            StringWriter       sw = new StringWriter(sb);
            IndentedTextWriter tw = new IndentedTextWriter(sw, "    ");

            ICodeGenerator gen = provider.CreateGenerator(tw);

            gen.GenerateCodeFromCompileUnit(compileunit, tw,
                                            new CodeGeneratorOptions());

            string code = sb.ToString();


            if (domainMap != null)
            {
                foreach (ICodeMap codeMap in domainMap.CodeMaps)
                {
                    if (provider is CSharpCodeProvider && codeMap.CodeLanguage == CodeLanguage.CSharp)
                    {
                        code = GetDomainCodeMap(domainMap, codeMap) + code;
                    }
                    else if (provider is VBCodeProvider && codeMap.CodeLanguage == CodeLanguage.VB)
                    {
                        code = GetDomainCodeMap(domainMap, codeMap) + code;
                    }
                    //						if (provider is DelphiCodeProvider && codeMap.CodeLanguage == CodeLanguage.Delphi)
                    //						{
                    //							code = GetDomainCodeMap(code, classMap, codeMap) + code;
                    //						}
                }

                foreach (IClassMap classMap in domainMap.ClassMaps)
                {
                    foreach (ICodeMap codeMap in classMap.CodeMaps)
                    {
                        if (provider is CSharpCodeProvider && codeMap.CodeLanguage == CodeLanguage.CSharp)
                        {
                            code = InsertCodeMap(code, classMap, codeMap);
                        }
                        else if (provider is VBCodeProvider && codeMap.CodeLanguage == CodeLanguage.VB)
                        {
                            code = InsertCodeMap(code, classMap, codeMap);
                        }
//						if (provider is DelphiCodeProvider && codeMap.CodeLanguage == CodeLanguage.Delphi)
//						{
//							code = InsertCodeMap(code, classMap, codeMap);
//						}
                    }
                }
            }

            return(code);
        }
コード例 #20
0
ファイル: Generator.cs プロジェクト: AJLogan/DesignPatterns
        private void writeCode(CodeDomProvider provider, StreamWriter sw)
        {
            //Create a code generator
            ICodeGenerator generator = provider.CreateGenerator();

            //Default options are fine
            CodeGeneratorOptions options = new CodeGeneratorOptions();

            //Build the code and display it
            generator.GenerateCodeFromCompileUnit(compileUnit, sw, options);

            sw.Flush();
        }
コード例 #21
0
        protected virtual ICodeGenerator GetCodeWriter()
        {
            CodeDomProvider codeDom = CodeProvider;

            if (codeDom != null)
            {
#pragma warning disable 618 //backwards compat
                return(codeDom.CreateGenerator());

#pragma warning restore 618
            }

            return(null);
        }
コード例 #22
0
        public static string ToCode(CodeCompileUnit compileunit, CodeDomProvider provider)
        {
            StringBuilder      sb = new StringBuilder();
            StringWriter       sw = new StringWriter(sb);
            IndentedTextWriter tw = new IndentedTextWriter(sw, "    ");

            ICodeGenerator gen = provider.CreateGenerator(tw);

            gen.GenerateCodeFromCompileUnit(compileunit, tw,
                                            new CodeGeneratorOptions());

            string code = sb.ToString();

            return(code);
        }
コード例 #23
0
        private void CreateCodeGenerator(out ICodeGenerator codeGen, out string fileExtension)
        {
            Language language = WsdlProperties.Language;

            switch (language)
            {
            case Language.CS:
                codeProvider = new CSharpCodeProvider();
                break;

            case Language.VB:
                codeProvider = new VBCodeProvider();
                break;

            default:
            {
                if (language != Language.Custom)
                {
                    throw new Exception("Unknown language");
                }
                Type type = Type.GetType(WsdlProperties.CustomCodeDomProvider);
                if (type == null)
                {
                    throw new TypeLoadException("Type '" + WsdlProperties.CustomCodeDomProvider + "' is not found");
                }
                codeProvider = (CodeDomProvider)Activator.CreateInstance(type);
                break;
            }
            }
            if (codeProvider != null)
            {
                codeGen       = codeProvider.CreateGenerator();
                fileExtension = codeProvider.FileExtension;
                if (fileExtension == null)
                {
                    fileExtension = string.Empty;
                }
                else if ((fileExtension.Length > 0) && (fileExtension[0] != '.'))
                {
                    fileExtension = "." + fileExtension;
                }
            }
            else
            {
                fileExtension = ".src";
                codeGen       = null;
            }
        }
コード例 #24
0
        private void language_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            CodeProviderInfo info = (CodeProviderInfo)language.SelectedItem;

            CodeDomProvider provider = codeproviderFactory.GetProvider(info);

            StringWriter         writer = new StringWriter();
            CodeGeneratorOptions opts   = new CodeGeneratorOptions();

            opts.BracingStyle             = "C";
            opts.BlankLinesBetweenMembers = true;

            provider.CreateGenerator().GenerateCodeFromType(typeDecl, writer, opts);

            richTextBox1.Text = writer.GetStringBuilder().ToString();
        }
コード例 #25
0
        private string GenerateCode(CodeNamespace sourceCode)
        {
            CodeDomProvider provider             = CreateProvider();
            var             codeGeneratorOptions = new CodeGeneratorOptions
            {
                BlankLinesBetweenMembers = false,
                BracingStyle             = "C",
                IndentString             = "   "
            };

            ICodeGenerator codeGenerator = provider.CreateGenerator();
            var            code          = new StringBuilder();
            var            stringWriter  = new StringWriter(code);

            codeGenerator.GenerateCodeFromNamespace(sourceCode, stringWriter, codeGeneratorOptions);
            return(code.ToString());
        }
コード例 #26
0
        public String ToCodeFile(CodeCompileUnit compileunit, CodeDomProvider provider, string fileName)
        {
#if NET2
            String sourceFile;
            if (provider.FileExtension[0] == '.')
            {
                sourceFile = fileName + provider.FileExtension;
            }
            else
            {
                sourceFile = fileName + "." + provider.FileExtension;
            }

            IndentedTextWriter tw = new IndentedTextWriter(
                new StreamWriter(sourceFile, false), "    ");

            provider.GenerateCodeFromCompileUnit(compileunit, tw,
                                                 new CodeGeneratorOptions());

            tw.Close();

            return(sourceFile);
#else
            ICodeGenerator gen = provider.CreateGenerator();

            String sourceFile;
            if (provider.FileExtension[0] == '.')
            {
                sourceFile = fileName + provider.FileExtension;
            }
            else
            {
                sourceFile = fileName + "." + provider.FileExtension;
            }

            IndentedTextWriter tw = new IndentedTextWriter(
                new StreamWriter(sourceFile, false), "    ");

            gen.GenerateCodeFromCompileUnit(compileunit, tw,
                                            new CodeGeneratorOptions());

            tw.Close();

            return(sourceFile);
#endif
        }
コード例 #27
0
        public void GenerateCode(
            string outputPath,
            NamespaceDeclaration ns
            )
        {
            if (ns == null)
            {
                throw new ArgumentNullException("ns");
            }

            ICodeGenerator gen = provider.CreateGenerator();

            foreach (DictionaryEntry de in ns.ToCodeDom())
            {
                FileName      key = (FileName)de.Key;
                CodeNamespace nms = (CodeNamespace)de.Value;

                // creating directory
                string path;
                if (createFolders)
                {
                    path = PathFromNamespace(outputPath, key.Namespace);
                }
                else
                {
                    path = outputPath;
                }

                string filePath = Path.Combine(path, key.Name + "." + this.Provider.FileExtension);

                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    // add copyright
                    nms.Comments.Add(new CodeCommentStatement(copyright));

                    // Create a TextWriter to a StreamWriter to an output file.
                    IndentedTextWriter tw = new IndentedTextWriter(writer, this.tab);
                    // Generate source code using the code generator.
                    gen.GenerateCodeFromNamespace(nms, tw, options);

                    // log
                    this.OnFileCreated(new StringEventArgs(filePath));
                }
            }
        }
コード例 #28
0
        //////////////////////////////////Генерация////////////////////////////////////
        private static void GENERATE_CODE_SERVER(CodeDomProvider provider,
                                                 CodeCompileUnit compileunit)
        {
            String sourceFile;

            ///////////////Файл "TEST_CODEDOM.cs"//////////////////////////////////////
            sourceFile = "TEST_CODEDOM." + provider.FileExtension;
            /////////Получаем ICodeGenerator от CodeDomProvider////////////////////////
            ICodeGenerator gen = provider.CreateGenerator();
            ///Создаем IndentedTextWriter, построенный с StreamWriter исходного кода///
            IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter(sourceFile,
                                                                            false), "    ");

            //////Генерируем исходный код, используя кодо-генератор////////////////////
            gen.GenerateCodeFromCompileUnit(compileunit, tw, new CodeGeneratorOptions());
            //////////////////Закрываем выходной файл//////////////////////////////////
            tw.Close();
        }
コード例 #29
0
        public string Convert(XamlReader reader, CodeDomProvider cscProvider)
        {
            MainCodeClassName = string.Empty;
            StringBuilder sb           = new StringBuilder();
            StringWriter  stringWriter = new StringWriter(sb);

            NamespacesToUse = new SortedDictionary <string, object>();

            // TODO: XamlXmlReader can sometimes be null, if there is misformed XML in the first sections of XML
            _schemaContext = reader != null ? reader.SchemaContext : new XamlSchemaContext();
            CodeDomDomWriter codeDomDomWriter = new CodeDomDomWriter(_schemaContext);

            // Load XAML into a specialized XAML DOM, for analysis and processing
            Debug.WriteLine("Building codeDOM from XAML...");
            while (reader.Read())
            {
                codeDomDomWriter.WriteNode(reader);
            }
            Debug.WriteLine("codeDOM complete.");
            CodeDomObjectNode objectNode = (CodeDomObjectNode)codeDomDomWriter.Result;

            //DumpNodeTree(objectNode);

            // Initialize CodeDom constructs
            ICodeGenerator cscg = cscProvider.CreateGenerator(stringWriter);

            ccu = new CodeCompileUnit();
            CodeNamespace cns = new CodeNamespace();

            ccu.Namespaces.Add(cns);

            // Go process XAML DOM
            CodeMemberMethod initMethod = CreateInitializeMethod(cns, objectNode);

            GenerateUsings(cns, objectNode);
            CreateClass(cns, objectNode, initMethod);
            AddPublicObjectMembers();

            // Create code from codeDOM
            cscg.GenerateCodeFromCompileUnit(ccu, stringWriter, new CodeGeneratorOptions());
            string returnText = sb.ToString();

            return(returnText);
        }
コード例 #30
0
        /// <include file='doc\BaseCompiler.uex' path='docs/doc[@for="BaseCompiler.GetCompiledType"]/*' />
        /// <devdoc>
        ///
        /// </devdoc>
        protected Type GetCompiledType()
        {
            // Instantiate an ICompiler based on the language
            CodeDomProvider codeProvider = (CodeDomProvider)HttpRuntime.CreatePublicInstance(
                CompilerInfo.CompilerType);
            ICodeCompiler compiler = codeProvider.CreateCompiler();

            _generator = codeProvider.CreateGenerator();

            _stringResourceBuilder = new StringResourceBuilder();

            // Build the data tree that needs to be compiled
            BuildSourceDataTree();

            // Create the resource file if needed
            if (_stringResourceBuilder.HasStrings)
            {
                string resFileName = _compilParams.TempFiles.AddExtension("res");
                _stringResourceBuilder.CreateResourceFile(resFileName);
                CompilParams.Win32Resource = resFileName;
            }

            // Compile into an assembly
            CompilerResults results;

            try {
                results = codeProvider.CreateCompiler().CompileAssemblyFromDom(_compilParams, _sourceData);
            }
            catch (Exception e) {
                throw new HttpUnhandledException(HttpRuntime.FormatResourceString(SR.CompilationUnhandledException, codeProvider.GetType().FullName), e);
            }

            string fullTypeName = _sourceDataNamespace.Name + "." + _sourceDataClass.Name;

            ThrowIfCompilerErrors(results, codeProvider, _sourceData, null, null);

            // After the compilation, update the list of assembly dependencies to be what
            // the assembly actually needs.
            Parser.AssemblyDependencies = Util.GetReferencedAssembliesHashtable(
                results.CompiledAssembly);

            // Get the type from the assembly
            return(results.CompiledAssembly.GetType(fullTypeName, true /*throwOnFail*/));
        }