tag:blogger.com,1999:blog-8912334.post-1119631566411935422005-06-24T09:42:00.000-07:002007-02-20T13:44:19.883-08:00self descriptionSomebody ask for the code of the self descripting c# code i've done <a href="http://oraclevsmicrosoft.blogspot.com/2005/01/code-generation-and-self-description.html"> a few times ago here</a> it is :<br /><br /><font face="courier"><br />using System;<br />using System.Collections;<br />using System.ComponentModel;<br />using System.Windows.Forms;<br />using System.CodeDom;<br />using System.CodeDom.Compiler;<br />using Microsoft.CSharp;<br />using System.Collections.Specialized;<br />namespace WindowsApplication2<br />{<br /> /// Main form<br /><br /> public class Form1 : System.Windows.Forms.Form<br /> {<br /> private System.Windows.Forms.Button button2;<br /> private System.Windows.Forms.Button button1;<br /> private System.Windows.Forms.Button bt_itself;<br /> private System.Windows.Forms.RichTextBox rt1;<br /> private System.Windows.Forms.ListBox listBox1;<br /> private System.ComponentModel.Container components = null;<br /><br /> public Form1()<br /> {<br /> //<br /> // Requis pour la prise en charge du Concepteur Windows Forms<br /> //<br /> InitializeComponent();<br /> }<br /><br /> /// Nettoyage des ressources utilisées.<br /> protected override void Dispose( bool disposing )<br /> {<br /> if( disposing )<br /> {<br /> if (components != null)<br /> {<br /> components.Dispose();<br /> }<br /> }<br /> base.Dispose( disposing );<br /> }<br /><br /> #region Code généré par le Concepteur Windows Form<br /> /// <summary><br /> /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas<br /> /// le contenu de cette méthode avec l'éditeur de code.<br /> /// </summary><br /> private void InitializeComponent() {<br /> this.listBox1 = new System.Windows.Forms.ListBox();<br /> this.rt1 = new System.Windows.Forms.RichTextBox();<br /> this.bt_itself = new System.Windows.Forms.Button();<br /> this.button1 = new System.Windows.Forms.Button();<br /> this.button2 = new System.Windows.Forms.Button();<br /> this.SuspendLayout();<br /> // <br /> // listBox1<br /> // <br /> this.listBox1.Location = new System.Drawing.Point(24, 360);<br /> this.listBox1.Name = "listBox1";<br /> this.listBox1.Size = new System.Drawing.Size(1016, 108);<br /> this.listBox1.TabIndex = 3;<br /> // <br /> // rt1<br /> // <br /> this.rt1.Location = new System.Drawing.Point(24, 16);<br /> this.rt1.Name = "rt1";<br /> this.rt1.Size = new System.Drawing.Size(632, 328);<br /> this.rt1.TabIndex = 1;<br /> this.rt1.Text = "richTextBox1";<br /> // <br /> // bt_itself<br /> // <br /> this.bt_itself.Location = new System.Drawing.Point(696, 40);<br /> this.bt_itself.Name = "bt_itself";<br /> this.bt_itself.Size = new System.Drawing.Size(72, 24);<br /> this.bt_itself.TabIndex = 0;<br /> this.bt_itself.Text = "it self";<br /> this.bt_itself.Click += new System.EventHandler(this.bt_itself_Click);<br /> // <br /> // button1<br /> // <br /> this.button1.Location = new System.Drawing.Point(696, 8);<br /> this.button1.Name = "button1";<br /> this.button1.Size = new System.Drawing.Size(72, 24);<br /> this.button1.TabIndex = 0;<br /> this.button1.Text = "genere";<br /> this.button1.Click += new System.EventHandler(this.button1_Click);<br /> // <br /> // button2<br /> // <br /> this.button2.Location = new System.Drawing.Point(696, 72);<br /> this.button2.Name = "button2";<br /> this.button2.Size = new System.Drawing.Size(72, 24);<br /> this.button2.TabIndex = 4;<br /> this.button2.Text = "compile";<br /> this.button2.Click += new System.EventHandler(this.button2_Click);<br /> <br /> // <br /> // Form1<br /> // <br /> this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);<br /> this.ClientSize = new System.Drawing.Size(1032, 526);<br /> this.Controls.Add(this.button2);<br /> this.Controls.Add(this.listBox1);<br /> this.Controls.Add(this.rt1);<br /> this.Controls.Add(this.button1);<br /> this.Controls.Add(this.bt_itself);<br /> this.Name = "Form1";<br /> this.Text = "Form1";<br /> this.Load += new System.EventHandler(this.Form1_Load);<br /> this.ResumeLayout(false);<br /> }<br /> #endregion<br /><br /> /// Point d'entrée principal de l'application.<br /> [STAThread]<br /> static void Main()<br /> {<br /> Application.Run(new Form1());<br /> }<br />// methode de base <br /> string join(string[] arr,string sep)<br /> {string strReturn="" ;<br /> foreach (string elt in arr)<br /> strReturn += elt+sep;<br /> strReturn.Substring(0,strReturn.Length-sep.Length);<br /> <br /> return strReturn;<br /> }<br /><br /> void seekandreplace(string[] arr,string strSrc,string strReplace)<br /> {<br /> int i=0;<br /> for(i=0;i<=arr.Length-1;i++)<br /> { if(arr[i]==strSrc)<br /> arr[i]=strReplace;<br /> }<br /> }<br /> string format (string str)<br /> {<br /> str = str.Replace("\\","\\\\");<br /> str = str.Replace("\"","\\\"");<br /> return str; <br /> }<br /> string joinformat(string[] arr,string sep)<br /> {<br /> string strReturn= "" ;<br /> foreach (string elt in arr)<br /> { strReturn +=format( elt)+sep;}<br /> <br /> strReturn = strReturn.Substring( 0,strReturn.Length-sep.Length);<br /> <br /> return strReturn;<br /> }<br /> private void Form1_Load(object sender, System.EventArgs e)<br /> {<br /> //nothing special here <br /> }<br /><br /> private void button1_Click(object sender, System.EventArgs e)<br /> {// here is starting the main part of the code:<br /> //<br /> //the CodeCompileUnit is the abstract code structure:<br /><br /> // Create a new CodeCompileUnit to contain the program graph<br /> CodeCompileUnit CompileUnit = new CodeCompileUnit();<br /> // Declare a new namespace called Samples.<br /> CodeNamespace Samples = new CodeNamespace("Samples");<br /> // Add the new namespace to the compile unit.<br /> CompileUnit.Namespaces.Add( Samples );<br /><br /> // Add the new namespace import for the System namespace.<br /> Samples.Imports.Add( new CodeNamespaceImport("System") );<br /><br /> // Declare a new type called Class1.<br /> CodeTypeDeclaration Class1 = new CodeTypeDeclaration("echo");<br /> // Add the new type to the namespace's type collection.<br /> Samples.Types.Add(Class1);<br /><br /> //a variable declaration<br /> CodeVariableDeclarationStatement Var = new<br /> CodeVariableDeclarationStatement("System.String","str1");<br /> // Declare a new code entry point method<br /> CodeEntryPointMethod Start = new CodeEntryPointMethod();<br /> // Create a new method invocation expression.<br /> CodeMethodInvokeExpression cs1 =<br /> new CodeMethodInvokeExpression(<br /> // Call the System.Console.WriteLine method.<br /> <br /> new CodeTypeReferenceExpression("System.Console"), "ReadLine");<br /> CodeAssignStatement as1 = new CodeAssignStatement(<br /> new CodeVariableReferenceExpression("str1"),cs1);<br /><br /> // Create a new method invocation expression.<br /> CodeMethodInvokeExpression cs2 =<br /> new CodeMethodInvokeExpression(<br /> // Call the System.Console.WriteLine method.<br /> new CodeTypeReferenceExpression("System.Console"), "WriteLine");<br /> cs2.Parameters.Add(new CodeVariableReferenceExpression(Var.Name));<br /><br /> Start.Statements.Add(Var);<br /> // Add the new method code statement.<br /> Start.Statements.Add( as1);<br /> // Add the new method code statement.<br /> Start.Statements.Add(new CodeExpressionStatement(cs2));<br /><br /> // Add the code entry point method to the type's members collection<br /> Class1.Members.Add( Start );<br /><br /><br /> System.IO.StringWriter Sw = new System.IO.StringWriter();<br /><br /> <br /> Microsoft.CSharp.CSharpCodeProvider provider =<br /> new CSharpCodeProvider();<br /> System.CodeDom.Compiler.ICodeGenerator generator = provider.CreateGenerator(Sw);<br /> CodeGeneratorOptions genOptions = new CodeGeneratorOptions();<br /><br /> // The code generator should insert blank lines <br /> genOptions.BlankLinesBetweenMembers = true;<br /><br /> try<br /> {<br /> generator.GenerateCodeFromCompileUnit(CompileUnit,Sw,genOptions);<br /> }<br /> catch (Exception Exc)<br /> {<br /> System.Windows.Forms.MessageBox.Show (Exc.Message);<br /> }<br /> rt1.Text = Sw.ToString();<br /><br /> }<br /> <br /> private void button2_Click(object sender, System.EventArgs e)<br /> {<br /> Microsoft.CSharp.CSharpCodeProvider provider =<br /> new CSharpCodeProvider();<br /> ///<br />// Compilation <br /> //instanciate csharp compiler<br /> System.CodeDom.Compiler.ICodeCompiler MyCompiler = provider.CreateCompiler();<br /> System.CodeDom.Compiler.CompilerParameters cp = new CompilerParameters();<br /> cp.GenerateExecutable = true;<br /> cp.CompilerOptions= " /target:exe";<br /> cp.ReferencedAssemblies.AddRange( new string[]{"System.Windows.Forms.dll","System.dll","System.drawing.dll",""});<br /> //where your exe will be saved<br /> cp.OutputAssembly = "c:\\echo.exe";<br /> // Invoke compilation.<br /> CompilerResults cr = MyCompiler.CompileAssemblyFromSource ( cp,rt1.Text);<br /> //<br /> // Return the results of compilation.<br /><br /> //eventually load compilation output to the listbox (usefull to debug)<br /> listBox1.DataSource=cr.Output;<br /><br /> //where is it? <br /> MessageBox.Show ( cr.PathToAssembly );<br /> }<br /><br /> private void bt_itself_Click(object sender, System.EventArgs e)<br /> {<br /> string[] arr=new string[]{<br />"using System;",<br />"using System.Collections;",<br />"using System.ComponentModel;",<br />"using System.Windows.Forms;",<br />"using System.CodeDom;",<br />"using System.CodeDom.Compiler;",<br />"using Microsoft.CSharp;",<br />"using System.Collections.Specialized;",<br />"namespace WindowsApplication2",<br />"{",<br />" /// Main form",<br />"",<br />" public class Form1 : System.Windows.Forms.Form",<br />" {",<br />" private System.Windows.Forms.Button button2;",<br />" private System.Windows.Forms.Button button1;",<br />" private System.Windows.Forms.Button bt_itself;",<br />" private System.Windows.Forms.RichTextBox rt1;",<br />" private System.Windows.Forms.ListBox listBox1;",<br />" private System.ComponentModel.Container components = null;",<br />"",<br />" public Form1()",<br />" {",<br />" //",<br />" // Requis pour la prise en charge du Concepteur Windows Forms",<br />" //",<br />" InitializeComponent();",<br />" }",<br />"",<br />" /// Nettoyage des ressources utilisées.",<br />" protected override void Dispose( bool disposing )",<br />" {",<br />" if( disposing )",<br />" {",<br />" if (components != null)",<br />" {",<br />" components.Dispose();",<br />" }",<br />" }",<br />" base.Dispose( disposing );",<br />" }",<br />"",<br />" #region Code généré par le Concepteur Windows Form",<br />" /// <summary>",<br />" /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas",<br />" /// le contenu de cette méthode avec l'éditeur de code.",<br />" /// </summary>",<br />" private void InitializeComponent() {",<br />" this.listBox1 = new System.Windows.Forms.ListBox();",<br />" this.rt1 = new System.Windows.Forms.RichTextBox();",<br />" this.bt_itself = new System.Windows.Forms.Button();",<br />" this.button1 = new System.Windows.Forms.Button();",<br />" this.button2 = new System.Windows.Forms.Button();",<br />" this.SuspendLayout();",<br />" // ",<br />" // listBox1",<br />" // ",<br />" this.listBox1.Location = new System.Drawing.Point(24, 360);",<br />" this.listBox1.Name = \"listBox1\";",<br />" this.listBox1.Size = new System.Drawing.Size(1016, 108);",<br />" this.listBox1.TabIndex = 3;",<br />" // ",<br />" // rt1",<br />" // ",<br />" this.rt1.Location = new System.Drawing.Point(24, 16);",<br />" this.rt1.Name = \"rt1\";",<br />" this.rt1.Size = new System.Drawing.Size(632, 328);",<br />" this.rt1.TabIndex = 1;",<br />" this.rt1.Text = \"richTextBox1\";",<br />" // ",<br />" // bt_itself",<br />" // ",<br />" this.bt_itself.Location = new System.Drawing.Point(696, 40);",<br />" this.bt_itself.Name = \"bt_itself\";",<br />" this.bt_itself.Size = new System.Drawing.Size(72, 24);",<br />" this.bt_itself.TabIndex = 0;",<br />" this.bt_itself.Text = \"it self\";",<br />" this.bt_itself.Click += new System.EventHandler(this.bt_itself_Click);",<br />" // ",<br />" // button1",<br />" // ",<br />" this.button1.Location = new System.Drawing.Point(696, 8);",<br />" this.button1.Name = \"button1\";",<br />" this.button1.Size = new System.Drawing.Size(72, 24);",<br />" this.button1.TabIndex = 0;",<br />" this.button1.Text = \"genere\";",<br />" this.button1.Click += new System.EventHandler(this.button1_Click);",<br />" // ",<br />" // button2",<br />" // ",<br />" this.button2.Location = new System.Drawing.Point(696, 72);",<br />" this.button2.Name = \"button2\";",<br />" this.button2.Size = new System.Drawing.Size(72, 24);",<br />" this.button2.TabIndex = 4;",<br />" this.button2.Text = \"compile\";",<br />" this.button2.Click += new System.EventHandler(this.button2_Click);",<br />" ",<br />" // ",<br />" // Form1",<br />" // ",<br />" this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);",<br />" this.ClientSize = new System.Drawing.Size(1032, 526);",<br />" this.Controls.Add(this.button2);",<br />" this.Controls.Add(this.listBox1);",<br />" this.Controls.Add(this.rt1);",<br />" this.Controls.Add(this.button1);",<br />" this.Controls.Add(this.bt_itself);",<br />" this.Name = \"Form1\";",<br />" this.Text = \"Form1\";",<br />" this.Load += new System.EventHandler(this.Form1_Load);",<br />" this.ResumeLayout(false);",<br />" }",<br />" #endregion",<br />"",<br />" /// Point d'entrée principal de l'application.",<br />" [STAThread]",<br />" static void Main()",<br />" {",<br />" Application.Run(new Form1());",<br />" }",<br />"// methode de base ",<br />" string join(string[] arr,string sep)",<br />" {string strReturn=\"\" ;",<br />" foreach (string elt in arr)",<br />" strReturn += elt+sep;",<br />" strReturn.Substring(0,strReturn.Length-sep.Length);",<br />" ",<br />" return strReturn;",<br />" }",<br />"",<br />" void seekandreplace(string[] arr,string strSrc,string strReplace)",<br />" {",<br />" int i=0;",<br />" for(i=0;i<=arr.Length-1;i++)",<br />" { if(arr[i]==strSrc)",<br />" arr[i]=strReplace;",<br />" }",<br />" }",<br />" string format (string str)",<br />" {",<br />" str = str.Replace(\"\\\\\",\"\\\\\\\\\");",<br />" str = str.Replace(\"\\\"\",\"\\\\\\\"\");",<br />" return str; ",<br />" }",<br />" string joinformat(string[] arr,string sep)",<br />" {",<br />" string strReturn= \"\" ;",<br />" foreach (string elt in arr)",<br />" { strReturn +=format( elt)+sep;}",<br />" ",<br />" strReturn = strReturn.Substring( 0,strReturn.Length-sep.Length);",<br />" ",<br />" return strReturn;",<br />" }",<br />" private void Form1_Load(object sender, System.EventArgs e)",<br />" {",<br />" //nothing special here ",<br />" }",<br />"",<br />" private void button1_Click(object sender, System.EventArgs e)",<br />" {// here is starting the main part of the code:",<br />" //",<br />" //the CodeCompileUnit is the abstract code structure:",<br />"",<br />" // Create a new CodeCompileUnit to contain the program graph",<br />" CodeCompileUnit CompileUnit = new CodeCompileUnit();",<br />" // Declare a new namespace called Samples.",<br />" CodeNamespace Samples = new CodeNamespace(\"Samples\");",<br />" // Add the new namespace to the compile unit.",<br />" CompileUnit.Namespaces.Add( Samples );",<br />"",<br />" // Add the new namespace import for the System namespace.",<br />" Samples.Imports.Add( new CodeNamespaceImport(\"System\") );",<br />"",<br />" // Declare a new type called Class1.",<br />" CodeTypeDeclaration Class1 = new CodeTypeDeclaration(\"echo\");",<br />" // Add the new type to the namespace's type collection.",<br />" Samples.Types.Add(Class1);",<br />"",<br />" //a variable declaration",<br />" CodeVariableDeclarationStatement Var = new",<br />" CodeVariableDeclarationStatement(\"System.String\",\"str1\");",<br />" // Declare a new code entry point method",<br />" CodeEntryPointMethod Start = new CodeEntryPointMethod();",<br />" // Create a new method invocation expression.",<br />" CodeMethodInvokeExpression cs1 =",<br />" new CodeMethodInvokeExpression(",<br />" // Call the System.Console.WriteLine method.",<br />" ",<br />" new CodeTypeReferenceExpression(\"System.Console\"), \"ReadLine\");",<br />" CodeAssignStatement as1 = new CodeAssignStatement(",<br />" new CodeVariableReferenceExpression(\"str1\"),cs1);",<br />"",<br />" // Create a new method invocation expression.",<br />" CodeMethodInvokeExpression cs2 =",<br />" new CodeMethodInvokeExpression(",<br />" // Call the System.Console.WriteLine method.",<br />" new CodeTypeReferenceExpression(\"System.Console\"), \"WriteLine\");",<br />" cs2.Parameters.Add(new CodeVariableReferenceExpression(Var.Name));",<br />"",<br />" Start.Statements.Add(Var);",<br />" // Add the new method code statement.",<br />" Start.Statements.Add( as1);",<br />" // Add the new method code statement.",<br />" Start.Statements.Add(new CodeExpressionStatement(cs2));",<br />"",<br />" // Add the code entry point method to the type's members collection",<br />" Class1.Members.Add( Start );",<br />"",<br />"",<br />" System.IO.StringWriter Sw = new System.IO.StringWriter();",<br />"",<br />" ",<br />" Microsoft.CSharp.CSharpCodeProvider provider =",<br />" new CSharpCodeProvider();",<br />" System.CodeDom.Compiler.ICodeGenerator generator = provider.CreateGenerator(Sw);",<br />" CodeGeneratorOptions genOptions = new CodeGeneratorOptions();",<br />"",<br />" // The code generator should insert blank lines ",<br />" genOptions.BlankLinesBetweenMembers = true;",<br />"",<br />" try",<br />" {",<br />" generator.GenerateCodeFromCompileUnit(CompileUnit,Sw,genOptions);",<br />" }",<br />" catch (Exception Exc)",<br />" {",<br />" System.Windows.Forms.MessageBox.Show (Exc.Message);",<br />" }",<br />" rt1.Text = Sw.ToString();",<br />"",<br />" }",<br />" ",<br />" private void button2_Click(object sender, System.EventArgs e)",<br />" {",<br />" Microsoft.CSharp.CSharpCodeProvider provider =",<br />" new CSharpCodeProvider();",<br />" ///",<br />"// Compilation ",<br />" //instanciate csharp compiler",<br />" System.CodeDom.Compiler.ICodeCompiler MyCompiler = provider.CreateCompiler();",<br />" System.CodeDom.Compiler.CompilerParameters cp = new CompilerParameters();",<br />" cp.GenerateExecutable = true;",<br />" cp.CompilerOptions= \" /target:exe\";",<br />" cp.ReferencedAssemblies.AddRange( new string[]{\"System.Windows.Forms.dll\",\"System.dll\",\"System.drawing.dll\",\"\"});",<br />" //where your exe will be saved",<br />" cp.OutputAssembly = \"c:\\\\echo.exe\";",<br />" // Invoke compilation.",<br />" CompilerResults cr = MyCompiler.CompileAssemblyFromSource ( cp,rt1.Text);",<br />" //",<br />" // Return the results of compilation.",<br />"",<br />" //eventually load compilation output to the listbox (usefull to debug)",<br />" listBox1.DataSource=cr.Output;",<br />"",<br />" //where is it? ",<br />" MessageBox.Show ( cr.PathToAssembly );",<br />" }",<br />"",<br />" private void bt_itself_Click(object sender, System.EventArgs e)",<br />" {",<br />" string[] arr=new string[]{",<br />"Les sanglots longs des violons de l'automne bercent mon coeur d'une langueur monotone",<br />" };",<br />" seekandreplace(arr,\"Les sanglots longs des violons de l'automne bercent mon coeur d'une langueur monotone\",\"\\\"\"+joinformat(arr,\"\\\",\\n\\\"\")+\"\\\"\");",<br />" this.rt1.Text = join(arr,\"\\n\");",<br />" }",<br />" }",<br />"}"<br /> };<br /> seekandreplace(arr,"Les sanglots longs des violons de l'automne bercent mon coeur d'une langueur monotone","\""+joinformat(arr,"\",\n\"")+"\"");<br /> this.rt1.Text = join(arr,"\n");<br /> }<br /> }<br />}<br /><br /><br /></font>Marcnoreply@blogger.com