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

<channel>
	<title>Dan Harman</title>
	<atom:link href="http://www.danharman.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.danharman.net</link>
	<description>Lock &#38; Code</description>
	<lastBuildDate>Fri, 17 May 2013 20:54:52 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>MongoDb Ninjitsu: Using ObjectId as a Timestamp</title>
		<link>http://www.danharman.net/2011/10/26/mongodb-ninjitsu-using-objectid-as-a-timestamp/</link>
		<comments>http://www.danharman.net/2011/10/26/mongodb-ninjitsu-using-objectid-as-a-timestamp/#comments</comments>
		<pubDate>Wed, 26 Oct 2011 18:05:34 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
				<category><![CDATA[Miscellaneous C#]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[Mongo]]></category>
		<category><![CDATA[mongodb]]></category>

		<guid isPermaLink="false">http://www.danharman.net/?p=337</guid>
		<description><![CDATA[Whilst reading around yesterday I stumbled upon this little gem of knowledge: Mongo&#8217;s ObjectIds contains a Utc timestamp with 1 second resolution. This means, that if we don&#8217;t need millisecond accuracy, we can drop all those &#8220;CreatedOn&#8221; fields from our schemas, and by doing so we win twice: Storage &#8211; no need to store a [...]]]></description>
				<content:encoded><![CDATA[<p>Whilst reading around yesterday I stumbled upon this little gem of knowledge:</p>
<p><em>Mongo&#8217;s ObjectIds contains a Utc timestamp with 1 second resolution.</em></p>
<p>This means, that if we don&#8217;t need millisecond accuracy, we can drop all those &#8220;CreatedOn&#8221; fields from our schemas, and by doing so we win twice:</p>
<ul>
<li><strong>Storage</strong> &#8211; no need to store a seperate time stamp field means less to store on disk and less for the server to shunt around.</li>
<li><strong>Free Index</strong> &#8211; assuming your ObjectId is your primary key, it already has an index on it by default, so not only are you saving the space of having to store a seperate time stamp, but it&#8217;s also indexed for free.</li>
</ul>
<p>To make it a little easier, I created an extension class to convert DateTimes to and from ObjectIds. This makes it insanely simple to query for objects created before/after a certain date. Here&#8217;s the code:</p>
<pre class="brush: csharp; title: ; notranslate">
/// Author	: Daniel Harman (http://www.danharman.net)
/// Date	: 26.Oct.2011
/// License : Public Domain with no warranty given. Please maintain author credit.
using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Bson;

namespace Mmphs.Utils.MongoDb
{
	public static class DateTimeExtensions
	{
		/// &lt;summary&gt;
		/// Converts a DateTime to an ObjectId.
		/// n.b. missing values that would ensure uniqueness. This is only intended for time comparisons.
		/// &lt;/summary&gt;
		/// &lt;param name=&quot;dateTime&quot;&gt;&lt;/param&gt;
		/// &lt;returns&gt;&lt;/returns&gt;
		public static ObjectId ToObjectId(this DateTime dateTime)
		{
			var timestamp = (int)(dateTime - BsonConstants.UnixEpoch).TotalSeconds;
			return new ObjectId(timestamp, 0, 0, 0);
		}

		/// &lt;summary&gt;
		/// Convert an ObjectId to a DateTime.
		/// &lt;/summary&gt;
		/// &lt;param name=&quot;id&quot;&gt;&lt;/param&gt;
		/// &lt;returns&gt;&lt;/returns&gt;
		public static DateTime ToDateTime(this ObjectId id)
		{
			return id.CreationTime;
		}

		static readonly int DATETIME_TRUNCATE_FACTOR = 10000;

		/// &lt;summary&gt;
		/// Truncate the accuracy of a datetime to the same resolution as a mongo db datetime.
		/// &lt;/summary&gt;
		/// &lt;param name=&quot;dateTime&quot;&gt;&lt;/param&gt;
		/// &lt;returns&gt;&lt;/returns&gt;
		public static DateTime MongoTruncate(this DateTime dateTime)
		{
			long ticks = dateTime.Ticks / DATETIME_TRUNCATE_FACTOR;
			return new DateTime(ticks * DATETIME_TRUNCATE_FACTOR, dateTime.Kind);
		}
	}
}
</pre>
<p>I&#8217;ve thrown in a little bonus there too &#8211; a method to truncate a DateTime in the same way MongoDb does when it persists one. This is handy for unit tests where you want to compare an object you&#8217;ve created and persisted and then loaded back up e.g. when testing a query brings back the right record.</p>
<p>Here is an example of using the ObjectId to get items after a certain date:</p>
<pre class="brush: csharp; title: ; notranslate">
		public IEnumerable&lt;Drop&gt; GetStreamActivities(ObjectId streamId, DateTime utcSince)
		{
			return _drops
				.AsQueryable()
				.Where(a =&gt; a.StreamId == streamId &amp;&amp; a.Id &gt;= utcSince.ToObjectId())
				.OrderBy(a =&gt; a.Id);
		}
</pre>
<p>n.b. I&#8217;m using FluentMongo, but you certainly don&#8217;t need to.</p>
<p>and here are the unit tests:</p>
<pre class="brush: csharp; title: ; notranslate">
/// Author	: Daniel Harman (http://www.danharman.net)
/// Date	: 26.Oct.2011
/// License : Public Domain with no warranty given. Please maintain author credit.

using System;
using System.Collections.Generic;
using System.Linq;
using MbUnit.Framework;
using MongoDB.Bson;

namespace Mmphs.Utils.MongoDb.Test.DateTimeExtensions
{
	[TestFixture]
	public class DateTimeExtensionsTest
	{
		[Test]
		public void Can_Convert_DateTime_To_ObjectId()
		{
			// Arrange
			DateTime dateTime = DateTime.UtcNow;

			// Act
			ObjectId result = dateTime.ToObjectId();

			// Assert
			Assert.AreApproximatelyEqual(dateTime, result.CreationTime, TimeSpan.FromSeconds(1));
		}

		[Test]
		public void Can_Convert_ObjectId_To_DateTime()
		{
			// Arrange
			ObjectId objectId = ObjectId.GenerateNewId();
			DateTime dateTime = DateTime.UtcNow;

			// Act
			var result = objectId.ToDateTime();

			// Assert
			Assert.AreApproximatelyEqual(dateTime, result, TimeSpan.FromSeconds(1));
		}
	}
}
</pre>
<pre class="brush: csharp; title: ; notranslate">
/// Author	: Daniel Harman (http://www.danharman.net)
/// Date	: 26.Oct.2011
/// License : Public Domain with no warranty given. Please maintain author credit.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MbUnit.Framework;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;

namespace Mmphs.Utils.MongoDb.Test.DateTimeExtensions
{
	[TestFixture]
	public class When_Truncating_DateTime
	{
		[Test]
		public void Should_Match_Mongo()
		{
			// Arrage
			DateTime dt = DateTime.UtcNow;
			var asJson = dt.ToJson();

			// Act
			var asTrunc = dt.MongoTruncate();
			
			// Assert
			var fromJson = BsonSerializer.Deserialize&lt;DateTime&gt;(asJson);
			Assert.AreEqual(fromJson, asTrunc);
		}
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.danharman.net/2011/10/26/mongodb-ninjitsu-using-objectid-as-a-timestamp/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>MongoDB and C# Dictionary Serialisation, Part 1 &#8211; The Problem</title>
		<link>http://www.danharman.net/2011/09/14/mongodb-and-c-dictionary-serialisation-part-1-the-problem/</link>
		<comments>http://www.danharman.net/2011/09/14/mongodb-and-c-dictionary-serialisation-part-1-the-problem/#comments</comments>
		<pubDate>Wed, 14 Sep 2011 21:15:01 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
				<category><![CDATA[Miscellaneous C#]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[Custom Serializer]]></category>
		<category><![CDATA[Dictionary]]></category>
		<category><![CDATA[Mongo]]></category>

		<guid isPermaLink="false">http://www.danharman.net/?p=306</guid>
		<description><![CDATA[I&#8217;m building a web site at the moment, and as consequence, have been doing a lot of work with MongoDB. One of the interesting things I&#8217;ve come across is the C# driver&#8217;s, and I don&#8217;t know if this applies to other languages, approach to serialising generic dictionaries. i.e. Dictionary&#60;TKey,TValue&#62;. The driver has two methods depending [...]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;m building a web site at the moment, and as consequence, have been doing a lot of work with MongoDB. One of the interesting things I&#8217;ve come across is the C# driver&#8217;s, and I don&#8217;t know if this applies to other languages, approach to serialising generic dictionaries. i.e. Dictionary&lt;TKey,TValue&gt;.</p>
<p>The driver has two methods depending on the type of the key. If TKey is an object then the serialiser will create a nested array e.g.:</p>
<pre class="brush: csharp; title: ; notranslate">
class Thread
{
 // Id of the Thread.
 ObjectId Id;

 // Dictionary&lt;MemberId, Message&gt;
 Dictionary&lt;ObjectId, string&gt; Posts;
}
</pre>
<p>serialises to:</p>
<pre class="brush: csharp; title: ; notranslate">
{ &quot;_id&quot; : ObjectId(&quot;4e519fe15fc9d4099c01733a&quot;),
	&quot;Posts&quot; : [
		[ ObjectId(&quot;4e3de6255fc9d40fd437a5ac&quot;), &quot;Is anyone there?&quot; ],
		[ ObjectId(&quot;4e3de6305fc9d40fd437a5ae&quot;), &quot;Nobody but us chickens.&quot;]
	]
}
</pre>
<p>Alternatively if, we store the member&#8217;s id as a string:</p>
<pre class="brush: csharp; title: ; notranslate">
class Thread
{
 // Id of the Thread.
 ObjectId Id;

 // Dictionary&lt;MemberName, Message&gt;
 Dictionary&lt;string, string&gt; Posts;
}
</pre>
<p>we get:</p>
<pre class="brush: csharp; title: ; notranslate">
{ &quot;_id&quot; : ObjectId(&quot;4e519fe15fc9d4099c01733a&quot;),
	&quot;Posts&quot; : {
		&quot;4e3de6255fc9d40fd437a5ac&quot; : &quot;Is anyone there?&quot;
		&quot;4e3de6305fc9d40fd437a5ae&quot; : &quot;Nobody but us chickens.&quot;
	}
}
</pre>
<p>This latter format is wonderfully compact and seems like a smart way of leveraging the map like properties of the json/bson collection type.</p>
<p>Unfortunately, I think there are some significant problems with both approaches, which I&#8217;ll outline below. If I&#8217;m wrong about these let me know as I&#8217;d gladly be corrected!</p>
<p><strong>Ability to search by the Dictionary&#8217;s Key</strong></p>
<p>With the nested dictionary, we can&#8217;t search for documents containing posts by a specific MemberId. This syntax, which one might think could do this:</p>
<pre class="brush: csharp; title: ; notranslate">
var q = Query(&quot;Posts.0&quot;, &quot;4e3de6255fc9d40fd437a5ac&quot;)
</pre>
<p>Will actually search for records where the first element in Posts equals <code>"4e3de6255fc9d40fd437a5ac"</code> &#8211; it&#8217;s not going to find any matches even if the TKey of the first element matches. This is because the first element is actually a nested array of two elements i.e.</p>
<pre class="brush: csharp; title: ; notranslate">
[ ObjectId(&quot;4e3de6255fc9d40fd437a5ac&quot;), &quot;Is anyone there?&quot; ]
</pre>
<p>So you can&#8217;t search by MemberId, you can only search if you know the complete contents of the dictionary entry, and only if you know its specific position in the dictionary. That&#8217;s not too useful when dealing with serialsed dictionaries!</p>
<div id='stb-container-8568' class='stb-container'><div id='stb-caption-box-8568' class='stb-info-caption_box stb_caption' >Info<div id="stb-tool-8568" class="stb-tool" style="float:right; padding:0px; margin:0px auto"><img id="stb-toolimg-8568" style="border: none; background-color: transparent; padding: 0px; margin: 0px auto;" src="http://www.danharman.net/wp-content/plugins/wp-special-textboxes/images/hide.png" title="Hide" /></div></div><div id='stb-body-box-8568' class='stb-info-body_box stb_body' ><br />
As a brief aside, there is an open ticket on Mongo&#8217;s Jira to add support for a syntax like this:</p>
<pre class="brush: csharp; title: ; notranslate">
var q = Query.EQ(&quot;Posts.$.0&quot;, &quot;4e3de6255fc9d40fd437a5ac&quot;)
</pre>
<p>This would be great as it would solve our problem. I&#8217;m not sure it&#8217;s on the cards to be implemented anytime soon though.<br />
</div></div>
<p>If instead, we now look at our example with the string key, we can search with the following:</p>
<pre class="brush: csharp; title: ; notranslate">
var q = Query.Exists(&quot;Posts.4e3de6255fc9d40fd437a5ac&quot;, true)
</pre>
<p>I don&#8217;t know about you, but I find it a little weird that the search value has become part of the key and we are having to use &#8216;Exists&#8217; rather than &#8216;EQ&#8217;. Still&#8230; at least we can search by our dictionary&#8217;s key with this schema.</p>
<p><strong>Ability to Index by the Dictionary&#8217;s Key</strong></p>
<p>We are stuffed here. We can&#8217;t create an index with the nested array because we can&#8217;t even index the fields with current mongo syntax. Nor can we create a dictionary of all the field names in a document. This means our searches for dictionary key&#8217;s or elements are going to be expensive&#8230;</p>
<p><strong>Ability to Atomically Update a Value in the Dictionary</strong></p>
<p>Working with a database like MongoDb, one of the most important tools in our arsenal is the ability to make atomic updates to documents without having to pull them back into memory. This side steps a lot of concurrency issues that are otherwise difficult to manage without native transactions and locking. With a simple document this is pretty easy. What about modifying values in our dictionaries?</p>
<p>Well, with the nested array, it is again a bit of a disaster. The only options is to load the whole document, edit in memory and Update. So long atomicity!</p>
<p>With the nested document, we are in better shape and can use the following:</p>
<pre class="brush: csharp; title: ; notranslate">
threadsCollection
        .FindAndModify(
		Query.Exists(&quot;Posts.4e3de6255fc9d40fd437a5ac&quot;, true),
                null,
                Update.Set(&quot;Posts.4e3de6255fc9d40fd437a5ac&quot;,
                       &quot;A new message replacing the old&quot;));
</pre>
<p><strong>Summary of Issues</strong></p>
<p>The nested array is not a well supported structure in mongo, and using it for dictionary persistence is very limiting. We lose the ability to search, index and update atomically.</p>
<p>The array of documents is more successful in that we can search and update atomically. We do however lose indexing, which is fairly catastrophic if we actually want to search and update across any reasonably sized collections.</p>
<p><strong>An Alternative</strong></p>
<p>Fortunately, there is an alternate approach which resolves all these problem. All we need to do is create a hybrid of the two approaches &#8211; an array, but this time, of specifically formatted documents with known fields for the key and value:</p>
<pre class="brush: csharp; title: ; notranslate">
{ &quot;_id&quot; : ObjectId(&quot;4e519fe15fc9d4099c01733a&quot;),
	&quot;Posts&quot; : [
		{ &quot;k&quot; : ObjectId(&quot;4e3de6255fc9d40fd437a5ac&quot;), &quot;v&quot; : &quot;Is anyone there?&quot; },
		{ &quot;k&quot; : ObjectId(&quot;4e3de6305fc9d40fd437a5ae&quot;), &quot;v&quot; : &quot;Nobody but us chickens.&quot; }
	]
}
</pre>
<p>By having well known fields we can now search by the key, the value, or if we want to store documents as the value, the fields in that document.</p>
<p>This search will find all the documents in the collection with a given key :</p>
<pre class="brush: csharp; title: ; notranslate">
var q = Query.EQ(&quot;Posts.K&quot;, &quot;4e3de6255fc9d40fd437a5ac&quot;)
</pre>
<p>To update the value:</p>
<pre class="brush: csharp; title: ; notranslate">
threadsCollection
	.Update(
		Query.EQ(&quot;Posts.K&quot;, &quot;4e3de6255fc9d40fd437a5ac&quot;),
		Update.Set(&quot;Posts.$.v&quot;, &quot;A new message replacing the old&quot;);
</pre>
<p>Its worth noting that if our TValue is a class containing further properties rather than a literal type, then the above syntax can be extended to index into it using the standard dot notation. e.g.</p>
<pre class="brush: csharp; title: ; notranslate">
threadsCollection
	.Update(
		Query.EQ(&quot;Posts.K&quot;, &quot;4e3de6255fc9d40fd437a5ac&quot;),
		Update.Set(&quot;Posts.$.v.Status&quot;, &quot;New Status&quot;);
</pre>
<p>And because we can directly index the key, or indeed any value, we can index them!</p>
<p>We can also do funky things like replicating the addToSet functionality with our dictionary. Imagine we have a second dictionary on our thread, this one indexed by member id, but containing the members name so that we can cache the user names of everyone who has posted in the thread:</p>
<pre class="brush: csharp; title: ; notranslate">
class Thread
{
 // Id of the Thread.
 ObjectId Id;

 // Dictionary&lt;MemberId, Message&gt;
 Dictionary&lt;ObjectId, string&gt; Posts;

 // Dictionary&lt;MemberId, Name&gt;
 Dictionary&lt;ObjectId, string&gt; NameLookup;

}
</pre>
<p>We don&#8217;t however want to have someone recorded in this lookup table style dictionary more than once, so addToSet is exactly the approach we need. To do this, we first have to create the element we would insert as a BsonDocument:</p>
<pre class="brush: csharp; title: ; notranslate">
class NameLookupEntry
{
	public ObjectId k { get; set; }
	public Name v { get; set}
}

var entry = new NameLookupEntry() { k = &quot;4e3de6255fc9d40fd437a5ac&quot;, v = &quot;Joe Blow&quot; };
</pre>
<p>In this instance we are searching for a specific thread by its Id, as we want to add the guy&#8217;s name to that one thread, and only if it isn&#8217;t already there:</p>
<pre class="brush: csharp; title: ; notranslate">
threadsCollection
	.Update(
		Query.AND(
			Query.EQ(&quot;Id&quot;, &quot;4e519fe15fc9d4099c01733a&quot;
			Query.NE(&quot;NameLookup.K&quot;, &quot;4e3de6255fc9d40fd437a5ac&quot;),
		Update.Set(&quot;NameLookup.$.v&quot;, entry.ToBsonDocument());
</pre>
<p>In part 2, I&#8217;ll show you the code to build a custom serialiser to support this alternate scheme.</p>
<p><em>Thanks to Robert Stam at 10gen for assistance and feedback on this topic.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.danharman.net/2011/09/14/mongodb-and-c-dictionary-serialisation-part-1-the-problem/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>DXGrid, Immediate Updates &amp; Nested Attached Behaviours</title>
		<link>http://www.danharman.net/2011/09/14/dxgrid-immediate-updates-nested-attached-behaviours/</link>
		<comments>http://www.danharman.net/2011/09/14/dxgrid-immediate-updates-nested-attached-behaviours/#comments</comments>
		<pubDate>Wed, 14 Sep 2011 20:32:49 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
				<category><![CDATA[DevExpress]]></category>
		<category><![CDATA[Miscellaneous C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Reactive]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Attached Behaviour]]></category>
		<category><![CDATA[Dev Express]]></category>
		<category><![CDATA[Reactive Extensions]]></category>
		<category><![CDATA[Reactive Rx]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.danharman.net/?p=296</guid>
		<description><![CDATA[With the Devexpress grid control, when you edit a row, it doesn&#8217;t update the view model until the row loses focus. I needed immediate update so that my view model would get notified when a checkbox in the grid was toggled as soon as it happened. So I wrote an attached behaviour to facilitate this [...]]]></description>
				<content:encoded><![CDATA[<p>With the Devexpress grid control, when you edit a row, it doesn&#8217;t update the view model until the row loses focus. I needed immediate update so that my view model would get notified when a checkbox in the grid was toggled as soon as it happened. So I wrote an attached behaviour to facilitate this without having to resort to code behind.</p>
<p>This example is also interesting as it shows how to maintain extra state on a control, using a second attached behaviour managed internally by the main one. In this case, this is necessary to manage the lifetime of the subscription to the controls events. I couldn&#8217;t find any info about this technique on the net, so not sure how well known it is.</p>
<p>The code is fairly well commented so should be self explanatory. You’ll also notice that the events are being converted to IObservable with Reactive extensions. I love the functional approach of reactive and the way that reactive returns an IDisposable makes the lifetime management really easy.</p>
<p>n.b. Since this class is dependent on Reactive Extensions, your references will need to look something like this:</p>
<p><a href="http://danharman.azurewebsites.net/wp-content/uploads/2011/09/image.png"><img style="background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://danharman.azurewebsites.net/wp-content/uploads/2011/09/image_thumb.png" width="236" height="244"></a></p>
<p>You can grab Reactive (Rx) from nuget.</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.Windows;
using DevExpress.Xpf.Grid;
using System.Reactive.Linq;
using System.Reactive;

namespace Utils.DevExpress
{
	/// &lt;summary&gt;
	/// Attached behaviour for Dev Express GridView's that forces the grid to immediately update the bound
	/// datasource row when values are changed in it. By default it will only update when the row loses
	/// focus.
	/// 
	/// Usage in xaml:
	/// 1. Add Reference
	///    xmlns:dxu=&quot;clr-namespace:Utils.DevExpress;assembly=Utils.DevExpress&quot;
	/// 
	/// 2. Attach to GridView
	///    {dxg:TableView ShowGroupPanel=&quot;False&quot;  MultiSelectMode=&quot;Row&quot;
	///                   dxu:DXGridViewUpdateBehaviour.ImmediateUpdate=&quot;True&quot;       
	///                   AllowBestFit=&quot;True&quot; AutoWidth=&quot;True&quot;/}
	///    {/dxg:GridControl.View}
	/// 
	/// Derived from DevExpress recommended work around which was based on code behind:
	///    http://www.devexpress.com/Support/Center/p/E2832.aspx
	/// 
	/// Author : Daniel Harman
	/// Date   : 07.09.2011
	/// &lt;/summary&gt;

	public class DXGridViewUpdateBehaviour : DependencyObject
	{

		#region Immediate Update Attached Property

		public static bool GetImmediateUpdate(DependencyObject obj)
		{
			return (bool)obj.GetValue(ImmediateUpdateProperty);
		}

		public static void SetImmediateUpdate(DependencyObject obj, bool value)
		{
			obj.SetValue(ImmediateUpdateProperty, value);
		}

		/// Immediate update is a boolean attached DP that when set to true, will ensure that grid row updates
		/// are immediately propagated to the view model, rather than only when the row loses focus.
		public static readonly DependencyProperty ImmediateUpdateProperty = DependencyProperty.RegisterAttached(
				&quot;ImmediateUpdate&quot;, typeof(bool), typeof(GridViewBase),
				new UIPropertyMetadata(false, OnImmediateUpdatePropertyChanged));

		#endregion

		#region Grid View Update Behaviour Subscription Attached Property

		public static DXGridViewUpdateBehaviourSubscription GetGridViewUpdateBehaviourSubscription(DependencyObject obj)
		{
			return (DXGridViewUpdateBehaviourSubscription)obj.GetValue(GridViewUpdateBehaviourProperty);
		}

		public static void SetGridViewUpdateBehaviourSubscription(
			DependencyObject obj, DXGridViewUpdateBehaviourSubscription value)
		{
			obj.SetValue(GridViewUpdateBehaviourProperty, value);
		}

		/// This property is used to store an instance of the subscription on the control. This instance
		/// contains the rxEventHandler IDisposable so that we can clean up when we want to change the binding
		/// etc.
		public static readonly DependencyProperty GridViewUpdateBehaviourProperty = DependencyProperty.RegisterAttached(
				 &quot;GridViewUpdateBehaviour&quot;, typeof(DXGridViewUpdateBehaviourSubscription), typeof(DXGridViewUpdateBehaviour),
				 new UIPropertyMetadata(null));

		#endregion

		/// &lt;summary&gt;
		/// Handle changes to ImmediateUpdate.
		/// &lt;/summary&gt;
		/// &lt;param name=&quot;d&quot;&gt;A child of GridViewBase&lt;/param&gt;
		/// &lt;param name=&quot;e&quot;&gt;true/false for value of attached DP.&lt;/param&gt;
		private static void OnImmediateUpdatePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var gridViewBase = (GridViewBase)d;
			var oldValue = (bool)e.OldValue;
			var newValue = (bool)e.NewValue;

			if (oldValue == newValue)
				return;

			// Remove old sub if it exists.
			var oldSub = GetGridViewUpdateBehaviourSubscription(d);

			if (oldSub != null)
				oldSub.Dispose();

			// If ImmediateUpdate==true then create new sub.
			if (newValue)
				SetGridViewUpdateBehaviourSubscription(d, new DXGridViewUpdateBehaviourSubscription(gridViewBase));
		}

		/// &lt;summary&gt;
		/// Nested class to manage the lifetime of the reactive event handler. This is attached the GridView
		/// as an attached dependency property.
		/// &lt;/summary&gt;
		public class DXGridViewUpdateBehaviourSubscription : IDisposable
		{
			IDisposable rxEventHandler;

			public DXGridViewUpdateBehaviourSubscription(GridViewBase gridViewBase)
			{
				// Create an rx observable of the events and subscribe handler to it.
				rxEventHandler = Observable
						 .FromEventPattern&lt;CellValueChangedEventHandler, CellValueChangedEventArgs&gt;(
								 h =&gt; gridViewBase.CellValueChanging += h,
								 h =&gt; gridViewBase.CellValueChanging -= h)
						 .Subscribe(OnCellValueChanging);
			}

			/// &lt;summary&gt;
			/// On notification that a cell value is changing, force the TableView to update the view model immediately.
			/// &lt;/summary&gt;
			/// &lt;param name=&quot;ep&quot;&gt;&lt;/param&gt;
			void OnCellValueChanging(EventPattern&lt;CellValueChangedEventArgs&gt; ep)
			{
				(ep.Sender as GridViewBase).PostEditor();
			}

			#region IDisposable Members

			public void Dispose()
			{
				rxEventHandler.Dispose();
			}

			#endregion
		}
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.danharman.net/2011/09/14/dxgrid-immediate-updates-nested-attached-behaviours/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Binding a DevExpress Grid Context Menu to a MVVM ViewModel Command</title>
		<link>http://www.danharman.net/2011/08/05/binding-a-devexpress-grid-context-menu-to-a-mvvm-viewmodel-command/</link>
		<comments>http://www.danharman.net/2011/08/05/binding-a-devexpress-grid-context-menu-to-a-mvvm-viewmodel-command/#comments</comments>
		<pubDate>Fri, 05 Aug 2011 16:36:42 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
				<category><![CDATA[DevExpress]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Grid]]></category>

		<guid isPermaLink="false">http://www.danharman.net/?p=271</guid>
		<description><![CDATA[One of the things I sometimes wrestle with, is keeping to MVVM when working with DevExpress controls. Today I was trying to bind the right click context menu on their grid control, to a command on my view model. I started off working from some of their example code which was event and code behind [...]]]></description>
				<content:encoded><![CDATA[<p>One of the things I sometimes wrestle with, is keeping to MVVM when working with DevExpress controls.</p>
<p>Today I was trying to bind the right click context menu on their grid control, to a command on my view model. I started off working from some of their example code which was event and code behind based. This lead me to the using the <a href="http://www.danharman.net/2011/08/05/binding-wpf-events-to-mvvm-viewmodel-commands/">EventToCommand pattern</a>, as didn&#8217;t want any code behind.</p>
<p>This is where the pain began! Firstly their BarButtonItem is derived from FrameworkContentElement, not FrameworkElement, which makes it incompatible with MVVM Light. I posted a question about this on <a href="http://stackoverflow.com/questions/6955785/how-to-attach-frameworkcontentelement-to-mvvm-light-eventtocommand/6957361#6957361">stackoveflow which was answered with a great workaround</a>. </p>
<p>However before I received that answer, I had already decided to just use the more vanilla System.Windows.Interactivity InvokeCommandAction which doesn&#8217;t have the limitation of only binding to FrameworkElements.</p>
<p>Again I ran into problems. It seems that the context menu&#8217;s from dev express are in their own visual tree, so I tried all sorts of bindings to try and get back to my ViewModel. None of which worked!</p>
<p>It was at this point that my colleague pointed out that, the menu items are actually buttons and have a command property. So all this wrestling with triggers was a complete waste of time &#8211; curses!</p>
<p>However, the binding to get back to the ViewModel is not at all obvious, as the DataContext on these popup menus is not what you might expect. Anyway it is possible, and the way to do it is as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
&lt;dxg:TableView.RowCellMenuCustomizations&gt;
    &lt;dxb:BarButtonItem Name=&quot;deleteRowItem&quot; Content=&quot;Delete&quot;
        Command=&quot;{Binding View.DataContext.DeleteCommand}&quot; /&gt;
&lt;/dxg:TableView.RowCellMenuCustomizations&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.danharman.net/2011/08/05/binding-a-devexpress-grid-context-menu-to-a-mvvm-viewmodel-command/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Binding WPF Events to MVVM ViewModel Commands</title>
		<link>http://www.danharman.net/2011/08/05/binding-wpf-events-to-mvvm-viewmodel-commands/</link>
		<comments>http://www.danharman.net/2011/08/05/binding-wpf-events-to-mvvm-viewmodel-commands/#comments</comments>
		<pubDate>Fri, 05 Aug 2011 16:25:29 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
				<category><![CDATA[Miscellaneous C#]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[mvvm wpf mvvmlight interactivity]]></category>

		<guid isPermaLink="false">http://www.danharman.net/?p=273</guid>
		<description><![CDATA[This article looks at binding event on WPF controls to commands in your MVVM view model. A lot of MVVM examples show you how to bind a command in a view to an ICommand in your view model. What they sometimes skirt over, is how you get events into the view model. Prism for example [...]]]></description>
				<content:encoded><![CDATA[<p><strong>This article looks at binding event on WPF controls to commands in your MVVM view model.</strong></p>
<p>A lot of MVVM examples show you how to bind a command in a view to an ICommand in your view model. What they sometimes skirt over, is how you get events into the view model. Prism for example recommends the use of an Event Aggregator.</p>
<p>However, there is an easier way! All we need is a class library that is part of Expression Blend. It&#8217;s called System.Windows.Interactivity and you can get hold of it from a variety of sources, but the one I recommend is the <a href="http://mvvmlight.codeplex.com/">MVVM Light library</a>.</p>
<p>This gives you the ability to create a trigger on an event and bind it to an ICommand on the view model.</p>
<pre class="brush: xml; title: References; notranslate">
xmlns:i=&quot;clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity&quot; 
</pre>
<pre class="brush: xml; title: Button Definition; notranslate">
&lt;Button&gt;
    &lt;i:Interaction.Triggers&gt;
        &lt;i:EventTrigger EventName=&quot;MouseEnter&quot; &gt;
            &lt;i:InvokeCommandAction Command=&quot;{Binding FooCommand}&quot; /&gt;
        &lt;/i:EventTrigger&gt;
    &lt;/i:Interaction.Triggers&gt;
&lt;/Button&gt;
</pre>
<p>Assuming the DataContext is your view model, then the above will map the &#8216;MouseEnter&#8217; event to &#8216;FooCommand&#8217; on the view model.</p>
<p>The only issue here, is that InvokeCommandAction doesn&#8217;t give you the event parameters.</p>
<p>I&#8217;ve already mentioned MVVM Light, and this library provides the a solution, by offering a different event to command behaviour that can optionally pass the parameters. Like this:</p>
<pre class="brush: xml; title: References; notranslate">
xmlns:i=&quot;clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity&quot; 
xmlns:cmd=&quot;clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4&quot;
</pre>
<pre class="brush: xml; title: Button Definition; notranslate">
&lt;Button&gt;
    &lt;i:Interaction.Triggers&gt;
        &lt;i:EventTrigger EventName=&quot;MouseEnter&quot; &gt;
             &lt;cmd:EventToCommand Command=&quot;{Binding FooCommand}&quot;
                 PassEventArgsToCommand=&quot;True&quot; /&gt;
        &lt;/i:EventTrigger&gt;
    &lt;/i:Interaction.Triggers&gt;
&lt;/Button&gt;
</pre>
<p>With this, you&#8217;ll find the MouseEventArgs in the Object passed into your command.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.danharman.net/2011/08/05/binding-wpf-events-to-mvvm-viewmodel-commands/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>SEO Slugification in Dotnet aka Unicode to Ascii aka Diacritic Stripping</title>
		<link>http://www.danharman.net/2011/07/18/seo-slugification-in-dotnet-aka-unicode-to-ascii-aka-diacritic-stripping/</link>
		<comments>http://www.danharman.net/2011/07/18/seo-slugification-in-dotnet-aka-unicode-to-ascii-aka-diacritic-stripping/#comments</comments>
		<pubDate>Mon, 18 Jul 2011 22:52:54 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
				<category><![CDATA[Asp.net MVC]]></category>
		<category><![CDATA[Miscellaneous C#]]></category>
		<category><![CDATA[ASP]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[diacritic]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[SEO]]></category>
		<category><![CDATA[slug]]></category>
		<category><![CDATA[slugification]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.danharman.net/?p=245</guid>
		<description><![CDATA[This article looks at SEO using url slugs, and how we can generate them in dotnet/asp. I&#8217;ve recently conducted quite a lot of research, looking for a class to create url slugs in C#. If you are not familiar with these, they are when sentences are converted to a url friendly format. Normally this involves [...]]]></description>
				<content:encoded><![CDATA[<p><strong>This article looks at SEO using url slugs, and how we can generate them in dotnet/asp.</strong></p>
<p>I&#8217;ve recently conducted quite a lot of research, looking for a class to create url slugs in C#. If you are not familiar with these, they are when sentences are converted to a url friendly format. Normally this involves converting spaces and punctuation to hyphens and removing accents from characters. e.g. &#8220;This is my resumé&#8221; becomes &#8220;this-is-my-resume&#8221;. </p>
<p>Slugification of urls to make them human readable, is considered good SEO strategy as it gets keywords into urls. Although how much weight engines put into it these days is a matter of debate as it has been abused by spammers. nonetheless I think humans are more likely to click on a human readable link if a search engine throws it up, so there is no downside.</p>
<p>Before digging into the implementation aspects, one thing worth mentioning, as it took me a while to realise, is that it&#8217;s not really worth trying to use the slug as the unique key to whatever resource you want to offer. Dealing with the problem of collisions where you have matching slugs is just not worth the pain. Especially if you want your slugs to contain something highly repeatable like names.</p>
<p>What you will see the experts do is include the id of the resource (e.g. a GUID) and the slug. You can see it on both Stack Overflow and Facebook:</p>
<blockquote><p>http://stackoverflow.com/questions/3769457/how-can-i-remove-accents-on-a-string</p>
<p>http://ms-my.facebook.com/people/Joe-Bloggs/12343243267683877</p>
</blockquote>
<p>For StackOverflow, the id is actually 3769457, and if you change the slug string it makes no odds to what you get back.</p>
<p>Facebook is exactly the same except they place the real id at the end instead of the middle. This seems a little smarter to me as google etc truncate very long URLs when they display them in search results, so by making sure the human readable part is at the front, you aren&#8217;t losing that whilst preserving a human meaningless id.</p>
<p>They also both do permanent redirects if you type in a random slug. This tackles the canonical problem of having the same content on multiple links if people mess up the slug, which is pure SEO poison if not tackled.</p>
<p>Right, to business &#8211; how do we do it? Well, the first part, punctuation removal and hyphenation, is trivial.</p>
<p>Removing accents however is rather more complex, and goes by many names including diacritic (accent) stripping and Unicode to ascii. My research took me to stack overflow where it became apparent that whilst there are libraries to help, C# coverage is very weak.</p>
<p>Looking at other language&#8217;s libraries, they tend to rely on lookup tables and regex. The tables are very difficult to make complete, and regex is quite an expensive operation.</p>
<p>There is also a more standards based way of doing this, which is known as Normalisation and is described in more detail on the Unicode website <a href="http://www.unicode.org/reports/tr15/tr15-34.html">here</a>. This describes the different forms of normalisation which I&#8217;m not going to go into here. What normalisation does, is split Unicode characters into the represented letter and a series of accents etc that follow (see the unicode link for more details).</p>
<p>Having got this string one then needs to remove the accent characters which should leave us with just the character and no accent. This is great in theory, unfortunately certain characters don&#8217;t map to a low Ascii character with normalise, so even with this approach one needs a lookup table for exceptions.</p>
<p>So the answer I&#8217;ve come to is based on two snippets which Jeff Atwood kindly shared on Stack Overflow. These are apparently the functions Stack Overflow uses for this very operation. You can find these <a href="http://stackoverflow.com/questions/25259/how-do-you-include-a-webpage-title-as-part-of-a-webpage-url/25486#25486">here</a> and <a href="http://meta.stackoverflow.com/questions/7435/non-us-ascii-characters-dropped-from-full-profile-url/7696#7696">here</a>. Using these you have the warm glow of knowing they are production tested on a high volume site and performance is solid &#8211; note the lack of regex!</p>
<p>I have however, made a few changes:</p>
<ul>
<li>The hyphens were appended in such a way that one could be added, and then need removing as it was the last character in the string. i.e. We never want &#8220;my-slug-&#8221;. This mean an extra string allocation. I&#8217;ve worked around this by delay-hyphening. If you compare my code to Jeff&#8217;s the logic for this is easy to follow.</li>
<li>His approach is purely lookup based and missed a lot of characters I found in examples whilst researching on stack overflow. To counter this, I first perform a normalisation pass, and then ignore any characters outside the acceptable ranges. This works most of the time&#8230;</li>
<li>&#8230;For when it doesn&#8217;t I&#8217;ve also had to add a lookup table. As mentioned above, some characters don&#8217;t map to a low ascii value when normalised. Rather than drop these I&#8217;ve got a manual list of exceptions that is doubtless full of holes, but better than nothing. The normalisation code was inspired by Jon Hanna&#8217;s great post <a href="http://stackoverflow.com/questions/3769457/how-can-i-remove-accents-on-a-string">here</a>.</li>
<li>The case conversion is now also optional.</li>
</ul>
<p>The upshot of all this, is that my version has better coverage than Jeff&#8217;s original and is a bit smarter with the hyphenation. I have a suspicion that the Microsoft implemented normalisation is likely to be slower than Jeff&#8217;s lookup table, so we are trading completeness for performance on that aspect. The hyphenation I would expect to be a bit faster, but not much as his extra string copy was only an edge case. </p>
<p>Anyway here&#8217;s the code:</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

	public static class Slug
	{
		public static string Create(bool toLower, params string[] values)
		{
			return Create(toLower, String.Join(&quot;-&quot;, values));
		}

		/// &lt;summary&gt;
		/// Creates a slug.
		/// Author: Daniel Harman, based on original code by Jeff Atwood
		/// References:
		/// http://www.unicode.org/reports/tr15/tr15-34.html
		/// http://meta.stackoverflow.com/questions/7435/non-us-ascii-characters-dropped-from-full-profile-url/7696#7696
		/// http://stackoverflow.com/questions/25259/how-do-you-include-a-webpage-title-as-part-of-a-webpage-url/25486#25486
		/// http://stackoverflow.com/questions/3769457/how-can-i-remove-accents-on-a-string
		/// &lt;/summary&gt;
		/// &lt;param name=&quot;toLower&quot;&gt;&lt;/param&gt;
		/// &lt;param name=&quot;normalised&quot;&gt;&lt;/param&gt;
		/// &lt;returns&gt;&lt;/returns&gt;
		public static string Create(bool toLower, string value)
		{
			if (value == null) return &quot;&quot;;

			var normalised = value.Normalize(NormalizationForm.FormKD);

			const int maxlen = 80;
			int len = normalised.Length;
			bool prevDash = false;
			var sb = new StringBuilder(len);
			char c;

			for (int i = 0; i &lt; len; i++)
			{
				c = normalised[i];
				if ((c &gt;= 'a' &amp;&amp; c &lt;= 'z') || (c &gt;= '0' &amp;&amp; c &lt;= '9'))
				{
					if (prevDash)
					{
						sb.Append('-');
						prevDash = false;
					}
					sb.Append(c);
				}
				else if (c &gt;= 'A' &amp;&amp; c &lt;= 'Z')
				{
					if (prevDash)
					{
						sb.Append('-');
						prevDash = false;
					}
					// tricky way to convert to lowercase
					if (toLower)
						sb.Append((char)(c | 32));
					else
						sb.Append(c);
				}
				else if (c == ' ' || c == ',' || c == '.' || c == '/' || c == '\' || c == '-' || c == '_' || c == '=')
				{
					if (!prevDash &amp;&amp; sb.Length &gt; 0)
					{
						prevDash = true;
					}
				}
				else
				{
					string swap = ConvertEdgeCases(c, toLower);

					if (swap != null)
					{
						if (prevDash)
						{
							sb.Append('-');
							prevDash = false;
						}
						sb.Append(swap);
					}
				}

				if (sb.Length == maxlen) break;
			}

			return sb.ToString();
		}

		static string ConvertEdgeCases(char c, bool toLower)
		{
			string swap = null;
			switch (c)
			{
				case 'ı':
					swap = &quot;i&quot;;
					break;
				case 'ł':
					swap = &quot;l&quot;;
					break;
				case 'Ł':
					swap = toLower ? &quot;l&quot; : &quot;L&quot;;
					break;
				case 'đ':
					swap = &quot;d&quot;;
					break;
				case 'ß':
					swap = &quot;ss&quot;;
					break;
				case 'ø':
					swap = &quot;o&quot;;
					break;
				case 'Þ':
					swap = &quot;th&quot;;
					break;
			}
			return swap;
		}
	}
</pre>
<p>and here are my mbunit tests:</p>
<pre class="brush: csharp; title: ; notranslate">
	[TestFixture]
	public class When_Creating_Slug
	{
		[Test]
		[Row(&quot;ṃ,ỹ,ṛ,è,ş,ư,ḿ,ĕ&quot;, &quot;m-y-r-e-s-u-m-e&quot;)]
		[Row(&quot;á-é-í-ó-ú&quot;, &quot;a-e-i-o-u&quot;)]
		[Row(&quot;à,å,á,â,ä,ã,å,ą&quot;, &quot;a-a-a-a-a-a-a-a&quot;)]
		[Row(&quot;è,é,ê,ë,ę&quot;, &quot;e-e-e-e-e&quot;)]
		[Row(&quot;ì,í,î,ï,ı&quot;, &quot;i-i-i-i-i&quot;)]
		[Row(&quot;ò,ó,ô,õ,ö,ø&quot;, &quot;o-o-o-o-o-o&quot;)]
		[Row(&quot;ù,ú,û,ü&quot;, &quot;u-u-u-u&quot;)]
		[Row(&quot;ç,ć,č&quot;, &quot;c-c-c&quot;)]
		[Row(&quot;ż,ź,ž&quot;, &quot;z-z-z&quot;)]
		[Row(&quot;ś,ş,š&quot;, &quot;s-s-s&quot;)]
		[Row(&quot;ñ,ń&quot;, &quot;n-n&quot;)]
		[Row(&quot;ý,Ÿ&quot;, &quot;y-Y&quot;)]
		[Row(&quot;ł,Ł&quot;, &quot;l-L&quot;)]
		[Row(&quot;đ&quot;, &quot;d&quot;)]
		[Row(&quot;ß&quot;, &quot;ss&quot;)]
		[Row(&quot;ğ&quot;, &quot;g&quot;)]
		[Row(&quot;Þ&quot;, &quot;th&quot;)]
		public void Should_Remove_Accents_Case_Invariant(string value, string expected)
		{
			var result = Slug.Create(false, value);
			
			Assert.AreEqual(expected, result);
		}

		[Test]
		[Row(&quot;ý,Ÿ&quot;, &quot;y-y&quot;)]
		[Row(&quot;ł,Ł&quot;, &quot;l-l&quot;)]
		public void Should_Remove_Accents_To_Lower(string value, string expected)
		{
			var result = Slug.Create(true, value);
			
			Assert.AreEqual(expected, result);
		}

		[Test]
		[Row(&quot;Slug Me &quot;, &quot;Slug-Me&quot;)]
		[Row(&quot;Slug Me,&quot;, &quot;Slug-Me&quot;)]
		[Row(&quot;Slug Me.&quot;, &quot;Slug-Me&quot;)]
		[Row(&quot;Slug Me/&quot;, &quot;Slug-Me&quot;)]
		[Row(&quot;Slug Me\&quot;, &quot;Slug-Me&quot;)]
		[Row(&quot;Slug Me-&quot;, &quot;Slug-Me&quot;)]
		[Row(&quot;Slug Me_&quot;, &quot;Slug-Me&quot;)]
		[Row(&quot;Slug Me=&quot;, &quot;Slug-Me&quot;)]
		[Row(&quot;Slug Me--&quot;, &quot;Slug-Me&quot;)]
		[Row(&quot;Slug Me---,&quot;, &quot;Slug-Me&quot;)]
		public void Should_Remove_Trailing_Punctuation(string value, string expected)
		{
			var result = Slug.Create(false, value);

			Assert.AreEqual(expected, result);
		}
	}
</pre>
<p>After all this, I&#8217;ve now realised I don&#8217;t really need this code where I thought I did. My use case was to convert people&#8217;s names into slugs for a name directory, but having done all this work, I had a look at how facebook does it (after all no harm copying the industry leaders). Well I wish I&#8217;d done this first, as it turns out, they just leave the accents in the names when they display them in a directory! Oh well, I&#8217;m pretty sure they will normalise for searching to maximise matches, and this code is sound for article type slugification rather than names.</p>
<p><em>With thanks to Tom Chantler for the spotting the bug handling large whitespace strings.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.danharman.net/2011/07/18/seo-slugification-in-dotnet-aka-unicode-to-ascii-aka-diacritic-stripping/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Storing Custom Data in Forms Authentication Tickets</title>
		<link>http://www.danharman.net/2011/07/07/storing-custom-data-in-forms-authentication-tickets/</link>
		<comments>http://www.danharman.net/2011/07/07/storing-custom-data-in-forms-authentication-tickets/#comments</comments>
		<pubDate>Thu, 07 Jul 2011 00:10:34 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
				<category><![CDATA[Asp.net MVC]]></category>
		<category><![CDATA[ASP]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[FormsAuthentication]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[membership]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.danharman.net/?p=218</guid>
		<description><![CDATA[This article looks at storing custom data in asp.net forms authentication tickets. I recently updated the article to make the custom model binder generic, and add the necessary registration code which was missing from the first draft. So you&#8217;ve decided to use FormsAuthentication, and perhaps enhanced it with your own custom providers. In your AccountController [...]]]></description>
				<content:encoded><![CDATA[<p><strong>This article looks at storing custom data in asp.net forms authentication tickets. I recently updated the article to make the custom model binder generic, and add the necessary registration code which was missing from the first draft.</strong></p>
<p>So you&#8217;ve decided to use FormsAuthentication, and perhaps enhanced it <a href="http://www.danharman.net/2011/06/23/asp-net-mvc-3-custom-membership-provider-with-repository-injection/">with your own custom providers</a>. In your AccountController Login method you probably have a call along these lines:</p>
<pre class="brush: csharp; title: ; notranslate">
FormsAuthentication.SetAuthCookie(account.Id.ToString(), model.RememberMe);
</pre>
<p>That all works great, but what if you need to store some extra data in the cookie. Perhaps the name you are passing into the AuthTicket isn&#8217;t actually the users name, but a GUID. Suddenly that built in ASP.Net login widget, in the top right of the page, doesn&#8217;t seem so great when it looks like this:</p>
<p><code>Hello 5D1D4743-9941-40B5-8931-6BC12617946C</code></p>
<p>What we need to do is store some extra data in that AuthTicket cookie right? That way we can keep the GUID as the authentication id, but still store things like the users first name in the cookie. Thus saving an expensive round trip to the db each time we render the widget.</p>
<p>Hmmm&#8230; whats this &#8216;UserData&#8217; property we see on the AuthTicket? Perfect!</p>
<p>Erk&#8230; It&#8217;s read only?!?!?!</p>
<p>At least that&#8217;s how my thought process went.</p>
<p>So we need to make an authentication ticket ourselves:</p>
<pre class="brush: csharp; title: ; notranslate">
var ticket = FormsAuthenticationTicket(int version, string name, DateTime issueDate,
	DateTime expiration, bool isPersistent, string userData, string cookiePath);
</pre>
<p>Unfortunately that&#8217;s quite a few more parameters than SetAuthCookie(&#8230;) required and they should be coming from the web.config rather than hard-coded.</p>
<p>On the plus side, there is access to the UserData!</p>
<p>To avoid losing the web.config driven settings, we can do a little trick and get FormsAuthentication to do the parsing for us. All we need to do is ask it for an AuthTicket and copy the settings from that into a new one we create.</p>
<p>To do this, a few steps are required. Firstly, after getting the ticket, we have to decrypt it, copy the data into a new ticket, and then make sure we encrypt that. Then we need to add it to the response.</p>
<p>Now before getting to the code, we should think about where it should live. It would seem logical to encapsulate this an extension method on FormsAuthentication, but being a static class we can&#8217;t. Instead we can attach it to HttpResponseBase which is not a bad home, especially as we have to add the cookie onto a response anyway. I&#8217;d recommend creating the following class in an &#8216;Infrastructure&#8217; folder in your project:</p>
<pre class="brush: csharp; title: ; notranslate">
	public static class HttpResponseBaseExtensions
	{
		public static int SetAuthCookie&lt;T&gt;(this HttpResponseBase responseBase, string name, bool rememberMe, T userData)
		{
			/// In order to pickup the settings from config, we create a default cookie and use its values to create a 
			/// new one.
			var cookie = FormsAuthentication.GetAuthCookie(name, rememberMe);
			var ticket = FormsAuthentication.Decrypt(cookie.Value);
			
			var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration,
				ticket.IsPersistent, userData.ToJson(), ticket.CookiePath);
			var encTicket = FormsAuthentication.Encrypt(newTicket);

			/// Use existing cookie. Could create new one but would have to copy settings over...
			cookie.Value = encTicket;

			responseBase.Cookies.Add(cookie);

			return encTicket.Length;
		}
	}
</pre>
<p>There are a couple of things of note here, firstly we are accepting a generic type for the UserData, and secondly we are encoding it to Json!</p>
<p>Why? well lets think about the UserData field. Being on a cookie, this can only contain string data. Now we could do our own custom serialisation into this string, but my preference is to use JSON as it&#8217;s designed for the task. In this instance I&#8217;m using the serialiser from MongoDb as I happen to be using that in my project, but any Json serialiser will do. You might like to try the ServiceStack implementation for example.</p>
<p>I&#8217;m also returning the size of the cookie &#8211; cookies should never be longer than 4000 bytes as some browsers will just discard them. Its worth keeping an eye on this as it&#8217;s not just the size of your UserData but the other mandatory parts of the cookie too.</p>
<p>So let&#8217;s get this wired into our AccountController.</p>
<p>First we define a UserData class with a FirstName in it:</p>
<pre class="brush: csharp; title: ; notranslate">
	public class UserData
	{
		public string FirstName { get; set; }

		public UserData()
		{
			FirstName = &quot;Unknown&quot;;
		}
	}
</pre>
<p>Now here&#8217;s an example Login Action. There are some extras in here around validation, but you can use whatever approach here that fits your project.</p>
<pre class="brush: csharp; title: ; notranslate">
[HttpPost]
		public ActionResult LogIn(AccountLoginVM model, string returnUrl)
		{
			try
			{
				if (ModelState.IsValid)
				{
					// Some code to validate and check authentication
					if (!Membership.ValidateUser(model.Email, model.Password))
						throw new RulesException(&quot;Incorrect username or password&quot;);

					Account account = _accounts.GetByEmail(model.Email);

					UserData userData = new UserData
					{
						FirstName = account.FirstName
					};

					Response.SetAuthCookie(account.Id.ToString(),
						model.RememberMe, userData);
				
					if (Url.IsLocalUrl(returnUrl))
					{
						return Redirect(returnUrl);
					}
					else
					{
						return RedirectToAction(&quot;Index&quot;, &quot;Home&quot;);
					}
				}
			}
			catch (RulesException ex)
			{
				ex.CopyTo(ModelState);
			}

			model.Password = &quot;&quot;;
			return View(model);
		}
</pre>
<p>That&#8217;s it. We&#8217;ve now got a cookie with our extra UserData in it.</p>
<p>Hang on&#8230; what about fixing that login widget in the top right?</p>
<p>One elegant way to crack this is to create a custom model binder, then if we swap the example widget from being a partial view to a partial action, all we need to do is demand a UserData object as an input param and the magic of binding will save us.</p>
<p>So, the custom model binder, again leveraging the MongoDb Json deserialiser:</p>
<pre class="brush: csharp; title: ; notranslate">
	/// &lt;summary&gt;
	/// Binder to pull the UserData out for any actions that may want it.
	/// &lt;/summary&gt;
	public class UserDataModelBinder&lt;T&gt; : IModelBinder
	{
		public object BindModel(ControllerContext controllerContext,
			ModelBindingContext bindingContext)
		{
			if (bindingContext.Model != null)
				throw new InvalidOperationException(&quot;Cannot update instances&quot;);
			if (controllerContext.RequestContext.HttpContext.Request.IsAuthenticated)
			{
				var cookie = controllerContext
					.RequestContext
					.HttpContext
					.Request
					.Cookies[FormsAuthentication.FormsCookieName];

				if (null == cookie)
					return null;

				var decrypted = FormsAuthentication.Decrypt(cookie.Value);

				if (!string.IsNullOrEmpty(decrypted.UserData))
					return BsonSerializer.Deserialize&lt;T&gt;(decrypted.UserData);
			}
			return null;
		}
	}
</pre>
<p>This is a generic so you can use whatever class suits to store the userdata. This then needs to be registered in Application_Start() in &#8216;Global.asax.cs&#8217; :</p>
<pre class="brush: csharp; title: ; notranslate">
ModelBinders.Binders.Add(typeof(UserData), new UserDataModelBinder&lt;UserData&gt;());
</pre>
<p>Now our login widget action, which passes a UserData object into our view (wrapped in a view model as we may not always want to pass all the UserData into the view).</p>
<pre class="brush: csharp; title: Action; notranslate">
		public ActionResult LoginWidget(UserData userData)
		{
			AccountLoginWidgetVM model = new AccountLoginWidgetVM();
			if (null != userData)
				model.UserData = userData;

			return PartialView(userData);
		}
</pre>
<pre class="brush: csharp; title: View; notranslate">
@model TestProj.Web.Models.AccountLoginWidgetVM
         
@if(Request.IsAuthenticated) {
    &lt;text&gt;Welcome &lt;b&gt;@Model.UserData.FirstName&lt;/b&gt;!
    [ @Html.ActionLink(&quot;Logout&quot;, &quot;Logout&quot;, &quot;Account&quot;) ]&lt;/text&gt;
}
else {
...
}
</pre>
<p>We&#8217;ve covered quite a broad range of topics here, but hopefully its clear and of use. If you need any clarification leave a comment.</p>
<p>Next time&#8230; a change of tack. I&#8217;m going to look at how to get some performance out of a devexpress WPF grid.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.danharman.net/2011/07/07/storing-custom-data-in-forms-authentication-tickets/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Encrypting (Hashing) Passwords for your Website</title>
		<link>http://www.danharman.net/2011/06/25/encrypting-hashing-passwords-for-your-website/</link>
		<comments>http://www.danharman.net/2011/06/25/encrypting-hashing-passwords-for-your-website/#comments</comments>
		<pubDate>Sat, 25 Jun 2011 02:18:25 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[NET]]></category>
		<category><![CDATA[SHA]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.danharman.net/?p=207</guid>
		<description><![CDATA[In my previous blog entry which explains how to implement a custom MembershipProvider on an ASP.Net MVC web site, I mentioned the BCrypt library in passing. Today I&#8217;d like to dig into the library a little more and show you how and why you should consider using it. Before we get into that though, what [...]]]></description>
				<content:encoded><![CDATA[<p>In my <a href="http://www.danharman.net/2011/06/23/asp-net-mvc-3-custom-membership-provider-with-repository-injection/">previous blog entry</a> which explains how to implement a custom MembershipProvider on an ASP.Net MVC web site, I mentioned the BCrypt library in passing. Today I&#8217;d like to dig into the library a little more and show you how and why you should consider using it.</p>
<p>Before we get into that though, what is what is &#8216;hashing&#8217; and how is it different to &#8216;encryption&#8217;?</p>
<p>Encryption is part of a two way process in which data is encoded, but must be decryptable afterwards. For password storage, this decryption step is unnecessary and is actually a security vulnerability if someone gets hold of your keys.</p>
<p>In contrast, hashing is a one way transformation that is very hard to reverse. So to store passwords, a site would simply hash them before saving them to a database. Then when a user logs in, the password they supply is also hashed and compared to the hashed value in the database. If they typed in the same password the hashes will match and the authentication passes.</p>
<p>The advantage of this, is that the web site doesn&#8217;t need to decrypt a password at any point. All it ever does is hash them which is great for security.</p>
<p>There are various hashing algorithms out there, and many of them are wonderfully optimised and very fast. A typical example is SHA. An optimal hasher sounds great doesn&#8217;t it?</p>
<p>&#8230; well it isn&#8217;t. In fact it&#8217;s a weakness with the power of modern cpus and cloud computing resources. It means that its very possible and remarkably cheap to brute force SHA with a dictionary attack, simply because it is so fast.</p>
<p>This is where BCrypt comes in. It is intentionally slow, so should someone try to brute force it, its simply not viable. Whereas a hacker can generate 100s of millions of SHA hashes a second, they can&#8217;t with BCrypt, and as technology marches on, you can just increase the work factor on BCrypt to keep ahead of processors.</p>
<p>There are a few BCrypt.Net implementations floating around, and the one I&#8217;ve used I pulled down with nuget. To use it is as simple as:</p>
<pre class="brush: csharp; title: Hash; notranslate">
private static readonly int BCRYPT_WORK_FACTOR = 10;
string hashedPassword = BCrypt.Net.BCrypt.HashPassword(account.HashedPassword, BCRYPT_WORK_FACTOR);
</pre>
<pre class="brush: csharp; title: Validate; notranslate">
bool matched = BCrypt.Net.BCrypt.Verify(password, match.HashedPassword))
</pre>
<p>Every increment in work factor doubles the type the hash takes. Some of the .net implemtations struggle to get past 31 due to a bug, but you shouldn&#8217;t need a value anything like that high for a few years at least!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.danharman.net/2011/06/25/encrypting-hashing-passwords-for-your-website/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC 3 Custom Membership Provider with Repository Injection</title>
		<link>http://www.danharman.net/2011/06/23/asp-net-mvc-3-custom-membership-provider-with-repository-injection/</link>
		<comments>http://www.danharman.net/2011/06/23/asp-net-mvc-3-custom-membership-provider-with-repository-injection/#comments</comments>
		<pubDate>Thu, 23 Jun 2011 23:37:52 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
				<category><![CDATA[Asp.net MVC]]></category>
		<category><![CDATA[ASP]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[membership]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[Ninject]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.danharman.net/?p=103</guid>
		<description><![CDATA[In most serious ASP.NET MVC, or even legacy ASP.Net web sites, you are unlikely to want to use the default membership provider of ASP.Net. Its dependency on SQLServer and unhealthy predilection for littering databases with hundreds tables, just to support features you don&#8217;t care about, make it distinctly unattractive. What we really want is to [...]]]></description>
				<content:encoded><![CDATA[<p>In most serious ASP.NET MVC, or even legacy ASP.Net web sites, you are unlikely to want to use the default membership provider of ASP.Net. Its dependency on SQLServer and unhealthy predilection for littering databases with hundreds tables, just to support features you don&#8217;t care about, make it distinctly unattractive.</p>
<p>What we really want is to integrate our web site&#8217;s security with the project&#8217;s schema and bind directly to a table or repository encapsulating the users model for the site. The way to do this is through the implementation of a custom MembershipProvider.</p>
<p>This may seem a little daunting, but in practise is fairly simple. In fact, all we need do is override a pair of methods, on a couple of abstract classes, and all authentication and role checking will be routed to our code. Even better, by leveraging the well-tested and robust ASP.NET security facilities, we can still utilise the convenience and security of ASP.Net&#8217;s attribute based security to protect your controllers and controller methods. If you aren&#8217;t familiar with these, it&#8217;s as simple as attaching an Authorise tag, and optionally specifying a role the user must have to gain access e.g.</p>
<pre class="brush: csharp; title: ; notranslate">
public class MemberController : Controller
{
	IAccountRepository repo;

	public MemberController(IAccountRepository accountRepository)
	{
		repo = accountRepository;
	}

	[Authorize]
	public ActionResult Index()
	{
...
	}

	[Authorize(Roles = &quot;Admin&quot;)]
	public ActionResult Delete(int accountId)
	{
...
	}
}
</pre>
<p>Just being authorised means the user has been authenticated i.e. logged in. The role is supplementary to this and allows you finer grained access control. Easy huh?</p>
<p>So, firstly authentication. To take control of this, we have to create a class derived from the abstract class MembershipProvider.</p>
<p>Unfortunately, being a hangover from old-school ASP.net, wiring this in is a little more clumsy than one might expect. It predates the pluggable design pattern applied throughout the MVC platform. The upshot being, that if you want to use the repository pattern with it, you can&#8217;t pass a repository into the constructor as ASP.Net instantiates the class for you, and only knows how to do this through a default constructor.</p>
<p>One way to work around this is to make your repository a property on the class and update it after the framework has constructed it. In this example I&#8217;m going to use ninject as my DI framework, but you could use a different one, or in fact just set the property without using DI at all.</p>
<p>First lets start with an example membership provider. I&#8217;ve only bothered to override ValidateUser() as the other methods aren&#8217;t required to leverage ASP.NET&#8217;s integrated security features.</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using Ninject;

namespace MyProj.Web.Infrastructure
{
	public class AccountMembershipProvider : MembershipProvider
	{
		[Inject]
		public IAccountRepository AccountRepository { get; set; }

		public override string ApplicationName
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

... lots of unimplemented overrides...

		public override void UpdateUser(MembershipUser user)
		{
			throw new NotImplementedException();
		}

		public override bool ValidateUser(string username, string password)
		{
			return AccountRepository.IsValidLogin(username, password);
		}
	}
}
</pre>
<p>You&#8217;ll notice there is an AccountRepository being used here to validate the user login. This is where your custom authorisation logic goes &#8211; as such I&#8217;m not going to provide an implementation here as it will depend on the specifics of your site.</p>
<p>Next, we need to ensure that the AccountRepository is injected into our MembershipProvider, and the place to do this is Application_Start() in Gloabl.asax.</p>
<pre class="brush: csharp; title: ; notranslate">
	internal class MyNinjectModules : NinjectModule
	{
		public override void Load()
		{
			Bind&lt;IAccountRepository&gt;()
				.To&lt;AccountRepository&gt;();
		}
	}

	public class MvcApplication : System.Web.HttpApplication
	{
		private IKernel _kernel = new StandardKernel(new MyNinjectModules());

...code deleted....

		protected void Application_Start()
		{
			AreaRegistration.RegisterAllAreas();

			RegisterGlobalFilters(GlobalFilters.Filters);
			RegisterRoutes(RouteTable.Routes);

			// Inject account repository into our custom membership provider.
			_kernel.Inject(Membership.Provider);
		}
	}
</pre>
<p>You&#8217;ll notice that I&#8217;m grabbing the framework instantiated instance of our membership provider, and using ninject to set the repository property on our custom membership provider.</p>
<p>I&#8217;m also setting up a ninject controller factory which is a great class when you want to inject repositories into your controller&#8217;s constructors. This is based on code found in one of the best programming books I&#8217;ve ever read <a href="http://blog.stevensanderson.com/2010/06/11/pro-aspnet-mvc-2-framework/">Pro ASP.NET MVC 2 Framework by Steven Sanderson</a>. This book covers so much more than ASP.NET MVC, it teaches you how to design and build applications for testability, and is the most digestable explanation of modern test driven design I&#8217;ve ever come across. It&#8217;s worth a read even if you aren&#8217;t an MVC programmer! n.b. I believe a revised MVC3 edition is to be released shortly.</p>
<pre class="brush: csharp; title: ; notranslate">
public class NinjectControllerFactory : DefaultControllerFactory
	{
		private IKernel _kernel;

		public NinjectControllerFactory(IKernel kernel)
		{
			_kernel = kernel;
		}

		protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
		{
			if (controllerType == null)
				return null;
		 
			return (IController)_kernel.Get(controllerType);
		}
	}
</pre>
<p>Now&#8230; what if we want to create a custom role provider too? Well that&#8217;s easy. Here is an exampe RoleProvider:</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using Ninject;

namespace MyProj.Web.Infrastructure
{
	public class AccountRoleProvider : RoleProvider
	{
		[Inject]
		public IAccountRepository AccountRepository { get; set; }

		public override void AddUsersToRoles(string[] usernames, string[] roleNames)
		{
			throw new NotImplementedException();
		}

... lots of unimplemented overrides...

		public override string[] GetRolesForUser(string id)
		{
			return AccountRepository.GetRoles(id);
		}

... lots of unimplemented overrides...

		public override bool RoleExists(string roleName)
		{
			throw new NotImplementedException();
		}
	}
}
</pre>
<p>Again, you really don&#8217;t need to override much of the RoleProvider abstract class, simply implementing GetRolesForUser() and ensuring it returns a string array of the given users roles will suffice.</p>
<p>To inject the membership provider juat change the previous code version of Application_Start() to: </p>
<pre class="brush: csharp; title: ; notranslate">
	public class MvcApplication : System.Web.HttpApplication
	{
		private IKernel _kernel = new StandardKernel(new MyNinjectModules());

...code deleted....

		protected void Application_Start()
		{
			AreaRegistration.RegisterAllAreas();

			RegisterGlobalFilters(GlobalFilters.Filters);
			RegisterRoutes(RouteTable.Routes);

			// Inject account repository into our custom membership &amp; role providers.
			_kernel.Inject(Membership.Provider);
			_kernel.Inject(Roles.Provider);
		}
	}
</pre>
<p>Finally we need to register our providers in web.config:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;configuration&gt;
...
  &lt;system.web&gt;
...
    &lt;membership defaultProvider=&quot;AccountMembershipProvider&quot;&gt;
      &lt;providers&gt;
        &lt;clear/&gt;
        &lt;add name=&quot;AccountMembershipProvider&quot;
             type=&quot;MyProj.Web.Infrastructure.AccountMembershipProvider&quot; /&gt;
      &lt;/providers&gt;
    &lt;/membership&gt;

    &lt;roleManager enabled=&quot;true&quot; defaultProvider=&quot;AccountRoleProvider&quot;&gt;
      &lt;providers&gt;
        &lt;clear/&gt;
        &lt;add name=&quot;AccountRoleProvider&quot;
             type=&quot;MyProj.Web.Infrastructure.AccountRoleProvider&quot; /&gt;
      &lt;/providers&gt;
    &lt;/roleManager&gt;
...
  &lt;/system.web&gt;
...  
&lt;/configuration&gt;
</pre>
<p>It really us as simple as that!</p>
<p>One other note, if you are implementing your own password storage, make sure you hash them! (and I recommend you look at <a href="http://www.danharman.net/2011/06/25/encrypting-hashing-passwords-for-your-website/">bcrypt</a> for that).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.danharman.net/2011/06/23/asp-net-mvc-3-custom-membership-provider-with-repository-injection/feed/</wfw:commentRss>
		<slash:comments>65</slash:comments>
		</item>
		<item>
		<title>ReactiveUI Property Name to Field Mapping Convention Override</title>
		<link>http://www.danharman.net/2011/06/23/reactiveui-property-name-to-field-mapping-convention-override/</link>
		<comments>http://www.danharman.net/2011/06/23/reactiveui-property-name-to-field-mapping-convention-override/#comments</comments>
		<pubDate>Thu, 23 Jun 2011 22:18:48 +0000</pubDate>
		<dc:creator>Dan</dc:creator>
				<category><![CDATA[ReactiveUI]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[reactiveui]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.danharman.net/?p=117</guid>
		<description><![CDATA[In a previous post I described how you can use the ReactiveUI framework to bind properties to both INotifyPropertyChanged and make them Observable to Reactive Extensions (Rx). The default binding behaviour of the RaiseAndSetIfChanged helper is to assume that a property named &#8220;MyProperty&#8221; has a backing field called &#8220;_MyProperty&#8221;. This is not a common convention, [...]]]></description>
				<content:encoded><![CDATA[<p>In a <a href="http://www.danharman.net/2011/06/13/using-reactiveui-to-integrate-inotifypropertychanged-iobservable/">previous post</a> I described how you can use the <a href="http://www.reactiveui.net/">ReactiveUI</a> framework to bind properties to both INotifyPropertyChanged and make them Observable to Reactive Extensions (Rx).</p>
<p>The default binding behaviour of the RaiseAndSetIfChanged helper is to assume that a property named &#8220;MyProperty&#8221; has a backing field called &#8220;_MyProperty&#8221;. This is not a common convention, and whilst you can explicitly override this behaviour in RaiseAndSetIfChanged, it&#8217;s extra work.</p>
<p>Fortunately, the framework offers a way of modifying the default mapping behaviour by binding a different function to RxApp.GetFieldNameForPropertyNameFunc.</p>
<p>Here are a couple of example functions that implement alternative behaviours. The first of which maps to <code>_propertyName</code> and the latter, simply to<code>propertyName</code>.</p>
<pre class="brush: csharp; title: ; notranslate">
                /// Maps property name MyProperty to field name _myProperty.
                Func&lt;string, string&gt; UnderscoreFirstToLowerBehaviour = x =&gt;
                {
                        char[] arr = x.ToCharArray();
                        arr[0] = char.ToLower(arr[0]);
                        return '_' + new String(arr);
                };

                /// Maps property name MyProperty to field name myProperty.
                Func&lt;string, string&gt; FirstToLowerBehaviour = x =&gt;
                {
                        char[] arr = x.ToCharArray();
                        arr[0] = char.ToLower(arr[0]);
                        return new String(arr);
                };
</pre>
<p>To use one of these behaviours, all you need do is call the following once during app startup:</p>
<pre class="brush: csharp; title: ; notranslate">
RxApp.GetFieldNameForPropertyNameFunc = underscoreFirstToLowerBehaviour;
</pre>
<p>Given this is executed on each notification, I guess the second coding style is more optimal!</p>
<p>p.s. I&#8217;m not sure these are the fastest implementations of these conversions, and I&#8217;m not going to benchmark, however I did base the code on <a href="http://www.dotnetperls.com/uppercase-first-letter">http://www.dotnetperls.com/uppercase-first-letter</a> who did do some benchmarking on similar code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.danharman.net/2011/06/23/reactiveui-property-name-to-field-mapping-convention-override/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
