Click here to Skip to main content
12,815,057 members (39,907 online)
Click here to Skip to main content
Articles » Languages » MSIL » General » Downloads

Stats

15.6K views
646 downloads
13 bookmarked
Posted 21 Sep 2012

IlPad

, 21 Sep 2012 CPOL
A program to compile C# code into MSIL code.
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.CSharp;

namespace IlPad
{
    public partial class MainForm : Form
    {
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, int[] lParam);

        public MainForm()
        {
            InitializeComponent();

            var graphics = txtInputProgram.CreateGraphics();
            var charWidth = (int)graphics.MeasureString("M", txtInputProgram.Font).Width;
            SendMessage(txtInputProgram.Handle, 0x00CB, 1, new[] { 1 * charWidth });
            graphics.Dispose();
        }

        private void MainFormLoad(object sender, EventArgs e)
        {
            LoadSnippet();

            lbReferences.Items.Add("Microsoft.CSharp");
            lbReferences.Items.Add("System.Core");
            lbReferences.Items.Add("System.Data");
            lbReferences.Items.Add("System.Dynamic");

            MinimumSize = new Size(587, 572);
            FixLayout();
        }

        private void BtnCompileClick(object sender, EventArgs e)
        {
            lvErrors.Items.Clear();
            txtOutputIl.Text = "";
            var options = new Dictionary<string, string> {{"CompilerVersion", "v4.0"}};
            var provider = new CSharpCodeProvider(options);

            var parms = new CompilerParameters
                {
                    CompilerOptions = @"/lib:C:\Windows\assembly\GAC /target:library",
                    GenerateExecutable = true,
                    GenerateInMemory = false
                };
            parms.ReferencedAssemblies.Add("System.dll");
            foreach (string item in lbReferences.Items)
            {
                parms.ReferencedAssemblies.Add(item + ".dll");
            }
            string outFile = Path.GetTempFileName();
            string ilOutFile = Path.GetTempFileName();
            string ildasm = Path.GetTempFileName() + ".exe";
            parms.OutputAssembly = outFile;

            CompilerResults res = provider.CompileAssemblyFromSource(parms, txtInputProgram.Text);
            if (res.Errors.HasErrors)
            {
                try
                {
                    File.Delete(outFile);
                } catch
                {
                }
                try
                {
                    File.Delete(ildasm);
                } catch
                {
                }
                try
                {
                    File.Delete(ilOutFile);
                } catch
                {
                }
                BindErrors(res);
                return;
            }
            ExpandIlDasm(ildasm);
            var startInfo = new ProcessStartInfo();
            var p = new Process();

            startInfo.CreateNoWindow = true;
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardOutput = true;
            startInfo.Arguments = "/out:" + ilOutFile + " " + outFile;
            startInfo.FileName = ildasm;
            p.StartInfo = startInfo;

            p.Start();
            p.WaitForExit();

            var sr = new StreamReader(ilOutFile);
            string outfile = sr.ReadToEnd();
            sr.Close();
            txtOutputIl.Text = outfile;
            try
            {
                File.Delete(outFile);
            }
            catch
            {
            }
            try
            {
                File.Delete(ildasm);
            }
            catch
            {
            }
            try
            {
                File.Delete(ilOutFile);
            }
            catch
            {
            }
        }

        private void ExpandIlDasm(string file)
        {
            Assembly objAssembly = Assembly.GetExecutingAssembly();
            var objStream = objAssembly.GetManifestResourceStream("IlPad.ildasm.exe");
            var ildasmResource = new byte[objStream.Length];
            objStream.Read(ildasmResource, 0, (int)objStream.Length);
            var objFileStream = new FileStream(file, FileMode.Create);
            objFileStream.Write(ildasmResource, 0, (int)objStream.Length);
            objFileStream.Close();
        }

        private void BtnAddReferenceClick(object sender, EventArgs e)
        {
            var dlg = new AddReferenceDialog();
            DialogResult dr = dlg.ShowDialog();
            if (dr == DialogResult.OK)
            {
                lbReferences.Items.Add(dlg.SelectedReference);
            }
        }

        private void BindErrors(CompilerResults res)
        {
            lvErrors.Items.Clear();
            foreach (CompilerError error in res.Errors)
            {
                var item = new ListViewItem
                    {
                        Text = error.ErrorText
                    };
                item.SubItems.Add(error.Line.ToString(CultureInfo.InvariantCulture));
                lvErrors.Items.Add(item);
            }
        }

        private void MainFormResize(object sender, EventArgs e)
        {
            FixLayout();
        }

        private void FixLayout()
        {
            lbReferences.Location = new Point(ClientSize.Width - 145, 55);
            lbReferences.Size = new Size(lbReferences.Width, ClientSize.Height - 175);
            btnAddReference.Location = new Point(ClientSize.Width - 145, 28);

            txtInputProgram.Size = new Size(ClientSize.Width - 179, ClientSize.Height - 360);
            lineNumbers_For_RichTextBox1.Height = ClientSize.Height - 360;

            btnCompile.Location = new Point(txtInputProgram.Location.X,
                                            txtInputProgram.Location.Y + txtInputProgram.Size.Height + 10);
            txtOutputIl.Location = new Point(btnCompile.Location.X, btnCompile.Location.Y + 30);

            btnCompile.Size = new Size(txtInputProgram.Size.Width, btnCompile.Size.Height);
            txtOutputIl.Size = new Size(txtInputProgram.Size.Width, txtOutputIl.Size.Height);
        }

        private void LoadSnippet()
        {
            using (var sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("IlPad.Snippet.cs")))
            {
                txtInputProgram.Text = sr.ReadToEnd();
            }
        }

        private void LoadSnippet2()
        {
            using (var sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("IlPad.Snippet2.cs")))
            {
                txtInputProgram.Text = sr.ReadToEnd();
            }
        }

        private void btnLoadSnippet1_Click(object sender, EventArgs e)
        {
            LoadSnippet();
        }

        private void btnLoadSnippet2_Click(object sender, EventArgs e)
        {
            LoadSnippet2();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

icemanind
Web Developer http://www.icemanind.com
United States United States
No Biography provided

You may also be interested in...

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170308.1 | Last Updated 22 Sep 2012
Article Copyright 2012 by icemanind
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid