<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Coding Lifestyle</title>
	<atom:link href="http://codinglifestyle.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://codinglifestyle.wordpress.com</link>
	<description>When it&#039;s not just a job...</description>
	<lastBuildDate>Wed, 25 Jan 2012 13:33:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='codinglifestyle.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Coding Lifestyle</title>
		<link>http://codinglifestyle.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://codinglifestyle.wordpress.com/osd.xml" title="Coding Lifestyle" />
	<atom:link rel='hub' href='http://codinglifestyle.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Dictionary Extensions: Define useful extensions to play safe</title>
		<link>http://codinglifestyle.wordpress.com/2012/01/18/dictionary-extensions-define-useful-extensions-to-play-safe/</link>
		<comments>http://codinglifestyle.wordpress.com/2012/01/18/dictionary-extensions-define-useful-extensions-to-play-safe/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 14:02:18 +0000</pubDate>
		<dc:creator>codinglifestyle</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[dictionary]]></category>
		<category><![CDATA[extension]]></category>
		<category><![CDATA[extension methods]]></category>
		<category><![CDATA[key]]></category>
		<category><![CDATA[safe]]></category>
		<category><![CDATA[templates]]></category>
		<category><![CDATA[value]]></category>

		<guid isPermaLink="false">http://codinglifestyle.wordpress.com/?p=433</guid>
		<description><![CDATA[Ever have a dictionary or similar data structure and your code has many repeated checks to pull the value when in reality you&#8217;d be happy with a default value like null or string.Empty? Well, consider the following extension to Dictionary: Let’s you do: where safe defaults to &#8220;&#8221; as it hasn’t been added. Stop! I [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=433&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><pre class="brush: csharp;">
   if (searchCriteria.ContainsKey(key) &amp;&amp;
       !string.IsNullOrEmpty(searchCriteria[key]))
       searchTerm = searchCriteria[key];
</pre></p>
<p>Ever have a dictionary or similar data structure and your code has many repeated checks to pull the value when in reality you&#8217;d be happy with a default value like <span style="color:#3366ff;">null</span> or <span style="color:#3366ff;">string</span>.Empty? Well, consider the following extension to Dictionary:</p>
<p><pre class="brush: csharp;">
    public static class DictionaryExtensions
    {
        public static TValue GetSafeValue&lt;TKey, TValue&gt;(this Dictionary&lt;TKey, TValue&gt; dictionary, TKey key)
        {
            TValue result = default(TValue);
            dictionary.TryGetValue(index, out result);
            return result;
        }
    }
</pre></p>
<p>Let’s you do:</p>
<p><pre class="brush: csharp;">
    Dictionary bob = new Dictionary();
    string safe = bob.GetSafeValue(100);
    System.Diagnostics.Trace.WriteLine(safe);
</pre></p>
<p>where <em>safe</em> defaults to &#8220;&#8221; as it hasn’t been added. Stop! I know what you’re going to say and I thought of that too. You can control the default value as well:</p>
<p><pre class="brush: csharp;">
    public static class DictionaryExtensions
    {
        /// &lt;summary&gt;
        /// Gets the safe value associated with the specified key.
        /// &lt;/summary&gt;
        /// &lt;typeparam name=&quot;TKey&quot;&gt;The type of the key.&lt;/typeparam&gt;
        /// &lt;typeparam name=&quot;TValue&quot;&gt;The type of the value.&lt;/typeparam&gt;
        /// &lt;param name=&quot;dictionary&quot;&gt;The dictionary.&lt;/param&gt;
        /// &lt;param name=&quot;key&quot;&gt;The key of the value to get.&lt;/param&gt;
        public static TValue GetSafeValue&lt;TKey, TValue&gt;(this Dictionary&lt;TKey, TValue&gt; dictionary, TKey key)
        {
            return dictionary.GetSafeValue(key, default(TValue));
        }

        /// &lt;summary&gt;
        /// Gets the safe value associated with the specified key.
        /// &lt;/summary&gt;
        /// &lt;typeparam name=&quot;TKey&quot;&gt;The type of the key.&lt;/typeparam&gt;
        /// &lt;typeparam name=&quot;TValue&quot;&gt;The type of the value.&lt;/typeparam&gt;
        /// &lt;param name=&quot;dictionary&quot;&gt;The dictionary.&lt;/param&gt;
        /// &lt;param name=&quot;key&quot;&gt;The key of the value to get.&lt;/param&gt;
        /// &lt;param name=&quot;defaultValue&quot;&gt;The default value.&lt;/param&gt;
        public static TValue GetSafeValue&lt;TKey, TValue&gt;(this Dictionary&lt;TKey, TValue&gt; dictionary, TKey key, TValue defaultValue)
        {
            TValue result;
            if (key == null || !dictionary.TryGetValue(key, out result))
                result = defaultValue;
            return result;
        }
    }
</pre></p>
<p>Let’s you do:</p>
<p><pre class="brush: csharp;">
   Dictionary bob = new Dictionary();
   string safe = bob.GetSafeValue(100, null);
   System.Diagnostics.Trace.WriteLine(safe);
</pre></p>
<p>where <em>safe</em> is <span style="color:#3366ff;">null</span>.</p>
<p>There’s obviously something wrong with me because I still think this stuff is cool.</p>
<p>I&#8217;m developing a nice little set of extensions at this point.  Often it seems like overkill to encapsulate handy functions like these in a class.  I had started by deriving a class from Dictionary&lt;TKey, TValue&gt; but changed over to the above.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codinglifestyle.wordpress.com/433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codinglifestyle.wordpress.com/433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codinglifestyle.wordpress.com/433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codinglifestyle.wordpress.com/433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codinglifestyle.wordpress.com/433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codinglifestyle.wordpress.com/433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codinglifestyle.wordpress.com/433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codinglifestyle.wordpress.com/433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codinglifestyle.wordpress.com/433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codinglifestyle.wordpress.com/433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codinglifestyle.wordpress.com/433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codinglifestyle.wordpress.com/433/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codinglifestyle.wordpress.com/433/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codinglifestyle.wordpress.com/433/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=433&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codinglifestyle.wordpress.com/2012/01/18/dictionary-extensions-define-useful-extensions-to-play-safe/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5222f005f72ad1480c4929741e356423?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">codinglifestyle</media:title>
		</media:content>
	</item>
		<item>
		<title>ScriptArguments: An easy way to programmatically pass arguments to script from codebehind</title>
		<link>http://codinglifestyle.wordpress.com/2012/01/13/scriptarguments-an-easy-way-to-programmatically-pass-arguements-to-script-from-codebehind/</link>
		<comments>http://codinglifestyle.wordpress.com/2012/01/13/scriptarguments-an-easy-way-to-programmatically-pass-arguements-to-script-from-codebehind/#comments</comments>
		<pubDate>Fri, 13 Jan 2012 11:35:53 +0000</pubDate>
		<dc:creator>codinglifestyle</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[arguements]]></category>
		<category><![CDATA[codebehind]]></category>
		<category><![CDATA[function signature]]></category>
		<category><![CDATA[programmatic]]></category>

		<guid isPermaLink="false">http://codinglifestyle.wordpress.com/?p=426</guid>
		<description><![CDATA[During my on-going adventures AJAXifying a crusty old business app I have been using a methodology by which most client events are setup in codebehind. The reason for this is I have easy access to my client ids, variables, and resources in codebehind. By constructing the script function calls at this stage, I can avoid [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=426&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>During my on-going adventures AJAXifying a crusty old business app I have been using a methodology by which most client events are setup in codebehind.  The reason for this is I have easy access to my client ids, variables, and resources in codebehind.  By constructing the script function calls at this stage, I can avoid messy and fragile in-line code.  What I am endeavouring to do is remove all script from the markup itself.  So instead of having MyPage.aspx with script mixed with markup I have MyPage.js and all functions here.  Separate js files avoid fragile in-line code which only fails at runtime, can&#8217;t be refactored, and doesn&#8217;t play as nice with the debugger.  Besides, separation of markup and script is good!</p>
<p>The downside to setting up all this script in the codebehind is it didn&#8217;t take long for the number of arguments to grow and become unruly.  My script function signature looked like this:</p>
<p><pre class="brush: jscript;">
function fnAddressChange(ddId, labelId, checkId, sameAsId, hidSelectId, hidSameAsId, onSelectEvent)
</pre><br />
And in the codebehind I had this:<br />
<pre class="brush: csharp;">
string selectArgs     = string.Format(&quot;'{0}', '{1}', '{2}', '{3}', '{4}', '{5}'&quot;, _DropDownAddress.ClientID, _LabelAddress.ClientID, _RowSameAs.ChildClientID, (SameAs &amp;&amp; _SameAsAddress != null) ? _SameAsAddress.LabelControl.ClientID : &quot;-1&quot;, _HiddenSelectedID.ClientID, _HiddenSameAs.ClientID);

string selectScript   = string.Format(&quot;fnAddressSelect({0}); &quot;, selectArgs);
string changeScript   = string.Format(&quot;fnAddressChange({0}, '{1}'); &quot;, selectArgs, OnClientSelect);
</pre></p>
<p>We can see selectArgs is getting out of control.  Not only is it getting ridiculous to add more to it, the function signature in script is getting huge and the ordering is easier to mess up.  So I came up with this solution:</p>
<p><pre class="brush: csharp;">
ScriptArguments args = new ScriptArguments ();
args.Add(&quot;ddId&quot;, _DropDownAddress.ClientID);
args.Add(&quot;labelId&quot;, _LabelAddress.ClientID);
args.Add(&quot;checkId&quot;, _RowSameAs.ChildClientID);
args.Add(&quot;sameAsId&quot;, (SameAs &amp;&amp; _SameAsAddress != null) ? _SameAsAddress.LabelControl.ClientID : &quot;-1&quot;);
args.Add(&quot;hidSelectId&quot;, _HiddenSelectedID.ClientID);
args.Add(&quot;hidSameAsId&quot;, _HiddenSameAs.ClientID);
</pre></p>
<p>Not only is the codebehind cleaner but I don&#8217;t have to worry about string.Format or the order in which I add arguments in.  The resulting script generated is:</p>
<p><pre class="brush: csharp;">
args.ToString()
&quot;{ ddId : 'ctl00__ContentMain__ControlOrderSoldTo__AddressSoldTo__DropDownAddress', labelId : 'ctl00__ContentMain__ControlOrderSoldTo__AddressSoldTo__LabelAddress', checkId : 'ctl00__ContentMain__ControlOrderSoldTo__AddressSoldTo__RowSameAs_FormField_CheckBox', sameAsId : '-1', hidSelectId : 'ctl00__ContentMain__ControlOrderSoldTo__AddressSoldTo__HiddenSelectedID', hidSameAsId : 'ctl00__ContentMain__ControlOrderSoldTo__AddressSoldTo__HiddenSameAs' }&quot;
</pre></p>
<p>This is a javascript Object with a property per key set to the corresponding value.  So in script I only need to take in one argument, the argument object.  I can then access every piece of information inserted in to ScriptArguments via the correct key:</p>
<p><pre class="brush: jscript;">
function fnAddressIsReadOnly(args) {
     alert(args.ddId);
     alert(args.labelId);
}
</pre></p>
<p>Will alert me with &#8220;ctl00__ContentMain__ControlOrderSoldTo__AddressSoldTo__DropDownAddress&#8221; and &#8220;ctl00__ContentMain__ControlOrderSoldTo__AddressSoldTo__LabelAddress&#8221;.</p>
<p>The great thing is how simple this was to implement:</p>
<p><pre class="brush: csharp;">
public class ScriptArguments : Dictionary&lt;string, string&gt;
{
    public override string ToString()
    {
        StringBuilder script = new StringBuilder(&quot;{ &quot;);
        this.Keys.ToList().ForEach(key =&gt; script.AppendFormat(&quot;{0} : '{1}', &quot;, key, this[key]));
        script.Remove(script.Length - 2, 2);
        script.Append(&quot; }&quot;);
        return script.ToString();
    }
}
</pre></p>
<p>This simple class solves a simple problem.  I hope you find it useful.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codinglifestyle.wordpress.com/426/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codinglifestyle.wordpress.com/426/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codinglifestyle.wordpress.com/426/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codinglifestyle.wordpress.com/426/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codinglifestyle.wordpress.com/426/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codinglifestyle.wordpress.com/426/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codinglifestyle.wordpress.com/426/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codinglifestyle.wordpress.com/426/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codinglifestyle.wordpress.com/426/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codinglifestyle.wordpress.com/426/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codinglifestyle.wordpress.com/426/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codinglifestyle.wordpress.com/426/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codinglifestyle.wordpress.com/426/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codinglifestyle.wordpress.com/426/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=426&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codinglifestyle.wordpress.com/2012/01/13/scriptarguments-an-easy-way-to-programmatically-pass-arguements-to-script-from-codebehind/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5222f005f72ad1480c4929741e356423?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">codinglifestyle</media:title>
		</media:content>
	</item>
		<item>
		<title>FindControl: Recursive DFS, BFS, and Leaf to Root Search with Pruning</title>
		<link>http://codinglifestyle.wordpress.com/2011/10/24/findcontrol-recursive-dfs-bfs-and-leaf-to-root-search-with-pruning/</link>
		<comments>http://codinglifestyle.wordpress.com/2011/10/24/findcontrol-recursive-dfs-bfs-and-leaf-to-root-search-with-pruning/#comments</comments>
		<pubDate>Mon, 24 Oct 2011 11:47:17 +0000</pubDate>
		<dc:creator>codinglifestyle</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[extension methods]]></category>
		<category><![CDATA[FindControl]]></category>
		<category><![CDATA[tree]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[pruning]]></category>

		<guid isPermaLink="false">http://codinglifestyle.wordpress.com/2011/10/24/findcontrol-recursive-dfs-bfs-and-leaf-to-root-search-with-pruning/</guid>
		<description><![CDATA[I have nefarious reason for posting this. It&#8217;s a prerequisite for another post I want to do on control mapping within javascript when you have one control which affects another and there&#8217;s no good spaghetti-less way to hook them together. But first, I need to talk about my nifty FindControl extensions. Whether you turn this [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=412&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have nefarious reason for posting this. It&#8217;s a prerequisite for another post I want to do on control mapping within javascript when you have one control which affects another and there&#8217;s no good spaghetti-less way to hook them together. But first, I need to talk about my nifty FindControl extensions. Whether you turn this in to an extension method or just place it in your page&#8217;s base class, you may find these handy.</p>
<p>We&#8217;ve all used FindControl and realized it&#8217;s a pretty lazy function that only searches its direct children and not the full control hierarchy. Let&#8217;s step back and consider what we&#8217;re searching before jumping to the code. What is the control hierarchy? It is a tree data structure whose root node is Page. The most common recursive FindControl extension starts at Page or a given parent node and performs a depth-first traversal over all the child nodes.</p>
<p><img src="http://codinglifestyle.files.wordpress.com/2011/10/102411_1147_findcontrol1.png?w=460" alt="Depth-first search" /><br />
Search order: a-b-d-h-e-i-j-c-f-k-g</p>
<p><pre class="brush: csharp;">
/// &lt;summary&gt;
/// Recurse through the controls collection checking for the id
/// &lt;/summary&gt;
/// &lt;param name=&quot;control&quot;&gt;The control we're checking&lt;/param&gt;
/// &lt;param name=&quot;id&quot;&gt;The id to find&lt;/param&gt;
/// &lt;returns&gt;The control, if found, or null&lt;/returns&gt;
public static Control FindControlEx(this Control control, string id)
{
    //Check if this is the control we're looking for
    if (control.ID == id)
        return control;

    //Recurse through the child controls
    Control c = null;
    for (int i = 0; i &lt; control.Controls.Count &amp;&amp; c == null; i++)
        c = FindControlEx((Control)control.Controls[i], id);

    return c;
}
</pre></p>
<p>You will find many examples of the above code on the net. This is the &#8220;good enough&#8221; algorithm of choice. If you have ever wondered about it&#8217;s efficiency, read on. Close you&#8217;re eyes and picture the complexity of the seemingly innocent form… how every table begets rows begets cells begets the controls within the cell and so forth. Before long you realize there can be quite a complex control heirarchy, sometimes quite deep, even in a relatively simple page.</p>
<p>Now imagine a page with several top-level composite controls, some of them rendering deep control heirachies (like tables). As the designer of the page you have inside knowledge about the layout and structure of the controls contained within. Therefore, you can pick the best method of searching that data structure. Looking at the diagram above and imagine the <em>b-branch</em> was much more complex and deep. Now say what we&#8217;re trying to find is <em>g</em>. With depth-first you would have to search the entiretly of the <em>b-branch</em> before moving on to the <em>c-branch</em> and ultimately finding the control in <em>g</em>. For this scenario, a breadth-first search would make more sense as we won&#8217;t waste time searching a complex and potentially deep branch when we know the control is close to our starting point, the root.</p>
<p><img src="http://codinglifestyle.files.wordpress.com/2011/10/102411_1147_findcontrol3.png?w=460" alt="Breadth-first search" /></p>
<p>Search order: a-b-c-d-e-f-g-h-i-j-k</p>
<p><pre class="brush: csharp;">
/// &lt;summary&gt;
/// Finds the control via a breadth first search.
/// &lt;/summary&gt;
/// &lt;param name=&quot;control&quot;&gt;The control we're checking&lt;/param&gt;
/// &lt;param name=&quot;id&quot;&gt;The id to find&lt;/param&gt;
/// &lt;returns&gt;If found, the control.  Otherwise null&lt;/returns&gt;
public static Control FindControlBFS(this Control control, string id)
{
    Queue&lt;Control&gt; queue = new Queue&lt;Control&gt;();
    //Enqueue the root control            
    queue.Enqueue(control);

    while (queue.Count &gt; 0)
    {
        //Dequeue the next control to test
        Control ctrl = queue.Dequeue();
        foreach (Control child in ctrl.Controls)
        {
            //Check if this is the control we're looking for
            if (child.ID == id)
                return child;
            //Place the child control on in the queue
            queue.Enqueue(child);
        }
    }

    return null;
}
</pre></p>
<p>Recently I had a scenario where I needed to link 2 controls together that coexisted in the ItemTemplate of a repeater. The controls existed in separate composite controls.</p>
<p><img src="http://codinglifestyle.files.wordpress.com/2011/10/102411_1147_findcontrol51.png?w=460" alt="" /></p>
<p>In this example I need to get _TexBoxPerformAction&#8217;s ClientID to enable/disable it via _ChechBoxEnable. Depending on the size of the data the repeater is bound to there may be hundreds of instances of the repeater&#8217;s ItemTemplate. How do I guarantee I get the right one? The above top-down FindControl algorithms would return he first match of _TextBoxPerformAction, not necessarily the right one. To solve this predicament, we need a bottom-up approach to find the control <em>closest to us</em>. By working our way up the control hierarchy we should be able to find the textbox within the same ItemTemplate instance guaranteeing we have the right one. The problem is, as we work our way up we will be repeatedly searching an increasingly large branch we&#8217;ve already seen. We need to prune the child branch we&#8217;ve already seen so we don&#8217;t search it over and over again as we work our way up.</p>
<p>To start we are in node 5 and need to get to node 1 to find our control. We recursively search node 5 which yields no results.</p>
<p><img src="http://codinglifestyle.files.wordpress.com/2011/10/102411_1147_findcontrol6.png?w=460" alt="" /></p>
<p>Next we look at node 5&#8242;s parent. We&#8217;ve already searched node 5, so we will prune it. Now recursively search node 4, which includes node 3, yielding no results.</p>
<p><img src="http://codinglifestyle.files.wordpress.com/2011/10/102411_1147_findcontrol7.png?w=460" alt="" /></p>
<p>Next we look at node 4&#8242;s parent.  We have already searched node 4 and its children so we prune it.  </p>
<p><img src="http://codinglifestyle.files.wordpress.com/2011/10/102411_1147_findcontrol8.png?w=460" alt="" /></p>
<p>Last we recursively search node 2, which includes node 1, yielding a result!<br />
<img src="http://codinglifestyle.files.wordpress.com/2011/10/102411_1147_findcontrol10.png?w=460" alt="" /></p>
<p>So here we can see that pruning saved us searching an entire branch repeatedly. And the best part is we only need to keep track of one id to prune.</p>
<p><pre class="brush: csharp;">
/// &lt;summary&gt;
/// Finds the control from the leaf node to root node.
/// &lt;/summary&gt;
/// &lt;param name=&quot;ctrlSource&quot;&gt;The control we're checking&lt;/param&gt;
/// &lt;param name=&quot;id&quot;&gt;The id to find&lt;/param&gt;
/// &lt;returns&gt;If found, the control.  Otherwise null&lt;/returns&gt;
public static Control FindControlLeafToRoot(this Control ctrlSource, string id)
{
    Control ctrlParent = ctrlSource.Parent;
    Control ctrlTarget = null;
    string pruneId = null;

    while (ctrlParent != null &amp;&amp;
           ctrlTarget == null)
    {
        ctrlTarget = FindControl(ctrlParent, id, pruneId);
        pruneId = ctrlParent.ClientID;
        ctrlParent = ctrlParent.Parent;
    }
    return ctrlTarget;
}

/// &lt;summary&gt;
/// Recurse through the controls collection checking for the id
/// &lt;/summary&gt;
/// &lt;param name=&quot;control&quot;&gt;The control we're checking&lt;/param&gt;
/// &lt;param name=&quot;id&quot;&gt;The id to find&lt;/param&gt;
/// &lt;param name=&quot;pruneClientID&quot;&gt;The client ID to prune from the search.&lt;/param&gt;
/// &lt;returns&gt;If found, the control.  Otherwise null&lt;/returns&gt;
public static Control FindControlEx(this Control control, string id, string pruneClientID)
{
    //Check if this is the control we're looking for
    if (control.ID == id)
        return control;

    //Recurse through the child controls
    Control c = null;
    for (int i = 0; i &lt; control.Controls.Count &amp;&amp; c == null; i++)
    {
        if (control.Controls[i].ClientID != pruneClientID)
            c = FindControlEx((Control)control.Controls[i], id, pruneClientID);
    }

    return c;
}
</pre></p>
<p>Now we have an efficient algorithm for searching leaf to root without wasting cycles searching the child branch we&#8217;ve come from. All this puts me in mind jQuery&#8217;s powerful selection capabilities. I&#8217;ve never dreamed up a reason for it yet, but searching for a collection of controls would be easy to implement and following jQuery&#8217;s lead we could extend the above to search for far more than just an ID.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codinglifestyle.wordpress.com/412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codinglifestyle.wordpress.com/412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codinglifestyle.wordpress.com/412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codinglifestyle.wordpress.com/412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codinglifestyle.wordpress.com/412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codinglifestyle.wordpress.com/412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codinglifestyle.wordpress.com/412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codinglifestyle.wordpress.com/412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codinglifestyle.wordpress.com/412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codinglifestyle.wordpress.com/412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codinglifestyle.wordpress.com/412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codinglifestyle.wordpress.com/412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codinglifestyle.wordpress.com/412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codinglifestyle.wordpress.com/412/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=412&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codinglifestyle.wordpress.com/2011/10/24/findcontrol-recursive-dfs-bfs-and-leaf-to-root-search-with-pruning/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5222f005f72ad1480c4929741e356423?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">codinglifestyle</media:title>
		</media:content>

		<media:content url="http://codinglifestyle.files.wordpress.com/2011/10/102411_1147_findcontrol1.png" medium="image">
			<media:title type="html">Depth-first search</media:title>
		</media:content>

		<media:content url="http://codinglifestyle.files.wordpress.com/2011/10/102411_1147_findcontrol3.png" medium="image">
			<media:title type="html">Breadth-first search</media:title>
		</media:content>

		<media:content url="http://codinglifestyle.files.wordpress.com/2011/10/102411_1147_findcontrol51.png" medium="image" />

		<media:content url="http://codinglifestyle.files.wordpress.com/2011/10/102411_1147_findcontrol6.png" medium="image" />

		<media:content url="http://codinglifestyle.files.wordpress.com/2011/10/102411_1147_findcontrol7.png" medium="image" />

		<media:content url="http://codinglifestyle.files.wordpress.com/2011/10/102411_1147_findcontrol8.png" medium="image" />

		<media:content url="http://codinglifestyle.files.wordpress.com/2011/10/102411_1147_findcontrol10.png" medium="image" />
	</item>
		<item>
		<title>Pass a Name Value Pair Collection to JavaScript</title>
		<link>http://codinglifestyle.wordpress.com/2011/08/08/pass-a-name-value-pair-collection-to-javascript/</link>
		<comments>http://codinglifestyle.wordpress.com/2011/08/08/pass-a-name-value-pair-collection-to-javascript/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 10:57:49 +0000</pubDate>
		<dc:creator>codinglifestyle</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://codinglifestyle.wordpress.com/?p=387</guid>
		<description><![CDATA[In my crusade against in-line code I am endevouring to clean up the script hell in my current project. My javascript is littered these types of statements: Part of the cleanup is to minimize script on the page and instead use a separate .js file. This encourages me to write static functions which take in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=387&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In my crusade against in-line code I am endevouring to clean up the script hell in my current project.  My javascript is littered these types of statements:</p>
<p><pre class="brush: jscript;">
var hid = &lt;%=hidSelectedItems.ClientId%&gt;;
var msg = &lt;%=GetResourceString('lblTooManyItems')%&gt;;
</pre></p>
<p>Part of the cleanup is to minimize script on the page and instead use a separate .<strong>js</strong> file.  This encourages me to write static functions which take in ids and resources as parameters, allows for easier script debugging, and removes all in-line code making maintenance or future refactoring easier.</p>
<p>While moving code to a proper .<strong>js</strong> file is nice there are times we might miss the in-line goodness.  Never fear, we can build a JavaScript object containing properties for anything we might need with ease.  This equates to passing a name/value pair collection to the JavaScript from the code behind.  Take a look at this example:</p>
<p><pre class="brush: csharp;">
    ScriptOptions options = new ScriptOptions();
    options.Add(&quot;ok&quot;, GetResourceString(&quot;btnOK&quot;));
    options.Add(&quot;oksave&quot;, GetResourceString(&quot;btnOkSave&quot;));
    options.Add(&quot;cancel&quot;, GetResourceString(&quot;btnCancel&quot;));
    options.Add(&quot;viewTitle&quot;, GetResourceString(&quot;lblAddressEditorView&quot;));
    options.Add(&quot;editTitle&quot;, GetResourceString(&quot;lblAddressEditorEdit&quot;));
    options.Add(&quot;createTitle&quot;, GetResourceString(&quot;lblAddressEditorCreate&quot;));
    options.RegisterOptionsScript(this, &quot;_OptionsAddressEditorResources&quot;);
</pre></p>
<p>Here we&#8217;re using the ScriptOptions class to create an object called <strong>_OptionsAddressEditorResources</strong> we can access in our script.  Now let&#8217;s see these options in use:<br />
<pre class="brush: jscript;">
function fnAddressEditDialog(address, args) {
    //Define the buttons and events
    var buttonList = {};
    buttonList[_OptionsAddressEditorResources.ok]     = function() { return fnAddressEditOnOk(jQuery(this), args); };
    buttonList[_OptionsAddressEditorResources.oksave] = function() { return fnAddressEditOnOkSave(jQuery(this), args); };
    buttonList[_OptionsAddressEditorResources.cancel] = function() { jQuery(this).dialog(&quot;close&quot;); };

    //Display the dialog
    jQuery(&quot;#addressEditorDialog&quot;).dialog({
        title: _OptionsAddressEditorResources.editTitle,
        modal: true,
        width: 535,
        resizable: false,
        buttons: buttonList
    });
}
</pre></p>
<p>Above we see the jQuery dialog using the resources contained within the _OptionsAddressEditorResources object.</p>
<p>So this seems simple but pretty powerful.  Below is the ScriptOptions class which simply extends a Dictionary and writes out the script creating a named global object.  Good luck cleaning up your script hell.  Hopefully this will help.<br />
<pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// Class for generating javascript option arrays
    /// &lt;/summary&gt;
    public class ScriptOptions : Dictionary&lt;string, string&gt;
    {
        /// &lt;summary&gt;
        /// Adds the control id to the options script
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;control&quot;&gt;The control.&lt;/param&gt;
        public void AddControlId(WebControl control)
        {
            this.Add(control.ID, control.ClientID);
        }

        /// &lt;summary&gt;
        /// Registers all the key/values as an options script for access in the client.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;page&quot;&gt;The page&lt;/param&gt;
        /// &lt;param name=&quot;optionsName&quot;&gt;Name of the options object&lt;/param&gt;
        public void RegisterOptionsScript(Page page, string optionsName)
        {
            if (!page.ClientScript.IsStartupScriptRegistered(page.GetType(), optionsName))
            {
                StringBuilder script = new StringBuilder(string.Format(&quot;var {0} = new Object();&quot;, optionsName));
                this.Keys.ToList().ForEach(key =&gt; script.Append(string.Format(&quot;{0}.{1}='{2}';&quot;, optionsName, key, this[key])));
                page.ClientScript.RegisterStartupScript(page.GetType(), optionsName, script.ToString(), true);
            } 
        }
    }
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codinglifestyle.wordpress.com/387/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codinglifestyle.wordpress.com/387/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codinglifestyle.wordpress.com/387/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codinglifestyle.wordpress.com/387/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codinglifestyle.wordpress.com/387/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codinglifestyle.wordpress.com/387/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codinglifestyle.wordpress.com/387/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codinglifestyle.wordpress.com/387/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codinglifestyle.wordpress.com/387/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codinglifestyle.wordpress.com/387/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codinglifestyle.wordpress.com/387/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codinglifestyle.wordpress.com/387/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codinglifestyle.wordpress.com/387/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codinglifestyle.wordpress.com/387/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=387&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codinglifestyle.wordpress.com/2011/08/08/pass-a-name-value-pair-collection-to-javascript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5222f005f72ad1480c4929741e356423?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">codinglifestyle</media:title>
		</media:content>
	</item>
		<item>
		<title>Custom Attributes with Extension Methods: Resource Key</title>
		<link>http://codinglifestyle.wordpress.com/2011/07/04/custom-attributes-with-extension-methods-resource-key/</link>
		<comments>http://codinglifestyle.wordpress.com/2011/07/04/custom-attributes-with-extension-methods-resource-key/#comments</comments>
		<pubDate>Mon, 04 Jul 2011 10:01:18 +0000</pubDate>
		<dc:creator>codinglifestyle</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[attributes]]></category>
		<category><![CDATA[custom]]></category>
		<category><![CDATA[extension methods]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[resource]]></category>
		<category><![CDATA[resource key]]></category>

		<guid isPermaLink="false">http://codinglifestyle.wordpress.com/?p=365</guid>
		<description><![CDATA[I picked up this technique in my last job to use a custom attribute to contain a resource key. The biggest benefit was all the enums in the system used this attribute which provided a way to translate that enum to text. Take a look at a sample enum: Each enum uses the AttributeResourceKey to specify [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=365&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I picked up this technique in my last job to use a custom attribute to contain a resource key. The biggest benefit was all the enums in the system used this attribute which provided a way to translate that enum to text. Take a look at a sample enum:</p>
<p><pre class="brush: csharp;">
public enum Mode
{
    [AttributeResourceKey(&quot;lblInvalid&quot;)]
    Invalid,
    [AttributeResourceKey(&quot;lblReview&quot;)]
    Review,
    [AttributeResourceKey(&quot;lblCheckout&quot;)]
    Checkout,
    [AttributeResourceKey(&quot;lblOrdered&quot;)]
    Ordered
}
</pre></p>
<p>Each enum uses the AttributeResourceKey to specify the resource key defined in the resx file. Combined with an extension method we can extend the enum itself to allow us to execute the following:</p>
<p><pre class="brush: csharp;">
public void DoOperation(Mode mode)
{
    Log.Info(GetResourceString(mode.ResourceKey()));
    ...
}
</pre></p>
<p>The C++ head in me thinks, &#8220;why are we using reflection when a static function in a helper class could contain a switch statement to convert the enum to the resource key?&#8221;.  Technically this is sufficient and faster.  However, the C# head in me loves the idea that the enum and the resource key are intimately tied together in the same file. There is no helper function to forget to update.  The penalty of reading an attribute is a small price to pay to keep the enum and resource key together in order to increase overall maintainability.</p>
<p>So the first thing I am going to do is define a simple interface for my custom attributes.</p>
<p><pre class="brush: csharp;">
public interface IAttributeValue&lt;T&gt;
{
    T Value { get; }
}
</pre></p>
<p>All this interface does is define that the custom attribute class itself will define a property called Value of type T. This will be useful when using the generic method, below, for pulling the attribute. Next we define the custom attribute class itself.</p>
<p><pre class="brush: csharp;">
    public sealed class AttributeResourceKey : Attribute, IAttributeValue&lt;string&gt;
    {
        private string _resourceKey;
        public AttributeResourceKey(string resourceKey)
        {
            _resourceKey = resourceKey;
        }

        #region IAttributeValue&lt;string&gt; Members
        public string Value
        {
            get { return _resourceKey; }
        }
        #endregion
    }
</pre></p>
<p>Notice how simple the above class is. We have a constructor taking a string and a property called Value which returns said string. Now let&#8217;s look at the generic method for pulling the attribute.</p>
<p><pre class="brush: csharp;">
    public static class AttributeHelper
    {
        /// &lt;summary&gt;
        /// Given an enum, pull out its attribute (if present)
        /// &lt;/summary&gt;
        public static TReturn GetValue&lt;TAttribute, TReturn&gt;(object value)
        where TAttribute: IAttributeValue&lt;TReturn&gt;
        {
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            object[] attribs    = fieldInfo.GetCustomAttributes(typeof(TAttribute), false);
            TReturn returnValue = default(TReturn);

            if (attribs != null &amp;&amp; attribs.Length &gt; 0)
                returnValue = ((TAttribute)attribs[0]).Value;

            return returnValue;
        }
    }
</pre></p>
<p>The code above is the heart of code. It uses generics so you need only define this code once in a static class. By passing the attribute and return type we can extract our Value defined by IAttributeValue&lt;TReturn&gt;.  Using the where constraint on TAttribute allows the generic method to know this type defines a property called Value of type TReturn.  This exposes the true power of generics as without this constraint the method could only presume TAttribute is nothing more than an object.  This might tempt you to wrongly cast TAttribute in order to access it&#8217;s properties inviting an exception only seen at runtime.</p>
<p>Now to define our extension method, to be placed in a common namespace, to extend all enums with the ResourceKey() method.</p>
<p><pre class="brush: csharp;">
    public static class EnumerationExtensions
    {
        /// &lt;summary&gt;
        /// Given an enum, pull out its resource key (if present)
        /// &lt;/summary&gt;
        public static string ResourceKey(this Enum value)
        {
            return AttributeHelper.GetValue&lt;AttributeResourceKey, string&gt;(value);
        }
    }
</pre></p>
<p>Thanks to the generic attribute helper the above extension method looks trivial. We simply use the helper to return the resource key and now we&#8217;ve extended all our enums to have this useful property.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codinglifestyle.wordpress.com/365/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codinglifestyle.wordpress.com/365/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codinglifestyle.wordpress.com/365/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codinglifestyle.wordpress.com/365/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codinglifestyle.wordpress.com/365/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codinglifestyle.wordpress.com/365/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codinglifestyle.wordpress.com/365/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codinglifestyle.wordpress.com/365/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codinglifestyle.wordpress.com/365/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codinglifestyle.wordpress.com/365/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codinglifestyle.wordpress.com/365/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codinglifestyle.wordpress.com/365/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codinglifestyle.wordpress.com/365/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codinglifestyle.wordpress.com/365/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=365&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codinglifestyle.wordpress.com/2011/07/04/custom-attributes-with-extension-methods-resource-key/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5222f005f72ad1480c4929741e356423?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">codinglifestyle</media:title>
		</media:content>
	</item>
		<item>
		<title>Understanding BackgroundWorker and Encapsulating your own Thread Class</title>
		<link>http://codinglifestyle.wordpress.com/2011/02/22/understanding-backgroundworker-and-encapsulating-your-own-thread-class/</link>
		<comments>http://codinglifestyle.wordpress.com/2011/02/22/understanding-backgroundworker-and-encapsulating-your-own-thread-class/#comments</comments>
		<pubDate>Tue, 22 Feb 2011 15:33:00 +0000</pubDate>
		<dc:creator>codinglifestyle</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[asynchronous]]></category>
		<category><![CDATA[BackgroundWorker]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[encapsulate]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[not firing]]></category>
		<category><![CDATA[synchronization]]></category>
		<category><![CDATA[thread]]></category>

		<guid isPermaLink="false">http://codinglifestyle.wordpress.com/?p=329</guid>
		<description><![CDATA[You may have come across this page if you were searching for any of the following: BackgroundWorker events not firing BackgroundWorker RunWorkerCompleted event not firing BackgroundWorker threads frozen Encapsulate thread class Yesterday my web page was launching several worker threads and waiting for them to return to amalgamate the results in to a single data [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=329&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>You may have come across this page if you were searching for any of the following:</p>
<ul>
<li>BackgroundWorker events not firing</li>
<li>BackgroundWorker RunWorkerCompleted event not firing</li>
<li>BackgroundWorker threads frozen</li>
<li>Encapsulate thread class</li>
</ul>
<p>Yesterday my web page was launching several worker threads and waiting for them to return to amalgamate the results in to a single data set to bind to a grid. Launching several worker threads and waiting for a <strong>join</strong> is a common pattern. To nicely encapsulate the thread itself I derived a class from BackgroundWorker. BackgroundWorker has many advantages such as using an event model, thread pool, and all the thread plumbing built right in. All you have to do is override <em>OnDoWork</em> and off you go. The RunWorkerCompleted event was used, in conjunction with a lock, to collect the data once the worker thread finished.</p>
<p>Everything looked good but for some reason the event never fired. The problem was that I had gotten myself in to a <strong>deadlock</strong> scenario. The expectation is that when the event fires the delegate method will run in the context of the thread which fired it. If this were true, this would have allowed my synchronization logic to operate normally and not deadlock. The reality is that BackgroundWorker goes out of its way to run this event in the <em>calling thread&#8217;s identity</em>. It did this so when using BackgroundWorker in conjunction with the UI no invoke will be required (an exception will be thrown if a thread tries to touch the UI&#8217;s controls requiring you to check InvokeRequired).</p>
<p>When in doubt, use something like this to check the identity of the thread executing the code:</p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:#2b91af;">Trace</span>.WriteLine(<span style="color:blue;">string</span>.Format(<span style="color:#a31515;">&#8220;Thread id {0}&#8221;</span>, System.Threading.<span style="color:#2b91af;">Thread</span>.CurrentThread.ManagedThreadId));</span></p>
<p>Once putting the above trace in the code I would clearly see that the identity of my main thread was identical to the thread identity in the RunWorkerCompleted event. Once the code tried to aquire the lock it was all over.</p>
<p>So the solution in my case was not to use the RunWorkerCompleted event. I added an alternative event to my thread class and called that at the end of <em>OnDoWork</em>. The event executed in the context of the thread, as expected, and my synchronization logic worked fine. But I couldn&#8217;t help feeling it was a bit of a kludge and pondered whether I should be deriving from BackgroundWorker at all. However, what&#8217;s the alternative? There really aren&#8217;t other alternatives to BackgroundWorker built in to the framework but it is easy to create your own.  See below:</p>
<p><pre class="brush: csharp;">
 /// &lt;summary&gt;
 /// Abstract base class which performs some work and stores it in a data property
 /// &lt;/summary&gt;
 /// &lt;typeparam name=&quot;T&quot;&gt;The type of data this thread will procure&lt;/typeparam&gt;
 public abstract class ThreadBase&lt;T&gt;
 {
 #region Public methods
 /// &lt;summary&gt;
 /// Does the work asynchronously and fires the OnComplete event
 /// &lt;/summary&gt;
 public void DoWorkAsync()
 {
     DoWorkAsync(null);
 }

 /// &lt;summary&gt;
 /// Does the work asynchronously and fires the OnComplete event
 /// &lt;/summary&gt;
 /// &lt;param name=&quot;arguement&quot;&gt;The arguement object&lt;/param&gt;
 public void DoWorkAsync(object arguement)
 {
 ThreadPool.QueueUserWorkItem(DoWorkHelper, arguement);
 }

 /// &lt;summary&gt;
 /// Does the work and populates the Data property
 /// &lt;/summary&gt;
 public void DoWork()
 {
 DoWork(null);
 }

 /// &lt;summary&gt;
 /// Does the work and populates the Data property
 /// &lt;/summary&gt;
 /// &lt;param name=&quot;arguement&quot;&gt;The arguement object&lt;/param&gt;
 /// &lt;remarks&gt;
 /// Can be called to run syncronously, which doesn't fire the OnComplete event
 /// &lt;/remarks&gt;
 public abstract void DoWork(object arguement);
 #endregion

#region Private methods
 private void DoWorkHelper(object arguement)
 {
 DoWork(arguement);
 if (OnComplete != null)
     OnComplete.Invoke(this, Data);
 }
 #endregion

#region Properties
 public T Data { get; protected set; }
 #endregion

#region Events

 /// &lt;summary&gt;
 /// Delegate which is invoked when the thread has completed
 /// &lt;/summary&gt;
 /// &lt;param name=&quot;thread&quot;&gt;The thread.&lt;/param&gt;
 /// &lt;param name=&quot;data&quot;&gt;The data.&lt;/param&gt;
 public delegate void ThreadComplete(ThreadBase&lt;T&gt; thread, T data);

 /// &lt;summary&gt;
 /// Occurs when the thread completes.
 /// &lt;/summary&gt;
 /// &lt;remarks&gt;This event operates in the context of the thread&lt;/remarks&gt;
 public event ThreadComplete OnComplete;
 #endregion
 }
</pre></p>
<p>My generic ThreadBase class is a lightweight baseclass substitute for BackgroundWorker providing the flexibility to call it synchronously or asynchronously, a generically typed Data property, and an OnComplete event. The OnComplete will execute in the thread&#8217;s context so synchronization of several threads won&#8217;t be a problem. Take a look at it in action:</p>
<p><pre class="brush: csharp;">
 public class MyThread : ThreadBase&lt;DateTime&gt;
 {
 public override void DoWork(object arguement)
 {
 Trace.WriteLine(string.Format(&quot;MyThread thread id {0}&quot;, System.Threading.Thread.CurrentThread.ManagedThreadId));

Data = DateTime.Now;
 }
 }
</pre></p>
<p>What a nicely encapsulated thread! Below we can see how cleanly a <span style="font-family:Courier New;font-size:10pt;"><span style="color:#2b91af;">MyThread</span></span> can be used<span style="font-family:Courier New;font-size:10pt;">:</span></p>
<p><pre class="brush: csharp;">
 MyThread thread = new MyThread();
 thread.OnComplete += new ThreadBase&lt;DateTime&gt;.ThreadComplete(thread_OnComplete);
 thread.DoWorkAsync();

 void thread_OnComplete(ThreadBase&lt;DateTime&gt; thread, DateTime data)
 {
 Trace.WriteLine(string.Format(&quot;Complete thread id {0}: {1}&quot;, Thread.CurrentThread.ManagedThreadId, data));
 }
</pre></p>
<p>Then I got to thinking what if I wanted the best of both worlds? Thanks to reflector I found out how BackgroundWorker&#8217;s RunWorkerCompleted event executes in the context of the calling thread. My generic ThreadBaseEx class offers two events: OnCompleteByThreadContext and OnCompleteByCallerContext.</p>
<p><pre class="brush: csharp;">
 /// &lt;summary&gt;
 /// Abstract base class which performs some work and stores it in a data property
 /// &lt;/summary&gt;
 /// &lt;typeparam name=&quot;T&quot;&gt;The type of data this thread will procure&lt;/typeparam&gt;
 public abstract class ThreadBaseEx&lt;T&gt;
 {
 #region Private variables
 private AsyncOperation _asyncOperation;
 private readonly SendOrPostCallback _operationCompleted;
 #endregion

#region Ctor
 public ThreadBaseEx()
 {
 _operationCompleted = new SendOrPostCallback(AsyncOperationCompleted);
 }
 #endregion

#region Public methods
 /// &lt;summary&gt;
 /// Does the work asynchronously and fires the OnComplete event
 /// &lt;/summary&gt;
 public void DoWorkAsync()
 {
 DoWorkAsync(null);
 }

 /// &lt;summary&gt;
 /// Does the work asynchronously and fires the OnComplete event
 /// &lt;/summary&gt;
 /// &lt;param name=&quot;arguement&quot;&gt;The arguement object&lt;/param&gt;
 public void DoWorkAsync(object arguement)
 {
 _asyncOperation = AsyncOperationManager.CreateOperation(null);
 ThreadPool.QueueUserWorkItem(DoWorkHelper, arguement);
 }

 /// &lt;summary&gt;
 /// Does the work and populates the Data property
 /// &lt;/summary&gt;
 public void DoWork()
 {
 DoWork(null);
 }

 /// &lt;summary&gt;
 /// Does the work and populates the Data property
 /// &lt;/summary&gt;
 /// &lt;param name=&quot;arguement&quot;&gt;The arguement object&lt;/param&gt;
 /// &lt;remarks&gt;
 /// Can be called to run syncronously, which doesn't fire the OnComplete event
 /// &lt;/remarks&gt;
 public abstract void DoWork(object arguement);
 #endregion

#region Private methods
 private void DoWorkHelper(object arguement)
 {
 DoWork(arguement);
 if (OnCompleteByThreadContext != null)
 OnCompleteByThreadContext.Invoke(this, Data);
 _asyncOperation.PostOperationCompleted(this._operationCompleted, arguement);
 }

private void AsyncOperationCompleted(object arg)
 {
 OnCompleteByCallerContext(this, Data);
 }
 #endregion

#region Properties
 public T Data { get; protected set; }
 #endregion

#region Events
 /// &lt;summary&gt;
 /// Delegate which is invoked when the thread has completed
 /// &lt;/summary&gt;
 /// &lt;param name=&quot;thread&quot;&gt;The thread.&lt;/param&gt;
 /// &lt;param name=&quot;data&quot;&gt;The data.&lt;/param&gt;
 public delegate void ThreadComplete(ThreadBaseEx&lt;T&gt; thread, T data);

 /// &lt;summary&gt;
 /// Occurs when the thread completes.
 /// &lt;/summary&gt;
 /// &lt;remarks&gt;This event operates in the context of the worker thread&lt;/remarks&gt;
 public event ThreadComplete OnCompleteByThreadContext;

 /// &lt;summary&gt;
 /// Occurs when the thread completes.
 /// &lt;/summary&gt;
 /// &lt;remarks&gt;This event operates in the context of the calling thread&lt;/remarks&gt;
public event ThreadComplete OnCompleteByCallerContext;
 #endregion
 }
</pre></p>
<p>Your encapsulated thread will be the same as above, but now with two events allowing either scenario, depending on what suits.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codinglifestyle.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codinglifestyle.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codinglifestyle.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codinglifestyle.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codinglifestyle.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codinglifestyle.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codinglifestyle.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codinglifestyle.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codinglifestyle.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codinglifestyle.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codinglifestyle.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codinglifestyle.wordpress.com/329/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codinglifestyle.wordpress.com/329/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codinglifestyle.wordpress.com/329/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=329&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codinglifestyle.wordpress.com/2011/02/22/understanding-backgroundworker-and-encapsulating-your-own-thread-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5222f005f72ad1480c4929741e356423?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">codinglifestyle</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.Net Windows Authentication: Authorization by Group</title>
		<link>http://codinglifestyle.wordpress.com/2011/01/20/asp-net-windows-authentication-authorization-by-ntlm-group-2/</link>
		<comments>http://codinglifestyle.wordpress.com/2011/01/20/asp-net-windows-authentication-authorization-by-ntlm-group-2/#comments</comments>
		<pubDate>Thu, 20 Jan 2011 11:29:28 +0000</pubDate>
		<dc:creator>codinglifestyle</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[@@Identity]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[authorization]]></category>
		<category><![CDATA[impersonate]]></category>
		<category><![CDATA[IPrincipal]]></category>
		<category><![CDATA[kerberos]]></category>
		<category><![CDATA[ntlm]]></category>
		<category><![CDATA[web.config]]></category>
		<category><![CDATA[windows authentication]]></category>

		<guid isPermaLink="false">http://codinglifestyle.wordpress.com/?p=311</guid>
		<description><![CDATA[Often in this line of work it&#8217;s the simple things that take the longest time. A seemingly simple question came up yesterday on how to lock access to a customer&#8217;s website to a specific Windows group. There are a couple of simple gotchas worth documenting in a relatively simple solution presented below. First, let&#8217;s start [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=311&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Often in this line of work it&#8217;s the simple things that take the longest time. A seemingly simple question came up yesterday on how to lock access to a customer&#8217;s website to a specific Windows group. There are a couple of simple gotchas worth documenting in a relatively simple solution presented below.</p>
<p>First, let&#8217;s start with the basics. By default ASP.NET executes code using a fixed account. Assuming you are using IIS 6 or greater, the identity is specified in the application pool. However, if we set impersonation to <strong>true</strong> ASP.NET assumes the <em>user&#8217;s</em> identity. Combined with Windows authentication, our code will run within the context of the user&#8217;s Windows identity.</p>
<p>To achieve this, in the <strong>web.config</strong> we set authentication to Windows and impersonate to true. Now we will have an authenticated Windows user, we next need to focus on authorization or what rights and restrictions apply to that user. Our requirement in this case is simple, if you belong to a specified Windows group you have access, otherwise you do not. When using Windows authentication, roles within ASP.NET translate to Windows groups. To allow a specific Windows group, allow that role within the authorization tag in the web.config. We could add additional lines to allow further roles or users. In this case, we simply want to deny everyone else, so notice the deny users <strong>*</strong> wildcard below.</p>
<h2>Web.config</h2>
<p><span style="color:blue;"><span style="font-family:Courier New;font-size:10pt;">&lt;<span style="color:#a31515;">system.web<span style="color:blue;">&gt;</span></span></span></span><br />
<span style="color:blue;font-family:Courier New;font-size:10pt;"> &lt;<span style="color:#a31515;">authentication<span style="color:blue;"> <span style="color:red;">mode<span style="color:blue;">=</span>&#8220;<span style="color:blue;">Windows</span>&#8220;<span style="color:blue;">/&gt;<br />
</span></span></span></span></span><span style="color:blue;font-family:Courier New;font-size:10pt;"> &lt;<span style="color:#a31515;">identity <span style="color:blue;"><span style="color:red;">impersonate<span style="color:blue;">=</span>&#8220;<span style="color:blue;">true</span>&#8220;<span style="color:blue;">/&gt;<br />
</span></span></span></span></span><span style="color:blue;font-family:Courier New;font-size:10pt;"> &lt;<span style="color:#a31515;">authorization<span style="color:blue;">&gt;<br />
</span></span></span><span style="color:blue;font-family:Courier New;font-size:10pt;"> &lt;<span style="color:#a31515;">allow <span style="color:blue;"><span style="color:red;">roles<span style="color:blue;">=</span>&#8220;<span style="color:blue;">BUILTIN\Administrators</span>&#8220;<span style="color:blue;">/&gt;<br />
</span></span></span></span></span><span style="color:blue;font-family:Courier New;font-size:10pt;"> &lt;<span style="color:#a31515;">deny <span style="color:blue;"><span style="color:red;">users<span style="color:blue;">=</span>&#8220;<span style="color:blue;">*</span>&#8220;<span style="color:blue;">/&gt;<br />
</span></span></span></span></span><span style="color:blue;font-family:Courier New;font-size:10pt;"> &lt;/<span style="color:#a31515;">authorization<span style="color:blue;">&gt;<br />
</span></span></span><span style="color:blue;"><span style="font-family:Courier New;font-size:10pt;">&lt;/<span style="color:#a31515;">system.web<span style="color:blue;">&gt;</span></span></span><br />
</span></p>
<p>Here&#8217;s a handy tip: When testing use the <strong>whoami</strong> command. This will show you all the groups the logged in user belongs to which is handy when testing.</p>
<p><img src="http://codinglifestyle.files.wordpress.com/2011/01/012011_1128_aspnetwindo1.png?w=460" alt="" /></p>
<p>If you are making modifications to local or domain groups for the current user (probably your own account for testing) ensure that you see the group information you expect with the <strong>whoami /groups</strong> command. If you have just added yourself to a test group, remember that you must logout and log back in to see these changes.</p>
<p>Now you could stop here, you&#8217;re website is secured. However, if you do the user will get IIS&#8217;s rather nasty 401 error page. It would be much nicer to show our own custom error or possibly redirect the user to a registration page of some sort. The problem is we&#8217;ve restricted the entire website, so even a harmless error page requires authorization. What we need is an exception, which we can do be adding the snippet below the system.web closing tag.</p>
<p><span style="color:blue;font-family:Courier New;font-size:10pt;">&lt;<span style="color:#a31515;">location <span style="color:blue;"><span style="color:red;">path<span style="color:blue;">=</span>&#8220;<span style="color:blue;background-color:yellow;">AccessDenied.aspx</span>&#8220;<span style="color:blue;">&gt;<br />
</span></span></span></span></span><span style="color:blue;font-family:Courier New;font-size:10pt;"> &lt;<span style="color:#a31515;">system.web<span style="color:blue;">&gt;<br />
</span></span></span><span style="color:blue;font-family:Courier New;font-size:10pt;"> &lt;<span style="color:#a31515;">authorization<span style="color:blue;">&gt;<br />
</span></span></span><span style="color:blue;font-family:Courier New;font-size:10pt;"> &lt;<span style="color:#a31515;">allow <span style="color:blue;"><span style="color:red;">users<span style="color:blue;">=</span>&#8220;<span style="color:blue;">*</span>&#8220;<span style="color:blue;">/&gt;<br />
</span></span></span></span></span><span style="color:blue;font-family:Courier New;font-size:10pt;"> &lt;/<span style="color:#a31515;">authorization<span style="color:blue;">&gt;<br />
</span></span></span><span style="color:blue;font-family:Courier New;font-size:10pt;"> &lt;/<span style="color:#a31515;">system.web<span style="color:blue;">&gt;<br />
</span></span></span><span style="color:blue;font-family:Courier New;font-size:10pt;">&lt;/<span style="color:#a31515;">location<span style="color:blue;">&gt;<br />
</span></span></span></p>
<p>What this has done is specify a specific file to have different authorization requirements to the rest of the website.  Optionally we could have specified a directory where we can place CSS, image files, a masterpage, or other resources we may want to allow access to.  In this example, we are only allowing all users to see the AccessDenied.aspx page.</p>
<p>You might think that using the customErrors section in the <strong>web.config</strong> would be the last step to redirect the user to the AccessDenied.aspx page. However, IIS has other ideas!  IIS catches the 401 before it ever consults with ASP.Net and therefore ignores your customErrors section for a 401. Use the below workaround in your global.asax.cs to catch the 401 and redirect the user to our error page before IIS has a chance to interfere.</p>
<h2>Global.asax.cs</h2>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:blue;">protected </span><span style="color:blue;">void</span> Application_EndRequest(<span style="color:#2b91af;">Object</span> sender, <span style="color:#2b91af;">EventArgs</span> e)</span><br />
{<br />
<span style="color:blue;"> if</span> (<span style="color:#2b91af;">HttpContext</span>.Current.Response.Status.StartsWith(<span style="color:#a31515;">&#8220;401&#8243;</span>))<br />
{<br />
<span style="color:#2b91af;"> HttpContext</span>.Current.Response.ClearContent();<br />
Server.Execute(<span style="color:#a31515;">&#8220;<span style="background-color:yellow;">AccessDenied.aspx</span>&#8220;</span>);<br />
}<br />
}</p>
<p>If we have further security requirements, we can do further checks any time by getting the IPrincipal from <strong>Page.User</strong> or <strong>HttpContext.Current.User</strong>. We could enable a button in our UI with a simple statement such as:</p>
<p>adminButton.Enabled = Page.User.IsInRole(@<span style="color:#800000;">&#8220;domain\domainadmins&#8221;</span>);</p>
<p>While the solution seems obvious and elegant, it took a bit of searching and playing to get it to work just right. There are other ways of centrally enforcing security such as Application_AuthenticateRequest in global.asax. However in this case it is far more configurable to take full advantage of the settings available to us in the <strong>web.config</strong>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codinglifestyle.wordpress.com/311/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codinglifestyle.wordpress.com/311/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codinglifestyle.wordpress.com/311/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codinglifestyle.wordpress.com/311/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codinglifestyle.wordpress.com/311/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codinglifestyle.wordpress.com/311/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codinglifestyle.wordpress.com/311/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codinglifestyle.wordpress.com/311/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codinglifestyle.wordpress.com/311/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codinglifestyle.wordpress.com/311/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codinglifestyle.wordpress.com/311/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codinglifestyle.wordpress.com/311/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codinglifestyle.wordpress.com/311/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codinglifestyle.wordpress.com/311/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=311&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codinglifestyle.wordpress.com/2011/01/20/asp-net-windows-authentication-authorization-by-ntlm-group-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5222f005f72ad1480c4929741e356423?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">codinglifestyle</media:title>
		</media:content>

		<media:content url="http://codinglifestyle.files.wordpress.com/2011/01/012011_1128_aspnetwindo1.png" medium="image" />
	</item>
		<item>
		<title>Late binding DataGridView data with BackgroundWorker threads</title>
		<link>http://codinglifestyle.wordpress.com/2010/10/18/late-binding-datagridview-data-with-backgroundworker-threads/</link>
		<comments>http://codinglifestyle.wordpress.com/2010/10/18/late-binding-datagridview-data-with-backgroundworker-threads/#comments</comments>
		<pubDate>Mon, 18 Oct 2010 12:40:58 +0000</pubDate>
		<dc:creator>codinglifestyle</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Winform]]></category>
		<category><![CDATA[BackgroundWorker]]></category>
		<category><![CDATA[DataGridView]]></category>
		<category><![CDATA[late binding]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://codinglifestyle.wordpress.com/?p=284</guid>
		<description><![CDATA[In an increasingly multicore world you may notice your WinForm app never pushes your machine to 100%.  Great, right?  Erm, no.  Winforms are traditionally single threaded applications meaning we typically only tap into 1/2, 1/4, or even 1/8th of our processor&#8217;s potential. I’ve recently been working on a utility containing a DataGridView for displaying work item data [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=284&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:Calibri;font-size:small;">In an increasingly multicore world you may notice your WinForm app never pushes your machine to 100%.  Great, right?  Erm, no.  Winforms are traditionally single threaded applications meaning we typically only tap into 1/2, 1/4, or even 1/8th of our processor&#8217;s potential.</span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:Calibri;font-size:small;">I’ve recently been working on a utility containing a DataGridView for displaying work item data from TFS. Some of the column data had to be calculated so when displaying 500+ records the whole app was slowing down considerably. What I wanted was a delayed binding such that the cell would be initially blank, launch a thread, and update itself when the thread returned with the value. It turned out this was pretty easy.</span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:Calibri;font-size:small;">First, use a data entity. You probably don’t have to, but I find having this layer offers an obvious place to add the changes I’ll cover below. The ideal place is in the bound property’s getter. Here you can see that the value is not yet calculated, launch a thread, and return blank or another default value in the meantime.</span></p>
<p style="background:white;margin:0;"><span style="font-family:Consolas;font-size:9pt;"> <span style="color:blue;">private</span> <span style="color:blue;">int</span> _nWeight = -1;</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9pt;"> <span style="color:blue;">public</span> <span style="color:blue;">int</span> Weight </span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9pt;"><span style="color:blue;"> get</span></span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;padding-left:30px;margin:0;"><span style="font-family:Consolas;font-size:9pt;"><span style="color:blue;"> if</span> (_nWeight &lt; 0)</span></p>
<p class="MsoNormal" style="line-height:normal;padding-left:30px;margin:0;"><span style="font-family:Consolas;font-size:9pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;padding-left:60px;margin:0;"><span style="font-family:Consolas;font-size:9pt;"><span style="color:#2b91af;"> Tfs</span>.GetWeight(Tag, GetWeightComplete);</span></p>
<p class="MsoNormal" style="line-height:normal;padding-left:60px;margin:0;"><span style="font-family:Consolas;font-size:9pt;"> _nWeight = 0;</span></p>
<p class="MsoNormal" style="line-height:normal;padding-left:30px;margin:0;"><span style="font-family:Consolas;font-size:9pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;padding-left:30px;margin:0;"><span style="font-family:Consolas;font-size:9pt;"><span style="color:blue;"> return</span> _nWeight;</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9pt;"> </span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9pt;"> <span style="color:blue;">private</span> <span style="color:blue;">void</span> GetWeightComplete(<span style="color:blue;">object</span> sender, <span style="color:#2b91af;">RunWorkerCompletedEventArgs</span> e)</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9pt;">_nWeight = (<span style="color:blue;">int</span>)e.Result;</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9pt;"><span style="color:blue;"> if</span> (Row &lt; <span style="color:#2b91af;">FormMain</span>.Instance.Grid.Rows.Count)</span></p>
<p class="MsoNormal" style="line-height:normal;padding-left:30px;margin:0;"><span style="font-family:Consolas;font-size:9pt;"><span style="color:#2b91af;"> FormMain</span>.Instance.Grid.InvalidateRow(Row);</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9pt;"> }</span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:Calibri;font-size:small;"> </span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:Calibri;font-size:small;">The property above represents the weight of the entity to be used in sorting or graphing by importance. Calculating the weight is a time intensive operation and is a great candidate for calculating in a worker thread. Notice a backing store, _nWeight, is used to check if the value has been calculated and also to cache the value. If _nWeight is uncached (-1) we launch the thread and return a default weight of 0 while the thread calculates the actual value. Notice when we call Tfs.GetWeight we pass the delegate, GetWeightComplete, as an argument. This function will ultimately be called when the thread returns.</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> <span style="color:blue;">public</span> <span style="color:blue;">static</span> <span style="color:blue;">void</span> GetWeight(<span style="color:#2b91af;">WorkItem</span> wi, <span style="color:#2b91af;">RunWorkerCompletedEventHandler</span> onCompleteEvent)</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"><span style="color:#2b91af;"> BackgroundWorker</span> worker    = <span style="color:blue;">new</span> <span style="color:#2b91af;">BackgroundWorker</span>();</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> worker.DoWork             += <span style="color:blue;">new</span> <span style="color:#2b91af;">DoWorkEventHandler</span>(GetWeightDoWork);</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> worker.RunWorkerCompleted += onCompleteEvent;</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> </span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> worker.RunWorkerAsync(wi);</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> </span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> <span style="color:blue;">private</span> <span style="color:blue;">static</span> <span style="color:blue;">void</span> GetWeightDoWork(<span style="color:blue;">object</span> sender, <span style="color:#2b91af;">DoWorkEventArgs</span> e)</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"><span style="color:#2b91af;"> WorkItem</span> wi = (<span style="color:#2b91af;">WorkItem</span>)e.Argument;</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> </span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"><span style="color:blue;"> int</span> result = 0;</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"><span style="color:blue;"> foreach</span> (<span style="color:#2b91af;">Revision</span> rev <span style="color:blue;">in</span> wi.Revisions)</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;padding-left:30px;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"><span style="color:blue;"> if</span> (rev.Fields[<span style="color:#2b91af;">CoreField</span>.ChangedBy].Value.ToString() == wi.Store.TeamFoundationServer.AuthenticatedUserDisplayName)</span></p>
<p class="MsoNormal" style="line-height:normal;padding-left:30px;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> result += 1;</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> </span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> result = <span style="color:#2b91af;">Math</span>.Min(result, 10);</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> </span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> e.Result = result;</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-family:Consolas;font-size:9.5pt;"> </span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:Calibri;font-size:small;"> </span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:Calibri;font-size:small;">When a call is made to GetWeight you can see it uses the standard System.CompnentModel.BackgroundWorker class to manage the work. This has two main advantages: 1) an easy to use asynchronous event based pattern and 2) uses the thread pool for optimal thread management. Notice the two events, DoWork and RunWorkerCompleted are set before the thread is launched and that we can pass an arguement via RunWorkerAsync. GetWeightDoWork is called when the thread is launched and sets the result to the event arguments.  When we leave this function the RunWorkerCompleted event is called.</span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:Calibri;font-size:small;">Finally, back in the data entity, GetWeightComplete is called when the thread has calculated the value.  The result is taken from the RunWorkercompletedEventArgs and set to the backing store. The form uses the singleton pattern and exposes the grid as a property (see <a href="http://codinglifestyle.wordpress.com/2007/06/27/afxgetmainwnd-in-c/" target="_blank">here</a>). This allows the data entity to easily invalidate the row which redraws the row taking the Weight value into account (in my case the weight determined the intensity of a yellow highlight drawn over the row indicating how often the authenticated user appeared in the work item&#8217;s revision history).</span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-family:Calibri;font-size:small;">The user experience when using the above method is truely fantastic.  You get a responsive UI which immediately displays information with calculated information quickly coming in a few seconds later.  The standard binding method of the DataGridView further enhances this experience by only binding the data currently shown to the user.  So if only the first 25 rows are displayed, only those values will be calculated.  As we scroll down to show more rows the DataGridView will calculate only the newly bound rows (saving loads of time for potentially 1000&#8242;s of rows never shown).  Good luck unlocking your other cores for a better UI experience.</span></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codinglifestyle.wordpress.com/284/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codinglifestyle.wordpress.com/284/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codinglifestyle.wordpress.com/284/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codinglifestyle.wordpress.com/284/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codinglifestyle.wordpress.com/284/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codinglifestyle.wordpress.com/284/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codinglifestyle.wordpress.com/284/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codinglifestyle.wordpress.com/284/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codinglifestyle.wordpress.com/284/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codinglifestyle.wordpress.com/284/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codinglifestyle.wordpress.com/284/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codinglifestyle.wordpress.com/284/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codinglifestyle.wordpress.com/284/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codinglifestyle.wordpress.com/284/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=284&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codinglifestyle.wordpress.com/2010/10/18/late-binding-datagridview-data-with-backgroundworker-threads/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5222f005f72ad1480c4929741e356423?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">codinglifestyle</media:title>
		</media:content>
	</item>
		<item>
		<title>Welcome Microsoft Delegate!  Lambda expressions right this way…</title>
		<link>http://codinglifestyle.wordpress.com/2010/07/03/welcome-microsoft-delegate-lamda-expressions-right-this-way%e2%80%a6/</link>
		<comments>http://codinglifestyle.wordpress.com/2010/07/03/welcome-microsoft-delegate-lamda-expressions-right-this-way%e2%80%a6/#comments</comments>
		<pubDate>Sat, 03 Jul 2010 08:45:24 +0000</pubDate>
		<dc:creator>codinglifestyle</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[anonymous]]></category>
		<category><![CDATA[anonymous delegate]]></category>
		<category><![CDATA[delegate]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[lambda]]></category>

		<guid isPermaLink="false">http://codinglifestyle.wordpress.com/?p=276</guid>
		<description><![CDATA[Delegates are deceptively great.  Without them something as simple as the OnClick event of a button would cease to work.  In a nutshell, they offer a simple way to pass a function as a parameter which in turn can be invoked anywhere, anytime.  Pointers for functions, very useful! In .NET v2.0 the anonymous delegate was [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=276&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-size:small;">Delegates are deceptively great.  Without them something as simple as the <em>OnClick</em> event of a button would cease to work.  In a nutshell, they offer a simple way to pass a function as a parameter which in turn can be invoked anywhere, anytime.  Pointers for functions, very useful!</span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-size:small;">In .NET v2.0 the anonymous delegate was quietly introduced, well at least it slipped my notice.  I read about them at the same time I read about Lambda functions.  I saw them laid bare without the syntactic sugar in all they’re simple glory.  As I was stuck on a .NET v2.0 project I found sugar-free anonymous delegates useful to, say, recursively find all controls of a given <span style="color:#558ed5;">Type</span> and execute a function on the matching controls. </span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-size:small;">More recently, I was working on a robust Windows service responsible for various IO operations.  It was vitally important each file operation (heretofore <em>fileop</em>) had its own comprehensive try/catch block.  As the number of <em>fileop</em>s increased the code looked like one huge catch block.</span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-size:small;">It was clear it would be nice to have just one try/catch block in a static utility class which could catch every IO exception conceivable.  Then I could replace each try/catch block with one-line:</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="color:blue;font-size:10pt;"> bool</span><span style="font-size:10pt;"> isBackedUp = <span style="color:#2b91af;">FileUtil</span>.FileOp(_logger, () =&gt; <span style="color:#2b91af;">File</span>.Copy(latestFilename, backupFilename, <span style="color:blue;">true</span>));</span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-size:small;"> </span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-size:small;">Notice the file copy on the other side of the lambda function syntax, <strong><span style="color:#558ed5;">() =&gt;</span></strong>, is what is executed in the try block below:</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> <span style="color:blue;">public</span> <span style="color:blue;">delegate</span> <span style="color:blue;">void</span> FileOperation();</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> </span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> <span style="color:blue;">internal</span> <span style="color:blue;">static</span> <span style="color:blue;">bool</span> FileOp(ILogger logger, FileOperation fileOp)</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> <span style="color:blue;">bool</span> success = <span style="color:blue;">false</span>;</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> <span style="color:blue;">try</span></span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> fileOp.DynamicInvoke();</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> success = <span style="color:blue;">true</span>;</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> <span style="color:blue;">catch</span> (<span style="color:#2b91af;">ArgumentException</span> argEx)</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> logger.Error(argEx, <span style="color:#a31515;">&#8220;Bad arguement(s) passed&#8221;</span>);</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> <span style="color:blue;">catch</span> (DirectoryNotFoundException dirEx)</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> logger.Error(dirEx, <span style="color:#a31515;">&#8220;The specified path is invalid&#8221;</span>);</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> <span style="color:blue;">catch</span> (FileNotFoundException fileEx)</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> logger.Error(fileEx, <span style="color:#a31515;">&#8220;The specified file was not found&#8221;</span>);</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> <span style="color:blue;">catch</span> (PathTooLongException pathEx)</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> logger.Error(pathEx, <span style="color:#a31515;">&#8220;The specified path, file name, or both exceed the system-defined maximum length&#8221;</span>);</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> <span style="color:blue;">catch</span> (IOException ioEx)</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> logger.Error(ioEx, <span style="color:#a31515;">&#8220;An I/O error has occurred&#8221;</span>);</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> <span style="color:blue;">catch</span> (<span style="color:#2b91af;">NotSupportedException</span> supportEx)</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> logger.Error(supportEx, <span style="color:#a31515;">&#8220;The requested operation was not supported&#8221;</span>);</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> <span style="color:blue;">catch</span> (SecurityException secEx)</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> logger.Error(secEx, <span style="color:#a31515;">&#8220;The caller does not have the required permission.&#8221;</span>);</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> <span style="color:blue;">catch</span> (<span style="color:#2b91af;">UnauthorizedAccessException</span> accessEx)</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> logger.Error(accessEx, <span style="color:#a31515;">&#8220;The caller does not have the required permission&#8221;</span>);</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> <span style="color:blue;">catch</span> (<span style="color:#2b91af;">Exception</span> ex)</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> {</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> logger.Error(ex, <span style="color:#a31515;">&#8220;General fileop exception&#8221;</span>);</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> }</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> </span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> <span style="color:blue;">return</span> success;</span></p>
<p class="MsoNormal" style="line-height:normal;margin:0;"><span style="font-size:10pt;"> }</span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-size:small;"> </span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-size:small;">Not only was this an elegant way to catch a comprehensive set of exceptions, but the resulting code was much more readable.</span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-size:small;">Of course we could pass bigger hunks of code and this is fine in moderation.  But the flip-side can mean less readable code when lambda functions (and especially lambda expressions) are used without restraint.  Readability for the whole team is paramount.  After all, too much syntactic sugar will rot your teeth!</span></p>
<p class="MsoNormal" style="margin:0 0 10pt;"><span style="font-size:small;">The brilliant thing about C# is the mind set of “I’m sure there’s a way to do this” is often rewarded with a little research. </span></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codinglifestyle.wordpress.com/276/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codinglifestyle.wordpress.com/276/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codinglifestyle.wordpress.com/276/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codinglifestyle.wordpress.com/276/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codinglifestyle.wordpress.com/276/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codinglifestyle.wordpress.com/276/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codinglifestyle.wordpress.com/276/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codinglifestyle.wordpress.com/276/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codinglifestyle.wordpress.com/276/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codinglifestyle.wordpress.com/276/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codinglifestyle.wordpress.com/276/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codinglifestyle.wordpress.com/276/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codinglifestyle.wordpress.com/276/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codinglifestyle.wordpress.com/276/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=276&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codinglifestyle.wordpress.com/2010/07/03/welcome-microsoft-delegate-lamda-expressions-right-this-way%e2%80%a6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5222f005f72ad1480c4929741e356423?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">codinglifestyle</media:title>
		</media:content>
	</item>
		<item>
		<title>Yet Another VS2010 Overview</title>
		<link>http://codinglifestyle.wordpress.com/2010/06/18/yet-another-vs2010-overview/</link>
		<comments>http://codinglifestyle.wordpress.com/2010/06/18/yet-another-vs2010-overview/#comments</comments>
		<pubDate>Fri, 18 Jun 2010 14:41:58 +0000</pubDate>
		<dc:creator>codinglifestyle</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>

		<guid isPermaLink="false">http://codinglifestyle.wordpress.com/?p=270</guid>
		<description><![CDATA[Today I attended a mediocre presentation by Paul Fallen which looked stellar compared to the atrocious overview put on at the Galway VS2010 Launch Event.  Paul had the look of a man who had seen these slides many times and glossed over them at speed.  In fairness, he was using the same presentation deck I’ve [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=270&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Today I attended a mediocre presentation by Paul Fallen which looked stellar compared to the atrocious overview put on at the Galway VS2010 Launch Event.  Paul had the look of a man who had seen these slides many times and glossed over them at speed.  In fairness, he was using the same presentation deck I’ve seen since TechEd 2008.  I think we had all seen several flavours of this overview by this time, so nobody seemed to mind.  Below are the few snippets of information to add to the smorgasbord of other snippets I’ve gleaned from other talks of this nature.</p>
<p>Please <a href="http://codinglifestyle.wordpress.com/tag/vs2010/">click here</a> for more comprehensive posts earlier on VS2010.</p>
<p>Here is the <a href="http://tinyurl.com/vs2010trainingkit">VS2010 Training Kit</a> which was used in the demos.</p>
<ul>
<li>Common Language Runtime
<ul>
<li>Latest version is CLR 4 (to go with .NET 4).</li>
<li>Previous version of CLR 2 encompassed .NET 2, 3, 3.5, 3.5SP1</li>
<li>Implications
<ul>
<li>App pool .NET Framework version</li>
<li>Incompatibilities running CLR frameworks side by side within same process
<ul>
<li>Think 3 COM objects accessing Outlook all using CLR1, 2, and 4</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>Managed Extensibility Framework (MEF)
<ul>
<li>Library in .NET that enables greater reuse of applications and components</li>
</ul>
</li>
<li>VS2010 &amp; C# 4.0
<ul>
<li>IDE
<ul>
<li>WPF editor – Ctrl + mouse wheel to zoom.  Handy for presentations
<ul>
<li>Box select (like command prompt selection)</li>
</ul>
</li>
<li>Breakpoint labelling, import/export, Intellitrace (covered below)</li>
<li>Code navigation improvements (Ctrl + , and Ctrl + &#8211; for back)</li>
<li>Call Hierarchy
<ul>
<li>Allows you to visualize all calls to and from a selected method, property, or constructor</li>
</ul>
</li>
<li>Improved Intellisense
<ul>
<li>Greatly improved javascript intellisense</li>
<li>Support for camel case</li>
<li>Can toggle (Ctrl + Space) between suggestive and consume first mode (handy for TDD)</li>
</ul>
</li>
<li>Test run record, fast forward</li>
<li>Better multi-monitor support, docking enhancements</li>
<li>Tracking requirements and tasks as work items</li>
</ul>
</li>
<li>Better control over ClientID</li>
<li>Routing moved out from MVP to general ASP.NET</li>
<li>Optional and named parameters</li>
<li>Improved website publishing, ClickOnce (see prev. posts)</li>
</ul>
</li>
<li>Parallelism
<ul>
<li>Pillars
<ul>
<li>Task Parallel Library (TPL)
<ul>
<li>He didn’t touch at all on the new <a href="http://msdn.microsoft.com/en-us/library/dd460717.aspx">task</a> concept</li>
</ul>
</li>
<li>Parallel LINQ (<a href="http://msdn.microsoft.com/en-us/library/dd460688.aspx">PLINQ</a>)
<ul>
<li>These are the extension methods to LINQ to turn query operators in to parallel operations.
<ul>
<li>var matches = from person in people.<strong>AsParallel(</strong>)</li>
<li>              where person.FirstName == &#8220;Bob&#8221;</li>
<li>              select person;</li>
</ul>
</li>
</ul>
</li>
<li>System.Threading significant updates</li>
<li>Coordination Data Structures (<a href="http://codinglifestyle.wordpress.com/wp-includes/js/tinymce/plugins/paste/•%09http:/blogs.msdn.com/b/pfxteam/archive/2008/06/18/8620615.aspx">CDS</a>)
<ul>
<li>Lightweight and scalable thread-safe data structures and synchronization primitives</li>
</ul>
</li>
</ul>
</li>
<li>Toolset
<ul>
<li>Debugger: record and visualize threads</li>
<li>Visualizer: View multiple stacks</li>
<li>IntelliTrace – new capability to record execution, play it backwards and forwards, even email it to another engineer and have them reproduce the problem on their box</li>
</ul>
</li>
<li>Other
<ul>
<li>Eventual depreciation of ThreadPool as higher level abstractions layer atop toolkit?</li>
<li><a href="http://msdn.microsoft.com/en-us/library/dd997364.aspx">Unified cancellation</a> using cancellation token</li>
</ul>
</li>
</ul>
</li>
<li>Dynamic Language Runtime (DLR)
<ul>
<li>New feature in CLR 4</li>
<li>Major new feature in C# 4 is <strong>dynamic</strong> type
<ul>
<li>What Linq was to C# 3.5</li>
</ul>
</li>
<li>Adds shared dynamic type system, standard hosting model and support to make it easy to generate fast dynamic code</li>
<li>Big boost working with COM: type equivalence, embedded interop, managed marshalling</li>
</ul>
</li>
<li>Windows Communication Framework (WCF)
<ul>
<li>Service discovery
<ul>
<li>Easier to discover endpoints</li>
<li>Imagine an IM chat program or devices that come and go</li>
</ul>
</li>
<li>REST support via WCF WebHttp Services
<ul>
<li>Available in the code gallery templates</li>
</ul>
</li>
</ul>
</li>
</ul>
<ul>
<li> 
<ul></ul>
</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codinglifestyle.wordpress.com/270/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codinglifestyle.wordpress.com/270/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codinglifestyle.wordpress.com/270/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codinglifestyle.wordpress.com/270/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codinglifestyle.wordpress.com/270/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codinglifestyle.wordpress.com/270/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codinglifestyle.wordpress.com/270/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codinglifestyle.wordpress.com/270/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codinglifestyle.wordpress.com/270/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codinglifestyle.wordpress.com/270/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codinglifestyle.wordpress.com/270/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codinglifestyle.wordpress.com/270/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codinglifestyle.wordpress.com/270/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codinglifestyle.wordpress.com/270/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codinglifestyle.wordpress.com&amp;blog=7497536&amp;post=270&amp;subd=codinglifestyle&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codinglifestyle.wordpress.com/2010/06/18/yet-another-vs2010-overview/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5222f005f72ad1480c4929741e356423?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">codinglifestyle</media:title>
		</media:content>
	</item>
	</channel>
</rss>
