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

<channel>
	<title>.Net Tips &#38; Tricks</title>
	<atom:link href="http://csharpsimplified.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://csharpsimplified.wordpress.com</link>
	<description>World of c# n WPF</description>
	<lastBuildDate>Mon, 23 Jan 2012 13:39:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='csharpsimplified.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>.Net Tips &#38; Tricks</title>
		<link>http://csharpsimplified.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://csharpsimplified.wordpress.com/osd.xml" title=".Net Tips &#38; Tricks" />
	<atom:link rel='hub' href='http://csharpsimplified.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Subclassing WPF user control</title>
		<link>http://csharpsimplified.wordpress.com/2011/09/21/subclassing-wpf-user-control/</link>
		<comments>http://csharpsimplified.wordpress.com/2011/09/21/subclassing-wpf-user-control/#comments</comments>
		<pubDate>Wed, 21 Sep 2011 05:57:20 +0000</pubDate>
		<dc:creator>KrunalC</dc:creator>
				<category><![CDATA[UserControl]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Inheritance]]></category>
		<category><![CDATA[subclassing]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://csharpsimplified.wordpress.com/?p=135</guid>
		<description><![CDATA[It is not very common to do User Control subclassing but if you have some compelling reason to do so then following detail explains how to do it with WPF User Control. Due to xaml, user control subclassing in WPF becomes little tricky. Following steps explain the procedure : 1. Create a base control as [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=135&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It is not very common to do User Control subclassing but if you have some compelling reason to do so then following detail explains how to do it with WPF User Control. Due to xaml, user control subclassing in WPF becomes little tricky. Following steps explain the procedure :</p>
<p>1. Create a base control as simple c# class and not WPF user control. Derive this base class from UserControl.</p>
<p><pre class="brush: csharp;">
    public class ESQBaseControl : UserControl
    {
		#region Constructor
		
        protected ESQBaseControl()
        {
            // protected constructor is required so that derived controls can have default parameterless constructor which is needed for xaml 
            // also protected constructor will ensure that new control creation always use constructor by passing parameters (e.g. in this example passing of string parameter is must in order to construct control)
        }

        public ESQBaseControl(string info)
        {
            
        }
		
		#endregion
		
		#region base implementation
		
		public virtual void SomeOperation()
		{
		
		}

		#endregion
	}
</pre><br />
2. Base class will not have UI implementation because of the absence of xaml. So time to build some UI for our control in concrete control xaml.</p>
<p><pre class="brush: csharp;">	
	&lt;view:ESQBaseControl x:Class=&quot;&lt;namespace&gt;.ESQConcreteControl&quot;
             xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
             xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot; 
             xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot; 
             xmlns:view=&quot;clr-namespace:&lt;namespace in which base control resides&gt;&quot;
             mc:Ignorable=&quot;d&quot; 
             d:DesignHeight=&quot;300&quot; d:DesignWidth=&quot;300&quot;&gt;
		&lt;Grid&gt;
			
			&lt;Grid.RowDefinitions&gt;
				&lt;RowDefinition/&gt;
				&lt;RowDefinition/&gt;
			&lt;/Grid.RowDefinitions&gt;

			&lt;Label Content=&quot;My Control&quot;/&gt;
			&lt;TextBox x:Name=&quot;MyTextBox&quot; Grid.Row=&quot;1&quot; Text=&quot;Some Text&quot;/&gt;
		&lt;/Grid&gt;
	&lt;/view:ESQBaseControl&gt;
</pre><br />
In above code note that whole xaml has been wrapped inside BaseControl class while class name inside xaml definition is given of the concrete class. </p>
<p>3. Finally, inside the code behind file user control&#8217;s concrete logic can be implemented :</p>
<p><pre class="brush: csharp;">
	public partial class ESQConcreteControl : ESQBaseControl
    {
        #region Constructor

        public ESQConcreteControl(string info) : base(info)
        {
            InitializeComponent();
        }
        
        #endregion
		
		#region Control implementation
		
		public override void SomeOperation()
		{
			myTextBox.Text = &quot;Hello World!!&quot;;
		}
		
		#endregion
	
	}
	</pre><br />
Hope this helps!!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/csharpsimplified.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/csharpsimplified.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/csharpsimplified.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/csharpsimplified.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/csharpsimplified.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/csharpsimplified.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/csharpsimplified.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/csharpsimplified.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/csharpsimplified.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/csharpsimplified.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/csharpsimplified.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/csharpsimplified.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/csharpsimplified.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/csharpsimplified.wordpress.com/135/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=135&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://csharpsimplified.wordpress.com/2011/09/21/subclassing-wpf-user-control/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5e385adf2aca841d63bedab64edb3629?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">krunalc</media:title>
		</media:content>
	</item>
		<item>
		<title>Interop &amp; IDataErrorInfo</title>
		<link>http://csharpsimplified.wordpress.com/2011/09/17/124/</link>
		<comments>http://csharpsimplified.wordpress.com/2011/09/17/124/#comments</comments>
		<pubDate>Fri, 16 Sep 2011 18:11:42 +0000</pubDate>
		<dc:creator>KrunalC</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Interop]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[AdornerLayer]]></category>
		<category><![CDATA[FocusStyle]]></category>
		<category><![CDATA[IDataErrorInfo]]></category>
		<category><![CDATA[interop]]></category>
		<category><![CDATA[PropertySheet]]></category>

		<guid isPermaLink="false">http://csharpsimplified.wordpress.com/?p=124</guid>
		<description><![CDATA[Despite of all the interop support available sometimes you will still come across some tricky issues which will be difficult to overcome. One such problem I faced recently. I had to configure the Dialog with MFC PropertySheet control. This PropertySheet control was holding few Property pages. These property pages didn’t had any MFC controls as [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=124&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Despite of all the interop support available sometimes you will still come across some tricky issues which will be difficult to overcome. One such problem I faced recently. I had to configure the Dialog with MFC PropertySheet control. This PropertySheet control was holding few Property pages. These property pages didn’t had any MFC controls as content but hosting the user controls developed in WPF. First  I will write very briefly about how to load the WPF user control inside the MFC container and then I will explain about my tricky problem and how I fixed it.</p>
<p>Hosting of WPF user control as content of PropertyPage wasn’t that challenging. In order to host the WPF content inside property page, first HwndSource needs to be configured. In order to create HwndSource, first you need to create HwndSourceParameter. Typical configuration for HwndSourceParameter can be as under :</p>
<p><pre class="brush: csharp;">
System::Windows::Interop::HwndSourceParameters^ sourceParams = gcnew System::Windows::Interop::HwndSourceParameters (&lt;Window Name&gt;);

// X position where WPF content to be placed
sourceParams-&gt;PositionX = x;
// Y position where WPF content to be placed
sourceParams-&gt;PositionY = y;
// height of the WPF content
sourceParams-&gt;Height = height;
// width of the WPF content
sourceParams-&gt;Width = width;
// Handle for the Parent window inside which WPF content to be hosted
sourceParams-&gt;ParentWindow = IntPtr(parent);
// style attributes as needed (“WS_TABSTOP” style needs to be set if WPF content needs to get focus while tabbing
sourceParams-&gt;WindowStyle = WS_VISIBLE | WS_CHILD | WS_TABSTOP;</pre></p>
<blockquote><p>Another important property for HwndSourceParams is “ResetFocusMode”. Default value for this property is “Auto”. Setting this property to “Auto” makes sure that when when the PropertySheet control (in my case) looses the focus and receives focus back the control which had focus prior to loosing focus retains the focus back. If you set this property to “None” then, none of the controls inside the page will have focus when propertysheet control receives the focus.</p></blockquote>
<p><pre class="brush: csharp;">
// now create HwndSource using this parameters
System::Windows::Interop::HwndSource^ hwndSource = gcnew HwndSource(*sourceParams)</pre></p>
<p>Now suppose I have a WPF user control named “PageUserControl” then create instance of this user control.<br />
<pre class="brush: csharp;">PageContentUserControl^ pageContent = gcnew PageContentUserControl();
//Now set this user control as RootVisual of HwndSource object. 
hwndSource-&gt;RootVisual = pageContent ;</pre></p>
<p>With above code in place it is possible to host the WPF content inside MFC control. This is just basic information which one should know in order to host the WPF content inside MFC container however somewhat plumbing work will be needed depending upon MFC container control in which you are placing the WPF control. </p>
<p>After hosting the control I had one more issue to deal with. My User control developed in WPF had few checkboxes, text boxes, etc. as it’s content. In order to validate my inputs and giving visual indication about the data validation failure, I had implemented interface “IDataErrorInfo”. (Now how this interface is implemented and how it works is not covered in this Post. Google it to find more on it)</p>
<p>When “IDataErrorInfo” interface implemented and bound value to the control  is invalid, control will have a red border around it to indicate user about the validation failure. Also, when you set focus on the control like check box through tabbing, you will not be able to see the dotted line around check box when it receives the focus. Following figure shows the focus styles for each case. When User Control is hosted within MFC container, you will assume that “IDataErrorInfo” implementation should work but infect it won’t.</p>
<p><a href="http://csharpsimplified.files.wordpress.com/2011/09/untitled.png"><img src="http://csharpsimplified.files.wordpress.com/2011/09/untitled.png?w=600" alt="" title="Untitled"   class="aligncenter size-full wp-image-125" /></a></p>
<p>The problem of not being able to see all such decoration is absence of Adorner layer. All these error templates and focus styles etc. are drawn inside the AdornerLayer.  The WPF window has an AdornerLayer by default, so we can always see validation errors in WPF. When hosting a user control in MFC, adornerlayer is not available by default and need to add an AdornerLayer into your UserControl to support adorners.</p>
<p>So in order to view all such Focus styles / Error template styles, we need to decorate the UserControl with AdornerDecorator. So following code should do the fix for you :</p>
<p><pre class="brush: csharp;">
&lt;UserControl x:Class=&quot;TestPjt.TestUC&quot;
             xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
             xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot; 
             xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
             xmlns:local=&quot;clr-namespace:TestPjt&quot;
             mc:Ignorable=&quot;d&quot; 
             d:DesignHeight=&quot;50&quot; d:DesignWidth=&quot;300&quot;&gt;
    &lt;AdornerDecorator&gt;
        &lt;Grid&gt;
              &lt;TextBox x:Name=&quot;txtbox&quot;/&gt;
        &lt;/Grid&gt;
    &lt;/AdornerDecorator&gt;
&lt;/UserControl&gt;</pre></p>
<p>This fix will start showing the expected focus and error template style for each control. HTH!!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/csharpsimplified.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/csharpsimplified.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/csharpsimplified.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/csharpsimplified.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/csharpsimplified.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/csharpsimplified.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/csharpsimplified.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/csharpsimplified.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/csharpsimplified.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/csharpsimplified.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/csharpsimplified.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/csharpsimplified.wordpress.com/124/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/csharpsimplified.wordpress.com/124/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/csharpsimplified.wordpress.com/124/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=124&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://csharpsimplified.wordpress.com/2011/09/17/124/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5e385adf2aca841d63bedab64edb3629?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">krunalc</media:title>
		</media:content>

		<media:content url="http://csharpsimplified.files.wordpress.com/2011/09/untitled.png" medium="image">
			<media:title type="html">Untitled</media:title>
		</media:content>
	</item>
		<item>
		<title>Destructor &#8211; Finalize &amp; IDispose</title>
		<link>http://csharpsimplified.wordpress.com/2010/10/03/destructor-finalize-idispose/</link>
		<comments>http://csharpsimplified.wordpress.com/2010/10/03/destructor-finalize-idispose/#comments</comments>
		<pubDate>Sat, 02 Oct 2010 18:02:24 +0000</pubDate>
		<dc:creator>KrunalC</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Dispose]]></category>
		<category><![CDATA[GarbageCollection]]></category>
		<category><![CDATA[Destructor]]></category>
		<category><![CDATA[Finalizer]]></category>
		<category><![CDATA[Garbage Collector]]></category>
		<category><![CDATA[IDisposable]]></category>

		<guid isPermaLink="false">https://csharpsimplified.wordpress.com/2010/10/03/destructor-finalize-idispose/</guid>
		<description><![CDATA[This post is about techniques on how managed/unmanaged resources used/referenced by objects can be released. There are two ways to do this. They are namely, 1. Implement IDisposable 2. Implement Destructor (Finalize) for object. This post describes how both gets implemented and what are the pros n cons of both ways. Destructor &#38; Finalize : [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=114&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span style="color:#000080;font-size:x-small;"><span style="color:#555555;">This post is about techniques on how managed/unmanaged resources used/referenced by objects can be released. There are two ways to do this. They are namely,</span></span></p>
<p><span style="font-size:x-small;">1. Implement IDisposable</span></p>
<p><span style="font-size:x-small;">2. Implement Destructor (Finalize) for object.</span></p>
<p><span style="font-size:x-small;">This post describes how both gets implemented and what are the pros n cons of both ways. </span></p>
<p><span style="color:#000080;font-size:x-small;"><strong>Destructor &amp; Finalize</strong></span> :</p>
<p>Destructor in managed code can be written in similar way as unmanaged code.</p>
<p><pre class="brush: csharp;">
 class TestClass
{
    ~TestClass()  // destructor implementation
    {
        // free resources
    }
}
</pre></p>
<p>When destructor is written in managed code, it ultimately translates into following code post compilation :</p>
<p><pre class="brush: csharp;">
protected override void Finalize()
{
    try
    {
        // free resources here
    }
    finally
    {
        base.Finalize();
    }
}
</pre></p>
<p>(So this means both destructor &amp; Finalize are same in managed context.)</p>
<p><strong><em>How destructor works</em></strong> :</p>
<p><span style="color:#000000;">When reference count becomes zero for the object which implements destructor then that object is marked for collection and object is put into the finalization queue. When garbage collector start collecting the memory, at that time destructor for the objects in the finalization queue will be called. When destructor is called then unmanaged resources can be freed and object memory is collected. </span></p>
<p><span style="color:#000080;font-size:x-small;"><strong>IDispose</strong></span> :</p>
<p>IDispose is basically .net framework interface which defines the method to release the allocated resources. Inside the interface method implementation should be present to release the resources.</p>
<p><strong><em><span style="color:#000000;">How IDispose work</span></em></strong> :</p>
<p>Let’s consider following code to understand how IDispose and destructor work in tandem. In following example “TestClass” implements IDisposable and also implements destructor. This code uses managed resource StreamReader and unmanaged some Integer pointer which needs to be freed before object is freed after it’s use.</p>
<p><pre class="brush: csharp;">
    public class TestClass: IDisposable
    {
        // Pointer to an external unmanaged resource.
        private IntPtr intPointer;
        // managed resource
        System.IO.StreamReader stream;
        // Track whether Dispose has been called.
        private bool disposed = false;

        // The class constructor.
        public TestClass()
        {
            this.intPointer = /* assign some integer pointer*/;
            stream = new System.IO.StreamReader(@&quot;C:\Test.txt&quot;);
        }

        // Implement IDisposable.
        public void Dispose()
        {
            Dispose(true);
            // as dispose has already been called supress finalizer
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if(!this.disposed)
            {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if(disposing)
                {
                    // Dispose managed resources.
                    stream.Close();
                }

                // dispose unmanaged resources here.
                intPointer = IntPtr.Zero;

                // Note disposing has been done.
                disposed = true;

            }
        }

        // destructor
        ~TestClass()
        {
            Dispose(false);
        }
    }
</pre></p>
<p>Dispose method with private accessor is being called from both interface Dispose method as well as destructor. When Dispose is called, first managed resource is freed and after that unmanaged resource is freed. Thus both managed and unmanaged resources are freed. After clearing the resources, GC.SupressFinalize is called so that the object is removed from finalize queue.</p>
<p>Now the question is when IDisposable and destructor are doing the same thing then why two separate things are required. Answer of this question lies in the nature of the execution of both these implementation.</p>
<p><span style="color:#000080;"><strong>Difference between Descturctor-Finalize &amp; IDisposable</strong></span> :</p>
<p>Destructor is not deterministic way of freeing the resource. When object with destructor is marked for garbage collection, it will be put inside the finalization queue. Whenever garbage collector runs, object inside the finalization queue will free the resources. Because time when the garbage collector will run is not sure, it can not be predicted when resources will be freed.</p>
<p>IDisposable is deterministic way of freeing the resource. IDisposable is useful when some shared resources or some high memory consuming resources needs to be freed. Calling the dispose on the object will ensure that resources are freed immediately (however memory associated to the object may not get collected until garbage collector runs).</p>
<p><span style="color:#000080;"><strong>Some Finer points about Destructor-finalize &amp; IDisposable</strong></span> :</p>
<p><strong><em>Destructor &#8211; Finalize</em></strong> :</p>
<ol>
<li>Finalize is not a good option to use when shared resources / memory consuming resources needs to be freed because of it’s non deterministic nature.</li>
<li>Releasing the resources using Finalize is costly from performance point of view. Why implementing Finalize is costly is explained <a href="http://msdn.microsoft.com/en-us/library/0s71x931.aspx" target="_blank">here</a> (last para) in MSDN.</li>
<li>In finalize method, finally block has been put and it calls the Finalize on base class also. This makes sure that all the hierarchy of objects release the resources properly.</li>
</ol>
<ol><strong><em>IDisposeable</em></strong> :</ol>
<ol>
<li>
<div>As mentioned above, IDispose can only free the resources and can not free the memory consumed by the object itself.</div>
</li>
<li>
<div>Onus of calling Dispose method on the object still remains with the user. Just implementing IDisposable will not make sure that all resources are released properly. Dispose method will not be called automatically by framework except object is called with “<a href="http://msdn.microsoft.com/en-us/library/yh598w02(VS.71).aspx" target="_blank">using</a>”.</div>
</li>
<li>
<div>Calling dispose is not thread-safe.</div>
</li>
<li>
<div>It is better to consider implementing try..finally block inside the dispose method because if during the execution of dispose method any exception occurs there is no way left to free the resources.</div>
</li>
</ol>
<p><strong><em><span style="color:#808080;font-size:xx-small;">References :</span></em></strong></p>
<p><strong><em><span style="color:#808080;font-size:xx-small;">MSDN</span></em></strong></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/csharpsimplified.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/csharpsimplified.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/csharpsimplified.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/csharpsimplified.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/csharpsimplified.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/csharpsimplified.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/csharpsimplified.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/csharpsimplified.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/csharpsimplified.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/csharpsimplified.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/csharpsimplified.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/csharpsimplified.wordpress.com/114/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/csharpsimplified.wordpress.com/114/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/csharpsimplified.wordpress.com/114/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=114&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://csharpsimplified.wordpress.com/2010/10/03/destructor-finalize-idispose/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5e385adf2aca841d63bedab64edb3629?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">krunalc</media:title>
		</media:content>
	</item>
		<item>
		<title>Design Principles</title>
		<link>http://csharpsimplified.wordpress.com/2010/10/01/design-principle/</link>
		<comments>http://csharpsimplified.wordpress.com/2010/10/01/design-principle/#comments</comments>
		<pubDate>Thu, 30 Sep 2010 16:25:03 +0000</pubDate>
		<dc:creator>KrunalC</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Principle]]></category>
		<category><![CDATA[Dependency Inversion Problem]]></category>
		<category><![CDATA[Design Principle]]></category>
		<category><![CDATA[Interface Segregation]]></category>
		<category><![CDATA[Liscov Principle of Substitution]]></category>
		<category><![CDATA[ObjectMentor]]></category>
		<category><![CDATA[Open-Closed Principle]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>
		<category><![CDATA[Solid Principle]]></category>

		<guid isPermaLink="false">https://csharpsimplified.wordpress.com/2010/10/01/design-principle/</guid>
		<description><![CDATA[In this post, I will be trying to describe my understanding about the design principles which is popularly known as “SOLID” principle. “SOLID” is abbreviation formed by collecting initials of five basic designing principles namely, Single Responsibility Principle Open &#8211; Closed Principle Liscov Substitution Principle Interface Segregation Principle Dependency Inversion Principle Let’s try to understand [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=90&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post, I will be trying to describe my understanding about the design principles which is popularly known as “SOLID” principle.</p>
<p>“SOLID” is abbreviation formed by collecting initials of five basic designing principles namely,</p>
<ol>
<li>
<div><span style="color:#800080;font-size:x-small;"><strong>S</strong></span>ingle Responsibility Principle</div>
</li>
<li>
<div><span style="color:#800080;font-size:x-small;"><strong>O</strong></span>pen &#8211; Closed Principle</div>
</li>
<li>
<div><span style="color:#800080;font-size:x-small;"><strong>L</strong></span>iscov Substitution Principle</div>
</li>
<li>
<div><strong><span style="color:#800080;font-size:x-small;">I</span></strong>nterface Segregation Principle</div>
</li>
<li>
<div><strong><span style="color:#800080;font-size:x-small;">D</span></strong>ependency Inversion Principle</div>
</li>
</ol>
<p>Let’s try to understand all these principles in brief with some examples :</p>
<p><strong><span style="color:#ff0000;">Single Responsibility Principle</span></strong> :</p>
<p>This principle states that</p>
<blockquote><p><strong><em><span style="color:#008000;font-size:x-small;"><span style="font-size:x-small;">There should never be more than one reason for class to change.</span></span></em></strong></p></blockquote>
<p>This principle is simplest however not so simple to apply effectively. Normally while designing the software we are tend to think  in terms of physical grouping and boundaries rather than thinking in terms of responsibility and functionality.</p>
<p>e.g. We have one window in the application which fetches the data from database and displays in the window. Following is the skeleton of the window class :</p>
<p><pre class="brush: csharp;">
  public class DisplayWindow
  {
      // establishes connection to database
      public void ConnectDataBase();
      // disconnect connection to database
      public void DisconnectDataBase();
      // gets data from databse
      public void GetData();
      // displays data read from database
      public void DisplayData();
  }
</pre></p>
<p>In Above example, all the implementation pertaining to said window has been grouped together in the DisplayWindow class. This  is definitely not following the Single Responsibility Principle. DisplayWindow class in this example is having responsibility of  data retrieval and representation both. There are two problems with this kind of approach :</p>
<p>1. it results in tight coupling between data and representation.</p>
<p>2. All the code has been stuffed in one class only so when changes are made to code it is more prone to regression defects.</p>
<p>If we want to segregate the classes based on the responsibility then it can be done as follow :</p>
<p><a href="http://csharpsimplified.files.wordpress.com/2010/10/image.png"><img title="image" style="display:inline;border-width:0;" src="http://csharpsimplified.files.wordpress.com/2010/10/image_thumb.png?w=568&#038;h=166" border="0" alt="image" width="568" height="166" /></a></p>
<p>So we can make two class namely Window class and DataManger class. Here responsibility of both the classes are very clear. Window class is responsible for displaying data and DataManager is responsible for retrieving data from Database and supplying it to presentation layer. This results in decoupling of data and presentation. Also, such change can make DataManager class reusable.</p>
<p>Hence, <span style="color:#008080;"><span style="text-decoration:underline;"><em>when we think about the responsibilities it will result in code which is not so tightly coupled and it will increase the reusability.</em></span> </span></p>
<p><span style="color:#008080;"> </span></p>
<p><span style="color:#ff0000;font-size:x-small;"><strong><span style="font-size:x-small;">Open &#8211; Closed Principle </span></strong></span></p>
<p>This principle states</p>
<blockquote><p><span style="color:#008000;font-size:x-small;"><strong><span style="font-size:x-small;">Software Entities (Classes, Modules, Functions, etc.) should be open for extension but closed for modifications. </span></strong></span></p></blockquote>
<p>This is very important principle and it states that design the code in such a way so that when the requirement changes, it is possible to meet the requirement by extending the module rather than making changes to existing implementation. It seems like kinda impossible right? However attempt can be made to achieve this objective.</p>
<p>Let’s consider one problem where banking application needs to calculate the interests for various types of account. Following code can meet the requirement :</p>
<p><pre class="brush: csharp;">
public class BankApp
  {
      public void CalculateInterest(string accountType)
      {
          switch (accountType)
          {
              case &quot;Savings&quot;:
                  // routine to calculate savings account interest
                  break;
              case &quot;Current&quot;:
                  // routine to calculate current account interest
                  break;
          }
      }
  }
</pre></p>
<p>Now bank introduces new account type i.e. “SavingsPlus”. Implementation has to change to calculate the interest for this new account type to accommodate this new requirement. So in above implementation one new case should be added for new account type. This mean altering the existing implementation every time new account type is introduced. Also, when new account type is added, code has to be changed at all places where action needs to be decided based on the account type. The scenario discussed here is very simple but in real world application altering existing code which is working is definitely risky and can cause regression defects.  Also, one requirement triggering changes at multiple places in already running code is also not desirable. Open-Closed principle is exactly meant for such situation.&lt;/p&gt; &lt;p&gt;Consider following solution for above problem :&lt;/p&gt; &lt;p&gt;&lt;a href=&#8221;http://csharpsimplified.files.wordpress.com/2010/10/image1.png&#8221;&gt;&lt;img style=&#8221;display:inline;border-width:0;&#8221; title=&#8221;image&#8221; border=&#8221;0&#8243; alt=&#8221;image&#8221; src=&#8221;http://csharpsimplified.files.wordpress.com/2010/10/image_thumb1.png&#8221; width=&#8221;593&#8243; height=&#8221;321&#8243; /&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;In above design, Abstraction has been achieved by introducing “Account” base class. Whenever new account type is introduced we can add one more concrete class deriving from “Account” base class and add the interest calculation routine to concrete class. Doing so we don’t have to change the existing implementation at all when new account type is introduced thus making existing code fully closed while code is still extendible.</p>
<p><pre class="brush: csharp;">
  public class BankApp
  {
      public void CalculateInterest()
      {
          foreach (Account account in accounts)
          {
              account.CalculateInterest();
          }
      }
  }
</pre></p>
<p>Two principles which are key to meet Open-closed principle is <span style="text-decoration:underline;"><em><strong>Abstraction</strong></em></span> and <span style="text-decoration:underline;"><em><strong>Polymorphism</strong></em></span>. Abstraction helps us in making our code more extensible while polymorphism helps us in making our code close. This is quite apparent from above example.</p>
<p>In real world, no implementation can be 100% closed e.g. if the way interest is calculated is changed then above design is not closed. In order to make change to interest calculation routine we have to change the “CalculateInterest” method of each concrete account classes. However while implementing the calculation routine if some abstraction can be achieved then changes required can be reduced or existing implementation can remain closed when new requirement comes.</p>
<p><span style="color:#ff0000;font-size:x-small;"><strong>Liskov Substitution Principle</strong></span></p>
<p>This principle state</p>
<blockquote><p><span style="color:#008000;font-size:x-small;"><strong>Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.</strong></span></p></blockquote>
<p>This principle stresses on the fact that when sub classing is done, it should not break the base class implementation and subclass &#8211; superclass should remain interchangeable. To understand this let’s take following example :</p>
<p><pre class="brush: csharp;">
  public class Rectangle
  {
      private double width;
      private double height;

      public Rectangle(double w, double h)
      {
          width = w;
          height = h;
      }

      public virtual void SetHeight(double h)
      {
          height = h;
      }

      public virtual void SetWidth(double w)
      {
          width = w;
      }

      public virtual double GetHeight()
      {
          return height;
      }

      public virtual double GetWidth()
      {
          return width;
      }
  }

  public class Square : Rectangle
  {
      private double size;

      public Square(double s) : base(s,s)
      {
          size = s;
      }

      public override void SetHeight(double h)
      {
          // for square we have to keep both height and width same
          base.SetHeight(h);
          base.SetWidth(h);
      }

      public override void SetWidth(double w)
      {
          // for square we have to keep both height and width same
          base.SetWidth(w);
          base.SetHeight(w);
      }
  }
</pre></p>
<p>In above code sample, Class Square is derived from Rectangle. In Square class when SetHeight is called we have to set both height and width in order to keep the sides same for square.</p>
<p>Now consider following use for the above implementation :</p>
<p><pre class="brush: csharp;">
  public class EditorApp
  {
      public void ReduceWidthToHalf(Rectangle r)
      {
          r.SetWidth(r.GetWidth() / 2);
      }

      public static void main(string[] args)
      {
          EditorApp editor = new EditorApp();

          Square sq = new Square(20);

          // calling this will result in reduction of both width and height by half.
          // This is not desirable as per implementation of ReducteWidthToHalf method.
          // When actual object passed is Rectangle only width is reduced to half but
          // when Square object is passed, it reduces both height and width by half.

          // this mean both base class and sub class objects exhibit different behaviors
          // and they are not interchangable without breaking functionalities.
          editor.ReduceWidthToHalf(sq);
      }
  }
</pre></p>
<p>In above code sample, as my code comment mentions base class and derived class exhibits different behavior and Square can not be substituted for a Rectangle and vice versa.</p>
<p>So in <span style="text-decoration:underline;"><span style="color:#ff0000;">nutshell</span></span>, Liskov principle states that <span style="color:#800080;font-size:x-small;"><strong><em>never break the base class implementation while subclassing</em></strong></span>.</p>
<p><strong><span style="color:#ff0000;font-size:x-small;">Interface Segregation Principle</span></strong></p>
<p>This principle states</p>
<blockquote><p><span style="color:#008000;font-size:x-small;"><strong>Clients should not be forced to depend upon interfaces that they don’t use.</strong></span></p></blockquote>
<p>This principle basically talks about the problem of “Polluted”/”Fat” interfaces. Following example (from <a href="http://www.objectmentor.com/resources/articles/isp.pdf" target="_blank">objectmentor</a>)should clarify what is Fat interface :</p>
<p>There is a door system with normal door operation like door open, close and getting the door status, etc. This is a normal door operation. Basic IDoor interface below should do the needed for this :</p>
<p><a href="http://csharpsimplified.files.wordpress.com/2010/10/image2.png"><img title="image" style="display:inline;margin-left:0;margin-right:0;border-width:0;" src="http://csharpsimplified.files.wordpress.com/2010/10/image_thumb2.png?w=167&#038;h=166" border="0" alt="image" width="167" height="166" align="left" /></a></p>
<p><a href="http://csharpsimplified.files.wordpress.com/2010/10/image3.png"><img title="image" style="display:inline;margin-left:0;margin-right:0;border-width:0;" src="http://csharpsimplified.files.wordpress.com/2010/10/image_thumb3.png?w=167&#038;h=184" border="0" alt="image" width="167" height="184" align="right" /></a></p>
<p>However, some specialized door system is requested where door should close / alert user about it being open after certain time period. So this additional feature will require to add some timer function to existing door system as shown in right :</p>
<p>Well, Changing the IDoor interface have it’s implications :</p>
<p>1. Adding new method to existing interface will break the existing implementation because all the classes that derive from the IDoor interface will have to implement newly added method “TimerFunction”.</p>
<p>2. Though not all doors need a timer function, still as per new interface design all the objects that derive from IDoors will have to implement TimerFunction which is not desirable.</p>
<p>Also, adding new features in this way will make interface more n more fat and it will lead to tightly coupled code. Also, making interface fat will result in violation of Open-Close principle.</p>
<p>So solution to this problem is to segregate the Interfaces. Ideal way is to design the separate interface for each client.</p>
<p><a href="http://csharpsimplified.files.wordpress.com/2010/10/image4.png"><img title="image" style="display:inline;border-width:0;margin:0 15px 0 0;" src="http://csharpsimplified.files.wordpress.com/2010/10/image_thumb4.png?w=340&#038;h=315" border="0" alt="image" width="340" height="315" align="left" /></a></p>
<p>So now we have two interfaces as shown in the figure. So to construct simple door we use IDoor interface while constructing TimedDoor we use both IDoor and ITimeFunction interface. In such design, the abstraction has been achieved in IDoor while add-ons have been segregated to new interface. Also, with this design even if changes in ITimeFunction is required than also changes will remain limited only to TimedDoor objects and SimpleDoor objects will remain unaffected. This way the tight coupling which existed in previously design is reduced. Also, after segregation classes are also complying to single responsibility principle.</p>
<p><span style="color:#ff0000;font-size:x-small;"><strong>Dependency Inversion Principle</strong></span></p>
<p>This principle state</p>
<blockquote><p>A. High level modules should not depend on low level module. Both should depend on abstraction. Both should depend on Abstraction.</p>
<p>B. Abstraction should not depend on details. Details should depend on Abstraction.</p></blockquote>
<p>To understand this, consider following Salary Calculator application example where perks for the employee is to be calculated :</p>
<p><a href="http://csharpsimplified.files.wordpress.com/2010/10/image5.png"><img title="image" style="display:inline;border-width:0;" src="http://csharpsimplified.files.wordpress.com/2010/10/image_thumb5.png?w=600&#038;h=442" border="0" alt="image" width="600" height="442" /></a></p>
<p>Worker is entitled to have various perks. Details of the allowed perk is available inside the Worker class. So in this implementation “ComputePerks” method will iterate through all the perks and go through the if loops to compute the final perk for each employee. But perks entitlement and perks may keep changing i.e. after a while no TransportationPerk is given or new perk say FoodAllownce is added then in this case we will have to change the if loops inside the method to accommodate new structure and this exercise will  repeat every time when perks change. So drawback of this design is :</p>
<p>1. High level module i.e. SalaryCalculator is dependent on the low level classes i.e. various perk calculator classes.</p>
<p>2. Tight coupling exist between the high and low level module.</p>
<p>3. Also, every time low level module changes, High level module has to change which also violates the “Open-Closed” principle.</p>
<p>So to fix this situation we have to follow what this principle is saying i.e. both High and low level module should depend on Abstraction. We should introduce Abstraction layer which can isolate high and low level modules and both can depend on this Abstraction layer. So consider the following new design :</p>
<p><a href="http://csharpsimplified.files.wordpress.com/2010/10/image6.png"><img title="image" style="display:inline;border-width:0;" src="http://csharpsimplified.files.wordpress.com/2010/10/image_thumb6.png?w=595&#038;h=427" border="0" alt="image" width="595" height="427" /></a></p>
<p>In this design, IPerks interface has been added and now all perks will implement this interface and worker class will use the IPerks. Also, SalaryCalculator class will use the IPerks collection inside the worker class and will calculate the perks by iterating through the list as mentioned in the comment in above diagram. Using this approach,</p>
<p>1. High level SalaryCalculator class is not directly depending upon the Perk classes.</p>
<p>2. Both High and low level classes now depend on the abstraction of IPerks interfaces.</p>
<p>3. Changes in the perk structures i.e. addition or removal of perks will not affect the SalaryCalculator top level class. Every time when perk structure changes only the list inside the worker class will change. So this will also follow the “Open-Close” principle.</p>
<p>So finally, I am done with describing the SOLID principle in brief as per my understanding.  All the principles are very extensive in nature and deserves separate post for each but here it is my humble effort to put them in shortest possible way.  However, people are always welcome to provide their feedbacks/suggestions or pointing out any errors in constructive way.</p>
<p><em>References </em>:</p>
<p>1. wiki</p>
<p>2. <a href="http://www.ObjectMentor.com">WWW.ObjectMentor.com</a></p>
<p>3. some other web contents</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/csharpsimplified.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/csharpsimplified.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/csharpsimplified.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/csharpsimplified.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/csharpsimplified.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/csharpsimplified.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/csharpsimplified.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/csharpsimplified.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/csharpsimplified.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/csharpsimplified.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/csharpsimplified.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/csharpsimplified.wordpress.com/90/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/csharpsimplified.wordpress.com/90/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/csharpsimplified.wordpress.com/90/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=90&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://csharpsimplified.wordpress.com/2010/10/01/design-principle/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5e385adf2aca841d63bedab64edb3629?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">krunalc</media:title>
		</media:content>

		<media:content url="http://csharpsimplified.files.wordpress.com/2010/10/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://csharpsimplified.files.wordpress.com/2010/10/image_thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://csharpsimplified.files.wordpress.com/2010/10/image_thumb3.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://csharpsimplified.files.wordpress.com/2010/10/image_thumb4.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://csharpsimplified.files.wordpress.com/2010/10/image_thumb5.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://csharpsimplified.files.wordpress.com/2010/10/image_thumb6.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>UpdateSourceTrigger &#8211; DataBinding</title>
		<link>http://csharpsimplified.wordpress.com/2009/08/22/updatesourcetrigger-databinding/</link>
		<comments>http://csharpsimplified.wordpress.com/2009/08/22/updatesourcetrigger-databinding/#comments</comments>
		<pubDate>Sat, 22 Aug 2009 15:30:56 +0000</pubDate>
		<dc:creator>KrunalC</dc:creator>
				<category><![CDATA[Data Binding]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Adam Nathan]]></category>
		<category><![CDATA[TwoWayBinding]]></category>
		<category><![CDATA[UpdateSourceTrigger]]></category>
		<category><![CDATA[WPF Unleashed]]></category>

		<guid isPermaLink="false">http://csharpsimplified.wordpress.com/2009/08/22/updatesourcetrigger-databinding/</guid>
		<description><![CDATA[Last week while working on two way binding, I discovered one very important settings for binding i.e. “UpdateSourceTrigger”. Before discovering this feature I faced problem in setting the value from target to source. Let me describe the problem I faced. In my setup, I had no. of text boxes in window whose text property were [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=67&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Last week while working on two way binding, I discovered one very important settings for binding i.e. “UpdateSourceTrigger”. Before discovering this feature I faced problem in setting the value from target to source. Let me describe the problem I faced. </p>
<p>In my setup, I had no. of text boxes in window whose text property were bound to the property of object in collection. So in this case, source for me was property of the object in collection and target was the text property of textboxes. </p>
<p>I configured my binding object as below :</p>
<blockquote><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#800080"><em>Binding binding = new Binding();          <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; binding.Source = <font color="#808080"><strong>&lt;source object from collection&gt;</strong></font>;           <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; binding.Path = new PropertyPath</em><strong><font color="#808080">(<em>&lt;PropertyName&gt;</em></font></strong><em>);          <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; binding.Mode = BindingMode.TwoWay;           <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; txtbox.SetBinding(TextBox.TextProperty, binding); </em></font></p>
</blockquote>
<p>With above binding configuration, source –&gt; target binding worked perfectly for me. But binding from target –&gt; source (i.e. from text box to object’s property in collection) was not working for me.<em> One thing which is important to mention here is, I was changing the text box’s text value in procedural code and not by entering the value in textbox</em>. </p>
<p>It was beyond my understanding why binding was not working? I spent almost half a day trying to figure out this. I googled it but google disappointed me. So I took Adam Nathan’s “WPF Unleashed” book in my hand and started looking for some solution. Again this book came to my rescue. While going through the “Data Binding” chapter in this book, I learned about “UpdateSourceTrigger’ property of the binding object. </p>
<p>“UpdatesourceTrigger” property is very important in “TwoWayBinding” and “OneWayToSource” binding modes. It defines how and when source should get updated. </p>
<p>Value of UpdateSourceTrigger could be any of the value from UpdateSourceTrigger Enumeration. Enumeration values are </p>
<ol>
<li>PropertyChanged &#8211; The source is updated whenever the target property value      <br />changes. </li>
<li>LostFocus – The source is updated when target property changes and target object looses focus. </li>
<li>Explicit – The source is updated when explicit call is made to update using “BindingExpression.UpdateSource”. </li>
</ol>
<p>Target controls have default values set for “UpdateSourceTrigger” for binding object. For text box control, default setting for this property is “LostFocus”. In my case, I was updating the textbox (i.e. target) through code and because of that textbox was not loosing focus. Hence my binding was not working. Then I changed above binding configuration to set the UpdateSourceTrigger property of binding object as following :</p>
<blockquote><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#800080"><em>Binding binding = new Binding();          <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; binding.Source = writeItemInfoList[index];           <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; binding.Path = new PropertyPath(&quot;ItemValue&quot;);           <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; binding.Mode = BindingMode.TwoWay;           <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#ff0000"><strong>binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;</strong>             <br /></font>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; txtbox.SetBinding(TextBox.TextProperty, binding); </em></font></p>
</blockquote>
<p>And Binding from Target to source started working for me. </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/csharpsimplified.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/csharpsimplified.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/csharpsimplified.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/csharpsimplified.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/csharpsimplified.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/csharpsimplified.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/csharpsimplified.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/csharpsimplified.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/csharpsimplified.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/csharpsimplified.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/csharpsimplified.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/csharpsimplified.wordpress.com/67/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/csharpsimplified.wordpress.com/67/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/csharpsimplified.wordpress.com/67/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=67&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://csharpsimplified.wordpress.com/2009/08/22/updatesourcetrigger-databinding/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5e385adf2aca841d63bedab64edb3629?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">krunalc</media:title>
		</media:content>
	</item>
		<item>
		<title>SQLBulkCopy</title>
		<link>http://csharpsimplified.wordpress.com/2009/05/01/sqlbulkcopy/</link>
		<comments>http://csharpsimplified.wordpress.com/2009/05/01/sqlbulkcopy/#comments</comments>
		<pubDate>Fri, 01 May 2009 07:06:07 +0000</pubDate>
		<dc:creator>KrunalC</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[ADO.net]]></category>
		<category><![CDATA[SQLBulkcopy]]></category>

		<guid isPermaLink="false">http://csharpsimplified.wordpress.com/2009/05/01/sqlbulkcopy/</guid>
		<description><![CDATA[I was looking to copy some bulk data from one of the data table in memory to my SQL DB table. I tried using DBAdapter.Update but it didn’t work as in my source datatable none of the row was in updated/new stage. Then after searching a lot, I found “SQLBulkCopy”. The SqlBulkCopy class can be [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=64&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I was looking to copy some bulk data from one of the data table in memory to my SQL DB table. I tried using DBAdapter.Update but it didn’t work as in my source datatable none of the row was in updated/new stage. Then after searching a lot, I found “SQLBulkCopy”. </p>
<p>The SqlBulkCopy class can be used to write bulk data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance. To copy the source data to destination table in the sql server, need to set destination table name and execute “WriteToServer” method. Following code snippet </p>
<blockquote><p><font color="#008000">// create sqlBulkCopy object       <br /></font>SqlBulkCopy bulkCopy = new SqlBulkCopy(connString);</p>
<p><font color="#008000">// set destination table name for sqlBulkcopy object       <br /></font>bulkCopy.DestinationTableName = &quot;<font color="#800080">[Table Name]</font>&quot;;</p>
<p><font color="#008000">// write source data to destination sql table       <br /></font>bulkCopy.WriteToServer(<font color="#800080"></font>); </p>
</blockquote>
<p>Performancewise using SQLBulkCopy is far better than using normal Insert/Update commands. </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/csharpsimplified.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/csharpsimplified.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/csharpsimplified.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/csharpsimplified.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/csharpsimplified.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/csharpsimplified.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/csharpsimplified.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/csharpsimplified.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/csharpsimplified.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/csharpsimplified.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/csharpsimplified.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/csharpsimplified.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/csharpsimplified.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/csharpsimplified.wordpress.com/64/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=64&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://csharpsimplified.wordpress.com/2009/05/01/sqlbulkcopy/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5e385adf2aca841d63bedab64edb3629?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">krunalc</media:title>
		</media:content>
	</item>
		<item>
		<title>Reading csv file in datatable</title>
		<link>http://csharpsimplified.wordpress.com/2009/05/01/reading-csv-file-in-datatable/</link>
		<comments>http://csharpsimplified.wordpress.com/2009/05/01/reading-csv-file-in-datatable/#comments</comments>
		<pubDate>Thu, 30 Apr 2009 16:57:23 +0000</pubDate>
		<dc:creator>KrunalC</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[csv]]></category>
		<category><![CDATA[datatable]]></category>
		<category><![CDATA[oledbadapter]]></category>

		<guid isPermaLink="false">http://csharpsimplified.wordpress.com/2009/05/01/reading-csv-file-in-datatable/</guid>
		<description><![CDATA[Recently I had to work on one problem where I had to read the csv file and filling up the data table with the csv file data. I used the OLEDBAdapter to accomplish that with just few lines of code. Following is the code : &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; string query = &#34;SELECT Symbol, [Name of Company], FROM [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=63&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recently I had to work on one problem where I had to read the csv file and filling up the data table with the csv file data. I used the OLEDBAdapter to accomplish that with just few lines of code. Following is the code :</p>
<blockquote><p>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <font color="#800080">string query = &quot;SELECT Symbol, <font color="#ff0000">[Name of Company]</font>, FROM [<font color="#008000">just <em>file name with extension</em></font>]&quot;;        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; string connStr = &quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=&quot; + [<em><font color="#008000">csv file path without file name</font></em>] + &quot;;&quot; + &quot;Extended Properties=&#8217;text;HDR=YES;&#8217;&quot;; </font></p>
<p><font color="#800080">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; //create dataadapter object       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; OleDbDataAdapter adapter = new OleDbDataAdapter(query, connStr); </font></p>
<p><font color="#800080">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; // create table       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; DataTable dtSymbolDetails = new DataTable(&quot;ScriptDetails&quot;);        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; dtSymbolDetails.Columns.Add(&quot;Symbol&quot;);        <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; dtSymbolDetails.Columns.Add(&quot;Name of Company&quot;);</font></p>
<p><font color="#800080">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; // fill the table with data using adapter       <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; adapter.Fill(dtDetails);</font></p>
</blockquote>
<p>So above code fills up the details of the csv file in the data table for further use. </p>
<p>Also note the text in red above. If column name contains the space then in query the column name should be put between [ ]. I learned it in bit hard way. It shows I’m so poor in my sql knowledge. </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/csharpsimplified.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/csharpsimplified.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/csharpsimplified.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/csharpsimplified.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/csharpsimplified.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/csharpsimplified.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/csharpsimplified.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/csharpsimplified.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/csharpsimplified.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/csharpsimplified.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/csharpsimplified.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/csharpsimplified.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/csharpsimplified.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/csharpsimplified.wordpress.com/63/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=63&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://csharpsimplified.wordpress.com/2009/05/01/reading-csv-file-in-datatable/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5e385adf2aca841d63bedab64edb3629?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">krunalc</media:title>
		</media:content>
	</item>
		<item>
		<title>Resources in WPF &#8211; II (Logical Resources)</title>
		<link>http://csharpsimplified.wordpress.com/2009/02/17/resources-in-wpf-ii-logical-resources/</link>
		<comments>http://csharpsimplified.wordpress.com/2009/02/17/resources-in-wpf-ii-logical-resources/#comments</comments>
		<pubDate>Tue, 17 Feb 2009 06:55:29 +0000</pubDate>
		<dc:creator>KrunalC</dc:creator>
				<category><![CDATA[Resources]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://csharpsimplified.wordpress.com/2009/02/17/resources-in-wpf-ii-logical-resources/</guid>
		<description><![CDATA[Logical resources are arbitrary .net objects stored (and named) in element’s ResourceDictionary. Logical resource can be shared among multiple elements depending upon the scope at which it has been defined. Both FrameworkElement and FrameworkContentElement has ResourceDictionary defined in it, hence almost all UI elements inherit the ResourceDictionary. Typical logical resources are styles, bindings, etc. Logical [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=59&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p align="justify">Logical resources are arbitrary .net objects stored (and named) in element’s ResourceDictionary. Logical resource can be shared among multiple elements depending upon the scope at which it has been defined. Both FrameworkElement and FrameworkContentElement has ResourceDictionary defined in it, hence almost all UI elements inherit the ResourceDictionary. Typical logical resources are styles, bindings, etc. </p>
<p align="justify">Logical resources are of two types :</p>
<p align="justify">1) StaticResources   <br />2) DynamicResources</p>
<p align="justify"><strong><font size="3">How resources are searched?</font></strong></p>
<p align="justify">StaticResource/DynamicResource markup extension accepts a key name as parameter. So this key is searched while looking up for resource. It is not mandatory that resource has to be defined on the element which is using it. Xaml looks for the resource at the element level first then to parent level and then to application level. Resource markup extension implements the ability to walk the logical tree to find the items upward in the logical tree so if resource is not found, it checks the parent element, its parent and so on until it reaches the root element. At this point, it checks the resources collection at the application level and system level subsequently. If the resource is not found anywhere, it throws “InvalidOperationException”. </p>
<p align="justify">Although it is advisable to have unique key associated with resource, however it is not mandatory. While looking up for the resource whatever&#160; resource is found first is assigned.</p>
<p align="justify"><strong><font size="3">Static v/s. Dynamic Resources</font></strong></p>
<table border="2" cellspacing="2" cellpadding="2" width="479">
<tbody>
<tr>
<td width="234" align="center">
<p align="justify"><strong>Static Resources</strong></p>
</td>
<td width="235" align="center">
<p align="justify"><strong>Dynamic Resources</strong></p>
</td>
</tr>
<tr>
<td width="234">
<p align="justify">StaticResource is applied only once (first time when it is used).</p>
</td>
<td valign="top" width="235">
<p align="justify">DynamicResource is applied every time when resource changes e.g. system colors can be changed using control panel. So if system colors has been used as resource, than update is required. DynamicResource will take care of such change in resource. </p>
</td>
</tr>
<tr>
<td width="234">
<p align="justify">StaticResource has lesser overhead as it is applied only once during the runtime of the application.</p>
</td>
<td valign="top" width="235">
<p align="justify">DynamicResource has more overhead as it is applied whenever the resource value changes. In order to do this, DynamicResource has to keep tracking about the changes in the resource during runtime also.</p>
</td>
</tr>
<tr>
<td width="234">
<p align="justify">StaticResources always get loaded the first time window/page is loaded irrespective of its use during start up.</p>
</td>
<td valign="top" width="235">
<p align="justify">DynamicResources are not loaded until it is actually used. So this results in better load time. </p>
</td>
</tr>
<tr>
<td width="234">
<p align="justify">StaticResources can be used for DependencyProperty as well as normal .net property.</p>
</td>
<td valign="top" width="235">
<p align="justify">DynamicResource can only be used for DependencyProperty. </p>
</td>
</tr>
<tr>
<td width="234">StaticResources has to be defined before it is used. Hence, StaticResources can not be forward referenced. </td>
<td valign="top" width="235">DynamicResources can use the forward references. </td>
</tr>
</tbody>
</table>
<p><strong><font size="3">Defining and Applying Resources from procedural code</font></strong></p>
<p>At element level adding resources (at definition level, static/dynamic resource is not differentiated) is easy. The syntax is </p>
<p>&lt;element&gt;.Resources.Add(<font color="#000080">object</font> key, <font color="#000080">object</font> value);</p>
<p align="justify"><strong>Static Resource</strong></p>
<p align="justify">If in xaml, resources are used as static resource as shown below (provided resource is already defined)</p>
<p align="justify"><font color="#800080"><em>&lt;Button BackGround={StaticResource backgraoundBrush}/&gt;</em></font></p>
<p align="justify">then from procedural code, this resource can be used as </p>
<p align="justify"><font color="#800080"><em>Button button = new Button();       <br />button.BackGround = (Brush)button.FindResource(“backgroundBrush”);</em></font></p>
<p align="justify">If “FindResource” fails to find the resource, it throws&#160; “ResourceReferenceKeyNotfoundException”. To avoid this situation, “TryFindResoruce” method can be used which returns ‘null’ if the resource key is not found. </p>
<p align="justify"><strong>Dynamic Resource</strong></p>
<p align="justify">in xaml, dynamic resource can be used as mentioned below :</p>
<p align="justify"><font color="#800080"><em>&lt;Button BackGround={DynamicResource backgraoundBrush}/&gt;</em></font></p>
<p align="justify"><font color="#000000">however in procedural code this can be set using SetResourceReference method as shown below :</font></p>
<p align="justify"><font color="#800080"><em>button.SetResourceReference(Button.BackgroundProperty, “backgroundbrush”);</em></font></p>
<p align="justify"><font color="#000000">Do remember that forward reference (i.e. defining the resource before using it) still remains invalid for Static Resource even with procedural code. </font></p>
<p align="justify"><font color="#000000" size="3"><strong>Accessing Resources from other assemblies </strong></font></p>
<p align="justify"><font color="#000000" size="2">In many cases resources are defined in separate assembly for the sake of better maintainability. In that case resources can be accessed from different assembly in following way ;</font></p>
<p align="justify"><font color="#800080" size="2"><em>&lt;Button BackGround={DynamicResource {ComponentResourcekey TypeinTargetAssembly=”local:MyResources, ResourceID=backgroundBrush }}</em></font></p>
<p align="justify"><font color="#800080" size="2"></font></p>
<p align="justify"><font color="#000000" size="2">Sometimes the other assembly in which the resource has been defined provides way to access the resource by defining property in class. </font></p>
<p align="justify"><font color="#800080" size="2"><em>public object MyResourceKey</em></font></p>
<p align="justify"><font color="#800080" size="2"><em>{       <br />&#160;&#160;&#160;&#160;&#160; get {return (new ComponentResourcekey (this.GetType(), “backgroundBrush”);}&#160;&#160;&#160;&#160; </em></font></p>
<p align="justify"><font color="#800080" size="2"><em>}</em></font></p>
<p align="justify"><font color="#000000" size="2">In such a case, resource can be accessed from xaml in following way :</font></p>
<p align="justify"><em><font color="#800080" size="2">&lt;Button BackGround=”{DynamicResource {x:static local:MyResourceKey}}”</font></em></p>
<p align="justify"><strong><font size="3">Accessing System Resources</font></strong></p>
<p align="justify">Sysem Resources i.e. System Fonts, System colors etc. can be used in similar way as mentioned above. </p>
<p align="justify"><font color="#800080"><em>&lt;Button BackGround =”{DynamicResource {x:static SystemColors.Desktopcolor}}”</em></font></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/csharpsimplified.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/csharpsimplified.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/csharpsimplified.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/csharpsimplified.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/csharpsimplified.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/csharpsimplified.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/csharpsimplified.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/csharpsimplified.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/csharpsimplified.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/csharpsimplified.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/csharpsimplified.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/csharpsimplified.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/csharpsimplified.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/csharpsimplified.wordpress.com/59/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=59&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://csharpsimplified.wordpress.com/2009/02/17/resources-in-wpf-ii-logical-resources/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5e385adf2aca841d63bedab64edb3629?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">krunalc</media:title>
		</media:content>
	</item>
		<item>
		<title>Resources in WPF &#8211; I (Binary Resources)</title>
		<link>http://csharpsimplified.wordpress.com/2009/02/16/resources-in-wpf-i-binary-resources/</link>
		<comments>http://csharpsimplified.wordpress.com/2009/02/16/resources-in-wpf-i-binary-resources/#comments</comments>
		<pubDate>Mon, 16 Feb 2009 09:53:48 +0000</pubDate>
		<dc:creator>KrunalC</dc:creator>
				<category><![CDATA[Resources]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Binary resources]]></category>
		<category><![CDATA[build actions]]></category>

		<guid isPermaLink="false">http://csharpsimplified.wordpress.com/?p=45</guid>
		<description><![CDATA[There are two types of resources in WPF : 1) Binary Resources 2) Logical Resources In this post, I have described the details of the Binary resources. Binary Resources : Binary resources could be logo/image files, AV files etc. Resource files which are added to project, can have the “Build Action” defined on it from [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=45&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p align="justify">There are two types of resources in WPF :</p>
<p align="justify">1) Binary Resources<br />
2) Logical Resources</p>
<p align="justify">In this post, I have described the details of the Binary resources.</p>
<p align="justify"><strong><span style="text-decoration:underline;">Binary Resources</span></strong> : Binary resources could be logo/image files, AV files etc. Resource files which are added to project, can have the “Build Action” defined on it from the file properties windows.</p>
<p align="justify">Out of the various build actions defined by WPF only following two are important for binary resources :</p>
<p align="justify"><a href="http://csharpsimplified.files.wordpress.com/2009/02/image.png"><img style="display:block;float:none;margin-left:auto;margin-right:auto;border-width:0;" title="image" src="http://csharpsimplified.files.wordpress.com/2009/02/image-thumb.png?w=244&#038;h=172" border="0" alt="image" width="244" height="172" /></a></p>
<ul>
<li>
<div><strong>Resource</strong> : Embeds resource into the assembly (or culture specific satellite assembly)</div>
</li>
<li>
<div><strong>Content </strong>: this leaves resource as loose file and upon compilation this resource information is not embedded to assembly. Instead, it adds custom attribute to the assembly (AssemblyAssociatedContentFile) which records the existence and relative location of file.It is also possible to access the resource file without adding into the project however with this approach management of resource file becomes bit difficult. However, this approach is useful is resource file is generated dynamically using some runtime information. In such a case, resource file will not be available at compile time so can not be added to project.</div>
</li>
</ul>
<blockquote>
<p align="justify"><em><span style="color:#808080;">What is the difference between the “Resource” and “Embedded Resource” build actions?<br />
“Resource” and “Content” build actions are to access the WPF resources using the Uris. However “Embedded Resource” is for prior technologies. However both options embeds the resource in assembly but “Resource” option to be used for WPF.</span></em></p></blockquote>
<blockquote>
<p align="justify"><strong>URIs for accessing the binary resources</strong></p>
<table border="2" cellspacing="2" cellpadding="2" width="911">
<tbody>
<tr>
<td width="250">
<p align="center">URI</p>
</td>
<td width="651" valign="top">
<p align="center">Resource</p>
</td>
</tr>
<tr>
<td width="255">“Logo.jpg”</td>
<td width="646" valign="top">
<ul>
<li>embedded in current assembly (using “Resource” as build action)</li>
<li>loose resource however physical file is placed along with xaml file or assembly (if selected build action is “Content”)</li>
</ul>
</td>
</tr>
<tr>
<td width="260">“A/B/Logo.jpg”</td>
<td width="642" valign="top">same as above but resource file is located in subfolder “A/B”</td>
</tr>
<tr>
<td width="264">“D:\Resource\Logo.jpg”</td>
<td width="639" valign="top">resource path hard coded</td>
</tr>
<tr>
<td width="267">http://pinvoke.net/logo.jpg</td>
<td width="636" valign="top">loose resource hosted at pinvoke.net website.</td>
</tr>
<tr>
<td width="270">ResourceDll;component/Logo.jpg</td>
<td width="634">this URI represents the resource embedded in assembly ResourceDLL.dll or ResourceDLL.exe</td>
</tr>
<tr>
<td width="272">ResourceDll;componen/tA/B/Logo.jpg</td>
<td width="632">same as above except resource is located in subfolder</td>
</tr>
<tr>
<td width="274">pack://siteOfOrigin:,,,/logo.jpg</td>
<td width="630">resource located at site of origin</td>
</tr>
<tr>
<td width="276">pack://siteOfOrigin:,,,/A/B/logo.jpg</td>
<td width="629">resource located at site of origin in sub folder</td>
</tr>
</tbody>
</table>
</blockquote>
<blockquote><p><strong>Site of Origin</strong> :</p>
<p>Site of origin at the runtime gets resolved in different ways depending upon the way in which the application has been deployed.</p>
<ul>
<li>For a full-trust application installed with Windows Installer, the site of origin is the application’s root folder.</li>
<li>For a full-trust ClickOnce application, the site of origin is the URL or Universal Naming Convention (UNC) path from which the application was deployed.</li>
<li>For a partial-trust XAML Browser Application (XBAP) or ClickOnce application, the site of origin is the URL or UNC path that hosts the application.</li>
<li>For loose XAML pages viewed in Internet Explorer, there is no site of origin. Attempting to use it throws an exception.</li>
</ul>
</blockquote>
<blockquote><p><strong>Accessing resources from procedural code</strong> :</p>
<p>While accessing the resource from procedural code in WPF, triple comma syntax is used however above table for URIs remains still applicable except the last two rows with site of origin.<br />
e.g. to read the embedded resource with “Resource” action “pack://application:,,,/logo.jpg&#8217;” can be used.</p>
<p>Following code shows how to read the resource from procedural code :</p>
<p><span style="color:#800080;"><em>Image image = new Image();<br />
image.Source = new BitmapImage(new Uri(“pack://application:,,,/logo.jpg”)) </em></span></p></blockquote>
<p>There is one more aspect to binary resource and that is localization but I’m not covering it as of now.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/csharpsimplified.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/csharpsimplified.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/csharpsimplified.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/csharpsimplified.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/csharpsimplified.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/csharpsimplified.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/csharpsimplified.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/csharpsimplified.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/csharpsimplified.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/csharpsimplified.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/csharpsimplified.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/csharpsimplified.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/csharpsimplified.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/csharpsimplified.wordpress.com/45/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=45&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://csharpsimplified.wordpress.com/2009/02/16/resources-in-wpf-i-binary-resources/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5e385adf2aca841d63bedab64edb3629?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">krunalc</media:title>
		</media:content>

		<media:content url="http://csharpsimplified.files.wordpress.com/2009/02/image-thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>retrieving command-line args for WPF application</title>
		<link>http://csharpsimplified.wordpress.com/2009/02/12/retrieving-command-line-args-for-wpf-application/</link>
		<comments>http://csharpsimplified.wordpress.com/2009/02/12/retrieving-command-line-args-for-wpf-application/#comments</comments>
		<pubDate>Thu, 12 Feb 2009 12:58:31 +0000</pubDate>
		<dc:creator>KrunalC</dc:creator>
				<category><![CDATA[Startup]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://csharpsimplified.wordpress.com/?p=39</guid>
		<description><![CDATA[Normally in winform applications, command line arguments are accessed from the string array argument in the main method. However in WPF main method is auto generated and can not be acceEditssed directly. So how to access the command line args with WPF application. The answer is use &#8220;System.Environment.GetCommandLineArgs&#8221;. Calling this method returns command line arguments [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=39&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Normally in winform applications, command line arguments are accessed from the string array argument in the main method. However in WPF main method is auto generated and can not be acce<a href="edit-pages.php">Edit</a>ssed directly. So how to access the command line args with WPF application.</p>
<p>The answer is use &#8220;System.Environment.GetCommandLineArgs&#8221;. Calling this method returns command line arguments at any given point of time.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/csharpsimplified.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/csharpsimplified.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/csharpsimplified.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/csharpsimplified.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/csharpsimplified.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/csharpsimplified.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/csharpsimplified.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/csharpsimplified.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/csharpsimplified.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/csharpsimplified.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/csharpsimplified.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/csharpsimplified.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/csharpsimplified.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/csharpsimplified.wordpress.com/39/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=csharpsimplified.wordpress.com&amp;blog=5144401&amp;post=39&amp;subd=csharpsimplified&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://csharpsimplified.wordpress.com/2009/02/12/retrieving-command-line-args-for-wpf-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/5e385adf2aca841d63bedab64edb3629?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">krunalc</media:title>
		</media:content>
	</item>
	</channel>
</rss>
