14 Temmuz 2017 Cuma

C# Runtime Code Execution

using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.CSharp;

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

        private void button1_Click(object sender, EventArgs e)
        {
           
            string source =
                @"
namespace RuntimeCoreExecution
{
using System;
using System.Linq;
using System.Windows.Forms;
    public partial class Form1
    {
        public void SelamSoyle()
        {
               var textBox = System.Windows.Forms.Application.OpenForms[""Form1""].Controls.Find(""textBox1"", true).FirstOrDefault() as TextBox;
               textBox.Text = ""Selam"";
        }
    }
}
            ";


            Dictionary providerOptions = new Dictionary
            {
                {"CompilerVersion", "v4.0"}
            };
            CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);

         
            var compilerParams = new CompilerParameters()
            {
                GenerateInMemory = true,
                GenerateExecutable = false,
                ReferencedAssemblies =
                {
                    "System.dll",
                    "System.Core.dll",
                    "System.Data.dll",
                    "System.Xml.dll",
                    "System.Xml.Linq.dll",
                    "System.Windows.Forms.dll",

                },
            };



            CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);

            if (results.Errors.Count != 0)
                throw new Exception("Mission failed!");

            object o = results.CompiledAssembly.CreateInstance("RuntimeCoreExecution.Form1");
            MethodInfo mi = o.GetType().GetMethod("SelamSoyle");
            mi.Invoke(o, null);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var textBox = Application.OpenForms["Form1"].Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
            textBox.Text = "Selam";
        }
    }
}

Hiç yorum yok:

Yorum Gönder