public void CreateGenerator_ReturnsSame()
        {
            CSharpCodeProvider provider = new CSharpCodeProvider();

#pragma warning disable 0618
            Assert.Same(provider.CreateGenerator(), provider.CreateGenerator());
#pragma warning restore 0618
        }
        public void Ctor_Default()
        {
            CSharpCodeProvider provider = new CSharpCodeProvider();

#pragma warning disable 0618
            Assert.NotNull(provider.CreateGenerator());
            Assert.Same(provider.CreateGenerator(), provider.CreateCompiler());
#pragma warning restore 0618
        }
        public void Ctor_IDictionaryStringString(IDictionary <string, string> providerOptions)
        {
            CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);

#pragma warning disable 0618
            Assert.NotNull(provider.CreateGenerator());
            Assert.Same(provider.CreateGenerator(), provider.CreateCompiler());
#pragma warning restore 0618
        }
        private StringBuilder BuildClass(List <Guid> resGuidsToTake)
        {
            // need a string to put the code into
            var source = new StringBuilder();
            var sw     = new StringWriter(source);
            //Declare your provider and generator
            var            codeProvider  = new CSharpCodeProvider();
            ICodeGenerator generator     = codeProvider.CreateGenerator(sw);
            var            codeOpts      = new CodeGeneratorOptions();
            var            codeNamespace = new CodeNamespace("WebHookData.DataAccess.ExternalAPI");

            codeNamespace.Imports.Add(new CodeNamespaceImport(nameof(System)));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Linq"));
            //Build the class declaration and member variables
            var classDeclaration = new CodeTypeDeclaration
            {
                IsClass    = true,
                Name       = "ProjectOnlineAccessService",
                Attributes = MemberAttributes.Public,
                IsPartial  = true
            };
            CodeMemberMethod method = BuildMethod(resGuidsToTake);

            classDeclaration.Members.Add(method);
            //write code
            codeNamespace.Types.Add(classDeclaration);
            generator.GenerateCodeFromNamespace(codeNamespace, sw, codeOpts);
            // cleanup
            sw.Flush();
            sw.Close();
            return(source);
        }
Пример #5
0
    static void CompileLocations(string outputFile)
    {
        CodeCompileUnit unit = new CodeCompileUnit();
        CodeNamespace   ns   = new CodeNamespace("Desklet.Weather");

        unit.Namespaces.Add(ns);
        ns.Imports.Add(new CodeNamespaceImport("System"));
        ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));

        MainClass = new CodeTypeDeclaration("Locations");
        MainClass.TypeAttributes = TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Public;
        MainClass.IsPartial      = true;
        ns.Types.Add(MainClass);

        CodeMemberMethod buildData = new CodeMemberMethod();

        buildData.Name = "BuildData";
        GenerateBuildData(buildData);
        MainClass.Members.Add(buildData);

        CodeDomProvider provider = new CSharpCodeProvider();
        ICodeGenerator  gen      = provider.CreateGenerator();

        TextWriter tw = new IndentedTextWriter(new StreamWriter(outputFile, false), "\t");

        gen.GenerateCodeFromCompileUnit(unit, tw, new CodeGeneratorOptions());
        tw.Close();
    }
Пример #6
0
        public void Deny_Unrestricted()
        {
            CSharpCodeProvider csprov = new CSharpCodeProvider();

            Assert.AreEqual("cs", csprov.FileExtension, "FileExtension");
            Assert.IsNotNull(csprov.CreateCompiler(), "CreateCompiler");
            Assert.IsNotNull(csprov.CreateGenerator(), "CreateGenerator");
            try {
                Assert.IsNotNull(csprov.GetConverter(typeof(string)), "GetConverter");
            }
            catch (NotImplementedException) {
                // mono
            }
#if NET_2_0
            CodeTypeMember       ctm = new CodeTypeMember();
            StringWriter         sw  = new StringWriter();
            CodeGeneratorOptions cgo = new CodeGeneratorOptions();
            try {
                csprov.GenerateCodeFromMember(ctm, sw, cgo);
            }
            catch (NotImplementedException) {
                // mono
            }
#endif
        }
        private void UpdateCodeWindows()
        {
            TabControl           tc = this.host.GetService(typeof(TabControl)) as TabControl;
            CodeGeneratorOptions o  = new CodeGeneratorOptions();

            o.BlankLinesBetweenMembers = true;
            o.BracingStyle             = "C";
            o.ElseOnClosing            = false;
            o.IndentString             = "    ";
            StringWriter       sw = new StringWriter();
            CSharpCodeProvider cs = new CSharpCodeProvider();

            cs.CreateGenerator().GenerateCodeFromCompileUnit(this.codeCompileUnit, sw, o);
            sw.Close();
            sw = new StringWriter();
            VBCodeProvider vb = new VBCodeProvider();

            vb.CreateGenerator().GenerateCodeFromCompileUnit(this.codeCompileUnit, sw, o);
            sw.Close();
            sw = new StringWriter();
            XmlTextWriter xtw = new XmlTextWriter(sw);

            xtw.Formatting = Formatting.Indented;
            this.xmlDocument.WriteTo(xtw);
            string cleanup = sw.ToString().Replace("<DOCUMENT_ELEMENT>", "").Replace("</DOCUMENT_ELEMENT>", "");

            sw.Close();
        }
Пример #8
0
        static void Main(string[] args)
        {
            Console.WriteLine("What string do you want the custom program to display?");
            string message = Console.ReadLine();

            Console.WriteLine("How many times do you want the program to display this message?");
            int             nDisplays = int.Parse(Console.ReadLine());
            CodeCompileUnit unit      = GenerateProgram(message, nDisplays);

            // Set up options for source code style
            CodeGeneratorOptions opts = new CodeGeneratorOptions();

            opts.BracingStyle = "C";
            opts.IndentString = "\t";

            // Create code generator and write code file
            CSharpCodeProvider cscp = new CSharpCodeProvider();
            ICodeGenerator     gen  = cscp.CreateGenerator();
            StreamWriter       sw   = new StreamWriter("MyCode.cs");

            gen.GenerateCodeFromCompileUnit(unit, sw, opts);
            sw.Close();

            CompilerParameters compilerParams = new CompilerParameters();

            compilerParams.GenerateExecutable = true;
            compilerParams.OutputAssembly     = "MyCode.exe";
            ICodeCompiler compiler = cscp.CreateCompiler();

            compiler.CompileAssemblyFromFile(compilerParams, "MyCode.cs");
        }
Пример #9
0
        public Interpreter()
        {
            this.varTable = new HashtableWithItemGetterHook(this);
            AddNamespace("System");
            AddNamespace("System.Collections");
            AddReference("System.dll");  // Also works on Mono
            SetValue("interpreter", this);
            SetValue("_", this);
            Utils.interpreter = this;
            string fullExecutablePath = FullExecutablePath();

            if (File.Exists(fullExecutablePath))
            {
                AddReference(fullExecutablePath);
            }

            string localNamespace = typeof(Interpreter).Namespace;

            if (!string.IsNullOrEmpty(localNamespace))
            {
                AddNamespace(localNamespace);
            }

            prov = new CSharpCodeProvider();
            using (StringWriter stringWriter = new StringWriter())
            {
                gen = prov.CreateGenerator(stringWriter);
            }
        }
Пример #10
0
        private string GenerateAssemblyInfo(string assemblyName)
        {
            var sb = new StringBuilder();

            using (var sw = new StringWriter(sb))
            {
                var codeDomProvider = new CSharpCodeProvider();
                var codeGenerator   = codeDomProvider.CreateGenerator(sw);
                var compileUnit     = new CodeCompileUnit();
                var time            = DateTime.Now;
                var build           = string.Format("{0:yy}{1}", time, time.DayOfYear);
                var revision        = string.Format("{0:HHmm}", time);

                compileUnit.AssemblyCustomAttributes.Add(typeof(System.Reflection.AssemblyTitleAttribute), assemblyName);
                compileUnit.AssemblyCustomAttributes.Add(typeof(System.Reflection.AssemblyDescriptionAttribute), "");
                compileUnit.AssemblyCustomAttributes.Add(typeof(System.Reflection.AssemblyConfigurationAttribute), "");
                compileUnit.AssemblyCustomAttributes.Add(typeof(System.Reflection.AssemblyCompanyAttribute), "NTREEV SOFT");
                compileUnit.AssemblyCustomAttributes.Add(typeof(System.Reflection.AssemblyProductAttribute), assemblyName);
                compileUnit.AssemblyCustomAttributes.Add(typeof(System.Reflection.AssemblyCopyrightAttribute), $"Copyright © NTREEV SOFT {DateTime.Now.Year}");
                compileUnit.AssemblyCustomAttributes.Add(typeof(System.Reflection.AssemblyTrademarkAttribute), "");
                compileUnit.AssemblyCustomAttributes.Add(typeof(System.Reflection.AssemblyCultureAttribute), "");

                compileUnit.AssemblyCustomAttributes.Add(typeof(System.Reflection.AssemblyVersionAttribute), $"{CremaSchema.MajorVersion}.{CremaSchema.MinorVersion}.0.0");
                compileUnit.AssemblyCustomAttributes.Add(typeof(System.Reflection.AssemblyFileVersionAttribute), $"{CremaSchema.MajorVersion}.{CremaSchema.MinorVersion}.{build}.{revision}");
                compileUnit.AssemblyCustomAttributes.Add(typeof(System.Reflection.AssemblyInformationalVersionAttribute), $"{CremaSchema.MajorVersion}.{CremaSchema.MinorVersion}.{build}.{revision}");

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

            return(sb.ToString());
        }
Пример #11
0
        public TypedDataSetGeneratorTest()
        {
            CodeDomProvider p = new CSharpCodeProvider();

            gen      = p.CreateGenerator();
            compiler = p.CreateCompiler();
        }
Пример #12
0
 /// <summary>
 /// 生成并输出类文件.
 /// </summary>
 /// <param name="codeClass">用于生成类的一些基本信息.</param>
 /// <param name="filePath">保存文到该文件.</param>
 /// <param name="overwrite">若源代码文件存在时是否覆盖.</param>
 public void WriteTo(string filePath, bool overwrite = false)
 {
     if (File.Exists(filePath))
     {
         if (overwrite)
         {
             File.Delete(filePath);
         }
         else
         {
             return;
         }
     }
     using (StreamWriter codeWriter = new StreamWriter(File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite)))
     {
         CSharpCodeProvider   provider  = new CSharpCodeProvider();
         ICodeGenerator       generator = provider.CreateGenerator(codeWriter);
         CodeGeneratorOptions options   = new CodeGeneratorOptions
         {
             BlankLinesBetweenMembers = true,
             BracingStyle             = "C"
         };
         // 生成 using 引用
         generator.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit(BuildCompileUnit()),
                                               codeWriter, options);
         // 将命名空间中的代码生成到文件.
         generator.GenerateCodeFromNamespace(codeNamespace, codeWriter, options);
     }
     if (ResetOnAfterWrite)
     {
         codeNamespace = null;
     }
 }
        public Assembly CompileSource(params string[] references)
        {
            try
            {
                //CodeDomProvider cpd = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } });
                CodeDomProvider      cpd           = new CSharpCodeProvider();
                ICodeGenerator       codeGenerator = cpd.CreateGenerator();
                StringBuilder        generateCode  = new StringBuilder();
                StringWriter         codeWriter    = new StringWriter(generateCode);
                CodeGeneratorOptions options       = new CodeGeneratorOptions
                {
                    BracingStyle = "C"
                };
                codeGenerator.GenerateCodeFromCompileUnit(TargetUnit, codeWriter, options);
                string thisCode = generateCode.ToString();

                CompilerParameters cp = new CompilerParameters();
                foreach (string refer in references)
                {
                    cp.ReferencedAssemblies.Add(refer);
                }
                cp.GenerateExecutable = false;

                CompilerResults cr = cpd.CompileAssemblyFromSource(cp, thisCode);
                return(cr.CompiledAssembly);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return(null);
        }
Пример #14
0
        /// <summary>
        /// Builds the class
        /// </summary>
        private void BuildClass()
        {
            // need a string to put the code into
            _source = new StringBuilder();
            var sw = new StringWriter(_source);

            //Declare your provider and generator
            var codeProvider = new CSharpCodeProvider();
            var generator    = codeProvider.CreateGenerator(sw);
            var codeOpts     = new CodeGeneratorOptions();


            //Setup the namespace and imports
            var myNamespace = new CodeNamespace("IndiaTango");

            myNamespace.Imports.Add(new CodeNamespaceImport("System"));
            myNamespace.Imports.Add(new CodeNamespaceImport("System.Linq"));
            myNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            myNamespace.Imports.Add(new CodeNamespaceImport("IndiaTango.Models"));

            //Build the class declaration and member variables
            var classDeclaration = new CodeTypeDeclaration {
                IsClass = true, Name = "Calculator", Attributes = MemberAttributes.Public
            };

            //default constructor
            var defaultConstructor = new CodeConstructor {
                Attributes = MemberAttributes.Public
            };

            defaultConstructor.Comments.Add(new CodeCommentStatement("Default Constructor for class", true));
            classDeclaration.Members.Add(defaultConstructor);

            //Our Calculate Method
            var myMethod = new CodeMemberMethod {
                Name = "ApplyFormula", ReturnType = new CodeTypeReference(typeof(KeyValuePair <Sensor, SensorState>))
            };

            myMethod.Comments.Add(new CodeCommentStatement("Apply a formula across a dataset", true));
            myMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(List <SensorVariable>)), "sensorVariables"));
            myMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(SensorVariable)), "variableAssignedTo"));
            myMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(DateTime)), "startTime"));
            myMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(DateTime)), "endTime"));
            myMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(bool)), "skipMissingValues"));
            myMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(ChangeReason)), "reason"));
            myMethod.Attributes = MemberAttributes.Public;

            //Add the user specified code
            myMethod.Statements.Add(new CodeSnippetExpression(_loopCode));

            myMethod.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("new KeyValuePair<Sensor,SensorState>(variableAssignedTo.Sensor,state)")));
            classDeclaration.Members.Add(myMethod);

            //write code
            myNamespace.Types.Add(classDeclaration);
            generator.GenerateCodeFromNamespace(myNamespace, sw, codeOpts);
            sw.Flush();
            sw.Close();
        }
Пример #15
0
        public static String GenerateFullClass(ICollection <String> references, ICollection <String> imports, String CodeNamespace, String className, string methodBody, String method = "Method")
        {
            CodeCompileUnit unit = new CodeCompileUnit();

            if (references != null)
            {
                foreach (var item in references)
                {
                    unit.ReferencedAssemblies.Add(item);
                }
            }

            CodeNamespace customEntityRoot = new CodeNamespace(CodeNamespace);    //Create a namespace

            unit.Namespaces.Add(customEntityRoot);

            if (imports != null)
            {
                foreach (var item in imports)
                {
                    customEntityRoot.Imports.Add(new CodeNamespaceImport(item));
                }
            }

            CodeTypeDeclaration derived = new CodeTypeDeclaration(className);

            customEntityRoot.Types.Add(derived);

            CodeConstructor derivedClassConstructor = new CodeConstructor();

            derivedClassConstructor.Attributes = MemberAttributes.Public;

            derived.Members.Add(derivedClassConstructor);


            CodeMemberMethod derivedMethod = new CodeMemberMethod();

            derivedMethod.Attributes = MemberAttributes.Public;
            derivedMethod.Name       = method;
            derivedMethod.ReturnType = new CodeTypeReference(typeof(void));

            CodeSnippetStatement code = new CodeSnippetStatement(methodBody);

            derivedMethod.Statements.Add(code);
            derived.Members.Add(derivedMethod);

            CSharpCodeProvider codeProvider  = new CSharpCodeProvider();
            ICodeGenerator     codeGenerator = codeProvider.CreateGenerator();

            StringBuilder        generatedCode = new StringBuilder();
            StringWriter         codeWriter    = new StringWriter(generatedCode);
            CodeGeneratorOptions options       = new CodeGeneratorOptions();

            options.BracingStyle = "C";
            codeGenerator.GenerateCodeFromCompileUnit(unit, codeWriter, options);
            return(generatedCode.ToString());
        }
Пример #16
0
        public static void GenerateCode(CodeNamespace ns)
        {
            CodeDomProvider provider = new CSharpCodeProvider();

            using (StreamWriter s = new StreamWriter("Auto.cs", false))
            {
                provider.CreateGenerator().GenerateCodeFromNamespace(ns, s, new CodeGeneratorOptions());
            }
        }
        /// <summary>
        /// Main driving routine for building a class
        /// </summary>
        private string BuildClass()
        {
            this.m_expression = RefineEvaluationString(this.m_expression);
            this.m_expression = this.m_expression.Replace("SE", "se").Replace("Se", "se");
            this.m_expression = ConvertToIf(this.m_expression).Replace("se", string.Empty);


            // need a string to put the code into
            StringBuilder source = new StringBuilder();

            using (StringWriter sw = new StringWriter(source))
            {
                //Declare your provider and generator
                CSharpCodeProvider   codeProvider = new CSharpCodeProvider();
                ICodeGenerator       generator    = codeProvider.CreateGenerator(sw);
                CodeGeneratorOptions codeOpts     = new CodeGeneratorOptions();

                CodeNamespace myNamespace = new CodeNamespace("ExpressionEvaluator");
                myNamespace.Imports.Add(new CodeNamespaceImport("System"));
                myNamespace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));

                //Build the class declaration and member variables
                CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration();
                classDeclaration.IsClass    = true;
                classDeclaration.Name       = "Calculator";
                classDeclaration.Attributes = MemberAttributes.Public;
                classDeclaration.Members.Add(FieldVariable("answer", typeof(double), MemberAttributes.Private));

                //default constructor
                CodeConstructor defaultConstructor = new CodeConstructor();
                defaultConstructor.Attributes = MemberAttributes.Public;
                defaultConstructor.Comments.Add(new CodeCommentStatement("Default Constructor for class", true));
                defaultConstructor.Statements.Add(new CodeSnippetStatement("//TODO: implement default constructor"));
                classDeclaration.Members.Add(defaultConstructor);

                //property
                classDeclaration.Members.Add(this.MakeProperty("Answer", "answer", typeof(double)));

                //Our Calculate Method
                CodeMemberMethod myMethod = new CodeMemberMethod();
                myMethod.Name       = "Calculate";
                myMethod.ReturnType = new CodeTypeReference(typeof(double));
                myMethod.Comments.Add(new CodeCommentStatement("Calculate an expression", true));
                myMethod.Attributes = MemberAttributes.Public;
                myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("Answer"), new CodeSnippetExpression(this.m_expression)));
                myMethod.Statements.Add(
                    new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Answer")));
                classDeclaration.Members.Add(myMethod);
                //write code
                myNamespace.Types.Add(classDeclaration);
                generator.GenerateCodeFromNamespace(myNamespace, sw, codeOpts);
                sw.Flush();
                sw.Close();
            }
            return(source.ToString());
        }
Пример #18
0
        static void Main(string[] args)
        {
            // Prompt for target language.
            Console.Write("Do you want to generate C# or VB .NET code? ");
            syntaxTarget = Console.ReadLine();

            // Get ICodeGenerator interface.
            switch (syntaxTarget.ToUpper())
            {
            case "C#":
            case "CSharp":
            case "CS":
                syntaxTarget = "cs";
                CSharpCodeProvider cdp = new CSharpCodeProvider();
                itfCG = cdp.CreateGenerator();
                itfCC = cdp.CreateCompiler();
                break;

            case "VB .NET":
            case "VB.NET":
            case "VB":
                syntaxTarget = "vb";
                VBCodeProvider vbdp = new VBCodeProvider();
                itfCG = vbdp.CreateGenerator();
                itfCC = vbdp.CreateCompiler();
                break;

            default:
                Console.WriteLine("Sorry...can't do it...");
                syntaxTarget = null;
                break;
            }

            // Only proceed if they picked a valid language
            // supported by System.CodeDOM.
            if (syntaxTarget != null)
            {
                // Now create the file and generate the code!
                TextWriter txtWriter = CreateFile(syntaxTarget);
                PopulateNamespace(itfCG, txtWriter);
                txtWriter.Close();
                Console.WriteLine("Done!");

                // Now compile the code into a .NET DLL.
                Console.WriteLine("Compiling code...");
                CompileCode(itfCC, syntaxTarget);

                // Now launch the application!
                Console.Write("Enter your message: ");
                string msg = Console.ReadLine();
                LoadAndRunAsm(msg);
                Console.WriteLine("Thanks for playing...");
            }
        }
Пример #19
0
        private void GenerateAssemblerSource()
        {
            CSharpCodeProvider   csp = new CSharpCodeProvider();
            CodeGeneratorOptions cop = new CodeGeneratorOptions();

            cop.BracingStyle = "C";
            StreamWriter   sw  = File.CreateText(m_context.AssemblerGenerationOptions.OutputFile);
            ICodeGenerator gen = csp.CreateGenerator(sw);

            gen.GenerateCodeFromNamespace(m_namespace, sw, cop);
            sw.Close();
        }
Пример #20
0
        public String GetCode()
        {
            CSharpCodeProvider codeProvider  = new CSharpCodeProvider();
            ICodeGenerator     codeGenerator = codeProvider.CreateGenerator();

            StringBuilder        generatedCode = new StringBuilder();
            StringWriter         codeWriter    = new StringWriter(generatedCode);
            CodeGeneratorOptions options       = new CodeGeneratorOptions();

            options.BracingStyle = "C";
            codeGenerator.GenerateCodeFromCompileUnit(CodeCompileUnit, codeWriter, options);
            return(generatedCode.ToString());
        }
        public static System.Reflection.Assembly CreateAssemblyFromDataTable(DataTable DataValues)
        {
            System.Random rnd = new Random();
            if (DataValues.TableName == null || DataValues.TableName == "")
            {
                DataValues.TableName = rnd.Next().ToString();
            }
            object result = null;

            CodeTypeDeclaration classDec = new CodeTypeDeclaration(DataValues.TableName);

            classDec.IsClass = true;


            CodeConstructor constructor = new CodeConstructor();

            constructor.Attributes = MemberAttributes.Public;
            classDec.Members.Add(classDec);


            foreach (System.Data.DataColumn col in DataValues.Columns)
            {
                AddPropertyAndField(classDec, col.DataType, "", col.ColumnName);
            }

            AddPropertyAndField(classDec, null, "System.Collections.Generic.List<" + DataValues.TableName + ">", "ListOf" + DataValues.TableName);

            using (CSharpCodeProvider provider = new CSharpCodeProvider())
            {
                ICodeGenerator generator = provider.CreateGenerator();
                CodeNamespace  ns        = new CodeNamespace("Terminals.Generated");
                ns.Types.Add((CodeTypeDeclaration)classDec);
                CodeGeneratorOptions options = new CodeGeneratorOptions();
                //options.BlankLinesBetweenMembers = true;
                string filename = System.IO.Path.GetTempFileName();
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, false))
                {
                    generator.GenerateCodeFromNamespace(ns, sw, options);

                    ICodeCompiler icc = provider.CreateCompiler();

                    CompilerParameters compileParams = new CompilerParameters();
                    compileParams.GenerateExecutable = false;
                    compileParams.GenerateInMemory   = true;

                    return(icc.CompileAssemblyFromSource(compileParams, System.IO.File.ReadAllText(filename)).CompiledAssembly);
                }
            }
            return(null);
        }
Пример #22
0
	static void Main(string[] args)
	{
		int namespaces = 10;
		int classesPerNamespace = 10;
		int methodsPerClass = 10;

		CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

		for (int i = 0; i < namespaces; ++i)
		{
			CodeNamespace codeNamespace = new CodeNamespace();
			codeCompileUnit.Namespaces.Add(codeNamespace);
			codeNamespace.Name = "Namespace" + i;

			for (int j = 0; j < classesPerNamespace; ++j)
			{
				CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration();
				codeNamespace.Types.Add(codeTypeDeclaration);
				codeTypeDeclaration.Name = "Class" + j;
				codeTypeDeclaration.TypeAttributes = TypeAttributes.Public;
				
				codeTypeDeclaration.Comments.Add(
					new CodeCommentStatement(
						"<summary>This is a summary.</summary>",
						true
					)
				);

				for (int k = 0; k < methodsPerClass; ++k)
				{
					CodeMemberMethod codeMemberMethod = new CodeMemberMethod();
					codeTypeDeclaration.Members.Add(codeMemberMethod);
					codeMemberMethod.Name = "Method" + k;
					codeMemberMethod.Attributes = MemberAttributes.Public;

					codeMemberMethod.Comments.Add(
						new CodeCommentStatement(
							"<summary>This is a summary.</summary>",
							true
						)
					);
				}
			}
		}

		CodeDomProvider codeDomProvider = new CSharpCodeProvider();
		ICodeGenerator codeGenerator = codeDomProvider.CreateGenerator();
		CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions();
		codeGenerator.GenerateCodeFromCompileUnit(codeCompileUnit, Console.Out, codeGeneratorOptions);
	}
Пример #23
0
        protected void OptionallyWriteCodeToDisk(string codeOutputFilename, CodeCompileUnit codeCompileUnit, CSharpCodeProvider provider)
        {
            if (codeOutputFilename != "")
            {
                TextWriter writer = File.CreateText(Path.Combine(MyDirectory, codeOutputFilename));

                ICodeGenerator       codeGenerator = provider.CreateGenerator(writer);
                CodeGeneratorOptions options       = GetCodeGeneratorOptions();

                codeGenerator.GenerateCodeFromCompileUnit(codeCompileUnit, writer, options);

                writer.Close();
            }
        }
Пример #24
0
        //根据CodeDOM产生程序代码,代码文件就是GenCodeHello.cs
        private string GenerateCode(CodeCompileUnit code)
        {
            CSharpCodeProvider cprovider = new CSharpCodeProvider();
            //当然换个Microsoft.VisualBasic.VBCodeProvider就产生VB.NET的代码
            ICodeGenerator gen = cprovider.CreateGenerator();

            // 也可以直接用字符串来存储源代码
            StringBuilder sb   = new StringBuilder();
            StringWriter  strW = new StringWriter(sb);

            // 将源代码存储起来

            gen.GenerateCodeFromCompileUnit(code, strW, new CodeGeneratorOptions());

            return(sb.ToString());
        }
Пример #25
0
        /// <summary>
        /// Dynamic combile a assembely accord the wsdl content
        /// </summary>
        /// <param name="wsdlContent">Wsdl content In string</param>
        /// <returns>Assembly</returns>
        public Assembly AssemblyFromWsdl(string wsdlContent)
        {
            // Xml text reader
            StringReader       wsdlStringReader = new StringReader(wsdlContent);
            XmlTextReader      tr = new XmlTextReader(wsdlStringReader);
            ServiceDescription sd = ServiceDescription.Read(tr);

            tr.Close();

            // WSDL service description importer
            CodeNamespace cns = new CodeNamespace(m_NameSpace);

            ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();

            sdi.AddServiceDescription(sd, null, null);
            sdi.ProtocolName = m_ProtocolName;
            sdi.Import(cns, null);

            // source code generation
            CSharpCodeProvider cscp             = new CSharpCodeProvider();
            ICodeGenerator     icg              = cscp.CreateGenerator();
            StringBuilder      srcStringBuilder = new StringBuilder();
            StringWriter       sw = new StringWriter(srcStringBuilder);

            icg.GenerateCodeFromNamespace(cns, sw, null);
            m_SourceProxy = srcStringBuilder.ToString();
            sw.Close();

            // assembly compilation.
            CompilerParameters cp = new CompilerParameters();

            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Xml.dll");
            cp.ReferencedAssemblies.Add("System.Web.Services.dll");
            cp.GenerateExecutable      = false;
            cp.GenerateInMemory        = true;
            cp.IncludeDebugInformation = false;
            ICodeCompiler   icc = cscp.CreateCompiler();
            CompilerResults cr  = icc.CompileAssemblyFromSource(cp, m_SourceProxy);

            if (cr.Errors.Count > 0)
            {
                throw new Exception(string.Format("Build failed: {0} errors",
                                                  cr.Errors.Count));
            }
            return(m_Assembly = cr.CompiledAssembly);
        }
Пример #26
0
        public string GeneratorCode()
        {
            CSharpCodeProvider codeProvider  = new CSharpCodeProvider();
            ICodeGenerator     codeGenerator = codeProvider.CreateGenerator();

            StringBuilder generatedCode = new StringBuilder();

            using (StringWriter codeWriter = new StringWriter(generatedCode))
            {
                CodeGeneratorOptions options = new CodeGeneratorOptions();
                options.BracingStyle = "C";//Keep the braces on the line following the statement or declaration that they are associated with
                codeGenerator.GenerateCodeFromCompileUnit(unit, codeWriter, options);
            }

            this._code = generatedCode.ToString();
            return(_code);
        }
        public Interpreter()
        {
            this.varTable = new HashtableWithItemGetterHook(this);
            AddNamespace("System");
            AddNamespace("System.Collections");
            AddReference("System.dll");  // Also works on Mono
            SetValue("interpreter", this);
            SetValue("_", this);
            Utils.interpreter = this;
            string fullExecutablePath = FullExecutablePath();

            if (File.Exists(fullExecutablePath))
            {
                AddReference(fullExecutablePath);
            }

            string localNamespace = typeof(Interpreter).Namespace;

            if (!string.IsNullOrEmpty(localNamespace))
            {
                AddNamespace(localNamespace);
            }

            ConstructorInfo constructorInfo = typeof(CSharpCodeProvider).GetConstructor(
                new Type[] { typeof(System.Collections.Generic.Dictionary <string, string>) });

            if (constructorInfo == null)
            {
                prov = new CSharpCodeProvider();
            }
            else
            {
                System.Collections.Generic.Dictionary <string, string> providerOptions =
                    new System.Collections.Generic.Dictionary <string, string>();
                providerOptions.Add(
                    "CompilerVersion",
                    (Environment.Version < new Version("4.0.0.0")) ? "v3.5" : "v4.0");
                prov = (CSharpCodeProvider)constructorInfo.Invoke(new object[] { providerOptions });
            }

            using (StringWriter stringWriter = new StringWriter())
            {
                gen = prov.CreateGenerator(stringWriter);
            }
        }
Пример #28
0
        private string GenerateTypeCode(CodeGenerationInfo generationInfo)
        {
            var sb = new StringBuilder();

            using (var sw = new StringWriter(sb))
            {
                var codeDomProvider = new CSharpCodeProvider();
                var codeGenerator   = codeDomProvider.CreateGenerator(sw);
                var compileUnit     = new CodeCompileUnit();
                var codeNamespace   = new CodeNamespace(generationInfo.Namespace);
                codeNamespace.Imports.Add(new CodeNamespaceImport(generationInfo.ReaderNamespace));
                CremaTypeEnumCreator.Create(codeNamespace, generationInfo);
                compileUnit.Namespaces.Add(codeNamespace);
                codeGenerator.GenerateCodeFromCompileUnit(compileUnit, sw, this.options);
            }

            return(sb.ToString());
        }
Пример #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="NameSpace"></param>
        /// <param name="FolderPath"></param>
        /// <param name="ctd"></param>
        public static void WriteCsharpFile(String CompanyName, String DataAccessNamespaceSegment, String DatabaseName, String FolderPath, CodeTypeDeclaration ctd)
        {
            // [0] Build the Namespaces
            String CompanyNamespace    = CompanyName;
            String DataAccessNamespace = String.Format("{0}.{1}", CompanyName, DataAccessNamespaceSegment);
            String DataLayerNamespace  = String.Format("{0}.{1}.{2}", CompanyName, DataAccessNamespaceSegment, DatabaseName);


            CodeCompileUnit targetUnit = new CodeCompileUnit();
            CodeNamespace   gNamespace = new CodeNamespace(DataLayerNamespace);

            gNamespace.Imports.Add(new CodeNamespaceImport("System"));
            gNamespace.Imports.Add(new CodeNamespaceImport("System.IO"));
            gNamespace.Imports.Add(new CodeNamespaceImport("System.Linq"));
            gNamespace.Imports.Add(new CodeNamespaceImport("System.Collections"));
            gNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            gNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.ObjectModel"));
            gNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Specialized"));
            gNamespace.Imports.Add(new CodeNamespaceImport("System.Data"));
            gNamespace.Imports.Add(new CodeNamespaceImport("System.Xml"));
            gNamespace.Imports.Add(new CodeNamespaceImport("System.Xml.Linq"));
            gNamespace.Imports.Add(new CodeNamespaceImport(CompanyNamespace));
            gNamespace.Imports.Add(new CodeNamespaceImport(DataAccessNamespace));
            gNamespace.Imports.Add(new CodeNamespaceImport("System.Runtime.Serialization"));
            gNamespace.Types.Add(ctd);

            String NewCodeFileName = FolderPath + @"\" + ctd.Name + ".generated.cs";
            Stream s = File.Open(NewCodeFileName, FileMode.Create);

            StreamWriter sw = new StreamWriter(s);

            CSharpCodeProvider cscProvider = new CSharpCodeProvider();
            //VBCodeProvider cscProvider = new VBCodeProvider();
            ICodeGenerator cscg = cscProvider.CreateGenerator(sw);


            CodeGeneratorOptions cop = new CodeGeneratorOptions();

            // Create the Generated File
            cscg.GenerateCodeFromNamespace(gNamespace, sw, cop);
            sw.Close();
            s.Close();
        }
Пример #30
0
        /// <summary>
        /// Constructor for the XsdGen class.
        /// </summary>
        /// <param name="args">Command-line arguments passed to the program.</param>
        private XsdGen(string[] args)
        {
            this.ParseCommandlineArgs(args);

            // show usage information
            if (this.showHelp)
            {
                Console.WriteLine("usage: XsdGen.exe <schema>.xsd <outputFile> <namespace> [<commonNamespace>]");
                return;
            }

            // ensure that the schema file exists
            if (!File.Exists(this.xsdFile))
            {
                throw new ApplicationException(String.Format("Schema file does not exist: '{0}'.", this.xsdFile));
            }

            XmlSchema document = null;

            using (StreamReader xsdFileReader = new StreamReader(this.xsdFile))
            {
                document = XmlSchema.Read(xsdFileReader, new ValidationEventHandler(this.ValidationHandler));
            }

            CodeCompileUnit codeCompileUnit = StronglyTypedClasses.Generate(document, this.outputNamespace, this.commonNamespace);

            using (CSharpCodeProvider codeProvider = new CSharpCodeProvider())
            {
                ICodeGenerator generator = codeProvider.CreateGenerator();

                CodeGeneratorOptions options = new CodeGeneratorOptions();
                options.BlankLinesBetweenMembers = true;
                options.BracingStyle             = "C";
                options.IndentString             = "    ";

                using (StreamWriter csharpFileWriter = new StreamWriter(this.outFile))
                {
                    generator.GenerateCodeFromCompileUnit(codeCompileUnit, csharpFileWriter, options);
                }
            }
        }
Пример #31
0
    void CreateTestFile(String[] values)
    {
        StreamWriter       sw      = new StreamWriter("test.cs");
        CSharpCodeProvider cdp     = new CSharpCodeProvider();
        ICodeGenerator     cg      = cdp.CreateGenerator();
        CodeNamespace      cnspace = new CodeNamespace("N");

        cnspace.Imports.Add(new CodeNamespaceImport("System"));
        CodeTypeDeclaration co = new CodeTypeDeclaration("C");

        co.IsClass = true;
        cnspace.Types.Add(co);
        co.TypeAttributes = TypeAttributes.Public;
        CodeMemberMethod cmm = new CodeMemberMethod();

        cmm.Name       = "Main";
        cmm.ReturnType = null;
        cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
        CodeVariableDeclarationStatement cvar = new CodeVariableDeclarationStatement(typeof(String[]), "args", new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Environment"), "GetCommandLineArgs"));

        cmm.Statements.Add(cvar);
        cvar = new CodeVariableDeclarationStatement(typeof(Int32), "exitCode", new CodeSnippetExpression("0"));
        cmm.Statements.Add(cvar);
        String strArgLength         = (values.Length + 1).ToString();
        CodeConditionStatement ccs1 = new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("args.Length"), CodeBinaryOperatorType.IdentityInequality, new CodeSnippetExpression(strArgLength)), new CodeStatement [] { new CodeAssignStatement(new CodeVariableReferenceExpression("exitCode"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("exitCode"), CodeBinaryOperatorType.Add, new CodeSnippetExpression("1"))) });

        cmm.Statements.Add(ccs1);
        ccs1 = new CodeConditionStatement(new CodeSnippetExpression("!args[0].ToLower().EndsWith(\"test.exe\")"), new CodeStatement [] { new CodeAssignStatement(new CodeVariableReferenceExpression("exitCode"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("exitCode"), CodeBinaryOperatorType.Add, new CodeSnippetExpression("1"))) });
        cmm.Statements.Add(ccs1);
        for (int i = 0; i < values.Length; i++)
        {
            ccs1 = new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("args[" + (i + 1).ToString() + "]"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(values[i])), new CodeStatement [] { new CodeAssignStatement(new CodeVariableReferenceExpression("exitCode"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("exitCode"), CodeBinaryOperatorType.Add, new CodeSnippetExpression("1"))) });
            cmm.Statements.Add(ccs1);
        }
        cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("Environment.ExitCode"), new CodeVariableReferenceExpression("exitCode")));
        co.Members.Add(cmm);
        cg.GenerateCodeFromNamespace(cnspace, sw, null);
        sw.Flush();
        sw.Close();
    }
Пример #32
0
	static void CompileLocations (string outputFile)
	{
		CodeCompileUnit unit = new CodeCompileUnit ();
		CodeNamespace ns = new CodeNamespace ("Desklet.Weather");

		unit.Namespaces.Add (ns);
		ns.Imports.Add (new CodeNamespaceImport ("System"));
		ns.Imports.Add (new CodeNamespaceImport ("System.Collections.Generic"));

		MainClass = new CodeTypeDeclaration ("Locations");
		MainClass.TypeAttributes = TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Public;
		MainClass.IsPartial = true;
		ns.Types.Add (MainClass);

		CodeMemberMethod buildData = new CodeMemberMethod ();
		buildData.Name = "BuildData";
		GenerateBuildData (buildData);
		MainClass.Members.Add (buildData);
		
		CodeDomProvider provider = new CSharpCodeProvider ();
		ICodeGenerator gen = provider.CreateGenerator ();

		TextWriter tw = new IndentedTextWriter (new StreamWriter (outputFile, false), "\t");
		gen.GenerateCodeFromCompileUnit (unit, tw, new CodeGeneratorOptions ());
		tw.Close ();
	}
Пример #33
0
 void CreateTestFile(String[] values)
   {
   StreamWriter sw = new StreamWriter("test.cs");
   CSharpCodeProvider cdp = new CSharpCodeProvider();
   ICodeGenerator cg = cdp.CreateGenerator();
   CodeNamespace cnspace = new CodeNamespace("N");
   cnspace.Imports.Add(new CodeNamespaceImport("System"));
   CodeTypeDeclaration co = new CodeTypeDeclaration ("C");
   co.IsClass = true;
   cnspace.Types.Add (co);
   co.TypeAttributes  = TypeAttributes.Public;
   CodeMemberMethod cmm = new CodeMemberMethod();
   cmm.Name = "Main";
   cmm.ReturnType = null;
   cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
   CodeVariableDeclarationStatement cvar = new CodeVariableDeclarationStatement(typeof(String[]), "args", new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Environment"), "GetCommandLineArgs"));
   cmm.Statements.Add(cvar);  
   cvar = new CodeVariableDeclarationStatement(typeof(Int32), "exitCode", new CodeSnippetExpression("0"));
   cmm.Statements.Add(cvar);
   String strArgLength = (values.Length + 1).ToString();
   CodeConditionStatement ccs1 = new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("args.Length"), CodeBinaryOperatorType.IdentityInequality, new CodeSnippetExpression(strArgLength)), new CodeStatement []{new CodeAssignStatement(new CodeVariableReferenceExpression("exitCode"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("exitCode"), CodeBinaryOperatorType.Add, new CodeSnippetExpression("1")))});
   cmm.Statements.Add(ccs1);
   ccs1 = new CodeConditionStatement(new CodeSnippetExpression("!args[0].ToLower().EndsWith(\"test.exe\")"), new CodeStatement []{new CodeAssignStatement(new CodeVariableReferenceExpression("exitCode"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("exitCode"), CodeBinaryOperatorType.Add, new CodeSnippetExpression("1")))});
   cmm.Statements.Add(ccs1);
   for(int i=0; i<values.Length; i++){
   ccs1 = new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("args[" + (i+1).ToString() + "]"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(values[i])), new CodeStatement []{new CodeAssignStatement(new CodeVariableReferenceExpression("exitCode"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("exitCode"), CodeBinaryOperatorType.Add, new CodeSnippetExpression("1")))});
   cmm.Statements.Add(ccs1);
   }
   cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("Environment.ExitCode"), new CodeVariableReferenceExpression("exitCode")));
   co.Members.Add(cmm);
   cg.GenerateCodeFromNamespace(cnspace, sw, null);
   sw.Flush();
   sw.Close();		
   }