public void SaveAssembly()
        {
            myassembly = new CodeCompileUnit();
            myassembly.Namespaces.Add(mynamespace);
            CompilerParameters comparam = new CompilerParameters(new string[] { "mscorlib.dll" });

            comparam.ReferencedAssemblies.Add("System.dll");
            comparam.GenerateInMemory   = false;
            comparam.GenerateExecutable = true;
            comparam.MainClass          = "mynamespace.Myclass";
            comparam.OutputAssembly     = @"c:\temp\HelloWorld.exe";
            Microsoft.CSharp.CSharpCodeProvider ccp = new Microsoft.CSharp.CSharpCodeProvider();
            StreamWriter sw = new StreamWriter(@"c:\temp\HelloWorld.cs");
            // ez is jo:
            // IndentedTextWriter
            // ???
            IndentedTextWriter idt = new IndentedTextWriter(sw, " ");

            idt.Indent = 1;
            ICodeGenerator  cscg    = ccp.CreateGenerator(idt);
            ICodeCompiler   icc     = ccp.CreateCompiler();
            CompilerResults compres = icc.CompileAssemblyFromDom(comparam, myassembly);

            cscg.GenerateCodeFromNamespace(mynamespace, idt, new CodeGeneratorOptions());
            idt.Close();
            if (compres == null || compres.Errors.Count > 0)
            {
                for (int i = 0; i < compres.Errors.Count; i++)
                {
                    Console.WriteLine(compres.Errors[i]);
                }
            }
        }
示例#2
0
        public override string ToString()
        {
            var w = new StringWriter();
            var o = new CodeGeneratorOptions();

            var provider = new Microsoft.CSharp.CSharpCodeProvider();

            provider.CreateGenerator().GenerateCodeFromExpression(this, w, o);
            return(w.ToString());
        }
示例#3
0
        public static System.IO.Stream GenerateViaCodeDOM(Utility.OutputType outputType, System.CodeDom.CodeCompileUnit compileunit)
        {
            System.CodeDom.Compiler.CodeDomProvider    provider = null;
            System.CodeDom.Compiler.ICodeGenerator     gen;
            System.CodeDom.Compiler.IndentedTextWriter tw = null;
            System.IO.MemoryStream stream;
            System.IO.StreamWriter writer;

            switch (outputType)
            {
            case Utility.OutputType.VB:
                provider = new Microsoft.VisualBasic.VBCodeProvider();
                break;

            case Utility.OutputType.CSharp:
                provider = new Microsoft.CSharp.CSharpCodeProvider();
                break;
            }
            gen = provider.CreateGenerator();

            try
            {
                stream = new System.IO.MemoryStream();
                writer = new System.IO.StreamWriter(stream);
                tw     = new System.CodeDom.Compiler.IndentedTextWriter(writer, "   ");
                gen.GenerateCodeFromCompileUnit(compileunit, tw, new System.CodeDom.Compiler.CodeGeneratorOptions());
                tw.Flush();
                stream.Seek(0, System.IO.SeekOrigin.Begin);
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                if (tw != null)
                {
                    tw.Flush();
                    tw.Close();
                }
                throw;
            }
            return(stream);
        }
示例#4
0
        public MDynamicSupport GetImplementation()
        {
            // TODO: Adds a cache for generated assemblies...

            CodeNamespace ns = BuildMDynamicSupportCodeDom();

            Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider();

            cp.CreateGenerator().GenerateCodeFromNamespace(ns, Console.Out, null);

            CodeCompileUnit unit = new CodeCompileUnit();

            unit.Namespaces.Add(ns);

            String[] assembliesName = GetRequiredAssemblies();

            CompilerParameters parameters = new CompilerParameters(assembliesName);

            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory   = true;

            CompilerResults result =
                cp.CreateCompiler().CompileAssemblyFromDom(parameters, unit);

            if (result.Errors.HasErrors)
            {
                throw new CompilationException(result.Errors);
            }

            Type dynamicType =
                result.CompiledAssembly.GetType(
                    "Castle.ManagementExtensions.Generated.DynamicImplementation", true, true);

            Object inst = Activator.CreateInstance(
                dynamicType,
                new object[] { info, instance });

            return((MDynamicSupport)inst);
        }
        public CodeGenerationResult Generate(PhysicalSchema schema /* Maybe this should take a logical schema instead to help work out the root elements? */, string targetNamespace)
        {
            var code = CreateCodeNamespace(schema, targetNamespace);

            var provider = new Microsoft.CSharp.CSharpCodeProvider();

            var sb = new StringBuilder();

            using (StringWriter sw = new StringWriter(sb))
            {
                provider.CreateGenerator().GenerateCodeFromNamespace(code.Code, sw, new CodeGeneratorOptions());
            }

            var result = new CodeGenerationResult()
            {
                Code = sb.ToString()
            };

            TypeGenerator.BuildGeneratedCode(result, schema.Files[0].FileName /* TODO */, CreateMetadataReferences());
            result.RootTypeName = code.RootElementName;
            return(result);
        }
		public MDynamicSupport GetImplementation()
		{
			// TODO: Adds a cache for generated assemblies...

			CodeNamespace ns = BuildMDynamicSupportCodeDom();

			Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider();

			cp.CreateGenerator().GenerateCodeFromNamespace( ns, Console.Out, null );

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

			String[] assembliesName = GetRequiredAssemblies(); 

			CompilerParameters parameters = new CompilerParameters(assembliesName);
			parameters.GenerateExecutable = false;
			parameters.GenerateInMemory   = true;

			CompilerResults result = 
				cp.CreateCompiler().CompileAssemblyFromDom(parameters, unit);

			if (result.Errors.HasErrors)
			{
				throw new CompilationException(result.Errors);
			}

			Type dynamicType = 
				result.CompiledAssembly.GetType(
					"Castle.ManagementExtensions.Generated.DynamicImplementation", true, true);

			Object inst = Activator.CreateInstance(
				dynamicType, 
				new object[] { info, instance } );

			return (MDynamicSupport) inst;
		}
示例#7
0
        /// <summary>
        /// Generate a C# assembly, compile it and load it up
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void generateCSharpButton_Click(object sender, System.EventArgs e)
        {
            CodeExpression[] emptyParams = new CodeExpression[] { } ;

            // Generate the C# for the control
            CodeCompileUnit ccu = new CodeCompileUnit ( ) ;

            // Create a namespace
            CodeNamespace ns = new CodeNamespace ( "MyControls" ) ;

            // Add some imports statements
            ns.Imports.Add ( new CodeNamespaceImport ( "System" ) ) ;
            ns.Imports.Add ( new CodeNamespaceImport ( "System.Drawing" ) ) ;
            ns.Imports.Add ( new CodeNamespaceImport ( "System.Windows.Forms" ) ) ;

            // Add the namespace to the code compile unit
            ccu.Namespaces.Add ( ns ) ;

            // Now create the class
            CodeTypeDeclaration ctd = new CodeTypeDeclaration ( "MyControl" ) ;

            ctd.BaseTypes.Add ( typeof ( System.Windows.Forms.UserControl ) ) ;

            // Add the type to the namespace
            ns.Types.Add ( ctd ) ;

            // Add the default constructor
            CodeConstructor constructor = new CodeConstructor ( ) ;

            constructor.Statements.Add ( new CodeMethodInvokeExpression ( new CodeThisReferenceExpression ( ) , "InitializeComponent", emptyParams ) ) ;

            constructor.Attributes = MemberAttributes.Public ;

            ctd.Members.Add ( constructor ) ;

            // Create the private member variable to hold the label
            CodeMemberField labelField = new CodeMemberField ( typeof ( System.Windows.Forms.Label ) , "_label" ) ;
            ctd.Members.Add ( labelField ) ;

            // Now add the InitializeComponent method
            CodeMemberMethod initializeComponent = new CodeMemberMethod ( ) ;
            initializeComponent.Name = "InitializeComponent" ;
            initializeComponent.ReturnType = new CodeTypeReference ( typeof ( void ) ) ;

            CodeAssignStatement labelNew = new CodeAssignStatement ( new CodeVariableReferenceExpression ( "_label" ),
                new CodeObjectCreateExpression ( typeof ( System.Windows.Forms.Label ), emptyParams ) ) ;
            initializeComponent.Statements.Add ( labelNew ) ;

            // Add the SuspendLayout() call
            initializeComponent.Statements.Add ( new CodeMethodInvokeExpression ( new CodeThisReferenceExpression ( ) , "SuspendLayout", emptyParams ) ) ;

            CodeBinaryOperatorExpression leftAndRight = new CodeBinaryOperatorExpression (
                new CodeFieldReferenceExpression ( new CodeTypeReferenceExpression ( typeof ( System.Windows.Forms.AnchorStyles ) ), "Left" ) ,
                CodeBinaryOperatorType.BitwiseOr ,
                new CodeFieldReferenceExpression ( new CodeTypeReferenceExpression ( typeof ( System.Windows.Forms.AnchorStyles ) ), "Right" ) ) ;

            CodeBinaryOperatorExpression topToo = new CodeBinaryOperatorExpression (
                new CodeFieldReferenceExpression ( new CodeTypeReferenceExpression ( typeof ( System.Windows.Forms.AnchorStyles ) ), "Top" ) ,
                CodeBinaryOperatorType.BitwiseOr ,
                leftAndRight ) ;

            // Setup the Anchor property of the label
            initializeComponent.Statements.Add ( new CodeAssignStatement (
                new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ( "_label" ), "Anchor" ),
                topToo ) ) ;

            // And setup the border style
            initializeComponent.Statements.Add ( new CodeAssignStatement (
                new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ( "_label" ), "BorderStyle" ),
                new CodeFieldReferenceExpression ( new CodeTypeReferenceExpression ( typeof ( System.Windows.Forms.BorderStyle ) ), "Fixed3D" ) ) ) ;

            // Set the location of the control
            initializeComponent.Statements.Add ( new CodeAssignStatement (
                new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ( "_label" ), "Location" ),
                new CodeObjectCreateExpression ( typeof ( System.Drawing.Point ) ,
                    new CodeExpression[] { new CodePrimitiveExpression ( 8 ) ,
                                            new CodePrimitiveExpression ( 8 ) } ) ) ) ;

            // Set the name of the control
            initializeComponent.Statements.Add ( new CodeAssignStatement (
                new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ( "_label" ), "Name" ),
                new CodePrimitiveExpression ( "_label" ) ) ) ;

            // Set the size of the control
            initializeComponent.Statements.Add ( new CodeAssignStatement (
                new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ( "_label" ), "Size" ),
                new CodeObjectCreateExpression ( typeof ( System.Drawing.Size ) ,
                new CodeExpression[] { new CodePrimitiveExpression ( 312 ) ,
                                        new CodePrimitiveExpression ( 23 ) } ) ) ) ;

            // Set the tab index
            initializeComponent.Statements.Add ( new CodeAssignStatement (
                new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ( "_label" ), "TabIndex" ),
                new CodePrimitiveExpression ( 0 ) ) ) ;

            // And then the text!
            initializeComponent.Statements.Add ( new CodeAssignStatement (
                new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression ( "_label" ), "Text" ),
                new CodePrimitiveExpression ( messageText.Text ) ) ) ;

            // Now add the label control to the controls collection
            initializeComponent.Statements.Add (
                new CodeMethodInvokeExpression ( new CodePropertyReferenceExpression ( new CodeThisReferenceExpression ( ) , "Controls" ), "Add",
                new CodeExpression[] { new CodeVariableReferenceExpression ( "_label" ) } ) ) ;

            // And set the name of the control to MyControl
            initializeComponent.Statements.Add ( new CodeAssignStatement ( new CodePropertyReferenceExpression ( new CodeThisReferenceExpression ( ) , "Name" ) ,
                new CodePrimitiveExpression ( "MyControl" ) ) ) ;

            // And the size of the control
            initializeComponent.Statements.Add ( new CodeAssignStatement ( new CodePropertyReferenceExpression ( new CodeThisReferenceExpression ( ) , "Size" ) ,
                new CodeObjectCreateExpression ( typeof ( System.Drawing.Size ) ,
                    new CodeExpression[] { new CodePrimitiveExpression ( 328 ) ,
                                            new CodePrimitiveExpression ( 100 ) } ) ) ) ;

            // Add the ResumeLayout ( false ) call
            initializeComponent.Statements.Add ( new CodeMethodInvokeExpression ( new CodeThisReferenceExpression ( ) , "ResumeLayout", new CodeExpression [] { new CodePrimitiveExpression ( false ) } ) ) ;

            // And finally add initializeComponent to the members for the class
            ctd.Members.Add ( initializeComponent ) ;

            // Finally create the C#
            CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider ( ) ;

            #if DEBUG
            // Generate the source code on disk
            ICodeGenerator generator = provider.CreateGenerator ( ) ;

            using ( StreamWriter sw = new StreamWriter ( "code.cs" , false ) )
            {
                CodeGeneratorOptions options = new CodeGeneratorOptions ( ) ;
                options.BracingStyle = "C" ;
                generator.GenerateCodeFromCompileUnit ( ccu, sw, options ) ;
            }
            #endif

            ICodeCompiler compiler = provider.CreateGenerator ( ) as ICodeCompiler ;

            CompilerParameters cp = new CompilerParameters ( new string[] { "System.dll", "System.Windows.Forms.dll", "System.Drawing.dll" } ) ;

            cp.GenerateInMemory = true ;
            cp.OutputAssembly = "AutoGenerated" ;

            CompilerResults results = compiler.CompileAssemblyFromDom ( cp, ccu ) ;

            if ( results.Errors.Count == 0 )
            {
                Type t = results.CompiledAssembly.GetType ( "MyControls.MyControl" ) ;

                Control c = Activator.CreateInstance ( t ) as Control ;

                c.Dock = DockStyle.Fill ;

                controlPanel.SuspendLayout ( ) ;
                controlPanel.Controls.Clear ( ) ;
                controlPanel.Controls.Add ( c ) ;
                controlPanel.ResumeLayout ( ) ;
            }
            else
            {
                CompilerError error = results.Errors[0] ;
                int i = 0 ;
                i++;
            }
        }
示例#8
0
        /// <summary>
        /// Generate a C# assembly, compile it and load it up
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void generateCSharpButton_Click(object sender, System.EventArgs e)
        {
            CodeExpression[] emptyParams = new CodeExpression[] { };

            // Generate the C# for the control
            CodeCompileUnit ccu = new CodeCompileUnit( );

            // Create a namespace
            CodeNamespace ns = new CodeNamespace("MyControls");

            // Add some imports statements
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
            ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));

            // Add the namespace to the code compile unit
            ccu.Namespaces.Add(ns);

            // Now create the class
            CodeTypeDeclaration ctd = new CodeTypeDeclaration("MyControl");

            ctd.BaseTypes.Add(typeof(System.Windows.Forms.UserControl));

            // Add the type to the namespace
            ns.Types.Add(ctd);

            // Add the default constructor
            CodeConstructor constructor = new CodeConstructor( );

            constructor.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression( ), "InitializeComponent", emptyParams));

            constructor.Attributes = MemberAttributes.Public;

            ctd.Members.Add(constructor);

            // Create the private member variable to hold the label
            CodeMemberField labelField = new CodeMemberField(typeof(System.Windows.Forms.Label), "_label");

            ctd.Members.Add(labelField);

            // Now add the InitializeComponent method
            CodeMemberMethod initializeComponent = new CodeMemberMethod( );

            initializeComponent.Name       = "InitializeComponent";
            initializeComponent.ReturnType = new CodeTypeReference(typeof(void));

            CodeAssignStatement labelNew = new CodeAssignStatement(new CodeVariableReferenceExpression("_label"),
                                                                   new CodeObjectCreateExpression(typeof(System.Windows.Forms.Label), emptyParams));

            initializeComponent.Statements.Add(labelNew);

            // Add the SuspendLayout() call
            initializeComponent.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression( ), "SuspendLayout", emptyParams));

            CodeBinaryOperatorExpression leftAndRight = new CodeBinaryOperatorExpression(
                new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Windows.Forms.AnchorStyles)), "Left"),
                CodeBinaryOperatorType.BitwiseOr,
                new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Windows.Forms.AnchorStyles)), "Right"));

            CodeBinaryOperatorExpression topToo = new CodeBinaryOperatorExpression(
                new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Windows.Forms.AnchorStyles)), "Top"),
                CodeBinaryOperatorType.BitwiseOr,
                leftAndRight);

            // Setup the Anchor property of the label
            initializeComponent.Statements.Add(new CodeAssignStatement(
                                                   new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("_label"), "Anchor"),
                                                   topToo));

            // And setup the border style
            initializeComponent.Statements.Add(new CodeAssignStatement(
                                                   new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("_label"), "BorderStyle"),
                                                   new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Windows.Forms.BorderStyle)), "Fixed3D")));

            // Set the location of the control
            initializeComponent.Statements.Add(new CodeAssignStatement(
                                                   new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("_label"), "Location"),
                                                   new CodeObjectCreateExpression(typeof(System.Drawing.Point),
                                                                                  new CodeExpression[] { new CodePrimitiveExpression(8),
                                                                                                         new CodePrimitiveExpression(8) })));

            // Set the name of the control
            initializeComponent.Statements.Add(new CodeAssignStatement(
                                                   new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("_label"), "Name"),
                                                   new CodePrimitiveExpression("_label")));

            // Set the size of the control
            initializeComponent.Statements.Add(new CodeAssignStatement(
                                                   new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("_label"), "Size"),
                                                   new CodeObjectCreateExpression(typeof(System.Drawing.Size),
                                                                                  new CodeExpression[] { new CodePrimitiveExpression(312),
                                                                                                         new CodePrimitiveExpression(23) })));

            // Set the tab index
            initializeComponent.Statements.Add(new CodeAssignStatement(
                                                   new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("_label"), "TabIndex"),
                                                   new CodePrimitiveExpression(0)));

            // And then the text!
            initializeComponent.Statements.Add(new CodeAssignStatement(
                                                   new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("_label"), "Text"),
                                                   new CodePrimitiveExpression(messageText.Text)));

            // Now add the label control to the controls collection
            initializeComponent.Statements.Add(
                new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression( ), "Controls"), "Add",
                                               new CodeExpression[] { new CodeVariableReferenceExpression("_label") }));

            // And set the name of the control to MyControl
            initializeComponent.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression( ), "Name"),
                                                                       new CodePrimitiveExpression("MyControl")));

            // And the size of the control
            initializeComponent.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression( ), "Size"),
                                                                       new CodeObjectCreateExpression(typeof(System.Drawing.Size),
                                                                                                      new CodeExpression[] { new CodePrimitiveExpression(328),
                                                                                                                             new CodePrimitiveExpression(100) })));

            // Add the ResumeLayout ( false ) call
            initializeComponent.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression( ), "ResumeLayout", new CodeExpression [] { new CodePrimitiveExpression(false) }));

            // And finally add initializeComponent to the members for the class
            ctd.Members.Add(initializeComponent);

            // Finally create the C#
            CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider( );

#if DEBUG
            // Generate the source code on disk
            ICodeGenerator generator = provider.CreateGenerator( );

            using (StreamWriter sw = new StreamWriter("code.cs", false))
            {
                CodeGeneratorOptions options = new CodeGeneratorOptions( );
                options.BracingStyle = "C";
                generator.GenerateCodeFromCompileUnit(ccu, sw, options);
            }
#endif

            ICodeCompiler compiler = provider.CreateGenerator( ) as ICodeCompiler;

            CompilerParameters cp = new CompilerParameters(new string[] { "System.dll", "System.Windows.Forms.dll", "System.Drawing.dll" });

            cp.GenerateInMemory = true;
            cp.OutputAssembly   = "AutoGenerated";

            CompilerResults results = compiler.CompileAssemblyFromDom(cp, ccu);

            if (results.Errors.Count == 0)
            {
                Type t = results.CompiledAssembly.GetType("MyControls.MyControl");

                Control c = Activator.CreateInstance(t) as Control;

                c.Dock = DockStyle.Fill;

                controlPanel.SuspendLayout( );
                controlPanel.Controls.Clear( );
                controlPanel.Controls.Add(c);
                controlPanel.ResumeLayout( );
            }
            else
            {
                CompilerError error = results.Errors[0];
                int           i     = 0;
                i++;
            }
        }
        public static Type GenerateControl( )
        {
            // Generate the C# for the control
            CodeCompileUnit ccu = new CodeCompileUnit( );

            // Create a namespace
            CodeNamespace ns = new CodeNamespace("MyASPCSControls");

            // Add some imports statements
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
            ns.Imports.Add(new CodeNamespaceImport("System.Web.UI"));
            ns.Imports.Add(new CodeNamespaceImport("System.Web.UI.WebControls"));

            // Add the namespace to the code compile unit
            ccu.Namespaces.Add(ns);

            // Now create the class
            CodeTypeDeclaration ctd = new CodeTypeDeclaration("MyASPCSControl");

            ctd.BaseTypes.Add(typeof(System.Web.UI.WebControls.WebControl));

            // Add the type to the namespace
            ns.Types.Add(ctd);

            // Create the private member variable to hold the label
            CodeMemberField textField = new CodeMemberField(typeof(string), "_text");

            ctd.Members.Add(textField);

            // Next add the Text property
            CodeMemberProperty textProp = new CodeMemberProperty( );

            textProp.Name       = "Text";
            textProp.Attributes = MemberAttributes.Public;
            textProp.Type       = new CodeTypeReference(typeof(string));

            textProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_text")));
            textProp.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_text"),
                                                               new CodePropertySetValueReferenceExpression( )));

            ctd.Members.Add(textProp);

            // Then override the Render() method
            CodeMemberMethod renderMeth = new CodeMemberMethod( );

            renderMeth.Name       = "Render";
            renderMeth.Attributes = MemberAttributes.Family | MemberAttributes.Override;

            CodeParameterDeclarationExpression writer = new CodeParameterDeclarationExpression(typeof(System.Web.UI.HtmlTextWriter), "writer");

            renderMeth.Parameters.Add(writer);

            renderMeth.Statements.Add(new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("writer"), "Write", new CodeExpression[] { new CodePropertyReferenceExpression(new CodeThisReferenceExpression( ), "Text") }));
            ctd.Members.Add(renderMeth);

            // Add the default constructor
            CodeConstructor constructor = new CodeConstructor( );

            constructor.Attributes = MemberAttributes.Public;

            ctd.Members.Add(constructor);

            // Finally create the C#
            CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider( );

            ICodeCompiler compiler = provider.CreateGenerator( ) as ICodeCompiler;

            CompilerParameters cp = new CompilerParameters(new string[] { "System.dll", "System.Web.dll" });

            cp.GenerateInMemory = true;

            CompilerResults results = compiler.CompileAssemblyFromDom(cp, ccu);

            if (results.Errors.Count == 0)
            {
                return(results.CompiledAssembly.GetType("MyASPCSControls.MyASPCSControl"));
            }

            // Oops, something was wrong
            throw new Exception(results.Errors[0].ErrorText);
        }
示例#10
0
		protected void GenerateSource()
		{
			String fileName = _assyInfo._name + ".cs";
			try {
				File.OpenRead(fileName);
				// It worked, so the souce file is there, don't generate
				// another one
				return;
			} catch (FileNotFoundException) {
				// Not found, we create it
			}
			CreateAssyNames();
			ReadTypeLibInfo();
			FileStream outStr = File.Create(fileName);
			Console.WriteLine("Generating source file: " + fileName);
			TextWriter writer = new StreamWriter(outStr);
			CodeCompileUnit compileUnit = new CodeCompileUnit();
			
			// Add TypeLib attribute
			CodeAttributeArgument typeLibArg = new CodeAttributeArgument();
			typeLibArg.Value = new CodePrimitiveExpression(Name);
			compileUnit.AssemblyCustomAttributes.Add
				(new CodeAttributeDeclaration
					("System.Runtime.InteropServices.ImportedFromTypeLib",
					new CodeAttributeArgument[] { typeLibArg }));
			// Add Guid attribute
			CodeAttributeArgument guidArg = new CodeAttributeArgument();
			guidArg.Value = new CodePrimitiveExpression(_typeLibKey._guid.ToString());
			compileUnit.AssemblyCustomAttributes.Add
				(new CodeAttributeDeclaration
					("System.Runtime.InteropServices.Guid",
					new CodeAttributeArgument[] { guidArg }));
			// Key file
			/***
			// FIXME - this is only for testing
			CodeAttributeArgument keyFileArg = new CodeAttributeArgument();
			keyFileArg.Value = new CodePrimitiveExpression
				("\\d\\src\\mstools\\key\\nogoop.snk");
			compileUnit.AssemblyCustomAttributes.Add
				(new CodeAttributeDeclaration
					("System.Reflection.AssemblyKeyFile",
					 new CodeAttributeArgument[] { keyFileArg }));
			***/
			CodeNamespace ns = new CodeNamespace(_assyInfo._name);
			compileUnit.Namespaces.Add(ns);
			foreach (Object cls in _members)
			{
				if (cls is ICodeDom)
					((ICodeDom)cls).AddDomTo(ns.Types);
			}
			CodeDomProvider provider = 
				new Microsoft.CSharp.CSharpCodeProvider();
			ICodeGenerator gen = provider.CreateGenerator();
			gen.GenerateCodeFromCompileUnit(compileUnit,
											writer,
											null);
			writer.Flush();
			writer.Close();
		}
示例#11
0
        public void DoServiceEvent(int k2_workflowId, SerializableDictionary <string, string> dataFields)
        {
            StringBuilder txt = new StringBuilder();

            foreach (KeyValuePair <string, string> item in dataFields)
            {
                txt.AppendFormat("{0}|{1}$", item.Key, item.Value);
            }

            string param = txt.ToString().Trim('$');

            //1. 创建WebClient下载WSDL信息
            WebClient web    = new WebClient();
            Stream    stream = web.OpenRead(string.Format("{0}?wsdl", Url));

            // 2. 创建和格式化 WSDL 文档。
            ServiceDescription description = ServiceDescription.Read(stream);

            // 3. 创建客户端代理代理类。
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

            importer.ProtocolName = "Soap";                               // 指定访问协议。
            importer.Style        = ServiceDescriptionImportStyle.Client; // 生成客户端代理。

            importer.AddServiceDescription(description, null, null);      // 添加 WSDL 文档。

            // 4. 使用 CodeDom 编译客户端代理类。
            CodeNamespace   nmspace = new CodeNamespace(); // 为代理类添加命名空间,缺省为全局空间。
            CodeCompileUnit unit    = new CodeCompileUnit();

            unit.Namespaces.Add(nmspace);

            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);

            //5. 修改WebService接口的基类(默认基类是SoapHttpClientProtocol),而因为使用的wse2.0,所以需要修改基类以便后面传递身份验证信息
            //CodeTypeDeclaration ctDecl = nmspace.Types[0];
            //nmspace.Types.Remove(ctDecl);
            //ctDecl.BaseTypes[0] = new CodeTypeReference("Microsoft.Web.Services2.WebServicesClientProtocol");
            //nmspace.Types.Add(ctDecl);

            //创建代码生成器
            CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();

            //6. 指定代码生成器,并获得源码
            ICodeGenerator icg = provider.CreateGenerator();
            StringBuilder  srcStringBuilder = new StringBuilder();
            StringWriter   sw = new StringWriter(srcStringBuilder);

            icg.GenerateCodeFromNamespace(nmspace, sw, null);
            string proxySource = srcStringBuilder.ToString();

            sw.Close();

            //7. 创建编译的参数
            CompilerParameters parameter = new CompilerParameters();

            //注意以下两个属性设置为false才能在多次动态调用时不会报错
            parameter.GenerateExecutable = false;
            parameter.GenerateInMemory   = false;
            //用于输出dll文件,调试的时候查看结果
            //parameter.OutputAssembly = "WebService.dll"; // 可以指定你所需的任何文件名。
            parameter.ReferencedAssemblies.Add("System.dll");
            parameter.ReferencedAssemblies.Add("System.XML.dll");
            parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
            parameter.ReferencedAssemblies.Add("System.Data.dll");


            //8. 动态编译文件
            ICodeCompiler   compiler = provider.CreateCompiler();
            CompilerResults result   = compiler.CompileAssemblyFromSource(parameter, proxySource);//compiler.CompileAssemblyFromDom(parameter, unit);

            try
            {
                // 9. 检查编译是否出错
                if (!result.Errors.HasErrors)
                {
                    //10. 使用 Reflection 调用 WebService。
                    Assembly asm = result.CompiledAssembly;
                    // 如果在前面为代理类添加了命名空间,此处需要将命名空间添加到类型前面。

                    //foreach (var item in asm.GetTypes())
                    //{
                    //if (item.IsSubclassOf(typeof(FinallyDisposeServiceBase)))
                    //{
                    string className = WF_GetRelatedLinks.GetRelatedClassName(k2_workflowId.ToString());
                    Type   t         = asm.GetType(className);
                    object o         = Activator.CreateInstance(t);
                    //调用WebService的方法
                    MethodInfo method = t.GetMethod("InvokeService");
                    //传递方法所需参数
                    method.Invoke(o, new object[] { k2_workflowId, param });
                    //获取返回结果;
                    //    }
                    //}
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
            }
        }