<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ramunas Geciauskas &#187; Programming</title>
	<atom:link href="http://geciauskas.com/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://geciauskas.com</link>
	<description>Imagination is more important than knowledge</description>
	<lastBuildDate>Thu, 04 Aug 2011 18:33:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Dynamically Creating .NET Assembly with System.Reflection and Emit</title>
		<link>http://geciauskas.com/dynamically-creating-net-assembly-with-system-reflections/</link>
		<comments>http://geciauskas.com/dynamically-creating-net-assembly-with-system-reflections/#comments</comments>
		<pubDate>Thu, 10 Feb 2011 19:58:14 +0000</pubDate>
		<dc:creator>Ramas</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[deleteafterrunning]]></category>
		<category><![CDATA[emit]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://geciauskas.com/?p=223</guid>
		<description><![CDATA[While creating DeleteAfterRunning application which allows to build self-deleting executable files, I come across System.Reflection class in .NET for creating assemblies in the run-time. All .NET assemblies are made from [...]]]></description>
			<content:encoded><![CDATA[<p>While creating <a href="http://geciauskas.com/deleteafterrunning">DeleteAfterRunning</a> application which allows to build self-deleting executable files, I come across System.Reflection class in .NET for creating assemblies in the run-time. All .NET assemblies are made from IL code which you can examine using any .NET dissembler. I use IL Dasm which comes with a Visual Studio.</p>
<h3>Dynamically Creating a New .NET Assembly</h3>
<p>Classes we need to examine are:</p>
<ul>
<li>AppDomain &#8211; controls isolated environment where our assemblies are running</li>
<li>AssemblyName &#8211; allows us to identify our assembly</li>
<li>AssemblyBuilder &#8211; key class for creating a new assembly dinamically</li>
<li>ModuleBuilder, TypeBuilder, MethodBuilder &#8211; additional classes used to define methods, types, etc</li>
<li>ILGenerator &#8211; class which generates .NET IL code for us</li>
</ul>
<h3>Code:</h3>
<pre class="brush: csharp; title: ; notranslate">
using System.Reflection;
using System.Reflection.Emit;
</pre>
<pre class="brush: csharp; title: ; notranslate">
private static void GenerateNewAssembly(string name, string fileName)
{
    // get an instance to our isolated environment, aka ApplicationDomain
    AppDomain appDomain = AppDomain.CurrentDomain;

    // create a descriptor for our new assembly and define its name
    AssemblyName assemblyName = new AssemblyName(name);

    // define AssemblyBuilder and assign its rights
    AssemblyBuilder aBuilder = appDomain.DefineDynamicAssembly(assemblyName,
        AssemblyBuilderAccess.Save);    // AssemblyBuilder can only save our new assembly

    // creating assembly's core module specifying name and file name (location)
    ModuleBuilder mBuilder = aBuilder.DefineDynamicModule(name, fileName);

    // define a Type that we'll use
    TypeBuilder tBuilder = mBuilder.DefineType(name + &quot;Type&quot;, TypeAttributes.Public);

    // and finally let's define our first method - Main() (which is required for any executable file)
    MethodBuilder methodBuilder = tBuilder.DefineMethod(&quot;Main&quot;,
        MethodAttributes.Public | MethodAttributes.Static,  // method attributes == public static void Main() {}
        null, null);

    // declare that your Main function will be an entry point for our assembly
    aBuilder.SetEntryPoint(methodBuilder,
        PEFileKinds.ConsoleApplication); // we will set a target to CUI rather than GUI for this example

    // IL code generator for our Main method
    ILGenerator il = methodBuilder.GetILGenerator();
    // create our IL code
    CreateIL(il);

    // create our defined Type
    tBuilder.CreateType();

    // save our new assembly
    aBuilder.Save(fileName);
}

private static void CreateIL(ILGenerator il)
{
    // System.Console.WriteLine(&quot;Hello World!&quot;); translated to IL code with ILGenerator help
    il.EmitWriteLine(&quot;Hello World!&quot;);
    // end Main method with a return call
    il.Emit(OpCodes.Ret);
}
</pre>
<h3>Adding IL Code</h3>
<p>Now we can call <em>GenerateNewAssembly(&#8220;Test&#8221;, &#8220;test.exe&#8221;)</em> method to generate a new Test assembly in &#8220;test.exe&#8221; file. The new executable file can be used as any other .NET .exe assembly, but all it does &#8211; displays a simple &#8220;Hello World!&#8221; text and quits. What if we want to add some functionality? Let&#8217;s say, add <em>Console.ReadKey()</em> method to wait for user&#8217;s input before closing. Time to expand our <em>CreateIL()</em> method and dive into IL code.</p>
<p>First, we need to figure out what IL operation codes we need to use to call <em>Console.ReadKey()</em> method. Let&#8217;s create a simple console application that has only a <em>Console.ReadKey()</em> in it. Compile. Run Visual Studio Command Prompt and start IL Dasm (execute &#8220;ildasm&#8221; command in the command prompt). Open the assembly and check IL code.</p>
<pre class="brush: plain; title: ; notranslate">
.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       8 (0x8)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  call       valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey()
  IL_0006:  pop
  IL_0007:  ret
} // end of method Program::Main
</pre>
<ul>
<li>Line 8 &#8211; <em>nop</em> operation that does absolutely nothing. Just skips the CPU cycle (mainly used to reduce overhead).</li>
<li>Line 9 &#8211; <em>call</em> operation with provided argument to specific method.</li>
<li>Line 10 &#8211; <em>pop</em> operation, which &#8220;pops&#8221; last entry in the assembly allocated stack. Stack is a place where methods pass their results, and since ReadKey() method returns us <em>ConsoleKeyInfo</em> object, we need to retrieve (&#8220;pop&#8221;) it from the stack, even if we won&#8217;t use it.</li>
<li>Line 11 &#8211; <em>ret</em> operation equivalent to <em>return</em> call, which ends our method&#8217;s execution.</li>
</ul>
<p>So, let&#8217;s extend our <em>CreateIL()</em> method to incorporate this IL.</p>
<pre class="brush: csharp; title: ; notranslate">
private static void CreateIL(ILGenerator il)
{
    // System.Console.WriteLine(&quot;Hello World!&quot;); translated to IL code with ILGenerator help
    il.EmitWriteLine(&quot;Hello World!&quot;);

    // get ReadKey() method information
    // GetMethod() will searh for specified method in .NET
    MethodInfo mInfo = typeof(System.Console).GetMethod(&quot;ReadKey&quot;,
        Type.EmptyTypes);       // we're not passing any parameters therefore Type.EmptyTypes
        // if we're looking for a method with additional parameters, you would need to specify their type
        // ...new Type[] { typeof(..), .. }
        // i.e. WriteLine(&quot;Hello&quot;) would be:
        // MethodInfo mInfo = typeof(System.Console).GetMethod(&quot;WriteLine&quot;, new Type[] { typeof(String) });

    // write &quot;call&quot; OP code with ReadKey method's information
    il.Emit(OpCodes.Call, mInfo);

    // pop the stack - retrieving the result
    il.Emit(OpCodes.Pop);

    // end Main method with a return call
    il.Emit(OpCodes.Ret);
}
</pre>
<h3>Conclusion</h3>
<p>There you have it. By using ILDasm, you can easily explore all OP Codes for any .NET assembly and then using System.Reflection classes recreate it dynamically. Analyzing our newly created test.exe with ILDasm, we can see that our IL looks exactly the same as we originally wanted.<br />
<a href="http://geciauskas.com/wp-content/uploads/2011/02/msil_ss.png"><img class="size-full wp-image-229 alignnone" title="ILDASM" src="http://geciauskas.com/wp-content/uploads/2011/02/msil_ss.png" alt="ILDASM" width="457" height="458" /></a></p>
<p><i>You can explore <a href="http://deleteafterrunning.codeplex.com/SourceControl/list/changesets">DeleteAfterRunning sources </a>for more examples of Emit class usage.</i></p>
]]></content:encoded>
			<wfw:commentRss>http://geciauskas.com/dynamically-creating-net-assembly-with-system-reflections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

