<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>e-pedro.com</title>
	
	<link>http://www.e-pedro.com</link>
	<description>constant improvement in software engineering</description>
	<lastBuildDate>Thu, 15 Jul 2010 19:49:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/e-pedro" /><feedburner:info uri="e-pedro" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>How to replace Prototype with jQuery in Rails</title>
		<link>http://feedproxy.google.com/~r/e-pedro/~3/GTYwJa916kk/</link>
		<comments>http://www.e-pedro.com/2010/07/how-to-replace-prototype-with-jquery-in-rails/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 19:49:39 +0000</pubDate>
		<dc:creator>Pedro Sampaio</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[prototype]]></category>
		<category><![CDATA[rails3]]></category>

		<guid isPermaLink="false">http://www.e-pedro.com/?p=112</guid>
		<description><![CDATA[How to replace Prototype with jQuery as the default Javascript framework in Rails 3.]]></description>
			<content:encoded><![CDATA[<p>One of the first thing I do when I create a new Rails application is to replace Prototype with jQuery. Quoting from a <a href="http://robots.thoughtbot.com/post/806379268/suspenders-now-with-rspec-jquery-and-more" onclick="pageTracker._trackPageview('/outgoing/robots.thoughtbot.com/post/806379268/suspenders-now-with-rspec-jquery-and-more?referer=');">post in the Thoughtbot blog</a>:</p>
<blockquote><p>For our front-end behavior we’re using jQuery. The ecosystem around jQuery Core, jQuery UI, and the slew of third-party plugins help bring life to our applications. Using jQuery also gives us an easy transition for mobile web app development with tools like jQTouch. jQuery replaces prototype/scriptaculous in suspenders.</p></blockquote>
<p>Furthermore, starting from Rails 3, we now get Unobtrusive Javascript. This means that rails no longer outputs Javascript inline, but rather outputs the new HTML5 data attributes, which the Javascript frameworks can use to do their thing.</p>
<p>So, here&#8217;s how you go about using jQuery. First, get a local copy of the files.</p>
<pre class="brush: bash; title: ; notranslate">
$ curl -L http://code.jquery.com/jquery-1.4.2.min.js &gt; public/javascripts/jquery.js
$ curl -L http://github.com/rails/jquery-ujs/raw/master/src/rails.js &gt; public/javascripts/rails.js
</pre>
<p>Then we use an initializer by <a href="http://yehudakatz.com/" onclick="pageTracker._trackPageview('/outgoing/yehudakatz.com/?referer=');">Yehuda Katz</a>, that loads jQuery as the default javascript framework. Just create a jQuery.rb file in config/initializers, and paste this code into it:</p>
<pre class="brush: ruby; title: ; notranslate">
module ActionView::Helpers::AssetTagHelper
  remove_const :JAVASCRIPT_DEFAULT_SOURCES
  JAVASCRIPT_DEFAULT_SOURCES = %w(jquery.js rails.js)

  reset_javascript_include_default
end
</pre>
<p>Just make sure you include csrf_meta_tag in your layout and you&#8217;re ready to go!</p>
<img src="http://feeds.feedburner.com/~r/e-pedro/~4/GTYwJa916kk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.e-pedro.com/2010/07/how-to-replace-prototype-with-jquery-in-rails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.e-pedro.com/2010/07/how-to-replace-prototype-with-jquery-in-rails/</feedburner:origLink></item>
		<item>
		<title>Creating a Rails 3 app without the ‘rails’ command</title>
		<link>http://feedproxy.google.com/~r/e-pedro/~3/-a_TJ4azlaQ/</link>
		<comments>http://www.e-pedro.com/2010/07/creating-a-rails-3-app-without-the-rails-command/#comments</comments>
		<pubDate>Tue, 13 Jul 2010 19:47:22 +0000</pubDate>
		<dc:creator>Pedro Sampaio</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[bundler]]></category>
		<category><![CDATA[gem]]></category>
		<category><![CDATA[gemfile]]></category>
		<category><![CDATA[rails3]]></category>

		<guid isPermaLink="false">http://www.e-pedro.com/?p=111</guid>
		<description><![CDATA[This post will show you how to create a Rails 3 application without having the rails gem pre-installed, using only Bundler and the Gemfile]]></description>
			<content:encoded><![CDATA[<p>Following my <a href="http://www.e-pedro.com/2010/07/getting-started-with-rails-3-using-rvm/">previous post</a> about Rails3 and RVM (and for my own future reference), you can create a new Rails 3 application without having installed Rails previously. To do this, you rely only on Bundler and a Gemfile.</p>
<p>All you have to do is, create a directory for your rails application and inside that directory, create your Gemfile with the gems you need, including Rails 3.</p>
<pre class="brush: plain; title: ; notranslate">
source 'http://rubygems.org'

gem 'rails', '3.0.0.beta4'
</pre>
<p>Now all you have to do is run these two commands, to install the gems and create your application:</p>
<pre class="brush: bash; title: ; notranslate">
$ bundle install vendor/bundle
$ bundle exec rails new . --skip-testunit --skip-prototype
</pre>
<p>Just remember that the Rails command will try to overwrite your Gemfile, so make sure you answer &#8216;no&#8217; to that question.</p>
<p>A very big thanks to <a href="http://blog.laranjee.com/" onclick="pageTracker._trackPageview('/outgoing/blog.laranjee.com/?referer=');">Eduardo</a> for this tip!</p>
<img src="http://feeds.feedburner.com/~r/e-pedro/~4/-a_TJ4azlaQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.e-pedro.com/2010/07/creating-a-rails-3-app-without-the-rails-command/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.e-pedro.com/2010/07/creating-a-rails-3-app-without-the-rails-command/</feedburner:origLink></item>
		<item>
		<title>Getting started with Rails 3 using RVM</title>
		<link>http://feedproxy.google.com/~r/e-pedro/~3/PNAqHfk5ymQ/</link>
		<comments>http://www.e-pedro.com/2010/07/getting-started-with-rails-3-using-rvm/#comments</comments>
		<pubDate>Mon, 05 Jul 2010 13:03:56 +0000</pubDate>
		<dc:creator>Pedro Sampaio</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[gemset]]></category>
		<category><![CDATA[rails 3]]></category>
		<category><![CDATA[rvm]]></category>
		<category><![CDATA[rvmrc]]></category>

		<guid isPermaLink="false">http://www.e-pedro.com/?p=19</guid>
		<description><![CDATA['Getting started with Rails 3 using RVM' shows how to install rails and use rvm to create an isolated gemset for the application with a .rvmrc file.]]></description>
			<content:encoded><![CDATA[<p>In this post, I will show you how to get Rails 3 running with RVM.</p>
<h2>Installing Rails</h2>
<p>This a &#8220;chicken and egg&#8221; kind of problem. You&#8217;ll need to add Rails to your Gemfile, and use bundler. But until you install Rails, you won&#8217;t have access to the <em>rails</em> command. As of this writing, rails&#8217; latest version is beta 4, so you will need to run the following command.</p>
<pre class="brush: bash; title: ; notranslate">$ gem install rails --version &quot;3.0.0.beta4&quot;</pre>
<h2>Creating the application</h2>
<p>Now that we have Rails installed, we can execute the <em>rails new</em> command.</p>
<pre class="brush: bash; title: ; notranslate">$ rails new sample_app --skip-testunit --skip-prototype</pre>
<p>This will create your Rails 3 application. As you can see from the command options, we skipped generating the test folder and the prototype files. The reason for this is that I use Rspec and jQuery, so there&#8217;s less cleanup to do. You can see other possible command options by executing this command:</p>
<pre class="brush: bash; title: ; notranslate">$ rails --help</pre>
<h2>Using RVM</h2>
<p>RVM has a really cool concept of <a title="gemsets" href="http://rvm.beginrescueend.com/gemsets/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/rvm.beginrescueend.com/gemsets/?referer=');">gemsets</a>. From the documentation:</p>
<blockquote><p>RVM gives you compartmentalized independent ruby setups.           This means that ruby, gems and irb are all separate and  self-contained from system and from each other. You may even have separate named gem sets.</p></blockquote>
<p>We will create a .rvmrc file in our application dir, and use an isolated gemset for our app, like so:</p>
<pre class="brush: bash; title: ; notranslate">$ echo &quot;rvm ruby-1.8.7@sample_app&quot; &gt; .rvmrc</pre>
<p>Now we have a clean gemset to use with out application. You can change the ruby version to whatever you like, for instance, to 1.9.2 or head. To actually create the gemset, you can either do it manually</p>
<pre class="brush: bash; title: ; notranslate">$ rvm gemset create &quot;sample_app&quot;</pre>
<p>or export the following flag in .rvmrc:</p>
<pre class="brush: bash; title: ; notranslate">$ rvm_gemset_create_on_use_flag=1</pre>
<p>This way, when you change to the application directory, RVM will pick up the .rvmrc file and automagically switch to the sample_app gemset. All you need to do now is bundle install and you&#8217;re off to go.</p>
<img src="http://feeds.feedburner.com/~r/e-pedro/~4/PNAqHfk5ymQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.e-pedro.com/2010/07/getting-started-with-rails-3-using-rvm/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://www.e-pedro.com/2010/07/getting-started-with-rails-3-using-rvm/</feedburner:origLink></item>
		<item>
		<title>Refactoring: Extracting the Singleton Pattern</title>
		<link>http://feedproxy.google.com/~r/e-pedro/~3/pRRi6iuf1y0/</link>
		<comments>http://www.e-pedro.com/2010/05/refactoring-extracting-the-singleton-pattern/#comments</comments>
		<pubDate>Tue, 04 May 2010 12:00:23 +0000</pubDate>
		<dc:creator>Pedro Sampaio</dc:creator>
				<category><![CDATA[.NET Technologies]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[dependency inversion]]></category>
		<category><![CDATA[inversion of control]]></category>
		<category><![CDATA[refactor]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://sweux.com/blogs/psampaio/?p=108</guid>
		<description><![CDATA[In this post, I show how to extract a Singleton Pattern, to reduce coupling and improve testability by using the Dependency-Inversion Principle]]></description>
			<content:encoded><![CDATA[<p>With this post I will be starting a series of posts on refactoring. The purpose is to use real production code (whenever possible) as a start point and improve it, instead of just random pointless examples.</p>
<h2>Starting point</h2>
<p>So the main class we will be changing is the DeviceManager. This class manages a collection of Devices (or a dictionary, to be more precise) and allows us to set which is the active device and to get a device by id. Note that this last feature could be handled by the Devices collection, but we are taking advantage of the dictionary to make that look-up more efficient.</p>
<p>One of the key points is that it has a singleton Instance property, that we use throughout the code.</p>
<pre class="brush: csharp; title: ; notranslate">
namespace PSampaio.Refactoring.Example1.Old
{
	using System.Collections.Generic;
	using System.Linq;

	public class DeviceManager
	{
		private static DeviceManager deviceManager;
		private static readonly object singletonLock = new object();
		private readonly Dictionary&lt;string, Device&gt; devices;

		public static DeviceManager Instance
		{
			get
			{
				lock (singletonLock)
				{
					if (deviceManager == null)
					{
						deviceManager = new DeviceManager();
					}
					return deviceManager;
				}
			}
		}

		public Device ActiveDevice { get; set; }

		public IEnumerable&lt;Device&gt; Devices
		{
			get { return devices.Values.AsEnumerable(); }
		}

		public DeviceManager()
		{
			devices = new Dictionary&lt;string, Device&gt;();
		}

		public void AddDevice(Device device)
		{
			if (!this.devices.ContainsKey(device.DeviceId))
			{
				this.devices.Add(device.DeviceId, device);
			}
		}

		public bool RemoveDevice(Device device)
		{
			var result = false;
			if (this.devices.ContainsKey(device.DeviceId))
			{
				result = this.devices.Remove(device.DeviceId);
			}
			return result;
		}

		public Device GetDeviceById(string id)
		{
			Device device;
			if (!devices.TryGetValue(id, out device))
			{
				device = null;
			}
			return device;
		}
	}
}
</pre>
<p>Then we have the actual Device. This class was edited down to the basics, as the real behavior of the Device is not important. For example purposes, it just has an Id that we use to index it in the dictionary.</p>
<pre class="brush: csharp; title: ; notranslate">
namespace PSampaio.Refactoring.Example1.Old
{
	public class Device
	{
		public string DeviceId { get; private set ; }

		public Device(string id)
		{
			DeviceId = id;
		}
	}
}
</pre>
<p>The ActiveDeviceSupport class is the one that uses both the DeviceManager and the Devices. Again, for example purposes, this only sets the first Device we have on the DeviceManager as the ActiveDevice.</p>
<pre class="brush: csharp; title: ; notranslate">
namespace PSampaio.Refactoring.Example1.Old
{
	using System.Linq;

	public class ActiveDeviceSupport
	{
		public void SetFirstDeviceAsActive()
		{
			var devices = DeviceManager.Instance.Devices;
			var firstDevice = devices.FirstOrDefault();
			if (firstDevice != null)
			{
				DeviceManager.Instance.ActiveDevice = firstDevice;
			}
		}
	}
}
</pre>
<p>And finally, we have the set of unit tests run against the DeviceManager. In case you are wondering, yes, these are the actual tests (albeit being slightly edited to protect the innocent) that we have for these classes.</p>
<pre class="brush: csharp; title: ; notranslate">
namespace PSampaio.Refactoring.Example1.Old
{
	using System.Collections.Generic;
	using System.Linq;

	using Microsoft.VisualStudio.TestTools.UnitTesting;

	[TestClass]
	public class Tests
	{
		[TestMethod]
		public void AddDevice()
		{
			var devices = new List&lt;Device&gt;();
			for (var i = 1; i &lt; 5; i++)
			{
				var device = new Device(string.Format(&quot;Device {0}&quot;, i));
				devices.Add(device);
				DeviceManager.Instance.AddDevice(device);
			}
			var thirdDevice = DeviceManager.Instance.GetDeviceById(&quot;Device 3&quot;);
			Assert.AreSame(devices.First(d =&gt; d.DeviceId == &quot;Device 3&quot;), thirdDevice);
		}

		[TestMethod]
		public void ListDevices()
		{
			var devices = DeviceManager.Instance.Devices;
			Assert.AreEqual(4, devices.Count());
		}

		[TestMethod]
		public void RemoveDeviceTest()
		{
			var devices = DeviceManager.Instance.Devices;
			var device = devices.ElementAt(2);
			Assert.IsTrue(DeviceManager.Instance.RemoveDevice(device));
			devices = DeviceManager.Instance.Devices;
			Assert.AreEqual(3, devices.Count());
			Assert.IsFalse(DeviceManager.Instance.RemoveDevice(device));
		}

	}
}
</pre>
<p>So what&#8217;s wrong with the code? The short answer is: a lot!</p>
<h2>Fixing the Singleton instance&#8230; and removing it</h2>
<p>Lets start by analyzing the Singleton instance. The first thing we need to consider when implementing a Singleton instance is whether we really need it, as it&#8217;s very likely we don&#8217;t. If we do, we should at least implement a double-check lock. See <a href="http://msdn.microsoft.com/en-us/library/ms998558.aspx" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/ms998558.aspx?referer=');">this MSDN page</a> and <a href="http://stackoverflow.com/questions/394898/double-checked-locking-in-net" onclick="pageTracker._trackPageview('/outgoing/stackoverflow.com/questions/394898/double-checked-locking-in-net?referer=');">this Stack Overflow question</a> for more information. Please note that this implementation has to be done just right, so be careful when writing it. I&#8217;ve read the block of code below a couple of times, and I think it&#8217;s correct, but you never know.</p>
<p>Here&#8217;s what we ended up with. Don&#8217;t just copy/paste it!</p>
<pre class="brush: csharp; title: ; notranslate">
private static volatile DeviceManager instance;
private static readonly object instanceLock = new object();
public static DeviceManager Instance
{
	get
	{
		if (instance == null)
		{
			lock (instanceLock)
			{
				if (instance == null)
				{
					instance = new DeviceManager();
				}
			}
		}

		return instance;
	}
}
</pre>
<p>In this case, we won&#8217;t be needing the Singleton instance so we will just remove this code altogether.</p>
<h2>Depend on abstractions</h2>
<p>The reason we don&#8217;t need the Singleton instance is twofold. First, it limits our ability to test any behavior that uses the DeviceManager (more on this later). Secondly, it forces us to depend on the concrete implementation of the DeviceManager, while what we want is to depend on abstractions. This way, we can promote the cohesiveness of our classes without having a tight coupling between them.</p>
<p>This is better stated in the book Agile Software Development &#8211; Principles, Patterns, and Practices by Robert <a href="http://twitter.com/unclebobmartin" onclick="pageTracker._trackPageview('/outgoing/twitter.com/unclebobmartin?referer=');">&#8220;Uncle Bob&#8221;</a> Martin. He calls this the Dependency-Inversion Principle:</p>
<blockquote><p>
A. High-level modules should not depend on low-level modules. Both should depend on abstractions.<br />
B. Abstractions should not depend on details. Details should depend on abstractions.
</p></blockquote>
<p>In order to do this, we need to extract an interface from DeviceManager.</p>
<pre class="brush: csharp; title: ; notranslate">
namespace PSampaio.Refactoring.Example1.New
{
	using System.Collections.Generic;
	using System.Linq;

	public interface IDeviceManager
	{
		Device ActiveDevice { get; set; }
		IEnumerable&lt;Device&gt; Devices { get; }
		void AddDevice(Device device);
		bool RemoveDevice(Device device);
		Device GetDeviceById(string id);
	}

	public class DeviceManager : IDeviceManager
	{
		private readonly Dictionary&lt;string, Device&gt; devices;

		public Device ActiveDevice { get; set; }

		public IEnumerable&lt;Device&gt; Devices
		{
			get { return devices.Values.AsEnumerable(); }
		}

		public DeviceManager()
		{
			devices = new Dictionary&lt;string, Device&gt;();
		}

		public void AddDevice(Device device)
		{
			if (!this.devices.ContainsKey(device.DeviceId))
			{
				this.devices.Add(device.DeviceId, device);
			}
		}

		public bool RemoveDevice(Device device)
		{
			var result = false;
			if (this.devices.ContainsKey(device.DeviceId))
			{
				result = this.devices.Remove(device.DeviceId);
			}
			return result;
		}

		public Device GetDeviceById(string id)
		{
			Device device;
			if (!devices.TryGetValue(id, out device))
			{
				device = null;
			}
			return device;
		}
	}
}
</pre>
<p>We also need to change the ActiveDeviceSupport class. Instead of having a concrete dependency on DeviceManager, we now depend on an abstraction, and that dependency is explicit. We could later evolve this design to use an IOC container to resolve the dependencies automatically.</p>
<pre class="brush: csharp; title: ; notranslate">
namespace PSampaio.Refactoring.Example1.New
{
	using System.Linq;

	public class ActiveDeviceSupport
	{
		private readonly IDeviceManager deviceManager;

		public ActiveDeviceSupport(IDeviceManager deviceManager)
		{
			this.deviceManager = deviceManager;
		}

		public void SetFirstDeviceAsActive()
		{
			var devices = deviceManager.Devices;
			var firstDevice = devices.FirstOrDefault();
			if (firstDevice != null)
			{
				deviceManager.ActiveDevice = firstDevice;
			}
		}
	}
}
</pre>
<h2>Correcting the tests</h2>
<p>The tests we started with are a perfect example of how not to do unit testing, as they will only pass if they are run all together and in a specific order. While the first (CanAddDevice) test is isolated, the other two depend on the previous ones passing. Obviously, the tests will fail if we run each one separately. The reason for this is that they depend on the Singleton instance of the DeviceManager. So based on the changes we have been making, we can now write the tests differently.</p>
<pre class="brush: csharp; title: ; notranslate">
namespace PSampaio.Refactoring.Example1.New
{
	using System.Linq;

	using Microsoft.VisualStudio.TestTools.UnitTesting;

	[TestClass]
	public class Tests
	{
		[TestMethod]
		public void CanAddDevice()
		{
			const string id = &quot;Device 1&quot;;
			var deviceManager = new DeviceManager();
			var device = new Device(id);
			deviceManager.AddDevice(device);
			Assert.AreSame(device, deviceManager.GetDeviceById(id));
		}

		[TestMethod]
		public void CanListDevices()
		{
			const int deviceCount = 4;
			var deviceManager = new DeviceManager();
			for (var i = 0; i &lt; deviceCount; i++)
			{
				var device = new Device(string.Format(&quot;Device {0}&quot;, i));
				deviceManager.AddDevice(device);
			}
			Assert.AreEqual(deviceCount, deviceManager.Devices.Count());
		}

		[TestMethod]
		public void CanRemoveDevice()
		{
			var deviceManager = new DeviceManager();
			var device = new Device(&quot;Device 1&quot;);
			deviceManager.AddDevice(device);
			Assert.AreEqual(1, deviceManager.Devices.Count());
			deviceManager.RemoveDevice(device);
			Assert.AreEqual(0, deviceManager.Devices.Count());
		}
	}
}
</pre>
<p>As you can see, each test is now isolated from the others, testing a specific code path in the DeviceManager. There are still changes that we could make, namely the for loop in the ListDevices test and the fact that we call IDeviceManager.AddDevice on the CanRemoveDevice test, but I&#8217;m OK with leaving it like that for now.</p>
<p>As a positive side-effect, if we need to test the ActiveDeviceSupport class, we don&#8217;t depend on DeviceManager anymore, so we can just mock the IDeviceManager interface and test ActiveDeviceSupport in isolation also.</p>
<p>Hope this helps!</p>
<img src="http://feeds.feedburner.com/~r/e-pedro/~4/pRRi6iuf1y0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.e-pedro.com/2010/05/refactoring-extracting-the-singleton-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.e-pedro.com/2010/05/refactoring-extracting-the-singleton-pattern/</feedburner:origLink></item>
		<item>
		<title>A view model base class to use with MVVM in WPF</title>
		<link>http://feedproxy.google.com/~r/e-pedro/~3/XPm6K-br1JA/</link>
		<comments>http://www.e-pedro.com/2009/07/a-view-model-base-class-to-use-with-mvvm-in-wpf/#comments</comments>
		<pubDate>Mon, 06 Jul 2009 01:19:09 +0000</pubDate>
		<dc:creator>Pedro Sampaio</dc:creator>
				<category><![CDATA[.NET Technologies]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[ViewModel]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://sweux.com/blogs/psampaio/?p=98</guid>
		<description><![CDATA[A view model base class to use with MVVM in WPF, with caching of PropertyChangedEventArgs for each property.]]></description>
			<content:encoded><![CDATA[<p>As I mentioned in previous posts (<a href="http://www.e-pedro.com/2009/04/creating-a-custom-observable-collection-in-wpf/">here</a>, <a href="http://www.e-pedro.com/2009/04/an-introduction-to-observablecollection-in-wpf/">here</a>, and <a href="http://www.e-pedro.com/2009/06/using-data-binding-with-static-resources-in-wpf/">here</a>), when you develop WPF application, you&#8217;ll eventually use view models. So, instead of keep developing them from scratch, I&#8217;m posting three different alternatives for easy reference.</p>
<h2>The simple view model</h2>
<pre class="brush: csharp; title: ; notranslate">
public class ViewModelBase : INotifyPropertyChanged
{
	#region Implementation of INotifyPropertyChanged

	public event PropertyChangedEventHandler PropertyChanged;

	protected virtual void OnPropertyChanged(string propertyName)
	{
		OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
	}

	protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
	{
		var handler = PropertyChanged;
		if (handler != null)
			handler(this, args);
	}

	#endregion
}
</pre>
<p>This is the simplest class you can have. It implements the INotifyPropertyChanged interface and provides two protected methods for you to notify that a specific property as changed. On that takes the string as a parameter, and another that takes a PropertyChangedEventArgs object. The problem with this approach is that you&#8217;ll keep creating new instances of PropertyChangedEventArgs, even though you have a limited number of properties in the class.</p>
<h2>The smarter view model</h2>
<pre class="brush: csharp; title: ; notranslate">
public abstract class ViewModelBaseWithArgCache : ViewModelBase
{
	private readonly Dictionary&lt;string, PropertyChangedEventArgs&gt; eventArgsCache;

	protected ViewModelBaseWithArgCache()
	{
		eventArgsCache = new Dictionary&lt;string, PropertyChangedEventArgs&gt;();
	}

	#region Overrides

	protected override void OnPropertyChanged(string propertyName)
	{
		PropertyChangedEventArgs args;
		if (!eventArgsCache.ContainsKey(propertyName))
		{
			args = new PropertyChangedEventArgs(propertyName);
			eventArgsCache.Add(propertyName, args);
		}
		else
		{
			args = eventArgsCache[propertyName];
		}

		OnPropertyChanged(args);
	}

	#endregion

}
</pre>
<p>Here, we&#8217;re overriding OnPropertyChanged(string propertyName), to provide a custom implementation. First we initialize a dictionary of , that we&#8217;re going to use as cache. Now, whenever we call OnPropertyChanged(string property), we check if we have an instance of EventArgs cached for that property. If we do, we return it. If we don&#8217;t, we create it, add it to the cache, and then return it. We use that instance to call the protected OnPropertyChanged(PropertyChangedEventArgs args) of ViewModelBase.</p>
<h2>The unified view model</h2>
<pre class="brush: csharp; title: ; notranslate">
public class UnifiedViewModelBase : INotifyPropertyChanged
{
	private readonly Dictionary&lt;string, PropertyChangedEventArgs&gt; eventArgsCache;

	protected UnifiedViewModelBase()
	{
		eventArgsCache = new Dictionary&lt;string, PropertyChangedEventArgs&gt;();
	}

	#region Implementation of INotifyPropertyChanged

	public event PropertyChangedEventHandler PropertyChanged;

	protected void OnPropertyChanged(string propertyName)
	{
		PropertyChangedEventArgs args;
		if (!eventArgsCache.TryGetValue(propertyName, out args))
		{
			args = new PropertyChangedEventArgs(propertyName);
			eventArgsCache.Add(propertyName, args);
		}

		OnPropertyChanged(args);
	}

	protected void OnPropertyChanged(PropertyChangedEventArgs args)
	{
		var handler = PropertyChanged;
		if (handler != null)
			handler(this, args);
	}

	#endregion
}
</pre>
<p>Now, instead of have a two-level hierarchy of classes, we combined them together in a single UnifiedViewModelBase. You may want to rename this class to something like ViewModelBase.</p>
<p>You can download all the code in this post by clicking <a href="http://www.e-pedro.com/wp-content/uploads/2009/07/PSampaio.ViewModelBaseClass.zip">this link</a>.</p>
<p>Hope this helps!</p>
<img src="http://feeds.feedburner.com/~r/e-pedro/~4/XPm6K-br1JA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.e-pedro.com/2009/07/a-view-model-base-class-to-use-with-mvvm-in-wpf/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		<feedburner:origLink>http://www.e-pedro.com/2009/07/a-view-model-base-class-to-use-with-mvvm-in-wpf/</feedburner:origLink></item>
		<item>
		<title>Using Data Binding with Static Resources in WPF</title>
		<link>http://feedproxy.google.com/~r/e-pedro/~3/EylrQ_1NclM/</link>
		<comments>http://www.e-pedro.com/2009/06/using-data-binding-with-static-resources-in-wpf/#comments</comments>
		<pubDate>Tue, 16 Jun 2009 10:36:18 +0000</pubDate>
		<dc:creator>Pedro Sampaio</dc:creator>
				<category><![CDATA[.NET Technologies]]></category>
		<category><![CDATA[Data Binding]]></category>
		<category><![CDATA[Static Resource]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://sweux.com/blogs/psampaio/?p=89</guid>
		<description><![CDATA[In this post, I’ll be showing how to use resources for which you don’t know in design time the key to use in xaml (maybe because you’re loading them dynamically), by binding them to view model properties.]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve been using WPF for more than a couple of weeks, I&#8217;m sure you wrote code like this a lot of times: you define a resource and reference it with StaticResource.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Window x:Class=&quot;PSampaio.StaticResourcesWithBinding.Window1&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    Title=&quot;Window1&quot; Width=&quot;400&quot; Height=&quot;200&quot;&gt;
	&lt;Window.Resources&gt;
		&lt;SolidColorBrush x:Key=&quot;RedBrush&quot; Color=&quot;#FFFF0000&quot; /&gt;
	&lt;/Window.Resources&gt;
	&lt;Grid&gt;
		&lt;TextBlock Text=&quot;Hello World&quot; FontSize=&quot;48&quot; Foreground=&quot;{StaticResource RedBrush}&quot; /&gt;
	&lt;/Grid&gt;
&lt;/Window&gt;
</pre>
<p>However, if you applications are getting increasingly more complex, then it can start to get more tricky. In this post, I&#8217;ll be showing how to use resources for which you don&#8217;t know in design time the key to use in xaml (maybe because you&#8217;re loading them dynamically), by binding them to view model properties (which, by the way, you should be using).</p>
<h2>Setting the scene</h2>
<p>Suppose you&#8217;re indeed loading the resources dynamically, like so:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Application x:Class=&quot;PSampaio.StaticResourcesWithBinding.App&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    StartupUri=&quot;Window1.xaml&quot;&gt;
	&lt;Application.Resources&gt;
		&lt;SolidColorBrush x:Key=&quot;RedBrush&quot; Color=&quot;#FFFF0000&quot; /&gt;
	&lt;/Application.Resources&gt;
&lt;/Application&gt;
</pre>
<p>Yes, yes, I know. You can reference that resource the usual way, but this is just sample code, so assume you can&#8217;t. We&#8217;re also using a view model that contains a property with the key for the resource you want to use (that maybe you got that after loading the resource dynamically). That model is being instanced from the window constructor. Again, let me stress that <strong>this is sample code</strong> that you need to adapt to fit your own circumstances.</p>
<pre class="brush: csharp; title: ; notranslate">
public Window1()
{
	InitializeComponent();

	DataContext = new MyViewModel(&quot;RedBrush&quot;);
}
</pre>
<pre class="brush: csharp; title: ; notranslate">
namespace PSampaio.StaticResourcesWithBinding
{
	public class MyViewModel
	{
		public string MyResourceKey { get; private set; }

		public MyViewModel(string myResourceKey)
		{
			MyResourceKey = myResourceKey;
		}
	}
}
</pre>
<p>Are you with me so far? Good. Lets move on!</p>
<h2>The obvious solution</h2>
<p>Your first reaction to this will be to actually use the binding in a StaticResource. You can go ahead and try it if you want to. You&#8217;ve get to something like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Window x:Class=&quot;PSampaio.StaticResourcesWithBinding.Window1&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    Title=&quot;Window1&quot; Width=&quot;400&quot; Height=&quot;200&quot;&gt;
	&lt;Grid&gt;
		&lt;TextBlock Text=&quot;Hello World&quot; FontSize=&quot;48&quot; Foreground=&quot;{StaticResource {Binding MyResourceKey}}&quot; /&gt;
	&lt;/Grid&gt;
&lt;/Window&gt;
</pre>
<p>This code will compile just fine, but if you run it, you&#8217;ll get an exception. This is because the StaticResource key is only evaluated when it&#8217;s needed, and when it tries to provide a value, it can&#8217;t find a resource named &#8216;{System.Windows.Data.Binding}&#8217;. So we&#8217;ll have to find another way, since this clearly won&#8217;t work.</p>
<h2>A better solution</h2>
<p>The only place were we can make this work is the markup itself, so lets start from the top, with the syntax we want to use, and go from there all the way to the bottom. We want this to work:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Window x:Class=&quot;PSampaio.StaticResourcesWithBinding.Window1&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    Title=&quot;Window1&quot; Width=&quot;400&quot; Height=&quot;200&quot;&gt;
	&lt;Grid&gt;
		&lt;TextBlock Text=&quot;Hello World&quot; FontSize=&quot;48&quot; Foreground=&quot;{BindableStaticResource {Binding MyResourceKey}}&quot; /&gt;
	&lt;/Grid&gt;
&lt;/Window&gt;
</pre>
<p> In order for this to work, we need to create a new markup extension, so lets do just that. Create a new class that derives from the original StaticResourceExtension, called BindableStaticResourceExtension. Notice that the suffix is optional in XAML, and that you&#8217;ll need to add the namespace prefix in the markup. Create it with 2 constructors, one empty, and one with the Binding. You should have this class for now.</p>
<pre class="brush: csharp; title: ; notranslate">
using System.Windows;
using System.Windows.Data;

namespace PSampaio.StaticResourcesWithBinding
{
	public class BindableStaticResource : StaticResourceExtension
	{
		public Binding Binding { get; set; }

		public BindableStaticResource()
		{
		}

		public BindableStaticResource(Binding binding)
		{
			Binding = binding;
		}
	}
}
</pre>
<p>Now the tricky part, when and how do you get the actual resource key, and what exactly do you do with it. The <strong>&#8216;when&#8217;</strong> part is the easy one: there&#8217;s one method you can override public override object ProvideValue(IServiceProvider serviceProvider) that the framework will call in order to get the value. In this method, you have to evaluate the binding and get its result (the <strong>&#8216;how&#8217;</strong>) and set it to the ResourceKey in the base StaticResourceExtension class (the <strong>&#8216;what to do&#8217;</strong>). After that, you can delegate the rest of the work to the base class and let it provide it&#8217;s value. I&#8217;ll first show the code, and then go through it.</p>
<pre class="brush: csharp; title: ; notranslate">
private static readonly DependencyProperty DummyProperty;

static BindableStaticResource()
{
	DummyProperty = DependencyProperty.RegisterAttached(&quot;Dummy&quot;,
										     typeof (Object),
										     typeof (DependencyObject),
										     new UIPropertyMetadata(null));
}

public override object ProvideValue(IServiceProvider serviceProvider)
{
	var target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
	var targetObject = (FrameworkElement)target.TargetObject;

	MyBinding.Source = targetObject.DataContext;
	var DummyDO = new DependencyObject();
	BindingOperations.SetBinding(DummyDO, DummyProperty, MyBinding);

	ResourceKey = DummyDO.GetValue(DummyProperty);

	return base.ProvideValue(serviceProvider);
}
</pre>
<p>It may take a little to fully understand what&#8217;s going on here, but it&#8217;s fairly easy (once you figure it out). You need to query the service provider for an IProvideValueTarget. The returned object has two properties: TargetObject and TargetProperty. This tells you which property of which object we&#8217;re evaluating the binding for. You set the source of the binding to the data context of the target object, meaning &#8220;look here for the path you want&#8221;. This is the only use you&#8217;ll have for the target object</p>
<p>You then set the binding on a dummy DependencyObject, with a dummy property. If you use TargetProperty here, the binding operation will try to convert the resulting value to the type of the property. In this case, it would try to convert the string &#8220;RedBrush&#8221; to an actual Brush object, as that&#8217;s the type of TargetProperty (Foreground is a Brush). After this, all you need to do is get the value from the dummy property.</p>
<p>Now that ResourceKey contains the resource key we need, just call base.ProvideValue(serviceProvider) and let StaticResourceExtension try and find a resource with that key. Hope this helps!</p>
<p>You can download the code <a href='http://www.e-pedro.com/wp-content/uploads/2009/06/PSampaio.StaticResourcesWithBinding.zip'>from this link</a>.</p>
<img src="http://feeds.feedburner.com/~r/e-pedro/~4/EylrQ_1NclM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.e-pedro.com/2009/06/using-data-binding-with-static-resources-in-wpf/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		<feedburner:origLink>http://www.e-pedro.com/2009/06/using-data-binding-with-static-resources-in-wpf/</feedburner:origLink></item>
		<item>
		<title>An Introduction to ObservableCollection in WPF</title>
		<link>http://feedproxy.google.com/~r/e-pedro/~3/bZKxj_VPV4A/</link>
		<comments>http://www.e-pedro.com/2009/04/an-introduction-to-observablecollection-in-wpf/#comments</comments>
		<pubDate>Tue, 28 Apr 2009 03:07:22 +0000</pubDate>
		<dc:creator>Pedro Sampaio</dc:creator>
				<category><![CDATA[.NET Technologies]]></category>
		<category><![CDATA[Data Binding]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://sweux.com/blogs/psampaio/?p=43</guid>
		<description><![CDATA[This post discusses ObservableCollection<t>, used in WPF data binding. It describes its basic uses, along with some sample code to help you better understand how it all works.]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://msdn.microsoft.com/en-us/library/ms668604.aspx" target="_blank" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/ms668604.aspx?referer=');">ObservableCollection&lt;T&gt;</a> is one of the most important features of WPF data binding. From the documentation:</p>
<blockquote><p>Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.</p></blockquote>
<p>Most people seem confused about this, so it&#8217;s worth a clear note. <strong>An ObservableCollection is just like a regular collection.</strong> If  you check the documentation, you can see that ObservableCollection is defined as:</p>
<pre class="brush: csharp; title: ; notranslate">public class ObservableCollection&lt;T&gt; : Collection&lt;T&gt;, INotifyCollectionChanged, INotifyPropertyChanged</pre>
<p>So you have access to all the members you would have in Collection&lt;T&gt;. Again, refer to the documentation for the list of all those members.</p>
<p>Notice that, like any collection that derives from Collection&lt;T&gt;, its methods (namelly Add and Remove) <strong>accept null parameters</strong> and do not throw an exception.</p>
<p>But the main feature of the ObservableCollection&lt;T&gt; are the events it raises when the items it contains change. By implementing the INotifyCollectionChanged and INotifyPropertyChanged interfaces, the collection has events for CollectionChanged and PropertyChanged. All these events are related. The first one is raised whenever something changed in the collection, be it Add, Remove, Move, etc. This also trigger the PropertyChanged event for the <strong>Items[]</strong> property. When you&#8217;re adding or removing items, PropertyChanged is also raised for the <strong>Count</strong> property.</p>
<p>But enough theory, here&#8217;s a small example of how to use it. First of all, we start with our domain model, the <strong>Person</strong>.</p>
<pre class="brush: csharp; title: ; notranslate">
namespace PSampaio.ObservableCollectionSample
{
	public class Person
	{
		public string FirstName { get; set; }
		public string LastName { get; set; }
		public string FullName { get { return string.Format(&quot;{0} {1}&quot;, FirstName, LastName); } }
	}
}
</pre>
<p>Next, we have a ViewModel that uses this domain model.</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;

namespace PSampaio.ObservableCollectionSample
{
	public class PickOneViewModel
	{
		readonly Random random = new Random();

		public List&lt;Person&gt; AvailablePeople { get; private set; }
		public ICommand PickOnecommand { get; private set; }
		public ObservableCollection&lt;Person&gt; SelectedPeople { get; private set; }

		public PickOneViewModel()
		{
			AvailablePeople = new List&lt;Person&gt;
			{
				new Person {FirstName = &quot;John&quot;, LastName = &quot;Doe&quot;},
				new Person {FirstName = &quot;Michael&quot;, LastName = &quot;Jones&quot;},
				new Person {FirstName = &quot;Jane&quot;, LastName = &quot;Smith&quot;},
			};

			PickOnecommand = new DelegateCommand&lt;object&gt;(obj =&gt;
			{
				int availablePersonIndex = random.Next(0, AvailablePeople.Count);
				SelectedPeople.Add(AvailablePeople[availablePersonIndex]);
			});

			SelectedPeople = new ObservableCollection&lt;Person&gt;();
		}
	}
}
</pre>
<p>This PickOneViewModel has three properties, that we will bind to in the Window XAML. AvailablePeople is just a list of the people available to be selected. It&#8217;s just a standard List because we do not want to update it, just use it as a source for SelectedPeople. PickOneCommand is a DelegateCommand. This delegate command was based on the CompositeWPF class with the same name, and lets the you create an ICommand that&#8217;s defined with delegates, instead of CommandBindings. Finally, SelectedPeople is an ObservableCollection that starts empty and where we will be adding the (random) person selected each time we execute PickOneCommand.</p>
<p>The UI for this sample is fairly simple. Just add the ViewModel as an ObjectDataProvider to the window resources and use it as a DataSource for the window contents.</p>
<pre class="brush: csharp; title: ; notranslate">
&lt;Window
	x:Class=&quot;PSampaio.ObservableCollectionSample.Window1&quot;
	xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
	xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
	xmlns:Sample=&quot;clr-namespace:PSampaio.ObservableCollectionSample&quot;
	Title=&quot;Window1&quot;
	Width=&quot;300&quot;
	Height=&quot;300&quot;&gt;

	&lt;Window.Resources&gt;
		&lt;ObjectDataProvider
			x:Key=&quot;Viewmodel&quot;
			ObjectType=&quot;{x:Type Sample:PickOneViewModel}&quot;/&gt;
	&lt;/Window.Resources&gt;

	&lt;DockPanel DataContext=&quot;{StaticResource Viewmodel}&quot;&gt;
		&lt;ListView DockPanel.Dock=&quot;Left&quot; Width=&quot;130&quot;
			ItemsSource=&quot;{Binding AvailablePeople}&quot;
			DisplayMemberPath=&quot;FullName&quot; /&gt;
		&lt;ListView DockPanel.Dock=&quot;Right&quot; Width=&quot;130&quot;
			ItemsSource=&quot;{Binding SelectedPeople}&quot;
			DisplayMemberPath=&quot;FullName&quot; /&gt;
		&lt;Button Width=&quot;20&quot;
			Command=&quot;{Binding PickOnecommand}&quot;
			Content=&quot;&gt;&gt;&quot;/&gt;
	&lt;/DockPanel&gt;
&lt;/Window&gt;
</pre>
<p>It really is that simple. What is happening is that, when you click on the button, PickOneCommand is executed, adding one random person to the SelectedPerson collection. When that occurs, the list raises a CollectionChanged event that WPF listens. By now, the data binding knows that, because the list has changed, that it needs to update its contents, which it does.</p>
<p>So now you know how to use ObservableCollection. Please keep in mind that you don&#8217;t have use a view model, although I would consider it a best practice, that allows you to effectively separate the content from the presentation. Also, you can replace DelegateCommand with your CommandBindings if you prefer. Again, this is a matter of preference, as I believe using it makes for cleaner code.</p>
<img src="http://feeds.feedburner.com/~r/e-pedro/~4/bZKxj_VPV4A" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.e-pedro.com/2009/04/an-introduction-to-observablecollection-in-wpf/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://www.e-pedro.com/2009/04/an-introduction-to-observablecollection-in-wpf/</feedburner:origLink></item>
		<item>
		<title>Creating a Custom Observable Collection in WPF</title>
		<link>http://feedproxy.google.com/~r/e-pedro/~3/GjuQA6NPcRM/</link>
		<comments>http://www.e-pedro.com/2009/04/creating-a-custom-observable-collection-in-wpf/#comments</comments>
		<pubDate>Mon, 13 Apr 2009 03:51:22 +0000</pubDate>
		<dc:creator>Pedro Sampaio</dc:creator>
				<category><![CDATA[.NET Technologies]]></category>
		<category><![CDATA[Custom Collections]]></category>
		<category><![CDATA[Data Binding]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://sweux.com/blogs/psampaio/?p=14</guid>
		<description><![CDATA[One of the biggest advantadges WPF has is its Data Binding features. Data Binding can be done in several ways, but the most common is using the INotifyPropertyChanged and INotifyCollectionChanged interfaces. For simple objects, all you need to do is implement the INotifyPropertyChanged, and raise the PropertyChanged event when your properties change. When you want to bind to a collection, you will want to use ObservableCollection&#60;T&#62;. This collection implements both interfaces, therefore notifying you when the items in the collection change and when the items' properties change. This works great if you're using standard collections. The problem arises when you want to use a custom collection. For databinding to work with custom collections, you will have to create a new "Observable" wrapper around it.]]></description>
			<content:encoded><![CDATA[<p>One of the biggest advantages WPF has is its Data Binding features. Data Binding can be done in several ways, but the most common is using the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx" target="_blank" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx?referer=');">INotifyPropertyChanged</a> and <a href="http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspx" target="_blank" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspx?referer=');">INotifyCollectionChanged</a> interfaces. For simple objects, all you need to do is implement the INotifyPropertyChanged, and raise the PropertyChanged event when your properties change. Maybe something like this:</p>
<pre class="brush: csharp; title: ; notranslate">
public class MySampleClass : INotifyPropertyChanged
{
	public int MyProperty
	{
	get
	{
		return _myProperty;
	}
	set
	{
		if (_myProperty == value)
		return;

		_myProperty = value;
		OnPropertyChanged(&quot;MyProperty&quot;);
	}
}

public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
	if (this.PropertyChanged != null)
	PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
	}
}
</pre>
<p>Instead of having each class implement the interface, you can create a base class that already does that, and inherit from this new one. You can see an example on <a href="http://www.e-pedro.com/2009/07/a-view-model-base-class-to-use-with-mvvm-in-wpf/" target="_blank">this post</a>. However, remember that you can only inherit from one class, so make sure you structure you class hierarchy properly. My advice is to use this only in presentation objects (or view models, if you&#8217;re using <a href="http://groups.google.com/group/wpf-disciples/browse_thread/thread/3fe270cd107f184f" target="_blank" onclick="pageTracker._trackPageview('/outgoing/groups.google.com/group/wpf-disciples/browse_thread/thread/3fe270cd107f184f?referer=');">MVVM</a>)</p>
<p>When you want to bind to a collection, you will want to use <a href="http://msdn.microsoft.com/en-us/library/ms668604.aspx" target="_blank" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/ms668604.aspx?referer=');">ObservableCollection&lt;T&gt;</a>. This collection implements both interfaces, therefore notifying you when the items in the collection change and when the items&#8217; properties change. This works great if you&#8217;re using standard collections. The problem arises when you want to use a custom collection. When you create an ObservableCollection&lt;T&gt; on v3.5, you have 3 constructors that rely on Collection&lt;T&gt; to create a new list. If you pass a List&lt;T&gt; or IEnumerable&lt;T&gt;, all that it does is copy the items, between both collections. This will of course make you custom collection useless. For this to work, you will have to create a new &#8220;Observable&#8221; wrapper around your custom collection. Lets start with the interface. All we need is a collection that implements the two interfaces we discussed earlier.</p>
<pre class="brush: csharp; title: ; notranslate">
public interface ICustomObservableCollection&lt;T&gt; : ICollection&lt;T&gt;, INotifyCollectionChanged, INotifyPropertyChanged
{
}
</pre>
<p>Before we move on the the implementation, first we need to better understand what is it that we&#8217;re trying to do and how to achieve it. We have a custom collection that we need to add additional features, so we need to &#8220;decorate&#8221; our collection with new behavior. For this we can follow the <a href="http://www.dofactory.com/Patterns/PatternDecorator.aspx" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.dofactory.com/Patterns/PatternDecorator.aspx?referer=');">Decorator Pattern</a>.</p>
<pre class="brush: csharp; title: ; notranslate">
public class CustomObservableCollection&lt;T&gt; : ICustomObservableCollection&lt;T&gt;
{
	#region Fields
	...
	#endregion

	#region Properties
	protected ICollection&lt;T&gt; InnerCollection { get; private set; }
	#endregion

	#region Constructors

	public CustomObservableCollection(ICollection&lt;T&gt; innerCollection)
	{
		if (innerCollection == null)
			throw new ArgumentNullException(&quot;innerCollection&quot;);

		InnerCollection = innerCollection;
	}

	#endregion

	#region Implementation

	#region Implementation of INotifyCollectionChanged
	...
	#endregion

	#region Implementation of INotifyPropertyChanged
	...
	#endregion

	#region Implementation of IEnumerable
	...
	#endregion

	#region Implementation of ICollection&lt;T&gt;
	...
	#endregion

	#endregion
}
</pre>
<p>Now that we have both collections wrapped on inside the other, all we need to do is provide the implementation of the interfaces. Starting with INotifyPropertyChanged:</p>
<pre class="brush: csharp; title: ; notranslate">
#region Implementation of INotifyPropertyChanged

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
	if (PropertyChanged != null)
	{
		PropertyChanged(this, e);
	}
}

private void OnPropertyChanged(string propertyName)
{
	OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}

#endregion
</pre>
<p>Then, we can implement INotifyCollectionChanged. For this implementation to work correctly, we need to add a monitor, so that we detect collection reentrancy. We can do this with this SimpleMonitor class, that implements IDisposable, and just keeps a counter of entries. We also need to provide methods tor activating the monitor.</p>
<pre class="brush: csharp; title: ; notranslate">
#region SimpleMonitor
protected IDisposable BlockReentrancy()
{
	this._monitor.Enter();
	return this._monitor;
}

protected void CheckReentrancy()
{
	if ((this._monitor.Busy &amp;&amp; (CollectionChanged != null)) &amp;&amp; (CollectionChanged.GetInvocationList().Length &gt; 1))
	{
		throw new InvalidOperationException(&quot;Collection Reentrancy Not Allowed&quot;);
	}
}

[Serializable]
private class SimpleMonitor : IDisposable
{
	private int _busyCount;

	public bool Busy
	{
		get { return this._busyCount &gt; 0; }
	}

	public void Enter()
	{
		this._busyCount++;
	}

	#region Implementation of IDisposable

	public void Dispose()
	{
		this._busyCount--;
	}

	#endregion
}
#endregion
</pre>
<p>This SimpleMonitor is created in the CustomObservableCollection constructor, so we need to account for that too.</p>
<pre class="brush: csharp; title: ; notranslate">
#region Fields
private readonly SimpleMonitor _monitor;
#endregion

#region Constructors

public CustomObservableCollection(ICollection innerCollection)
{
	this._monitor = new SimpleMonitor();

	if (innerCollection == null)
	{
		throw new ArgumentNullException(&quot;innerCollection&quot;);
	}

	InnerCollection = innerCollection;
}

#endregion
</pre>
<p>Now, we&#8217;re ready to provide an implementation for INotifyCollectionChanged.</p>
<pre class="brush: csharp; title: ; notranslate">
#region Implementation of INotifyCollectionChanged

public event NotifyCollectionChangedEventHandler CollectionChanged;

protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
	if (CollectionChanged != null)
	{
		using (BlockReentrancy())
		{
			CollectionChanged(this, e);
		}
	}
}

private void OnCollectionChanged(NotifyCollectionChangedAction action, object item)
{
	OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item));
}

private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index)
{
	OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index));
}

private void OnCollectionReset()
{
	OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}

#endregion
</pre>
<p>The next one is IEnumerable. For this one, we will delegate to the InnerCollection.</p>
<pre class="brush: csharp; title: ; notranslate">
#region Implementation of IEnumerable

public IEnumerator GetEnumerator()
{
	return InnerCollection.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
	return GetEnumerator();
}

#endregion
</pre>
<p>Finally, provide the implementation for ICollection&lt;T&gt;. Again, this will delegate to the InnerCollection raising events when needed. Notice the use of the CountString and IndexerName fields.</p>
<pre class="brush: csharp; title: ; notranslate">
#region Fields

private const string CountString = &quot;Count&quot;;
private const string IndexerName = &quot;Item[]&quot;;

private readonly SimpleMonitor _monitor;

#endregion
</pre>
<pre class="brush: csharp; title: ; notranslate">
#region Implementation of ICollection

public void Add(T item)
{
	CheckReentrancy();
	InnerCollection.Add(item);
	OnPropertyChanged(CountString);
	OnPropertyChanged(IndexerName);
	OnCollectionChanged(NotifyCollectionChangedAction.Add, item, InnerCollection.Count);
}

public void Clear()
{
	CheckReentrancy();
	InnerCollection.Clear();
	OnPropertyChanged(CountString);
	OnPropertyChanged(IndexerName);
	OnCollectionReset();
}

public bool Contains(T item)
{
	return InnerCollection.Contains(item);
}

public void CopyTo(T[] array, int arrayIndex)
{
	InnerCollection.CopyTo(array, arrayIndex);
}

public bool Remove(T item)
{
	CheckReentrancy();
	bool result = InnerCollection.Remove(item);
	OnPropertyChanged(CountString);
	OnPropertyChanged(IndexerName);
	OnCollectionChanged(NotifyCollectionChangedAction.Remove, item);
	return result;
}

public int Count
{
	get { return InnerCollection.Count; }
}

public bool IsReadOnly
{
	get { return InnerCollection.IsReadOnly; }
}

#endregion
</pre>
<p>You can download the source code <del datetime="2009-04-21T11:07:40+00:00">here</del>.</p>
<p><strong>Update: Added the source code as a compressed file. You can get it <a href="http://www.e-pedro.com/wp-content/uploads/2009/04/customobservablecollection.zip">here</a>.</strong></p>
<img src="http://feeds.feedburner.com/~r/e-pedro/~4/GjuQA6NPcRM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.e-pedro.com/2009/04/creating-a-custom-observable-collection-in-wpf/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		<feedburner:origLink>http://www.e-pedro.com/2009/04/creating-a-custom-observable-collection-in-wpf/</feedburner:origLink></item>
		<item>
		<title>No clues, just money</title>
		<link>http://feedproxy.google.com/~r/e-pedro/~3/HT8BPWJwy6k/</link>
		<comments>http://www.e-pedro.com/2009/02/no-clues-just-money/#comments</comments>
		<pubDate>Mon, 23 Feb 2009 14:52:47 +0000</pubDate>
		<dc:creator>Pedro Sampaio</dc:creator>
				<category><![CDATA[User Experience]]></category>
		<category><![CDATA[ATM]]></category>
		<category><![CDATA[TPA]]></category>
		<category><![CDATA[UX]]></category>

		<guid isPermaLink="false">http://sweux.com/blogs/psampaio/?p=8</guid>
		<description><![CDATA[Please remove your card I&#8217;m not the kind of person to carry much money in my wallet. I usually depend on debit or credit cards for most of my transactions. But while this is much more convenient for me, it sometimes is a nuisance, like the one that happened just a couple of days ago. I was having dinner at a local restaurant, and when we finished the meal, we proceeded to pay with the [...]]]></description>
			<content:encoded><![CDATA[<h3>Please remove your card</h3>
<p>I&#8217;m not the kind of person to carry much money in my wallet. I usually depend on debit or credit cards for most of my transactions. But while this is much more convenient for me, it sometimes is a nuisance, like the one that happened just a couple of days ago.</p>
<p><a href="http://www.e-pedro.com/blog/wp-content/uploads/2009/02/atm.jpg"><img style="border-right: 0px; border-top: 0px; display: inline; margin: 0px 0px 0px 10px; border-left: 0px; border-bottom: 0px" title="ATM" src="http://www.e-pedro.com/blog/wp-content/uploads/2009/02/atm-thumb.jpg" border="0" alt="ATM" width="299" height="252" align="right" /></a>I was having dinner at a local restaurant, and when we finished the meal, we proceeded to pay with the debit card. The waitress keys in the value, &#8220;Please press OK, then your code, and then OK once again. And so I did: &#8221; OK &#8230; #### &#8230; OK&#8221;. After a couple of minutes later, the answer comes: &#8220;Please remove your card&#8221;. No receipt, no error message, nothing. Just &#8220;Please remove your card&#8221;. Figuring there was something wrong with the communication, we tried again. &#8220;OK &#8230; #### &#8230; OK&#8221;.  And again, the result was the same: &#8220;Please remove your card&#8221;.</p>
<p>Without any other clues to what was going on, we decided that the card was the culprit, and tried another time with a different card from a different bank. This time, it was even worse, as there was no message displayed, not even asking to remove the card.</p>
<h3>No paper, what else?</h3>
<p>After all these unsuccessful attempts, the waitress called another waitress that was passing by and asked her if she could help. She thought of the obvious (it’s always obvious looking back): “Have you checked if the machine has paper?” Well, of course it didn’t. Just as soon as she opened the machine, we all noticed the empty cardboard roll. Now, it’s true that the waitress that used it the last time when the paper ended could have changed it, but this is clearly an User Experience problem.</p>
<p>The main issue here is that the portable payment terminal gives insufficient information regarding this error (and eventually even gives no information at all). This could be corrected with a simple message stating the actual problem: “Unable to print receipt. No paper.” This would be enough for someone using the machine to at least understand what’s going on.</p>
<p>But we could go even further. When you’re starting a transaction, the machine could preemptively warn the user that it’s not possible to proceed with it. At the very least, if the user is still allowed to carry on with the transaction, keep him informed about what will happen: “Unable to print receipt. Do you want to continue with the transaction?” This way, the user is able to make an informed decision.</p>
<p>Finally, how hard would it be to include a small blinking light, signaling that there is not paper?</p>
<h3>Bottom line</h3>
<p>Sometimes we don’t really think about the objects that surrounds us, and how they impact our lives every day. It takes a lot of time to get the interaction with these objects just right, and with a little effort, we can actually make them enjoyable. This is the purpose of <a href="http://en.wikipedia.org/wiki/User_experience" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/User_experience?referer=');">User Experience</a>.</p>
<p>Oh, and I did get charged 3 times, so I had to go to an ATM, get the last transactions in my accounts and take it back to the restaurant so they could refund me.</p>
<img src="http://feeds.feedburner.com/~r/e-pedro/~4/HT8BPWJwy6k" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.e-pedro.com/2009/02/no-clues-just-money/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.e-pedro.com/2009/02/no-clues-just-money/</feedburner:origLink></item>
		<item>
		<title>Lets get the ball rolling</title>
		<link>http://feedproxy.google.com/~r/e-pedro/~3/yrJyvc-V5Ng/</link>
		<comments>http://www.e-pedro.com/2009/02/lets-get-the-ball-rolling/#comments</comments>
		<pubDate>Tue, 03 Feb 2009 07:54:58 +0000</pubDate>
		<dc:creator>Pedro Sampaio</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sweux.com/blogs/psampaio/?p=5</guid>
		<description><![CDATA[Hi. My name is Pedro Sampaio and I work for FARO Technologies, in the SWE-UX team based in Oporto, Portugal. I&#8217;m just finishing setting up this blog and hopefully will start posting more regularly soon. Hope you all find my posts helpful and I look forward to some great interactions!]]></description>
			<content:encoded><![CDATA[<p>Hi. My name is Pedro Sampaio and I work for FARO Technologies, in the SWE-UX team based in Oporto, Portugal. I&#8217;m just finishing setting up this blog and hopefully will start posting more regularly soon.</p>
<p>Hope you all find my posts helpful and I look forward to some great interactions!</p>
<img src="http://feeds.feedburner.com/~r/e-pedro/~4/yrJyvc-V5Ng" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.e-pedro.com/2009/02/lets-get-the-ball-rolling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.e-pedro.com/2009/02/lets-get-the-ball-rolling/</feedburner:origLink></item>
	</channel>
</rss>

