<?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>Software Ninjaneer</title>
	<atom:link href="http://softwareninjaneer.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://softwareninjaneer.com/blog</link>
	<description>Slicing and dicing code into bits</description>
	<lastBuildDate>Thu, 07 Feb 2013 18:52:25 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>The C# null coalescing operator and when 2 + 3 = 2</title>
		<link>http://softwareninjaneer.com/blog/2012/08/02/null-coalescing-operator-precedence/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=null-coalescing-operator-precedence</link>
		<comments>http://softwareninjaneer.com/blog/2012/08/02/null-coalescing-operator-precedence/#comments</comments>
		<pubDate>Thu, 02 Aug 2012 11:50:16 +0000</pubDate>
		<dc:creator>Ahmad Mageed</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://softwareninjaneer.com/blog/?p=424</guid>
		<description><![CDATA[<p><p>Original post: <a href="http://softwareninjaneer.com/blog/2012/08/02/null-coalescing-operator-precedence/">The C# null coalescing operator and when 2 + 3 = 2</a></p><p>Recently I was working with some nullable objects that I needed to add together. This led to some incorrect results when I wrote the code to sum them up due to the use of the null coalescing operator. The good news is that I wrote the code in a particular way, on purpose, to see what the compiler would do and my intuition proved to be correct. On top of that, I had some unit tests in place, so I was confident that a wrong result would get caught immediately. While I don&#8217;t think this is an earth-shattering finding, a quick search shows that the issue has tripped up a few people. Quick, what&#8217;s 2 + 3? Would you expect the answer to be 2? If not, then read on! Here is some code to put this all in perspective. So why did I end up with a result of two? Clearly 2 + 3 = 5, not 2! The answer is that the precedence rules for the ?? operator played a role in returning the odd result. After reviewing the C# operators precedence rules, I found that the ?? operator has a very low precedence. The addition operator has higher precedence than it, which essentially causes the entire expression to be evaluated as follows: Bear in mind that these steps may not be exactly how the C# compiler evaluates the expression, but they&#8217;re close enough to illustrate how it arrives to the seemingly incorrect result. Eric Lippert&#8217;s post titled, &#8220;Precedence vs Associativity vs Order,&#8221; sheds some light on how the compiler evaluates expressions if you&#8217;re looking for more detail. As you may have guessed, the solution to return the expected result is to group the operator in parentheses so that the intended precedence is maintained. The following code yields the correct result of five: An alternate approach, applicable with nullable types, is to use the Nullable.GetValueOrDefault method. However, it doesn&#8217;t have the brevity of the ?? operator. Most people have an idea of general precedence rules, but as software developers we run into more operators with different levels of precedence. For clarity, and when you&#8217;re in doubt, group your expressions in parentheses.</p></p><p>Published by Ahmad Mageed on <a href="http://softwareninjaneer.com/blog">Software Ninjaneer</a></p>]]></description>
				<content:encoded><![CDATA[<p>Original post: <a href="http://softwareninjaneer.com/blog/2012/08/02/null-coalescing-operator-precedence/">The C# null coalescing operator and when 2 + 3 = 2</a></p><p>Recently I was working with some nullable objects that I needed to add together. This led to some incorrect results when I wrote the code to sum them up due to the use of the <a href="http://msdn.microsoft.com/en-us/library/ms173224.aspx" title="?? Operator">null coalescing operator</a>.</p>
<p>The good news is that I wrote the code in a particular way, on purpose, to see what the compiler would do and my intuition proved to be correct. On top of that, I had some unit tests in place, so I was confident that a wrong result would get caught immediately. While I don&#8217;t think this is an earth-shattering finding, a quick search shows that the issue has tripped up a few people.</p>
<p>Quick, what&#8217;s 2 + 3? Would you expect the answer to be 2? If not, then read on! Here is some code to put this all in perspective.</p>
<pre class="brush: csharp; title: ; notranslate">
int? x = 2;
int? y = 3;

int result = x ?? 0 + y ?? 0;
Console.WriteLine(result);  // 2
</pre>
<p>So why did I end up with a result of two? Clearly 2 + 3 = 5, not 2! The answer is that the precedence rules for the <em>?? operator</em> played a role in returning the odd result.</p>
<p>After reviewing the <a href="http://msdn.microsoft.com/en-us/library/6a71f45d.aspx" title="C# Operators">C# operators precedence rules</a>, I found that the <em>?? operator</em> has a very low precedence. The addition operator has higher precedence than it, which essentially causes the entire expression to be evaluated as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
// parenthesize based on higher precedence of addition
x ?? (0 + y) ?? 0
x ?? (0 + 3) ?? 0  // y is 3

// the left-hand operand, x, isn't null
// so use its value and ignore the right-hand operand
(x ?? 3) ?? 0

x ?? 0  // once again, ignore the right-hand operand
2       // result is x, which is 2
</pre>
<p>Bear in mind that these steps may not be exactly how the C# compiler evaluates the expression, but they&#8217;re close enough to illustrate how it arrives to the seemingly incorrect result. Eric Lippert&#8217;s post titled, &#8220;<a href="http://blogs.msdn.com/b/ericlippert/archive/2008/05/23/precedence-vs-associativity-vs-order.aspx" title="Precedence vs Associativity vs Order">Precedence vs Associativity vs Order</a>,&#8221; sheds some light on how the compiler evaluates expressions if you&#8217;re looking for more detail.</p>
<p>As you may have guessed, the solution to return the expected result is to group the operator in parentheses so that the intended precedence is maintained. The following code yields the correct result of five:</p>
<pre class="brush: csharp; title: ; notranslate">
int? x = 2;
int? y = 3;

int result = (x ?? 0) + (y ?? 0);
Console.WriteLine(result);  // 5, as intended
</pre>
<p>An alternate approach, applicable with nullable types, is to use the <a href="http://msdn.microsoft.com/en-us/library/72cec0e0.aspx" title="Nullable.GetValueOrDefault method"><code>Nullable.GetValueOrDefault</code> method</a>. However, it doesn&#8217;t have the brevity of the <em>?? operator</em>.</p>
<pre class="brush: csharp; title: ; notranslate">
int result = x.GetValueOrDefault() + y.GetValueOrDefault();
</pre>
<p>Most people have an idea of general precedence rules, but as software developers we run into more operators with different levels of precedence. For clarity, and when you&#8217;re in doubt, group your expressions in parentheses.</p>
<p>Published by Ahmad Mageed on <a href="http://softwareninjaneer.com/blog">Software Ninjaneer</a></p>]]></content:encoded>
			<wfw:commentRss>http://softwareninjaneer.com/blog/2012/08/02/null-coalescing-operator-precedence/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Returning classes that inherit List&lt;T&gt; using a generic method</title>
		<link>http://softwareninjaneer.com/blog/2012/03/05/returning-classes-that-inherit-listt-using-a-generic-method/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=returning-classes-that-inherit-listt-using-a-generic-method</link>
		<comments>http://softwareninjaneer.com/blog/2012/03/05/returning-classes-that-inherit-listt-using-a-generic-method/#comments</comments>
		<pubDate>Mon, 05 Mar 2012 14:35:10 +0000</pubDate>
		<dc:creator>Ahmad Mageed</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://softwareninjaneer.com/blog/?p=262</guid>
		<description><![CDATA[<p><p>Original post: <a href="http://softwareninjaneer.com/blog/2012/03/05/returning-classes-that-inherit-listt-using-a-generic-method/">Returning classes that inherit List&lt;T&gt; using a generic method</a></p><p>Recently a past coworker came across a problem and issued a code challenge to some of her colleagues to help figure it out. This post is my response to that challenge. Problem and Challenge In an effort to enhance the readability of a List&#60;T&#62;, especially when nested within another list, the developer decided to implement a new class that inherits from List&#60;T&#62;. This looks like: She wanted to have an extension method that would operate on the List&#60;T&#62; but return the actual type that inherited from it (ProductList, in this example). To illustrate, consider an extension method that simply skips the first item in a list and returns the remaining items (exciting, I know). This sample reflects the approach taken: The extension method was used in the following manner: This caused an InvalidCastException to be thrown: Unable to cast object of type &#8216;System.Collections.Generic.List`1[CollectionInheritance.Product]&#8216; to type &#8216;CollectionInheritance.ProductList&#8217; At this point she could&#8217;ve fallen back on using List&#60;T&#62; but she worked around it using AutoMapper instead. The problem with that approach is that the original intention to provide an elegant solution to be used with other classes following the same inheritance setup was somewhat lost. It now required two steps: (1) calling SkipFirst, and (2) mapping from List&#60;T&#62; to TList. Dissatisfied, she issued the code challenge seeking an extension method that would work with classes which inherit from List&#60;T&#62; without using AutoMapper. Understanding why casting fails Before I get to my solution I wanted to shed some light on why casting doesn&#8217;t work. As seen earlier, an explicit cast threw an InvalidCastException. Similarly, usage of the as operator is incorrect and would return a null result. The reason both approaches fail is because ProductList and List are different types! Yes, they represent the same thing to us on the outside, but they aren&#8217;t the same. Jeffrey Richter touches upon this very topic in his excellent CLR via C# book (p. 287, 3rd ed.): &#8220;&#8230; you should never define a new class explicitly for the purpose of making your source code easier to read. The reason is because you lose type identity and equivalence&#8230;&#8221; He continues with an example to demonstrate, similar to what follows, which evaluates to false: With that in mind, it&#8217;s clear why casting won&#8217;t work. Likewise, the as operator returns a null value since, by definition, if the conversion fails it will return null instead of throwing an exception. Another important point (also raised in the book) is that this approach prevents List&#60;T&#62; from being passed to a method that expects the new class which inherits from List&#60;T&#62; as a parameter. However, going in the opposite direction is allowed. In other words, passing a List&#60;Product&#62; to a method that accepts a ProductList would fail, but passing a ProductList to a method expecting List&#60;Product&#62; is valid since ProductList inherits from List&#60;Product&#62;. Solution To meet the challenge I wrote the following extension method: Usage: There you go! Nice and succinct. No casting, and no need for the extra line of code to use AutoMapper. The key to this puzzle was to return TCollection, instead of a List&#60;T&#62;. Furthermore, adding the generic constraints ensures that TCollection implements ICollection&#60;T&#62; and has a public parameterless constructor in order to new up an instance of the class. Note that List&#60;T&#62; and IList&#60;T&#62; could&#8217;ve been used in the extension method. Implementing custom collections and public APIs For simplicity&#8217;s sake it&#8217;s not uncommon to see a subclass of List&#60;T&#62;. Perhaps this is acceptable for internal usage, however it isn&#8217;t recommended when exposed in a public API. This issue has been brought up numerous times. If a custom collection needs to have special behavior then it&#8217;s possible to change the collection&#8217;s implementation if inheriting from classes meant to be extended. To paraphrase Krzysztof Cwalina, co-author of the .NET Framework Design Guidelines, List&#60;T&#62; wasn&#8217;t meant to be extended, unlike Collection&#60;T&#62; which lets you override its members and supports awareness of item modification. Also, List&#60;T&#62; returns a rich set of members that typically aren&#8217;t appropriate for all scenarios. This guideline is also covered by a Code Analysis warning, CA1002: Do not expose generic lists. David Kean, a member of the Code Analysis team, expanded on this warning with supporting code examples in the post titled FAQ: Why does DoNotExposeGenericLists recommend that I expose Collection&#60;T&#62; instead of List&#60;T&#62;?</p></p><p>Published by Ahmad Mageed on <a href="http://softwareninjaneer.com/blog">Software Ninjaneer</a></p>]]></description>
				<content:encoded><![CDATA[<p>Original post: <a href="http://softwareninjaneer.com/blog/2012/03/05/returning-classes-that-inherit-listt-using-a-generic-method/">Returning classes that inherit List&lt;T&gt; using a generic method</a></p><p>Recently a past coworker came across a problem and issued a code challenge to some of her colleagues to help figure it out. This post is my response to that challenge.</p>
<h3>Problem and Challenge</h3>
<p>In an effort to enhance the readability of a <code>List&lt;T&gt;</code>, especially when nested within another list, the developer decided to implement a new class that inherits from <code>List&lt;T&gt;</code>. This looks like:</p>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
public class ProductList : List&lt;Product&gt; { }
</pre>
<p>She wanted to have an extension method that would operate on the <code>List&lt;T&gt;</code> but return the actual type that inherited from it (<code>ProductList</code>, in this example).</p>
<p>To illustrate, consider an extension method that simply skips the first item in a list and returns the remaining items (exciting, I know). This sample reflects the approach taken:</p>
<pre class="brush: csharp; title: ; notranslate"> 
public static class Extensions
{
    public static List&lt;T&gt; SkipFirst&lt;T&gt;(this List&lt;T&gt; input)
    {
        List&lt;T&gt; result = input.Skip(1).ToList();
        return result;
    }
}
</pre>
<p>The extension method was used in the following manner:</p>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
ProductList result = (ProductList)list.SkipFirst();
</pre>
<p>This caused an <code>InvalidCastException</code> to be thrown:</p>
<blockquote><p>
Unable to cast object of type &#8216;System.Collections.Generic.List`1[CollectionInheritance.Product]&#8216; to type &#8216;CollectionInheritance.ProductList&#8217;</p></blockquote>
<p>At this point she could&#8217;ve fallen back on using <code>List&lt;T&gt;</code> but she worked around it using AutoMapper instead. The problem with that approach is that the original intention to provide an elegant solution to be used with other classes following the same inheritance setup was somewhat lost. It now required two steps: (1) calling <code>SkipFirst</code>, and (2) mapping from <code>List&lt;T&gt;</code> to <code>TList</code>.</p>
<p>Dissatisfied, she issued the code challenge seeking an extension method that would work with classes which inherit from <code>List&lt;T&gt;</code> without using AutoMapper.</p>
<p><a href="http://softwareninjaneer.com/blog/wp-content/uploads/2012/03/ChallengeAcceptedGenericsInheritance.jpg"><img class="aligncenter size-full wp-image-264" title="ChallengeAcceptedGenericsInheritance" src="http://softwareninjaneer.com/blog/wp-content/uploads/2012/03/ChallengeAcceptedGenericsInheritance.jpg" alt="Generics and Inheritance? Challenge Accepted!" width="400" height="299" /></a></p>
<h3>Understanding why casting fails</h3>
<p>Before I get to my solution I wanted to shed some light on why casting doesn&#8217;t work. As seen earlier, an explicit cast threw an <code>InvalidCastException</code>. Similarly, usage of the <a href="http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx" title="C# as operator"><code>as</code> operator</a> is incorrect and would return a <em>null</em> result.</p>
<p>The reason both approaches fail is because <code>ProductList</code> and <code>List<Product></code> are different types! Yes, they represent the same thing to us on the outside, but they aren&#8217;t the same.</p>
<p>Jeffrey Richter touches upon this very topic in his excellent <a href="http://www.amazon.com/gp/product/0735627045/ref=as_li_tf_tl?ie=UTF8&#038;tag=softwaninjan-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0735627045">CLR via C#</a> book (p. 287, 3rd ed.):</p>
<blockquote><p>
&#8220;&#8230; you should never define a new class explicitly for the purpose of making your source code easier to read. The reason is because you lose type identity and equivalence&#8230;&#8221;</p></blockquote>
<p>He continues with an example to demonstrate, similar to what follows, which evaluates to <em>false</em>:</p>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
bool sameType = typeof(List&lt;Product&gt;) == typeof(ProductList); // false
</pre>
<p>With that in mind, it&#8217;s clear why casting won&#8217;t work. Likewise, the <code>as</code> operator returns a null value since, by definition, if the conversion fails it will return null instead of throwing an exception.</p>
<p>Another important point (also raised in the book) is that this approach prevents <code>List&lt;T&gt;</code> from being passed to a method that expects the new class which inherits from <code>List&lt;T&gt;</code> as a parameter. However, going in the opposite direction is allowed. In other words, passing a <code>List&lt;Product&gt;</code> to a method that accepts a <code>ProductList</code> would fail, but passing a <code>ProductList</code> to a method expecting <code>List&lt;Product&gt;</code> is valid since <code>ProductList</code> inherits from <code>List&lt;Product&gt;</code>.</p>
<h3>Solution</h3>
<p>To meet the challenge I wrote the following extension method:</p>
<pre class="brush: csharp; title: ; notranslate">
public static TCollection SkipFirst&lt;T, TCollection&gt;
    (this ICollection&lt;T&gt; input)
        where TCollection : ICollection&lt;T&gt;, new()
{
    var processedItems = input.Skip(1);

    var result = new TCollection();
    foreach (T item in processedItems)
    {
        result.Add(item);
    }

    return result;
}
</pre>
<p>Usage:</p>
<pre class="brush: csharp; gutter: false; title: ; notranslate">
ProductList result = list.SkipFirst&lt;Product, ProductList&gt;();
</pre>
<p>There you go! Nice and succinct. No casting, and no need for the extra line of code to use AutoMapper. The key to this puzzle was to return <code>TCollection</code>, instead of a <code>List&lt;T&gt;</code>. Furthermore, adding the generic constraints ensures that <code>TCollection</code> implements <code>ICollection&lt;T&gt;</code> and has a public parameterless constructor in order to new up an instance of the class.</p>
<p>Note that <code>List&lt;T&gt;</code> and <code>IList&lt;T&gt;</code> could&#8217;ve been used in the extension method.</p>
<h3>Implementing custom collections and public APIs</h3>
<p>For simplicity&#8217;s sake it&#8217;s not uncommon to see a subclass of <code>List&lt;T&gt;</code>. Perhaps this is acceptable for internal usage, however it isn&#8217;t recommended when exposed in a <em>public API</em>. This issue has been <a href="http://stackoverflow.com/q/5376203/59111" title="Inherit List&lt;T&gt;" target="_blank">brought up</a> <a href="http://stackoverflow.com/q/3748931/59111" title="Inheriting List&lt;T&gt; to implement collections a bad idea?" target="_blank">numerous</a> <a href="http://stackoverflow.com/q/21715/59111" title="List&lt;BusinessObject&gt; or BusinessObjectCollection?" target="_blank">times</a>. If a custom collection needs to have special behavior then it&#8217;s possible to change the collection&#8217;s implementation if inheriting from classes meant to be extended.</p>
<p>To paraphrase <a href="blogs.msdn.com/b/kcwalina/archive/2005/09/26/474010.aspx" title="Why we don't recommend using List&lt;T&gt; in public APIs">Krzysztof Cwalina</a>, co-author of the .NET <a href="http://www.amazon.com/gp/product/0321545613/ref=as_li_tf_tl?ie=UTF8&#038;tag=softwaninjan-20&#038;linkCode=as2&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0321545613">Framework Design Guidelines</a>, <code>List&lt;T&gt;</code> wasn&#8217;t meant to be extended, unlike <code>Collection&lt;T&gt;</code> which lets you override its members and supports awareness of item modification. Also, <code>List&lt;T&gt;</code> returns a rich set of members that typically aren&#8217;t appropriate for all scenarios.</p>
<p>This guideline is also covered by a Code Analysis warning, <a href="http://msdn.microsoft.com/en-us/library/ms182142.aspx" title="CA1002: Do not expose generic lists" target="_blank">CA1002: Do not expose generic lists</a>. David Kean, a member of the Code Analysis team, expanded on this warning with supporting code examples in the post titled <a href="http://blogs.msdn.com/b/codeanalysis/archive/2006/04/27/faq-why-does-donotexposegenericlists-recommend-that-i-expose-collection-lt-t-gt-instead-of-list-lt-t-gt-david-kean.aspx" title="FAQ: Why does DoNotExposeGenericLists recommend that I expose Collection&lt;T&gt; instead of List&lt;T&gt;?">FAQ: Why does DoNotExposeGenericLists recommend that I expose Collection&lt;T&gt; instead of List&lt;T&gt;?</a></p>
<p>Published by Ahmad Mageed on <a href="http://softwareninjaneer.com/blog">Software Ninjaneer</a></p>]]></content:encoded>
			<wfw:commentRss>http://softwareninjaneer.com/blog/2012/03/05/returning-classes-that-inherit-listt-using-a-generic-method/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Designating different audio devices for playback and communication on Windows 7</title>
		<link>http://softwareninjaneer.com/blog/2012/02/25/designating-different-audio-devices-for-playback-and-communication-on-windows-7/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=designating-different-audio-devices-for-playback-and-communication-on-windows-7</link>
		<comments>http://softwareninjaneer.com/blog/2012/02/25/designating-different-audio-devices-for-playback-and-communication-on-windows-7/#comments</comments>
		<pubDate>Sat, 25 Feb 2012 21:57:57 +0000</pubDate>
		<dc:creator>Ahmad Mageed</dc:creator>
				<category><![CDATA[windows7]]></category>

		<guid isPermaLink="false">http://softwareninjaneer.com/blog/?p=241</guid>
		<description><![CDATA[<p><p>Original post: <a href="http://softwareninjaneer.com/blog/2012/02/25/designating-different-audio-devices-for-playback-and-communication-on-windows-7/">Designating different audio devices for playback and communication on Windows 7</a></p><p>My desktop is hooked up to external speakers, which all audio is emitted from. However, if I want to jump on a Skype call (or similar), all sound is routed to the USB headset as soon as I plug it in. This is great for the duration of the call, but since I have Pandora running almost constantly, or might want to watch (and hear) a video, I don&#8217;t want to wear the headset all day. Plus, if I kept it plugged in I might miss all audio cues from Outlook, Skype notifications, and so on. True, most programs have visual cues too, but I might not be looking at that portion of the screen, or at the monitor the application lives on in the case of dual monitors. I also didn&#8217;t want to keep plugging and unplugging the USB, which meant I had to use an accessible USB slot instead of one behind the desktop &#8211; let&#8217;s face it, who wants to see a distracting bunch of cable near them? Determined to find a solution to a seemingly simple need, I played around with the sound settings. Originally I thought there might be a way to specify the audio device on a per application basis. Instead, I was happy to find a user-friendly option that&#8217;s built right into Windows 7 (maybe Vista too, not sure, but you&#8217;re not really using that are you?). Essentially, Windows 7 allows us to specify a default device and a default communications device. Without further ado, here&#8217;s how I set it up! Setting up playback devices Step 1: Right-click the volume control, and select &#8220;Playback devices&#8221; This will bring up the Sound control panel, which will look similar to the following image. On the Playback tab notice that the USB headset is currently set as the default device. Your setup might be different, which is fine since the next couple of steps are the important ones. Step 2: set your desired speakers as the default device. A green check-mark icon will appear next to it. Step 3: set the USB headset as the default communication device. Upon doing so a green phone icon will appear next to it. The final setup should resemble the image below. That&#8217;s it! With the above setup I can now leave my USB headset plugged in, and only use it when speaking to someone on Skype or attending an online presentation. In the meantime all my audio is coming from my external speakers. Controlling other sounds when placing a call Windows 7 provides a neat feature that adjusts the sound from other devices when using the communications device. The feature is known as ducking, or stream attenuation. By default, I found that the volume was lowered by 80% when I initiated a Skype call. It&#8217;s a reasonable default, but I prefer to completely mute all other sounds. To do so, bring up the Sound control panel again, select the Communications tab, then choose your desired option.</p></p><p>Published by Ahmad Mageed on <a href="http://softwareninjaneer.com/blog">Software Ninjaneer</a></p>]]></description>
				<content:encoded><![CDATA[<p>Original post: <a href="http://softwareninjaneer.com/blog/2012/02/25/designating-different-audio-devices-for-playback-and-communication-on-windows-7/">Designating different audio devices for playback and communication on Windows 7</a></p><p>My desktop is hooked up to external speakers, which all audio is emitted from. However, if I want to jump on a Skype call (or similar), all sound is routed to the USB headset as soon as I plug it in. This is great for the duration of the call, but since I have Pandora running almost constantly, or might want to watch (and hear) a video, I don&#8217;t want to wear the headset all day. Plus, if I kept it plugged in I might miss all audio cues from Outlook, Skype notifications, and so on. True, most programs have visual cues too, but I might not be looking at that portion of the screen, or at the monitor the application lives on in the case of dual monitors.</p>
<p>I also didn&#8217;t want to keep plugging and unplugging the USB, which meant I had to use an accessible USB slot instead of one behind the desktop &#8211; let&#8217;s face it, who wants to see a distracting bunch of cable near them?</p>
<p>Determined to find a solution to a seemingly simple need, I played around with the sound settings. Originally I thought there might be a way to specify the audio device on a per application basis. Instead, I was happy to find a user-friendly option that&#8217;s built right into Windows 7 (maybe Vista too, not sure, but you&#8217;re not really using that are you?). Essentially, Windows 7 allows us to specify a <em>default device</em> and a <em>default communications device</em>. Without further ado, here&#8217;s how I set it up!</p>
<h3>Setting up playback devices</h3>
<p><strong>Step 1:</strong> Right-click the volume control, and select <em>&#8220;Playback devices&#8221;</em></p>
<p><a href="http://softwareninjaneer.com/blog/wp-content/uploads/2012/02/VolumeMenu.png"><img class="aligncenter size-full wp-image-246" title="VolumeMenu" src="http://softwareninjaneer.com/blog/wp-content/uploads/2012/02/VolumeMenu.png" alt="Volume Menu to select Playback devices" width="210" height="150" /></a></p>
<p>This will bring up the Sound control panel, which will look similar to the following image. On the <em>Playback</em> tab notice that the USB headset is currently set as the default device. Your setup might be different, which is fine since the next couple of steps are the important ones.</p>
<p><a href="http://softwareninjaneer.com/blog/wp-content/uploads/2012/02/SoundDialog.png"><img class="aligncenter size-full wp-image-249" title="SoundDialog" src="http://softwareninjaneer.com/blog/wp-content/uploads/2012/02/SoundDialog.png" alt="Sound dialog with USB headset plugged in" width="414" height="222" /></a></p>
<p><strong>Step 2:</strong> set your desired speakers as the default device. A green check-mark icon will appear next to it.</p>
<p><a href="http://softwareninjaneer.com/blog/wp-content/uploads/2012/02/SoundDialogSetDefault.png"><img class="aligncenter size-full wp-image-250" title="SoundDialogSetDefault" src="http://softwareninjaneer.com/blog/wp-content/uploads/2012/02/SoundDialogSetDefault.png" alt="Set default device" width="414" height="461" /></a></p>
<p><strong>Step 3:</strong> set the USB headset as the default communication device.</p>
<p><a href="http://softwareninjaneer.com/blog/wp-content/uploads/2012/02/SoundDialogSetCommunication.png"><img class="aligncenter size-full wp-image-251" title="SoundDialogSetCommunication" src="http://softwareninjaneer.com/blog/wp-content/uploads/2012/02/SoundDialogSetCommunication.png" alt="Set the default communication device" width="358" height="252" /></a></p>
<p>Upon doing so a green phone icon will appear next to it. The final setup should resemble the image below.</p>
<p><a href="http://softwareninjaneer.com/blog/wp-content/uploads/2012/02/SoundDialogResult.png"><img class="aligncenter size-full wp-image-252" title="SoundDialogResult" src="http://softwareninjaneer.com/blog/wp-content/uploads/2012/02/SoundDialogResult.png" alt="Different playback devices set to default and communications" width="352" height="111" /></a></p>
<p>That&#8217;s it! With the above setup I can now leave my USB headset plugged in, and only use it when speaking to someone on Skype or attending an online presentation. In the meantime all my audio is coming from my external speakers.</p>
<h3>Controlling other sounds when placing a call</h3>
<p>Windows 7 provides a neat feature that adjusts the sound from other devices when using the communications device. The feature is known as <a title="Default ducking experience" href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd316773%28v=vs.85%29.aspx">ducking, or stream attenuation</a>. By default, I found that the volume was lowered by 80% when I initiated a Skype call. It&#8217;s a reasonable default, but I prefer to completely mute all other sounds. To do so, bring up the Sound control panel again, select the <em>Communications</em> tab, then choose your desired option.</p>
<p><a href="http://softwareninjaneer.com/blog/wp-content/uploads/2012/02/SoundDialogCommunicationsDucking.png"><img class="aligncenter size-full wp-image-254" title="SoundDialogCommunicationsDucking" src="http://softwareninjaneer.com/blog/wp-content/uploads/2012/02/SoundDialogCommunicationsDucking.png" alt="Ducking (stream attenuation) options" width="414" height="267" /></a></p>
<p>Published by Ahmad Mageed on <a href="http://softwareninjaneer.com/blog">Software Ninjaneer</a></p>]]></content:encoded>
			<wfw:commentRss>http://softwareninjaneer.com/blog/2012/02/25/designating-different-audio-devices-for-playback-and-communication-on-windows-7/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Productivity tip: delimiting multiple lines with your IDE</title>
		<link>http://softwareninjaneer.com/blog/2012/01/11/productivity-tip-delimiting-multiple-lines-with-your-ide/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=productivity-tip-delimiting-multiple-lines-with-your-ide</link>
		<comments>http://softwareninjaneer.com/blog/2012/01/11/productivity-tip-delimiting-multiple-lines-with-your-ide/#comments</comments>
		<pubDate>Wed, 11 Jan 2012 17:47:36 +0000</pubDate>
		<dc:creator>Ahmad Mageed</dc:creator>
				<category><![CDATA[productivity]]></category>
		<category><![CDATA[regex]]></category>

		<guid isPermaLink="false">http://softwareninjaneer.com/blog/?p=153</guid>
		<description><![CDATA[<p><p>Original post: <a href="http://softwareninjaneer.com/blog/2012/01/11/productivity-tip-delimiting-multiple-lines-with-your-ide/">Productivity tip: delimiting multiple lines with your IDE</a></p><p>During development I&#8217;ve had the need to delimit a number of lines with a character. Sometimes these lines are numerous and the task is mind-numbingly tedious if I have to sit there and do it manually. Imagine you&#8217;re working with SQL and have a list of ProductId values on separate lines in your clipboard: 1 12 123 1234 You want to include these values when using the IN keyword: The goal is to place commas before the numbers, or after the numbers, as shown below. This is the order most people take: Paste numbers between the parentheses Position cursor at the start (or end) of the line with the arrow keys (bad) or Home/End key (better) Insert comma Move to the next line Repeat N &#8211; 1 times There&#8217;s got to be a better way to do this right? Right! The two techniques I&#8217;ll cover in this post are: Column mode selection Find/Replace using regular expressions &#160; Column mode selection The typical selection mode is known as continuous stream selection, which is the default selection via the mouse or is performed by using the Shift + arrow keys. The other mode is column mode, or box mode. It lets you select text in columns with a rectangular portion for vertical editing. Once the columns are selected you have the option of inserting, deleting, copying, or pasting text. It&#8217;s also possible to overwrite text (i.e., overstrike) by hitting the Insert key and typing new text. Some IDEs and text-editors support column mode, such as Visual Studio 2010 and Notepad++. In fact, prior versions of Visual Studio supported it, but they didn&#8217;t support text insertion, pasting, or zero-length boxes, which are new features introduced in VS 2010. Thus, it was only good for copying and deleting text. Microsoft SQL Server Management Studio (SSMS, using SQL Server 2008) seems to have the limited pre-VS 2010 support for this, which was the inspiration behind this post&#8217;s second technique. Keyboard approach: Place the cursor at the beginning of the line. Press and hold the Shift + Alt keys, then move the cursor with any arrow key. You will see the cursor flashing on each line you&#8217;ve selected. Type the desired character or text to prefix or delimit the lines with. For this example it&#8217;s a comma: ,. Mouse approach: Place the cursor at the beginning of the line. Press and hold the Alt key, then click the left mouse button and move the cursor over the desired text. Modify text as desired. To clarify, for the purposes of this example the cursor is placed at the beginning of the line. However, column mode can be used anywhere in the text, even in the middle of a word. With regards to the SQL statement earlier, delimiting at the beginning of the lines is probably the best option when using this feature since the text is lined up properly. The end of your lines usually won&#8217;t line up since they might have different lengths. The following screenshot demonstrates selecting the columns and the result after adding commas. There are a number of places where this technique could be useful. In the earlier screenshot showing the stream and column modes, the Hungarian notation could be eliminated easily. Just select the column of &#8220;i&#8221; characters and hit Backspace. Voila! Consider another scenario where you want to add or change the access modifier for a bunch of properties on a class, making them all public&#8230; column mode to the rescue! For additional information refer to: Notepad++ &#8211; Column edit mode Visual Studio 2010 &#8211; How to: Select and Change Text &#160; Find/Replace using regular expressions In case your IDE of choice doesn&#8217;t support column selection, you can still pull this off if you&#8217;re not averse to learning a tiny amount of regex. When I say &#8220;tiny&#8221; I really mean it. All it takes is one regex metacharacter, and you have two to choose from depending on where you want to place the delimiter. To solve this task use the IDE&#8217;s Find/Replace dialog and select the regex option. The two metacharacters of interest are: ^: the caret character matches the position at the beginning of the line $: the dollar sign matches the position at the end of the line These are known as anchors since they match at specific positions. To place the commas before the numbers, use the caret. Otherwise, use the dollar sign to place them after the numbers. The replacement character will be a comma, and you should select the lines to delimit then restrict the replacement to the active selection. The following screenshots show the find/replace dialog setup in Microsoft Visual Studio 2010 before the replacement, and the result after the replacement. Before: After: Similarly, it&#8217;s possible to place the commas at the end of the lines using the dollar sign metacharacter. The following screenshots demonstrate this approach in Notepad++. Before: After: Beware that while most IDEs and text-editors support regex, some only support a subset of metacharacters or may use different metacharacters completely. The good news is the two metacharacters I&#8217;ve introduced are standard amongst most regex flavors, which should make this tip universally applicable. I&#8217;ve used this tip in Microsoft Visual Studio, Notepad++, LINQPad, and SSMS. Note, however, that SSMS exhibits an odd behavior (bug?) when using the caret to delimit at the beginning of the line. It skips the first selected line, resulting in 2 occurrences being replaced instead of the expected 3, per my example. This isn&#8217;t such a big deal, since at that point all you need to do is manually do the work on one line. Alternately, to get around this, I include the line before the target line to delimit in my selection. That means including the line that starts with &#8220;WHERE&#8221; so the replacement skips that line and correctly delimits the remaining lines. That said, SSMS works fine when using the end of line delimiting approach with the dollar sign. Closing thoughts Obviously column mode is much simpler [...]</p></p><p>Published by Ahmad Mageed on <a href="http://softwareninjaneer.com/blog">Software Ninjaneer</a></p>]]></description>
				<content:encoded><![CDATA[<p>Original post: <a href="http://softwareninjaneer.com/blog/2012/01/11/productivity-tip-delimiting-multiple-lines-with-your-ide/">Productivity tip: delimiting multiple lines with your IDE</a></p><p>During development I&#8217;ve had the need to delimit a number of lines with a character. Sometimes these lines are numerous and the task is mind-numbingly tedious if I have to sit there and do it manually.</p>
<p>Imagine you&#8217;re working with SQL and have a list of ProductId values on separate lines in your clipboard:</p>
<blockquote><p>1<br />
12<br />
123<br />
1234</p></blockquote>
<p>You want to include these values when using the IN keyword:</p>
<pre class="brush: sql; title: ; notranslate">
SELECT * FROM Products
WHERE ProductId IN (...)
</pre>
<p>The goal is to place commas before the numbers, or after the numbers, as shown below.</p>
<pre class="brush: sql; title: ; notranslate">
-- commas before
SELECT * FROM Products
WHERE ProductId IN (1
,12
,123
,1234)

-- commas after
SELECT * FROM Products
WHERE ProductId IN (1,
12,
123,
1234)
</pre>
<p>This is the order most people take:</p>
<ol>
<li>Paste numbers between the parentheses</li>
<li>Position cursor at the start (or end) of the line with the arrow keys (bad) or Home/End key (better)</li>
<li>Insert comma</li>
<li>Move to the next line</li>
<li>Repeat N &#8211; 1 times</li>
</ol>
<p></p>
<p>There&#8217;s got to be a better way to do this right? Right!</p>
<p>The two techniques I&#8217;ll cover in this post are:</p>
<ol>
<li><a href="#ColumnMode">Column mode selection</a></li>
<li><a href="#Regex">Find/Replace using regular expressions</a></li>
</ol>
<p><a name="ColumnMode" style="visibility:hidden;">&nbsp;</a></p>
<h3>Column mode selection</h3>
<p>The typical selection mode is known as <em>continuous stream selection</em>, which is the default selection via the mouse or is performed by using the <kbd>Shift</kbd> <strong>+ arrow</strong> keys. The other mode is <strong>column mode</strong>, or <strong>box mode</strong>. It lets you select text in columns with a rectangular portion for vertical editing. Once the columns are selected you have the option of inserting, deleting, copying, or pasting text. It&#8217;s also possible to overwrite text (i.e., overstrike) by hitting the <kbd>Insert</kbd> key and typing new text.</p>
<p><a href="http://softwareninjaneer.com/blog/wp-content/uploads/2012/01/StreamAndColumnSelectionModes.png"><img src="http://softwareninjaneer.com/blog/wp-content/uploads/2012/01/StreamAndColumnSelectionModes.png" alt="Stream and Column selection modes" title="StreamAndColumnSelectionModes" width="140" height="185" class="aligncenter size-full wp-image-201" /></a></p>
<p>Some IDEs and text-editors support column mode, such as Visual Studio 2010 and Notepad++. In fact, prior versions of Visual Studio supported it, but they didn&#8217;t support text insertion, pasting, or zero-length boxes, which are <a href="http://msdn.microsoft.com/en-us/library/dd465268.aspx" title="What's New in the Visual Studio 2010 Editor">new features introduced in VS 2010</a>. Thus, it was only good for copying and deleting text. Microsoft SQL Server Management Studio (SSMS, using SQL Server 2008) seems to have the limited pre-VS 2010 support for this, which was the inspiration behind this post&#8217;s <a href="#Regex">second technique</a>.</p>
<h4>Keyboard approach:</h4>
<ol>
<li>Place the cursor at the beginning of the line.</li>
<li>Press and hold the <kbd>Shift</kbd> + <kbd>Alt</kbd> keys, then move the cursor with any <strong>arrow key</strong>. You will see the cursor flashing on each line you&#8217;ve selected.</li>
<li>Type the desired character or text to prefix or delimit the lines with. For this example it&#8217;s a comma: <kbd>,</kbd>.</li>
</ol>
<p></p>
<h4>Mouse approach:</h4>
<ol>
<li>Place the cursor at the beginning of the line.</li>
<li>Press and hold the <kbd>Alt</kbd> key, then click the left mouse button and move the cursor over the desired text.</li>
<li>Modify text as desired.</li>
</ol>
<p></p>
<p>To clarify, for the purposes of this example the cursor is placed at the beginning of the line. However, column mode can be used anywhere in the text, even in the middle of a word.</p>
<p>With regards to the SQL statement earlier, delimiting at the beginning of the lines is probably the best option when using this feature since the text is lined up properly. The end of your lines usually won&#8217;t line up since they might have different lengths. The following screenshot demonstrates selecting the columns and the result after adding commas.</p>
<p><a href="http://softwareninjaneer.com/blog/wp-content/uploads/2012/01/ColumnSelection.png"><img src="http://softwareninjaneer.com/blog/wp-content/uploads/2012/01/ColumnSelection.png" alt="Column selection and result of inserting commas" title="ColumnSelection" width="489" height="175" class="aligncenter size-full wp-image-202" /></a></p>
<p>There are a number of places where this technique could be useful. In the earlier screenshot showing the stream and column modes, the Hungarian notation could be eliminated easily. Just select the column of &#8220;i&#8221; characters and hit <kbd>Backspace</kbd>. Voila! Consider another scenario where you want to add or change the access modifier for a bunch of properties on a class, making them all <code>public</code>&#8230; column mode to the rescue!</p>
<p><a href="http://softwareninjaneer.com/blog/wp-content/uploads/2012/01/ColumnSelectionPersonClass.png"><img src="http://softwareninjaneer.com/blog/wp-content/uploads/2012/01/ColumnSelectionPersonClass.png" alt="Column selection to add access modifiers to class properties" title="ColumnSelectionPersonClass" width="659" height="156" class="aligncenter size-full wp-image-205" /></a></p>
<p>For additional information refer to:</p>
<ul>
<li>Notepad++ &#8211; <a href="http://npp-community.tuxfamily.org/documentation/notepad-user-manual/editing/column-mode-editing" title="Column edit mode in Notepad++">Column edit mode</a></li>
<li>Visual Studio 2010 &#8211; <a href="http://msdn.microsoft.com/en-us/library/729s2dhh.aspx" title="Selecting and changing text in Visual Studio 2010">How to: Select and Change Text</a></li>
</ul>
<p><a name="Regex" style="visibility:hidden;">&nbsp;</a></p>
<h3>Find/Replace using regular expressions</h3>
<p>In case your IDE of choice doesn&#8217;t support column selection, you can still pull this off if you&#8217;re not averse to learning a tiny amount of regex. When I say &#8220;tiny&#8221; I really mean it. All it takes is one regex metacharacter, and you have two to choose from depending on where you want to place the delimiter.</p>
<p><center><a href="http://cheezburger.com/View/5656160768" style="text-decoration: none; border-width: 0;"><img id="_r_a_5656160768" class="event-item-lol-image" title="Regex?  oh noes!!!" src="http://images.cheezburger.com/completestore/2012/1/5/62311133-3d91-4df8-aedb-566c75a9ef22.jpg" alt="Regex?  oh noes!!!" /></a></center></p>
<p>To solve this task use the IDE&#8217;s Find/Replace dialog and select the regex option. The two metacharacters of interest are:</p>
<ul>
<li><strong>^</strong>: the caret character matches the position at the beginning of the line</li>
<li><strong>$</strong>: the dollar sign matches the position at the end of the line</li>
</ul>
<p></p>
<p>These are known as <a title="Regex Anchors" href="http://www.regular-expressions.info/anchors.html">anchors</a> since they match at specific positions.</p>
<p>To place the commas before the numbers, use the caret. Otherwise, use the dollar sign to place them after the numbers. The replacement character will be a comma, and you should select the lines to delimit then restrict the replacement to the active selection.</p>
<p>The following screenshots show the find/replace dialog setup in Microsoft Visual Studio 2010 before the replacement, and the result after the replacement.</p>
<p><strong>Before:</strong></p>
<p style="text-align: center;"><a href="http://softwareninjaneer.com/blog/wp-content/uploads/2012/01/IdeRegexDelimitLineStart.png"><img class="aligncenter size-full wp-image-171" title="IdeRegexDelimitLineStart" src="http://softwareninjaneer.com/blog/wp-content/uploads/2012/01/IdeRegexDelimitLineStart.png" alt="Delimiting the beginning of lines via regex" width="466" height="425" /></a></p>
<p><strong>After:</strong></p>
<p style="text-align: center;"><a href="http://softwareninjaneer.com/blog/wp-content/uploads/2012/01/IdeRegexDelimitLineStartResult.png"><img class="aligncenter size-full wp-image-172" title="IdeRegexDelimitLineStartResult" src="http://softwareninjaneer.com/blog/wp-content/uploads/2012/01/IdeRegexDelimitLineStartResult.png" alt="Result of delimiting the beginning of lines via regex" width="459" height="315" /></a></p>
<p>Similarly, it&#8217;s possible to place the commas at the end of the lines using the dollar sign metacharacter. The following screenshots demonstrate this approach in Notepad++.</p>
<p><strong>Before:</strong><br />
<a href="http://softwareninjaneer.com/blog/wp-content/uploads/2012/01/IdeRegexDelimitLineEnd.png"><img src="http://softwareninjaneer.com/blog/wp-content/uploads/2012/01/IdeRegexDelimitLineEnd.png" alt="Delimiting the end of lines via regex" title="IdeRegexDelimitLineEnd" width="587" height="437" class="aligncenter size-full wp-image-181" /></a><br />
<strong>After:</strong><br />
<a href="http://softwareninjaneer.com/blog/wp-content/uploads/2012/01/IdeRegexDelimitLineEndResult.png"><img src="http://softwareninjaneer.com/blog/wp-content/uploads/2012/01/IdeRegexDelimitLineEndResult.png" alt="Result of delimiting end lines" title="IdeRegexDelimitLineEndResult" width="297" height="212" class="aligncenter size-full wp-image-182" /></a></p>
<p>Beware that while most IDEs and text-editors support regex, some only support a subset of metacharacters or may use different metacharacters completely. The good news is the two metacharacters I&#8217;ve introduced are standard amongst most regex flavors, which should make this tip universally applicable. I&#8217;ve used this tip in Microsoft Visual Studio, Notepad++, LINQPad, and SSMS.</p>
<p>Note, however, that SSMS exhibits an odd behavior (bug?) when using the caret to delimit at the beginning of the line. It skips the first selected line, resulting in 2 occurrences being replaced instead of the expected 3, per my example. This isn&#8217;t such a big deal, since at that point all you need to do is manually do the work on one line. Alternately, to get around this, I include the line before the target line to delimit in my selection. That means including the line that starts with &#8220;WHERE&#8221; so the replacement skips that line and correctly delimits the remaining lines. That said, SSMS works fine when using the end of line delimiting approach with the dollar sign.</p>
<h3>Closing thoughts</h3>
<p>Obviously column mode is much simpler than using find/replace and regex. If you have that option, use it. Nonetheless, regex is extremely useful for other scenarios where you want to locate a string or series of characters in a certain pattern, then not only add a prefix or suffix to it, but re-use portions of the original input in the replacement. To do so, knowledge of regex comes in handy and can let you pull off such complex text manipulation tasks. Perhaps that&#8217;s a post for another day!</p>
<p>For the purposes of this post, however, I&#8217;ve only covered delimiting at the start and end of a string and detailed a comparable one to one solution for the column mode and regex approaches.</p>
<p>Published by Ahmad Mageed on <a href="http://softwareninjaneer.com/blog">Software Ninjaneer</a></p>]]></content:encoded>
			<wfw:commentRss>http://softwareninjaneer.com/blog/2012/01/11/productivity-tip-delimiting-multiple-lines-with-your-ide/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Enumerating weakly typed collections with implicitly typed variables</title>
		<link>http://softwareninjaneer.com/blog/2011/11/27/enumerating-weakly-typed-collections-with-implicitly-typed-variables/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=enumerating-weakly-typed-collections-with-implicitly-typed-variables</link>
		<comments>http://softwareninjaneer.com/blog/2011/11/27/enumerating-weakly-typed-collections-with-implicitly-typed-variables/#comments</comments>
		<pubDate>Sun, 27 Nov 2011 18:28:23 +0000</pubDate>
		<dc:creator>Ahmad Mageed</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[linq]]></category>

		<guid isPermaLink="false">http://softwareninjaneer.com/blog/?p=111</guid>
		<description><![CDATA[<p><p>Original post: <a href="http://softwareninjaneer.com/blog/2011/11/27/enumerating-weakly-typed-collections-with-implicitly-typed-variables/">Enumerating weakly typed collections with implicitly typed variables</a></p><p>The advent of C# 3.0 introduced the ability to use implicitly typed local variables via the var keyword. Usage of var has flourished since then, and while some people use it judiciously, others make liberal use of it. Ultimately, most people are bound to run into a scenario where it surprisingly ceases to behave properly. Suddenly using var in a foreach loop causes IntelliSense to stop working properly, and an error is generated upon compiling. The scenario I&#8217;m referring to is enumerating over weakly typed collections. This is common when working with COM, Microsoft Office interop, an ArrayList, and any collection that returns a non-generic IEnumerable (i.e., an IEnumerable&#60;object&#62;). I&#8217;ll use this simple Car class to demonstrate in the upcoming examples: Now, consider the following example: As I write the line inside the foreach loop, I immediately notice something fishy. When I type "c." the IntelliSense suggestions pop up, but the properties on the Car class are missing! I expect to see Make, Model, and IsHybrid in the popup, but they are visibly absent. What gives? Since ArrayList returns an IEnumerable&#60;object&#62; the usage of var results in the variable c being an object type. With this in mind, it makes sense that the only IntelliSense items available are the ones that are defined on all objects. Ignoring this early warning that something is amiss, attempting to compile the code would generate this error: &#8216;object&#8217; does not contain a definition for &#8216;Make&#8217; and no extension method &#8216;Make&#8217; accepting a first argument of type &#8216;object&#8217; could be found (are you missing a using directive or an assembly reference?) Workaround #1: Be explicit The most straightforward solution is to use an explicitly typed local variable. In this case, we would use Car instead of var. The updated code will make IntelliSense work as expected, and compiles correctly. So what&#8217;s the difference and why does this approach work? Allow me to refer to the C# language specification in order to &#8220;PhD things up,&#8221; as one of my co-workers fondly enjoys accusing me of doing occasionally! Essentially, it works because an implicit cast is occurring within the foreach. Section 8.8.4 of the spec (version 4.0) details how the foreach statement determines the type when var is specified. A bunch of steps take place to determine the type, and they are beyond the scope of this post, however the relevant part of the spec that this falls under occurs when the compiler checks for an enumerable interface. In particular, the spec states: Otherwise, if there is an implicit conversion from X to the System.Collections.IEnumerable interface, then the collection type is this interface, the enumerator type is the interface System.Collections.IEnumerator, and the element type is object. The spec also shows the individual components of the foreach statement and its expansion, which clarifies how the casting occurs. Workaround #2: LINQ to the rescue! With LINQ we can use the Enumerable.Cast method (or Enumerable.OfType) to cast all the elements of the IEnumerable to a given type. In our case, we will specify a Car type and the result will be a strongly-typed IEnumerable&#60;Car&#62;. The equivalent query syntax is: Notice that the range variable c is explicitly typed in the from clause and omitting the type by writing from c in cars would have generated this compile-time error: Could not find an implementation of the query pattern for source type &#8216;System.Collections.ArrayList&#8217;. &#8216;Select&#8217; not found. Consider explicitly specifying the type of the range variable &#8216;c&#8217;. Normally, when working with data sources which implement IEnumerable&#60;T&#62;, we can omit the type since the compiler infers it. While the above approaches illustrate the point, the first workaround is the preferred way to deal with this issue unless we plan to do more with the LINQ query. The Enumerable methods are beneficial when constructing a larger LINQ query, allowing us to chain multiple extension methods together. Understanding how extension methods work is vital to appreciate how this all fits together. In brief, Enumerable.Cast extends the IEnumerable type, which is why it is available for use on the cars ArrayList. The result is a strongly-typed IEnumerable&#60;Car&#62;. Since a large majority of extension methods extend IEnumerable&#60;T&#62;, we can begin to use them after using the Cast or OfType extension methods. Even Enumerable.Select, the most basic of extension methods, isn&#8217;t available until one of the aforementioned extension methods is used. As an example of method chaining, the following query can be used to group hybrid and non-hybrid cars together:</p></p><p>Published by Ahmad Mageed on <a href="http://softwareninjaneer.com/blog">Software Ninjaneer</a></p>]]></description>
				<content:encoded><![CDATA[<p>Original post: <a href="http://softwareninjaneer.com/blog/2011/11/27/enumerating-weakly-typed-collections-with-implicitly-typed-variables/">Enumerating weakly typed collections with implicitly typed variables</a></p><p>The advent of C# 3.0 introduced the ability to use implicitly typed local variables via the <a title="var keyword reference" href="http://msdn.microsoft.com/en-us/library/bb383973.aspx"><code>var</code> keyword</a>. Usage of <code>var</code> has flourished since then, and while some people use it judiciously, others make liberal use of it. Ultimately, most people are bound to run into a scenario where it surprisingly ceases to behave properly. Suddenly using <code>var</code> in a foreach loop causes IntelliSense to stop working properly, and an error is generated upon compiling.</p>
<p>The scenario I&#8217;m referring to is enumerating over weakly typed collections. This is common when working with COM, Microsoft Office interop, an <code>ArrayList</code>, and any collection that returns a non-generic <code>IEnumerable</code> (i.e., an <code>IEnumerable&lt;object&gt;</code>).</p>
<p>I&#8217;ll use this simple <code>Car</code> class to demonstrate in the upcoming examples:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Car
{
    public string Make { get; set; }
    public string Model { get; set; }
    public bool IsHybrid { get; set; }

    public Car(string make, string model, bool isHybrid)
    {
        Make = make;
        Model = model;
        IsHybrid = isHybrid;
    }
}
</pre>
<p>Now, consider the following example:</p>
<pre class="brush: csharp; title: ; notranslate">
var cars = new ArrayList()
{
    new Car(&quot;BMW&quot;, &quot;335i&quot;, false),
    new Car(&quot;Infiniti&quot;, &quot;G37&quot;, false),
    new Car(&quot;Toyota&quot;, &quot;Prius&quot;, true)
};

foreach (var c in cars)
{
    Console.WriteLine(c.Make);
}
</pre>
<p>As I write the line inside the foreach loop, I immediately notice something fishy. When I type <code>"c."</code> the IntelliSense suggestions pop up, but the properties on the <code>Car</code> class are missing! I expect to see <code>Make</code>, <code>Model</code>, and <code>IsHybrid</code> in the popup, but they are visibly absent. What gives?</p>
<div id="attachment_119" class="wp-caption aligncenter" style="width: 311px"><a href="http://softwareninjaneer.com/blog/wp-content/uploads/2011/11/CarNoIntelliSense.png"><img class="size-full wp-image-119" title="Car object missing properties" src="http://softwareninjaneer.com/blog/wp-content/uploads/2011/11/CarNoIntelliSense.png" alt="Screenshot of IntelliSense and missing properties" width="301" height="132" /></a>
<p class="wp-caption-text">Screenshot of IntelliSense and missing properties</p>
</div>
<p>Since <code>ArrayList</code> returns an <code>IEnumerable&lt;object&gt;</code> the usage of <code>var</code> results in the variable <code>c</code> being an <code>object</code> type. With this in mind, it makes sense that the only IntelliSense items available are the ones that are defined on all objects.</p>
<p>Ignoring this early warning that something is amiss, attempting to compile the code would generate this error:</p>
<blockquote><p>&#8216;object&#8217; does not contain a definition for &#8216;Make&#8217; and no extension method &#8216;Make&#8217; accepting a first argument of type &#8216;object&#8217; could be found (are you missing a using directive or an assembly reference?)</p></blockquote>
<h3>Workaround #1: Be explicit</h3>
<p>The most straightforward solution is to use an explicitly typed local variable. In this case, we would use <code>Car</code> instead of <code>var</code>. The updated code will make IntelliSense work as expected, and compiles correctly.</p>
<pre class="brush: csharp; title: ; notranslate">
foreach (Car c in cars)
{
    Console.WriteLine(c.Make);
}
</pre>
<p>So what&#8217;s the difference and why does this approach work? Allow me to refer to the C# language specification in order to &#8220;PhD things up,&#8221; as one of my co-workers fondly enjoys accusing me of doing occasionally! Essentially, it works because an implicit cast is occurring within the foreach. Section 8.8.4 of the spec (version 4.0) details how the <code>foreach</code> statement determines the type when <code>var</code> is specified. A bunch of steps take place to determine the type, and they are beyond the scope of this post, however the relevant part of the spec that this falls under occurs when the compiler checks for an enumerable interface. In particular, the spec states:</p>
<blockquote><p>Otherwise, if there is an implicit conversion from X to the System.Collections.IEnumerable interface, then the collection type is this interface, the enumerator type is the interface System.Collections.IEnumerator, and the element type is object.
</p></blockquote>
<p>The spec also shows the individual components of the <code>foreach</code> statement and its expansion, which clarifies how the casting occurs.</p>
<h3>Workaround #2: LINQ to the rescue!</h3>
<p>With LINQ we can use the <a title="Enumerable.Cast method" href="http://msdn.microsoft.com/en-us/library/bb341406.aspx">Enumerable.Cast method</a> (or <a title="Enumerable.OfType method" href="http://msdn.microsoft.com/en-us/library/bb360913.aspx">Enumerable.OfType</a>) to cast all the elements of the <code>IEnumerable</code> to a given type. In our case, we will specify a <code>Car</code> type and the result will be a strongly-typed <code>IEnumerable&lt;Car&gt;</code>.</p>
<pre class="brush: csharp; title: ; notranslate">
foreach (var c in cars.Cast&lt;Car&gt;())
{
    Console.WriteLine(c.Make);
}
</pre>
<p>The equivalent query syntax is:</p>
<pre class="brush: csharp; title: ; notranslate">
var query = from Car c in cars
            select c;

foreach (var c in query)
{
    Console.WriteLine(c.Make);
}
</pre>
<p>Notice that the range variable <code>c</code> is explicitly typed in the <a href="http://msdn.microsoft.com/en-us/library/bb383978.aspx" title="LINQ from clause">from clause</a> and omitting the type by writing <code>from c in cars</code> would have generated this compile-time error:</p>
<blockquote><p>Could not find an implementation of the query pattern for source type &#8216;System.Collections.ArrayList&#8217;.  &#8216;Select&#8217; not found.  Consider explicitly specifying the type of the range variable &#8216;c&#8217;.</p></blockquote>
<p>Normally, when working with data sources which implement IEnumerable&lt;T&gt;, we can omit the type since the compiler infers it.</p>
<p>While the above approaches illustrate the point, the first workaround is the preferred way to deal with this issue unless we plan to do more with the LINQ query. The <code>Enumerable</code> methods are beneficial when constructing a larger LINQ query, allowing us to chain multiple extension methods together. Understanding how <a title="C# extension methods" href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension methods</a> work is vital to appreciate how this all fits together.</p>
<p>In brief, <code>Enumerable.Cast</code> extends the <code>IEnumerable</code> type, which is why it is available for use on the <code>cars ArrayList</code>. The result is a strongly-typed <code>IEnumerable&lt;Car&gt;</code>. Since a large majority of extension methods extend <code>IEnumerable&lt;T&gt;</code>, we can begin to use them after using the <code>Cast</code> or <code>OfType</code> extension methods. Even <code>Enumerable.Select</code>, the most basic of extension methods, isn&#8217;t available until one of the aforementioned extension methods is used.</p>
<p>As an example of method chaining, the following query can be used to group hybrid and non-hybrid cars together:</p>
<pre class="brush: csharp; title: ; notranslate">
var hybridGroups = cars.Cast&lt;Car&gt;().GroupBy(c =&gt; c.IsHybrid);

foreach (var group in hybridGroups)
{
    Console.WriteLine(&quot;{0} Cars: {1}&quot;,
        group.Key ? &quot;Hybrid&quot; : &quot;Non-Hybrid&quot;,
        group.Count());

    foreach (var c in group)
    {
        Console.WriteLine(&quot;- {0} {1}&quot;, c.Make, c.Model);
    }
}
</pre>
<p>Published by Ahmad Mageed on <a href="http://softwareninjaneer.com/blog">Software Ninjaneer</a></p>]]></content:encoded>
			<wfw:commentRss>http://softwareninjaneer.com/blog/2011/11/27/enumerating-weakly-typed-collections-with-implicitly-typed-variables/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Regex engine updated to allow timeouts in .NET 4.5</title>
		<link>http://softwareninjaneer.com/blog/2011/09/21/regex-engine-updated-to-allow-timeouts-in-net-4-5/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=regex-engine-updated-to-allow-timeouts-in-net-4-5</link>
		<comments>http://softwareninjaneer.com/blog/2011/09/21/regex-engine-updated-to-allow-timeouts-in-net-4-5/#comments</comments>
		<pubDate>Wed, 21 Sep 2011 05:44:03 +0000</pubDate>
		<dc:creator>Ahmad Mageed</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[regex]]></category>

		<guid isPermaLink="false">http://softwareninjaneer.com/blog/?p=19</guid>
		<description><![CDATA[<p><p>Original post: <a href="http://softwareninjaneer.com/blog/2011/09/21/regex-engine-updated-to-allow-timeouts-in-net-4-5/">Regex engine updated to allow timeouts in .NET 4.5</a></p><p>Many new features were listed as part of what&#8217;s new in the .NET Framework 4.5 Developer Preview, but the one that caught my eye was this Regex engine update: Ability to limit how long the regular expression engine will attempt to resolve a regular expression before it times out. Eager to try this feature out I installed the Visual Studio 11 Developer Preview. For what it&#8217;s worth, I initially setup the Windows 8 Developer Preview in VirtualBox and played with Visual Studio 11 there, but that&#8217;s not necessary. I later installed the VS 11 Developer Preview on my machine and it behaved nicely as a side by side install with VS 2010. At the time of this writing this post refers to the .NET Framework 4.5 Developer Preview. The current MSDN documentation about this new feature can be found here. Should the implementation change in the RTM version I will try to update this post accordingly. Why is this feature helpful? If you&#8217;ve written a few regular expressions the chances are you&#8217;ve encountered a pattern that caused the regex engine to take a lengthy amount of time to complete. Some might even claim that the engine hangs and they aren&#8217;t going to wait around to find out if a match is finally returned. Despite the excessive processing time you may have wound up with the correct result. However, the time spent may not be acceptable for your application. Here are a few scenarios where poor regex performance may occur: Accepting user supplied input to perform a search on data. Accepting user supplied regex patterns to search data. Working with large string inputs. Using patterns that suffer from excessive backtracking, back-references, and other factors. The old way of terminating the matching process Imagine providing a web service that allows people to supply regex patterns to test them against their desired data. How do you prevent someone from maliciously &#8211; or accidentally &#8211; bringing down your service with a poor pattern? To address this concern developers would need to handle the regex task asynchronously, measure the amount of time elapsed, and abandon the task if it exceeds a reasonable period of time. Wouldn&#8217;t it be great if some timeout mechanism was built-in? Well, now we have just that! This feature addresses Connect feedback from 2007 and it&#8217;s great to see Microsoft continue to improve the regex engine. Show me what&#8217;s new already! Alright! First I&#8217;ll cover the new pieces of the Regex class, then I&#8217;ll demonstrate with some code. The .NET 4.5 Regex class has been updated to include: New overloaded constructors that accept a matchTimeout parameter of type TimeSpan. This applies to both instances of the Regex class and static usage of the class. If a timeout isn&#8217;t specified it will default to the application-wide default timeout value, if set, or the InfiniteMatchTimeout value otherwise. Support for an application-wide default timeout value specified by setting the &#8220;REGEX_DEFAULT_MATCH_TIMEOUT&#8221; property via the AppDomain.SetData method. A static InfiniteMatchTimeout field member (TimeSpan) which indicates that a pattern matching operation shouldn&#8217;t time out. A MatchTimeout property (TimeSpan) representing the time-out interval of the current instance. When using the static methods this property can be accessed by handling the RegexMatchTimeoutException. Should the matchTimeout be exceeded, or invalid, the following exceptions will be thrown with the given messages: RegexMatchTimeoutException: this exception is thrown when a timeout occurs. The message reads, &#8220;The RegEx engine has timed out while trying to match a pattern to an input string. This can occur for many reasons, including very large inputs or excessive backtracking caused by nested quantifiers, back-references and other factors.&#8221; ArgumentOutOfRangeException: according to the class&#8217; metadata this is thrown when &#8220;options is not a valid RegexOptions value&#8221; or when &#8220;matchTimeout is negative or greater than approximately 24 days.&#8221; The latter part is what&#8217;s new. Although it wasn&#8217;t mentioned explicitly, I found that a value of zero is also considered invalid, which should come as no surprise. Being aware of these two exceptions will be useful when working with the new feature. In addition, handling the TypeInitializationException is useful when using the application-wide timeout default. I&#8217;ll demonstrate all of this in the subsequent sections that follow. Introducing a poor pattern Consider this pattern: ([a-z ]+)*! This is a poor pattern with nested quantifiers that will cause excessive backtracking. It specifies a group that should be matched zero or more times (i.e., optional). The group contains a character class to match lowercase alphabets or the space character, one or more times. Finally, an exclamation mark should be matched. Now, consider this input: &#8220;The quick brown fox jumps&#8221; When I tested the pattern with this input it took an average of 11 seconds to process. I tried using the full pangram but it took way too long, so I stopped at the word &#8220;jumps&#8221; to get an idea of the processing time. As the string grows so will the time needed for the engine to complete it&#8217;s pattern matching attempt. This pattern has an exponential complexity of O(2n). If you&#8217;re interested in the details of what makes this a poor pattern read up on catastrophic backtracking. The code for the above pattern and input looks like this: Try it out. I&#8217;ll wait! Then try it with a longer input and continue reading this post. I suspect it&#8217;ll still be running long after you&#8217;re done reading. Limiting processing time with the matchTimeout parameter Let&#8217;s update the code to make it timeout after 4 seconds: That&#8217;s all there is to it! Now the regex engine will give up and throw an exception if 4 seconds elapse. Also notice the helpful properties accessible from the RegexMatchTimeoutException object. Checking the specified duration with the MatchTimeout property When using an instance of the Regex class you have access to the MatchTimeout property. In the following example I&#8217;ll use a StopWatch and compare the time taken to match a new sentence. Handling invalid matchTimeout durations What happens when we specify an invalid matchTimeout value? As mentioned earlier, an ArgumentOutOfRangeException will be thrown [...]</p></p><p>Published by Ahmad Mageed on <a href="http://softwareninjaneer.com/blog">Software Ninjaneer</a></p>]]></description>
				<content:encoded><![CDATA[<p>Original post: <a href="http://softwareninjaneer.com/blog/2011/09/21/regex-engine-updated-to-allow-timeouts-in-net-4-5/">Regex engine updated to allow timeouts in .NET 4.5</a></p><p>Many new features were listed as part of <a title="What's New in the .NET Framework 4.5 Developer Preview" href="http://msdn.microsoft.com/en-us/library/ms171868(v=vs.110).aspx">what&#8217;s new in the </a><a title="What's New in the .NET Framework 4.5 Developer Preview" href="http://msdn.microsoft.com/en-us/library/ms171868(v=vs.110).aspx">.NET Framework 4.5 Developer Preview</a>, but the one that caught my eye was this Regex engine update:</p>
<blockquote><p><em>Ability to limit how long the regular expression engine will attempt to resolve a regular expression before it times out.</em></p></blockquote>
<p>Eager to try this feature out I installed the <a title="Visual Studio 11 Developer Preview" href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=27543">Visual Studio 11 Developer Preview</a>. For what it&#8217;s worth, I initially setup the Windows 8 Developer Preview in VirtualBox and played with Visual Studio 11 there, but that&#8217;s not necessary. I later installed the VS 11 Developer Preview on my machine and it behaved nicely as a side by side install with VS 2010.</p>
<p>At the time of this writing this post refers to the .NET Framework 4.5 Developer Preview. The current MSDN documentation about this new feature can be found <a title=".NET 4.5 RegularExpressions Namespace" href="http://msdn.microsoft.com/en-us/library/c75he57e%28v=VS.110%29.aspx">here</a>. Should the implementation change in the RTM version I will try to update this post accordingly.</p>
<h2>Why is this feature helpful?</h2>
<p>If you&#8217;ve written a few regular expressions the chances are you&#8217;ve encountered a pattern that caused the regex engine to take a lengthy amount of time to complete. Some might even claim that the engine hangs and they aren&#8217;t going to wait around to find out if a match is finally returned. Despite the excessive processing time you may have wound up with the correct result. However, the time spent may not be acceptable for your application.</p>
<p>Here are a few scenarios where poor regex performance may occur:</p>
<ul>
<li>Accepting user supplied input to perform a search on data.</li>
<li>Accepting user supplied regex patterns to search data.</li>
<li>Working with large string inputs.</li>
<li>Using patterns that suffer from excessive backtracking, back-references, and other factors.</li>
</ul>
<p></p>
<h3>The old way of terminating the matching process</h3>
<p>Imagine providing a web service that allows people to supply regex patterns to test them against their desired data. How do you prevent someone from maliciously &#8211; or accidentally &#8211; bringing down your service with a poor pattern? To address this concern developers would need to handle the regex task asynchronously, measure the amount of time elapsed, and abandon the task if it exceeds a reasonable period of time.</p>
<p>Wouldn&#8217;t it be great if some timeout mechanism was built-in? Well, now we have just that! This feature addresses <a title="Connect request for regex improvements" href="http://connect.microsoft.com/VisualStudio/feedback/details/259625/regular-expression-regex-improvements-timeout-pattern-tester">Connect feedback</a> from 2007 and it&#8217;s great to see Microsoft continue to improve the regex engine.</p>
<h2>Show me what&#8217;s new already!</h2>
<p>Alright! First I&#8217;ll cover the new pieces of the <em>Regex</em> class, then I&#8217;ll demonstrate with some code.</p>
<p>The .NET 4.5 <em>Regex</em> class has been updated to include:</p>
<ul>
<li>New overloaded constructors that accept a <strong><em>matchTimeout</em></strong> parameter of type <em>TimeSpan</em>. This applies to both instances of the <em>Regex</em> class and static usage of the class. If a timeout isn&#8217;t specified it will default to the application-wide default timeout value, if set, or the <strong><em>InfiniteMatchTimeout</em></strong> value otherwise.</li>
<li title="AppDomain.SetData method">Support for an application-wide default timeout value specified by setting the <strong>&#8220;REGEX_DEFAULT_MATCH_TIMEOUT&#8221;</strong> property via the <a title="AppDomain.SetData method" href="http://msdn.microsoft.com/en-us/library/system.appdomain.setdata%28v=VS.110%29.aspx"><strong>AppDomain.SetData</strong></a> method.</li>
<li>A static <strong><a title="Regex.InfiniteMatchTimeout Field" href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.infinitematchtimeout%28v=VS.110%29.aspx"><em>InfiniteMatchTimeout</em></a></strong> field member (<em>TimeSpan</em>) which indicates that a pattern matching operation shouldn&#8217;t time out.</li>
<li>A <strong><em>MatchTimeout</em></strong> property (<em>TimeSpan</em>) representing the time-out interval of the current instance. When using the static methods this property can be accessed by handling the <em>RegexMatchTimeoutException</em>.</li>
</ul>
<p>
<p>
Should the <em><strong>matchTimeout</strong></em> be exceeded, or invalid, the following exceptions will be thrown with the given messages:</p>
<ul>
<li><a title="RegexMatchTimeoutException Class" href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regexmatchtimeoutexception%28v=VS.110%29.aspx"><em><strong>RegexMatchTimeoutException</strong></em></a>: this exception is thrown when a timeout occurs. The message reads, &#8220;The RegEx engine has timed out while trying to match a pattern to an input string. This can occur for many reasons, including very large inputs or excessive backtracking caused by nested quantifiers, back-references and other factors.&#8221;</li>
<li><em><strong>ArgumentOutOfRangeException</strong></em>: according to the class&#8217; metadata this is thrown when &#8220;<em><strong>options</strong></em> is not a valid <em><strong>RegexOptions</strong></em> value&#8221; or when <em>&#8220;</em><strong><em>matchTimeout</em></strong> is negative or greater than approximately 24 days.&#8221; The latter part is what&#8217;s new. Although it wasn&#8217;t mentioned explicitly, I found that a value of zero is also considered invalid, which should come as no surprise.</li>
</ul>
<p>
<p>Being aware of these two exceptions will be useful when working with the new feature. In addition, handling the <a title="TypeInitializationException Class " href="http://msdn.microsoft.com/en-us/library/system.typeinitializationexception.aspx"><strong>TypeInitializationException</strong></a> is useful when using the application-wide timeout default. I&#8217;ll demonstrate all of this in the subsequent sections that follow.</p>
<h3>Introducing a poor pattern</h3>
<p>Consider this pattern: <strong><code>([a-z ]+)*!</code></strong></p>
<p>This is a poor pattern with nested quantifiers that will cause excessive backtracking. It specifies a group that should be matched zero or more times (i.e., optional). The group contains a character class to match lowercase alphabets or the space character, one or more times. Finally, an exclamation mark should be matched.</p>
<p>Now, consider this input: <em>&#8220;The quick brown fox jumps&#8221;</em></p>
<p>When I tested the pattern with this input it took an average of 11 seconds to process. I tried using <a title="The quick brown fox jumps over the lazy dog" href="http://en.wikipedia.org/wiki/The_quick_brown_fox_jumps_over_the_lazy_dog">the full pangram</a> but it took way too long, so I stopped at the word &#8220;jumps&#8221; to get an idea of the processing time. As the string grows so will the time needed for the engine to complete it&#8217;s pattern matching attempt. This pattern has an exponential complexity of O(2<sup>n</sup>).</p>
<p>If you&#8217;re interested in the details of what makes this a poor pattern read up on <a title="Catastrophic backtracking" href="http://www.regular-expressions.info/catastrophic.html">catastrophic backtracking</a>.</p>
<p>The code for the above pattern and input looks like this:</p>
<pre class="brush: csharp; title: ; notranslate">
string input = &quot;The quick brown fox jumps&quot;;
string pattern = @&quot;([a-z ]+)*!&quot;;
bool result = Regex.IsMatch(input, pattern);
</pre>
<p>Try it out. I&#8217;ll wait! Then try it with a longer input and continue reading this post. I suspect it&#8217;ll still be running long after you&#8217;re done reading.</p>
<h3>Limiting processing time with the matchTimeout parameter</h3>
<p>Let&#8217;s update the code to make it timeout after 4 seconds:</p>
<pre class="brush: csharp; title: ; notranslate">
string input = &quot;The quick brown fox jumps over the lazy dog.&quot;;
string pattern = @&quot;([a-z ]+)*!&quot;;
var matchTimeout = TimeSpan.FromSeconds(4);
try
{
    bool result = Regex.IsMatch(input, pattern,
                                RegexOptions.None,
                                matchTimeout);
}
catch (RegexMatchTimeoutException ex)
{
    // handle exception
    Console.WriteLine(&quot;Match timed out!&quot;);
    Console.WriteLine(&quot;- Timeout interval specified: &quot; + ex.MatchTimeout);
    Console.WriteLine(&quot;- Pattern: &quot; + ex.Pattern);
    Console.WriteLine(&quot;- Input: &quot; + ex.Input);
}

/* Output:
Match timed out!
- Timeout interval specified: 00:00:04
- Pattern: ([a-z ]+)*!
- Input: The quick brown fox jumps over the lazy dog.
*/
</pre>
<p>That&#8217;s all there is to it! Now the regex engine will give up and throw an exception if 4 seconds elapse. Also notice the helpful properties accessible from the <em>RegexMatchTimeoutException</em> object.</p>
<h3>Checking the specified duration with the MatchTimeout property</h3>
<p>When using an instance of the <em>Regex</em> class you have access to the <em>MatchTimeout</em> property. In the following example I&#8217;ll use a <em>StopWatch</em> and compare the time taken to match a new sentence.</p>
<pre class="brush: csharp; title: ; notranslate">
string input = &quot;The English alphabet has 26 letters&quot;;
string pattern = @&quot;\d+&quot;;
var matchTimeout = TimeSpan.FromMilliseconds(10);
var sw = Stopwatch.StartNew();
try
{
    var re = new Regex(pattern, RegexOptions.None, matchTimeout);
    bool result = re.IsMatch(input);
    sw.Stop();

    Console.WriteLine(&quot;Completed match in: &quot; + sw.Elapsed);
    Console.WriteLine(&quot;MatchTimeout specified: &quot; + re.MatchTimeout);
    Console.WriteLine(&quot;Matched with {0} to spare!&quot;,
                         re.MatchTimeout.Subtract(sw.Elapsed));
}
catch (RegexMatchTimeoutException ex)
{
    sw.Stop();
    Console.WriteLine(ex.Message);
}

/* Output:
Completed match in: 00:00:00.0007495
MatchTimeout specified: 00:00:00.0100000
Matched with 00:00:00.0092505 to spare!
*/
</pre>
<h3>Handling invalid matchTimeout durations</h3>
<p>What happens when we specify an invalid <em>matchTimeout</em> value? As mentioned earlier, an <em>ArgumentOutOfRangeException</em> will be thrown when <em>matchTimeout</em> is either:</p>
<ul>
<li>Negative (see my comments on <em>Regex.InfiniteMatchTimeout</em> next for an exception to the rule)</li>
<li>Zero</li>
<li>Greater than approximately 24 days</li>
</ul>
<p>
<p>To see this in action, let&#8217;s use the last case. I&#8217;m not sure how Microsoft decided on the ~24 day limit, but if you have a regex taking days to process I would question whether you&#8217;re using the right tool for the job.</p>
<pre class="brush: csharp; title: ; notranslate">
string input = &quot;The quick brown fox jumps over the lazy dog.&quot;;
string pattern = @&quot;([a-z ]+)*!&quot;;

// invalid timeout of 25 days
var matchTimeout = TimeSpan.FromDays(25);
try
{
    var re = new Regex(pattern, RegexOptions.None, matchTimeout);
    bool result = re.IsMatch(input);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.Message);
}

/* Output:
Specified argument was out of the range of valid values.
Parameter name: matchTimeout
*/
</pre>
<h3>To infinity&#8230; and beyond!</h3>
<p>Oddly enough the <em>Regex.InfiniteMatchTimeout</em> field has a negative <em>TimeSpan</em> value of -00:00:00.0010000 (-1 ms) that, when passed as a <em>matchTimeout</em> parameter, doesn&#8217;t cause the <em>ArgumentOutOfRangeException</em> to be thrown. Talk about being exceptional!</p>
<p>So what exactly is its purpose? As stated earlier it&#8217;s used as a default value that indicates a match should not timeout, which is essentially the original pre-.NET 4.5  behavior. It takes effect only when the application-wide default value isn&#8217;t set. Thus, it&#8217;s quite redundant to pass in as a parameter.</p>
<p>To illustrate, these two regex instances share equivalent timeout values (when no application-wide default value is present):</p>
<pre class="brush: csharp; title: ; notranslate">
string pattern = @&quot;\d+&quot;;
var re = new Regex(pattern);
var reInfinite = new Regex(pattern, RegexOptions.None, Regex.InfiniteMatchTimeout);
Console.WriteLine(re.MatchTimeout == reInfinite.MatchTimeout);
// Output: True
</pre>
<h2>Application-wide default match timeout</h2>
<p>To specify an application-wide default timeout value for all regex operations in an application domain you need to set the <strong>&#8220;REGEX_DEFAULT_MATCH_TIMEOUT&#8221;</strong> property. Any regex operation or instance declaration will then use the value assigned to that <em>AppDomain</em> property.</p>
<h3>Setting the AppDomain default value</h3>
<pre class="brush: csharp; title: ; notranslate">
string input = &quot;The quick brown fox jumps over the lazy dog.&quot;;
string pattern = @&quot;([a-z ]+)*!&quot;;

// AppDomain default set somewhere in your application
var defaultMatchTimeout = TimeSpan.FromSeconds(2);
AppDomain.CurrentDomain.SetData(&quot;REGEX_DEFAULT_MATCH_TIMEOUT&quot;,
                                defaultMatchTimeout);

// regex use elsewhere...
var sw = Stopwatch.StartNew();
try
{
    bool result = Regex.IsMatch(input, pattern);
    sw.Stop();
}
catch (RegexMatchTimeoutException ex)
{
    sw.Stop();
    Console.WriteLine(&quot;Match timed out!&quot;);
    Console.WriteLine(&quot;Applied Default: &quot; + ex.MatchTimeout);
}
catch (ArgumentOutOfRangeException ex)
{
    sw.Stop();
}
catch (TypeInitializationException ex)
{
    sw.Stop();
    Console.WriteLine(&quot;TypeInitializationException: &quot; + ex.Message);
    Console.WriteLine(&quot;InnerException: {0} - {1}&quot;,
        ex.InnerException.GetType().Name, ex.InnerException.Message);
}

Console.WriteLine(&quot;AppDomain Default: {0}&quot;,
    AppDomain.CurrentDomain.GetData(&quot;REGEX_DEFAULT_MATCH_TIMEOUT&quot;));
Console.WriteLine(&quot;Stopwatch: &quot; + sw.Elapsed);
</pre>
<p>Woah! What&#8217;s with all that code?! Most of the code is clear. A default value is set in the <em>AppDomain</em> somewhere in your application. Then a regex operation is used without specifying a <em>matchTimeout</em> value and the RegexMatchTimeoutException will be thrown. When the exception is caught it prints out the applied <em>MatchTimeout</em>, which should be the 2 seconds specified for the <em>AppDomain</em> property. Finally the <em>AppDomain</em> property is displayed, along with the elapsed <em>Stopwatch</em> time. The output should be similar to this:</p>
<pre class="brush: csharp; title: ; notranslate">
/* Output:
Match timed out!
Applied Default: 00:00:02
AppDomain Default: 00:00:02
Stopwatch: 00:00:02.0322906
*/
</pre>
<p>Next, notice the catch block that handles the <em>TypeInitializationException</em>. Re-run the code but this time use a negative (invalid) value for the <em>defaultMatchTimeout</em> variable. When the <em>AppDomain</em> property is invalid the <em>Regex</em> class throws this type of exception and the output of the code above then resembles this:</p>
<pre class="brush: csharp; title: ; notranslate">
/* Output:
TypeInitializationException: The type initializer for
'System.Text.RegularExpressions.Regex' threw an exception.
InnerException: ArgumentOutOfRangeException - Specified argument was out of the
range of valid values.
Parameter name: AppDomain data 'REGEX_DEFAULT_MATCH_TIMEOUT' contains an invalid
value or object for specifying a default matching timeout for
System.Text.RegularExpressions.Regex.
AppDomain Default: -00:00:02
Stopwatch: 00:00:00.0550294
*/
</pre>
<h3>Overriding the AppDomain default value</h3>
<p>While you may want to use the application-wide default value in most cases, there are times when you want certain regex operations to use different values. Overriding the <em>AppDomain</em> default is as easy as specifying the <em>matchTimeout</em> parameter.</p>
<p>For example:</p>
<pre class="brush: csharp; title: ; notranslate">
var defaultMatchTimeout = TimeSpan.FromSeconds(5);
AppDomain.CurrentDomain.SetData(&quot;REGEX_DEFAULT_MATCH_TIMEOUT&quot;,
                                defaultMatchTimeout);

string input = &quot;The quick brown fox jumps over the lazy dog.&quot;;
string pattern = @&quot;([a-z ]+)*!&quot;;

var sw = Stopwatch.StartNew();
try
{
    var matchTimeout = TimeSpan.FromSeconds(2);
    bool result = Regex.IsMatch(input, pattern, RegexOptions.None, matchTimeout);
    sw.Stop();
}
catch (RegexMatchTimeoutException ex)
{
    sw.Stop();
    Console.WriteLine(&quot;Match timed out!&quot;);
    Console.WriteLine(&quot;Applied Default: &quot; + ex.MatchTimeout);
}

Console.WriteLine(&quot;AppDomain Default: {0}&quot;,
    AppDomain.CurrentDomain.GetData(&quot;REGEX_DEFAULT_MATCH_TIMEOUT&quot;));
Console.WriteLine(&quot;Stopwatch: &quot; + sw.Elapsed);

/* Output:
Match timed out!
Applied Default: 00:00:02
AppDomain Default: 00:00:05
Stopwatch: 00:00:02.0256260
*/
</pre>
<h2>Recognizing the underlying issues</h2>
<p>While this new feature is great, it&#8217;s important to be cognizant of the underlying issues. Look back at the reasons listed for poor regex performance and ponder over them.</p>
<p>I think this feature is ideal for people who are writing services or features that accept user input. It&#8217;s now a breeze to put an end to potentially rampant patterns. A reasonable timeout duration could be set, or it may even be dynamically assigned based on upfront checks of pattern length and input length for flexibility.</p>
<p>That said, if you&#8217;re the author of poorly performing patterns then using this as a crutch to fall back on isn&#8217;t acceptable. Simply put, take regular expressions seriously and learn to write better patterns by understanding the shortcomings and characteristics of bad patterns.</p>
<h2>Conclusion: Default values, existing Regex utilization and guidance</h2>
<p>By default the <em>Regex</em> class will not timeout. So what should we do about previous uses of <em>Regex</em> in our projects, if anything? The <a title="Regex Class" href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex%28v=VS.110%29.aspx">MSDN documentation</a> states:</p>
<blockquote><p>We recommend that you set a time-out value in all regular expression pattern-matching operations. For more information, see <a title="Best Practices for Regular Expressions in the .NET Framework" href="http://msdn.microsoft.com/en-us/library/gg578045%28v=VS.110%29.aspx">Best Practices for Regular Expressions in the .NET Framework</a>.</p></blockquote>
<p>I have some reservations about doing that all the time. I suggest leaving them alone, for the most part. There&#8217;s no need to hunt down all your regular expressions just to assign a timeout duration to them. That would entail identifying their current performance in order to avoid setting low timeout durations that would cause them to fail. Instead, focus on the patterns with poor performance, time critical usages, or areas where user input is used. If you&#8217;re aware of problem areas, then by all means apply the <em>matchTimeout</em> to them individually after determining reasonable timeout limits.</p>
<p>I would caution against specifying an <em>AppDomain</em> level default timeout and walking away. Again, knowing your patterns and scenarios make a huge difference in what strategy to employ. An <em>AppDomain</em> default is appropriate when you want to set an absolute maximum timeout limit for all your <em>Regex</em> operations to prevent a pattern&#8217;s performance from catching you by surprise. With that guard in place you should then identify any patterns you believe need more time and override those values directly. This could also present an opportunity to incorporate unit tests of your patterns to ensure timeouts occur within the expected interval, or that they pass successfully before the limit is reached.</p>
<p>Bear in mind that you&#8217;ll want to add exception handling too. Handle the <em>RegexMatchTimeoutException</em> to cover timeouts, and handle the <em>ArgumentOutOfRangeException</em> when dynamically applying a <em>matchTimeout</em> value.</p>
<p>Despite the addition of this feature, most operations execute fairly quickly, usually in the milliseconds to early seconds range. When determining reasonable timeout intervals the <a title="Regex.MatchTimeout Property" href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.matchtimeout(v=vs.110).aspx">MSDN documentation</a> suggests taking the following factors into consideration:</p>
<blockquote>
<ul>
<li>The length and complexity of the regular expression pattern. Longer and more complex regular expressions require more time than shorter and simpler ones.</li>
<li>The expected machine load. Processing takes more time on systems with high CPU and memory utilization.</li>
</ul>
</blockquote>
<p>To add to that advice, the length of the input is another factor to consider.</p>
<p>Overall I&#8217;m pleased with the addition of this feature and think it provides a simple approach to managing performance concerns without the need of writing ugly workarounds to address application responsiveness.</p>
<p>Published by Ahmad Mageed on <a href="http://softwareninjaneer.com/blog">Software Ninjaneer</a></p>]]></content:encoded>
			<wfw:commentRss>http://softwareninjaneer.com/blog/2011/09/21/regex-engine-updated-to-allow-timeouts-in-net-4-5/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
