<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Alxandr Productions</title>
	<atom:link href="http://blog.alxandr.me/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.alxandr.me</link>
	<description>The creations and thoughts of a university student.</description>
	<lastBuildDate>Fri, 16 Dec 2011 15:49:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='blog.alxandr.me' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Alxandr Productions</title>
		<link>http://blog.alxandr.me</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.alxandr.me/osd.xml" title="Alxandr Productions" />
	<atom:link rel='hub' href='http://blog.alxandr.me/?pushpress=hub'/>
		<item>
		<title>dotRant: Making an IRC library for .NET in C# – Part 5: Reflection and IRCCommands</title>
		<link>http://blog.alxandr.me/2011/11/04/dotrant-making-an-irc-library-for-net-in-c-part-5-reflection-and-irccommands/</link>
		<comments>http://blog.alxandr.me/2011/11/04/dotrant-making-an-irc-library-for-net-in-c-part-5-reflection-and-irccommands/#comments</comments>
		<pubDate>Fri, 04 Nov 2011 07:33:06 +0000</pubDate>
		<dc:creator>Alxandr</dc:creator>
				<category><![CDATA[dotRant]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[irc]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.alxandr.me/?p=339</guid>
		<description><![CDATA[Part 4 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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=339&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="post-nav">
<div class="nav-previous"><a href="/2011/10/24/dotrant-making-an-irc-library-for-net-in-c-part-4-skeletal-structure-of-the-ircclient-and-the-defaultdictionary/">Part 4</a></div>
</div>
<p>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:<br />
<span id="more-339"></span></p>
<h3>Parsing IRC-commands</h3>
<p>As discuss earlier, an IRC-command consists of mainly 3 parts, a prefix, a name, and a list of parameters. Before we can do anything we need to split the command up into these three parts so that we know what command is actually send, and by whom, and we need to create a data-structure to hold this data. For this we will create the IRCCommand class.<br />
<pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// A class used to represent IRC commands.
    /// &lt;/summary&gt;
    [DebuggerDisplay(&quot;{ToString()}&quot;, Name = &quot;{Name}&quot;)]
    public class IrcCommand
    {
        private string name;
        private string prefix;
        private IrcParameter[] parameters;

        /// &lt;summary&gt;
        /// Initializes a new instance of the &lt;see cref=&quot;IrcCommand&quot;/&gt; class.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;prefix&quot;&gt;The prefix.&lt;/param&gt;
        /// &lt;param name=&quot;name&quot;&gt;The name.&lt;/param&gt;
        /// &lt;param name=&quot;parameters&quot;&gt;The parameters.&lt;/param&gt;
        public IrcCommand(string prefix, string name, params IrcParameter[] parameters)
        {
            this.prefix = prefix;
            this.name = name;
            this.parameters = parameters;

            var restParams = parameters.Where(p =&gt; p.IsRest);
            if (restParams.Count() &gt; 1)
                throw new ArgumentException(&quot;Can't be more than 1 rest-parameter.&quot;, &quot;parameters&quot;);
            else if (restParams.Count() == 1 &amp;&amp; restParams.First() != parameters.Last())
                throw new ArgumentException(&quot;Rest parameter must always be the last parameter.&quot;, &quot;parameters&quot;);
        }

        /// &lt;summary&gt;
        /// Gets the name.
        /// &lt;/summary&gt;
        public string Name
        {
            get { return name; }
        }

        /// &lt;summary&gt;
        /// Gets the prefix.
        /// &lt;/summary&gt;
        public string Prefix
        {
            get { return prefix; }
        }

        /// &lt;summary&gt;
        /// Gets the parameters.
        /// &lt;/summary&gt;
        public string[] Parameters
        {
            get { return parameters.Select(p =&gt; (string)p).ToArray(); }
        }

        /// &lt;summary&gt;
        /// Returns a &lt;see cref=&quot;System.String&quot;/&gt; that represents this instance.
        /// &lt;/summary&gt;
        /// &lt;returns&gt;
        /// A &lt;see cref=&quot;System.String&quot;/&gt; that represents this instance.
        /// &lt;/returns&gt;
        public override string ToString()
        {
            return (prefix == null ? &quot;&quot; : &quot;:&quot; + prefix + &quot; &quot;) +
                name + &quot; &quot; + String.Join(&quot; &quot;, parameters.Select(p =&gt; p.ToString()));
        }
    }

    /// &lt;summary&gt;
    /// Represent an IRC-parameter.
    /// &lt;/summary&gt;
    [DebuggerDisplay(&quot;{ToString()}&quot;)]
    public class IrcParameter
    {
        string value;
        bool isRest;

        /// &lt;summary&gt;
        /// Initializes a new instance of the &lt;see cref=&quot;IrcParameter&quot;/&gt; class.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;value&quot;&gt;The value.&lt;/param&gt;
        /// &lt;param name=&quot;isRest&quot;&gt;if set to &lt;c&gt;true&lt;/c&gt; [is rest].&lt;/param&gt;
        public IrcParameter(string value, bool isRest = false)
        {
            this.value = value;
            this.isRest = isRest;

            if (!isRest &amp;&amp; value.IndexOfAny(new char[] { '&#092;&#048;', '\n', '\r', ' ' }) != -1)
                throw new ArgumentException(&quot;value can't contain '\&#092;&#048;', '\\n', '\\r' or ' ' in a non-rest-parameter.&quot;, &quot;value&quot;);
        }

        /// &lt;summary&gt;
        /// Gets the value.
        /// &lt;/summary&gt;
        public string Value
        {
            get { return value; }
        }

        /// &lt;summary&gt;
        /// Gets a value indicating whether this instance is rest-value.
        /// &lt;/summary&gt;
        /// &lt;value&gt;
        ///   &lt;c&gt;true&lt;/c&gt; if this instance is rest-value; otherwise, &lt;c&gt;false&lt;/c&gt;.
        /// &lt;/value&gt;
        public bool IsRest
        {
            get { return isRest; }
        }

        /// &lt;summary&gt;
        /// Performs an implicit conversion from &lt;see cref=&quot;System.String&quot;/&gt; to &lt;see cref=&quot;dotRant.IrcParameter&quot;/&gt;.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;parameter&quot;&gt;The parameter.&lt;/param&gt;
        /// &lt;returns&gt;
        /// The result of the conversion.
        /// &lt;/returns&gt;
        public static implicit operator IrcParameter(string parameter)
        {
            return new IrcParameter(parameter);
        }

        /// &lt;summary&gt;
        /// Performs an explicit conversion from &lt;see cref=&quot;dotRant.IrcParameter&quot;/&gt; to &lt;see cref=&quot;System.String&quot;/&gt;.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;parameter&quot;&gt;The parameter.&lt;/param&gt;
        /// &lt;returns&gt;
        /// The result of the conversion.
        /// &lt;/returns&gt;
        public static explicit operator string(IrcParameter parameter)
        {
            return parameter.value;
        }

        /// &lt;summary&gt;
        /// Returns a &lt;see cref=&quot;System.String&quot;/&gt; that represents this instance.
        /// &lt;/summary&gt;
        /// &lt;returns&gt;
        /// A &lt;see cref=&quot;System.String&quot;/&gt; that represents this instance.
        /// &lt;/returns&gt;
        public override string ToString()
        {
            return (isRest ? &quot;:&quot; : &quot;&quot;) + value;
        }
    }
</pre><br />
These are two fairly simple classes which don&#8217;t do much more than hold the data required, also, the IrcParameter contains conversion to and from string using implicit and explicit operators. Also, the constructor for both classes performs checks as to the validity of the data given. The only thing left to do here is to add parsing of the commands, but before we do that, let&#8217;s take a look at how the commands are defined in the IRC specification (RFC 2812):<br />
<em>PS: Please do note that what I here refer to as a command, is referred to as a message in this specification.</em><br />
<pre class="brush: plain;">
    message    =  [ &quot;:&quot; prefix SPACE ] command [ params ] crlf
    prefix     =  servername / ( nickname [ [ &quot;!&quot; user ] &quot;@&quot; host ] )
    command    =  1*letter / 3digit
    params     =  *14( SPACE middle ) [ SPACE &quot;:&quot; trailing ]
               =/ 14( SPACE middle ) [ SPACE [ &quot;:&quot; ] trailing ]

    nospcrlfcl =  %x01-09 / %x0B-0C / %x0E-1F / %x21-39 / %x3B-FF
                    ; any octet except NUL, CR, LF, &quot; &quot; and &quot;:&quot;
    middle     =  nospcrlfcl *( &quot;:&quot; / nospcrlfcl )
    trailing   =  *( &quot;:&quot; / &quot; &quot; / nospcrlfcl )

    SPACE      =  %x20        ; space character
    crlf       =  %x0D %x0A   ; &quot;carriage return&quot; &quot;linefeed&quot;
</pre><br />
Normally, IRC-commands are really simple. They&#8217;ve split by space and have a prefix, however, when reading the specification it becomes clear that they can be much more complex looking then that. For instance, parameters that are not &#8220;trailing&#8221; (or as I&#8217;ve called them, rest-parameters) can contain &#8216;:&#8217;, they just can&#8217;t start with a colon. This means we can&#8217;t just simply split on &#8216;:&#8217; to get rest-parameters, neither can we simply split on space, cause spaces needs to be maintained in the rest-parameter. Nevertheless, it&#8217;s not a very complex thing to parse, as you will soon see.</p>
<p>A thing to notice first, is that you can have messages without a prefix, and that if there is a prefix, the command should start with a colon. This can be checked easily by doing something like this:<br />
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Parses the specified command.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;cmd&quot;&gt;The command.&lt;/param&gt;
        /// &lt;returns&gt;The IrcCommand-representation of the given command.&lt;/returns&gt;
        public static IrcCommand Parse(string cmd)
        {
            string prefix = null, name = null;
            List&lt;IrcParameter&gt; parameters = new List&lt;IrcParameter&gt;();
            if (cmd[0] == ':')
            {
                prefix = cmd.Substring(1, cmd.IndexOf(' ') - 1);
                cmd = cmd.Substring(cmd.IndexOf(' ') + 1);
            }
</pre><br />
After that, we need to get the name of the command, which too is really simple, and can be achieved with the following 3 lines:<br />
<pre class="brush: csharp;">
            var nameEnd = cmd.IndexOf(' ');
            name = cmd.Substring(0, nameEnd);
            cmd = cmd.Substring(nameEnd + 1);
</pre><br />
Then, what&#8217;s left is the parameters, and the rules for parameters is that if they start with a space, it&#8217;s a rest-parameter, and there can only be one of them, thus the code can look like this:<br />
<pre class="brush: csharp;">
            while (cmd.Length &gt; 0)
            {
                if (cmd[0] == ':')
                {
                    parameters.Add(cmd.Substring(1).AsIrcRestParameter());
                    cmd = &quot;&quot;;
                }
                else
                {
                    var paramEnd = cmd.IndexOf(' ');
                    if (paramEnd == -1)
                        paramEnd = cmd.Length;
                    var param = cmd.Substring(0, paramEnd);
                    parameters.Add(param);
                    if (paramEnd != cmd.Length)
                        cmd = cmd.Substring(paramEnd + 1);
                    else
                        cmd = &quot;&quot;;
                }
            }

            return new IrcCommand(prefix, name, parameters.ToArray());
        }
</pre><br />
For the following code to work we need to add an extension-method to System.String that turns it into an IRC rest-parameter. I&#8217;ve added 2 excension-methods to help with this in the following helper-class:<br />
<pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// Provides extension-helpers for IrcParameters.
    /// &lt;/summary&gt;
    public static class IrcParameterExtensions
    {
        /// &lt;summary&gt;
        /// Converts the string to an irc parameter.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;parameter&quot;&gt;The parameter.&lt;/param&gt;
        /// &lt;param name=&quot;isRest&quot;&gt;if set to &lt;c&gt;true&lt;/c&gt; treated as rest-parameter, if &lt;c&gt;false&lt;/c&gt; not treated as rest-parameter, and if &lt;c&gt;null&lt;/c&gt; selects automatically.&lt;/param&gt;
        /// &lt;returns&gt;A irc parameter.&lt;/returns&gt;
        public static IrcParameter AsIrcParameter(this string parameter, bool? isRest = null)
        {
            return new IrcParameter(parameter, isRest.HasValue ? isRest.Value : parameter.IndexOfAny(new char[] { '&#092;&#048;', '\n', '\r', ' ', ':' }) != -1);
        }

        /// &lt;summary&gt;
        /// Converts the string to an irc parameter.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;parameter&quot;&gt;The parameter.&lt;/param&gt;
        /// &lt;returns&gt;A irc rest-parameter.&lt;/returns&gt;
        public static IrcParameter AsIrcRestParameter(this string parameter)
        {
            return new IrcParameter(parameter, true);
        }
    }
</pre><br />
And there you have it. That&#8217;s all that&#8217;s required for parsing IRC-commands. As said, IRC is a rather simple protocol. Now we got more or less everything we need to start responding to commands that are sent from the server.</p>
<h3>Handling commands</h3>
<p>In order to actually handle commands sent from the server it&#8217;s needed to tell our class what functions it should trigger for what commands, and in order to do that I decided to use attributes as explained in the previous post. But in order to do so, we first need to actually create the attribute-class. All attribute-classes needs to inherit from Attribute, and they can have an AttributeUsageAttribute to denote where and how you can use the attribute. The attribute we are to create is fairly simple. All it requires is a name and the ability to later retrieve that name, and can be written like this:<br />
<pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// Attribute used to denote IrcCommand-methods
    /// &lt;/summary&gt;
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
    public class IrcCommandAttribute : Attribute
    {
        private string name;
        /// &lt;summary&gt;
        /// Initializes a new instance of the &lt;see cref=&quot;IrcCommandAttribute&quot;/&gt; class with a name.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;name&quot;&gt;The name.&lt;/param&gt;
        public IrcCommandAttribute(string name)
        {
            this.name = name;
        }

        /// &lt;summary&gt;
        /// Gets the name.
        /// &lt;/summary&gt;
        public string Name
        {
            get { return name; }
        }
    }
</pre><br />
Now we&#8217;re all set. Let&#8217;s start by updating the client_Message method in our IrcClient class to look like this:<br />
<pre class="brush: csharp;">
        void client_Message(object sender, MessageEventArgs e)
        {
            string msg = encoding.GetString(e.Message);
            var cmd = IrcCommand.Parse(msg);
            GetCommand(cmd.Name).Invoke(this, new object[] { cmd.Prefix, cmd.Name, cmd.Parameters });
        }
</pre><br />
Pretty slick, eh? Anyways, with this added we need to create the GetCommand(string name) method, but first I&#8217;d like to talk a bit about the strategy we take here. As explained in the previous post I aim to use the DefaultDictionary to store references from name to function-call and thus we need to populate a DefaultDictionary somewhere. However, consider a scenario where you have more than a 100 IrcClient instances running at once. There is no need for each of them to have their own DefaultDictionary cause they all have the same methods, thus we can make it static. This saves both memory, and initialization-time of our class since we only need to build the dictionary once. However, there is one problem with this approach too, and that is if you subclass the IrcClient. If you do so you can get various funny effects like the application not doing what you want it to, or simply just crashing. To prevent this we need a double-dictionary that maintains a DefaultDictionary for each type of IrcClient we currently have. Like this:<br />
<pre class="brush: csharp;">
private static readonly Dictionary&lt;Type, DefaultDictionary&lt;string, MethodInfo&gt;&gt; ircCommands = new Dictionary&lt;Type, DefaultDictionary&lt;string, MethodInfo&gt;&gt;();
</pre><br />
The rest is pretty straight forward. When you call the GetCommand(string name) method it calls a static GetCommand(Type type, string name) method that checks if the type is present in the first dictionary. If it&#8217;s not it creates a new DefaultDictionary for that type. After that it returns the MethodInfo for the method to call regardless if the DefaultDictionary was just created or not. To create the DefaultDictionary I employ a simple LINQ-trick and all in all we end up with this:<br />
<pre class="brush: csharp;">
        private static MethodInfo GetCommand(Type type, string cmdName)
        {
            if (!ircCommands.ContainsKey(type))
            {
                lock (ircCommands)
                {
                    if (!ircCommands.ContainsKey(type))
                    {
                        var dict = new DefaultDictionary&lt;string, MethodInfo&gt;();
                        var methods = from mi in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod)
                                      from attr in mi.GetCustomAttributes(typeof(IrcCommandAttribute), true).Cast&lt;IrcCommandAttribute&gt;()
                                      select new { Method = mi, Name = attr.Name };
                        foreach (var m in methods)
                        {
                            if (m.Name != &quot;_Default&quot;)
                                dict[m.Name] = m.Method;
                            else
                                dict.Default = m.Method;
                        }
                        ircCommands.Add(type, dict);
                    }
                }
            }
            return ircCommands[type][cmdName];
        }
        private MethodInfo GetCommand(string cmdName) { return GetCommand(this.GetType(), cmdName); }
</pre><br />
After that we can go ahead and add a couple of methods to our class. Just to clarify things I prefix these methods with IrcCmd_.<br />
<em>I know these comments makes no sence, but I didn&#8217;t notice at the time of writing the code. The comments are auto-generated.</em><br />
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Ircs the CMD_ default.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;prefix&quot;&gt;The prefix.&lt;/param&gt;
        /// &lt;param name=&quot;cmd&quot;&gt;The CMD.&lt;/param&gt;
        /// &lt;param name=&quot;parameters&quot;&gt;The parameters.&lt;/param&gt;
        [IrcCommand(&quot;_Default&quot;)]
        protected virtual void IrcCmd_Default(string prefix, string cmd, string[] parameters)
        {
            //TODO: Create and fire an event.
        }

        /// &lt;summary&gt;
        /// Ircs the CMD_ ping.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;prefix&quot;&gt;The prefix.&lt;/param&gt;
        /// &lt;param name=&quot;cmd&quot;&gt;The CMD.&lt;/param&gt;
        /// &lt;param name=&quot;parameters&quot;&gt;The parameters.&lt;/param&gt;
        [IrcCommand(&quot;PING&quot;)]
        protected virtual void IrcCmd_Ping(string prefix, string cmd, string[] parameters)
        {
            Send(new IrcCommand(null, &quot;PONG&quot;, parameters[0].AsIrcParameter()));
        }
</pre></p>
<h3>Small changes</h3>
<p>I&#8217;ve changed a few things about the IrcClient class since my last post, and the main thing that&#8217;s changed is the constructor. I removed the parameters from the constructor and rather made them into properties instead, so the constructor now looks like this:<br />
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Initializes a new instance of the &lt;see cref=&quot;IrcClient&quot;/&gt; class.
        /// &lt;/summary&gt;
        public IrcClient()
        {
            if (encoding == null)
                encoding = Encoding.UTF8;

            client = new MessageConnection();
            client.Disconnect += new EventHandler&lt;EventArgs&gt;(client_Disconnect);
            client.SslValidate += new EventHandler&lt;SslValidateEventArgs&gt;(client_SslValidate);
            client.Message += new EventHandler&lt;MessageEventArgs&gt;(client_Message);
        }
</pre><br />
And also I&#8217;ve added 3 new properties that looks like this:<br />
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Gets or sets the encoding.
        /// &lt;/summary&gt;
        /// &lt;value&gt;
        /// The encoding.
        /// &lt;/value&gt;
        public Encoding Encoding
        {
            get
            {
                return encoding;
            }
            set
            {
                encoding = value;
            }
        }

        /// &lt;summary&gt;
        /// Gets or sets the nick.
        /// &lt;/summary&gt;
        /// &lt;value&gt;
        /// The nick.
        /// &lt;/value&gt;
        public string Nick
        {
            get
            {
                return nick;
            }
            set
            {
                nick = value;
                if (Connected)
                    Send(new IrcCommand(null, &quot;NICK&quot;, nick));
            }
        }

        /// &lt;summary&gt;
        /// Gets or sets the full name.
        /// &lt;/summary&gt;
        /// &lt;value&gt;
        /// The full name.
        /// &lt;/value&gt;
        public string FullName
        {
            get
            {
                return fullName;
            }
            set
            {
                if (Connected)
                    throw new InvalidOperationException(&quot;Can't change full-name after connected.&quot;);
                fullName = value;
            }
        }
</pre><br />
Then there&#8217;s the ConnectAsync method that now looks like this:<br />
<pre class="brush: csharp;">
        public Task ConnectAsync(string hostname, int port, bool secureConnection)
        {
            if (String.IsNullOrWhiteSpace(nick))
                throw new InvalidOperationException(&quot;Can't connect with nick beeing unset.&quot;);
            if (String.IsNullOrWhiteSpace(fullName))
                throw new InvalidOperationException(&quot;Can't connect with fullname beeing unset.&quot;);
            return client.ConnectAsync(hostname, port, secureConnection).ContinueWith(task =&gt;
            {
                Send(new IrcCommand(null, &quot;PASS&quot;, &quot;*&quot;));
                Send(new IrcCommand(null, &quot;NICK&quot;, nick));
                Send(new IrcCommand(null, &quot;USER&quot;, &quot;dotRant&quot;, &quot;8&quot;, &quot;*&quot;, fullName.AsIrcRestParameter()));
                // PASS *
                // NICK &lt;nick&gt;
                // USER dotRant 8 * :&lt;full name&gt;
            });
        }
</pre><br />
And last but not least the Send-method:<br />
<pre class="brush: csharp;">
        private void Send(IrcCommand cmd)
        {
            var bytes = encoding.GetBytes(cmd.ToString());
            client.Send(bytes);
        }
</pre><br />
As always, if there are any questions, please leave a comment below. The code for this post can be found here: <a href="https://github.com/Alxandr/dotRant/tree/part-5/src/dotRant">https://github.com/Alxandr/dotRant/tree/part-5/src/dotRant</a>.</p>
<p>Until then. Alxandr.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alxen.wordpress.com/339/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alxen.wordpress.com/339/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alxen.wordpress.com/339/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alxen.wordpress.com/339/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alxen.wordpress.com/339/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alxen.wordpress.com/339/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alxen.wordpress.com/339/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alxen.wordpress.com/339/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alxen.wordpress.com/339/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alxen.wordpress.com/339/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alxen.wordpress.com/339/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alxen.wordpress.com/339/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alxen.wordpress.com/339/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alxen.wordpress.com/339/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=339&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.alxandr.me/2011/11/04/dotrant-making-an-irc-library-for-net-in-c-part-5-reflection-and-irccommands/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5a87311ea4c9950793397f01eb208830?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Alxandr</media:title>
		</media:content>
	</item>
		<item>
		<title>dotRant: Making an IRC library for .NET in C# – Part 4: Skeletal structure of the IrcClient and the DefaultDictionary</title>
		<link>http://blog.alxandr.me/2011/10/24/dotrant-making-an-irc-library-for-net-in-c-part-4-skeletal-structure-of-the-ircclient-and-the-defaultdictionary/</link>
		<comments>http://blog.alxandr.me/2011/10/24/dotrant-making-an-irc-library-for-net-in-c-part-4-skeletal-structure-of-the-ircclient-and-the-defaultdictionary/#comments</comments>
		<pubDate>Mon, 24 Oct 2011 21:42:52 +0000</pubDate>
		<dc:creator>Alxandr</dc:creator>
				<category><![CDATA[dotRant]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[irc]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.alxandr.me/?p=329</guid>
		<description><![CDATA[Part 3 Part 5 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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=329&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="post-nav">
<div class="nav-previous"><a href="/2011/10/18/dotrant-making-an-irc-library-for-net-in-c-part-3-a-word-about-asynchronism-and-some-bug-fixes/">Part 3</a></div>
<div class="nav-next"><a href="/2011/11/04/dotrant-making-an-irc-library-for-net-in-c-part-5-reflection-and-irccommands/">Part 5</a></div>
</div>
<p>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&#8217;s take a look at the problem we have at hand.</p>
<p>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&#8217;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&#8217;t think I have to tell you that I don&#8217;t want the class to end up as a mess, so let&#8217;s look at some of the alternative ways of handling commands sent from the server.<br />
<span id="more-329"></span></p>
<h3>Handling commands</h3>
<p>The first thing that comes to mind when you need to run different code depending on something is a regular if-else-test. Using an if-else-test we can write a function that handles the command like this:<br />
<pre class="brush: csharp;">
private void HandleCommand(string cmdName, string[] cmdArgs)
{
	if(cmdName == &quot;PRIVMSG&quot;)
	{
		// Perform handeling of the private message.
	}
	else if(cmdName == &quot;JOIN&quot;)
	{
		// Perform handeling of a JOIN command.
	}
	else
	{
		// Default action, command not known.
	}
}
</pre><br />
Needless to say, this is not very pretty, and does scale bad. You end up putting all the functionality into a single function, and there is a lot of code to do this simple matching. One way we can make this code better is by changing the if-else-test with a switch-test. Another thing we can do to further improve our code is to create functions for the commands, rather than just putting all the code in one function, then we end up with something like this:<br />
<pre class="brush: csharp;">
private void HandleCommand(string cmdName, string[] cmdArgs)
{
	switch(cmdName)
	{
		case &quot;PRIVMSG&quot;:
			HandlePrivmsg(cmdName, cmdArgs); break;
		case &quot;JOIN&quot;:
			HandleJoin(cmdName, cmdArgs); break;
		default:
			HandleUnknown(cmdName, cmdArgs); break;
	}
}
</pre><br />
This makes our code a lot better, but there is still one problem, whenever we add support for a new command we need to change code two places. First, we need to create a new function, than we need to add a clause in our switch-case statement, and if we remove something, or rename, it also needs to be changed both places. I personally don&#8217;t like that, and thus has found another way to solve this problem, by using Attributes. If you don&#8217;t know what attributes in C# is I recommend reading up on them, but essentially you can add info to functions or properties or even input-parameters and classes that you might use later to figure out how to use that class or method, and that&#8217;s precisely what we&#8217;re going to do. On our HandleJoin-method (which by the way is not necessarily a final name as I have yet to write the method) we just denote that we want this method to be called whenever a &#8220;JOIN&#8221; command is received, and then we handle the rest in our HandleCommand method (which too is just a temporarily name). Doing this enables us to add functionality much more simply, but how do we achieve this? Well, the actual implementation is something I&#8217;ll post in my next blog-post as I still need to do a bit more research about how efficient my current method of handling that task is. However, one of the things we do require for this functionality is to emulate the switch-case statement over a variable list of items containing a name and a function to call should there be a match, and also a default item, and for this I&#8217;ve created the DefaultDictionary. The DefaultDictionary is basically just a simple Dictionary that has a Default property that is returned should the dictionary not contain a match for the requested key, just like the switch-case does. Thus, you will never get a KeyNotFoundException cause if the key is not found the Default is returned instead. The DefaultDictionary is really easy to implement, and should be easy to understand. The code, fully commented with XML-comments where required, looks like this:<br />
<pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// A dictionary that also holds a default-value which it returns if
    /// you try to access a key that doesn't exist.
    /// &lt;/summary&gt;
    /// &lt;typeparam name=&quot;TKey&quot;&gt;The type of the key.&lt;/typeparam&gt;
    /// &lt;typeparam name=&quot;TValue&quot;&gt;The type of the values.&lt;/typeparam&gt;
    public class DefaultDictionary&lt;TKey, TValue&gt; : IDictionary&lt;TKey, TValue&gt;
    {
        private TValue defaultValue = default(TValue);
        private Dictionary&lt;TKey, TValue&gt; dict = new Dictionary&lt;TKey, TValue&gt;();

        /// &lt;summary&gt;
        /// Gets or sets the default.
        /// &lt;/summary&gt;
        /// &lt;value&gt;
        /// The default.
        /// &lt;/value&gt;
        public TValue Default
        {
            get { return defaultValue; }
            set { defaultValue = value; }
        }

        #region IDictionary&lt;TKey,TValue&gt; Members

        /// &lt;summary&gt;
        /// Gets or sets the value associated with the specified key.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;key&quot;&gt;The key of the value to get or set.&lt;/param&gt;
        /// &lt;returns&gt;The value associated with the specified key.&lt;/returns&gt;
        /// &lt;exception cref=&quot;T:System.ArgumentNullException&quot;&gt;&lt;paramref name=&quot;key&quot;/&gt; is null.&lt;/exception&gt;
        /// &lt;exception cref=&quot;T:System.NotSupportedException&quot;&gt;The property is set and the &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt; is read-only.&lt;/exception&gt;
        public TValue this[TKey key]
        {
            get
            {
                if (!dict.ContainsKey(key))
                    return defaultValue;
                return dict[key];
            }
            set
            {
                dict[key] = value;
            }
        }

        /// &lt;summary&gt;
        /// Adds an element with the provided key and value to the &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt;.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;key&quot;&gt;The object to use as the key of the element to add.&lt;/param&gt;
        /// &lt;param name=&quot;value&quot;&gt;The object to use as the value of the element to add.&lt;/param&gt;
        /// &lt;exception cref=&quot;T:System.ArgumentNullException&quot;&gt;&lt;paramref name=&quot;key&quot;/&gt; is null.&lt;/exception&gt;
        /// &lt;exception cref=&quot;T:System.ArgumentException&quot;&gt;An element with the same key already exists in the &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt;.&lt;/exception&gt;
        /// &lt;exception cref=&quot;T:System.NotSupportedException&quot;&gt;The &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt; is read-only.&lt;/exception&gt;
        public void Add(TKey key, TValue value)
        {
            dict.Add(key, value);
        }

        /// &lt;summary&gt;
        /// Determines whether the &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt; contains an element with the specified key.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;key&quot;&gt;The key to locate in the &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt;.&lt;/param&gt;
        /// &lt;returns&gt;
        /// true if the &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt; contains an element with the key; otherwise, false.
        /// &lt;/returns&gt;
        /// &lt;exception cref=&quot;T:System.ArgumentNullException&quot;&gt;&lt;paramref name=&quot;key&quot;/&gt; is null.&lt;/exception&gt;
        public bool ContainsKey(TKey key)
        {
            return dict.ContainsKey(key);
        }

        /// &lt;summary&gt;
        /// Gets an &lt;see cref=&quot;T:System.Collections.Generic.ICollection`1&quot;/&gt; containing the keys of the &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt;.
        /// &lt;/summary&gt;
        /// &lt;returns&gt;An &lt;see cref=&quot;T:System.Collections.Generic.ICollection`1&quot;/&gt; containing the keys of the object that implements &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt;.&lt;/returns&gt;
        public ICollection&lt;TKey&gt; Keys
        {
            get { return dict.Keys; }
        }

        /// &lt;summary&gt;
        /// Removes the element with the specified key from the &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt;.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;key&quot;&gt;The key of the element to remove.&lt;/param&gt;
        /// &lt;returns&gt;
        /// true if the element is successfully removed; otherwise, false.  This method also returns false if &lt;paramref name=&quot;key&quot;/&gt; was not found in the original &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt;.
        /// &lt;/returns&gt;
        /// &lt;exception cref=&quot;T:System.ArgumentNullException&quot;&gt;&lt;paramref name=&quot;key&quot;/&gt; is null.&lt;/exception&gt;
        /// &lt;exception cref=&quot;T:System.NotSupportedException&quot;&gt;The &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt; is read-only.&lt;/exception&gt;
        public bool Remove(TKey key)
        {
            return dict.Remove(key);
        }

        /// &lt;summary&gt;
        /// Gets the value associated with the specified key.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;key&quot;&gt;The key whose value to get.&lt;/param&gt;
        /// &lt;param name=&quot;value&quot;&gt;When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the &lt;paramref name=&quot;value&quot;/&gt; parameter. This parameter is passed uninitialized.&lt;/param&gt;
        /// &lt;returns&gt;
        /// true if the object that implements &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt; contains an element with the specified key; otherwise, false.
        /// &lt;/returns&gt;
        /// &lt;exception cref=&quot;T:System.ArgumentNullException&quot;&gt;&lt;paramref name=&quot;key&quot;/&gt; is null.&lt;/exception&gt;
        public bool TryGetValue(TKey key, out TValue value)
        {
            return dict.TryGetValue(key, out value);
        }

        /// &lt;summary&gt;
        /// Gets an &lt;see cref=&quot;T:System.Collections.Generic.ICollection`1&quot;/&gt; containing the values in the &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt;.
        /// &lt;/summary&gt;
        /// &lt;returns&gt;An &lt;see cref=&quot;T:System.Collections.Generic.ICollection`1&quot;/&gt; containing the values in the object that implements &lt;see cref=&quot;T:System.Collections.Generic.IDictionary`2&quot;/&gt;.&lt;/returns&gt;
        public ICollection&lt;TValue&gt; Values
        {
            get { return dict.Values; }
        }

        /// &lt;summary&gt;
        /// Removes all items from the &lt;see cref=&quot;T:System.Collections.Generic.ICollection`1&quot;/&gt;.
        /// &lt;/summary&gt;
        /// &lt;exception cref=&quot;T:System.NotSupportedException&quot;&gt;The &lt;see cref=&quot;T:System.Collections.Generic.ICollection`1&quot;/&gt; is read-only. &lt;/exception&gt;
        public void Clear()
        {
            dict.Clear();
        }

        #endregion

        #region ICollection&lt;KeyValuePair&lt;TKey,TValue&gt;&gt; Members

        void ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.Add(KeyValuePair&lt;TKey, TValue&gt; item)
        {
            ((ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;)dict).Add(item);
        }

        void ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.Clear()
        {
            ((ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;)dict).Clear();
        }

        bool ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.Contains(KeyValuePair&lt;TKey, TValue&gt; item)
        {
            return ((ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;)dict).Contains(item);
        }

        void ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.CopyTo(KeyValuePair&lt;TKey, TValue&gt;[] array, int arrayIndex)
        {
            ((ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;)dict).CopyTo(array, arrayIndex);
        }

        int ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.Count
        {
            get { return ((ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;)dict).Count; }
        }

        bool ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.IsReadOnly
        {
            get { return ((ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;)dict).IsReadOnly; }
        }

        bool ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.Remove(KeyValuePair&lt;TKey, TValue&gt; item)
        {
            return ((ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;)dict).Remove(item);
        }

        #endregion

        #region IEnumerable&lt;KeyValuePair&lt;TKey,TValue&gt;&gt; Members

        IEnumerator&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; IEnumerable&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.GetEnumerator()
        {
            return ((IEnumerable&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;)dict).GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((IEnumerable)dict).GetEnumerator();
        }

        #endregion
    }
</pre><br />
As you can see it just delegates every call to the underlying dictionary, with the exception of the index-method where it returns the defaultValue if the key does not exist. The DefaultDictionary is used to store the function-delegates associated with their names, and a default-action to perform should the command not be known. As we get further on you will also see that the DefualtDictionary is useful for other aspects of the irc-library too.</p>
<h3>The skeletal structure of the IrcClient</h3>
<p>Now it&#8217;s about time we start writing the actual IrcClient-class. The IrcClass needs to delegate the events fired by the MessageConnection with the exception of the MessageEvent, it should contain Connect and ConnectAsync methods, and it must allow the user of the library to select Encoding to be used, and Nick and Fullname of the connected user (also, at a later point I will add the functionality to specify the client-name by subclassing the IrcClient-class. All in all it&#8217;s a simple class, so I&#8217;m just going ahead and posting the code as most of it&#8217;s been explained earlier.<br />
<pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// An IRC-client used to connect to and chat at a irc-network.
    /// &lt;/summary&gt;
    public class IrcClient
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();

        #region Private Members
        private readonly MessageConnection client;
        private Encoding encoding;
        private string nick;
        private string fullName;
        #endregion

        #region Constructors
        /// &lt;summary&gt;
        /// Initializes a new instance of the &lt;see cref=&quot;IrcClient&quot;/&gt; class.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;nick&quot;&gt;The nick.&lt;/param&gt;
        /// &lt;param name=&quot;fullName&quot;&gt;The full name.&lt;/param&gt;
        /// &lt;param name=&quot;encoding&quot;&gt;The encoding.&lt;/param&gt;
        public IrcClient(string nick, string fullName, Encoding encoding = null)
        {
            if (encoding == null)
                encoding = Encoding.UTF8;

            this.nick = nick;
            this.fullName = fullName;
            this.encoding = encoding;

            client = new MessageConnection();
            client.Disconnect += new EventHandler&lt;EventArgs&gt;(client_Disconnect);
            client.SslValidate += new EventHandler&lt;SslValidateEventArgs&gt;(client_SslValidate);
            client.Message += new EventHandler&lt;MessageEventArgs&gt;(client_Message);
        }
        #endregion

        #region Client Events
        void client_Message(object sender, MessageEventArgs e)
        {
            throw new NotImplementedException(&quot;Implement handling commands.&quot;);
        }

        void client_SslValidate(object sender, SslValidateEventArgs e)
        {
            e.Accept = OnSslValidate(e.Sender, e.Certificate, e.Chain, e.SslPolicyErrors);
        }

        void client_Disconnect(object sender, EventArgs e)
        {
            OnDisconnect();
        }
        #endregion

        #region Properties
        /// &lt;summary&gt;
        /// Gets a value indicating whether this &lt;see cref=&quot;MessageConnection&quot;/&gt; is connected.
        /// &lt;/summary&gt;
        /// &lt;value&gt;
        ///   &lt;c&gt;true&lt;/c&gt; if connected; otherwise, &lt;c&gt;false&lt;/c&gt;.
        /// &lt;/value&gt;
        public bool Connected
        {
            get
            {
                return client != null &amp;&amp; client.Connected;
            }
        }
        #endregion

        #region Events
        /// &lt;summary&gt;
        /// Occurs when a SSL-certificate should be validated.
        /// &lt;/summary&gt;
        public event EventHandler&lt;SslValidateEventArgs&gt; SslValidate;

        /// &lt;summary&gt;
        /// Occurs when the connection is disconnected from the other end.
        /// &lt;/summary&gt;
        public event EventHandler&lt;EventArgs&gt; Disconnect;
        #endregion

        #region Public Methods
        /// &lt;summary&gt;
        /// Connects the specified hostname.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;hostname&quot;&gt;The hostname.&lt;/param&gt;
        /// &lt;param name=&quot;port&quot;&gt;The port.&lt;/param&gt;
        /// &lt;param name=&quot;secureConnection&quot;&gt;if set to &lt;c&gt;true&lt;/c&gt; connects using ssl.&lt;/param&gt;
        /// &lt;returns&gt;A task representing the async operation.&lt;/returns&gt;
        public Task ConnectAsync(string hostname, int port, bool secureConnection)
        {
            return client.ConnectAsync(hostname, port, secureConnection).ContinueWith(task =&gt;
            {
                throw new NotImplementedException(&quot;Implement sending of commands.&quot;);
                // PASS *
                // NICK &lt;nick&gt;
                // USER dotRant 8 * :&lt;full name&gt;
            });
        }
        /// &lt;summary&gt;
        /// Connects the specified hostname.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;hostname&quot;&gt;The hostname.&lt;/param&gt;
        /// &lt;param name=&quot;port&quot;&gt;The port.&lt;/param&gt;
        /// &lt;param name=&quot;secureConnection&quot;&gt;if set to &lt;c&gt;true&lt;/c&gt; connects using ssl.&lt;/param&gt;
        /// &lt;returns&gt;A task representing the async operation.&lt;/returns&gt;
        public void Connect(string hostname, int port, bool secureConnection)
        {
            ConnectAsync(hostname, port, secureConnection).Wait();
        }
        #endregion

        #region EventHelpers
        /// &lt;summary&gt;
        /// Called when a ssl-certificate should be validated.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;sender&quot;&gt;The sender.&lt;/param&gt;
        /// &lt;param name=&quot;certificate&quot;&gt;The certificate.&lt;/param&gt;
        /// &lt;param name=&quot;chain&quot;&gt;The chain.&lt;/param&gt;
        /// &lt;param name=&quot;sslPolicyErrors&quot;&gt;The SSL policy errors.&lt;/param&gt;
        /// &lt;returns&gt;Whether or not to accept the sertificate.&lt;/returns&gt;
        protected virtual bool OnSslValidate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            SslValidateEventArgs args = new SslValidateEventArgs(sender, certificate, chain, sslPolicyErrors);
            if (SslValidate != null)
                SslValidate(this, args);
            return args.Accept;
        }

        /// &lt;summary&gt;
        /// Called when the other end disconnects.
        /// &lt;/summary&gt;
        protected virtual void OnDisconnect()
        {
            if (Disconnect != null)
                Disconnect(this, new EventArgs());
        }
        #endregion
    }
</pre><br />
As always, if there are any questions, please leave a comment below. The code for this post can be found here: <a href="https://github.com/Alxandr/dotRant/tree/part-4/src/dotRant">https://github.com/Alxandr/dotRant/tree/part-4/src/dotRant</a>.</p>
<p>Until then. Alxandr.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alxen.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alxen.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alxen.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alxen.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alxen.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alxen.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alxen.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alxen.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alxen.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alxen.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alxen.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alxen.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alxen.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alxen.wordpress.com/329/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=329&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.alxandr.me/2011/10/24/dotrant-making-an-irc-library-for-net-in-c-part-4-skeletal-structure-of-the-ircclient-and-the-defaultdictionary/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5a87311ea4c9950793397f01eb208830?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Alxandr</media:title>
		</media:content>
	</item>
		<item>
		<title>dotRant: Making an IRC library for .NET in C# – Part 3: A word about asynchronism (and some bug-fixes)</title>
		<link>http://blog.alxandr.me/2011/10/18/dotrant-making-an-irc-library-for-net-in-c-part-3-a-word-about-asynchronism-and-some-bug-fixes/</link>
		<comments>http://blog.alxandr.me/2011/10/18/dotrant-making-an-irc-library-for-net-in-c-part-3-a-word-about-asynchronism-and-some-bug-fixes/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 09:59:23 +0000</pubDate>
		<dc:creator>Alxandr</dc:creator>
				<category><![CDATA[dotRant]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[irc]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.alxandr.me/?p=319</guid>
		<description><![CDATA[Part 2 Part 4 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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=319&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="post-nav">
<div class="nav-previous"><a href="/2011/10/07/dotrant-making-an-irc-library-for-net-in-c-part-2-the-message-connection/">Part 2</a></div>
<div class="nav-next"><a href="/2011/10/24/dotrant-making-an-irc-library-for-net-in-c-part-4-skeletal-structure-of-the-ircclient-and-the-defaultdictionary/">Part 4</a></div>
</div>
<p>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&#8217;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:<br />
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Sends the specified message.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;message&quot;&gt;The message.&lt;/param&gt;
        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(&quot;&gt;&gt; {0}&quot;, Encoding.UTF8.GetString(message));
            lock (sendBuffer)
                sendBuffer.Write(buffer, 0, buffer.Length);
            TransferData(null);
        }
</pre></p>
<p>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&#8217;ve added a event called &#8220;Disconnect&#8221;, and a &#8220;OnDisconnect&#8221;-method (same as with the other events), and then I&#8217;ve added the following piece of code right after the EndReceive-call in DataReceived<br />
<pre class="brush: csharp;">
            if (receivedDataLength == 0)
            {
                logger.Debug(&quot;Disconnected&quot;);
                client.Close();
                OnDisconnect();
                return;
            }
</pre><br />
Next, in the same function you want to replace<br />
<pre class="brush: csharp;">
buffer.CopyTo(data, bufferLength);
</pre><br />
with<br />
<pre class="brush: csharp;">
Array.Copy(buffer, 0, data, bufferLength, receivedDataLength);
</pre><br />
and then you want to replace<br />
<pre class="brush: csharp;">
byte[] message = new byte[i];
Array.Copy(data, msgStart, message, 0, i); // Copy data[msgStart:i] to message
</pre><br />
with<br />
<pre class="brush: csharp;">
byte[] message = new byte[i - msgStart];
Array.Copy(data, msgStart, message, 0, i - msgStart); // Copy data[msgStart:i] to message
</pre><br />
After this is done we can move on to the next topic.<br />
<span id="more-319"></span></p>
<h3>Asynchronism</h3>
<p>As I might have stated earlier, I want dotRant to run async. There are several good reasons to this and I&#8217;ve already taken measures to make sure most of dotRant is async, but there is still one thing that can cause a freeze if it takes too long time. This can be bad, it will also make connecting to several servers at once take unnecessarily long time as we&#8217;d have to wait for each connection to finish before starting on the next. So, I&#8217;ve changed the Connect-methods to ConnectAsync-methods that returns a Task-instance, and then I&#8217;ve also created two new Connect-methods that runs synchronously, that use our async implementations and wait for their completion. The code is pretty simple and self-explanatory, so I&#8217;m just gone post it.<br />
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Connects the specified end point.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;endPoint&quot;&gt;The end point.&lt;/param&gt;
        /// &lt;param name=&quot;secureConnection&quot;&gt;if set to &lt;c&gt;true&lt;/c&gt; connects using ssl.&lt;/param&gt;
        public Task ConnectAsync(IPEndPoint endPoint, bool secureConnection)
        {
            if (Connected)
                throw new InvalidOperationException(&quot;Cannot connect when already connected&quot;);
            if (client == null)
                client = new TcpClient();

            logger.Debug(&quot;Connecting to {0}:{1}&quot;, endPoint.Address, endPoint.Port);

            var asyncResult = client.BeginConnect(endPoint.Address, endPoint.Port, null, null);
            return Task.Factory.FromAsync(asyncResult, result =&gt;
            {
                client.EndConnect(result);
                if (!secureConnection)
                {
                    networkStream = client.GetStream();
                }
                else
                {
                    if (String.IsNullOrWhiteSpace(hostname))
                        throw new InvalidOperationException(&quot;Can't use ssl without specifying a host-name&quot;);

                    networkStream = new SslStream(client.GetStream(),
                        false,
                        new RemoteCertificateValidationCallback(ValidateServerCert),
                        null);
                    try { ((SslStream)networkStream).AuthenticateAsClient(hostname); }
                    catch (AuthenticationException ex)
                    {
                        logger.Warn(&quot;Certificate not accepted, exception: {0}&quot;, ex);
                        throw ex;
                    }
                }
                messagesBuffer = new MemoryStream();
                sendBuffer = new MemoryStream();
                networkStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(DataReceived), null);
            });
        }
        /// &lt;summary&gt;
        /// Connects the specified hostname.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;hostname&quot;&gt;The hostname.&lt;/param&gt;
        /// &lt;param name=&quot;port&quot;&gt;The port.&lt;/param&gt;
        /// &lt;param name=&quot;secureConnection&quot;&gt;if set to &lt;c&gt;true&lt;/c&gt; connects using ssl.&lt;/param&gt;
        public Task ConnectAsync(string hostname, int port, bool secureConnection)
        {
            this.hostname = hostname;
            return ConnectAsync(new IPEndPoint(Dns.GetHostAddresses(hostname)[0], port), secureConnection);
        }
        /// &lt;summary&gt;
        /// Connects the specified end point.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;endPoint&quot;&gt;The end point.&lt;/param&gt;
        /// &lt;param name=&quot;secureConnection&quot;&gt;if set to &lt;c&gt;true&lt;/c&gt; connects using ssl.&lt;/param&gt;
        public void Connect(IPEndPoint endPoint, bool secureConnection)
        {
            ConnectAsync(endPoint, secureConnection).Wait();
        }
        /// &lt;summary&gt;
        /// Connects the specified hostname.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;hostname&quot;&gt;The hostname.&lt;/param&gt;
        /// &lt;param name=&quot;port&quot;&gt;The port.&lt;/param&gt;
        /// &lt;param name=&quot;secureConnection&quot;&gt;if set to &lt;c&gt;true&lt;/c&gt; connects using ssl.&lt;/param&gt;
        public void Connect(string hostname, int port, bool secureConnection)
        {
            ConnectAsync(hostname, port, secureConnection).Wait();
        }
</pre><br />
Should you find any mistakes, or have any questions, please contact me or leave a comment. The entire source-code can be found on link below:<br />
<a href="https://github.com/Alxandr/dotRant/tree/part-3/src/dotRant">https://github.com/Alxandr/dotRant/tree/part-3/src/dotRant</a></p>
<p>Until then. Alxandr.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alxen.wordpress.com/319/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alxen.wordpress.com/319/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alxen.wordpress.com/319/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alxen.wordpress.com/319/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alxen.wordpress.com/319/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alxen.wordpress.com/319/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alxen.wordpress.com/319/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alxen.wordpress.com/319/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alxen.wordpress.com/319/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alxen.wordpress.com/319/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alxen.wordpress.com/319/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alxen.wordpress.com/319/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alxen.wordpress.com/319/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alxen.wordpress.com/319/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=319&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.alxandr.me/2011/10/18/dotrant-making-an-irc-library-for-net-in-c-part-3-a-word-about-asynchronism-and-some-bug-fixes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5a87311ea4c9950793397f01eb208830?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Alxandr</media:title>
		</media:content>
	</item>
		<item>
		<title>dotRant: Making an IRC library for .NET in C# – Part 2: The message connection</title>
		<link>http://blog.alxandr.me/2011/10/07/dotrant-making-an-irc-library-for-net-in-c-part-2-the-message-connection/</link>
		<comments>http://blog.alxandr.me/2011/10/07/dotrant-making-an-irc-library-for-net-in-c-part-2-the-message-connection/#comments</comments>
		<pubDate>Fri, 07 Oct 2011 06:57:59 +0000</pubDate>
		<dc:creator>Alxandr</dc:creator>
				<category><![CDATA[dotRant]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[irc]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.alxandr.me/?p=276</guid>
		<description><![CDATA[Part 1 Part 3 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 &#8220;CRLF&#8221; (windows newline), and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=276&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="post-nav">
<div class="nav-previous"><a href="/2011/10/06/dotrant-making-an-irc-library-for-net-in-c-part-1-the-irc-protocol/">Part 1</a></div>
<div class="nav-next"><a href="/2011/10/18/dotrant-making-an-irc-library-for-net-in-c-part-3-a-word-about-asynchronism-and-some-bug-fixes/">Part 3</a></div>
</div>
<p>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 &#8220;CRLF&#8221; (windows newline), and consist of only text. This makes parsing of IRC pretty easy, so today we&#8217;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.</p>
<p>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 &#8220;TcpClient&#8221;-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&#8217;ve found that you need to have a Stream, and those are simply provided to us by the &#8220;TcpClient&#8221;-class, so for simplicity we are using that one, or rather, the &#8220;NetworkStream&#8221; 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&#8217;m using NLog to implement logging in our library. Just thought I&#8217;d let you know. Now, let&#8217;s start with some code already xD.<br />
<span id="more-276"></span></p>
<h3>MessageConnection</h3>
<p>Let&#8217;s first begin with an empty class named MessageConnection, containing a logger and a TcpClient.<br />
<pre class="brush: csharp;">
using System.Net.Sockets;
using NLog;

namespace dotRant
{
    /// &lt;summary&gt;
    /// A class used to create a message TCP-connection
    /// with a server.
    /// &lt;/summary&gt;
    public class MessageConnection
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();

        private TcpClient client;
    }
}
</pre></p>
<p>Currently this class does absolute nothing, but it&#8217;s a start at least xD. What we first need is the ability to connect to a server, however, we don&#8217;t want the user to be able to connect to a server if a connection is already existing, so let&#8217;s add a property to check if the connection is existing or not. Here&#8217;s the property<br />
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Gets a value indicating whether this &lt;see cref=&quot;MessageConnection&quot;/&gt; is connected.
        /// &lt;/summary&gt;
        /// &lt;value&gt;
        ///   &lt;c&gt;true&lt;/c&gt; if connected; otherwise, &lt;c&gt;false&lt;/c&gt;.
        /// &lt;/value&gt;
        public bool Connected
        {
            get
            {
                return client != null &amp;&amp; client.Connected;
            }
        }
</pre></p>
<h3>Connecting</h3>
<p>Now that we have that out of the way, we can start writing on a Connect-method. A Connect-method should take 2 parameters: The &#8220;EndPoint&#8221; we want to connect to, and whether or not to use a secure connection. However, constructing &#8220;EndPoint&#8221;-instances can be a pain, so it should also have an overload which takes 3 parameters; the hostname/ip-address to connect to, the port number, and whether or not to use a secure connection. Also, I&#8217;ve already mentioned supporting secure connections requires a stream, so we should add that to our class, because if we are to use a secure connection we use an &#8220;SslStream&#8221;, which is a wrapper for a normal Stream, so we need to address it when sending and receiving messages. So, go ahead and add a &#8220;Stream&#8221; to our class, and call it &#8220;networkStream&#8221;. Also, we need a string containing the hostname for when we are to authenticate using Ssl, so go ahead and add that too, then we can make our Connect-methods.</p>
<p><pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Connects the specified end point.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;endPoint&quot;&gt;The end point.&lt;/param&gt;
        /// &lt;param name=&quot;secureConnection&quot;&gt;if set to &lt;c&gt;true&lt;/c&gt; connects using ssl.&lt;/param&gt;
        public void Connect(IPEndPoint endPoint, bool secureConnection)
        {
            if (Connected)
                throw new InvalidOperationException(&quot;Cannot connect when already connected&quot;);
            if (client == null)
                client = new TcpClient();

            logger.Debug(&quot;Connecting to {0}:{1}&quot;, endPoint.Address, endPoint.Port);
            client.Connect(endPoint);
            if (!secureConnection)
            {
                networkStream = client.GetStream();
            }
            else
            {
                if (String.IsNullOrWhiteSpace(hostname))
                    throw new InvalidOperationException(&quot;Can't use ssl without specifying a host-name&quot;);

                networkStream = new SslStream(client.GetStream(),
                    false,
                    new RemoteCertificateValidationCallback(ValidateServerCert),
                    null);
                try { ((SslStream)networkStream).AuthenticateAsClient(hostname); }
                catch (AuthenticationException ex)
                {
                    throw new NotImplementedException(&quot;Not yet implemented.&quot;);
                }
            }
            throw new NotImplementedException(&quot;Begin reading data.&quot;);
        }
        /// &lt;summary&gt;
        /// Connects the specified hostname.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;hostname&quot;&gt;The hostname.&lt;/param&gt;
        /// &lt;param name=&quot;port&quot;&gt;The port.&lt;/param&gt;
        /// &lt;param name=&quot;secureConnection&quot;&gt;if set to &lt;c&gt;true&lt;/c&gt; connects using ssl.&lt;/param&gt;
        public void Connect(string hostname, int port, bool secureConnection)
        {
            Connect(new IPEndPoint(Dns.GetHostAddresses(hostname)[0], port), secureConnection);
            this.hostname = hostname;
        }
</pre><br />
Now, there are a few thing to note here. First of all, line 24, we register a callback for validating the remote server-certificate. This is yet to be implemented in our class. Also, there are two places in our method where a NotImplementedException is fired. The first one is whenever there was an error in authenticating with the server (they had the wrong certificate for instance), and the second is when we are done connecting, cause then we want to start listening for data.</p>
<h3>Receiving data</h3>
<p>Let&#8217;s start by implementing listening for data, as that can be done pretty simply. What we need is a buffer for the data to be downloaded into, and then we need a new method. But lets start with creating a byte[] called buffer and add it to the class. Initialize it to be of BUFFER_SIZE size, and define a const int BUFFER_SIZE that is set to 4096. Then replace the NotImplementedException call at the bottom of the first Connect-method with this:<br />
<pre class="brush: csharp;">
networkStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(DataReceived), null);
</pre><br />
That&#8217;s a start. Now, whenever our client has finished connecting it will start listening for data, and the data will be put into the buffer-array. Now we just need to implement our DataReceived-method and we are done with that part, but first, a small explanation on some networking is due. One of the &#8220;problems&#8221; with sending data over the network is that you never know how it&#8217;s going to arrive. You send a bunch of bytes, and TCP guarantees you (as long as there is a connection) that the data will arrive in the same order as it was sent, however, what it does not guarantee is that the data arrives as a blob the same size as it was sent. Let me explain this with a example rather. If I send 500 bytes of data to server B, then right after that I send 500 more bytes, there is nothing wrong with server B receiving that as one blob of 1000 bytes. That however is still easy to handle, the problem is when you send 500 bytes, and it arrives as 200, then 200, then 100. If all those 500 bytes was one command you need to sow it back together before you can parse it, and to do so, we need a second buffer. However, this can&#8217;t be a simple byte-array, because we have no idea of the size of commands that might arrive from the server. There are several possible methods to solve this. We could use a List of bytes, we could use a MemoryStream, or we could even use a StringBuilder. The problem with using a StringBuilder (or any type that want&#8217;s to store the buffer as a string rather than bytes) is that it is possible to retrieve a part of a message in such a way that one char get&#8217;s split in two. For instance, say we use UTF-8 and transfer the letter &#8220;å&#8221;. The letter &#8220;å&#8221; get&#8217;s encoded as the bytes [0xC3,0xA5]. It is possible that we received the first of the two bytes as one message, then the last one. If we only received the first one and try to parse that as UTF-8 to store it in a string, we&#8217;d get an error in our message, therefore it&#8217;s better to use bytes as the buffer. In dotRant I will implement this second buffer as a MemoryStream, and I will call it messagesBuffer. I will also initialize it just before I call BeginRead in the Connect-method.</p>
<p>A short description of how DataReceived needs to work before we start making it: DataReceived is called whenever there is new data available from the server. However, as discussed in the previous section, we can not know that what we receive is one command, it might be more, and it might be less. In the case that it&#8217;s more, it&#8217;s quite simple, we just split it up by &#8220;CRLF&#8221;, however, if there are less we need to store what we received, so that we can add that to the data we receive next time DataReceived is called. That too however might be more than one message, and so forth. I think the best way to show this is to show the code, but I just thought I&#8217;d explain my thoughts about how to write this function before actually showing it to you.<br />
<pre class="brush: csharp;">
        private void DataReceived(IAsyncResult result)
        {
            int receivedDataLength = networkStream.EndRead(result);
            int bufferLength = (int)messagesBuffer.Length;
            int totalDataLength = bufferLength + receivedDataLength;
            byte[] data = new byte[totalDataLength];
            messagesBuffer.ToArray().CopyTo(data, 0);
            buffer.CopyTo(data, bufferLength);
            messagesBuffer.SetLength(0);
            // At this point data is all the received data, including what was in the buffer, and the buffer is emptied.

            int msgStart = 0;
            for (int i = 0; i &lt; data.Length - 1; i++)
            {
                if (data[i] == 13 &amp;&amp; data[i + 1] == 10) // byte 10 = LF and byte 13 = CR
                {
                    byte[] message = new byte[i];
                    Array.Copy(data, msgStart, message, 0, i); // Copy data[msgStart:i] to message
                    logger.Debug(&quot;&lt;&lt; {0}&quot;, Encoding.UTF8.GetString(message));
                    throw new NotImplementedException(&quot;Handle the message&quot;);
                    msgStart = i = i + 2;
                }
            }

            // What is left from msgStart til the end of data is only a partial message.
            // We want to save that for when the rest of the message arrives.
            messagesBuffer.Write(data, msgStart, data.Length);

            // Start listening again
            networkStream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(DataReceived), null);
        }
</pre></p>
<p>A note about the DataReceived function; on line 19 there is a new &#8220;NotImplementedException&#8221;. What we want to do here is tell whatever class created this MessageConnection that there is a new message. So, what we need is to create an event, then fire that event. But to get data sent trough an event we need first create a &#8220;EventArgs&#8221;-class. Let&#8217;s call this &#8220;MessageEventArgs&#8221; and have it look like this:</p>
<p><pre class="brush: csharp;">
using System;

namespace dotRant
{
    /// &lt;summary&gt;
    /// EventArgs-class used when a new Message is received in the &lt;see cref=&quot;MessageConnection&quot;/&gt; class.
    /// &lt;/summary&gt;
    public class MessageEventArgs : EventArgs
    {
        private byte[] message;
        /// &lt;summary&gt;
        /// Initializes a new instance of the &lt;see cref=&quot;MessageEventArgs&quot;/&gt; class.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;message&quot;&gt;The message.&lt;/param&gt;
        public MessageEventArgs(byte[] message)
        {
            this.message = message;
        }

        /// &lt;summary&gt;
        /// Gets the message.
        /// &lt;/summary&gt;
        public byte[] Message
        {
            get { return message; }
        }
    }
}
</pre></p>
<p>Then lets create an EventHandler&lt;MessageEventArgs&gt; event in the MessageConnection-class, and let&#8217;s call it &#8220;Message&#8221;, after that let&#8217;s make a virtual protected function named OnMessage that looks like this:</p>
<p><pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Called when a new message is received.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;message&quot;&gt;The message.&lt;/param&gt;
        protected virtual void OnMessage(byte[] message)
        {
            if (Message != null)
                Message(this, new MessageEventArgs(message));
        }
</pre></p>
<p>Now we&#8217;re getting close to something. Replace the NotImplementedExceptoin in DataReceived with a call to OnMessage, and our class is done with the aspect of receiving data.</p>
<h3>Sending data</h3>
<p>Sending data is much simpler than receiving, simply because we don&#8217;t need to parse it. However, we need to make sure that the data we send don&#8217;t contain &#8220;CRLF&#8221;, and append &#8220;CRLF&#8221; at the end of the data. Let&#8217;s start by creating a Send-method that takes a byte-array as it&#8217;s only parameter. It should check to see that we are connected, then it should send the data async. However, by sending the data async would mean that there is a chance that the Send-method will be called again before it&#8217;s finished sending, and we need to handle that scenario. What we should do is to implement a sendBuffer, the same way we implemented a messageBuffer. Also, in the same way DataReceived is called whenever there is new data available, we can have a function be called whenever it&#8217;s finished writing, so we just need that function to continue sending if there is anything in the buffer. First we should create a MemoryStream that is named sendBuffer the same way we did with messageBuffer, then we should initialize it at the same place we initialized the messageBuffer too.</p>
<p><pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Sends the specified message.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;message&quot;&gt;The message.&lt;/param&gt;
        public void Send(byte[] message)
        {
            message = RemoveCrLf(message);
            logger.Debug(&quot;&gt;&gt; {0}&quot;, Encoding.UTF8.GetString(message));
            lock (sendBuffer)
                sendBuffer.Write(message, 0, message.Length);
            TransferData(null);
        }
        private byte[] RemoveCrLf(byte[] data)
        {
            MemoryStream ms = new MemoryStream();
            for (int i = 0; i &lt; data.Length; i++)
            {
                if (i &lt; data.Length - 1 &amp;&amp; data[i] == 13 &amp;&amp; data[i + 1] == 10) // byte 10 = LF and byte 13 = CR
                    continue;

                ms.WriteByte(data[i]);
            }
            if (ms.Length != data.Length)
                return RemoveCrLf(ms.ToArray());
            return data;
        }
</pre></p>
<p>The &#8220;TransferData&#8221;-methodcall that&#8217;s been made here has yet to be written. It will do the actual sending of the data, however, it will also be called whenever sending is complete. An interesting fact to se here is the lock-statement I&#8217;ve wrapped sendBuffer.Write in. This is to make sure that there are no errors when running this &#8220;Send&#8221;-method from several threads at once. Now, let&#8217;s write the TransferData-method. However, for it to function properly we need to add another private member to our class. A bool named sending.</p>
<p><pre class="brush: csharp;">
        private void TransferData(IAsyncResult result)
        {
            if (result != null)
            {
                networkStream.EndWrite(result);
                lock (sendBuffer)
                    sending = false;
            }
            MemoryStream ms = null;
            lock (sendBuffer)
            {
                if (sending)
                    return;

                if (sendBuffer.Length != 0)
                {
                    sending = true;
                    ms = new MemoryStream();
                    sendBuffer.CopyTo(ms);
                    sendBuffer.SetLength(0);
                }
            }
            if (ms != null)
                networkStream.BeginWrite(ms.ToArray(), 0, (int)ms.Length, new AsyncCallback(TransferData), null);
        }
</pre></p>
<p>Now our class is nearly complete. We have sending, and we have receiving of data. There is only one thing lacking.</p>
<h3>Authentication using SSL</h3>
<p>As shown earlier in this post, we need to handle authentication of our client when we want to use a secure connection. To do this we need to implement one function (&#8220;ValidateServerCert&#8221;), and we also have a NotImplementedException in the event that the authentication failed. Now, what I would like for our &#8220;MessageConnection&#8221;-class to do when we try to authenticate with the server is to call out to the handling class and let it decide what to do, and to do so we should implement an event. However, before we do so, let&#8217;s just implement a vanilla-implementation of the ValidateServerCert-function like this:</p>
<p><pre class="brush: csharp;">
        private bool ValidateServerCert(
              object sender,
              X509Certificate certificate,
              X509Chain chain,
              SslPolicyErrors sslPolicyErrors)
        {
            return OnSslValidate(sender, certificate, chain, sslPolicyErrors);
        }
</pre></p>
<p>Before we go ahead and create our OnSslValidate-function, let&#8217;s create a new EventArgs-class like we did with the MessageEventArgs, this one should be called &#8220;SslValidateEventArgs&#8221;.</p>
<p><pre class="brush: csharp;">
using System;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace dotRant
{
    /// &lt;summary&gt;
    /// EventArgs-class used when authenticating using ssl in the &lt;see cref=&quot;MessageConnection&quot;/&gt; class.
    /// &lt;/summary&gt;
    public class SslValidateEventArgs : EventArgs
    {
        private object sender;
        private X509Certificate certificate;
        private X509Chain chain;
        private SslPolicyErrors sslPolicyErrors;
        private bool accept;

        /// &lt;summary&gt;
        /// Initializes a new instance of the &lt;see cref=&quot;SslValidateEventArgs&quot;/&gt; class.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;sender&quot;&gt;The sender.&lt;/param&gt;
        /// &lt;param name=&quot;certificate&quot;&gt;The certificate.&lt;/param&gt;
        /// &lt;param name=&quot;chain&quot;&gt;The chain.&lt;/param&gt;
        /// &lt;param name=&quot;sslPolicyErrors&quot;&gt;The SSL policy errors.&lt;/param&gt;
        public SslValidateEventArgs(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            this.sender = sender;
            this.certificate = certificate;
            this.chain = chain;
            this.sslPolicyErrors = sslPolicyErrors;
            this.accept = false;
        }

        /// &lt;summary&gt;
        /// Gets the sender.
        /// &lt;/summary&gt;
        public object Sender
        {
            get { return sender; }
        }

        /// &lt;summary&gt;
        /// Gets the certificate.
        /// &lt;/summary&gt;
        public X509Certificate Certificate
        {
            get { return certificate; }
        }

        /// &lt;summary&gt;
        /// Gets the chain.
        /// &lt;/summary&gt;
        public X509Chain Chain
        {
            get { return chain; }
        }

        /// &lt;summary&gt;
        /// Gets the SSL policy errors.
        /// &lt;/summary&gt;
        public SslPolicyErrors SslPolicyErrors
        {
            get { return sslPolicyErrors; }
        }

        /// &lt;summary&gt;
        /// Gets or sets a value indicating whether this certificate is accepted.
        /// &lt;/summary&gt;
        /// &lt;value&gt;
        ///   &lt;c&gt;true&lt;/c&gt; if accepted; otherwise, &lt;c&gt;false&lt;/c&gt;.
        /// &lt;/value&gt;
        public bool Accept
        {
            get { return accept; }
            set { accept = value; }
        }
    }
}
</pre></p>
<p>Notice the &#8220;Accept&#8221;-value that wasn&#8217;t present in our OnSslValidate-method. This Accept-value is used to set wheaten or not to accept the certificate, and should be the return-value of OnSslValidate. Now we can implement OnSslValidate pretty easily, like this (note I&#8217;ve already added the event EventHandler&lt;SslValidateEventArgs&gt; SslValidate):<br />
<pre class="brush: csharp;">
        /// &lt;summary&gt;
        /// Called when a ssl-certificate should be validated.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;sender&quot;&gt;The sender.&lt;/param&gt;
        /// &lt;param name=&quot;certificate&quot;&gt;The certificate.&lt;/param&gt;
        /// &lt;param name=&quot;chain&quot;&gt;The chain.&lt;/param&gt;
        /// &lt;param name=&quot;sslPolicyErrors&quot;&gt;The SSL policy errors.&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        protected virtual bool OnSslValidate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            SslValidateEventArgs args = new SslValidateEventArgs(sender, certificate, chain, sslPolicyErrors);
            if (SslValidate != null)
                SslValidate(this, args);
            return args.Accept;
        }
</pre></p>
<p>Now, what we should do is to edit the catch-block of the Connect-method to log the error, than rethrow it. And then we&#8217;re done. Should you find any mistakes, or have any questions, please contact me or leave a comment. The entire source-code can be found on link below:<br />
<a href="https://github.com/Alxandr/dotRant/tree/part-2/src/dotRant">https://github.com/Alxandr/dotRant/tree/part-2/src/dotRant</a></p>
<p>Until then. Alxandr.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alxen.wordpress.com/276/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alxen.wordpress.com/276/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alxen.wordpress.com/276/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alxen.wordpress.com/276/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alxen.wordpress.com/276/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alxen.wordpress.com/276/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alxen.wordpress.com/276/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alxen.wordpress.com/276/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alxen.wordpress.com/276/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alxen.wordpress.com/276/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alxen.wordpress.com/276/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alxen.wordpress.com/276/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alxen.wordpress.com/276/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alxen.wordpress.com/276/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=276&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.alxandr.me/2011/10/07/dotrant-making-an-irc-library-for-net-in-c-part-2-the-message-connection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5a87311ea4c9950793397f01eb208830?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Alxandr</media:title>
		</media:content>
	</item>
		<item>
		<title>dotRant: Making an IRC library for .NET in C# &#8211; Part 1: The IRC protocol</title>
		<link>http://blog.alxandr.me/2011/10/06/dotrant-making-an-irc-library-for-net-in-c-part-1-the-irc-protocol/</link>
		<comments>http://blog.alxandr.me/2011/10/06/dotrant-making-an-irc-library-for-net-in-c-part-1-the-irc-protocol/#comments</comments>
		<pubDate>Thu, 06 Oct 2011 03:47:47 +0000</pubDate>
		<dc:creator>Alxandr</dc:creator>
				<category><![CDATA[dotRant]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[irc]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.alxandr.me/?p=244</guid>
		<description><![CDATA[Part 2 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 &#8220;Internet Relay Chat&#8221; and is an old chatting-protocol. Not that many people use [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=244&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="post-nav">
<div class="nav-next"><a href="/2011/10/07/dotrant-making-an-irc-library-for-net-in-c-part-2-the-message-connection/">Part 2</a></div>
</div>
<p>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 &#8220;Internet Relay Chat&#8221; and is an old chatting-protocol. Not that many people use IRC anymore, and many people don&#8217;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&#8217;s made to chat with groups, not single persons. The point with IRC is that you enter a &#8220;room&#8221;, or a &#8220;group&#8221;, 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&#8217;s also has the capability to do group-chats, but you need to be invited to those. You can&#8217;t just join a group based on its name and talk to persons you have never talked to before, and that&#8217;s what I use IRC for.</p>
<p>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&#8217;d really like to create an IRC client in WPF, simply for the fun of doing it, but currently I&#8217;m focusing on the bot part. Another thing to know about this series is that I don&#8217;t know when it&#8217;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&#8217;t understand, and that works out just fine. The same can be said for all IRC clients. Most clients I&#8217;ve used, if they receive something they don&#8217;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&#8217;ll see more about that when we get a little further.</p>
<p><span id="more-244"></span></p>
<h3>The IRC protocol</h3>
<p>The IRC protocol is a simple protocol which makes creating an IRC C# library a task that&#8217;s not very complicated looking at the network part. The protocol consists of sending messages, or commands as I&#8217;ll refer them as, back and forth from the client and the server. These messages should be within a certain size (I don&#8217;t know if there is actually a set limit for the command-size, but I&#8217;ve experienced servers rejecting commands that are too long), and consists of a prefix (only received messages as far as I know), a command-name, and a (possibly empty) sequence of parameters. The parameters are separated by one or more spaces, and the command is separated by &#8220;CRLF&#8221; (windows, and telnet newline). The prefix is generally who sent the command (which might vary depending on the command), and the command-name is ether a string of letters, or a number. The prefix and the command-name is also separated by a space. Empty commands are allowed (you can send one by sending &#8220;CRLFCRLF&#8221;), and they are simply ignored by the receiver. Parameters are separated by space, and can thus normally not contain spaces, however, as this would be pretty inconvenient (you would only be able to send messages with one word) the last parameter can contain spaces by prefixing it with a colon (&#8216;:&#8217;). An example of this would be the command below, it shows the command to send a message to the channel &#8220;#test&#8221; containing the text &#8220;This is simply a test.&#8221;.</p>
<p><pre class="brush: plain;">
PRIVMSG #test :This is simply a test.
</pre></p>
<p style="margin-top:25px;">
To connect to an IRC network you first need to identify yourself. This isn&#8217;t like login with username and password to enter, it&#8217;s simply telling the server who you are, and what you would like to be called. This is done with the &#8220;USER&#8221;, &#8220;PASS&#8221; and the &#8220;NICK&#8221; commands. &#8220;NICK&#8221; can also be used later to change your nick to something else. An example of what a connecting client would send to the server when it connects would be something like this:</p>
<p><pre class="brush: plain;">
PASS *
NICK &lt;nick&gt;
USER guest 8 * :&lt;full name&gt;
</pre></p>
<p>
What happens here is that the user tells the server that it would like to login with the nick &lt;nick&gt;, and that its full-name is &lt;full name&gt;. The 8 in the &#8220;USER&#8221;-command signifies that the user would like to be invisible, and the * in the USER-command is an unused parameter placed there for legacy-reasons.</p>
<p>Some of the important commands to know in IRC are the following:</p>
<ul>
<li><strong>PASS</strong>: Used when connecting to a server. In theory (and maybe in practice too) servers might have a password set, to disable users from connecting that don&#8217;t know the password, but normally you just pass &#8220;*&#8221; as the password</li>
<li><strong>NICK</strong>: Used to set your nick. May result in the server sending an error complaining about the fact that the nick you picked is already in use by someone else.</li>
<li><strong>USER</strong>: Used when connecting, mostly specifies full name.</li>
<li><strong>PRIVMSG</strong>: Used to send messages to users or channels (groups).</li>
<li><strong>JOIN</strong>: Used to join a channel.</li>
<li><strong>PART</strong>: Used to leave a channel.</li>
<li><strong>PONG</strong>: Used to answer the server&#8217;s ping-requests</li>
</ul>
<p>All of these are commands that should be sent to the server from the client. One of the things that&#8217;s important to notice is the &#8220;PONG&#8221; command. From time to time the server will send you a &#8220;PING&#8221; command (if you are not active). This is to ensure that the client has not disconnected. If you do not reply to the &#8220;PING&#8221;, the server will assume that you have lost the connection, and disconnect from you. This means no more IRC until you reconnect, which is not a good thing as you probably will miss messages. &#8220;PING&#8221; is sent from the server with a single parameter, and you just have to send &#8220;PONG&#8221; back with the same parameter. Simple as that.</p>
<h3>IRC in telnet</h3>
<p>To try out the IRC protocol, the simplest thing to do is to test it out using telnet. If you are on Windows, you might need to turn on the telnet-client (&#8220;turn windows features on/off&#8221; from control panel). To connect to an IRC server you need to know it&#8217;s host-name or ip, and the port it&#8217;s listening on (usually 6667 for normal and 9999 for ssl). To connect, simply open a command-prompt (cmd in windows, terminal on mac, and if you are on linux and don&#8217;t know how to get a command prompt then shame on you) and type &#8220;telnet  &#8220;. At first, after it&#8217;s connected, you will probably not see anything (except for an empty console). To start, you need to send the &#8220;PASS&#8221;, &#8220;NICK&#8221; and &#8220;USER&#8221; commands. After you have done this, wait a few seconds, and data should be popping down in your console. Simple as that. If you have any problems at all with getting this to work, please leave me a comment in the comment-section, and I&#8217;ll get back to you so we can figure out what is wrong).</p>
<h3>What&#8217;s next?</h3>
<p>Now, this was a long post about writing a library in C#, and without a single line of code. However, I hope I&#8217;ve given you a brief explanation of how IRC works, and that is required to know before we start building our library. In the next post we will start coding, and laying the foundation for the dotRant IRC library.</p>
<p>Until then. Alxandr.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alxen.wordpress.com/244/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alxen.wordpress.com/244/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alxen.wordpress.com/244/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alxen.wordpress.com/244/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alxen.wordpress.com/244/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alxen.wordpress.com/244/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alxen.wordpress.com/244/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alxen.wordpress.com/244/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alxen.wordpress.com/244/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alxen.wordpress.com/244/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alxen.wordpress.com/244/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alxen.wordpress.com/244/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alxen.wordpress.com/244/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alxen.wordpress.com/244/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=244&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.alxandr.me/2011/10/06/dotrant-making-an-irc-library-for-net-in-c-part-1-the-irc-protocol/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5a87311ea4c9950793397f01eb208830?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Alxandr</media:title>
		</media:content>
	</item>
		<item>
		<title>MutableObject 1.2 &#8211; Reset the state of mutable-objects.</title>
		<link>http://blog.alxandr.me/2011/10/05/mutableobject-1-2-reset-the-state-of-mutable-objects/</link>
		<comments>http://blog.alxandr.me/2011/10/05/mutableobject-1-2-reset-the-state-of-mutable-objects/#comments</comments>
		<pubDate>Wed, 05 Oct 2011 19:38:56 +0000</pubDate>
		<dc:creator>Alxandr</dc:creator>
				<category><![CDATA[Creations]]></category>
		<category><![CDATA[MutableObject]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.alxandr.me/?p=239</guid>
		<description><![CDATA[I just updated MutableObject with a new feature which I just thought I&#8217;d show. To make this short (I don&#8217;t have time for long posts right now) I&#8217;ll just post a unit-test that shows the new behavior perfectly. I&#8217;ve also edited my nuget-build-rutine (for later releases) so that it includes the xml-documentation for the methods. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=239&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I just updated MutableObject with a new feature which I just thought I&#8217;d show. To make this short (I don&#8217;t have time for long posts right now) I&#8217;ll just post a unit-test that shows the new behavior perfectly.</p>
<p><pre class="brush: csharp;">
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 = &quot;Per&quot;;

		Interface1 obj1 = Mutate.CreateMutableObject&lt;Interface1&gt;();
		Interface1 obj2 = Mutate.CreateMutableObject&lt;Interface1&gt;(obj);

		obj1.Name = &quot;Knut&quot;;
		obj2.Name = &quot;Knut&quot;;

		Assert.AreEqual(obj.Name, &quot;Knut&quot;);

		Mutate.Reset(obj1);
		Mutate.Reset(obj2);

		Assert.AreEqual(obj.Name, &quot;Per&quot;);
		Assert.IsFalse(Mutate.PropertiesIsSet(obj1, &quot;Name&quot;));
	}
	
}
</pre></p>
<p>I&#8217;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 <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p>Later.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alxen.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alxen.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alxen.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alxen.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alxen.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alxen.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alxen.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alxen.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alxen.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alxen.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alxen.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alxen.wordpress.com/239/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alxen.wordpress.com/239/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alxen.wordpress.com/239/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=239&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.alxandr.me/2011/10/05/mutableobject-1-2-reset-the-state-of-mutable-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5a87311ea4c9950793397f01eb208830?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Alxandr</media:title>
		</media:content>
	</item>
		<item>
		<title>MutableObject &#8211; Track state of simple CLR objects</title>
		<link>http://blog.alxandr.me/2011/10/04/mutableobject-track-state-of-simple-clr-objects/</link>
		<comments>http://blog.alxandr.me/2011/10/04/mutableobject-track-state-of-simple-clr-objects/#comments</comments>
		<pubDate>Mon, 03 Oct 2011 23:07:29 +0000</pubDate>
		<dc:creator>Alxandr</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[MutableObject]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://alxen.wordpress.com/?p=218</guid>
		<description><![CDATA[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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=218&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>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&#8217;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:</p>
<p><pre class="brush: csharp;">
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(&quot;UPDATE Contacts SET &quot;);
		// Get all the changed properties and loop trough and add
		// the property to the update-query.
		qb.Append(&quot; WHERE Id = &quot;).Append(contact.Id);
	}
}
</pre></p>
<p>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&#8217;m using concatenation to construct a SQL-query (which you simply shouldn&#8217;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 &#8220;Install-Package MutableObject&#8221;. Then, let&#8217;s change our GetContact-method a tiny bit to enable the use of MutableObject.</p>
<p><pre class="brush: csharp;">
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&lt;IContact&gt;(contact);
}
</pre></p>
<p>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&#8217;s only parameter. It&#8217;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 &#8220;bound&#8221;), 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.</p>
<p>Once you have a MutableObject (which you can confirm by calling <span style="white-space:pre;font-family:Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;font-weight:bold;">Mutate.IsMutable(object obj)</span>) 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 <span style="white-space:pre;font-family:Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;font-weight:bold;">Mutate.PropertiesIsSet(object obj, params string[] propertyNames)</span>, however, when using bound items this will always return true.</p>
<p>Now, let&#8217;s update our Update-method so that it actually builds the query.</p>
<p><pre class="brush: csharp;">
public void Update(IContact contact)
{
	var dbContact = GetContact(contact.Id);
	var qb = new StringBuilder(&quot;UPDATE Contacts SET &quot;);
	var props = Mutate.GetChangedProperties(contact);
	foreach(var prop in props)
		qb.Append(prop.Key).Append(&quot; = \&quot;&quot;).Append(prop.Value).Append(&quot;\&quot;, &quot;);
	qb.Remove(qb.Length - 3, 3);
	qb.Append(&quot; WHERE Id = &quot;).Append(contact.Id);
}
</pre></p>
<p>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&#8217;s all for another time. Hope you can find some use for it <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . Leave me a comment if there is anything you want to ask or don&#8217;t understand.</p>
<p>Later.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alxen.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alxen.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alxen.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alxen.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alxen.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alxen.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alxen.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alxen.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alxen.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alxen.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alxen.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alxen.wordpress.com/218/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alxen.wordpress.com/218/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alxen.wordpress.com/218/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=218&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.alxandr.me/2011/10/04/mutableobject-track-state-of-simple-clr-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5a87311ea4c9950793397f01eb208830?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Alxandr</media:title>
		</media:content>
	</item>
		<item>
		<title>An introduction to System.Reflection.Emit and OpCodes</title>
		<link>http://blog.alxandr.me/2010/10/16/an-introduction-to-system-reflection-emit-and-opcodes/</link>
		<comments>http://blog.alxandr.me/2010/10/16/an-introduction-to-system-reflection-emit-and-opcodes/#comments</comments>
		<pubDate>Sat, 16 Oct 2010 21:17:20 +0000</pubDate>
		<dc:creator>Alxandr</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[reflection]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://alxen.wordpress.com/?p=205</guid>
		<description><![CDATA[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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=205&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>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&#8217;d try to explain a bit. I&#8217;m no expert on this subject, but I think I&#8217;ve understood enough of it to make it useful, and I will try to tell you what I&#8217;ve found out about how the IL-code you generate should look like.</p>
<p>I&#8217;m also going to try to make this as practical as possible, so first let&#8217;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&#8217;ve come up with a simple extension-method that will simplify our code a little, add the following few lines to your project:</p>
<p><pre class="brush: csharp;">
public static class MethodExtensions
{
	public static object InvokeStatic(this DynamicMethod method,
		params object[] args)
	{
		return method.Invoke(null, args);
	}
	public static T InvokeStatic&lt;T&gt;(this DynamicMethod method,
		params object[] args)
	{
		return (T)method.InvokeStatic(args);
	}
}
</pre></p>
<p>This provides a cleaner way to call the methods we create later on. But let&#8217;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 &#8220;Method1&#8243; that returns a DynamicMethod, and write the following in it:</p>
<p><pre class="brush: csharp;">
static DynamicMethod Method1()
{
	DynamicMethod method1 = new DynamicMethod(&quot;Method1&quot;, typeof(void),
		new Type[] { });
	ILGenerator il = method1.GetILGenerator();
	il.EmitWriteLine(&quot;Method 1 here&quot;);
	il.Emit(OpCodes.Ret);

	return method1;
}
</pre></p>
<p>This creates a method that calls Console.WriteLine with the parameter &#8220;Method 1 here&#8221;. This is the simplest thing you can do with the DynamicMethod, but it&#8217;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&#8217;t much hard either, the code can look like this:</p>
<p><pre class="brush: csharp;">
static DynamicMethod Method2()
{
	DynamicMethod method1 = new DynamicMethod(&quot;Method2&quot;, typeof(void),
		new Type[] { typeof(string) });
	ILGenerator il = method1.GetILGenerator();
	il.EmitWriteLine(&quot;Method 2 begin&quot;);

	il.Emit(OpCodes.Ldarg_0);
	il.Emit(OpCodes.Call, typeof(Console).GetMethod(&quot;WriteLine&quot;,
		new Type[] { typeof(string) }));

	il.EmitWriteLine(&quot;Method 2 end&quot;);
	il.Emit(OpCodes.Ret);

	return method1;
}
</pre></p>
<p>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 &#8220;this&#8221;-object onto the stack. But since this is a &#8220;static&#8221; 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 &#8220;WriteLine&#8221; on the console is called.</p>
<p>Ok, so that&#8217;s about it for writing out strings. Also, this was the basic of passing arguments to our function, for the next example, let&#8217;s try returning a string. This isn&#8217;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 &#8220;ret&#8221; 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.</p>
<p>To return the string passed in, simply write this:</p>
<p><pre class="brush: csharp;">
static DynamicMethod Method3()
{
	DynamicMethod method1 = new DynamicMethod(&quot;Method3&quot;, typeof(string),
		new Type[] { });
	ILGenerator il = method1.GetILGenerator();

	il.Emit(OpCodes.Ldstr, &quot;This is a string from method 3&quot;);
	il.Emit(OpCodes.Ret);

	return method1;
}
</pre></p>
<p>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&#8217;t know is that a struct is also a value-type (this is the biggest difference between classes and structs if I&#8217;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&#8217;t get an error. However, to use the data-piece it either needs to be casted, or looked upon with reflection.</p>
<p>What most people don&#8217;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&#8217;t really see that it&#8217;s done, and when you cast it back, it&#8217;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&#8217;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.</p>
<p><pre class="brush: csharp;">
static DynamicMethod Method4()
{
	DynamicMethod method1 = new DynamicMethod(&quot;Method4&quot;, typeof(DateTime),
		new Type[] { typeof(DateTime) });
	ILGenerator il = method1.GetILGenerator();

	il.Emit(OpCodes.Ldarg_0);
	il.Emit(OpCodes.Ret);

	return method1;
}
</pre></p>
<p>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:</p>
<p><pre class="brush: csharp;">
static DynamicMethod Method5()
{
	DynamicMethod method1 = new DynamicMethod(&quot;Method4&quot;, 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;
}
</pre></p>
<p>And if we were to switch the parameters, so that the function accepted a DateTime and returned an object, we&#8217;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&#8217;ll use is the WriteLine(Object) overload. The code is as following:</p>
<p><pre class="brush: csharp;">
static DynamicMethod Method6()
{
	DynamicMethod method1 = new DynamicMethod(&quot;Method5&quot;, typeof(void),
		new Type[] { typeof(DateTime) });
	ILGenerator il = method1.GetILGenerator();

	il.EmitWriteLine(&quot;In function 6: &quot;);
	il.Emit(OpCodes.Ldarg_0);
	il.Emit(OpCodes.Box, typeof(DateTime));
	il.Emit(OpCodes.Call, typeof(Console).GetMethod(&quot;WriteLine&quot;,
		new Type[] { typeof(object) }));

	il.Emit(OpCodes.Ret);

	return method1;
}
</pre></p>
<p>If you have any questions please leave them in the comment-section.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alxen.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alxen.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alxen.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alxen.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alxen.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alxen.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alxen.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alxen.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alxen.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alxen.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alxen.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alxen.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alxen.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alxen.wordpress.com/205/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=205&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.alxandr.me/2010/10/16/an-introduction-to-system-reflection-emit-and-opcodes/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5a87311ea4c9950793397f01eb208830?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Alxandr</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating a proxyclass-generator using System.Reflection.Emit</title>
		<link>http://blog.alxandr.me/2010/10/15/creating-a-proxyclass-generator-using-system-reflection-emit/</link>
		<comments>http://blog.alxandr.me/2010/10/15/creating-a-proxyclass-generator-using-system-reflection-emit/#comments</comments>
		<pubDate>Fri, 15 Oct 2010 02:24:27 +0000</pubDate>
		<dc:creator>Alxandr</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[reflection]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://alxen.wordpress.com/?p=172</guid>
		<description><![CDATA[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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=172&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>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:</p>
<p><pre class="brush: csharp;">
public interface InterfaceA
{
    void DoSomething();
    int GetInt();
    int Multiply(int int1, int int2);
    string TrimString(string str);
}
</pre></p>
<p>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:</p>
<p><pre class="brush: csharp;">
ProxyGenerator pg = new ProxyGenerator(IProxyHandler handler);
</pre></p>
<p>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:</p>
<p><pre class="brush: csharp;">
public interface IProxyHandler
{
    object OnMethod(MethodInfo method, object[] args);
}
</pre></p>
<p>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 &#8220;cached&#8221; in the ProxyClass, last but not least we don&#8217;t want to create the same proxy-class twice, so it should be cached too.</p>
<p>The barebone ProxyGenerator-class (without the acutall proxy-generating) looks as following:</p>
<p><pre class="brush: csharp;">
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; }
	}
}
</pre></p>
<p>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&#8217;t get created twice in different threads, and the typeCache is (as the name suggests) the cache used to store the proxy-classes we&#8217;ve created. All of this should be pretty straight forward. The <em>T obj;</em> is where we want to store an instance of the acutal proxy-class. The class will automatically get instantiated.</p>
<p>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&#8217; 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:</p>
<p><pre class="brush: csharp;">
lock (buildLock)
{
	if (!built)
	{
		assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
			new AssemblyName(&quot;NirQ.Proxies&quot;),
			AssemblyBuilderAccess.Run);

		string assemblyName = assemblyBuilder.GetName().Name;

		moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName);
	}
	built = true;
}
</pre></p>
<p>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 &#8220;NirQ.Proxies&#8221; (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&#8217;t able to be created, so before the code above, add the following three lines:</p>
<p><pre class="brush: csharp;">
Type t = typeof(T);
if (!t.IsInterface)
	throw new ArgumentException(&quot;T needs to be an interface&quot;);
</pre></p>
<p>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:</p>
<p><pre class="brush: csharp;">
if (typeCache.Keys.Contains(typeName))
{
	result = typeCache[typeName];
}
else
{
	// Create the class
}
</pre></p>
<p>And now&#8217;s about the time when the fun part starts. Creating a &#8220;on-the-fly&#8221;-class like this is not actually anything that&#8217;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.</p>
<p><pre class="brush: csharp;">
typeBuilder = moduleBuilder.DefineType(
	String.Format(&quot;{0}_NirQ_proxy&quot;, t.Name),
	TypeAttributes.Class | TypeAttributes.Public,
	typeof(Object),
	new Type[] { t });
</pre></p>
<p>This is a hard to crack nut. The DefineType method on the moduleBuilder has several overloads, but the one I&#8217;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 &#8220;_NirQ_proxy&#8221; appended, it&#8217;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).</p>
<p>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 &#8220;string ToString()&#8221;). But before we start implementing the interface itself, lets start with the constructor and the variables we&#8217;ll be using. One thing we want to do in a constructor (I don&#8217;t know if this is required, but I think it&#8217;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:</p>
<p><pre class="brush: csharp;">
Type objType = Type.GetType(&quot;System.Object&quot;);
ConstructorInfo objCtor = objType.GetConstructor(new Type[] { });
</pre></p>
<p>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&#8217;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&#8217;s a single line like this:</p>
<p><pre class="brush: csharp;">
FieldBuilder proxyFieldBuilder = typeBuilder.DefineField(&quot;handler&quot;, typeof(IProxyHandler), FieldAttributes.Private);
</pre></p>
<p>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&#8217;s calling-conventions and the parameters it takes. In this case the function is a instance-method, and has the calling-convention &#8220;CallingConventions.HasThis&#8221;. 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:</p>
<p><pre class="brush: csharp;">
ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(
	MethodAttributes.Public,
	CallingConventions.HasThis, new Type[] { typeof(IProxyHandler) });
</pre></p>
<p>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&#8217;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 &#8220;this&#8221; object. Also, whenever you call a function values are popped and pushed onto the stack, so it&#8217;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:</p>
<p><pre class="brush: csharp;">
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);
</pre></p>
<p>What this code does is: First it loads the &#8220;this&#8221;-object onto the stack. Than it calls the base constructor (Object.Object()), when the constructor is called it pops the &#8220;this&#8221;-object of the stack, and since it&#8217;s a constructor and not a function that returns anything, it doesn&#8217;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&#8217;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).</p>
<p>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:</p>
<p><pre class="brush: csharp;">
MethodInfo callRetMethod = typeof(IProxyHandler).GetMethod(
	&quot;OnMethod&quot;,
	BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
	null,
	new Type[] { typeof(MethodInfo), typeof(object[]) },
	null);
</pre></p>
<p>Ok, lets start looping trough all the methods in the interface; the following is the rest of the code for the else-clause we&#8217;re currently in:</p>
<p><pre class="brush: csharp;">
foreach (MethodInfo mi in t.GetMethods())
{
	// Implement the method
}
result = typeBuilder.CreateType();

typeCache.Add(typeName, result);
</pre></p>
<p>Now, all that&#8217;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&#8217;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&#8217;s done as follows:</p>
<p><pre class="brush: csharp;">
MethodBuilder mb = typeBuilder.DefineMethod(mi.Name,
	MethodAttributes.Public | MethodAttributes.HideBySig |
	MethodAttributes.NewSlot | MethodAttributes.Virtual, mi.ReturnType,
	mi.GetParameters().Select(pi =&gt; pi.ParameterType).ToArray());

int privateParameterCount = mi.GetParameters().Length;

ILGenerator il = mb.GetILGenerator();
</pre></p>
<p>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.</p>
<p>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:</p>
<p><pre class="brush: csharp;">
LocalBuilder argArray = il.DeclareLocal(typeof(object[]));
il.Emit(OpCodes.Ldc_I4, privateParameterCount);
il.Emit(OpCodes.Newarr, typeof(object));
il.Emit(OpCodes.Stloc, argArray);
</pre></p>
<p>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&#8217;t compiled yet). Then we need to call MethodBase.GetMethodFromHandle(RuntimeMethodHandle handle) on the token. The code itself isn&#8217;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.</p>
<p><pre class="brush: csharp;">
LocalBuilder methodInfo = il.DeclareLocal(typeof(MethodInfo));
il.Emit(OpCodes.Ldtoken, mi);
il.Emit(OpCodes.Call, typeof(MethodBase).GetMethod(
	&quot;GetMethodFromHandle&quot;, new Type[] { typeof(RuntimeMethodHandle) }));
il.Emit(OpCodes.Stloc, methodInfo);
</pre></p>
<p>Ok, now that we&#8217;ve created the array and the MethodInfo-object we need to populate the array. This isn&#8217;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&#8217;t work. Every so-called value-type (including int, float, and all structs like DateTime) needs to be &#8220;boxed&#8221; before they can be referenced like an object. This isn&#8217;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&#8217;s required. In other word, if I were to write this function in C# it would look something like this:</p>
<p><pre class="brush: csharp;">
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);
}
</pre></p>
<p>Note here though that box is a fictive function, and that the boxing normally is taken care of by the c#-&gt;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&#8217;s position, and the last item should be the array itself. The whole loop to populate the array looks like this:</p>
<p><pre class="brush: csharp;">
for (int i = 0; i &lt; 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);
}
</pre></p>
<p>The next part is also pretty simple. The first thing you do is load the &#8220;this&#8221;-object (arg_0) onto the stack. Then you use Ldfld to get the proxyFieldBuilder-field (which pops the &#8220;this&#8221;-object and replaces it with the IProxyHandler). Then we load the methodInfo local variable (which is the first parameter of &#8220;OnMethod&#8221;), and we load the argArray (which is the second parameter of &#8220;OnMethod&#8221;). And at last we call &#8220;OnMethod&#8221; 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&#8217;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&#8217;re writing want&#8217;s an int, we have to unbox it first. This is done with Unbox_all. Also, if the function we&#8217;re writing is a void-function we don&#8217;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:</p>
<p><pre class="brush: csharp;">
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 &amp;&amp; mi.ReturnType != typeof(void))
	il.Emit(OpCodes.Unbox_Any, mi.ReturnType);

if (mi.ReturnType == typeof(void))
	il.Emit(OpCodes.Pop);

il.Emit(OpCodes.Ret);
</pre></p>
<p>Now there&#8217;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:</p>
<p><pre class="brush: csharp;">
object o = Activator.CreateInstance(result, new object[] { handler });
obj = (T)o;
</pre></p>
<p>And there you have it. A fully working proxy-generator which you may use in any way that you want to. For example I&#8217;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.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alxen.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alxen.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alxen.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alxen.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alxen.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alxen.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alxen.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alxen.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alxen.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alxen.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alxen.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alxen.wordpress.com/172/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alxen.wordpress.com/172/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alxen.wordpress.com/172/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=172&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.alxandr.me/2010/10/15/creating-a-proxyclass-generator-using-system-reflection-emit/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5a87311ea4c9950793397f01eb208830?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Alxandr</media:title>
		</media:content>
	</item>
		<item>
		<title>Starting to blog again</title>
		<link>http://blog.alxandr.me/2010/10/12/starting-to-blog-again/</link>
		<comments>http://blog.alxandr.me/2010/10/12/starting-to-blog-again/#comments</comments>
		<pubDate>Mon, 11 Oct 2010 23:42:36 +0000</pubDate>
		<dc:creator>Alxandr</dc:creator>
				<category><![CDATA[Thinking out loud]]></category>
		<category><![CDATA[feature]]></category>

		<guid isPermaLink="false">https://alxen.wordpress.com/2010/10/12/starting-to-blog-again/</guid>
		<description><![CDATA[I&#8217;ve never been any good at this blog-thing, but I&#8217;ve always found the idea appealing. I myself reads several blogposts a day whenever there&#8217;s a coding-problem that I don&#8217;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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=169&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve never been any good at this blog-thing, but I&#8217;ve always found the idea appealing. I myself reads several blogposts a day whenever there&#8217;s a coding-problem that I don&#8217;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.</p>
<p>Whenever I find myself in one of those kind of situations I always think when I&#8217;m done &#8220;I should blog about this&#8221;. 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&#8217;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.</p>
<p>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 <img src='http://s2.wp.com/wp-includes/images/smilies/icon_razz.gif' alt=':-P' class='wp-smiley' /> . Later.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/alxen.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/alxen.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/alxen.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/alxen.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/alxen.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/alxen.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/alxen.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/alxen.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/alxen.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/alxen.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/alxen.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/alxen.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/alxen.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/alxen.wordpress.com/169/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.alxandr.me&amp;blog=4405795&amp;post=169&amp;subd=alxen&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.alxandr.me/2010/10/12/starting-to-blog-again/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5a87311ea4c9950793397f01eb208830?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Alxandr</media:title>
		</media:content>
	</item>
	</channel>
</rss>
