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

<channel>
	<title>Jonathan C Dickinson &#187; Best Practices</title>
	<atom:link href="http://jonathan.dickinsons.co.za/blog/category/programming/best-practices/feed/" rel="self" type="application/rss+xml" />
	<link>http://jonathan.dickinsons.co.za/blog</link>
	<description>&#34;Jonathan Chayce Dickinson&#34;.ToString()</description>
	<lastBuildDate>Sat, 26 Feb 2011 14:21:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>.Net Sockets and You</title>
		<link>http://jonathan.dickinsons.co.za/blog/2011/02/net-sockets-and-you/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2011/02/net-sockets-and-you/#comments</comments>
		<pubDate>Sat, 26 Feb 2011 14:21:08 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Networking]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=250</guid>
		<description><![CDATA[Writing a socket server in .Net is one of the most rewarding things you can do in .Net. Unfortunately at the same time there is a lot of pre-requisite knowledge &#8211; and the knowledge isn&#8217;t easy to find online (in fact it is very easy to examples and tutorials that are blatantly wrong). After reading [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://jonathan.dickinsons.co.za/blog/wp-content/uploads/2011/02/IBM-Server-300x192.png" alt="" title="IBM Server" width="300" height="192" class="alignleft size-medium wp-image-251" />Writing a socket server in .Net is one of the most rewarding things you can do in .Net. Unfortunately at the same time there is a lot of pre-requisite knowledge &#8211; and the knowledge isn&#8217;t easy to find online (in fact it is very easy to examples and tutorials that are blatantly wrong).</p>
<p>After reading this you should know enough to write a pretty good socket server; and hopefully where to start looking when bad things happen. This post is written progressively, meaning I may use certain bad practices in the first few sections. <strong><em>Don&#8217;t just go and copy and paste</em></strong> &#8211; make sure you read the whole thing.</p>
<h1>IOCP (I/O Completion Ports)</h1>
<p>IOCP is probably the most important part of a socket server. If you have ever heard of the Berkely socket pattern; this is the exact opposite. Berkely relies on a tight loop that queries each socket asking it if it has any data ready; it doesn&#8217;t scale. Another often-used (and incorrect) pattern is the multi-threaded Berkely socket pattern. Instead of a single tight loop querying each socket, the server assigns a thread-per-client. While in theory this is a good idea; realise that spinning up 1000 tight loops is going to bring your server to a screeching halt very quickly.</p>
<p>So what is IOCP? Put simply; it&#8217;s a way for a program to say to the kernel &#8220;Hey, I am in charge of these streams. When data arrives on ANY of them please resume this thread I have created for you.&#8221; The .Net BCL team took IOCP a step further and shield developers from having to manage that thread. Using IOCP in .Net is as easy as implementing your server using the <a href="http://msdn.microsoft.com/en-us/library/aa719595(v=vs.71).aspx">Begin/End async pattern</a>. Using this pattern is quite simple:</p>
<ol>
<li>Create your own Begin* method (as a bad example, BeginReceive).</li>
<li>Create a stub for the End* method. This method should accept a single IAsyncResult as a parameter.</li>
<li>In your Begin* method, call socket.Begin* passing your End* as a delegate parameter.</li>
<li>In your End* method, call socket.End* passing the IAsyncResult you got as a parameter.
 </li>
<li>Then call your Begin* method.
</li>
</ol>
<p>This sets up an async loop; there is a shorter form of this loop (designed for DRY error handling) &#8211; which looks like this:</p>
<p><script src="https://gist.github.com/845181.js"> </script></p>
<p>Note that you should use the async pattern for everything: Accept, Receive, Send, Connect. As a side-note &#8211; using BeginSend with a null callback is fine (fire and forget); but it will play havoc with the socket performace counters for your process. You may also want to set <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.useonlyoverlappedio.aspx">UseOnlyOverlappedIO</a> to true.</p>
<p>I also suggest you look at <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896">Reactive Extensions</a>; as one of the things it deals with is the async pattern.</p>
<h1>Use Streams</h1>
<p>Don&#8217;t use the built-in Receive and Send methods, construct a NetworkStream over the socket. This is important because it allows you wrap your socket in a <a href="http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx">SslStream</a> or <a href="http://msdn.microsoft.com/en-us/library/system.io.compression.deflatestream.aspx">DeflateStream</a> (side note: always wrap the data in compression BEFORE encryption).</p>
<p><script src="https://gist.github.com/845206.js"> </script></p>
<p>Side note: DeflateStream was implemented in a really strange way (the existence of the CompressionMode parameter). You are typically going to write a Stream that uses one DeflateStream (in CompressionMode.Compress) to write and another (in CompressionMode.Decompress) to read.</p>
<h1>The Evils of Pinning</h1>
<p>The Microsoft CLR uses P/Invoke to provision sockets. A side-effect of P/Invoke is that any reference types (and a Byte Array a.k.a buffer is a reference type) that you pass as parameters are pinned for the duration of the call. Pinning is a process whereby the Garbage Collector is informed that it should not move an object around (the garbage collector moves objects around to ensure that large continuous areas of free space are available). What this means is that if you pass a new buffer to each Send/Receive call you will wind up with a lot of pinned objects, which can lead to fragmentation. There have been stories of processes getting so fragmented that a process using 800MB of memory and 1.2GB of free memory throwing an OutOfMemoryException (because it could not find a large enough space to allocate an object). Remember that an OutOfMemoryException kills your .Net process without ever calling any catch blocks &#8211; not good. To further compound the problem, TCP has this problem where it can go into a black-hole state &#8211; this means that even though the connection was lost; the operating system (and your process) think it&#8217;s still there. A black-hole can last for as long as 15 minutes in certain worst-case scenarios.</p>
<p>The way to get around this is to pre-allocate large blocks of memory for buffers. <a href="http://msdn.microsoft.com/en-us/library/1hsbd92d(v=vs.80).aspx">ArraySegment</a> is a good way to get handles on &#8216;sub-arrays&#8217;. Here is an effective buffer pool to get you started:</p>
<p><script src="https://gist.github.com/845212.js"> </script></p>
<p>Note that you can also use <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.buffermanager.aspx">BufferManager</a> (which doesn&#8217;t support ArraySegment).</p>
<p>Unfortunately this one is actually really hard to get 100% right in the scenario where you do use SslStream and DeflateStream. These two streams allocate their own buffers; which means even if you do write to the &#8220;targetStream&#8221; using pooled buffers, unpooled buffers will still be sent to the underlying socket. There is no easy way to put this, if you do run into this scenario you are going to land up writing quite a bit of code (subclassing Stream; placed directly above your NetworkStream) that swaps out the buffers passed to it for pooled buffers (keeping in mind you need to do this async). <em>I have some code that does this, but it is tied into some pretty proprietary stuff at the moment, so I have to isolate it before posting.</em> If you go down this route just remember to use <a href="http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx">Buffer.BlockCopy</a> and not ArrayCopy as Buffer.BlockCopy is blindingly fast compared to the former (IIRC it uses DMA).</p>
<p>There are also two ways to manage these pooled buffers. If your server behaves in a streaming fashion (which is probably the case) you will want to experiment with allocating a buffer to each client; instead of a buffer to each Read/Write call. Whether this will work out better or not depends on the nature of your server.</p>
<h1>DOS</h1>
<p>Denial-Of-Service (not that I didn&#8217;t mention DDOS; pretty-much the only way to deal with that is horizontal scaling) is one you need to look out for. DOS is really simple to pull off if you don&#8217;t protect yourself against it. It merely comes down to asking &#8220;why is this client connected to me?&#8221;, &#8220;can I handle this much data?&#8221; and for the love of God staying away from byte arrays (except for, obviously, at the socket level). For instance, what is a client doing connected to you if it has not authenticated itself in 30 seconds? Why is this client sending you 200MB of data? Can the data be written to disk instead?</p>
<h1>PUSH Parsing</h1>
<p>Make sure that your server can PUSH parse. One form of DOS is to send a really big (but valid) packet. Naive servers will build up a large buffer in memory to attempt to store this packet before parsing it. Don&#8217;t do this, instead parse the bytes as you get them. For instance instead of using a StreamReader look at the following:</p>
<p><script src="https://gist.github.com/845231.js"> </script></p>
<p>If you need to build up the packet before parsing it (say it&#8217;s XML and you don&#8217;t want to write/test your own PUSH parser) rather write it to a temporary file.</p>
<h1>Hope This Helps</h1>
<p>If you can think of anything I should add or correct please let me know in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2011/02/net-sockets-and-you/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Cross-AppDomain Singleton in C#</title>
		<link>http://jonathan.dickinsons.co.za/blog/2010/11/cross-domain-singleton-in-c/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2010/11/cross-domain-singleton-in-c/#comments</comments>
		<pubDate>Tue, 02 Nov 2010 11:12:03 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tricks]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=217</guid>
		<description><![CDATA[How create a cross-AppDomain singleton in C# without using interop calls to the runtime.]]></description>
			<content:encoded><![CDATA[<h2>Scenario</h2>
<p>I have a logging system that contains one or more loggers. These logger should NOT be initialized (or ever constructed) for child domains; this is a problem because each AppDomain in .Net recieves it&#8217;s own static instances.</p>
<h2>Typical Solution</h2>
<p>Most people resort to the MSCOREE library and enumerate all the current AppDomains to find the primary AppDomain. After that they can retrieve the singleton instance from within the primary AppDomain.</p>
<p>This has it&#8217;s problems, most notably interop ties you to an architecture and requires certain CAS policies. Furthermore, I just don&#8217;t like too much interop.</p>
<h2>My Solution</h2>
<p>My solution involves creating a custom AppDomainManager that is aware of the primary AppDomain. The principle is that the AppDomainManager creates a new AppDomain for primary execution. This new domain uses the custom AppDomainManager (which can then control the creation of child domains; and therefore wire itself into them). The code is self-explanatory (hopefully):</p>
<pre class="brush: csharp;">    /// &lt;summary&gt;
    /// Represents a &lt;see cref=&quot;AppDomainManager&quot;/&gt; that is
    /// aware of the primary application AppDomain.
    /// &lt;/summary&gt;
    public class PrimaryAppDomainManager : AppDomainManager
    {
        private static AppDomain _primaryDomain;

        /// &lt;summary&gt;
        /// Gets the primary domain.
        /// &lt;/summary&gt;
        /// &lt;value&gt;The primary domain.&lt;/value&gt;
        public static AppDomain PrimaryDomain
        {
            get
            {
                return _primaryDomain;
            }
        }

        /// &lt;summary&gt;
        /// Sets the primary domain.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;primaryDomain&quot;&gt;The primary domain.&lt;/param&gt;
        private void SetPrimaryDomain(AppDomain primaryDomain)
        {
            _primaryDomain = primaryDomain;
        }

        /// &lt;summary&gt;
        /// Sets the primary domain to self.
        /// &lt;/summary&gt;
        private void SetPrimaryDomainToSelf()
        {
            _primaryDomain = AppDomain.CurrentDomain;
        }

        /// &lt;summary&gt;
        /// Determines whether this is the primary domain.
        /// &lt;/summary&gt;
        /// &lt;value&gt;
        /// 	&lt;see langword=&quot;true&quot;/&gt; if this instance is the primary domain; otherwise, &lt;see langword=&quot;false&quot;/&gt;.
        /// &lt;/value&gt;
        public static bool IsPrimaryDomain
        {
            get
            {
                return _primaryDomain == AppDomain.CurrentDomain;
            }
        }

        /// &lt;summary&gt;
        /// Creates the initial domain.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;friendlyName&quot;&gt;Name of the friendly.&lt;/param&gt;
        /// &lt;param name=&quot;securityInfo&quot;&gt;The security info.&lt;/param&gt;
        /// &lt;param name=&quot;appDomainInfo&quot;&gt;The AppDomain setup info.&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public static AppDomain CreateInitialDomain(string friendlyName, Evidence securityInfo, AppDomainSetup appDomainInfo)
        {
            if (AppDomain.CurrentDomain.DomainManager is PrimaryAppDomainManager)
                return null;

            appDomainInfo = appDomainInfo ?? new AppDomainSetup();
            appDomainInfo.AppDomainManagerAssembly = typeof(PrimaryAppDomainManager).Assembly.FullName;
            appDomainInfo.AppDomainManagerType = typeof(PrimaryAppDomainManager).FullName;

            var appDomain = AppDomainManager.CreateDomainHelper(friendlyName, securityInfo, appDomainInfo);
            ((PrimaryAppDomainManager)appDomain.DomainManager).SetPrimaryDomainToSelf();
            _primaryDomain = appDomain;
            return appDomain;
        }

        /// &lt;summary&gt;
        /// Returns a new or existing application domain.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;friendlyName&quot;&gt;The friendly name of the domain.&lt;/param&gt;
        /// &lt;param name=&quot;securityInfo&quot;&gt;An object that contains evidence mapped through the security policy to establish a top-of-stack permission set.&lt;/param&gt;
        /// &lt;param name=&quot;appDomainInfo&quot;&gt;An object that contains application domain initialization information.&lt;/param&gt;
        /// &lt;returns&gt;A new or existing application domain.&lt;/returns&gt;
        /// &lt;PermissionSet&gt;
        /// 	&lt;IPermission class=&quot;System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&quot; version=&quot;1&quot; Flags=&quot;ControlEvidence, ControlAppDomain, Infrastructure&quot;/&gt;
        /// &lt;/PermissionSet&gt;
        public override AppDomain CreateDomain(string friendlyName, Evidence securityInfo, AppDomainSetup appDomainInfo)
        {
            appDomainInfo = appDomainInfo ?? new AppDomainSetup();
            appDomainInfo.AppDomainManagerAssembly = typeof(PrimaryAppDomainManager).Assembly.FullName;
            appDomainInfo.AppDomainManagerType = typeof(PrimaryAppDomainManager).FullName;

            var appDomain = base.CreateDomain(friendlyName, securityInfo, appDomainInfo);
            ((PrimaryAppDomainManager)appDomain.DomainManager).SetPrimaryDomain(_primaryDomain);

            return appDomain;
        }
    }</pre>
<p>Note that it isn&#8217;t possible to use the &#8216;real&#8217; primary domain for anything; otherwise any domains created by it would be outside of the control of PrimaryAppDomainManager. Using this we can implement cross-domain thread-safe singleton class:</p>
<pre class="brush: csharp;">    /// &lt;summary&gt;
    /// Represents a cross-domain singleton.
    /// &lt;/summary&gt;
    /// &lt;remarks&gt;
    /// The singleton always lives in the primary domain.
    /// &lt;/remarks&gt;
    public abstract class CrossDomainSingleton&lt;TSelf&gt; : MarshalByRefObject
        where TSelf : CrossDomainSingleton&lt;TSelf&gt;, new()
    {
        // Used to alter the primary domain
        // in a thread safe-manner.
        private class Locker : MarshalByRefObject
        {
            private static object _lock = new object();
            public void Lock()
            {
                Monitor.Enter(_lock);
            }

            public void Exit()
            {
                Monitor.Exit(_lock);
            }

            public TSelf GetSelf()
            {
                // At this point we always have a lock;
                // just check that the instance is still null.
                if (_instance == null)
                {
                    _instance = new TSelf();
                }
                return _instance;
            }
        }

        private static TSelf _instance;
        /// &lt;summary&gt;
        /// Gets the instance.
        /// &lt;/summary&gt;
        /// &lt;value&gt;The instance.&lt;/value&gt;
        public static TSelf Instance
        {
            get
            {
                Contract.Ensures(Contract.Result&lt;TSelf&gt;() != null);
                if (_instance == null)
                {
                    SetInstance();
                }
                return _instance;
            }
        }

        private static void SetInstance()
        {
            Locker locker;
            if (PrimaryAppDomainManager.IsPrimaryDomain)
            {
                // No need for the remoting.
                locker = new Locker();
            }
            else
            {
                // Get the primary domain locker.
                locker = PrimaryAppDomainManager.PrimaryDomain.CreateInstanceAndUnwrap&lt;Locker&gt;();
            }

            try
            {
                locker.Lock();
                _instance = locker.GetSelf();
            }
            finally
            {
                locker.Exit();
            }
        }
    }</pre>
<p>You will need the following extension method somewhere:</p>
<pre class="brush: csharp;">/// &lt;summary&gt;
/// Creates a new instance of the specified type.
/// &lt;/summary&gt;
/// &lt;typeparam name=&quot;T&quot;&gt;The type of object to create.&lt;/typeparam&gt;
/// &lt;param name=&quot;appDomain&quot;&gt;The app domain.&lt;/param&gt;
/// &lt;returns&gt;A proxy for the new object.&lt;/returns&gt;
public static T CreateInstanceAndUnwrap&lt;T&gt;(this AppDomain appDomain)
{
    Contract.Requires&lt;ArgumentNullException&gt;(appDomain != null);
    Contract.Ensures(Contract.Result&lt;T&gt;() != null);

    var res = (T)appDomain.CreateInstanceAndUnwrap(typeof(T));
    return res;
}</pre>
<p>In order for all of this to work you need to make sure that your &#8216;real&#8217; primary domain is never used:</p>
<pre class="brush: csharp;">    class Program : MarshalByRefObject
    {
        /// &lt;summary&gt;
        /// The main entry point for the application.
        /// &lt;/summary&gt;
        static void Main(string[] args)
        {
            new Program().Run(args);
        }

        void Run(string[] args)
        {
            var domain = PrimaryAppDomainManager.CreateInitialDomain(&quot;PrimaryDomain&quot;, null, null);
            if (domain == null)
            {
                // Original Main() code here.
            }
            else
            {
                domain.CreateInstanceAndUnwrap&lt;Program&gt;().Run(args);
            }
        }
    }</pre>
<p>And the singleton classes are simple (thanks to the generic-TSelf trick; which I need to do a post on some time):</p>
<pre class="brush: csharp;">    class Foo : CrossDomainSingleton&lt;Foo&gt;
    {
        public Foo()
        {
            // Singleton initializer.
        }
    }</pre>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2010/11/cross-domain-singleton-in-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Code Contracts</title>
		<link>http://jonathan.dickinsons.co.za/blog/2010/01/code-contracts/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2010/01/code-contracts/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 20:38:34 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Short]]></category>
		<category><![CDATA[XMPP Server 2010]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=179</guid>
		<description><![CDATA[I recently started using CodeContracts and have a few tips.]]></description>
			<content:encoded><![CDATA[<p>I have recently started using the <a href="http://research.microsoft.com/en-us/projects/contracts/">Microsoft CodeContracts</a> on a large scale. These have been a fantastic addition to my toolset; because when I get the green flag on my code I know that I am <em>pretty</em> safe (it is beta, after all). I had to migrate quite a bit of code into the contracts and found that it can be quite a daunting task. A few things that I have picked up are:</p>
<ul>
<li>If you are migrating existing code and worrying only about contracts, switch off background checking. Firstly, this means that the results you get are comprehensive and secondly because of the build time you will think twice about hitting that build key again. Long builds == fewer builds == more time thinking == better code.</li>
<li>Use code snippets. The ones provided by Microsoft are great! Think about creating your own or changing them. For example cren and cresn no longer throw ArgumentExceptions for me; they are both ArgumentNullExceptions. I also have snippets like create contract class for (cc &#8211; scaffolding for ContractClassFor) and contract class implementation (cci &#8211; ContractClass attributation).</li>
<li>Invariants are your friend. Figure out what state a class should really be in and depend on that rather than Contract.Requires everywhere.</li>
<li>A well placed Contract.Ensures will save you a lot of grief.</li>
<li>Don&#8217;t loose hope. It may seem like it&#8217;s daunting at first &#8211; but as you start thinking in terms of contracts things become a lot faster. A single well-thought out Contract call will often clear off 5 warnings (for the bigger projects).</li>
<li>Some classes can be skipped ([ContractVerification(false)]) &#8211; especially if they are internal. Don&#8217;t gung-ho and try and get everything in contracts; because sometimes they may be ill-suited for the task (and you would by &#8216;lying&#8217; just to get the stuff to pass). These situations are few and far between; but they are there.</li>
<li>New development = contracts. Full stop.</li>
</ul>
<p>Overall I am finding fewer and fewer Contract failures during each build. This is mainly because CodeContracts is getting me into a better and more disciplined mindset. It&#8217;s a great tool and I highly recommend it.</p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2010/01/code-contracts/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

