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

<channel>
	<title>Dan Rigsby - Coding Up Style &#187; Common Libraries</title>
	<atom:link href="http://www.danrigsby.com/blog/index.php/category/common-libraries/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.danrigsby.com/blog</link>
	<description>Developer.Speaker.Blogger</description>
	<lastBuildDate>Tue, 17 Nov 2009 18:29:29 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Remove Icon from WPF Window</title>
		<link>http://www.danrigsby.com/blog/index.php/2008/05/26/remove-icon-from-wpf-window/</link>
		<comments>http://www.danrigsby.com/blog/index.php/2008/05/26/remove-icon-from-wpf-window/#comments</comments>
		<pubDate>Mon, 26 May 2008 17:07:55 +0000</pubDate>
		<dc:creator>Dan Rigsby</dc:creator>
				<category><![CDATA[Common Libraries]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://www.danrigsby.com/blog/index.php/2008/05/26/remove-icon-from-wpf-window/</guid>
		<description><![CDATA[In general, a window should always have an icon because it helps give context to the window.&#160; However, there are occasions when you may want a window with icon such as a custom tool window or some other dialog. In Windows Forms if you want a window without an icon, you could just simply set:
&#160;

this.ShowIcon [...]]]></description>
			<content:encoded><![CDATA[<div>In general, a window should always have an icon because it helps give context to the window.&#160; However, there are occasions when you may want a window with icon such as a custom tool window or some other dialog. In Windows Forms if you want a window without an icon, you could just simply set:</div>
<div>&#160;</div>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">this</span>.ShowIcon = <span style="color: #0000ff">false;</span></pre>
</div>
<div>&#160;</div>
<div>In WPF, there is no simple way to just remove the icon.&#160; If you try to just set the Icon to null, it will display the default windows icon.&#160; The only way to disable the icon is to use some interop code to remove the icon directly through the windows API:</div>
<div>&#160;</div>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">using</span> System;
<span style="color: #0000ff">using</span> System.Windows;
<span style="color: #0000ff">using</span> System.Windows.Interop;
<span style="color: #0000ff">using</span> System.Runtime.InteropServices;

<span style="color: #0000ff">public</span> <span style="color: #0000ff">partial</span> <span style="color: #0000ff">class</span> WindowWithoutIcon : Window
{
    [DllImport(<span style="color: #006080">&quot;user32.dll&quot;</span>)]
    <span style="color: #0000ff">static</span> <span style="color: #0000ff">extern</span> <span style="color: #0000ff">int</span> GetWindowLong(IntPtr hwnd, <span style="color: #0000ff">int</span> index);

    [DllImport(<span style="color: #006080">&quot;user32.dll&quot;</span>)]
    <span style="color: #0000ff">static</span> <span style="color: #0000ff">extern</span> <span style="color: #0000ff">int</span> SetWindowLong(IntPtr hwnd, <span style="color: #0000ff">int</span> index, <span style="color: #0000ff">int</span> newStyle);

    [DllImport(<span style="color: #006080">&quot;user32.dll&quot;</span>)]
    <span style="color: #0000ff">static</span> <span style="color: #0000ff">extern</span> <span style="color: #0000ff">bool</span> SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, <span style="color: #0000ff">int</span> x, <span style="color: #0000ff">int</span> y, <span style="color: #0000ff">int</span> width, <span style="color: #0000ff">int</span> height, <span style="color: #0000ff">uint</span> flags);

    [DllImport(<span style="color: #006080">&quot;user32.dll&quot;</span>)]
    <span style="color: #0000ff">static</span> <span style="color: #0000ff">extern</span> IntPtr SendMessage(IntPtr hwnd, <span style="color: #0000ff">uint</span> msg, IntPtr wParam, IntPtr lParam);

    <span style="color: #0000ff">const</span> <span style="color: #0000ff">int</span> GWL_EXSTYLE = -20;
    <span style="color: #0000ff">const</span> <span style="color: #0000ff">int</span> WS_EX_DLGMODALFRAME = 0x0001;
    <span style="color: #0000ff">const</span> <span style="color: #0000ff">int</span> SWP_NOSIZE = 0x0001;
    <span style="color: #0000ff">const</span> <span style="color: #0000ff">int</span> SWP_NOMOVE = 0x0002;
    <span style="color: #0000ff">const</span> <span style="color: #0000ff">int</span> SWP_NOZORDER = 0x0004;
    <span style="color: #0000ff">const</span> <span style="color: #0000ff">int</span> SWP_FRAMECHANGED = 0x0020;
    <span style="color: #0000ff">const</span> <span style="color: #0000ff">uint</span> WM_SETICON = 0x0080;

    <span style="color: #0000ff">public</span> MainWindow()
    {
        InitializeComponent();
    }

    <span style="color: #0000ff">protected</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> OnSourceInitialized(EventArgs e)
    {
        <span style="color: #0000ff">base</span>.OnSourceInitialized(e);

        <span style="color: #008000">// Get this window's handle</span>
        IntPtr hwnd = <span style="color: #0000ff">new</span> WindowInteropHelper(<span style="color: #0000ff">this</span>).Handle;

        <span style="color: #008000">// Change the extended window style to not show a window icon</span>
        <span style="color: #0000ff">int</span> extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
        SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_DLGMODALFRAME);

        <span style="color: #008000">// Update the window's non-client area to reflect the changes</span>
        SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
    }
}</pre>
</div>
<div>&#160;</div>
<div><em>Source derived from: </em><a title="http://blogs.msdn.com/wpfsdk/archive/2007/08/02/a-wpf-window-without-an-window-icon-the-thing-you-click-to-get-the-system-menu.aspx" href="http://blogs.msdn.com/wpfsdk/archive/2007/08/02/a-wpf-window-without-an-window-icon-the-thing-you-click-to-get-the-system-menu.aspx"><em>http://blogs.msdn.com/wpfsdk/archive/2007/08/02/a-wpf-window-without-an-window-icon-the-thing-you-click-to-get-the-system-menu.aspx</em></a></div>
<div>&#160;</div>
<div></div>
]]></content:encoded>
			<wfw:commentRss>http://www.danrigsby.com/blog/index.php/2008/05/26/remove-icon-from-wpf-window/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>How to grayout an image in .Net</title>
		<link>http://www.danrigsby.com/blog/index.php/2008/03/28/how-to-grayout-an-image-in-net/</link>
		<comments>http://www.danrigsby.com/blog/index.php/2008/03/28/how-to-grayout-an-image-in-net/#comments</comments>
		<pubDate>Sat, 29 Mar 2008 03:49:44 +0000</pubDate>
		<dc:creator>Dan Rigsby</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Common Libraries]]></category>

		<guid isPermaLink="false">http://www.danrigsby.com/blog/index.php/2008/03/28/how-to-grayout-an-image-in-net/</guid>
		<description><![CDATA[Here is a handy method for making a grayscale version of an image.&#160; I use this method a lot to grayout icons that I wish to show as disabled.&#160; All you need to do is pass in the image and it will apply a grayscale over it.&#160; The key to getting all of this to [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a handy method for making a grayscale version of an image.&nbsp; I use this method a lot to grayout icons that I wish to show as disabled.&nbsp; All you need to do is pass in the image and it will apply a grayscale over it.&nbsp; The key to getting all of this to work is the <a href="http://msdn2.microsoft.com/en-us/library/system.drawing.imaging.colormatrix.aspx">ColorMatrix</a>.&nbsp; There is a detailed article about how this works on codeproject: <a title="http://www.codeproject.com/KB/GDI-plus/colormatrix.aspx" href="http://www.codeproject.com/KB/GDI-plus/colormatrix.aspx">http://www.codeproject.com/KB/GDI-plus/colormatrix.aspx</a>.</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> ApplyGrayscale(
    <span style="color: #0000ff">ref</span> Image image)
{
    <span style="color: #008000">// Build color matrix set at 1/3</span>
    ColorMatrix matrix = <span style="color: #0000ff">new</span> ColorMatrix();
    matrix[0, 0] = 1/3f;
    matrix[0, 1] = 1/3f;
    matrix[0, 2] = 1/3f;
    matrix[1, 0] = 1/3f;
    matrix[1, 1] = 1/3f;
    matrix[1, 2] = 1/3f;
    matrix[2, 0] = 1/3f;
    matrix[2, 1] = 1/3f;
    matrix[2, 2] = 1/3f;

    <span style="color: #008000">// Create image attributes that will applied to the image</span>
    ImageAttributes attributes = <span style="color: #0000ff">new</span> ImageAttributes();
    attributes.SetColorMatrix(matrix);

    Graphics g = <span style="color: #0000ff">null</span>;
    <span style="color: #0000ff">try</span>
    {
        <span style="color: #008000">// Get the graphics object from the image</span>
        g = Graphics.FromImage(image);

        <span style="color: #008000">// Redraw the image on the graphics object using the grayscale color matrix</span>
        g.DrawImage(image,
            <span style="color: #0000ff">new</span> Rectangle(0, 0, image.Width, image.Height),
            0,
            0,
            image.Width,
            image.Height,
            GraphicsUnit.Pixel,
            attributes);
    }
    <span style="color: #0000ff">finally</span>
    {
        <span style="color: #0000ff">if</span> (g != <span style="color: #0000ff">null</span>)
        {
            g.Dispose();
        }
    }
}</pre>
</div>
<p>&nbsp;</p>
<p>Here are some sample before and after images (of my daughter Claire):</p>
<table cellspacing="0" cellpadding="2" width="400" border="0">
<tbody>
<tr>
<td valign="top" width="200"><a href="http://www.danrigsby.com/blog/wp-content/uploads/2008/03/claire.jpg"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="182" alt="claire" src="http://www.danrigsby.com/blog/wp-content/uploads/2008/03/claire-thumb.jpg" width="243" border="0"></a> </td>
<td valign="top" width="200"><a href="http://www.danrigsby.com/blog/wp-content/uploads/2008/03/clairegray.jpg"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="182" alt="clairegray" src="http://www.danrigsby.com/blog/wp-content/uploads/2008/03/clairegray-thumb.jpg" width="243" border="0"></a> </td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p>Here is another example with a more typical line-of-business image:</p>
<table cellspacing="0" cellpadding="2" width="538" border="0">
<tbody>
<tr>
<td valign="top" width="268"><a href="http://www.danrigsby.com/blog/wp-content/uploads/2008/03/disk-blue.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="48" alt="disk_blue" src="http://www.danrigsby.com/blog/wp-content/uploads/2008/03/disk-blue-thumb.png" width="48" border="0"></a> </td>
<td valign="top" width="268"><a href="http://www.danrigsby.com/blog/wp-content/uploads/2008/03/disk-bluegray.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="48" alt="disk_bluegray" src="http://www.danrigsby.com/blog/wp-content/uploads/2008/03/disk-bluegray-thumb.png" width="48" border="0"></a> </td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p>To make this easier to try out or use, I have wrapped the method into a executable as well.&nbsp; You can download the source for this here: <a href="http://www.danrigsby.com/Files/Rigsby.ImageUtilities.Grayscale.zip">http://www.danrigsby.com/Files/Rigsby.ImageUtilities.Grayscale.zip</a></p>
<p>To run the program, compile the code and execute the exe file while passing in the source file name and the file name you want to save the new grayscaled image to, like this:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">Rigsby.ImageUtilities.Grayscale.exe "c:\Claire.jpg" "c:\Claire-Gray.jpg"</pre>
</div>
<div>&nbsp;</div>
]]></content:encoded>
			<wfw:commentRss>http://www.danrigsby.com/blog/index.php/2008/03/28/how-to-grayout-an-image-in-net/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Disposable Base Class</title>
		<link>http://www.danrigsby.com/blog/index.php/2008/03/15/disposable-base-class/</link>
		<comments>http://www.danrigsby.com/blog/index.php/2008/03/15/disposable-base-class/#comments</comments>
		<pubDate>Sat, 15 Mar 2008 17:24:27 +0000</pubDate>
		<dc:creator>Dan Rigsby</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Common Libraries]]></category>

		<guid isPermaLink="false">http://www.danrigsby.com/blog/index.php/2008/03/15/disposable-base-class/</guid>
		<description><![CDATA[Many classes are built that implement System.IDisposable, which is a good thing.&#160; This pattern makes for a good design to clean up your objects and can be used by the using statement to easily dispose of your objects.&#160; This article already assumes that you know the basics of the Dispose Pattern. However sometimes having just [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.danrigsby.com/blog/wp-content/uploads/2008/03/trashcan.jpg"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" border="0" alt="trashcan" align="right" src="http://www.danrigsby.com/blog/wp-content/uploads/2008/03/trashcan-thumb.jpg" width="74" height="100" /></a>Many classes are built that implement <a href="http://msdn2.microsoft.com/en-us/library/system.idisposable.aspx">System.IDisposable</a>, which is a good thing.&#160; This pattern makes for a good design to clean up your objects and can be used by the <a href="http://msdn2.microsoft.com/en-us/library/yh598w02.aspx">using statement</a> to easily dispose of your objects.&#160; This article already assumes that you know the basics of the <a href="http://haacked.com/archive/2005/11/18/ACloserLookAtDisposePattern.aspx">Dispose Pattern</a>. However sometimes having just a Dispose() method isn&#8217;t always enough.&#160; Many times you a combination of a Disposed event, a void Dispose(bool disposing) method for use by a deconstructor, a boolean flag to check if the object IsDisposed, and maybe a method to check if the object is disposed that can throw an exception.&#160; Some &quot;best practices&quot; often dictate that you should be using some of these additional things.&#160; You may be writing this logic over and over again for each class, or you might start with a basic IDisposable pattern and weeks later you decide to refactor it to add in something like the boolean flag for IsDisposed.</p>
<p>After facing these same issues for awhile, I decided to put together a simple Diposable base class with all of the recommended patterns for using Disposable.&#160; Of course, this can&#8217;t always be used since you might already have a base class.&#160; But many times a class will derive from IDisposable and nothing else.&#160; This is just screaming for a Disposable base class that encapsulates this logic!&#160; For classes that already have a base class, I also have a code snippet to include everything that&#8217;s in the base class.</p>
<p>Here are the features of the Disposable Base Class and Code Snippet:</p>
<ol>
<li><strong>void Dispose() Method</strong> &#8211; This is just the standard Dispose method that is defined in the IDisposable interface. </li>
<li><strong>void Dispose(bool disposing) Method</strong> &#8211; This method is called from the Dispose() method passing in true.&#160; Its called from the deconstructor using false.&#160; This is the method that you should override in your parent class and check if disposing is true before disposing of managed code.&#160; The reason for this is that the deconstructor would have already disposed of the managed code, so you shouldn&#8217;t try to do it again.&#160; If the deconstrutor called this method, you should only dispose of unmanaged code. </li>
<li><strong>void CheckDisposed() Method</strong> &#8211; This method is marked protected and is used by the parent class to check if the object is disposed.&#160; It will throw an <a href="http://msdn2.microsoft.com/en-us/library/system.objectdisposedexception.aspx">ObjectDisposedException</a> if necessary. </li>
<li><strong>bool IsDisposed Property</strong> &#8211; A simple property to check whether or not this object has been disposed yet. </li>
<li><strong>Disposed Event</strong> &#8211; This event is fired when the object has been disposed. </li>
</ol>
<p>To use the base class, you just override the Dispose(bool disposing) method. An example of this base class in use could look like this:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> MyClass : Disposable
{
    <span style="color: #0000ff">protected</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> Dispose(<span style="color: #0000ff">bool</span> disposing)
    {
        <span style="color: #0000ff">if</span> (disposing)
        {
            <span style="color: #008000">// Dispose any managed code here</span>
        }

        <span style="color: #008000">// Dispose any unmanaged code here</span>

        <span style="color: #0000ff">base</span>.Dispose(disposing);
    }
}</pre>
</div>
<p>&#160;</p>
<p>Here is the base class:</p>
<div style="border-right: gray 1px solid; padding-right: 4px; padding-left: 4px; font-size: 8pt; border-top: gray 1px solid; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &#39;Courier New&#39;, courier, monospace; background-color: #f4f4f4">
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">using</span> System;
<span style="color: #0000ff">using</span> System.ComponentModel;

<span style="color: #0000ff">namespace</span> Rigsby
{
    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Represents a basic disposable class.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">abstract</span> <span style="color: #0000ff">class</span> Disposable : IDisposable
    {
        <span style="color: #cc6633">#region</span> Private Properties
        <span style="color: #0000ff">private</span> <span style="color: #0000ff">bool</span> m_IsDisposed = <span style="color: #0000ff">false</span>;
        <span style="color: #cc6633">#endregion</span> Private Properties

        <span style="color: #cc6633">#region</span> Public Properties
        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Gets a value indicating whether this instance is disposed.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;value&gt;</span>
        <span style="color: #008000">///     &lt;c&gt;true&lt;/c&gt; if this instance is disposed; otherwise, &lt;c&gt;false&lt;/c&gt;.</span>
        <span style="color: #008000">/// &lt;/value&gt;</span>
        [Browsable(<span style="color: #0000ff">false</span>)]
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">bool</span> IsDisposed
        {
            get
            {
                <span style="color: #0000ff">return</span> m_IsDisposed;
            }
        }
        <span style="color: #cc6633">#endregion</span> Public Properties

        <span style="color: #cc6633">#region</span> Constructors
        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Initializes a new instance of the &lt;see cref=&quot;Disposable&quot;/&gt; class.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #0000ff">public</span> Disposable()
        {
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Releases unmanaged resources and performs other cleanup operations before the</span>
        <span style="color: #008000">/// &lt;see cref=&quot;Disposable&quot;/&gt; is reclaimed by garbage collection.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        ~Disposable()
        {
            Dispose(<span style="color: #0000ff">false</span>);
        }
        <span style="color: #cc6633">#endregion</span> Constructors

        <span style="color: #cc6633">#region</span> IDisposable Members
        <span style="color: #0000ff">private</span> <span style="color: #0000ff">event</span> System.EventHandler m_Disposed;

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Occurs when this instance is disposed.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">event</span> System.EventHandler Disposed
        {
            add
            {
                m_Disposed += <span style="color: #0000ff">value</span>;
            }
            remove
            {
                m_Disposed -= <span style="color: #0000ff">value</span>;
            }
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Releases unmanaged and - optionally - managed resources</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Dispose()
        {
            <span style="color: #0000ff">if</span> (!m_IsDisposed)
            {
                <span style="color: #0000ff">this</span>.Dispose(<span style="color: #0000ff">true</span>);
                GC.SuppressFinalize(<span style="color: #0000ff">this</span>);
            }
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Releases unmanaged and - optionally - managed resources</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;param name=&quot;disposing&quot;&gt;&lt;c&gt;true&lt;/c&gt; to release both managed and unmanaged resources; &lt;c&gt;false&lt;/c&gt; to release only unmanaged resources.&lt;/param&gt;</span>
        <span style="color: #0000ff">protected</span> <span style="color: #0000ff">virtual</span> <span style="color: #0000ff">void</span> Dispose(<span style="color: #0000ff">bool</span> disposing)
        {
            <span style="color: #0000ff">try</span>
            {
                <span style="color: #0000ff">if</span> (disposing)
                {
                    EventHandler handler = m_Disposed;
                    <span style="color: #0000ff">if</span> (handler != <span style="color: #0000ff">null</span>)
                    {
                        handler(<span style="color: #0000ff">this</span>, EventArgs.Empty);
                        handler = <span style="color: #0000ff">null</span>;
                    }
                }
            }
            <span style="color: #0000ff">finally</span>
            {
                m_IsDisposed = <span style="color: #0000ff">true</span>;
            }
        }
        <span style="color: #cc6633">#endregion</span> IDisposable Members

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">///    &lt;para&gt;</span>
        <span style="color: #008000">///        Checks if the instance has been disposed of, and if it has, throws an &lt;see cref=&quot;ObjectDisposedException&quot;/&gt;; otherwise, does nothing.</span>
        <span style="color: #008000">///    &lt;/para&gt;</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;exception cref=&quot;ObjectDisposedException&quot;&gt;</span>
        <span style="color: #008000">///    The instance has been disposed of.</span>
        <span style="color: #008000">///    &lt;/exception&gt;</span>
        <span style="color: #008000">///    &lt;remarks&gt;</span>
        <span style="color: #008000">///    &lt;para&gt;</span>
        <span style="color: #008000">///        Derived classes should call this method at the start of all methods and properties that should not be accessed after a call to &lt;see cref=&quot;Dispose()&quot;/&gt;.</span>
        <span style="color: #008000">///    &lt;/para&gt;</span>
        <span style="color: #008000">/// &lt;/remarks&gt;</span>
        <span style="color: #0000ff">protected</span> <span style="color: #0000ff">void</span> CheckDisposed()
        {
            <span style="color: #0000ff">if</span> (m_IsDisposed)
            {
                <span style="color: #0000ff">string</span> typeName = GetType().FullName;

                <span style="color: #008000">// TODO: You might want to move the message string into a resource file</span>
                <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ObjectDisposedException(
                    typeName,
                    String.Format(System.Globalization.CultureInfo.InvariantCulture,
                        <span style="color: #006080">&quot;Cannot access a disposed {0}.&quot;</span>,
                        typeName));
            }
        }
    }
}</pre>
</div>
<p>Here is the code snippet version, or <a href="http://www.danrigsby.com/files/IDisposable.zip">download it here</a>.&#160; If you use the snippet, you will want to manually change your class to derive from the IDisposable interface, then add this snippet.</p>
<div style="border-right: gray 1px solid; padding-right: 4px; padding-left: 4px; font-size: 8pt; border-top: gray 1px solid; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &#39;Courier New&#39;, courier, monospace; background-color: #f4f4f4">
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">&lt;?</span><span style="color: #800000">xml</span> <span style="color: #ff0000">version</span><span style="color: #0000ff">=&quot;1.0&quot;</span> <span style="color: #ff0000">encoding</span><span style="color: #0000ff">=&quot;utf-8&quot;</span>?<span style="color: #0000ff">&gt;</span> <span style="color: #0000ff">&lt;</span><span style="color: #800000">CodeSnippets</span> <span style="color: #ff0000">xmlns</span><span style="color: #0000ff">=&quot;http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet&quot;</span><span style="color: #0000ff">&gt;</span>   <span style="color: #0000ff">&lt;</span><span style="color: #800000">CodeSnippet</span> <span style="color: #ff0000">Format</span><span style="color: #0000ff">=&quot;1.0.0&quot;</span><span style="color: #0000ff">&gt;</span>     <span style="color: #0000ff">&lt;</span><span style="color: #800000">Header</span><span style="color: #0000ff">&gt;</span>       <span style="color: #0000ff">&lt;</span><span style="color: #800000">Title</span><span style="color: #0000ff">&gt;</span>IDisposable<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Title</span><span style="color: #0000ff">&gt;</span>       <span style="color: #0000ff">&lt;</span><span style="color: #800000">Shortcut</span><span style="color: #0000ff">&gt;</span>       <span style="color: #0000ff">&lt;/</span><span style="color: #800000">Shortcut</span><span style="color: #0000ff">&gt;</span>       <span style="color: #0000ff">&lt;</span><span style="color: #800000">Description</span><span style="color: #0000ff">&gt;</span>Implements the IDisposable interface with additional best practices.<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Description</span><span style="color: #0000ff">&gt;</span>       <span style="color: #0000ff">&lt;</span><span style="color: #800000">Author</span><span style="color: #0000ff">&gt;</span>Dan Rigsby<span style="color: #0000ff">&lt;/</span><span style="color: #800000">Author</span><span style="color: #0000ff">&gt;</span>     <span style="color: #0000ff">&lt;/</span><span style="color: #800000">Header</span><span style="color: #0000ff">&gt;</span>     <span style="color: #0000ff">&lt;</span><span style="color: #800000">Snippet</span><span style="color: #0000ff">&gt;</span>       <span style="color: #0000ff">&lt;</span><span style="color: #800000">Code</span> <span style="color: #ff0000">Language</span><span style="color: #0000ff">=&quot;csharp&quot;</span><span style="color: #0000ff">&gt;&lt;!</span>[CDATA[        #region IDisposable Members
        private bool m_IsDisposed = false;
        private event System.EventHandler m_Disposed;

        /// <span style="color: #0000ff">&lt;</span><span style="color: #800000">summary</span><span style="color: #0000ff">&gt;</span>
        /// Gets a value indicating whether this instance is disposed.
        /// <span style="color: #0000ff">&lt;/</span><span style="color: #800000">summary</span><span style="color: #0000ff">&gt;</span>
        /// <span style="color: #0000ff">&lt;</span><span style="color: #800000">value</span><span style="color: #0000ff">&gt;</span>
        ///     <span style="color: #0000ff">&lt;</span><span style="color: #800000">c</span><span style="color: #0000ff">&gt;</span>true<span style="color: #0000ff">&lt;/</span><span style="color: #800000">c</span><span style="color: #0000ff">&gt;</span> if this instance is disposed; otherwise, <span style="color: #0000ff">&lt;</span><span style="color: #800000">c</span><span style="color: #0000ff">&gt;</span>false<span style="color: #0000ff">&lt;/</span><span style="color: #800000">c</span><span style="color: #0000ff">&gt;</span>.
        /// <span style="color: #0000ff">&lt;/</span><span style="color: #800000">value</span><span style="color: #0000ff">&gt;</span>
        [System.ComponentModel.Browsable(false)]
        public bool IsDisposed
        {
            get
            {
                return m_IsDisposed;
            }
        }

        /// <span style="color: #0000ff">&lt;</span><span style="color: #800000">summary</span><span style="color: #0000ff">&gt;</span>
        /// Occurs when this instance is disposed.
        /// <span style="color: #0000ff">&lt;/</span><span style="color: #800000">summary</span><span style="color: #0000ff">&gt;</span>
        public event System.EventHandler Disposed
        {
            add
            {
                m_Disposed += value;
            }
            remove
            {
                m_Disposed -= value;
            }
        }

        /// <span style="color: #0000ff">&lt;</span><span style="color: #800000">summary</span><span style="color: #0000ff">&gt;</span>
        /// Releases unmanaged and - optionally - managed resources
        /// <span style="color: #0000ff">&lt;/</span><span style="color: #800000">summary</span><span style="color: #0000ff">&gt;</span>
        public void Dispose()
        {
            if (!m_IsDisposed)
            {
                this.Dispose(true);
                System.GC.SuppressFinalize(this);
            }
        }

        /// <span style="color: #0000ff">&lt;</span><span style="color: #800000">summary</span><span style="color: #0000ff">&gt;</span>
        /// Releases unmanaged and - optionally - managed resources
        /// <span style="color: #0000ff">&lt;/</span><span style="color: #800000">summary</span><span style="color: #0000ff">&gt;</span>
        /// <span style="color: #0000ff">&lt;</span><span style="color: #800000">param</span> <span style="color: #ff0000">name</span><span style="color: #0000ff">=&quot;disposing&quot;</span><span style="color: #0000ff">&gt;&lt;</span><span style="color: #800000">c</span><span style="color: #0000ff">&gt;</span>true<span style="color: #0000ff">&lt;/</span><span style="color: #800000">c</span><span style="color: #0000ff">&gt;</span> to release both managed and unmanaged resources; <span style="color: #0000ff">&lt;</span><span style="color: #800000">c</span><span style="color: #0000ff">&gt;</span>false<span style="color: #0000ff">&lt;/</span><span style="color: #800000">c</span><span style="color: #0000ff">&gt;</span> to release only unmanaged resources.<span style="color: #0000ff">&lt;/</span><span style="color: #800000">param</span><span style="color: #0000ff">&gt;</span>
        protected virtual void Dispose(bool disposing)
        {
            try
            {
                if (disposing)
                {
                    System.EventHandler handler = m_Disposed;
                    if (handler != null)
                    {
                        handler(this, System.EventArgs.Empty);
                        handler = null;
                    }
                }
            }
            finally
            {
                m_IsDisposed = true;
            }
        }

        /// <span style="color: #0000ff">&lt;</span><span style="color: #800000">summary</span><span style="color: #0000ff">&gt;</span>
        ///    <span style="color: #0000ff">&lt;</span><span style="color: #800000">para</span><span style="color: #0000ff">&gt;</span>
        ///        Checks if the instance has been disposed of, and if it has, throws an <span style="color: #0000ff">&lt;</span><span style="color: #800000">see</span> <span style="color: #ff0000">cref</span><span style="color: #0000ff">=&quot;ObjectDisposedException&quot;</span><span style="color: #0000ff">/&gt;</span>; otherwise, does nothing.
        ///    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">para</span><span style="color: #0000ff">&gt;</span>
        /// <span style="color: #0000ff">&lt;/</span><span style="color: #800000">summary</span><span style="color: #0000ff">&gt;</span>
        /// <span style="color: #0000ff">&lt;</span><span style="color: #800000">exception</span> <span style="color: #ff0000">cref</span><span style="color: #0000ff">=&quot;System.ObjectDisposedException&quot;</span><span style="color: #0000ff">&gt;</span>
        ///    The instance has been disposed of.
        ///    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">exception</span><span style="color: #0000ff">&gt;</span>
        ///    <span style="color: #0000ff">&lt;</span><span style="color: #800000">remarks</span><span style="color: #0000ff">&gt;</span>
        ///    <span style="color: #0000ff">&lt;</span><span style="color: #800000">para</span><span style="color: #0000ff">&gt;</span>
        ///        Derived classes should call this method at the start of all methods and properties that should not be accessed after a call to <span style="color: #0000ff">&lt;</span><span style="color: #800000">see</span> <span style="color: #ff0000">cref</span><span style="color: #0000ff">=&quot;Dispose()&quot;</span><span style="color: #0000ff">/&gt;</span>.
        ///    <span style="color: #0000ff">&lt;/</span><span style="color: #800000">para</span><span style="color: #0000ff">&gt;</span>
        /// <span style="color: #0000ff">&lt;/</span><span style="color: #800000">remarks</span><span style="color: #0000ff">&gt;</span>
        protected void CheckDisposed()
        {
            if (m_IsDisposed)
            {
                string typeName = GetType().FullName;

                // TODO: You might want to move the message string into a resource file
                throw new System.ObjectDisposedException(
                    typeName,
                    String.Format(System.Globalization.CultureInfo.InvariantCulture,
                        &quot;Cannot access a disposed {0}.&quot;,
                        typeName));
            }
        }
        #endregion IDisposable Members]]<span style="color: #0000ff">&gt;&lt;/</span><span style="color: #800000">Code</span><span style="color: #0000ff">&gt;</span>     <span style="color: #0000ff">&lt;/</span><span style="color: #800000">Snippet</span><span style="color: #0000ff">&gt;</span>   <span style="color: #0000ff">&lt;/</span><span style="color: #800000">CodeSnippet</span><span style="color: #0000ff">&gt;</span> <span style="color: #0000ff">&lt;/</span><span style="color: #800000">CodeSnippets</span><span style="color: #0000ff">&gt;</span></pre>
</div>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fwww.danrigsby.com%2fblog%2findex.php%2f2008%2f03%2f15%2fdisposable-base-class%2f"><img border="0" alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fwww.danrigsby.com%2fblog%2findex.php%2f2008%2f03%2f15%2fdisposable-base-class%2f&amp;bgcolor=FF9900" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.danrigsby.com/blog/index.php/2008/03/15/disposable-base-class/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Generic Notify Property Change Controller</title>
		<link>http://www.danrigsby.com/blog/index.php/2008/03/14/generic-notify-property-change-controller/</link>
		<comments>http://www.danrigsby.com/blog/index.php/2008/03/14/generic-notify-property-change-controller/#comments</comments>
		<pubDate>Fri, 14 Mar 2008 12:57:35 +0000</pubDate>
		<dc:creator>Dan Rigsby</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Common Libraries]]></category>

		<guid isPermaLink="false">http://www.danrigsby.com/blog/index.php/2008/03/14/generic-notify-property-change-controller/</guid>
		<description><![CDATA[This is another example of a class you could put into a common library.&#160;&#160; Suppose I want to create a class that fires an event every time the value of a property changes.&#160; I could implement such a class like this:

public class MyClass : INotifyPropertyChanged
{
    private string m_Text;
    public [...]]]></description>
			<content:encoded><![CDATA[<p>This is <a href="http://www.danrigsby.com/blog/index.php/category/common-libraries/">another example</a> of a class you could put into a common library.&nbsp;&nbsp; Suppose I want to create a class that fires an event every time the value of a property changes.&nbsp; I could implement such a class like this:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> MyClass : INotifyPropertyChanged
{
    <span style="color: #0000ff">private</span> <span style="color: #0000ff">string</span> m_Text;
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> Text
    {
        get { <span style="color: #0000ff">return</span> m_Text; }
        set
        {
            <span style="color: #0000ff">if</span> (m_Text != <span style="color: #0000ff">value</span>)
            {
                m_Text = <span style="color: #0000ff">value</span>;
                OnPropertyChanged(<span style="color: #006080">"Text"</span>);
            }
        }
    }

    <span style="color: #0000ff">protected</span> <span style="color: #0000ff">virtual</span> <span style="color: #0000ff">void</span> OnPropertyChanged(
        <span style="color: #0000ff">string</span> propertyName)
    {
        PropertyChangedEventHandler handler = m_PropertyChanged;
        <span style="color: #0000ff">if</span> (handler != <span style="color: #0000ff">null</span>)
        {
            m_PropertyChanged(<span style="color: #0000ff">this</span>, <span style="color: #0000ff">new</span> PropertyChangedEventArgs(propertyName));
        }
    }

    <span style="color: #cc6633">#region</span> INotifyPropertyChanged Members
    <span style="color: #0000ff">private</span> <span style="color: #0000ff">event</span> PropertyChangedEventHandler m_PropertyChanged;
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">event</span> PropertyChangedEventHandler PropertyChanged
    {
        add { m_PropertyChanged += <span style="color: #0000ff">value</span>; }
        remove { m_PropertyChanged -= <span style="color: #0000ff">value</span>; }
    }
    <span style="color: #cc6633">#endregion</span> INotifyPropertyChanged Members
}</pre>
</div>
<div>&nbsp;</div>
<div>If you have a large class library and a lot of properties, this can add up to a lot of code.&nbsp; There is an easier way to do this at a <u>very</u> small cost of performance.&nbsp; Ill show the code for the PropertyController class at the end of this post, but this is an example of what the above code could look like:</div>
<div>&nbsp;</div>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> MyClass : INotifyPropertyChanged
{
    <span style="color: #0000ff">private</span> PropertyController m_PropertyController
    <span style="color: #0000ff">private</span> <span style="color: #0000ff">string</span> m_Text;
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> Text
    {
        get { <span style="color: #0000ff">return</span> m_Text; }
        set { m_PropertyController.ChangeProperty(<span style="color: #006080">"Text"</span>, <span style="color: #0000ff">value</span>);
    }

    <span style="color: #cc6633">#region</span> INotifyPropertyChanged Members
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">event</span> PropertyChangedEventHandler PropertyChanged
    {
        add { m_PropertyController.PropertyChanged += <span style="color: #0000ff">value</span>; }
        remove { m_PropertyController.PropertyChanged -= <span style="color: #0000ff">value</span>; }
    }
    <span style="color: #cc6633">#endregion</span> INotifyPropertyChanged Members
}</pre>
</div>
<p>&nbsp;</p>
<p>That is significantly less code and much cleaner.&nbsp; Just, imagine if I had a class library with 30 classes. </p>
<p>You could also do this:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">set { m_PropertyController.ChangeProperty(<span style="color: #006080">"Text"</span>, <span style="color: #0000ff">value</span>);</pre>
</div>
<p>&nbsp;</p>
<p>instead of:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">set { m_PropertyController.ChangeProperty(<span style="color: #0000ff">value</span>);</pre>
</div>
<p>&nbsp;</p>
<p>The cost of doing this is that the PropertyController has to look at the stack trace, but depending on what you are doing, this may be worth the cost.</p>
<p>The ChangeProperty method returns a boolean to indicate whether or not the value was changed.&nbsp; So inside your property code you could react depending on the result.</p>
<p>Here is the complete PropertyController class.&nbsp; Feel free to use it, modify it, ignore it, etc. You could even use this class and not even expose the PropertyChanged event, if you don&#8217;t need it.</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, 'Courier New', courier, monospace; background-color: #f4f4f4">
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> PropertyController : INotifyPropertyChanged, IDisposable
{
    <span style="color: #0000ff">private</span> Dictionary&lt;<span style="color: #0000ff">string</span>, PropertyInfo&gt; m_Properties =
        <span style="color: #0000ff">new</span> Dictionary&lt;<span style="color: #0000ff">string</span>, PropertyInfo&gt;();

    <span style="color: #0000ff">public</span> PropertyController()
    {
    }

    <span style="color: #cc6633">#region</span> INotifyPropertyChanged Members
    <span style="color: #0000ff">private</span> <span style="color: #0000ff">event</span> PropertyChangedEventHandler m_PropertyChanged;

    <span style="color: #0000ff">public</span> <span style="color: #0000ff">event</span> PropertyChangedEventHandler PropertyChanged
    {
        add
        {
            m_PropertyChanged += <span style="color: #0000ff">value</span>;
        }
        remove
        {
            m_PropertyChanged -= <span style="color: #0000ff">value</span>;
        }
    }
    <span style="color: #cc6633">#endregion</span> INotifyPropertyChanged Members

    <span style="color: #0000ff">protected</span> PropertyInfo GetProperty(<span style="color: #0000ff">string</span> propertyName)
    {
        <span style="color: #0000ff">if</span> (!m_Properties.ContainsKey(propertyName))
        {
            m_Properties.Add(propertyName, <span style="color: #0000ff">this</span>.GetType().GetProperty(propertyName));
        }

        <span style="color: #0000ff">return</span> m_Properties[propertyName];
    }

    <span style="color: #0000ff">public</span> <span style="color: #0000ff">virtual</span> <span style="color: #0000ff">bool</span> ChangeProperty(<span style="color: #0000ff">object</span> newValue)
    {
        <span style="color: #0000ff">return</span> ChangeProperty(<span style="color: #0000ff">new</span> System.Diagnostics.StackTrace().GetFrame(1).GetMethod().Name, newValue);
    }

    <span style="color: #0000ff">public</span> <span style="color: #0000ff">virtual</span> <span style="color: #0000ff">bool</span> ChangeProperty(<span style="color: #0000ff">string</span> propertyName, <span style="color: #0000ff">object</span> newValue)
    {
        System.Reflection.PropertyInfo property =
            GetProperty(propertyName);

        <span style="color: #0000ff">if</span> (property.GetValue(<span style="color: #0000ff">this</span>, <span style="color: #0000ff">null</span>) != newValue)
        {
            property.SetValue(<span style="color: #0000ff">this</span>, newValue, <span style="color: #0000ff">null</span>);
            OnPropertyChanged(propertyName);

            <span style="color: #0000ff">return</span> <span style="color: #0000ff">true</span>;
        }

        <span style="color: #0000ff">return</span> <span style="color: #0000ff">false</span>;
    }

    <span style="color: #0000ff">public</span> <span style="color: #0000ff">virtual</span> <span style="color: #0000ff">void</span> OnPropertyChanged(
        <span style="color: #0000ff">string</span> propertyName)
    {
        PropertyChangedEventHandler handler = m_PropertyChanged;
        <span style="color: #0000ff">if</span> (handler != <span style="color: #0000ff">null</span>)
        {
            m_PropertyChanged(<span style="color: #0000ff">this</span>, <span style="color: #0000ff">new</span> PropertyChangedEventArgs(propertyName));
        }
    }

    <span style="color: #cc6633">#region</span> IDisposable Members
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Dispose()
    {
        m_PropertyChanged = <span style="color: #0000ff">null</span>;
    }
    <span style="color: #cc6633">#endregion</span> IDisposable Members
}</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.danrigsby.com/blog/index.php/2008/03/14/generic-notify-property-change-controller/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to Extend the Provider Model to Make It Easy to Use</title>
		<link>http://www.danrigsby.com/blog/index.php/2008/02/22/how-to-extend-the-provider-model-to-make-it-easy-to-use/</link>
		<comments>http://www.danrigsby.com/blog/index.php/2008/02/22/how-to-extend-the-provider-model-to-make-it-easy-to-use/#comments</comments>
		<pubDate>Fri, 22 Feb 2008 19:21:33 +0000</pubDate>
		<dc:creator>Dan Rigsby</dc:creator>
				<category><![CDATA[Common Libraries]]></category>
		<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://www.danrigsby.com/blog/index.php/2008/02/22/how-to-extend-the-provider-model-to-make-it-easy-to-use/</guid>
		<description><![CDATA[The Provider Model has been around for quite awhile now and its in use all over the .Net Framework and Enterprise Library since .Net 2.0.&#160; The provider model allows you to program against an intermediary, while the actual implementation can be defined in the app.config file.&#160; The best example of this is a data access [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://msdn2.microsoft.com/en-us/library/ms972319.aspx">Provider Model</a> has been around for quite awhile now and its in use all over the .Net Framework and <a href="http://msdn2.microsoft.com/en-us/library/aa480453.aspx">Enterprise Library</a> since .Net 2.0.&#160; The provider model allows you to program against an intermediary, while the actual implementation can be defined in the app.config file.&#160; The best example of this is a data access layer.&#160; You might program a generic data access layer, but the actual implementation may be for Sql Server or Oracle and can be decided in the app.config file.&#160; I have used the provider model to abstract things such as a data access layer, a geocoding service, an authentication system, etc.&#160; Its nice to be able to just create a different implementation and swap it out in the app.config filer.</p>
<p>There is a decent amount of information out there (including a recent <a href="http://www.rosscode.com/blog/index.php?title=draft_creating_your_own_provider_framewo&amp;more=1&amp;c=1&amp;tb=1&amp;pb=1">post by Joel Ross</a>) and there is built in support for it in <a href="http://msdn2.microsoft.com/en-us/library/system.configuration.provider.aspx">System.Configuration.Provider</a>.&#160; However, while the tools in .Net make it possible to use the Provider Model, there is little guidance and some missing features in this namespace. This article is about how to extend the provider model to make it easier to use, and give a little insight into how it might be used.&#160; We are going to specifically look at the following areas:</p>
<ol>
<li>ProviderBase extensions:
<ol>
<li>Exposing the configuration values through the provider so they can be used later in the code </li>
<li>Using the provider type as the default name if no name is specified </li>
</ol>
</li>
<li>How to create a ProvidersSection that allows you to specify the default provider to use </li>
<li>ProviderCollection extensions:
<ol>
<li>Add Generics support </li>
<li>Add the ability to get an Provider by index instead of just by name </li>
</ol>
</li>
<li>How to build a generic ProviderRepository </li>
</ol>
<p><em>Note: At the bottom of this post I have zipped up all of the code and samples in this article.&#160; The sample included is a complete working example of the basic principles outlined here.</em></p>
<h2></h2>
<h2>Definitions</h2>
<p> <strong>Abstract Provider:</strong> an abstract class that services as a base for your providers.&#160; This usually contains all abstract methods and properties or overloaded methods and implementation details that can be shared by all providers.&#160; This usually derives from <a href="http://msdn2.microsoft.com/en-us/library/system.configuration.provider.providerbase.aspx">ProviderBase</a>.   </p>
<p><strong>Provider:</strong>&#160; the actual implementation of an abstract base provider.&#160; For instance, this could be your actual SQL Server implementation of the abstract data provider.</p>
<p><strong>ProvidersSection:</strong> the configuration section used by providers in the app.config file</p>
<p><strong>ProviderCollection:</strong> a collection of providers</p>
<p><strong>ProviderRepository:</strong> a repository that abstracts the need to manually try to determine which provider to use from the app.config file and wraps up tools needed to work with provider and the entire collection of providers.</p>
<h2>ProviderBase Extensions</h2>
<p>When working with the provider model each provider is named.&#160; This is important so that each provider in the list can be recognized from the others such as:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">&lt;DataService defaultProvider=<span style="color: #006080">&quot;SqlDataProvider&quot;</span>&gt;
    &lt;providers&gt;
        &lt;add
            name=<span style="color: #006080">&quot;SqlDataProvider&quot;</span>
            type=<span style="color: #006080">&quot;DataAccessLayer.SqlClient.SqlDataProvider, DataAccessLayer.SqlClient&quot;</span>
        /&gt;
        &lt;add
            name=<span style="color: #006080">&quot;OracleDataProvider&quot;</span>
            type=<span style="color: #006080">&quot;DataAccessLayer.OleDb.OracleDataProvider, DataAccessLayer.OleDb&quot;</span>
        /&gt;
    &lt;/providers&gt;
&lt;/DataService&gt;</pre>
</div>
<p>&#160;</p>
<p>As you can see, each provider has a name and a type.&#160; Here is my extended implementation of ProviderBase:</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &#39;Courier New&#39;, courier, monospace; background-color: #f4f4f4">
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">using</span> System;
<span style="color: #0000ff">using</span> System.Collections.Specialized;
<span style="color: #0000ff">using</span> System.Configuration;
<span style="color: #0000ff">using</span> System.Configuration.Provider;

<span style="color: #0000ff">namespace</span> Rigsby.Configuration.Provider
{
    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Provides a base implementation for the extensible provider model.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> ProviderBase : System.Configuration.Provider.ProviderBase
    {
        <span style="color: #cc6633">#region</span> Private Properties
        <span style="color: #0000ff">private</span> NameValueCollection m_Configuration = <span style="color: #0000ff">new</span> NameValueCollection();
        <span style="color: #0000ff">private</span> <span style="color: #0000ff">bool</span> m_IsInitialized = <span style="color: #0000ff">false</span>;
        <span style="color: #0000ff">private</span> <span style="color: #0000ff">string</span> m_Name = String.Empty;
        <span style="color: #cc6633">#endregion</span> Private Properties

        <span style="color: #cc6633">#region</span> Public Properties
        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Gets the configuration.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;value&gt;The configuration.&lt;/value&gt;</span>
        <span style="color: #0000ff">public</span> NameValueCollection Configuration
        {
            get
            {
                <span style="color: #0000ff">return</span> m_Configuration;
            }
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Gets or sets the friendly name used to refer to the provider during configuration.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;value&gt;&lt;/value&gt;</span>
        <span style="color: #008000">/// &lt;returns&gt;The friendly name used to refer to the provider during configuration.&lt;/returns&gt;</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">new</span> <span style="color: #0000ff">string</span> Name
        {
            get
            {
                <span style="color: #0000ff">return</span> m_Name;
            }
            set
            {
                m_Name = <span style="color: #0000ff">value</span>;
            }
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Gets a value indicating whether this instance is initialized.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;value&gt;</span>
        <span style="color: #008000">///     &lt;c&gt;true&lt;/c&gt; if this instance is initialized; otherwise, &lt;c&gt;false&lt;/c&gt;.</span>
        <span style="color: #008000">/// &lt;/value&gt;</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">bool</span> IsInitialized
        {
            get
            {
                <span style="color: #0000ff">return</span> m_IsInitialized;
            }
        }
        <span style="color: #cc6633">#endregion</span> Public Properties

        <span style="color: #cc6633">#region</span> Overrides
        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Initializes the provider.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Initialize()
        {
            Initialize(String.Empty);
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Initializes the provider.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;param name=&quot;name&quot;&gt;The friendly name of the provider.&lt;/param&gt;</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Initialize(
            <span style="color: #0000ff">string</span> name)
        {
            Initialize(name, <span style="color: #0000ff">new</span> NameValueCollection());
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Initializes the provider.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;param name=&quot;name&quot;&gt;The friendly name of the provider.&lt;/param&gt;</span>
        <span style="color: #008000">/// &lt;param name=&quot;config&quot;&gt;A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.&lt;/param&gt;</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> Initialize(
            <span style="color: #0000ff">string</span> name,
            NameValueCollection config)
        {
            <span style="color: #0000ff">if</span> (config == <span style="color: #0000ff">null</span>)
            {
                config = <span style="color: #0000ff">new</span> NameValueCollection();
            }

            <span style="color: #008000">// Get default name if empty or null</span>
            <span style="color: #0000ff">if</span> (String.IsNullOrEmpty(name))
            {
                <span style="color: #0000ff">if</span> (!String.IsNullOrEmpty(m_Name))
                {
                    name = m_Name;
                }
                <span style="color: #0000ff">else</span>
                {
                    name = <span style="color: #0000ff">this</span>.GetType().Name;
                }
            }
            m_Name = name;

            <span style="color: #008000">// Store configuration values</span>
            m_Configuration.Clear();
            <span style="color: #0000ff">foreach</span> (<span style="color: #0000ff">string</span> key <span style="color: #0000ff">in</span> config.Keys)
            {
                m_Configuration.Add(key, config[key]);
            }

            <span style="color: #008000">// Call the base class's Initialize method</span>
            <span style="color: #0000ff">base</span>.Initialize(name, config);

            m_IsInitialized = <span style="color: #0000ff">true</span>;
        }
        <span style="color: #cc6633">#endregion</span> Overrides
    }
}</pre>
</div>
<p>The default System.Configuration.Provider.ProviderBase will hide all of the configuration values after Initialize is called.&#160; I wanted to expose this collection so that you can add in custom configuration attributes easily and access them later in your code.&#160; The default provider base would also throw exceptions if there were any unknown attributes.&#160; I found this to be undesirable. If I wanted to add a new attribute that only one of my providers might need, I would want to be able to add it without it on the fly without having to extend my provider and make sure it understood the attribute.&#160; So now based on this new ProviderBase we can do things like this:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #008000">// Configuration file</span>
&lt;DataService defaultProvider=<span style="color: #006080">&quot;SqlDataProvider&quot;</span>&gt;
    &lt;providers&gt;
        &lt;add
            name=<span style="color: #006080">&quot;SqlDataProvider&quot;</span>
            type=<span style="color: #006080">&quot;DataAccessLayer.SqlClient.SqlDataProvider, DataAccessLayer.SqlClient&quot;</span>
            useStoredProcedure=<span style="color: #006080">&quot;true&quot;</span>
        /&gt;
    &lt;/providers&gt;
&lt;/DataService&gt;

<span style="color: #008000">// Code</span>
<span style="color: #0000ff">if</span> (provider.Configuration[<span style="color: #006080">&quot;useStoredProcedure&quot;</span>])
{
    <span style="color: #008000">// handle stored procedures</span>
}</pre>
</div>
<p>&#160;</p>
<p>This may not seem like much, but it can be a real time saver if you use the Provider Model a lot and need inject custom attributes.</p>
<h2>Creating a ProvidersSection</h2>
<p>In our previous example, we showed the list of providers an app.config file and the root configuration section specified a &quot;defaultProvider&quot; attribute.&#160; This is an example of the custom ProvidersSection.&#160; It&#8217;s just a generic ConfigurationSection that allows for a &quot;defaultProvider&quot; attribute and a collection of ProviderSettings.&#160; You can extend this to add your own attributes, but for most purposes any custom attributes you will need will be on the provider settings themselves and not on the ProvidersSection.</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &#39;Courier New&#39;, courier, monospace; background-color: #f4f4f4">
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">using</span> System;
<span style="color: #0000ff">using</span> System.Configuration;

<span style="color: #0000ff">namespace</span> Rigsby.Configuration.Provider
{
    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// A configuration section for a collection of providers.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> ProvidersSection : ConfigurationSection
    {
        <span style="color: #0000ff">private</span> <span style="color: #0000ff">const</span> <span style="color: #0000ff">string</span> m_DefaultProviderProperty = <span style="color: #006080">&quot;defaultProvider&quot;</span>;

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Gets the providers.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;value&gt;The providers.&lt;/value&gt;</span>
        [ConfigurationProperty(<span style="color: #006080">&quot;providers&quot;</span>)]
        <span style="color: #0000ff">public</span> ProviderSettingsCollection Providers
        {
            get
            {
                <span style="color: #0000ff">return</span> (ProviderSettingsCollection)<span style="color: #0000ff">base</span>[<span style="color: #006080">&quot;providers&quot;</span>];
            }
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Gets or sets the default provider.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;value&gt;The default provider.&lt;/value&gt;</span>
        [ConfigurationProperty(m_DefaultProviderProperty, IsRequired=<span style="color: #0000ff">false</span>)]
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> DefaultProvider
        {
            get
            {
                <span style="color: #0000ff">return</span> (<span style="color: #0000ff">string</span>)<span style="color: #0000ff">base</span>[m_DefaultProviderProperty];
            }
            set
            {
                <span style="color: #0000ff">base</span>[m_DefaultProviderProperty] = <span style="color: #0000ff">value</span>;
            }
        }
    }
}</pre>
</div>
<h2>ProviderCollection Extensions</h2>
<p>The default ProviderCollection does not contain support for generics.&#160; This means you have to do a lot of extra casting and things aren&#8217;t strongly typed.&#160; It is also setup to only allow retrieval of providers by name.&#160;&#160; In some cases you need to be able to get the provider by index.&#160; Suppose you want to setup the provider model to try to use the first provider in the list, and if that doesn&#8217;t work, then use the next provider, and so on.&#160; If you could only get the providers by name, there is no way to easily get the next provider.&#160; The custom ProviderCollection shown below adds generics support and the ability to retrieve a provider by index.</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &#39;Courier New&#39;, courier, monospace; background-color: #f4f4f4">
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">using</span> System;
<span style="color: #0000ff">using</span> System.Configuration;
<span style="color: #0000ff">using</span> System.Configuration.Provider;

<span style="color: #0000ff">namespace</span> Rigsby.Configuration.Provider
{
    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Represents a collection of provider objects that inherit from &lt;see cref=&quot;ProviderBase&quot;/&gt;.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;typeparam name=&quot;T&quot;&gt;&lt;/typeparam&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> ProviderCollection&lt;T&gt; : ProviderCollection
        <span style="color: #0000ff">where</span> T : Rigsby.Configuration.Provider.ProviderBase
    {
        <span style="color: #cc6633">#region</span> Public Properties
        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Gets the &lt;see cref=&quot;T:DataProvider&quot;/&gt; with the specified name.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;value&gt;&lt;/value&gt;</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">new</span> T <span style="color: #0000ff">this</span>[<span style="color: #0000ff">string</span> name]
        {
            get
            {
                <span style="color: #0000ff">return</span> (T)<span style="color: #0000ff">base</span>[name];
            }
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Gets the cref=&quot;&amp;lt;T&amp;gt;&quot;/&gt; at the specified index.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;value&gt;&lt;/value&gt;</span>
        <span style="color: #0000ff">public</span> T <span style="color: #0000ff">this</span>[<span style="color: #0000ff">int</span> index]
        {
            get
            {
                <span style="color: #0000ff">int</span> counter = 0;

                <span style="color: #0000ff">foreach</span>(T provider <span style="color: #0000ff">in</span> <span style="color: #0000ff">this</span>)
                {
                    <span style="color: #0000ff">if</span> (counter == index)
                    {
                        <span style="color: #0000ff">return</span> provider;
                    }
                    counter++;
                }

                <span style="color: #0000ff">return</span> <span style="color: #0000ff">null</span>;
            }
        }
        <span style="color: #cc6633">#endregion</span> Public Properties

        <span style="color: #cc6633">#region</span> Public Methods
        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Adds a provider to the collection.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;param name=&quot;provider&quot;&gt;The provider to be added.&lt;/param&gt;</span>
        <span style="color: #008000">/// &lt;permissionSet class=&quot;System.Security.permissionSet&quot; version=&quot;1&quot;&gt;</span>
        <span style="color: #008000">///     &lt;IPermission class=&quot;System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&quot; version=&quot;1&quot; Flags=&quot;UnmanagedCode, ControlEvidence&quot;/&gt;</span>
        <span style="color: #008000">/// &lt;/permissionSet&gt;</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> <span style="color: #0000ff">void</span> Add(
            System.Configuration.Provider.ProviderBase provider)
        {
            <span style="color: #0000ff">if</span> (!(provider <span style="color: #0000ff">is</span> T))
            {
                <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ArgumentException(
                    String.Format(&quot;The provider is not of type {0}.&quot;, <span style="color: #0000ff">typeof</span>(T).ToString()));
            }

            <span style="color: #0000ff">this</span>.Add((T)provider);
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Adds the specified provider.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;param name=&quot;provider&quot;&gt;The provider.&lt;/param&gt;</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Add(
            T provider)
        {
            <span style="color: #0000ff">if</span> (!provider.IsInitialized)
            {
                provider.Initialize();
            }

            <span style="color: #0000ff">base</span>.Add(provider);
        }
        <span style="color: #cc6633">#endregion</span> Public Methods
    }
}</pre>
</div>
<h2>Creating a Generic ProviderRepository</h2>
<p>All of the changes listed above are extensions of the the default provider model to make it easier to use.&#160; The ProviderRepository though is a new concept not in the default provider model, but builds on the extensions we have already talked about.&#160; The ProviderRepository is designed to encapsulate the loading of providers from the app.config file.&#160; It will contain the list of available providers and specify which provider should be used based on the &quot;defaultProvider&quot;. It is a generic class that takes in the type of provider you are working with.&#160; For most implementations you will probably be extending ProviderBase the, so you will use ProviderRepositoy&lt;MyProviderType&gt;.&#160; For example if you have a custom data access layer provider you might call it DataProvider and use ProviderRepository&lt;DataProvider&gt;.</p>
<p>In the ProviderRepository you specify the name of the configuration section to use from the app.config file. If you leave this null or empty, then it will attempt to look for a configuration section with same name as the generic provider type.&#160; So if you created it like ProviderRepository&lt;Rigsby.Test.DataAccessLayer&gt;, then it will look for a configuration section named &lt;Rigsby.Test.DataAccessLayer&gt; in the app.config file that is a ProvidersSection.</p>
<div style="border-right: gray 1px solid; padding-right: 4px; border-top: gray 1px solid; padding-left: 4px; font-size: 8pt; padding-bottom: 4px; margin: 20px 0px 10px; overflow: auto; border-left: gray 1px solid; width: 97.5%; cursor: text; max-height: 200px; line-height: 12pt; padding-top: 4px; border-bottom: gray 1px solid; font-family: consolas, &#39;Courier New&#39;, courier, monospace; background-color: #f4f4f4">
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">using</span> System;
<span style="color: #0000ff">using</span> System.Configuration;
<span style="color: #0000ff">using</span> System.Configuration.Provider;
<span style="color: #0000ff">using</span> System.Collections.Generic;
<span style="color: #0000ff">using</span> System.Text;
<span style="color: #0000ff">using</span> System.Web.Configuration;

<span style="color: #0000ff">namespace</span> Rigsby.Configuration.Provider
{
    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Represents a repository to give access to providers.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> ProviderRepository&lt;T&gt;
        <span style="color: #0000ff">where</span> T : ProviderBase
    {
        <span style="color: #cc6633">#region</span> Private Properties
        <span style="color: #0000ff">private</span> T m_Provider = <span style="color: #0000ff">null</span>;
        <span style="color: #0000ff">private</span> ProviderCollection&lt;T&gt; m_Providers = <span style="color: #0000ff">null</span>;
        <span style="color: #0000ff">private</span> <span style="color: #0000ff">volatile</span> <span style="color: #0000ff">object</span> m_SyncRoot = <span style="color: #0000ff">new</span> <span style="color: #0000ff">object</span>();

        <span style="color: #0000ff">private</span> <span style="color: #0000ff">string</span> m_SectionName = String.Empty;
        <span style="color: #cc6633">#endregion</span> Private Properties

        <span style="color: #cc6633">#region</span> Public Properties
        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Gets the provider.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;value&gt;The provider.&lt;/value&gt;</span>
        <span style="color: #0000ff">public</span> T Provider
        {
            get
            {
                <span style="color: #0000ff">if</span> (m_Provider == <span style="color: #0000ff">null</span> &amp;&amp; m_Providers.Count &gt; 0)
                {
                    m_Provider = m_Providers[0];
                }

                <span style="color: #0000ff">return</span> m_Provider;
            }
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Gets the providers.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;value&gt;The providers.&lt;/value&gt;</span>
        <span style="color: #0000ff">public</span> ProviderCollection&lt;T&gt; Providers
        {
            get
            {
                <span style="color: #0000ff">return</span> m_Providers;
            }
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Gets the name of the configuration section.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;value&gt;The name of the section.&lt;/value&gt;</span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> SectionName
        {
            get
            {
                <span style="color: #0000ff">return</span> m_SectionName;
            }
        }
        <span style="color: #cc6633">#endregion</span> Public Properties

        <span style="color: #cc6633">#region</span> Constructors
        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Initializes a new instance of the &lt;see cref=&quot;ProviderRepository&amp;lt;T&amp;gt;&quot;/&gt; class.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #0000ff">public</span> ProviderRepository(
            ) : <span style="color: #0000ff">this</span>(<span style="color: #0000ff">true</span>)
        {
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Initializes a new instance of the &lt;see cref=&quot;ProviderRepository&amp;lt;T&amp;gt;&quot;/&gt; class.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;param name=&quot;throwErrorIfUnableToLoadSection&quot;&gt;if set to &lt;c&gt;true&lt;/c&gt; [throw error if unable to load section].&lt;/param&gt;</span>
        <span style="color: #0000ff">public</span> ProviderRepository(
            <span style="color: #0000ff">bool</span> throwErrorIfUnableToLoadSection)
        {
            <span style="color: #0000ff">if</span> (String.IsNullOrEmpty(m_SectionName))
            {
                m_SectionName = <span style="color: #0000ff">typeof</span>(T).ToString();
            }

            LoadProviders(throwErrorIfUnableToLoadSection);
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Initializes a new instance of the &lt;see cref=&quot;ProviderRepository&amp;lt;T&amp;gt;&quot;/&gt; class.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;param name=&quot;sectionName&quot;&gt;Name of the section.&lt;/param&gt;</span>
        <span style="color: #0000ff">public</span> ProviderRepository(
            <span style="color: #0000ff">string</span> sectionName) : <span style="color: #0000ff">this</span>(sectionName, <span style="color: #0000ff">true</span>)
        {
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Initializes a new instance of the &lt;see cref=&quot;ProviderRepository&amp;lt;T&amp;gt;&quot;/&gt; class.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;param name=&quot;sectionName&quot;&gt;Name of the section.&lt;/param&gt;</span>
        <span style="color: #008000">/// &lt;param name=&quot;throwErrorIfUnableToLoadSection&quot;&gt;if set to &lt;c&gt;true&lt;/c&gt; [throw error if unable to load section].&lt;/param&gt;</span>
        <span style="color: #0000ff">public</span> ProviderRepository(
            <span style="color: #0000ff">string</span> sectionName,
            <span style="color: #0000ff">bool</span> throwErrorIfUnableToLoadSection)
        {
            m_SectionName = sectionName;
            LoadProviders(throwErrorIfUnableToLoadSection);
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Initializes a new instance of the &lt;see cref=&quot;ProviderRepository&amp;lt;T&amp;gt;&quot;/&gt; class.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;param name=&quot;provider&quot;&gt;The provider.&lt;/param&gt;</span>
        <span style="color: #0000ff">public</span> ProviderRepository(
            T provider)
        {
            m_Providers = <span style="color: #0000ff">new</span> ProviderCollection&lt;T&gt;();
            m_Providers.Add(provider);

            m_Provider = provider;
        }

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Initializes a new instance of the &lt;see cref=&quot;ProviderRepository&amp;lt;T&amp;gt;&quot;/&gt; class.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #008000">/// &lt;param name=&quot;providers&quot;&gt;The providers.&lt;/param&gt;</span>
        <span style="color: #0000ff">public</span> ProviderRepository(
            ProviderCollection&lt;T&gt; providers)
        {
            m_Providers = providers;
        }
        <span style="color: #cc6633">#endregion</span> Constructors

        <span style="color: #008000">/// &lt;summary&gt;</span>
        <span style="color: #008000">/// Loads the providers.</span>
        <span style="color: #008000">/// &lt;/summary&gt;</span>
        <span style="color: #0000ff">protected</span> <span style="color: #0000ff">virtual</span> <span style="color: #0000ff">void</span> LoadProviders(
            <span style="color: #0000ff">bool</span> throwErrorIfUnableToLoadSection)
        {
            <span style="color: #008000">// Avoid claiming lock if providers are already loaded</span>
            <span style="color: #0000ff">if</span> (m_Providers == <span style="color: #0000ff">null</span>)
            {
                <span style="color: #0000ff">lock</span> (m_SyncRoot)
                {
                    <span style="color: #008000">// Do this again to make sure provider is still null</span>
                    <span style="color: #0000ff">if</span> (m_Providers == <span style="color: #0000ff">null</span>)
                    {
                        <span style="color: #008000">// Get the providers</span>
                        m_Providers = <span style="color: #0000ff">new</span> ProviderCollection&lt;T&gt;();

                        <span style="color: #008000">// Get a reference to the section</span>
                        ProvidersSection section = <span style="color: #0000ff">null</span>;
                        <span style="color: #0000ff">try</span>
                        {
                            section =
                                ConfigurationManager.GetSection(m_SectionName) <span style="color: #0000ff">as</span> ProvidersSection;
                        }
                        <span style="color: #0000ff">catch</span> (Exception)
                        {
                            section = <span style="color: #0000ff">null</span>;
                        }

                        <span style="color: #0000ff">if</span> (section == <span style="color: #0000ff">null</span>)
                        {
                            <span style="color: #0000ff">if</span> (throwErrorIfUnableToLoadSection)
                            {
                                <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ProviderException(
                                    String.Format(<span style="color: #006080">&quot;Unable to load configuration section: '{0}'.&quot;</span>,
                                        m_SectionName));
                            }
                        }
                        <span style="color: #0000ff">else</span>
                        {
                            ProvidersHelper.InstantiateProviders(section.Providers, m_Providers, <span style="color: #0000ff">typeof</span>(T));

                            <span style="color: #0000ff">if</span> (m_Providers.Count &gt; 0)
                            {
                                <span style="color: #008000">// If there is a default provider specified, then grab it, </span>
                                <span style="color: #008000">// else grab the first provider in the collection</span>
                                <span style="color: #0000ff">if</span> (!String.IsNullOrEmpty(section.DefaultProvider))
                                {
                                    m_Provider = (T)m_Providers[section.DefaultProvider];
                                }
                                <span style="color: #0000ff">else</span>
                                {
                                    m_Provider = m_Providers[0];
                                }
                            }

                            <span style="color: #0000ff">if</span> (throwErrorIfUnableToLoadSection)
                            {
                                <span style="color: #008000">// If we have no provider, then throw an exception</span>
                                <span style="color: #0000ff">if</span> (m_Provider == <span style="color: #0000ff">null</span>)
                                {
                                    <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ProviderException(
                                        String.Format(<span style="color: #006080">&quot;Unable to load default provider for section: '{0}'.&quot;</span>,
                                            m_SectionName));
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}</pre>
</div>
<h2>Putting It All Together</h2>
<p>To get this all to work you just need to do the following:</p>
<ol>
<li>Create the base provider you want to use. This should derive from ProviderBase. </li>
<li>Created at least one implementation of your base provider. This should derive from the class you made in the previous step. </li>
<li>Setup a section in your app.config file to specify the providers. </li>
<li>Create an instance of the ProviderRepository&lt;&gt; in your code that you will use to reference the provider. </li>
</ol>
<p>Below are examples of these 4 steps to put all of this together.</p>
<p><strong>Step 1 Example:</strong></p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">abstract</span> <span style="color: #0000ff">class</span> DataProvider : ProviderBase
{
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">abstract</span> System.Data.DataTable GetRows();

    <span style="color: #0000ff">public</span> <span style="color: #0000ff">string</span> GetConnectionString()
    {
        <span style="color: #0000ff">string</span> connectionStringName = <span style="color: #0000ff">this</span>.Configuration[<span style="color: #006080">&quot;connectionStringName&quot;</span>];
        <span style="color: #0000ff">if</span> (String.IsNullOrEmpty(connectionStringName))
        {
            <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ProviderException(<span style="color: #006080">&quot;Empty or missing connectionStringName&quot;</span>);
        }
        <span style="color: #0000ff">if</span> (WebConfigurationManager.ConnectionStrings[connectionStringName] == <span style="color: #0000ff">null</span>)
        {
            <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> ProviderException(<span style="color: #006080">&quot;Missing connection string&quot;</span>);
        }

        <span style="color: #0000ff">return</span> WebConfigurationManager.ConnectionStrings
            [connectionStringName].ConnectionString;
    }
}</pre>
</div>
<p>&#160;</p>
<p><strong>Step 2 Example:</strong></p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> SqlDataProvider : DataProvider
{
    <span style="color: #008000">// TODO: Implement data access layer here</span>

    <span style="color: #008000">/// &lt;summary&gt;</span>
    <span style="color: #008000">/// Gets the rows.</span>
    <span style="color: #008000">/// &lt;/summary&gt;</span>
    <span style="color: #008000">/// &lt;returns&gt;&lt;/returns&gt;</span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">override</span> System.Data.DataTable GetRows()
    {
        <span style="color: #0000ff">return</span> <span style="color: #0000ff">new</span> System.Data.DataTable();
    }
}</pre>
</div>
<p>&#160;</p>
<p><strong>Step 3 Example:</strong></p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none">&lt;?xml version=<span style="color: #006080">&quot;1.0&quot;</span> encoding=<span style="color: #006080">&quot;utf-8&quot;</span> ?&gt;
&lt;configuration&gt;
    &lt;configSections&gt;
        &lt;section name=<span style="color: #006080">&quot;DataService&quot;</span>
            type=<span style="color: #006080">&quot;Rigsby.Configuration.Provider.ProvidersSection, Rigsby.Configuration.Provider&quot;</span>
            allowDefinition=<span style="color: #006080">&quot;MachineToApplication&quot;</span>
            restartOnExternalChanges=<span style="color: #006080">&quot;true&quot;</span> /&gt;
    &lt;/configSections&gt;

    &lt;connectionStrings&gt;
        &lt;add name=<span style="color: #006080">&quot;connectionString&quot;</span>
            providerName=<span style="color: #006080">&quot;System.Data.SqlClient&quot;</span>
            connectionString=<span style="color: #006080">&quot;Data Source=localhost;Initial Catalog=DB;UID=sa;PWD=;&quot;</span> /&gt;
    &lt;/connectionStrings&gt;

    &lt;DataService defaultProvider=<span style="color: #006080">&quot;SqlDataProvider&quot;</span>&gt;
        &lt;providers&gt;
            &lt;add
                name=<span style="color: #006080">&quot;SqlDataProvider&quot;</span>
                type=<span style="color: #006080">&quot;Rigsby.Configuration.Provider.Sample.DataAccessLayer.SqlDataProvider,
                    Rigsby.Configuration.Provider.Sample&quot;</span>
                connectionStringName=<span style="color: #006080">&quot;connectionString&quot;</span>
                providerInvariantName=<span style="color: #006080">&quot;System.Data.SqlClient&quot;</span>
            /&gt;
        &lt;/providers&gt;
    &lt;/DataService&gt;
&lt;/configuration&gt;</pre>
</div>
<div>&#160;</div>
<p><strong>Step 4 Example:</strong></p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, &#39;Courier New&#39;, courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">class</span> Program
{
    <span style="color: #0000ff">private</span> <span style="color: #0000ff">static</span> ProviderRepository&lt;DataAccessLayer.DataProvider&gt; m_DatabaseProviders =
        <span style="color: #0000ff">new</span> ProviderRepository&lt;DataAccessLayer.DataProvider&gt;(<span style="color: #006080">&quot;DataService&quot;</span>);

    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">void</span> Main(<span style="color: #0000ff">string</span>[] args)
    {
        Console.WriteLine(
            String.Format(<span style="color: #006080">&quot;ProviderName = '{0}'&quot;</span>, m_DatabaseProviders.Provider.Name));
        Console.WriteLine(
            String.Format(<span style="color: #006080">&quot;ConnectionString = '{0}'&quot;</span>, m_DatabaseProviders.Provider.GetConnectionString()));

        Console.ReadLine();
    }
}</pre>
</div>
<p>&#160;</p>
<p>Here is a link to the complete code and samples: <a title="http://www.danrigsby.com/files/rigsby.configuration.provider.zip" href="http://www.danrigsby.com/files/rigsby.configuration.provider.zip">http://www.danrigsby.com/files/rigsby.configuration.provider.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.danrigsby.com/blog/index.php/2008/02/22/how-to-extend-the-provider-model-to-make-it-easy-to-use/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ReadOnlyController Codeproject Published</title>
		<link>http://www.danrigsby.com/blog/index.php/2007/12/19/readonlycontroller-codeproject-published/</link>
		<comments>http://www.danrigsby.com/blog/index.php/2007/12/19/readonlycontroller-codeproject-published/#comments</comments>
		<pubDate>Wed, 19 Dec 2007 03:29:43 +0000</pubDate>
		<dc:creator>Dan Rigsby</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Common Libraries]]></category>

		<guid isPermaLink="false">http://www.danrigsby.com/wordpress/?p=24</guid>
		<description><![CDATA[I finally got around to publishing an article on codeproject.  I chose the ReadOnlyController as its a fairly simple concept, is an excellent demonstration of how to use the IExtenderProvider, and would be a small enough project to get up on codeproject and learn the ropes.  I have created projects on codeplex before.  Codeplex is [...]]]></description>
			<content:encoded><![CDATA[<p>I finally got around to <a href="http://www.codeproject.com/KB/cs/ReadOnlyController.aspx">publishing an article</a> on <a href="http://www.codeproject.com">codeproject</a>.  I chose the ReadOnlyController as its a fairly simple concept, is an excellent demonstration of how to use the IExtenderProvider, and would be a small enough project to get up on codeproject and learn the ropes.  I have created <a href="http://www.codeplex.com/IUPUIStellarResults">projects</a> on <a href="http://www.codeplex.com/">codeplex</a> before.  Codeplex is very nice, but is meant for projects.  Single components like the ReadOnlyController are better suited for codeproject.</p>
<p>The ReadOnlyController is a Component so that can be dropped on a form in design mode and implements IExtenderProvider so that it can extend the properties on controls on the form. Controls that have either a <code>Readonly </code>or <code>Enabled </code>property can be extended to enable control from the ReadOnly Controller. See the screenshot below for how this might look in the designer:</p>
<p><a href="http://codingupstyle.files.wordpress.com/2007/12/readonlycontroller.jpg"><img border="0" width="446" src="http://codingupstyle.files.wordpress.com/2007/12/readonlycontroller-thumb.jpg" alt="ReadOnlyController" height="386" style="border: 0px" /></a></p>
<p><strong>Link:</strong><br />
<a href="http://www.codeproject.com/KB/cs/ReadOnlyController.aspx" title="http://www.codeproject.com/KB/cs/ReadOnlyController.aspx">http://www.codeproject.com/KB/cs/ReadOnlyController.aspx</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.danrigsby.com/blog/index.php/2007/12/19/readonlycontroller-codeproject-published/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Missing static generic alternatives in Enum class?</title>
		<link>http://www.danrigsby.com/blog/index.php/2007/12/16/missing-static-generic-alternatives-in-enum-class/</link>
		<comments>http://www.danrigsby.com/blog/index.php/2007/12/16/missing-static-generic-alternatives-in-enum-class/#comments</comments>
		<pubDate>Sun, 16 Dec 2007 20:09:26 +0000</pubDate>
		<dc:creator>Dan Rigsby</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Common Libraries]]></category>

		<guid isPermaLink="false">http://www.danrigsby.com/wordpress/?p=23</guid>
		<description><![CDATA[I ran into an issue earlier this week while working with a generic class where one of the template parameters would represent a possible enum value.&#160; (Basically we have different enum lists representing different actions). You cant use a &#8220;where&#8221; clause for the enum class.&#160; So how would take a string or an int and [...]]]></description>
			<content:encoded><![CDATA[<p>I ran into an issue earlier this week while working with a generic class where one of the template parameters would represent a possible enum value.&nbsp; (Basically we have different enum lists representing different actions). You cant use a &#8220;where&#8221; clause for the enum class.&nbsp; So how would take a string or an int and cast it back to the type of enum defined in the template parameter? I had thought the static Enum class would provide new methods such as Enum.ToObject&lt;T&gt; and Enum.Parse&lt;T&gt; to match the non-generic methods, but they weren&#8217;t there.&nbsp; My needs here were pretty specific, but I soon realized that every time I cast an into to an enum I had to cast the result of Enum.ToObject(int) to the enum type.&nbsp; Why wouldn&#8217;t they have implemented generic methods for these common task?&nbsp; Generics were built for stuff like this.</p>
<p>Here is a basic EnumUtilities class I built to work around this issue and to assist with enum casting in the future:</p>
<div>
<pre style="padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0em; overflow: visible; width: 100%; color: black; border-top-style: none; line-height: 12pt; padding-top: 0px; font-family: consolas, 'Courier New', courier, monospace; border-right-style: none; border-left-style: none; background-color: #f4f4f4; border-bottom-style: none"><span style="color: #0000ff">using</span> System;
<span style="color: #0000ff">namespace</span> ININ.Common
{
    <span style="color: #008000">/// &lt;summary&gt;   </span>
    <span style="color: #008000">/// Utilities to assist with enums.   </span>
    <span style="color: #008000">/// &lt;/summary&gt;   </span>
    <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">class</span> EnumUtilities
    {
        <span style="color: #008000">/// &lt;summary&gt;       </span>
        <span style="color: #008000">/// Parses the enum.       </span>
        <span style="color: #008000">/// &lt;/summary&gt;       </span>
        <span style="color: #008000">/// &lt;typeparam name=”T”&gt;&lt;/typeparam&gt;       </span>
        <span style="color: #008000">/// &lt;param name=”name”&gt;The name.&lt;/param&gt;       </span>
        <span style="color: #008000">/// &lt;returns&gt;&lt;/returns&gt;       </span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> T ParseEnum&lt;T&gt;(
            <span style="color: #0000ff">string</span> name)
        {
            <span style="color: #0000ff">if</span> (String.IsNullOrEmpty(name))
            {
                <span style="color: #0000ff">throw</span> <span style="color: #0000ff">new</span> NullArguementException(<span style="color: #006080">"name is null or an empty string."</span>);
            }
            <span style="color: #0000ff">return</span> (T)Enum.Parse(<span style="color: #0000ff">typeof</span>(T), name);
        }        

        <span style="color: #008000">/// &lt;summary&gt;       </span>
        <span style="color: #008000">/// Parses the enum ID to the enum type.       </span>
        <span style="color: #008000">/// &lt;/summary&gt;       </span>
        <span style="color: #008000">/// &lt;typeparam name=”T”&gt;&lt;/typeparam&gt;       </span>
        <span style="color: #008000">/// &lt;param name=”i”&gt;The i.&lt;/param&gt;       </span>
        <span style="color: #008000">/// &lt;returns&gt;&lt;/returns&gt;       </span>
        <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> T ToObject&lt;T&gt;(
            <span style="color: #0000ff">int</span> i)
        {
            <span style="color: #0000ff">return</span> (T)Enum.ToObject(<span style="color: #0000ff">typeof</span>(T), i);
        }
    }
}</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.danrigsby.com/blog/index.php/2007/12/16/missing-static-generic-alternatives-in-enum-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
