CodeDom : compile partial class

Posted by James on Stack Overflow See other posts from Stack Overflow or by James
Published on 2010-04-24T06:17:36Z Indexed on 2010/04/24 6:23 UTC
Read the original article Hit count: 435

Filed under:
|
|

I'm attempting to compile code in a text file to change a value in a TextBox on the main form of a WinForms application. Ie. add another partial class with method to the calling form. The form has one button (button1) and one TextBox (textBox1).

The code in the text file is:

this.textBox1.Text = "Hello World!!";

And the code:

namespace WinFormCodeCompile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Load code from file
            StreamReader sReader = new StreamReader(@"Code.txt");
            string input = sReader.ReadToEnd();
            sReader.Close();

            // Code literal
            string code =
                @"using System;
                  using System.Windows.Forms;

                  namespace WinFormCodeCompile
                  {
                      public partial class Form1 : Form
                      {

                           public void UpdateText()
                           {" + input + @"
                           }
                       }
                   }";

            // Compile code
            CSharpCodeProvider cProv = new CSharpCodeProvider();
            CompilerParameters cParams = new CompilerParameters();
            cParams.ReferencedAssemblies.Add("mscorlib.dll");
            cParams.ReferencedAssemblies.Add("System.dll");
            cParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            cParams.GenerateExecutable = false;
            cParams.GenerateInMemory = true;

            CompilerResults cResults = cProv.CompileAssemblyFromSource(cParams, code);

            // Check for errors
            if (cResults.Errors.Count != 0)
            {
                foreach (var er in cResults.Errors)
                {
                    MessageBox.Show(er.ToString());
                }
            }
            else
            {
                // Attempt to execute method.
                object obj = cResults.CompiledAssembly.CreateInstance("WinFormCodeCompile.Form1");
                Type t = obj.GetType();
                t.InvokeMember("UpdateText", BindingFlags.InvokeMethod, null, obj, null);
            }


        }
    }
}

When I compile the code, the CompilerResults returns an error that says WinFormCodeCompile.Form1 does not contain a definition for textBox1.

Is there a way to dynamically create another partial class file to the calling assembly and execute that code?

I assume I'm missing something really simple here.

© Stack Overflow or respective owner

Related posts about codedom

Related posts about c#