Search code examples
c#dynamiccompilationdynamically-generatedcompiled

Use program class from my dynamically compiled form


I have a class that Read/Write from registry. But how can i use this class from dynamically compiled form. I can execute function and even get var valuables from dynamically compiled form, but how can i execute my program function or get var valuable from my dynamically compiled form.

RegistryHelper class

using Microsoft.Win32;

namespace myForm
{
    class RegistryHelper
    {
        public void WriteKey(string k, string value)
        {
            RegistryKey key = Registry.CurrentUser.CreateSubKey("rGO");
            key.SetValue(k, value);
            key.Close();
        }

        public string ReadKey(string k)
        {
            RegistryKey op = Registry.CurrentUser.OpenSubKey("rGO");
            return (string)op.GetValue(k);
        }
    }
}

Example where i execute test function inside Form1 class

using System;
using System.CodeDom.Compiler;
using System.IO;
using Microsoft.CSharp;

namespace myForm
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var foo = new CSharpCodeProvider())
            {
                var parameters = new CompilerParameters
                {
                    GenerateInMemory = true,
                    GenerateExecutable = false
                };

                parameters.ReferencedAssemblies.Add("System.dll");
                parameters.ReferencedAssemblies.Add("System.Core.dll");
                parameters.ReferencedAssemblies.Add("System.Drawing.dll");
                parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");

                var source = File.ReadAllText("form.txt");
                CompilerResults results = foo.CompileAssemblyFromSource(parameters, source);
                Type type = results.CompiledAssembly.GetType("myForm.Form1");
                object compiledObject = Activator.CreateInstance(type);

                // Execure test function from dynamically compiled form
                type.GetMethod("test").Invoke(compiledObject, new object[] { });
            }
        }
    }
}

form.txt source

using System.Windows.Forms;

namespace myForm
{
    public partial class Form1 : Form
    {
        public static int _testVar = 0; // how can i get this var value?
        public Form1()
        {
            InitializeComponent();
        }

        public void test()
        {
            MessageBox.Show("test");
        }
    }
}

namespace myForm
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // richTextBox1
            // 
            this.richTextBox1.Location = new System.Drawing.Point(12, 12);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.Size = new System.Drawing.Size(260, 204);
            this.richTextBox1.TabIndex = 0;
            this.richTextBox1.Text = "";
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(12, 222);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(260, 40);
            this.button1.TabIndex = 1;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 274);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.richTextBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.RichTextBox richTextBox1;
        private System.Windows.Forms.Button button1;
    }
}

Solution

  • To do this, you just need to add a reference to itself in the references compiled code:

    using System;
    using System.CodeDom.Compiler;
    using System.IO;
    using System.Reflection;
    using System.Windows.Forms;
    using Microsoft.CSharp;
    
    namespace ConsoleApplication212
    {
        class Program
        {
            static void Main(string[] args)
            {
                //dynamic code
                var source = @"
                static class Program
                {
                    public static void Start()
                    {
                        //We call the Test method of the class Console Application 212.Helper
                        ConsoleApplication212.Helper.Test();
                    }
                }";
    
                //compile and run
                Run(source);
    
                Console.ReadLine();
            }
    
            static void Run(string source)
            {
                using (var provider = new CSharpCodeProvider())
                {
                    var parameters = new CompilerParameters { GenerateInMemory = true };
    
                    parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                    //link your self
                    parameters.ReferencedAssemblies.Add(Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase));
    
                    //compile
                    var result = provider.CompileAssemblyFromSource(parameters, source);
                    if (result.Errors.Count > 0)
                        throw new Exception(result.Errors[0].ErrorText);
    
                    //Find class Program
                    var type = result.CompiledAssembly.GetType("Program");
                    //вызыаем метод Start
                    type.GetMethod("Start").Invoke(null, null);
                }
            }
        }
    
        /// <summary>
        /// Public class that will be used in dynamically compiled code
        /// </summary>
        public static class Helper
        {
            public static void Test()
            {
                MessageBox.Show("Hi from Helper");
            }
        }
    }