The previous phase has been doing a plugin based on VS.NET2K3, which is approximately automatic generation of business code. I started from more than two months, but I have not idle time, and then add some questions about the VS plugin during the actual development process. All always dragged. The procedure finally breakthrough in the past few days, all functions can be achieved. Includes automatic addition of engineering, reference, compilation, etc. Waiting for some days, optimize the code (while removing some bugs, I have never understood that when I generate a tens of thousands of lines of code, my development environment will be fully collapsed) and release it. Yesterday, I suddenly thought that the code now produced is too life, and cannot generate the corresponding language code according to the user's choice. If you die, it is too boring. I thought that I have seen the code that CodeDom, which I have introduced before I have seen it, can dynamically call compilation, so I quickly read the CodeDom again, and I can generate C #, VB, JScript code. But just started research, I only wrote a small program. But I feel very interesting. In this case, I can let my Toolkit rewrite my Toolkit can make different programmers to generate the corresponding code according to their own preferences (the function is the same.) Using system; using system.codedom; using system.codedom.compiler ; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Windows.Forms; using Microsoft.CSharp; using Microsoft.VisualBasic; using Microsoft.JScript; // Add reference. // This example demonstrates how to create a Hello World program using System.codedom, will generate and compile the C #, VB, JScript version of the C #, VB, JScript version based on the user's selection dynamic code
namespace CodeDOMTest {public class CodeDomExampleForm: System.Windows.Forms.Form {private System.Windows.Forms.Button run_button = new System.Windows.Forms.Button (); private System.Windows.Forms.Button compile_button = new System.Windows .Forms.Button (); private System.Windows.Forms.Button generate_button = new System.Windows.Forms.Button (); private System.Windows.Forms.TextBox textBox1 = new System.Windows.Forms.TextBox (); private System.Windows.Forms.ComboBox comboBox1 = new System.Windows.Forms.ComboBox (); private System.Windows.Forms.Label label1 = new System.Windows.Forms.Label (); private void generate_button_Click (object sender, System. EventArgs e) {CodeDomProvider provider = GetCurrentProvider (); CodeDomExample.GenerateCode (provider, CodeDomExample.BuildHelloWorldGraph ()); StreamReader sr = new StreamReader ( "MyHello.cs"); textBox1.Text = sr.ReadToEnd (); sr.Close ();} Private void compile_button_click (Object Sender, System.Eventargs E ) {CODEDOMPROVIDER Provider = getCurrentProvider (); CompilerResults cr = CodeDomexample.compilecode (provider, "myhello.cs");
IF (cr.errors.count> 0) {textBox1.text = "Compile file error:" cr.pathtoassembly ": / r / n"; foreach (compilererror cein cr.erro) textbox1.appendtext (CE.TOSTRING) "/ r / n"); run_button.enabled = false;} else {textbox1.text = cr.pathtoassembly "Compile Success"; Run_Button.enabled = true;}}
Private void run_button_click (object sender, system.eventargs e) {process.start ("myhello.exe");} ///
new System.EventHandler (this.generate_button_Click); this.compile_button.Location = new System.Drawing.Point (136, 16); this.compile_button.Name = "compile_button"; this.compile_button.Size = new System.Drawing.Size (120, 23); this.compile_button.Text = "Compile"; this.compile_button.Click = new System.EventHandler (this.compile_button_Click); this.run_button.Enabled = false; this.run_button.Location = new System. Drawing.point (264, 16); this.Run_Button.Name = "Run_Button"; this.Run_Button.Size = new system.drawing.size (120, 23); this.Run_Button.Text = "run"; this.Run_Button .Click = new System.EventHandler (this.run_button_Click); this.textBox1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms. Anchorstyles.Lorms.Anchorstyles.Right; this.textbox1.location = new system.drawing.point (8, 4 8); this.textBox1.Multiline = true; this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size ( 744, 280); this.TextBox1.text = ""; // codedomexampleform this.autoscalebasesize = new system.drawing.size (5, 13); this.clientsize = new system.drawing.size (768, 340); this .Minimumsize = new system.drawing.size (750, 340);
this.Controls.AddRange (new System.Windows.Forms.Control [] {this.textBox1, this.run_button, this.compile_button, this.generate_button, this.comboBox1, this.label1}); this.Name = "CodeDomExampleForm" This.Text = "Codedom Hello World Example"; this.ResumeLayout (false);} protected} {base.dispose (disposing);}
Private void initializecomponent () {this.autoscalebasesize = new system.drawing.size (6, 14); this.clientsize = new system.drawing.size (448, 269); this.name = "CodedMexampleForm";
}
[Stathread] static void main () {Application.run (New CodeDomexampleForm ());}}
Public class codedomexample {
Public Static CodeCompileUnit BuildHelloWorldGraph () {// Create a code container // codeCompileUnit contains the following collections: You can store the collection of CodeNameSpace objects containing the CodeDom source graphics, the collection of the assembly of // project references, and project assemblies Attribute collection. CodeCompileUnit Compileunit = New CodeCompileunit ();
// Declare a namespace CODENAMESPACE MYSAMPLE = New CodeNameSpace ("MySample"); // Add Name Space to Code Container CompileUnit.NameSpaces.add (MySample); // Import a Name Space MySample.imports.Add (New CodenameSpaceImport) "System"));
// Declare a type of CODETYPEDECLATION Hello = New CodeTypedeclaration ("Hello"); // Add type to the container in the type collection of mysample.types.add (hello); // Conquerory function (not) CodeConstructor con = New CodeConstructor ); Con?attributes = memory; membutes.public; hello.members.add (con); // Indicates the entry point method of executable file, that is, a program's entrance coderyPointMethod Start = new codePointMethod (); // establishing a code calls expression CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression (// call the method. System.Console.WriteLine new CodeTypeReferenceExpression ( "System.Console"), "WriteLine", // pass a primitive data type value to the new method CodePrimitiveExpression ( "Hello World!")); // the method of adding to the process Start.Statements.Add (new CodeExpressionStatement (cs1)); CodeMethodInvokeExpression cs2 = new CodeMethodInvokeExpression (); CodeMethodReferenceExpression cmr = new CodeMethodReferenceExpression (); cmr.MethodName = "SayHell"; cs2.method = CMR; start.statements.add (New codeExpressionStatement (CS2)); // Add Method to the type Hello.members.Add ( Start);
// member function Sayhello, has parameters, no reference
// public bool shorthello (String Input) // {// Console.writeline (Input); // Return false; //} codemembermethod cm = new codeMeMBerMethod (); cm.name = "selfhello"; cm.returntype = new CodeTypeReference (typeof (bool)); cm.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static; cm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "input")); cm.Statements.Add ( new CodeMethodInvokeExpression (new CodeSnippetExpression ( "Console"), "WriteLine", new CodeArgumentReferenceExpression ( "input"))); cm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (false))); Hello.Members.Add (cm) Return CompileUnit;}
public static void GenerateCode (CodeDomProvider provider, CodeCompileUnit compileunit) {// get the generated code interface ICodeGenerator gen = provider.CreateGenerator (); // output to a file IndentedTextWriter tw = new IndentedTextWriter (new StreamWriter ( "MyHello.cs", false) , ""); // Use the code generation interface to generate the source code. Gen.GeneratecodeFromCompileunit (CompileUnit, Tw, New CodegeneratorOptions ()); tw.close ();
Public Static CompilerResults CompileCode (CODEPROVIDER Provider, String FilePath) {// Get the compiler. iCodeCompiler compiler = provider.createCompiler (); // Configure the compilation parameters. Will System. DLL references come in, and clearly generated code for EXE CompilerParameters cp = new compilerParameters (new string [] {"system.dll"}, filepath.substring (0, filepath.lastindexof (".") 1) "exe" , false; cp.generateexecutable = true; // Call compiler CompilerResults cr = compiler.compileassemblyFromFile (CP, FilePath); Return Cr;}}