<?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</title>
	<atom:link href="http://jonathan.dickinsons.co.za/blog/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>Versatile Distortions in XNA</title>
		<link>http://jonathan.dickinsons.co.za/blog/2011/01/versatile-distortions-in-xna/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2011/01/versatile-distortions-in-xna/#comments</comments>
		<pubDate>Mon, 03 Jan 2011 08:41:53 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=236</guid>
		<description><![CDATA[How to do more versatile distortions in XNA.]]></description>
			<content:encoded><![CDATA[<p><em>Disclaimer: there is a lot of &#8216;missing&#8217; stuff here. For example exactly how one does post-processing. A search on Google will get you what you need to know. Also some of the stuff isn&#8217;t the best, for example I should be using a screen-aligned quad and not a SpriteBatch. Also note that my blog doesn&#8217;t support Math ML math nuts won&#8217;t like my formulas &#8211; still understandable though.</em></p>
<h2>TLDR; Part</h2>
<p>I recently started a game (that I plan to finish for once) that requires distortion effects. I read up about a few implementations on how to do distortions, all of them pretty much handled one type of distortion: radial (i.e explosions/ripple). I needed distortions for heat haze etc.</p>
<p>The usual post-processing stuff is pretty static. Apply a threshold, apply a Gaussian blur, multiply. Notice that this stuff happens against one image. Versatile distortions require 2 images. Firstly you need the entire game as a render target (i.e. Texture2D) as well as the distortion render target. Typically you would use a particle system to fill the distortion render target. I will come back to how I did this a bit later (as it is TLDR; ).</p>
<p>Now here is the crunch. Each color component in the distortion target represents the following:</p>
<ul>
<li><strong>R</strong>: dx: X offset &#8211; f(x)=2x-1 mapping ([0.0f, 1.0f] to [-1.0f, 1.0f]).</li>
<li><strong>G</strong>: dy: Y offset &#8211; f(x)=2x-1 mapping.</li>
<li><strong>B</strong>: m: Z strength &#8211; f(x)=x mapping.</li>
</ul>
<p>The B component is not entirely necessary but it does make creating the textures simpler (because if you use pure black it means no distortion, as R/G only needs grey as 0-offset). The next elegant bit: to determine the final outcome of a wave you simply need to add all of its vector components (in our case dx, dy, m). So if you have two waves you can determine the final outcome as follows:</p>
<pre class="brush: plain">
where dx(x, y, i), dy(x, y, i), m(x, y, i) are the sizes of the vector components in the wave at position x,y for wave i.
where fdx(x, y), fdy(x, y), fm(x, y) are the sizes of the vector components in the final wave at position x,y.
fdx(x, y) = dx(x, y, 0) + dx(x, y, 1) + ... + dx(x, y, n)
fdy(x, y) = dy(x, y, 0) + dy(x, y, 1) + ... + dy(x, y, n)
fm(x, y) = m(x, y, 0) + m(x, y, 1) + ... + m(x, y, n)
</pre>
<p>In other words. Render a particle system to a render target using additive blending. The particles themselves are quite interesting. For example to get the typical ripple effect you would use the following image:</p>
<p><img src="http://jonathan.dickinsons.co.za/blog/wp-content/uploads/2011/01/ripple.png" alt="Ripple Particle" /></p>
<p>I used to a console program to generate that. Basically it pushes out the offset from the center (remember the R/G mapping) into the pixels using the R and G components. The B component is a simple radial gradient. What you would do with this is render it in a particle system where the particle size grows as it gets older; as well as fading (through grey) to black.</p>
<p>As a further example here is an (untested) heat haze particle. Because of the B scaling it is simple to create these in an image editor (black means no distortion):</p>
<p><img src="http://jonathan.dickinsons.co.za/blog/wp-content/uploads/2011/01/Heat.png" alt="Heat Particle" /></p>
<p>Finally this render target needs to be composed with the actual render target. I used the following shader:</p>
<pre class="brush: plain">
Texture InputTexture;
Texture LastTexture;

sampler inputTexture = sampler_state
{
texture = &lt;InputTexture&gt;;
magFilter = POINT;
minFilter = POINT;
mipFilter = POINT;
};

sampler lastTexture = sampler_state
{
texture = &lt;LastTexture&gt;;
magFilter = LINEAR;
minFilter = LINEAR;
mipFilter = LINEAR;
addressU = CLAMP;
addressV = CLAMP;
};

struct VS_OUTPUT
{
float4 Position : POSITION;
float2 TexCoords : TEXCOORD0;
};

float4 Distort (VS_OUTPUT Input)
{
float4 color1;
float4 color2;
float2 coords;
float mul;

coords = Input.TexCoords;
color1 = tex2D(inputTexture, coords);

// 0.1 seems to work nicely.
mul = (color1.b * 0.1);

coords.x += (color1.r * mul) - mul / 2;
coords.y += (color1.g * mul) - mul / 2;

color2 = tex2D(lastTexture, coords);

return color2;
}

float4 RunEffects (VS_OUTPUT Input) : COLOR0
{
float4 color;

color = Distort(Input);

return color;
}

technique Main
{
pass P0
{
PixelShader = compile ps_2_0 RunEffects();
}
}
</pre>
<p>Pretty simple shader, but it has a great effect:</p>
<p><img src="http://jonathan.dickinsons.co.za/blog/wp-content/uploads/2011/01/Ripple-Outcome.png" alt="Ripple Effect" /></p>
<h2>The Required Render System</h2>
<p>In order for this to work you need a slightly more advanced render system. You basically need to be able to:</p>
<ul>
<li>Render a scene/layer/whatever to a temporary render target.</li>
<li>Compose this render target with an underlying render target using a pixel shader (basically provide a &#8216;last composition&#8217; texture to the shader).</li>
</ul>
<p>My layers (I call them RenderContexts) are DrawableGameComponents. Each one contains a RenderTarget2D member that it uses when it renders it&#8217;s children; once a RenderContext has finished rendering it informs the containing game. The Game contains a final RenderTarget (remember changing RenderTargets clears the back buffer) that is used for the final scene. The crunch of the code is:</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Called when a context has been rendered.
/// &lt;/summary&gt;
/// &lt;param name=&quot;context&quot;&gt;The context.&lt;/param&gt;
internal void ContextRendered(RenderingContext context)
{
var renderTarget = CompositingRenderTarget;
var effect = context.CompositingEffect;

if (effect != null)
{
// See if the effect needs the last context rendered.
var param = effect.Parameters[&quot;LastTexture&quot;];
if (param != null)
{
// Store the last render target in a new render target.
// You can&#39;t render to- and read from- a render target in
// the same shader.
GraphicsDevice.SetRenderTarget(EffectRenderTarget);
_compositingSpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque);
_compositingSpriteBatch.Draw(CompositingRenderTarget, new Vector2(0, 0), Color.White);
_compositingSpriteBatch.End();
}
}

GraphicsDevice.SetRenderTarget(CompositingRenderTarget);

if (effect == null)
{
_compositingSpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
}
else
{
// Now we can send the shader the composed image.
var param = effect.Parameters[&quot;LastTexture&quot;];
if (param != null)
{
param.SetValue(EffectRenderTarget);
}
_compositingSpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, effect);
}

// Notice I am using a sprite batch, not the best way to do things
// but better during the prototyping phase.
_compositingSpriteBatch.Draw(context.RenderTarget, new Vector2(0, 0), Color.White);
_compositingSpriteBatch.End();
}
</pre>
<p>Hope that helps you all do some seriously sweet distortions in your game. If there are any obvious omissions feel free to complain.</p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2011/01/versatile-distortions-in-xna/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Expression Blend Visual Studio and Command Line</title>
		<link>http://jonathan.dickinsons.co.za/blog/2010/12/expression-blend-theme/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2010/12/expression-blend-theme/#comments</comments>
		<pubDate>Mon, 20 Dec 2010 14:25:35 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=230</guid>
		<description><![CDATA[Expression Blend-like theme for Visual Studio]]></description>
			<content:encoded><![CDATA[<p>I really enjoy Expression Blend because it&#8217;s so easy on the eyes (dark colors with perfect contrast); I spent a while pulling together all the required themes in order to achieve it.</p>
<h2>Parts</h2>
<ul>
<li><a href="http://visualstudiogallery.msdn.microsoft.com/en-us/20cd93a2-c435-4d00-a797-499f16402378">Visual Studio theme editor</a>.</li>
<li><a href="http://www.nerdpad.com/visual-studio/visual-studio-2010-dark-expression-blend-color-theme">Visual Studio theme</a>.</li>
<li><a href="http://studiostyl.es/schemes/selenitic">Visual Studio syntax theme</a> (not 100% Expression Blend; but fits in nicer than Metroline).</li>
<li><a href="http://jonathan.dickinsons.co.za/blog/wp-content/uploads/2011/02/Metroline-Commandline.txt">My Command-line Console color set. (rename to .reg)</a></li>
</ul>
<h2>Command-line Theme</h2>
<pre class="brush: plain">
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Console]
"ColorTable00"=dword:00333333
"ColorTable01"=dword:00ff8080
"ColorTable02"=dword:0080ff80
"ColorTable03"=dword:00ffff80
"ColorTable04"=dword:008080ff
"ColorTable05"=dword:00ff80ff
"ColorTable06"=dword:0080ffff
"ColorTable07"=dword:00c0c0c0
"ColorTable08"=dword:00808080
"ColorTable09"=dword:00ff8000
"ColorTable10"=dword:0000ff80
"ColorTable11"=dword:00dcff00
"ColorTable12"=dword:008000ff
"ColorTable13"=dword:00dc00ff
"ColorTable14"=dword:0000dcff
"ColorTable15"=dword:00dddddd
"FontFamily"=dword:00000036
"FontSize"=dword:00100000
"FontWeight"=dword:00000190
"PopupColors"=dword:00000001
"ScreenColors"=dword:0000000f
"FaceName"="Consolas"
</pre>
<h2>Preview</h2>
<p>Even though the console is blurred it should give you the general idea of the colors (they are pretty much identitical to the Selenitic ones).</p>
<p><img src="http://jonathan.dickinsons.co.za/blog/wp-content/uploads/2010/12/Theme.png" alt="Screenshot of Visual Studio and Commandline" /></p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2010/12/expression-blend-theme/feed/</wfw:commentRss>
		<slash:comments>2</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>WCF and Windows/Custom Auth</title>
		<link>http://jonathan.dickinsons.co.za/blog/2010/10/wcf-windows-custom-aut/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2010/10/wcf-windows-custom-aut/#comments</comments>
		<pubDate>Thu, 28 Oct 2010 08:25:40 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=212</guid>
		<description><![CDATA[Allowing a WCF web client (hosted in IIS) to send either Windows Authentication or Custom Authentication.]]></description>
			<content:encoded><![CDATA[<p>I was tasked with writing an IIS only WCF service. It was required to bind to SOAP (basicHttpBinding) or to REST (webHttpBinding); furthermore both Windows and Basic (rewritten to authenticate against our server, so it is classed as custom) need to be supported.</p>
<p>Initially the custom module would prevent Windows credentials from being accepted. The browser would enter the login dialog loop with valid credentials. This is because the basic module was eagerly checking the Authorization header. I had to make the following fix:</p>
<pre class="brush: csharp;">protected bool IsHeaderPresent
{
    get
    {
        HttpContext context = HttpContext.Current;
        string authHeader = context.Request.Headers["Authorization"];
        return (!string.IsNullOrEmpty(authHeader))
                 &#038;&#038; authHeader.StartsWith("Basic"); // Added this line.
    }
}</pre>
<p>This property is used in the AuthenticateRequest event handler. What you need to do is short-circuit your entire method, as such:</p>
<pre class="brush: csharp;">void context_AuthenticateRequest(object sender, EventArgs e)
{
    if (IsHeaderPresent)
    {
        // Previous method body
    }
}</pre>
<p>Next you need to enable Windows Authentication in IIS. How you do this depends on which version of IIS you are using; and is trivial. You then need to add it to your web.config:</p>
<pre class="brush: xml;">&lt;system.web&gt;
   &lt;authentication mode="Windows" /&gt;
&lt;/system.web&gt;</pre>
<p>The custom authentication module I read indicated that the following needed to be added to the web.config; if you have something like it remove it:</p>
<pre class="brush: xml;">&lt;serviceAuthorization principalPermissionMode="Custom"&gt;
  &lt;authorizationPolicies&gt;
    &lt;add policyType="X.Services.Authentication.HttpContextIdentityPolicy, X.Services.Runtime" /&gt;
    &lt;add policyType="X.Services.Authentication.HttpContextPrincipalPolicy, X.Services.Runtime" /&gt;
  &lt;/authorizationPolicies&gt;
&lt;/serviceAuthorization&gt;</pre>
<p>Now you just need to look for your custom Identity/Principal; versus the Windows one and react accordingly. Good luck!</p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2010/10/wcf-windows-custom-aut/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WinDBG not Resolving Method Names: Resolution</title>
		<link>http://jonathan.dickinsons.co.za/blog/2010/08/windbg-stack-fix/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2010/08/windbg-stack-fix/#comments</comments>
		<pubDate>Wed, 25 Aug 2010 08:50:42 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=205</guid>
		<description><![CDATA[How to fix stack traces that only contain HelperMethodFrame and GCFrame when using SOS.dll.]]></description>
			<content:encoded><![CDATA[<p>Over the past few months my process for determining the cause for crashes has been the same: open the dump, load SOS, load SOSEX and run <code>!pe</code>. This has always had the same result:</p>
<pre class="brush: plain;">0:019&gt; !pe
PDB symbol for mscorwks.dll not loaded
Exception object: 029e87f4
Exception type: System.ArgumentNullException
Message: Value cannot be null.
InnerException:
StackTrace (generated):
    SP       IP       Function

StackTraceString:
HResult: 80004003
There are nested exceptions on this thread. Run with -nested for details</pre>
<p>As has the output of <code>!clrstack</code>:</p>
<pre class="brush: plain;">0:019&gt; !clrstack
OS Thread Id: 0x5d0 (19)
ESP       EIP
0f31f340 7c80bef7 [HelperMethodFrame_1OBJ: 0f31f340]
0f31f398 1449167a
0f31f3c4 144915e6
0f31f3f4 10d81b48
0f31f4b4 793e25cf
0f31f4bc 79366b3d
0f31f4d4 793e2734
0f31f4e8 793e26ac
0f31f678 79e7c0e3 [GCFrame: 0f31f678]</pre>
<p>This invariably leads to me closing WinDBG and start manually trying to determine what is going wrong without it. The reason? Microsoft needs to rethink documentation around WinDBG, SOS, and MSCORDACWKS. According to them all you need is the correct version of MSCORDACWKS; that will get you as far as the above.</p>
<h2>Getting a Memory Dump From Your Customer</h2>
<p>After using whichever method you suggest (e.g. ADPlus) they will <strong>also</strong> need to do this:</p>
<ol>
<li>Navigate to <em>%WINDIR%\Microsoft.NET\Framework\v2.0.50727</em>
<ol>
<li>Copy SOS.DLL</li>
<li>Copy MSCORDACWKS.DLL</li>
</ol>
</li>
<li>If 64bit Navigate to <em>%WINDIR%\Microsoft.NET\Framework64\v2.0.50727</em>
<ol>
<li>Copy SOS.DLL</li>
<li>Copy MSCORDACWKS.DLL</li>
</ol>
</li>
<li>If they you are optionally or additionally using .Net 4.0 they will need to do steps 1 and 2 for \v4.0.30319.</li>
</ol>
<p>You will need those files individually; and keep them along-side the memory dump.</p>
<h2>Setting Up Your Environment</h2>
<p>You are going to need a local symbols directory (we have a file share on a server). WinDBG is rather unforgiving when it comes to the MSCORDACWKS search (e.g. having MSCORDACWKS in the same directory as the memory dump doesn&#8217;t work); so you have to put their MSCORDACWKS in your symbol store.</p>
<h2>Determining where to store MSCORDACWKS</h2>
<p>FYI: I have been able to get this DLL from the Microsoft Symbol Servers; so you should probably try this first:</p>
<pre class="brush: plain;">
.sympath srv*http://msdl.microsoft.com/download/symbols;cache*D:\symbols
.reload
</pre>
<p>Otherwise, there is a way to determine this; but using WinDBG to figure out the path is more reliable:</p>
<pre class="brush: plain;">
0:019> !sym noisy
noisy mode - symbol prompts on
0:019> .sympath+ D:\symbols
DBGHELP: Symbol Search Path: d:\symbols
DBGHELP: Symbol Search Path: d:\symbols
Symbol search path is: D:\symbols
Expanded Symbol search path is: d:\symbols
0:019> !loadby sos mscorwks
0:019> .cordll -ve -u -l
CLR DLL status: No load attempts
0:019> !threads
PDB symbol for mscorwks.dll not loaded
...
SYMSRV:  d:\symbols\mscordacwks_x86_x86_2.0.50727.1873.dll\4A7D131D59b000\mscordacwks_x86_x86_2.0.50727.1873.dll not found
...
</pre>
<p>That SYMSRV line is your answer. Create the directory, rename the file and copy the file there.</p>
<h2>Loading up SOS.DLL</h2>
<p>First we should undo the noisy symbol prompts:</p>
<pre class="brush: plain;">
0:019> !sym quiet
quiet mode - symbol prompts on
</pre>
<p>We can then load up the correct version of SOS:</p>
<pre class="brush: plain;">
0:019> !load D:\Dump Files\2010-01-01\x86\v2.0\SOS.dll
</pre>
<p>And now we can get stack traces:</p>
<pre class="brush: plain;">
0:019> !clrstack
OS Thread Id: 0x5d0 (19)
ESP       EIP
0f31f340 7c80bef7 [HelperMethodFrame_1OBJ: 0f31f340] System.Threading.Monitor.Enter(System.Object)
0f31f398 1449167a SourceCode.**
0f31f3c4 144915e6 SourceCode.**
0f31f3f4 10d81b48 K2Worker.**
0f31f4b4 793e25cf System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(System.Object)
0f31f4bc 79366b3d System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
0f31f4d4 793e2734 System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(System.Threading._ThreadPoolWaitCallback)
0f31f4e8 793e26ac System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(System.Object)
0f31f678 79e7c0e3 [GCFrame: 0f31f678]
</pre>
<p>Good luck and happy debugging!</p>
<p><strong>Update:</strong> According to Tess Ferrandez of WinDBG fame the new SOS (called PSSCOR2.DLL) used by the employees at Microsoft will also fix this. Read about it more over at her <a href="http://blogs.msdn.com/b/tess/archive/2010/03/30/new-debugger-extension-for-net-psscor2.aspx">blog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2010/08/windbg-stack-fix/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Android: Emulator Can&#8217;t Find Images</title>
		<link>http://jonathan.dickinsons.co.za/blog/2010/06/android-emulator-cant-find-images/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2010/06/android-emulator-cant-find-images/#comments</comments>
		<pubDate>Sun, 06 Jun 2010 11:07:31 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Top Hacks]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=201</guid>
		<description><![CDATA[Fix the 'could not find virtual device named' error with Android Emulator.]]></description>
			<content:encoded><![CDATA[<p>If you are getting an error message from the Android emulator similar to:</p>
<pre class="brush: plain;">
emulator: ERROR: unknown virtual device name: 'xxx'
emulator: could not find virtual device named 'xxx'
</pre>
<p>It&#8217;s because the Android emulator works a little differently from the rest of the SDK (the rest of the SDK is Java, emulator.exe is C/++). The rest of the SDK behaves correctly in terms of user home folder (I move mine to a different hard disk) and emulator.exe has it hardcoded (depending on your OS). In Windows 7 and Vista that means it ALWAYS looks in &#8220;C:\Users\&lt;username&gt;\.android&#8221;. The fix for this is simple (in a command prompt under Vista/Win7):</p>
<pre class="brush: plain;">
C:
cd C:\Users\&lt;user name&gt;
mklink /j .android &lt;new home directory&gt;\.android
</pre>
<p>Worked for me. Source: <a href="http://forum.xda-developers.com/showpost.php?p=5612951&#038;postcount=12">XDA Developers</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2010/06/android-emulator-cant-find-images/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Virtual Machine Installation Checklist</title>
		<link>http://jonathan.dickinsons.co.za/blog/2010/02/virtual-machine-installation-checklist/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2010/02/virtual-machine-installation-checklist/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 13:39:28 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[Virtualization]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=191</guid>
		<description><![CDATA[Todo list when making new virtual machines.]]></description>
			<content:encoded><![CDATA[<p>A quick checklist. Mostly just for me.</p>
<ol>
<li>Install guest.</li>
<li>Create descriptive wallpaper (root chain).</li>
<li>Install guest tools.</li>
<li>Change WSUS server.</li>
<li>Update Windows.</li>
<li>Bootstrap Internet Explorer.</li>
<li>Install Clamwin.</li>
<li>Update Clamwin.</li>
<li><a href="http://stackoverflow.com/questions/200635/how-to-change-registration-company-name-for-visual-studio-2008" target="_blank">Change registered company to my company.</a> Remember WOW64 node.</li>
<li>Disable netlogon machine password change.
<pre class="brush: plain;">HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Netlogon\Parameters\DisablePasswordChange = 1</pre>
</li>
<li>Disable shutdown event tracker.</li>
<li>(Snapshot)</li>
<li>Create descriptive wallpaper (development chain).</li>
<li>Join domain.</li>
<li>Install .Net Framework 3.51.</li>
<li>Install IIS.</li>
<li>Install MSMQ AD Integration.</li>
<li>Install Visual Studio.</li>
<li>Install TFS Client.</li>
<li>Install Visual Studio SP1.</li>
<li>Install SQL Server.</li>
<li>Install SQL Server SP1.</li>
<li><a href="http://social.technet.microsoft.com/Forums/en/operationsmanagerdeployment/thread/53fa9a6b-b9db-473f-8564-2ac4c62c3365" target="_blank">Configure SQL Firewall Ports.</a></li>
<li>Enable SQL Server TCP/IP.</li>
<li>Install GhostDoc.</li>
<li>Install CodeRush.</li>
<li>Install Coco/R.</li>
<li>Install Tytan.</li>
<li>Update Windows.</li>
<li>Bootstrap VS.</li>
<li>Apply VS customizations.
<ol>
<li>Import settings.</li>
<li>Set up TFS working folder.</li>
<li>Set up GhostDoc to use langword.</li>
</ol>
</li>
<li>Bootstrap SMS.</li>
<li>Create link to K2 keygen.</li>
<li>(Snapshot)</li>
<li>Justice.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2010/02/virtual-machine-installation-checklist/feed/</wfw:commentRss>
		<slash:comments>2</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>
		<item>
		<title>Code Block Toggler</title>
		<link>http://jonathan.dickinsons.co.za/blog/2009/12/code-block-toggler/</link>
		<comments>http://jonathan.dickinsons.co.za/blog/2009/12/code-block-toggler/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 22:42:34 +0000</pubDate>
		<dc:creator>Jonathan Dickinson</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Top Hacks]]></category>
		<category><![CDATA[Tricks]]></category>

		<guid isPermaLink="false">http://jonathan.dickinsons.co.za/blog/?p=171</guid>
		<description><![CDATA[Handy snippet to switch between two code blocks.]]></description>
			<content:encoded><![CDATA[<p>I came across one of the most awesome meta-language features for C-style languages (specifically any language that has /* */ and // comment support). The nitty-gritties are up at <a href="http://theycallmemrjames.blogspot.com/2009/06/toggle-between-code-blocks.html">a rather good blog</a>. I whipped up a snippet to handle this automatically.</p>
<p>It has a few notable features &#8211; it gives a reason for the flip, it wraps it in a region, it has a auto-task FLIP: prefix and it explains how it&#8217;s used.</p>
<pre class="brush: csharp;">
            #region Flip - This new behaviour is experimental. -
            // FLIP: This new behaviour is experimental.
            //*/// Two proceding slashes will activate the first block, one will activate the second.
            Console.ReadLine();
            /*/
            Console.ReadLine();
            //*/
            #endregion Flip - This new behaviour is experimental. -
</pre>
<p>Drop it in your My Code Snippets folder. In VS select the code you want to flip-comment, Hold CTRL, Press K, Press S, Release CTRL, Press M, Press Enter, Press F, Press Enter (I wish you could assign hot keys to snippets!).</p>
<p><a href='http://jonathan.dickinsons.co.za/blog/wp-content/uploads/2009/12/flipper.txt'>Code Block Flipper</a> (WordPress won&#8217;t let me upload .snippet &#8211; so you will need to rename it)</p>
]]></content:encoded>
			<wfw:commentRss>http://jonathan.dickinsons.co.za/blog/2009/12/code-block-toggler/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

