dotRant: Making an IRC library for .NET in C# – Part 5: Reflection and IRCCommands

Last post we discussed methods of responding to messages coming from the IRC-server, and I also explained the method I wanted to use, and why I would want to use it. Today I will do the actual implementation of the described method. Also, to handle IRC commands, we need to parse them, and we need a method of sending replies to the server, and last but not least we need to create the attribute to be set on the methods that we want called. But lets start with the first thing first:
Continue reading

dotRant: Making an IRC library for .NET in C# – Part 4: Skeletal structure of the IrcClient and the DefaultDictionary

In the previous post in this series I talked about some errors I found in the dotRant code, and what had to be done to fix those, and I also talked a bit about taking an async approach to connecting to the server. This will allow for better responsiveness in applications using dotRant while still maintaining a simple way of using the library tanks to the System.Threading.Tasks namespace. In this post I will create the actual base structure of the IrcClient-class, and also construct a helper-class that I call DefaultDictionary, but first of all, let’s take a look at the problem we have at hand.

Irc consists of messages (or as I like to call them, commands) sent back and forth from client and server. These messages all contains a name which can be viewed as a string (though it might just be a number). We’ve already made functionality for sending and receiving these messages, however, we need to act upon the fact that there is a new command available, and depending upon how we decide to do this our class might end up as a mess, or it might end up being neat and tidy. I don’t think I have to tell you that I don’t want the class to end up as a mess, so let’s look at some of the alternative ways of handling commands sent from the server.
Continue reading

dotRant: Making an IRC library for .NET in C# – Part 3: A word about asynchronism (and some bug-fixes)

In my previous post we created a MessageConnection to be used with our IRC-library. The MessageConnection in it self might be used for other things than IRC though, but for but our goal is to implement it in our IRC-library. However, as I might have stated in my previous post, the code posted there was never tested. Thus, the likeliness of there being bugs is pretty high, and as one would suspect I found several of them. Some of the bugs were pretty trivial (like forgetting to append CRLF to the messages we send to the server), but others were more severe. Let’s start by fixing the first one, which was that we need to append CRLF to all messages sent from our application. To fix this is fairly simple, just update the Send-method to look like this:

        /// <summary>
        /// Sends the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        public void Send(byte[] message)
        {
            message = RemoveCrLf(message);
            var buffer = new byte[message.Length + 2];
            message.CopyTo(buffer, 0);
            buffer[buffer.Length - 2] = 13; // CR
            buffer[buffer.Length - 1] = 10; // LF
            logger.Debug(">> {0}", Encoding.UTF8.GetString(message));
            lock (sendBuffer)
                sendBuffer.Write(buffer, 0, buffer.Length);
            TransferData(null);
        }

The next couple of bugs are a bit worse. They concern the DataReceived-method, and two of them is about copying arrays, and the last one is about what happens when the connection to the other end is lost. To tackle the problem with lost connections I’ve added a event called “Disconnect”, and a “OnDisconnect”-method (same as with the other events), and then I’ve added the following piece of code right after the EndReceive-call in DataReceived

            if (receivedDataLength == 0)
            {
                logger.Debug("Disconnected");
                client.Close();
                OnDisconnect();
                return;
            }

Next, in the same function you want to replace
buffer.CopyTo(data, bufferLength);

with
Array.Copy(buffer, 0, data, bufferLength, receivedDataLength);

and then you want to replace
byte[] message = new byte[i];
Array.Copy(data, msgStart, message, 0, i); // Copy data[msgStart:i] to message

with
byte[] message = new byte[i - msgStart];
Array.Copy(data, msgStart, message, 0, i - msgStart); // Copy data[msgStart:i] to message

After this is done we can move on to the next topic.
Continue reading

dotRant: Making an IRC library for .NET in C# – Part 2: The message connection

Last time I showed you the basics of how IRC works. If you have yet to read that part, I recommend you read it. As I showed you, IRC works by sending commands back and forth, from the client and the server. The commands are separated by “CRLF” (windows newline), and consist of only text. This makes parsing of IRC pretty easy, so today we’ll start by creating what I call a message connection. But first, for those of you who have not worked with networking in .NET before, a quick summary.

Networking in .NET can be done in several ways. We can use plain old sockets, or we can use one of the wrappers that are provided to us for simplicity (like the “TcpClient”-class). Personally I like to work with the socket-class, however, as I want our library to be able to connect to servers using SSL and TLS, I’ve found that you need to have a Stream, and those are simply provided to us by the “TcpClient”-class, so for simplicity we are using that one, or rather, the “NetworkStream” we get from it. Streams support 2 things in basic, sending and receiving of binary data. That means that we need to interpret the data as text ourselves. Also, networking can be done asynchronously, and synchronously. We need to implement our library asynchronously, because we want it to be event-driven, so that when we receive a message we tell the application that a message has been received, rather than the application waiting for messages for us. Anyway, enough about that for now, we can get back to that later. One more thing before we start. I’m using NLog to implement logging in our library. Just thought I’d let you know. Now, let’s start with some code already xD.
Continue reading

dotRant: Making an IRC library for .NET in C# – Part 1: The IRC protocol

Hi, and welcome to my first blog-series ever. This blog series is about creating a IRC library in C#, that can (hopefully xD) be used by any .NET language. If you do not know what IRC is, it stands for “Internet Relay Chat” and is an old chatting-protocol. Not that many people use IRC anymore, and many people don’t see a reason why they should use it either. For me the point about IRC is that it takes a bit of a different approach on chatting than most modern chatting-application, and it’s made to chat with groups, not single persons. The point with IRC is that you enter a “room”, or a “group”, and then send messages to them, as opposed to applications like WLM which are made to send person to person messages. I know that most modern IM’s also has the capability to do group-chats, but you need to be invited to those. You can’t just join a group based on its name and talk to persons you have never talked to before, and that’s what I use IRC for.

Then the question comes to mind, why on earth would I want to write a library for IRCing in .NET? The answer is simple, to make a bot. Or several bots actually. And in some feature, I’d really like to create an IRC client in WPF, simply for the fun of doing it, but currently I’m focusing on the bot part. Another thing to know about this series is that I don’t know when it’s going to be finished, or how complete my library will be when I reach that point, because, to simply make a capable IRC bot, does not require it to understand all of the data coming from the IRC server. It can simply disregard what it doesn’t understand, and that works out just fine. The same can be said for all IRC clients. Most clients I’ve used, if they receive something they don’t understand, they simply display it to the user as-is, without any changes, and display it as a message received from the server itself. But anyways, we’ll see more about that when we get a little further.

Continue reading

MutableObject 1.2 – Reset the state of mutable-objects.

I just updated MutableObject with a new feature which I just thought I’d show. To make this short (I don’t have time for long posts right now) I’ll just post a unit-test that shows the new behavior perfectly.

public interface Interface1
{
	string Name { get; set; }
}

public class Class1 : Interface1
{
	public string Name { get; set; }
}

[TestFixture]
public class MutableObjectTests
{

	[Test]
	public void CanResetTest()
	{
		Interface1 obj = new Class1();

		obj.Name = "Per";

		Interface1 obj1 = Mutate.CreateMutableObject<Interface1>();
		Interface1 obj2 = Mutate.CreateMutableObject<Interface1>(obj);

		obj1.Name = "Knut";
		obj2.Name = "Knut";

		Assert.AreEqual(obj.Name, "Knut");

		Mutate.Reset(obj1);
		Mutate.Reset(obj2);

		Assert.AreEqual(obj.Name, "Per");
		Assert.IsFalse(Mutate.PropertiesIsSet(obj1, "Name"));
	}
	
}

I’ve also edited my nuget-build-rutine (for later releases) so that it includes the xml-documentation for the methods. Hope someone finds this useful :) .

Later.

MutableObject – Track state of simple CLR objects

I recently released my very first package to NuGet. Enter MutableObject, used to create and manage CLR-objects that you can track state of with a few simple calls. Ever came into a situation where you wanted to know what properties has changed since some point in your code? To do so, you needed to rewrite every setter in the entire class, and that’s simply painful to do when this is a task that could be solved automatically. MutableObject solves this, but let me just illustrate this problem first:

public interface IContact
{
    int Id { get; set; }
    string Name { get; set; }
    string Email { get; set; }
}

public class Contact : IContact
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}
public class ContactRepo
{
	public IContact GetContact(int id)
	{
		// Lots of db-code to get the contact. Not LinqToSql or Entities,
		// plain SQL here.
		if(!result)
			return null;
		return new Contact
		{
			Name = name,
			Email = email,
			Id = id
		};
	}

	public void Update(IContact contact)
	{
		var dbContact = GetContact(contact.Id);
		var qb = new StringBuilder("UPDATE Contacts SET ");
		// Get all the changed properties and loop trough and add
		// the property to the update-query.
		qb.Append(" WHERE Id = ").Append(contact.Id);
	}
}

Now this is just a dummy-problem that I constructed to illustrate how MutableObject might be used, but I think this shows it pretty well. For instance, I’m using concatenation to construct a SQL-query (which you simply shouldn’t do in this day and age). Anyway, my point was to talk about MutableObject, so, in VisualStudio fire up the nuget package manager and run “Install-Package MutableObject”. Then, let’s change our GetContact-method a tiny bit to enable the use of MutableObject.

public IContact GetContact(int id)
{
    // Lots of db-code to get the contact. Not LinqToSql or Entities,
    // plain SQL here.
    if(!result)
        return null;
    var contact = new Contact
    {
        Name = name,
        Email = email,
        Id = id
    };
    return Mutate.CreateMutableObject<IContact>(contact);
}

Now, what we did was to make sure that the GetContact-method returns a MutableObject and not just a simple Contact. The MutableObject returned implement all of IContact (as long as there are only properties), so the object returned from GetContact can be used just like normal. This is called creating a MutableObject with a base-object. The base-object is the contact we passed in as it’s only parameter. It’s also possible to create a MutableObject without a base-object, but if you do, and you try to read a property without setting it first, it will throw an exception. If a MutableObject is created with a base-object (i.e. it is “bound”), all changes done to the MutableObject will be reflected in the base-object, however, you should be careful about changing the base-object after the MutableObject is created, as that is something I have never tried to do, and I have no idea of what the result will be.

Once you have a MutableObject (which you can confirm by calling Mutate.IsMutable(object obj)) you can essentially do two things with it, you can use it like any normal .Net classes, and set/get properties as you like, and you can get a list over the properties that has changed since the MutableObject was created. You can also check if a property/properties is set with the Mutate.PropertiesIsSet(object obj, params string[] propertyNames), however, when using bound items this will always return true.

Now, let’s update our Update-method so that it actually builds the query.

public void Update(IContact contact)
{
	var dbContact = GetContact(contact.Id);
	var qb = new StringBuilder("UPDATE Contacts SET ");
	var props = Mutate.GetChangedProperties(contact);
	foreach(var prop in props)
		qb.Append(prop.Key).Append(" = \"").Append(prop.Value).Append("\", ");
	qb.Remove(qb.Length - 3, 3);
	qb.Append(" WHERE Id = ").Append(contact.Id);
}

And there you have it! Ofcause MutableObject could be inproved (and I plan to do so in the feature). One of the things I plan to implement is the ability to reset the MutableObject, or create a new MutableObject with another mutable-object as a snapshot without applying changes back to the original MutableObject, but that’s all for another time. Hope you can find some use for it :) . Leave me a comment if there is anything you want to ask or don’t understand.

Later.

An introduction to System.Reflection.Emit and OpCodes

A couple of days ago I wrote a tutorial describing how to create a proxy-class generator using System.Refleciton.Emit. After viewing the statistics of what people search for when they enter that tutorial it is clear that the problem seems to be getting dynamic functions created with System.Reflection.Emit to work with DateTime values. I had the same problem myself working with the proxy-class generator, and I thought I’d try to explain a bit. I’m no expert on this subject, but I think I’ve understood enough of it to make it useful, and I will try to tell you what I’ve found out about how the IL-code you generate should look like.

I’m also going to try to make this as practical as possible, so first let’s start by creating a console-application. And then we want to create a method that simply outputs something to the console, just to make sure that everything is working as we expected it to. But before we start writing any methods, I’ve come up with a simple extension-method that will simplify our code a little, add the following few lines to your project:

public static class MethodExtensions
{
	public static object InvokeStatic(this DynamicMethod method,
		params object[] args)
	{
		return method.Invoke(null, args);
	}
	public static T InvokeStatic<T>(this DynamicMethod method,
		params object[] args)
	{
		return (T)method.InvokeStatic(args);
	}
}

This provides a cleaner way to call the methods we create later on. But let’s get started, the first thing we want to do is simply to make our method write something to the console, just to make sure that everything works the way we expect it to. Create a method “Method1″ that returns a DynamicMethod, and write the following in it:

static DynamicMethod Method1()
{
	DynamicMethod method1 = new DynamicMethod("Method1", typeof(void),
		new Type[] { });
	ILGenerator il = method1.GetILGenerator();
	il.EmitWriteLine("Method 1 here");
	il.Emit(OpCodes.Ret);

	return method1;
}

This creates a method that calls Console.WriteLine with the parameter “Method 1 here”. This is the simplest thing you can do with the DynamicMethod, but it’s still a start. The next thing we want to do is to provide the function with a parameter specifying what to write. This isn’t much hard either, the code can look like this:

static DynamicMethod Method2()
{
	DynamicMethod method1 = new DynamicMethod("Method2", typeof(void),
		new Type[] { typeof(string) });
	ILGenerator il = method1.GetILGenerator();
	il.EmitWriteLine("Method 2 begin");

	il.Emit(OpCodes.Ldarg_0);
	il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine",
		new Type[] { typeof(string) }));

	il.EmitWriteLine("Method 2 end");
	il.Emit(OpCodes.Ret);

	return method1;
}

Notice the call to Ldarg_0. This loads the first argument onto the stack. On point to notice though, is that if this was a member-function to some class, Ldarg_0 would load the “this”-object onto the stack. But since this is a “static” function (has no this), arg_0 is the first argument passed in to the function. If you have used python (the programming language) before, this is a lot like the methods in python expects the arguments to be. After the argument is loaded onto the stack, the correct overload of “WriteLine” on the console is called.

Ok, so that’s about it for writing out strings. Also, this was the basic of passing arguments to our function, for the next example, let’s try returning a string. This isn’t hard to do either, you only need to know how it works. To return a value it needs to be the only element on the stack when you call the “ret” statement, and if you function is a void-function this will cause your program to crash, so in void-functions the stack should be empty.

To return the string passed in, simply write this:

static DynamicMethod Method3()
{
	DynamicMethod method1 = new DynamicMethod("Method3", typeof(string),
		new Type[] { });
	ILGenerator il = method1.GetILGenerator();

	il.Emit(OpCodes.Ldstr, "This is a string from method 3");
	il.Emit(OpCodes.Ret);

	return method1;
}

Thats about it for working with complex objects, and types that are passed by reference for now. As most of you probably know there exists two different types of variables in C# and in .NET in general. You have the value-types like int, float, double, etc., and you have the reference-types like string, Window, and all normal classes in general. What people probably don’t know is that a struct is also a value-type (this is the biggest difference between classes and structs if I’m not mistaken). However, a trait of the C# language (and other .NET languages too) is that everything can be passed around as an object (which is reference-type). This includes integers, floats, strings, and everything else. If you create an object-variable in C#, no matter what you try putting in it, you won’t get an error. However, to use the data-piece it either needs to be casted, or looked upon with reflection.

What most people don’t know is that when you take a value-type value and put it in an object-reference, an action is performed on the value-type variable before it is put in the object-reference. This action is called boxing. When you assign an integer or a DateTime or any other value-type value to a object-reference, boxing is done for you automatically, and you don’t really see that it’s done, and when you cast it back, it’s unboxed automatically too. However, when working with System.Reflection.Emit and OpCodes, the boxing and unboxing needs to be taken care of by the programmer (you). But before we start with that, let’s look at a simple example that takes in a DateTime, and returns it, this is fairly strait-forward since there is no object-references involved at all.

static DynamicMethod Method4()
{
	DynamicMethod method1 = new DynamicMethod("Method4", typeof(DateTime),
		new Type[] { typeof(DateTime) });
	ILGenerator il = method1.GetILGenerator();

	il.Emit(OpCodes.Ldarg_0);
	il.Emit(OpCodes.Ret);

	return method1;
}

This works as you would expect it to. You pass the function a DateTime-object and it returns it just like we wanted it to. However, what if we were to make this function into an object-function? If we replace the typeof(DateTime) (the last one) in the creation of the method, and call the method the same way you will get an error, and your code will not work. That is because when you pass the DateTime to the object-function it is automatically boxed for you, and before you can return it as a DateTime-object you need to unbox it. If you try this code however, it should work as the last example:

static DynamicMethod Method5()
{
	DynamicMethod method1 = new DynamicMethod("Method4", typeof(DateTime),
		new Type[] { typeof(object) });
	ILGenerator il = method1.GetILGenerator();

	il.Emit(OpCodes.Ldarg_0);
	il.Emit(OpCodes.Unbox_Any, typeof(DateTime));
	il.Emit(OpCodes.Ret);

	return method1;
}

And if we were to switch the parameters, so that the function accepted a DateTime and returned an object, we’dd just have to switch the Unbox_any with Box, and it would still work. As for a last example, I will provide you with a function that takes in a DateTime and prints it. The overload of the Console.WriteLine I’ll use is the WriteLine(Object) overload. The code is as following:

static DynamicMethod Method6()
{
	DynamicMethod method1 = new DynamicMethod("Method5", typeof(void),
		new Type[] { typeof(DateTime) });
	ILGenerator il = method1.GetILGenerator();

	il.EmitWriteLine("In function 6: ");
	il.Emit(OpCodes.Ldarg_0);
	il.Emit(OpCodes.Box, typeof(DateTime));
	il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine",
		new Type[] { typeof(object) }));

	il.Emit(OpCodes.Ret);

	return method1;
}

If you have any questions please leave them in the comment-section.

Creating a proxyclass-generator using System.Reflection.Emit

I started the other day writing something which I thought might be pretty awesome. A proxyclass-generator. I had no idea at the time how this could be done, but I new it could, because wcf uses something of the sorts. The idea was as following: I want to be able to create a interface as following:

public interface InterfaceA
{
    void DoSomething();
    int GetInt();
    int Multiply(int int1, int int2);
    string TrimString(string str);
}

Then I want to pass that interface to an object or a constructor and get out an object implementing that interface, and also I want to define what happens whenever any and all of the functions are called. The syntax I ended up with is something like this:

ProxyGenerator pg = new ProxyGenerator(IProxyHandler handler);

In this case the IProxyHandler is a simple interface with one function, and that function gets called whenever any function is called on the proxied object. The IProxyHandler-interface looks as following:

public interface IProxyHandler
{
    object OnMethod(MethodInfo method, object[] args);
}

Ok, now we basically have everything we need to start building the ProxyGenerator. But there is a few more decisions to be made. Firstly, I decided that the work of the ProxyGenerator should be done in the constructor, so that the construction of the class is the only thing that is time-consuming. In the constructor we will make our assembly, module and proxy-class. Also, all proxy-classes will be in the same assembly, and in the same module. So the module and the assembly we create our proxy-classes in will be static and thereby “cached” in the ProxyClass, last but not least we don’t want to create the same proxy-class twice, so it should be cached too.

The barebone ProxyGenerator-class (without the acutall proxy-generating) looks as following:

public class ProxyGenerator
{
	private static volatile bool built;
	private static AssemblyBuilder assemblyBuilder;
	private static ModuleBuilder moduleBuilder;
	private static readonly object buildLock = new object();
	private static Dictionary typeCache = new Dictionary();

	private TypeBuilder typeBuilder;

	private T obj;

	public ProxyGenerator(IProxyHandler handler)
	{
		/* do the magic */
	}

	public T Object
	{
		get { return obj; }
	}
}

The built-boolean indicates wheater or not the assembly and module is created, the buildLock is a lock-object to make shure that the assembly and module dosn’t get created twice in different threads, and the typeCache is (as the name suggests) the cache used to store the proxy-classes we’ve created. All of this should be pretty straight forward. The T obj; is where we want to store an instance of the acutal proxy-class. The class will automatically get instantiated.

The first thing to do is to create the assembly and the module, and for this we use the AssemblyBuilder and the ModuleBuilder located inside the ProxyClass’ static variables. Also, we must remember to check if the assembly and module is already created, and we must make it thread-safe. To do so, insert the following code into the constructor:

lock (buildLock)
{
	if (!built)
	{
		assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
			new AssemblyName("NirQ.Proxies"),
			AssemblyBuilderAccess.Run);

		string assemblyName = assemblyBuilder.GetName().Name;

		moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName);
	}
	built = true;
}

I recon you all know the meaning of the lock-keyword, and how it is used, and the rest of the code is pretty straight forward. First we define an assembly named “NirQ.Proxies” (or you might rename it to whatever you like), then create the module. All of the classes proxy-classes created hereafter will be added to the module here created. However, creating an assembly is probably not something you want to do if the class itself isn’t able to be created, so before the code above, add the following three lines:

Type t = typeof(T);
if (!t.IsInterface)
	throw new ArgumentException("T needs to be an interface");

After the generation of the assembly and the module we need to make sure that a proxy-class for this interface has not been created earlier. This is done simply by checking for the typename in the typeCache like so:

if (typeCache.Keys.Contains(typeName))
{
	result = typeCache[typeName];
}
else
{
	// Create the class
}

And now’s about the time when the fun part starts. Creating a “on-the-fly”-class like this is not actually anything that’s hard to do at all, but the hard part is creating the methods that can be called on the class. But before I start talking about that there are some few more lines of code that should be added to the constructor, namely the creation of an empty class that implements the interface given. This should be added inside the else-part of the if-else above.

typeBuilder = moduleBuilder.DefineType(
	String.Format("{0}_NirQ_proxy", t.Name),
	TypeAttributes.Class | TypeAttributes.Public,
	typeof(Object),
	new Type[] { t });

This is a hard to crack nut. The DefineType method on the moduleBuilder has several overloads, but the one I’m using accepts the following arguments: The name of the new class, typeattributes (like this is a public class), the base of the class (for inheritance), and an array of interfaces whom the class inherits. In other word, our class will be named the same as the interface, with “_NirQ_proxy” appended, it’s a public class that inherits from object (same as a default class), and inherits the interface t (t = typeof(T), T is the type-argument given to the class, ie the interface to implement).

Ok, so now we got an empty class. If we try to compile the class as is, we would get an error because the class does not implement all the methods of the interface (unless the interface is empty, or only contains methods already in Object (like “string ToString()”). But before we start implementing the interface itself, lets start with the constructor and the variables we’ll be using. One thing we want to do in a constructor (I don’t know if this is required, but I think it’s good practice) is to call the base constructor. To do so we first need to get a MethodInfo, or rather a ConstructorInfo that represents the constructor we want to call. To get them is simple, just use the following two lines of code:

Type objType = Type.GetType("System.Object");
ConstructorInfo objCtor = objType.GetConstructor(new Type[] { });

The parameter used for GetConstructor is an empty Type-array to specify that we want the default constructor with no parameters. Next thing we want to do is to define a class-wide private variable. This variable will hold the IProxyHandler passed in as a parameter the the constructor we’re currently writing. The proxy-class needs to know of the IProxyHandler so that it can route method-calls to the handler in action. The code to create this field is realy simple, it’s a single line like this:

FieldBuilder proxyFieldBuilder = typeBuilder.DefineField("handler", typeof(IProxyHandler), FieldAttributes.Private);

Ok, and now onto the actual creation of the constructor. To create a constructor we call the DefineConstructor on our TypeBuilder. It needs to know if the constructor should be public/internal/private etc, it’s calling-conventions and the parameters it takes. In this case the function is a instance-method, and has the calling-convention “CallingConventions.HasThis”. The actual functionality of the constructor (like calling the base constructor and saving the parameter as a variable) comes later. The code goes as following:

ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(
	MethodAttributes.Public,
	CallingConventions.HasThis, new Type[] { typeof(IProxyHandler) });

Next up is creating of the actual constructor. What we want the constructor to do is to call the base constructor, then to save the parameter passed to the function onto the private variable. The method used to achieve this is trough the System.Reflection.Emit namespace, and the methode used is ILGenerator.Emit(). The IL-code is a sort of a stack-machine, so if you don’t know what that is you can read along and try to understand, but I would suggest doing some research on the subject. Also, one thing to notice is that we often load in the argument index 0. This is not the first argument to the function (that is argument index 1), but rather the “this” object. Also, whenever you call a function values are popped and pushed onto the stack, so it’s important to keep you head straight. One of the problems I had in early stages was calling return while there was something left on the stack on a void-function. This is the code for the constructor, I will try my best to explain it in detail after the code itself:

ILGenerator cIl = constructorBuilder.GetILGenerator();

cIl.Emit(OpCodes.Ldarg_0); // Load this to stack
cIl.Emit(OpCodes.Call, objCtor); // Call base (object) constructor

cIl.Emit(OpCodes.Ldarg_0); // Load this to stack
cIl.Emit(OpCodes.Ldarg_1); // Load the IProxyHandler to stack
cIl.Emit(OpCodes.Stfld, proxyFieldBuilder); // Set proxy to the actual proxy

cIl.Emit(OpCodes.Ret);

What this code does is: First it loads the “this”-object onto the stack. Than it calls the base constructor (Object.Object()), when the constructor is called it pops the “this”-object of the stack, and since it’s a constructor and not a function that returns anything, it doesn’t push anything back onto the stack. Now we want to store the argument passed in (arg_1) in the IProxyHandler field (proxyFieldBuilder). This is more tricky, as the operations seems to be in reverse, but what happens is the following. First we load this onto the stack, then we load the IProxyHandler onto the stack. Then we call the Stfld-command, which takes what lies at the top of the stack, and stores it in the field provided in parameter 2 of the function, on the object that lies on top of the stack after the previous one’s been popped. So in other word: read top of stack and pop and save at field in top of stack, then pop again. Now the stack is empty and we can exit the function (by calling Ret).

Next up is creation of the member-methods in the interface, but before we do that we need to have the function we want to call on the IProxyHandler available. This is done simply by the following code:

MethodInfo callRetMethod = typeof(IProxyHandler).GetMethod(
	"OnMethod",
	BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
	null,
	new Type[] { typeof(MethodInfo), typeof(object[]) },
	null);

Ok, lets start looping trough all the methods in the interface; the following is the rest of the code for the else-clause we’re currently in:

foreach (MethodInfo mi in t.GetMethods())
{
	// Implement the method
}
result = typeBuilder.CreateType();

typeCache.Add(typeName, result);

Now, all that’s left is to actually implements the methods and instantiate an object of the class we created. As you probably might have guessed this is more stack-machine, but I’ll try taking it one step at a time. The first thing we want to do is to define the method. Also, we want to know the number of parameters the function is supposed to take, and then we start the ILGenerator. This is pretty straight forward, it’s done as follows:

MethodBuilder mb = typeBuilder.DefineMethod(mi.Name,
	MethodAttributes.Public | MethodAttributes.HideBySig |
	MethodAttributes.NewSlot | MethodAttributes.Virtual, mi.ReturnType,
	mi.GetParameters().Select(pi => pi.ParameterType).ToArray());

int privateParameterCount = mi.GetParameters().Length;

ILGenerator il = mb.GetILGenerator();

The first thing we want to do in the function is to declare an object-array to hold the parameters, and a MethodInfo-variable to hold the current method being called. Remember that the IProxyHandler.OnMethod expected this.

To create the array we first declare it. Then we create a new object-array at the top of the stack and then we store that array at the newly declared variable (first declaration, then initialization). Also, to create an array a size must be specified. That size must lay on the top of the stack when we call the Newarr-call. To load a constant integer onto the stack we use Ldc_I4 (must be int32). The code is as shown below:

LocalBuilder argArray = il.DeclareLocal(typeof(object[]));
il.Emit(OpCodes.Ldc_I4, privateParameterCount);
il.Emit(OpCodes.Newarr, typeof(object));
il.Emit(OpCodes.Stloc, argArray);

The MethodInfo-variable is even more tricky. To get the MethodInfo we first load what is called a token (which is a unique reference of sort to either a method, class, or the likes if I understood the documentation correctly) of the MethodInfo we have at build-time (remember, the IL-code we generate isn’t compiled yet). Then we need to call MethodBase.GetMethodFromHandle(RuntimeMethodHandle handle) on the token. The code itself isn’t that hard, but the tricky part was to figure out about MethodBase.GetMethodFromHandle, and how to call it. The code can be seen below.

LocalBuilder methodInfo = il.DeclareLocal(typeof(MethodInfo));
il.Emit(OpCodes.Ldtoken, mi);
il.Emit(OpCodes.Call, typeof(MethodBase).GetMethod(
	"GetMethodFromHandle", new Type[] { typeof(RuntimeMethodHandle) }));
il.Emit(OpCodes.Stloc, methodInfo);

Ok, now that we’ve created the array and the MethodInfo-object we need to populate the array. This isn’t too hard a task, but what we need to remember is that there exist different types of types in .NET, and while in code putting the number 3 into an object-object might seem fine, in IL that doesn’t work. Every so-called value-type (including int, float, and all structs like DateTime) needs to be “boxed” before they can be referenced like an object. This isn’t hard at all, but you need to know that you need to do that in order for it to work properly, or else the application will crash if you try to give it a valuetype like an int. Also, one thing to notice is that when we loop trough the parameters the function take, the loop is on the build-side of the code. This means that once the function is called (after it is created), there is no loop at all. It has no ifs, no elses, no loops, no nothing at all except doing the bare minimum of what’s required. In other word, if I were to write this function in C# it would look something like this:

void DoSomething(int arg1, string arg2, DateTime arg3)
{
	object[] argArray;
	argArray = new object[3];
	
	MethodInfo methodInfo;
	methodInfo = MethodBase.GetMethod(*someHandle*);
	
	argArray[0] = box(arg1, int);
	argArray[1] = arg2;
	argArray[2] = box(arg3, DateTime);
}

Note here though that box is a fictive function, and that the boxing normally is taken care of by the c#->IL compiler for you. But as you can see though, no loops. To put an element into an array we use the Stelem_ref-call. The Stelem_ref-call expects the first item on the stack to be the item to put into the array. The next item should be an integer specifying it’s position, and the last item should be the array itself. The whole loop to populate the array looks like this:

for (int i = 0; i < privateParameterCount; i++)
{
	ParameterInfo info = mi.GetParameters()[i];

	il.Emit(OpCodes.Ldloc, argArray);
	il.Emit(OpCodes.Ldc_I4, i);
	il.Emit(OpCodes.Ldarg_S, i + 1);
	if (info.ParameterType.IsPrimitive || info.ParameterType.IsValueType)
		il.Emit(OpCodes.Box, info.ParameterType);
	il.Emit(OpCodes.Stelem_Ref);
}

The next part is also pretty simple. The first thing you do is load the “this”-object (arg_0) onto the stack. Then you use Ldfld to get the proxyFieldBuilder-field (which pops the “this”-object and replaces it with the IProxyHandler). Then we load the methodInfo local variable (which is the first parameter of “OnMethod”), and we load the argArray (which is the second parameter of “OnMethod”). And at last we call “OnMethod” with the loaded parameters. This will pop argArray, methodInfo and the proxyFieldBuilder, and push the result of the function onto the stack. The only thing that’s left on the stack now is in other words the result of the OnMethod-call. However, the OnMethod-call always returns an object, so if the function we’re writing want’s an int, we have to unbox it first. This is done with Unbox_all. Also, if the function we’re writing is a void-function we don’t want to return anything, regardless of what the OnMethod returned, so we just pop the value of the stack before calling Ret. This leaves the remaining code in the foreach-loop like this:

il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, proxyFieldBuilder);
il.Emit(OpCodes.Ldloc, methodInfo);
il.Emit(OpCodes.Ldloc, argArray);
il.Emit(OpCodes.Call, callRetMethod);
if (mi.ReturnType.IsValueType && mi.ReturnType != typeof(void))
	il.Emit(OpCodes.Unbox_Any, mi.ReturnType);

if (mi.ReturnType == typeof(void))
	il.Emit(OpCodes.Pop);

il.Emit(OpCodes.Ret);

Now there’s only one thing left, and that is to instantiate the class we just made. This is to be put outside the if-else loop we started nearly at the beginning of this constructor (the test to check if the type was cached). We use the Activator to create an instance, then simply cast it to T and assign it to obj. The code is below:

object o = Activator.CreateInstance(result, new object[] { handler });
obj = (T)o;

And there you have it. A fully working proxy-generator which you may use in any way that you want to. For example I’ve used this to create a small framework for server-client communication that is seamless. I hope you learned something, and please leave a comment if you have any questions or if you just like the article.

Starting to blog again

I’ve never been any good at this blog-thing, but I’ve always found the idea appealing. I myself reads several blogposts a day whenever there’s a coding-problem that I don’t know how to solve, but sometimes the results not that easy to find, and you end up reading documentations and stuff like that (which might not always be easy to understand without good viewcases). And it happens that one has to find the solution to some trivial matters all by one self.

Whenever I find myself in one of those kind of situations I always think when I’m done “I should blog about this”. Though in the end I never do. But I will try to get better at this, so that one day people searching for a solution to a problem which I’ve solved might find it with just a little googling. So that I might give back to the rich blog-community that already thought me how to program.

That being said, look forward to seeing my next blog-post as it will probably be around soon. That is, if anyone actually read this though :-P . Later.