<?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>Sorted Bits &#187; C#</title>
	<atom:link href="http://www.sortedbits.com/category/coding/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sortedbits.com</link>
	<description>objectiveC, C# and more interesting stuff</description>
	<lastBuildDate>Wed, 04 Jan 2012 10:11:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>string extension methods for C#</title>
		<link>http://www.sortedbits.com/string-extension-methods-for-c/</link>
		<comments>http://www.sortedbits.com/string-extension-methods-for-c/#comments</comments>
		<pubDate>Tue, 04 Oct 2011 15:07:46 +0000</pubDate>
		<dc:creator>Wim</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Snippets]]></category>

		<guid isPermaLink="false">http://www.wim.me/?p=1386</guid>
		<description><![CDATA[I admit, I have a big passion for writing useful extension methods in C#. I love how easy they make my job and keep me from writing code over and over again. There are some methods I use regularly and most of them apply to the string [...]]]></description>
			<content:encoded><![CDATA[<p>I admit, I have a big passion for writing useful extension methods in C#. I love how easy they make my job and keep me from writing code over and over again.</p>
<p>There are some methods I use regularly and most of them apply to the string class. So without further ado, here are some of my favorites.</p>
<p><strong>Validating</strong></p>
<div id="gist-1302057" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">public</span> <span class="k">static</span> <span class="kt">bool</span> <span class="nf">IsInt</span><span class="p">(</span><span class="k">this</span> <span class="kt">string</span> <span class="n">text</span><span class="p">)</span></div><div class='line' id='LC2'><span class="p">{</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">int</span> <span class="n">integer</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="n">Int32</span><span class="p">.</span><span class="n">TryParse</span><span class="p">(</span><span class="n">text</span><span class="p">, autoload = </span> <span class="k">out</span> <span class="n">integer</span><span class="p">);</span></div><div class='line' id='LC5'><span class="p">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1302057/adcdf50c97766dec972e2f43b3176acc82e8cf40/gistfile1.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1302057#file_gistfile1.cs" style="float:right;margin-right:10px;color:#666">gistfile1.cs</a>
            <a href="https://gist.github.com/1302057">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Of course you can create methods like this for all kind of types to support. This one just shows an example for the Int32 type. This way I can easily check if variables are correct. It is too bad that you can&#8217;t just parse the variable into the void so an extra variable is needed.</p>
<p>One other is an extension to make a valid filename from a string, like this:</p>
<div id="gist-1302069" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">static</span> <span class="k">public</span> <span class="kt">string</span> <span class="nf">ToValidFileName</span><span class="p">(</span><span class="k">this</span> <span class="kt">string</span> <span class="n">name</span><span class="p">)</span></div><div class='line' id='LC2'><span class="p">{</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">string</span> <span class="n">invalidChars</span> <span class="p">=</span> <span class="n">Regex</span><span class="p">.</span><span class="n">Escape</span><span class="p">(</span><span class="k">new</span> <span class="kt">string</span><span class="p">(</span><span class="n">Path</span><span class="p">.</span><span class="n">GetInvalidFileNameChars</span><span class="p">()));</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">string</span> <span class="n">invalidReStr</span> <span class="p">=</span> <span class="kt">string</span><span class="p">.</span><span class="n">Format</span><span class="p">(</span><span class="s">@&quot;[{0}]+&quot;</span><span class="p">,</span> <span class="n">invalidChars</span><span class="p">);</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="n">Regex</span><span class="p">.</span><span class="n">Replace</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">invalidReStr</span><span class="p">,</span> <span class="s">&quot;_&quot;</span><span class="p">);</span></div><div class='line' id='LC6'><span class="p">}</span> </div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1302069/1b5ac77226be4d7acc7fcb8ff633592280a88e68/gistfile1.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1302069#file_gistfile1.cs" style="float:right;margin-right:10px;color:#666">gistfile1.cs</a>
            <a href="https://gist.github.com/1302069">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p><strong>Hashing</strong><br />
There are several reasons to hash a string, I personally use it to store passwords. Nowadays I use SHA1 hashing because MD5 is not that secure.</p>
<div id="gist-1302074" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">public</span> <span class="k">static</span> <span class="kt">string</span> <span class="nf">ToSHA1</span><span class="p">(</span><span class="k">this</span> <span class="kt">string</span> <span class="n">text</span><span class="p">,</span> <span class="n">Encoding</span> <span class="n">enc</span><span class="p">)</span></div><div class='line' id='LC2'><span class="p">{</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">byte</span><span class="p">[]</span> <span class="n">buffer</span> <span class="p">=</span> <span class="n">enc</span><span class="p">.</span><span class="n">GetBytes</span><span class="p">(</span><span class="n">text</span><span class="p">);</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">SHA1CryptoServiceProvider</span> <span class="n">cryptoTransformSHA1</span> <span class="p">=</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">new</span> <span class="nf">SHA1CryptoServiceProvider</span><span class="p">();</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">string</span> <span class="n">hash</span> <span class="p">=</span> <span class="n">BitConverter</span><span class="p">.</span><span class="n">ToString</span><span class="p">(</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">cryptoTransformSHA1</span><span class="p">.</span><span class="n">ComputeHash</span><span class="p">(</span><span class="n">buffer</span><span class="p">)).</span><span class="n">Replace</span><span class="p">(</span><span class="s">&quot;-&quot;</span><span class="p">,</span> <span class="s">&quot;&quot;</span><span class="p">);</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="n">hash</span><span class="p">;</span></div><div class='line' id='LC9'><span class="p">}</span></div><div class='line' id='LC10'><br/></div><div class='line' id='LC11'><span class="k">public</span> <span class="k">static</span> <span class="kt">string</span> <span class="nf">ToMD5</span><span class="p">(</span><span class="k">this</span> <span class="kt">string</span> <span class="n">input</span><span class="p">)</span></div><div class='line' id='LC12'><span class="p">{</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">MD5</span> <span class="n">md5</span> <span class="p">=</span> <span class="n">System</span><span class="p">.</span><span class="n">Security</span><span class="p">.</span><span class="n">Cryptography</span><span class="p">.</span><span class="n">MD5</span><span class="p">.</span><span class="n">Create</span><span class="p">();</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">byte</span><span class="p">[]</span> <span class="n">inputBytes</span> <span class="p">=</span> <span class="n">System</span><span class="p">.</span><span class="n">Text</span><span class="p">.</span><span class="n">Encoding</span><span class="p">.</span><span class="n">ASCII</span><span class="p">.</span><span class="n">GetBytes</span><span class="p">(</span><span class="n">input</span><span class="p">);</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">byte</span><span class="p">[]</span> <span class="n">hash</span> <span class="p">=</span> <span class="n">md5</span><span class="p">.</span><span class="n">ComputeHash</span><span class="p">(</span><span class="n">inputBytes</span><span class="p">);</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">StringBuilder</span> <span class="n">sb</span> <span class="p">=</span> <span class="k">new</span> <span class="n">StringBuilder</span><span class="p">();</span></div><div class='line' id='LC17'><br/></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&amp;</span><span class="n">lt</span><span class="p">;</span> <span class="n">hash</span><span class="p">.</span><span class="n">Length</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">sb</span><span class="p">.</span><span class="n">Append</span><span class="p">(</span><span class="n">hash</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">ToString</span><span class="p">(&amp;</span><span class="n">quot</span><span class="p">;</span><span class="n">X2</span><span class="p">&amp;</span><span class="n">quot</span><span class="p">;));</span></div><div class='line' id='LC21'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC22'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="n">sb</span><span class="p">.</span><span class="n">ToString</span><span class="p">();</span></div><div class='line' id='LC23'><span class="p">}</span> </div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1302074/c584d2cf6e41c8193469fa44be887893f862afd0/gistfile1.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1302074#file_gistfile1.cs" style="float:right;margin-right:10px;color:#666">gistfile1.cs</a>
            <a href="https://gist.github.com/1302074">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p><strong>Encrypting/Decrypting</strong><br />
Encrypting and decrypting data is very important in one of my latest projects. For that reason I created these 2 extension methods. They encrypt and decrypt a string with a supplied passphrase. If there was no passphrase supplied, it will try to fetch one from the .config file.</p>
<div id="gist-1302080" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">public</span> <span class="k">static</span> <span class="kt">string</span> <span class="nf">Encrypt</span><span class="p">(</span><span class="k">this</span> <span class="kt">string</span> <span class="n">Message</span><span class="p">,</span> <span class="kt">string</span> <span class="n">passphrase</span> <span class="p">=</span> <span class="s">&quot;&quot;</span><span class="p">)</span></div><div class='line' id='LC2'><span class="p">{</span></div><div class='line' id='LC3'>	<span class="k">if</span> <span class="p">(</span><span class="n">passphrase</span> <span class="p">==</span> <span class="s">&quot;&quot;</span><span class="p">)</span></div><div class='line' id='LC4'>		<span class="n">passphrase</span> <span class="p">=</span> <span class="n">ConfigurationManager</span><span class="p">.</span><span class="n">AppSettings</span><span class="p">[</span><span class="s">&quot;encrpytionPassphrase&quot;</span><span class="p">];</span></div><div class='line' id='LC5'><br/></div><div class='line' id='LC6'>	<span class="kt">byte</span><span class="p">[]</span> <span class="n">Results</span><span class="p">;</span></div><div class='line' id='LC7'>	<span class="n">System</span><span class="p">.</span><span class="n">Text</span><span class="p">.</span><span class="n">UTF8Encoding</span> <span class="n">UTF8</span> <span class="p">=</span> <span class="k">new</span> <span class="n">System</span><span class="p">.</span><span class="n">Text</span><span class="p">.</span><span class="n">UTF8Encoding</span><span class="p">();</span></div><div class='line' id='LC8'><br/></div><div class='line' id='LC9'>	<span class="n">MD5CryptoServiceProvider</span> <span class="n">HashProvider</span> <span class="p">=</span> <span class="k">new</span> <span class="n">MD5CryptoServiceProvider</span><span class="p">();</span></div><div class='line' id='LC10'>	<span class="kt">byte</span><span class="p">[]</span> <span class="n">TDESKey</span> <span class="p">=</span> <span class="n">HashProvider</span><span class="p">.</span><span class="n">ComputeHash</span><span class="p">(</span><span class="n">UTF8</span><span class="p">.</span><span class="n">GetBytes</span><span class="p">(</span><span class="n">passphrase</span><span class="p">));</span></div><div class='line' id='LC11'><br/></div><div class='line' id='LC12'>	<span class="n">TripleDESCryptoServiceProvider</span> <span class="n">TDESAlgorithm</span> <span class="p">=</span> <span class="k">new</span> <span class="n">TripleDESCryptoServiceProvider</span><span class="p">();</span></div><div class='line' id='LC13'><br/></div><div class='line' id='LC14'>	<span class="n">TDESAlgorithm</span><span class="p">.</span><span class="n">Key</span> <span class="p">=</span> <span class="n">TDESKey</span><span class="p">;</span></div><div class='line' id='LC15'>	<span class="n">TDESAlgorithm</span><span class="p">.</span><span class="n">Mode</span> <span class="p">=</span> <span class="n">CipherMode</span><span class="p">.</span><span class="n">ECB</span><span class="p">;</span></div><div class='line' id='LC16'>	<span class="n">TDESAlgorithm</span><span class="p">.</span><span class="n">Padding</span> <span class="p">=</span> <span class="n">PaddingMode</span><span class="p">.</span><span class="n">PKCS7</span><span class="p">;</span></div><div class='line' id='LC17'><br/></div><div class='line' id='LC18'>	<span class="kt">byte</span><span class="p">[]</span> <span class="n">DataToEncrypt</span> <span class="p">=</span> <span class="n">UTF8</span><span class="p">.</span><span class="n">GetBytes</span><span class="p">(</span><span class="n">Message</span><span class="p">);</span></div><div class='line' id='LC19'><br/></div><div class='line' id='LC20'>	<span class="k">try</span></div><div class='line' id='LC21'>	<span class="p">{</span></div><div class='line' id='LC22'>		<span class="n">ICryptoTransform</span> <span class="n">Encryptor</span> <span class="p">=</span> <span class="n">TDESAlgorithm</span><span class="p">.</span><span class="n">CreateEncryptor</span><span class="p">();</span></div><div class='line' id='LC23'>		<span class="n">Results</span> <span class="p">=</span> <span class="n">Encryptor</span><span class="p">.</span><span class="n">TransformFinalBlock</span><span class="p">(</span><span class="n">DataToEncrypt</span><span class="p">,</span> <span class="m">0</span><span class="p">,</span> <span class="n">DataToEncrypt</span><span class="p">.</span><span class="n">Length</span><span class="p">);</span></div><div class='line' id='LC24'>	<span class="p">}</span></div><div class='line' id='LC25'>	<span class="k">finally</span></div><div class='line' id='LC26'>	<span class="p">{</span></div><div class='line' id='LC27'>		<span class="n">TDESAlgorithm</span><span class="p">.</span><span class="n">Clear</span><span class="p">();</span></div><div class='line' id='LC28'>		<span class="n">HashProvider</span><span class="p">.</span><span class="n">Clear</span><span class="p">();</span></div><div class='line' id='LC29'>	<span class="p">}</span></div><div class='line' id='LC30'><br/></div><div class='line' id='LC31'>	<span class="k">return</span> <span class="n">Convert</span><span class="p">.</span><span class="n">ToBase64String</span><span class="p">(</span><span class="n">Results</span><span class="p">);</span></div><div class='line' id='LC32'><span class="p">}</span></div><div class='line' id='LC33'><br/></div><div class='line' id='LC34'><span class="k">public</span> <span class="k">static</span> <span class="kt">string</span> <span class="nf">Decrypt</span><span class="p">(</span><span class="k">this</span> <span class="kt">string</span> <span class="n">Message</span><span class="p">,</span> <span class="kt">string</span> <span class="n">passphrase</span> <span class="p">=</span> <span class="s">&quot;&quot;</span><span class="p">)</span></div><div class='line' id='LC35'><span class="p">{</span></div><div class='line' id='LC36'>	<span class="k">if</span> <span class="p">(</span><span class="n">passphrase</span> <span class="p">==</span> <span class="s">&quot;&quot;</span><span class="p">)</span></div><div class='line' id='LC37'>		<span class="n">passphrase</span> <span class="p">=</span> <span class="n">ConfigurationManager</span><span class="p">.</span><span class="n">AppSettings</span><span class="p">[</span><span class="s">&quot;encrpytionPassphrase&quot;</span><span class="p">];</span></div><div class='line' id='LC38'>	<span class="k">if</span> <span class="p">(</span><span class="n">Message</span> <span class="p">==</span> <span class="kt">string</span><span class="p">.</span><span class="n">Empty</span><span class="p">)</span></div><div class='line' id='LC39'>		<span class="k">return</span> <span class="kt">string</span><span class="p">.</span><span class="n">Empty</span><span class="p">;</span></div><div class='line' id='LC40'><br/></div><div class='line' id='LC41'>	<span class="kt">byte</span><span class="p">[]</span> <span class="n">Results</span><span class="p">;</span></div><div class='line' id='LC42'>	<span class="n">System</span><span class="p">.</span><span class="n">Text</span><span class="p">.</span><span class="n">UTF8Encoding</span> <span class="n">UTF8</span> <span class="p">=</span> <span class="k">new</span> <span class="n">System</span><span class="p">.</span><span class="n">Text</span><span class="p">.</span><span class="n">UTF8Encoding</span><span class="p">();</span></div><div class='line' id='LC43'><br/></div><div class='line' id='LC44'>	<span class="n">MD5CryptoServiceProvider</span> <span class="n">HashProvider</span> <span class="p">=</span> <span class="k">new</span> <span class="n">MD5CryptoServiceProvider</span><span class="p">();</span></div><div class='line' id='LC45'>	<span class="kt">byte</span><span class="p">[]</span> <span class="n">TDESKey</span> <span class="p">=</span> <span class="n">HashProvider</span><span class="p">.</span><span class="n">ComputeHash</span><span class="p">(</span><span class="n">UTF8</span><span class="p">.</span><span class="n">GetBytes</span><span class="p">(</span><span class="n">passphrase</span><span class="p">));</span></div><div class='line' id='LC46'><br/></div><div class='line' id='LC47'>	<span class="n">TripleDESCryptoServiceProvider</span> <span class="n">TDESAlgorithm</span> <span class="p">=</span> <span class="k">new</span> <span class="n">TripleDESCryptoServiceProvider</span><span class="p">();</span></div><div class='line' id='LC48'><br/></div><div class='line' id='LC49'>	<span class="n">TDESAlgorithm</span><span class="p">.</span><span class="n">Key</span> <span class="p">=</span> <span class="n">TDESKey</span><span class="p">;</span></div><div class='line' id='LC50'>	<span class="n">TDESAlgorithm</span><span class="p">.</span><span class="n">Mode</span> <span class="p">=</span> <span class="n">CipherMode</span><span class="p">.</span><span class="n">ECB</span><span class="p">;</span></div><div class='line' id='LC51'>	<span class="n">TDESAlgorithm</span><span class="p">.</span><span class="n">Padding</span> <span class="p">=</span> <span class="n">PaddingMode</span><span class="p">.</span><span class="n">PKCS7</span><span class="p">;</span></div><div class='line' id='LC52'><br/></div><div class='line' id='LC53'>	<span class="kt">byte</span><span class="p">[]</span> <span class="n">DataToDecrypt</span> <span class="p">=</span> <span class="n">Convert</span><span class="p">.</span><span class="n">FromBase64String</span><span class="p">(</span><span class="n">Message</span><span class="p">);</span></div><div class='line' id='LC54'><br/></div><div class='line' id='LC55'>	<span class="k">try</span></div><div class='line' id='LC56'>	<span class="p">{</span></div><div class='line' id='LC57'>		<span class="n">ICryptoTransform</span> <span class="n">Decryptor</span> <span class="p">=</span> <span class="n">TDESAlgorithm</span><span class="p">.</span><span class="n">CreateDecryptor</span><span class="p">();</span></div><div class='line' id='LC58'>		<span class="n">Results</span> <span class="p">=</span> <span class="n">Decryptor</span><span class="p">.</span><span class="n">TransformFinalBlock</span><span class="p">(</span><span class="n">DataToDecrypt</span><span class="p">,</span> <span class="m">0</span><span class="p">,</span> <span class="n">DataToDecrypt</span><span class="p">.</span><span class="n">Length</span><span class="p">);</span></div><div class='line' id='LC59'>	<span class="p">}</span></div><div class='line' id='LC60'>	<span class="k">catch</span></div><div class='line' id='LC61'>	<span class="p">{</span></div><div class='line' id='LC62'>		<span class="n">Results</span> <span class="p">=</span> <span class="k">new</span> <span class="kt">byte</span><span class="p">[</span><span class="m">0</span><span class="p">];</span></div><div class='line' id='LC63'>	<span class="p">}</span></div><div class='line' id='LC64'>	<span class="k">finally</span></div><div class='line' id='LC65'>	<span class="p">{</span></div><div class='line' id='LC66'>		<span class="n">TDESAlgorithm</span><span class="p">.</span><span class="n">Clear</span><span class="p">();</span></div><div class='line' id='LC67'>		<span class="n">HashProvider</span><span class="p">.</span><span class="n">Clear</span><span class="p">();</span></div><div class='line' id='LC68'>	<span class="p">}</span></div><div class='line' id='LC69'><br/></div><div class='line' id='LC70'>	<span class="k">return</span> <span class="n">UTF8</span><span class="p">.</span><span class="n">GetString</span><span class="p">(</span><span class="n">Results</span><span class="p">);</span></div><div class='line' id='LC71'><span class="p">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1302080/d9b4a9b28870fac5d7b116b901b307eee68a1f68/gistfile1.cs" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1302080#file_gistfile1.cs" style="float:right;margin-right:10px;color:#666">gistfile1.cs</a>
            <a href="https://gist.github.com/1302080">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://www.sortedbits.com/string-extension-methods-for-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using NLog in your web.config</title>
		<link>http://www.sortedbits.com/using-nlog-in-your-web-config/</link>
		<comments>http://www.sortedbits.com/using-nlog-in-your-web-config/#comments</comments>
		<pubDate>Thu, 08 Jul 2010 07:48:52 +0000</pubDate>
		<dc:creator>Wim</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Snippets]]></category>
		<category><![CDATA[Nlog]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>

		<guid isPermaLink="false">http://www.wimhaanstra.com/?p=778</guid>
		<description><![CDATA[I have been working on my YourRid.es project a bit lately and one of the things I wanted to put in place, was a good logging system. Most of the time I just use a custom build (read: my own shit) logger, but this time I found [...]]]></description>
			<content:encoded><![CDATA[<p>I have been working on my YourRid.es project a bit lately and one of the things I wanted to put in place, was a good logging system. Most of the time I just use a custom build (read: my own shit) logger, but this time I found the time to browse the internet for some good loggers.</p>
<p>After comparing a bit, I came to NLog and tried integrating this in my project. My project being build in Visual Studio 2010 has support for those nice web.config&#8217;s that can be transformed/malformed/adjusted while publishing. This was very necessary because my debug (local) build uses a different SQL instance than my production build.</p>
<p>So I just wanted to show you how I configured NLog in my web.config. It might be obvious for some people, but for others it might not.<br />
<span id="more-778"></span><br />
In my normal web.config I added the following lines. First I added a new <strong>section</strong> row to my <strong>configSections</strong>.</p>
<pre>
<section />
</pre>
<p>After that I went and added the normal NLog configuration to my web.config.</p>
<pre>

 insert into Log (TimeStamp, Level, Logger, Message, UserIdentity, CallSite) values(@time_stamp, @level, @logger, @message, @useridentity, @callsite);
</pre>
<p>This is the information for my debug environment. Because my laptop run SQL express, it connects to that instance.</p>
<p>This is my web.config.release :</p>
<pre>
</pre>
<p>It changes the connectionstring when I publish my release version. I love that feature of Visual Studio 2010!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sortedbits.com/using-nlog-in-your-web-config/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Reading big XML file with C# XmlReader</title>
		<link>http://www.sortedbits.com/reading-big-xml-file-with-c-xmlreader/</link>
		<comments>http://www.sortedbits.com/reading-big-xml-file-with-c-xmlreader/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 21:27:35 +0000</pubDate>
		<dc:creator>Wim</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.depl0y.com/?p=524</guid>
		<description><![CDATA[Today I needed to parse a LARGE (1.9GB) XML file and extract some information from it. Loading it in a XmlDocument (my favorite .NET way of handling XML) wasn&#8217;t really a possibility, because that would cause Out of Memory errors the minute I would try it. I [...]]]></description>
			<content:encoded><![CDATA[<p>Today I needed to parse a <strong>LARGE</strong> (1.9GB) XML file and extract some information from it. Loading it in a XmlDocument (my favorite .NET way of handling XML) wasn&#8217;t really a possibility, because that would cause Out of Memory errors the minute I would try it.</p>
<p>I am using a XmlReader for this and I noticed that there arent really many usable examples on the internet about this, so here is just a small example I created to show how you could read a RSS feed.</p>
<p>Sample after the break&#8230;<span id="more-524"></span></p>
<pre class="syntax c">// File to open up, can be an URL too
string XmlFileUrl = @&quot;c:feed.xml&quot;;
using (XmlReader reader = new XmlTextReader(XmlFileUrl))
{
	// Initialize a list for storage of the items
	List items = new List();
	// boolean to see if a node was opened before
	bool openItem = false;
	RssItem item = new RssItem();

	// Loop the reader, till it cant read anymore
	while (reader.Read())
	{
		// An object with the type Element was found.
		if (reader.NodeType == XmlNodeType.Element)
		{
			// Check name of the node and write the contents in the object accordingly.
			if (reader.Name == &quot;item&quot;)
			{
				item = new RssItem();
				openItem = true;
			}
			else if (reader.Name == &quot;title&quot; &amp;amp;&amp;amp; openItem)
				item.title = reader.ReadElementContentAsString();
			else if (reader.Name == &quot;link&quot; &amp;amp;&amp;amp; openItem)
				item.link = reader.ReadElementContentAsString();
			else if (reader.Name == &quot;description&quot; &amp;amp;&amp;amp; openItem)
				item.description = reader.ReadElementContentAsString();
		}
		// EndElement was found, check if it is named item, if it is, store the object in the list and set openItem to false.
		else if (reader.NodeType == XmlNodeType.EndElement &amp;amp;&amp;amp; reader.Name == &quot;item&quot; &amp;amp;&amp;amp; openItem)
		{
			openItem = false;
			items.Add(item);
		}
	}
}</pre>
<p>The <strong>RssItem</strong> class I created is just a simple class containing a couple of properties:</p>
<pre class="syntax c">public class RssItem
{
	public string title { get; set; }
	public string pubDate { get; set; }
	public string link { get; set; }
	public string description { get; set; }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.sortedbits.com/reading-big-xml-file-with-c-xmlreader/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Resizing an image in C#</title>
		<link>http://www.sortedbits.com/resizing-an-image-in-c/</link>
		<comments>http://www.sortedbits.com/resizing-an-image-in-c/#comments</comments>
		<pubDate>Tue, 26 Jan 2010 14:15:14 +0000</pubDate>
		<dc:creator>Wim</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[resize]]></category>

		<guid isPermaLink="false">http://www.depl0y.com/?p=477</guid>
		<description><![CDATA[For a project I am working on, I was looking for a good way to resize images in a few different ways. I have done image resizing before, but it really feels that I am re-inventing the wheel every time I do this. So now I decided [...]]]></description>
			<content:encoded><![CDATA[<p>For a project I am working on, I was looking for a good way to resize images in a few different ways. I have done image resizing before, but it really feels that I am re-inventing the wheel every time I do this. So now I decided to write a nice static method which can resize an Image to certain dimensions and outputs an Image object again.</p>
<p>The method requires 3 parameters:</p>
<p>1. An image object. I hope you know how to load a file in an Image object (hint: FromFile).<br />
2. A Resolution object, being nothing more than a small class I created, which also contains the width and the height.<br />
3. The mode you want to use for resizing the image. I explained the modes in the enum listed below.</p>
<p>It probably isnt the neatest code you&#8217;ve ever seen, so if you have any comments, please let me know. Code and more explanation after the break&#8230;<span id="more-477"></span></p>
<pre>///
/// Method resizes the image so it fits the wanted resolution best.
///
///The image to be resized
///The resolution which the image should be when the method is ready.
///The mode for resizing the image.
public static System.Drawing.Image Resize(System.Drawing.Image image, Resolution targetResolution, ResizeMode resizeMode)
{
	int sourceWidth = image.Width;
	int sourceHeight = image.Height;

	int targetWidth = targetResolution.Width;
	int targetHeight = targetResolution.Height;

	// Supplied image is landscape, while the target resolution is portait OR
	// supplied image is in portait, while the target resolution is in landscape.
	// switch target resolution to match the image.
	if ((sourceWidth &gt; sourceHeight &amp;&amp; targetWidth &lt; targetHeight) || (sourceWidth &lt; sourceHeight &amp;&amp; targetWidth &gt; targetHeight))
	{
		targetWidth = targetResolution.Height;
		targetHeight = targetResolution.Width;
	}

	float ratio = 0;
	float ratioWidth = ((float)targetWidth / (float)sourceWidth);
	float ratioHeight = ((float)targetHeight / (float)sourceHeight);

	if (ratioHeight &lt; ratioWidth)
		ratio = ratioHeight;
	else
		ratio = ratioWidth;

	Bitmap newImage = null;

	switch (resizeMode)
	{
		case ResizeMode.Normal:
		default:
			{
				int destWidth = (int)(sourceWidth * ratio);
				int destHeight = (int)(sourceHeight * ratio);

				newImage = new Bitmap(destWidth, destHeight);
				using (Graphics graphics = Graphics.FromImage((System.Drawing.Image)newImage))
				{
					graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
					graphics.DrawImage(image, 0, 0, destWidth, destHeight);
				}

				break;
			}
		case ResizeMode.Crop:
			{
				if (ratioHeight &gt; ratioWidth)
					ratio = ratioHeight;
				else
					ratio = ratioWidth;

				int destWidth = (int)(sourceWidth * ratio);
				int destHeight = (int)(sourceHeight * ratio);

				newImage = new Bitmap(targetWidth, targetHeight);

				int startX = 0;
				int startY = 0;

				if (destWidth &gt; targetWidth)
					startX = 0 - ((destWidth - targetWidth) / 2);

				if (destHeight &gt; targetHeight)
					startY = 0 - ((destHeight - targetHeight) / 2);

				using (Graphics graphics = Graphics.FromImage((System.Drawing.Image)newImage))
				{
					graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
					graphics.DrawImage(image, startX, startY, destWidth, destHeight);
				}

				break;
			}
		case ResizeMode.Stretch:
			{
				newImage = new Bitmap(targetWidth, targetHeight);
				using (Graphics graphics = Graphics.FromImage((System.Drawing.Image)newImage))
				{
					graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
					graphics.DrawImage(image, 0, 0, targetWidth, targetHeight);
				}
				break;
			}
		case ResizeMode.Fill:
			{
				newImage = new Bitmap(targetWidth, targetHeight);

				int destWidth = (int)(sourceWidth * ratio);
				int destHeight = (int)(sourceHeight * ratio);

				int startX = 0;
				int startY = 0;

				if (destWidth &lt; targetWidth)
					startX = 0 + ((targetWidth - destWidth) / 2);

				if (destHeight &lt; targetHeight)
					startY = 0 + ((targetHeight - destHeight) / 2);

				newImage = new Bitmap(targetWidth, targetHeight);
				using (Graphics graphics = Graphics.FromImage((System.Drawing.Image)newImage))
				{
					graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
					graphics.DrawImage(image, startX, startY, destWidth, destHeight);
				}

				break;
			}
	}

	return (System.Drawing.Image)newImage;
}</pre>
<p>The <strong>resizeMode</strong> parameter is of the type ResizeMode, which is nothing more than a simple enumeration, like this:</p>
<pre>///
/// Modes available for the resize method of images.
///
public enum ResizeMode
{
	///
	/// This will resize images to the resolution nearest to the target resolution. Images can become smaller when using this option
	///
	Normal = 1,
	///
	/// This will stretch an image so it always is the exact dimensions of the target resolution
	///
	Stretch = 2,
	///
	/// This will size an image to the exact dimensions of the target resolution, keeping ratio in mind and cropping parts that can't
	/// fit in the picture.
	///
	Crop = 3,
	///
	/// This will size an image to the exact dimensions of the target resolution, keeping ratio in mind and filling up the image
	/// with black bars when some parts remain empty.
	///
	Fill = 4
}</pre>
<p>And the <strong>targetResolution</strong> parameter, is a simple class containing some properties like <strong>Name</strong>, <strong>Width</strong> and <strong>Height</strong>.</p>
<p>This method seems to do everything I need, if you need anything more, or any information about this code, just email me or reply here.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sortedbits.com/resizing-an-image-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Management of your pictures/videos etc.</title>
		<link>http://www.sortedbits.com/management-of-your-picturesvideos-etc/</link>
		<comments>http://www.sortedbits.com/management-of-your-picturesvideos-etc/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 12:05:16 +0000</pubDate>
		<dc:creator>Wim</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.depl0y.com/?p=452</guid>
		<description><![CDATA[I have (just as so many people probably) been struggling to keep my digital photo&#8217;s and home-made videos manageable. I tried so many photo/media management tools that I actually lost count and they never satisfied my needs. They always kept my library as messy as it now, [...]]]></description>
			<content:encoded><![CDATA[<p>I have (just as so many people probably) been struggling to keep my digital photo&#8217;s and home-made videos manageable. I tried so many photo/media management tools that I actually lost count and they never satisfied my needs. They always kept my library as messy as it now, which is a HUGE directory, with files which have names like &#8217;2009_1225_183025.jpg&#8217;. Since a couple of weeks I also shoot HD movies with my camcorder and those files are already stacking up also.</p>
<p>I have been thinking about what could actually help me solve this problem and I think I came up with a solution to my (own) problem. I am currently making a tool with the project-name &#8220;Media-Manager&#8221;. The tool extracts all meta data from my media files and stores it nicely in a data source (e.g. SQL Server, XML files). In my tool I can specify events which happened on certain date&#8217;s (or a longer time-span) and it automatically filters the photo&#8217;s by those event.<span id="more-452"></span></p>
<p>Let me give you an example, which should clear up my story.</p>
<p>My oldest daughter &#8216;Luuke&#8217;, she has her birthday on January 7th and we always take pictures from it. In my tool I can specify an event called &#8220;Luuke&#8217;s Birthday&#8221;, which recurs yearly on the 7th of January. My tool will the propose which pictures fit with that event. You can then either confirm for each picture that it indeed is one that should be linked to that event or you confirm them in batches. The tool will then create directory structure like this:</p>
<blockquote><p>Z:MediaLuuke&#8217;s Birthday2010<br />
Z:MediaLuuke&#8217;s Birthday2009<br />
Z:MediaLuuke&#8217;s Birthday2008<br />
Z:MediaLuuke&#8217;s Birthday2007<br />
etc.</p></blockquote>
<p>Pictures that are uncategorized will be put in a different folder like this:</p>
<blockquote><p>Z:MediaUncategorized20101<br />
Z:MediaUncategorized200912<br />
Z:MediaUncategorized200911<br />
Z:MediaUncategorized200910<br />
etc.</p></blockquote>
<p>When you have categorized some pictures, for example the birthday of 2010, you can simply click that &#8216;Event&#8217; and export images to a directory (maybe later to a web destination). You can specify if images should be converted to a different file-type, size or compression level.</p>
<p>The media manager, also reads meta-data from MTS files, these are the (Full HD video) files coming from my camcorder and it will also put those movies in the right category/event.</p>
<p>This is my first full-blown WPF project, where I also create my own custom controls to make sure the GUI is all nice and flashy looking. I am using Visual Studio 2010 for the development of this tool and I must say that I am hooked. Visual Studio 2010 seems so much easier to use and the WPF/XAML designer is actually pretty fast.</p>
<p>I hope I can actually put a release of the tool on here, once it is finished. Because I cant believe I am the only one with this nice little problem that comes with digital photography.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sortedbits.com/management-of-your-picturesvideos-etc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using jQuery Dialog with ASP.NET</title>
		<link>http://www.sortedbits.com/using-jquery-dialog-with-asp-net/</link>
		<comments>http://www.sortedbits.com/using-jquery-dialog-with-asp-net/#comments</comments>
		<pubDate>Tue, 08 Sep 2009 20:19:52 +0000</pubDate>
		<dc:creator>Wim</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Snippets]]></category>

		<guid isPermaLink="false">http://www.depl0y.com/?p=442</guid>
		<description><![CDATA[I have been playing around with jQuery a bit lately and I wanted to use the nice dialog boxes on my new project. The problem with the dialog boxes is, that they do not create a postback when one of the buttons is clicked. Also the values [...]]]></description>
			<content:encoded><![CDATA[<p>I have been playing around with jQuery a bit lately and I wanted to use the nice dialog boxes on my new project. The problem with the dialog boxes is, that they do not create a postback when one of the buttons is clicked. Also the values of any controls inside the dialog are always empty, when using the dialog box.</p>
<p>I just will be posting my code here, to let you see how I solved the problem. <span id="more-442"></span><br />
First, my JavaScript code to show the dialog I want:</p>
<pre>function showDialog(ID) {
	var dlg = $("#" + ID).dialog({
		bgiframe: true,
		height: 165,
		width: 450,
		modal: true,
		buttons: {
			Ok: function() {
			$(this).dialog('close');
			__doPostBack = newDoPostBack;
			 __doPostBack("aspnetForm", null);
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		}
	});
	dlg.parent().appendTo(jQuery('form:first'));
}

function newDoPostBack(eventTarget, eventArgument) {
	var theForm = document.forms[0];

	if (!theForm) {
		theForm = document.aspnetForm;
	}

	if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
		document.getElementById("__EVENTTARGET").value = eventTarget;
		document.getElementById("__EVENTARGUMENT").value = eventArgument;
		theForm.submit();
	}
}</pre>
<p>Now here is my simple dialog, and the code to initiate it.</p>
<pre>
<div class="btn-140-addserver">
<div>

		Please enter a server name here. It can be anything you like:</div>
</div>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.sortedbits.com/using-jquery-dialog-with-asp-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Running Sitecore 6 on Windows 7&#8242;s IIS</title>
		<link>http://www.sortedbits.com/running-sitecore-6-on-windows-7s-iis/</link>
		<comments>http://www.sortedbits.com/running-sitecore-6-on-windows-7s-iis/#comments</comments>
		<pubDate>Fri, 27 Feb 2009 07:27:06 +0000</pubDate>
		<dc:creator>Wim</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.depl0y.com/?p=386</guid>
		<description><![CDATA[Just posting this info, for all the people getting an error after installing Sitecore 6 on IIS7 of Windows 7. The error Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and [...]]]></description>
			<content:encoded><![CDATA[<p>Just posting this info, for all the people getting an error after installing Sitecore 6 on IIS7 of Windows 7.</p>
<p><strong>The error</strong></p>
<pre>
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Security.Cryptography.CryptographicException: The system cannot find the file specified.
</pre>
<p>Well, the solution is rather easy&#8230; make sure you got the following code in your <strong>global.asax</strong></p>
<pre>
  public void Application_Start() {
	  System.Security.Cryptography.RSACryptoServiceProvider.UseMachineKeyStore = true;
	  System.Security.Cryptography.DSACryptoServiceProvider.UseMachineKeyStore = true;
  }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.sortedbits.com/running-sitecore-6-on-windows-7s-iis/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>foreach and mixed array</title>
		<link>http://www.sortedbits.com/foreach-and-mixed-array/</link>
		<comments>http://www.sortedbits.com/foreach-and-mixed-array/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 07:55:20 +0000</pubDate>
		<dc:creator>Wim</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Coding]]></category>

		<guid isPermaLink="false">http://www.depl0y.com/?p=258</guid>
		<description><![CDATA[Yesterday I was just coding along and I was (accidently) filling an ArrayList with strings and Guids. After that I tried to read all strings from that ArrayList with just some simple code: foreach (string myString in myArrayList) { // some code here. } It bombed out [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I was just coding along and I was (accidently) filling an ArrayList with strings and Guids.</p>
<p>After that I tried to read all strings from that ArrayList with just some simple code:</p>
<pre>
foreach (string myString in myArrayList)
{
// some code here.
}
</pre>
<p>It bombed out with an exception, telling me that it couldn&#8217;t cast a Guid to a String.</p>
<p>I thought that with an foreach, you only grabbed items of a certain type from the ArrayList. But somehow it just tries to grab every item and cast it to a string. Weird.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sortedbits.com/foreach-and-mixed-array/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Braces and cases</title>
		<link>http://www.sortedbits.com/braces-and-cases/</link>
		<comments>http://www.sortedbits.com/braces-and-cases/#comments</comments>
		<pubDate>Tue, 16 Dec 2008 22:50:36 +0000</pubDate>
		<dc:creator>Wim</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.depl0y.com/?p=244</guid>
		<description><![CDATA[Ok, I might be a n00b software developer or something, but today I found out something shocking, which I want to share with you. I was writing a bit of code, where I had a case statement. See my simple example below. switch (inputText) { case "Title1": [...]]]></description>
			<content:encoded><![CDATA[<p>Ok, I might be a n00b software developer or something, but today I found out something shocking, which I want to share with you.</p>
<p>I was writing a bit of code, where I had a case statement. See my simple example below.<span id="more-244"></span></p>
<pre>
switch (inputText)
{
	case "Title1":
		XmlNode titleNode = xmlDocument.CreateElement("title");
		titleNode.InnerText = "Title 1";
		break;
	case "Title2":
		XmlNode titleNode = xmlDocument.CreateElement("title");
		titleNode.InnerText = "Title 2";
		break;
}
</pre>
<p>When you try to compile this, Visual Studio will tell you that you cannot redefine the XmlNode titleNode, because it is already defined in this scope.</p>
<p>But if you do this:</p>
<pre>
switch (inputText)
{
	case "Title1":
	{
		XmlNode titleNode = xmlDocument.CreateElement("title");
		titleNode.InnerText = "Title 1";
		break;
	}
	case "Title2":
	{
		XmlNode titleNode = xmlDocument.CreateElement("title");
		titleNode.InnerText = "Title 2";
		break;
	}
}
</pre>
<p>The compiler says it&#8217;s alright, just as would expect for the first example. Is this really by design or am I missing something here?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sortedbits.com/braces-and-cases/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multiple web.config files</title>
		<link>http://www.sortedbits.com/multiple-webconfig-files/</link>
		<comments>http://www.sortedbits.com/multiple-webconfig-files/#comments</comments>
		<pubDate>Sun, 14 Dec 2008 10:24:58 +0000</pubDate>
		<dc:creator>Wim</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Snippets]]></category>

		<guid isPermaLink="false">http://www.depl0y.com/?p=229</guid>
		<description><![CDATA[We all know this problem, when publishing your web applications to different servers, you always need to take extra care of your config files. Because database connections and physical paths stored in the web.config are machine specific. Well there is no real solution for this kind of [...]]]></description>
			<content:encoded><![CDATA[<p>We all know this problem, when publishing your web applications to different servers, you always need to take extra care of your config files. Because database connections and physical paths stored in the web.config are machine specific.</p>
<p>Well there is no real solution for this kind of problem, at least not one I could find. So I created a ConfigManager class which can replace the ConfigurationManager class.</p>
<p>So what does the ConfigManager class do?</p>
<li>First it loads in your normal configuration file (web.config or app.config).</li>
<li>It looks for an appSetting called &#8216;ConfigLocation&#8217;, this is a virtual path where the machine specific configuration files are stored.</li>
<li>The NETBIOS name of the machine running the application is determined.</li>
<li>It looks for a &#8216;[YOUR NETBIOS NAME].config&#8217; file in the directory specified in step 2. For example, if your computer name is &#8216;MyComputer&#8217; then it looks for a file &#8216;MyComputer.config&#8217;.</li>
<li>When a configuration file is found with that name, it loads that configuration file and it &#8216;overrides&#8217; the values in the normal configuration file.</li>
<p>So, actually it does nothing more than just extend the normal ConfigurationManager.</p>
<p><strong>Usage:</strong></p>
<pre>
string indexDirectory = ConfigManager.AppSettings["IndexDirectory"];
string connection = ConfigManager.ConnectionStrings["DatabaseConnection"];
</pre>
<p>I also created a small method that can output all active settings in an HTML string:</p>
<pre>
string html = ConfigManager.PresentContents();
</pre>
<p><strong>Sample web.config:</strong></p>
<pre>
...

...
</pre>
<p><strong>Sample ~/Configurations/MyComputer.config:</strong></p>
<pre>
</pre>
<p>The MyComputer.config file is only loaded if the application is run on a machine with the name &#8216;MyComputer&#8217;. When it IS run on that machine, the IndexDirectory configuration setting from the web.config is overridden by the IndexDirectory setting from the MyComputer.config.</p>
<p><a href='http://www.depl0y.com/files/configmanager.zip'>ConfigManager v2 1.0</a><br />
<a href='http://www.depl0y.com/files/configmanager.chm'>ConfigManager v2 1.0 Help File</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sortedbits.com/multiple-webconfig-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

