<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" gd:etag="W/&quot;AkcMSHY_fSp7ImA9WhRUEkk.&quot;"><id>tag:blogger.com,1999:blog-36201586</id><updated>2012-01-22T16:01:29.845Z</updated><category term="VBScript" /><category term="Rockbox" /><category term="Vista" /><category term="LINQPad" /><category term="design patterns" /><category term="MVC" /><category term="DLNA" /><category term="Amazon" /><category term="WSC" /><category term="SQL Server" /><category term="MSXML" /><category term="digital home" /><category term="Windows" /><category term="Apple" /><category term="Azure" /><category term="ASP.NET" /><category term="WOW64" /><category term="OEM Software" /><category term="Visual Web Developer" /><category term="FLAC" /><category term="Mapstraction" /><category term="iPod" /><category term="Exact Audio Copy" /><category term="DDD" /><category term="JScript" /><category term="x64" /><category term="digital media" /><category term="music download" /><category term="ADO" /><category term="ripping" /><category term="jQuery" /><category term="64-bit" /><category term="XSL" /><category term="CSS" /><category term="PMP" /><category term="security" /><category term="Hack Day" /><category term="Music" /><category term="MP3" /><category term="streaming" /><category term="ASP" /><category term="XML" /><category term="OO" /><category term="WSH" /><category term="Web 2.0" /><category term="ADO.NET" /><category term="C#" /><category term="iPhone" /><category term="XPath" /><category term="NHibernate" /><category term="JavaScript" /><category term=".NET" /><category term="Silverlight" /><title>Derek says:</title><subtitle type="html">Real-world technobabble</subtitle><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://blog.dezfowler.com/" /><link rel="next" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default?start-index=26&amp;max-results=25&amp;redirect=false&amp;v=2" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>73</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/DerekSays" /><feedburner:info uri="dereksays" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry gd:etag="W/&quot;A0QMRnwyeip7ImA9WhdWGEs.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-3046806922049828590</id><published>2011-09-13T00:14:00.002+01:00</published><updated>2011-09-13T00:16:27.292+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-09-13T00:16:27.292+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".NET" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>Fun with enum</title><content type="html">&lt;p&gt;If you’ve done any vaguely serious programming with a pre-4 version of the .NET Framework then chances are you’ve had to write an Enum.TryParse() method. You probably wrote something like this:&lt;/p&gt;  &lt;pre&gt;&lt;code class="c#"&gt;public static bool TryParse&amp;lt;TEnum&amp;gt;(string value, out TEnum enumValue)
{
 Type enumType = typeof(TEnum);
 if (!enumType.IsEnum) throw new ArgumentException(&amp;quot;Type is not an enum.&amp;quot;);
 
 enumValue = default(TEnum);
 
 if (Enum.IsDefined(enumType, value))
 {
  enumValue = (TEnum)Enum.Parse(enumType, value);
  return true;
 }
 
 return false;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Everything went fine until someone decided to pass in a string representing a value of the underlying type such as “0” at which point Enum.IsDefined() said no even though your enum looked like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;public enum MyEnum
{
 Zero = 0, One, Two, Three
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Enum.Parse() will accept “0” just fine but IsDefined() requires the value be of the correct underlying type so in this case you’d need 0 as an integer for it to return true. Doesn't that mean I now need to work out the underlying type and then do the appropriate Parse() method using reflection? Oh dear, looks like our nice generic solution may get rather complicated!&lt;/p&gt;

&lt;p&gt;Fear not. Because we know our input type is a string and there are a very limited number of underlying types we can have there’s a handy framework method we can use to sort this out – Convert.ChangeType().&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;public static bool IsUnderlyingDefined(Type enumType, string value)
{
 if (!enumType.IsEnum) throw new ArgumentException(&amp;quot;Type is not an enum.&amp;quot;);
 
 Type underlying = Enum.GetUnderlyingType(enumType);
 
 var val = Convert.ChangeType(value, underlying, CultureInfo.InvariantCulture);
  
 return Enum.IsDefined(enumType, val);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;ChangeType() is effectively selecting the correct Parse method for us and calling it, passing in our string and returning a nice strongly typed underlying value which we can pass into Enum.IsDefined(). So our TryParse now looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;public static bool TryParse&amp;lt;TEnum&amp;gt;(string value, out TEnum enumValue)
{
 Type enumType = typeof(TEnum);
 if (!enumType.IsEnum) throw new ArgumentException(&amp;quot;Type is not an enum.&amp;quot;);
 
 enumValue = default(TEnum);
 
 if (Enum.IsDefined(enumType, value) || IsUnderlyingDefined(enumType, value))
 {
  enumValue = (TEnum)Enum.Parse(enumType, value);
  return true;
 }
 
 return false;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This exercise is somewhat contrived especially now Enum.TryParse is part of .NET 4.0 but the synergy of ChangeType and IsDefined is quite nice and a technique worth pointing out nonetheless.&lt;/p&gt;

&lt;h4&gt;Links&lt;/h4&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/ms130977.aspx"&gt;Convert.ChangeType() on MSDN&lt;/a&gt; &lt;/li&gt;

  &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.enum.isdefined.aspx"&gt;Enum.IsDefined() on MSDN&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-3046806922049828590?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/3FTdpRBoF74" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/3046806922049828590/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=3046806922049828590" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/3046806922049828590?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/3046806922049828590?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/3FTdpRBoF74/fun-with-enum.html" title="Fun with enum" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://blog.dezfowler.com/2011/09/fun-with-enum.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0UERnszeCp7ImA9WhZWE0w.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-2213684624161080139</id><published>2011-05-13T19:24:00.001+01:00</published><updated>2011-05-13T19:26:47.580+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-05-13T19:26:47.580+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="ADO.NET" /><category scheme="http://www.blogger.com/atom/ns#" term=".NET" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="SQL Server" /><title>Bulk upsert to SQL Server from .NET</title><content type="html">&lt;p&gt;or, “How inserting multiple records using an ORM should probably work”&lt;/p&gt;  &lt;p&gt;Anyone familiar with .NET ORMs should know that one area they’re lacking in is where it comes to updating or inserting multiple objects at the same time. You end up with many individual UPDATE and INSERT statements being executed on the database which can be very inefficient and often results in developers having to extend the ORM or break out of it completely in order to perform particular operations. An added complication is that, where identities are being used in tables, each INSERT command the ORM performs must immediately be followed by a SELECT SCOPE_IDENTITY() call to retrieve the identity value for the newly inserted row so that the CLR object may be amended.&lt;/p&gt;  &lt;p&gt;It’s possible to drastically improve on this by making use of a couple of features already supported in the .NET Framework and SQL Server and I’m hoping that a similar solution will feature in future releases of the major ORMs.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The .NET Framework’s &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx" target="_blank"&gt;SqlBulkCopy&lt;/a&gt; class allowing you to take advantage of BULK operations supported by SQL Server. &lt;/li&gt;    &lt;li&gt;SQL Server temporary tables. &lt;/li&gt;    &lt;li&gt;SQL Server 2008’s &lt;a href="http://msdn.microsoft.com/en-us/library/bb510625.aspx" target="_blank"&gt;MERGE&lt;/a&gt; command which allows upsert operations to be performed on a table and in particular its ability, using the OUTPUT command, to return identities for inserted rows. &lt;/li&gt; &lt;/ul&gt;  &lt;h3&gt;The process&lt;/h3&gt;  &lt;p&gt;The main steps of the process are as follows:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Using ADO.NET create a temporary table in SQL Server whose schema mirrors your source data and whose column types match the types in the target table. &lt;/li&gt;    &lt;li&gt;Using SqlBulkCopy populate the temporary table with the source data. &lt;/li&gt;    &lt;li&gt;Execute a MERGE command via ADO.NET on the SQL Server which upserts data from the temporary table into the target table, outputting identities. &lt;/li&gt;    &lt;li&gt;Read the row set of inserted identities. &lt;/li&gt;    &lt;li&gt;Drop the temporary table. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;So instead of &lt;em&gt;n&lt;/em&gt; INSERT statements to insert &lt;em&gt;n&lt;/em&gt; records that’s four SQL commands in all to insert &lt;strong&gt;or&lt;/strong&gt; update &lt;em&gt;n&lt;/em&gt; records.&lt;/p&gt;  &lt;p&gt;There’s already a blog post on this technique that goes into more detail by Kelias which you can read &lt;a href="http://jarloo.com/code/database/c-bulk-upsert-to-sql-server-tutorial/" target="_blank"&gt;here&lt;/a&gt;. The only part missing from Kelias’ post is the piece utilising the OUTPUT modifier to retrieve the inserted identities from the MERGE command. This is simply an additional line in the merge command e.g.&lt;/p&gt;  &lt;pre&gt;&lt;code class="sql"&gt;OUTPUT $action, INSERTED.$IDENTITY&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and the small matter of reading those returned identities out of a SqlDataReader.&lt;/p&gt;

&lt;p&gt;This is the crucial piece, however, as it is this which allows us to tie the inserted row back to the original CLR “entity” item that formed part of our source data. Updating our CLR object with this identity will allow us to save subsequent changes away as an UPDATE to the now existing database row.&lt;/p&gt;

&lt;h3&gt;Performance&lt;/h3&gt;

&lt;p&gt;I did some brief testing to get rough timings of this technique versus individual INSERT calls using a parameterised ADO.NET command. With a variety of numbers and sizes of rows from 100 to 10,000 and with row sizes from 1k to 10k roughly the upsert technique nearly always executed in less than half the time of the individual INSERT statements. For example, 1,000 rows of about 1k each took individual INSERTs an average of just over 500ms versus bulk upsert’s 150ms on my quite old desktop with not very much RAM.&lt;/p&gt;

&lt;p&gt;That’s pretty cool considering the upsert could be performing either an INSERT or an UPDATE command in the same number of calls whereas if I were to factor that into the individual SQL statements method it would be a lot of extra commands to try an UPDATE and then check whether any rows had been affected etc.&lt;/p&gt;

&lt;h3&gt;Github project&lt;/h3&gt;

&lt;p&gt;I decided to have a go at wrapping the upsert technique up in a library which would automatically generate the SQL necessary for creating the temporary table and running the MERGE. I pushed an initial version of this SqlBulkUpsert project to github which can be found here: 
  &lt;br /&gt;&lt;a title="https://github.com/dezfowler/SqlBulkUpsert" href="https://github.com/dezfowler/SqlBulkUpsert"&gt;https://github.com/dezfowler/SqlBulkUpsert&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Usage would be something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;using (var connection = DatabaseHelper.CreateAndOpenConnection())
{
	var targetSchema = SqlTableSchema.LoadFromDatabase(connection, &amp;quot;TestUpsert&amp;quot;, &amp;quot;ident&amp;quot;);

	var columnMappings = new Dictionary&amp;lt;string, Func&amp;lt;TestDto, object&amp;gt;&amp;gt;
							{
								{&amp;quot;ident&amp;quot;, d =&amp;gt; d.Ident},
								{&amp;quot;key_part_1&amp;quot;, d =&amp;gt; d.KeyPart1},
								{&amp;quot;key_part_2&amp;quot;, d =&amp;gt; d.KeyPart2},
								{&amp;quot;nullable_text&amp;quot;, d =&amp;gt; d.Text},
								{&amp;quot;nullable_number&amp;quot;, d =&amp;gt; d.Number},
								{&amp;quot;nullable_datetimeoffset&amp;quot;, d =&amp;gt; d.Date},
							};

	Action&amp;lt;TestDto, int&amp;gt; identUpdater = (d, i) =&amp;gt; d.Ident = i;

	var upserter = new TypedUpserter&amp;lt;TestDto&amp;gt;(targetSchema, columnMappings, identUpdater);

	var items = new List&amp;lt;TestDto&amp;gt;();

	// Populate items with TestDto instances
	
	upserter.Upsert(connection, items);

	// Ident property of TestDto instances updated
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;with TestDto just being a simple class like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;public class TestDto
{
	public int? Ident { get; set; }
	public string KeyPart1 { get; set; }
	public short KeyPart2 { get; set; }
	public string Text { get; set; }
	public int Number { get; set; }
	public DateTimeOffset Date { get; set; }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this TypedUpserter example we:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;define the schema of the target table either in code or by loading it from the database (shown in the example) &lt;/li&gt;

  &lt;li&gt;define mappings from column names of the target to a lambda retrieving the appropriate property value from the TestDto class &lt;/li&gt;

  &lt;li&gt;define an action to be called to allow setting the the new identity to a property of the DTO &lt;/li&gt;

  &lt;li&gt;instantiate the Upserter and call Upsert() with a list of items and a database connection &lt;/li&gt;

  &lt;li&gt;the identity properties of the TestDto instances will have been updated using the defined action so the CLR objects will now be consistent with the database rows. &lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;Next step&lt;/h3&gt;

&lt;p&gt;The object model could probably do with some refinement and it needs lots more tests adding but it’s in pretty good shape so next I’m going to look at integrating it into &lt;a href="https://github.com/markrendle/Simple.Data" target="_blank"&gt;Mark Rendle’s Simple.Data project&lt;/a&gt; which should mean that, to my knowledge, it’s the only .NET ORM doing proper bulk loading of multiple records.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-2213684624161080139?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/3j90_4ZpZ3I" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/2213684624161080139/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=2213684624161080139" title="5 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/2213684624161080139?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/2213684624161080139?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/3j90_4ZpZ3I/bulk-upsert-to-sql-server-from-net.html" title="Bulk upsert to SQL Server from .NET" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>5</thr:total><feedburner:origLink>http://blog.dezfowler.com/2011/05/bulk-upsert-to-sql-server-from-net.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0UMRH4_fip7ImA9Wx9VEEQ.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-7881566121065575275</id><published>2011-01-26T23:09:00.001Z</published><updated>2011-01-27T01:21:25.046Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-01-27T01:21:25.046Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".NET" /><title>Adding collections to a custom ConfigurationSection</title><content type="html">&lt;p&gt;The attributed model for creating custom ConfigurationSection types for use in your app.config or web.config file is quite verbose and examples are hard to come by. Collections in particular are a pain point, there is very little documentation around them and the examples all tend to follow the default add/remove/clear model i.e. that used in &amp;lt;appSettings/&amp;gt;.&lt;/p&gt;
&lt;p&gt;Three particular scenarios with collections which caused me problems while doing the same piece of work were:&lt;/p&gt;  
&lt;ul&gt;   
&lt;li&gt;When the items of a collection have a custom name e.g. "item" instead of add/remove/clear&lt;/li&gt;
&lt;li&gt;When the items of a collection can have different element names representing different actions or subclasses e.g. the&amp;#160; &amp;lt;allow/&amp;gt; and &amp;lt;deny/&amp;gt; elements used with &amp;lt;authorization/&amp;gt; &lt;/li&gt;
&lt;li&gt;When the items of a collection don’t have an attribute which represents a unique key e.g. not having anything like the key attribute of an &amp;lt;add/&amp;gt; or &amp;lt;remove/&amp;gt; element &lt;/li&gt;
&lt;/ul&gt;  
&lt;p&gt;This first and last are relatively trivial to fix, the second less so and it took me a bit of digging around in Reflector to work out how to set up something that worked.&lt;/p&gt;

&lt;h3&gt;Collection items with a custom element name&lt;/h3&gt;  
&lt;p&gt;This scenario can be accomplished as follows.&lt;/p&gt;  
&lt;pre&gt;&lt;code class="c#"&gt;
public class MySpecialConfigurationSection : ConfigurationSection
{
 [ConfigurationProperty(&amp;quot;&amp;quot;, IsRequired = false, IsKey = false, IsDefaultCollection = true)]
 public ItemCollection Items
 {
  get { return ((ItemCollection) (base[&amp;quot;items&amp;quot;])); }
  set { base[&amp;quot;items&amp;quot;] = value; }
 }
}

[ConfigurationCollection(typeof(Item), CollectionType = ConfigurationElementCollectionType.BasicMapAlternate)]
public class ItemCollection : ConfigurationElementCollection
{
 internal const string ItemPropertyName = &amp;quot;item&amp;quot;;

 public override ConfigurationElementCollectionType CollectionType
 {
  get { return ConfigurationElementCollectionType.BasicMapAlternate; }
 }

 protected override string ElementName
 {
  get { return ItemPropertyName; }
 }

 protected override bool IsElementName(string elementName)
 {
  return (elementName == ItemPropertyName);
 }

 protected override object GetElementKey(ConfigurationElement element)
 {
  return ((Item)element).Value;
 }

 protected override ConfigurationElement CreateNewElement()
 {
  return new Item();
 }

 public override bool IsReadOnly()
 {
  return false;
 }

}

public class Item
{
 [ConfigurationProperty(&amp;quot;value&amp;quot;)]
 public string Value 
 {
  get { return (string)base[&amp;quot;value&amp;quot;]; }
  set { base[&amp;quot;value&amp;quot;] = value; }
 }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which will allow us to specify our section like so:&lt;/p&gt;

&lt;pre&gt;&lt;code class="xml"&gt;
&amp;lt;configSections&amp;gt;
  &amp;lt;section name=&amp;quot;mySpecialSection&amp;quot; type=&amp;quot;MyNamespace.MySpecialConfigurationSection, MyAssembly&amp;quot;/&amp;gt; 
&amp;lt;/configSections&amp;gt;

...

&amp;lt;mySpecialSection&amp;gt;
 &amp;lt;item value=&amp;quot;one&amp;quot;/&amp;gt;
 &amp;lt;item value=&amp;quot;two&amp;quot;/&amp;gt;
 &amp;lt;item value=&amp;quot;three&amp;quot;/&amp;gt;
&amp;lt;/mySpecialSection&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;First off we have a property representing our collection on our ConfigurationSection or ConfigurationElement whose type derives from ConfigurationElementCollection. This property decorated with a ConfigurationProperty attribute. If the collection should be contained directly within the parent element then set IsDefaultCollection equal to true and leave element name as empty string. If the collection should be contained within a container element specify an element name.&lt;/p&gt;

&lt;p&gt;Next, the ConfigurationElementCollection derived type of the property should have a ConfigurationCollection attribute specifying element type and collection type. The collection type specifies the inheritance behaviour when the section appears in web.config files nested deeper in the folder structure for example.&lt;/p&gt;

&lt;p&gt;For the collection type itself we do this:&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;Override ElementName to return collection item element&amp;#160; name &lt;/li&gt;

      &lt;li&gt;Override IsElementName to return true when encountering element name &lt;/li&gt;

      &lt;li&gt;Override GetNewElement() to new up an instance of your item type &lt;/li&gt;

      &lt;li&gt;Override GetElementKey(element) to return an object which uniquely identifies the item. This could be a property value, a combination of values as some hash or the element itself &lt;/li&gt;
    &lt;/ul&gt;


&lt;h3&gt;Collection items with varying element name&lt;/h3&gt;

&lt;pre&gt;&lt;code class="c#"&gt;
public class MySpecialConfigurationSection : ConfigurationSection
{
 [ConfigurationProperty(&amp;quot;items&amp;quot;, IsRequired = false, IsKey = false, IsDefaultCollection = false)]
 public ItemCollection Items
 {
  get { return ((ItemCollection) (base[&amp;quot;items&amp;quot;])); }
  set { base[&amp;quot;items&amp;quot;] = value; }
 }    
}
    
[ConfigurationCollection(typeof(Item), AddItemName = &amp;quot;apple,orange&amp;quot;, CollectionType = ConfigurationElementCollectionType.BasicMapAlternate)]
public class ItemCollection : ConfigurationElementCollection
{
 public override ConfigurationElementCollectionType CollectionType
 {
  get { return ConfigurationElementCollectionType.BasicMapAlternate; }
 }

 protected override string ElementName
 {
  get { return string.Empty; }
 }

 protected override bool IsElementName(string elementName)
 {
  return (elementName == &amp;quot;apple&amp;quot; || elementName == &amp;quot;orange&amp;quot;);
 }

 protected override object GetElementKey(ConfigurationElement element)
 {
  return element;
 }

 protected override ConfigurationElement CreateNewElement()
 {
  return new Item();
 }

 protected override ConfigurationElement CreateNewElement(string elementName)
 {
  var item = new Item();
  if (elementName == &amp;quot;apple&amp;quot;)
  {
   item.Type = ItemType.Apple;
  }
  else if(elementName == &amp;quot;orange&amp;quot;)
  {
   item.Type = ItemType.Orange;
  }
  return item;
 }
 
 public override bool IsReadOnly()
 {
  return false;
 }
}

public class Item
{
 public ItemType Type { get; set; }

 [ConfigurationProperty(&amp;quot;value&amp;quot;)]
 public string Value 
 {
  get { return (string)base[&amp;quot;value&amp;quot;]; }
  set { base[&amp;quot;value&amp;quot;] = value; }
 }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Which will allow us to specify our section like so:&lt;/p&gt;

&lt;pre&gt;&lt;code class="xml"&gt;
&amp;lt;configSections&amp;gt;
  &amp;lt;section name=&amp;quot;mySpecialSection&amp;quot; type=&amp;quot;MyNamespace.MySpecialConfigurationSection, MyAssembly&amp;quot;/&amp;gt; 
&amp;lt;/configSections&amp;gt;

...

&amp;lt;mySpecialSection&amp;gt;
 &amp;lt;items&amp;gt;
  &amp;lt;apple value=&amp;quot;one&amp;quot;/&amp;gt;
  &amp;lt;apple value=&amp;quot;two&amp;quot;/&amp;gt;
  &amp;lt;orange value=&amp;quot;one&amp;quot;/&amp;gt;
 &amp;lt;/items&amp;gt;
&amp;lt;/mySpecialSection&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice that here we've specified two collection items with the value "one" which would have resulted in one overwriting the other in the previous example. To get around this, instead of returning the Value property we're returning the element itself as the unique key.&lt;/p&gt;

&lt;p&gt;This time our ConfigurationElementCollection derived type's ConfigurationCollection attribute also specifies a comma delimited AddItemName e.g. "allow,deny". We override the methods of the base as follows:&lt;/p&gt;
    &lt;ul&gt;
      &lt;li&gt;Override ElementName to return empty string &lt;/li&gt;

      &lt;li&gt;Override IsElementName to return true when encountering a correct element name&lt;/li&gt;

      &lt;li&gt;Override GetNewElement() to new up an instance of your item type&lt;/li&gt;

      &lt;li&gt;Override GetNewElement(elementName) to new up an instance of the correct item type for particular element name setting relevant properties&lt;/li&gt;

      &lt;li&gt;Override GetElementKey(element) to return an object which uniquely identifies the item. This could be a property value, a combination of values as some hash or the element itself &lt;/li&gt;
    &lt;/ul&gt;

&lt;h4&gt;Caveat&lt;/h4&gt;

&lt;p&gt;While our varying element names will be readable the object model is read-only. I haven't covered support for writing changes back to the config file here as it involves taking charge of the serialization of the objects so really requires its own blog post.&lt;/p&gt;

&lt;h3&gt;Links&lt;/h3&gt;

&lt;ul&gt;

&lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationsection.aspx" target="_blank"&gt;ConfigurationSection&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationelement.aspx" target="_blank"&gt;ConfigurationElement&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationelementcollection.aspx" target="_blank"&gt;ConfigurationElementCollection&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationpropertyattribute.aspx" target="_blank"&gt;ConfigurationPropertyAttribute&lt;/a&gt;&lt;/li&gt;

&lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationcollectionattribute.aspx" target="_blank"&gt;ConfigurationCollectionAttribute&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-7881566121065575275?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/N3HAb9SpnfU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/7881566121065575275/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=7881566121065575275" title="3 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/7881566121065575275?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/7881566121065575275?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/N3HAb9SpnfU/adding-collections-to-custom.html" title="Adding collections to a custom ConfigurationSection" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>3</thr:total><feedburner:origLink>http://blog.dezfowler.com/2011/01/adding-collections-to-custom.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A0cEQ30-fCp7ImA9Wx9SFUQ.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-4402363224435106983</id><published>2010-12-05T23:28:00.000Z</published><updated>2010-12-06T01:30:02.354Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-12-06T01:30:02.354Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Music" /><title>Taking my music listening in a new direction</title><content type="html">&lt;p&gt;or, Why I'm cancelling my Spotify Premium subscription&lt;/p&gt;  &lt;p&gt;Not entirely sure when I started using &lt;a href="http://www.spotify.com" target="_blank"&gt;Spotify&lt;/a&gt; but it was probably late 2008 / early 2009 and I've found it to be a revelation of music discovery. I've spent hours just clicking from one artist to another, exploring back catalogues and having a serious listen to full albums in a way that would be quite difficult without already having bought the album or &amp;quot;obtained&amp;quot; it from P2P. Previously, using a combination of &lt;a href="http://www.last.fm" target="_blank"&gt;Last.fm&lt;/a&gt; and &lt;a href="http://www.myspace.com/" target="_blank"&gt;Myspace&lt;/a&gt; you could get quite close but the Spotify desktop app made the whole experience so much more seamless and enjoyable with full, consistent quality tracks.&lt;/p&gt;  &lt;p&gt;I've been a Premium subscriber since 1 Aug 2009 with several factors leading to my decision to pay up. The first being high-bitrate uninterrupted audio; having some decent audio kit at home I wanted to make the most of it. Second was the Spotify for Android app I could use on my HTC Hero which is hands down the most convenient means of getting music on a mobile device. Put tracks in a playlist in the desktop app and they magically appear on the device – brilliant.&lt;/p&gt;  &lt;h3&gt;So, why am I quitting?&lt;/h3&gt;  &lt;h4&gt;1. Cost&lt;/h4&gt;  &lt;p&gt;To date that's £169.83 in subscription fees - £9.99 a month for 17 months. I tend to buy CDs for £5 off Amazon so that equates to about 33 CD albums or about 2 albums a month. I’ve listened to a lot more albums than that during the time but I doubt that there would have been more than 33 that I would have considered buying a CD copy of. I’ve never paid for an MP3, I refuse to pay the same price as a CD for a lossy version but I paid for Spotify as the service does offer significantly more especially when you use the mobile apps. I’m just not sure it’s worth £9.99 a month.&lt;/p&gt;  &lt;h4&gt;2. Quality&lt;/h4&gt;  &lt;p&gt;Spotify Premium ups the track bitrate from 160kbps to 320kbps. At least that’s the idea, in practice it seems large portions of their library are only available in the lower quality and I doubt that more than 10% of the tracks I’ve listened to recently have been high bitrate. There’s also no visibility on &amp;quot;high quality&amp;quot; tracks in the app so I’m seriously sceptical about whether I’m getting the high-bitrates I’m paying for. The quality is certainly still miles off CD audio and having made a return to CDs recently it’s very noticeable that I’m missing out on audio clarity and have been making do with poor quality audio whilst also paying for the privilege.&lt;/p&gt;  &lt;h4&gt;3. Nothing to show for it&lt;/h4&gt;  &lt;p&gt;It’s a bitter pill to swallow but worst of all is the fact that after all the cost I’ve just been renting the music. I don’t get to keep the OGG tracks, I don’t own any of it and, when I cancel, the app on my phone will just stop working.&lt;/p&gt;  &lt;h4&gt;&lt;/h4&gt;  &lt;h3&gt;What service would I be happy with?&lt;/h3&gt;  &lt;p&gt;I’ve been wondering about the kind of service I’d like to see and that I’d be happy to pay for. Unlimited ad-supported listening of any tracks for discovering new music would be fine. I’d like to be able to buy albums, download them in full CD quality and stream them uninterrupted (no ads) in a reasonable bitrate to other computers&amp;#160; and mobile devices. I’d also like to be able to register CDs I own with the service so those tracks are also available wherever I am.&lt;/p&gt;  &lt;p&gt;The roll-your-own solution might be buying CDs, ripping them and paying $9.99 for at 50GB Dropbox to sync up my machines. Apparently the Dropbox for Android app has the ability to stream music and movies straight to the device so maybe that’s an option worth considering.&lt;/p&gt;  &lt;h4&gt;Lossless&lt;/h4&gt;  &lt;p&gt;In this day and age of high-def video, broadband internet&amp;#160; and huge hard disks I don’t want to pay for, and there is no necessity for, low bitrate music. It’s rather interesting that the medium with the highest audio quality most widely available is &lt;a href="http://en.wikipedia.org/wiki/Blu-ray_Disc#Audio" target="_blank"&gt;Blu-ray disc&lt;/a&gt; in the form of Dolby TrueHD and DTS-HD. With video the soundtrack is more of a supporting role so lossy compression can be forgiven to some extent but with music the audio is the main event, it should be CD quality at least. MP3 was great for portability but it has a lot to answer for in terms of killing our appreciation of high quality audio and therefore the market’s desire to provide us with (and push) a high-definition medium solely for audio.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-4402363224435106983?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/zwlsl9TixkI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/4402363224435106983/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=4402363224435106983" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/4402363224435106983?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/4402363224435106983?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/zwlsl9TixkI/taking-my-music-listening-in-new.html" title="Taking my music listening in a new direction" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/12/taking-my-music-listening-in-new.html</feedburner:origLink></entry><entry gd:etag="W/&quot;AkUMRnk7fip7ImA9Wx9TF08.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-2198727489647024017</id><published>2010-11-25T23:37:00.000Z</published><updated>2010-11-25T23:38:07.706Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-11-25T23:38:07.706Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="MVC" /><category scheme="http://www.blogger.com/atom/ns#" term=".NET" /><category scheme="http://www.blogger.com/atom/ns#" term="ASP.NET" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>Adding a design mode to your MVC app</title><content type="html">&lt;p&gt;When developing websites you'll likely have ended up in the situation where you need to make some styling changes to a page that's buried deep within the site. If that page is at the end of a process such as registration or checkout then it can be extremely time consuming entering test data that passes validation in order to navigate to the correct page. Add to that the complexity of maybe needing to log in and also having to do the same thing on multiple browsers and things can get ridiculous. If you’re using the WebForms view engine then you have limited design time capability in Visual Studio but this isn’t satisfactory for ensuring cross-browser compatibility.&lt;/p&gt;  &lt;p&gt;What's needed is a dumb version of the site which simply renders the views using a variety of data. Effectively you want to create a load of static pages, each with ViewData, Model etc set up so that they represent a different step in one of the real processes on the site. Using this version you’d be able to get to the correct page straight away, be able to refresh it quickly after making markup or CSS changes and be able to visit the page in all your test browsers. Ideally using this version of the site will require no authentication and it wont have any external dependencies like databases or web services that must be set up or configured.&lt;/p&gt;  &lt;p&gt;We can use a set of different controllers to do this, each having some hard coded model data for example:&lt;/p&gt;  &lt;pre&gt;&lt;code class="c#"&gt;// A real controller may look like this... 
public class PeopleController : Controller
{
	public ActionResult Index()
	{
		List&amp;lt;Person&amp;gt; people = GetListOfPeopleFromDatabase();
		return View(people);
	}

	private List&amp;lt;Person&amp;gt; GetListOfPeopleFromDatabase()
	{
		// Do some data access
		
		return new List&amp;lt;Person&amp;gt;
			{
				new Person{ Name = &amp;quot;Runtime Person 1&amp;quot; },
				new Person{ Name = &amp;quot;Runtime Person 2&amp;quot; },
				new Person{ Name = &amp;quot;Runtime Person 3&amp;quot; },
			};
	}
}


// And our design time controller like this...
public class PeopleController : Controller
{
	[Description(&amp;quot;Empty people list page&amp;quot;)]
	public ActionResult EmptyList()
	{
		return View(&amp;quot;Index&amp;quot;, new List&amp;lt;Person&amp;gt;{});
	}

	[Description(&amp;quot;People list page with 5 random people&amp;quot;)]
	public ActionResult ListWithFivePeople()
	{
		return View(&amp;quot;Index&amp;quot;, new List&amp;lt;Person&amp;gt;
			{
				new Person
				{
					Name = &amp;quot;John Smith&amp;quot;
				},
				new Person
				{
					Name = &amp;quot;Betty Davis&amp;quot;
				},
				new Person
				{
					Name = &amp;quot;Steve Jobs&amp;quot;
				},
				new Person
				{
					Name = &amp;quot;Bill Gates&amp;quot;
				},
				new Person
				{
					Name = &amp;quot;John Carmack&amp;quot;
				},
			});
	}
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will work best if your model classes or, the data entity classes you're passing on to your views are dumb i.e. they don't try to do any database access when the view renders. If you already have your controllers in a separate assembly then it should be a relatively simple task to swap your design time ones in and use them instead. If however you have the standard MVC setup of controllers, views and models all in the same project and assembly then things are a bit more difficult.&lt;/p&gt;

&lt;p&gt;At the very&amp;#160; least we want our design time controllers in a separate folder of our project, away from the real ones. The issue with this is that the default MVC controller factory will find them here anyway. Thankfully we don't need to implement an entire new factory, we can hide them from the default one by simply breaking with the convention it uses to identify them, the easiest way being not naming them &amp;quot;...Controller&amp;quot;.&lt;/p&gt;

&lt;h3&gt;Home page&lt;/h3&gt;

&lt;p&gt;A nice to have in this &amp;quot;design&amp;quot; mode would be a default page which shows a list of links to all the actions of the design time controllers with descriptions for what each represents. This would be particularly useful when handing the markup and CSS over to a third party to be styled up as it allows them to quickly access each variation of each screen. You'd end up with something like this:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Products 
    &lt;ul&gt;
      &lt;li&gt;List products &lt;/li&gt;

      &lt;li&gt;Search products &lt;/li&gt;

      &lt;li&gt;View product &lt;/li&gt;

      &lt;li&gt;Product category &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;

  &lt;li&gt;Basket 
    &lt;ul&gt;
      &lt;li&gt;Empty &lt;/li&gt;

      &lt;li&gt;Full &lt;/li&gt;

      &lt;li&gt;Saved &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;

  &lt;li&gt;My Account 
    &lt;ul&gt;
      &lt;li&gt;Addresses &lt;/li&gt;

      &lt;li&gt;Billing details &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;

  &lt;li&gt;Home &lt;/li&gt;

  &lt;li&gt;Contact us &lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;Variations&lt;/h3&gt;

&lt;p&gt;In addition to each individual view the design time functionality could also allow for variations of these pages e.g. logged in / logged out&amp;#160; views, special offer views, user customised views etc. Variations could be&amp;#160; defined on an action, a controller or on the whole site and rather than defining the particular data in each of these cases a transform function could be defined which is called before view render. This function could do work along the lines of setting IsAuthenticated booleans for the logged in / logged out case and possibly more complex operations otherwise.&lt;/p&gt;

&lt;p&gt;This would allow a wide variety of viewable pages to be created without&amp;#160; needing to specifically define data in all those cases.&lt;/p&gt;

&lt;h3&gt;Proof of concept&lt;/h3&gt;

&lt;p&gt;I've put a quick proof of concept up on Github here:
  &lt;br /&gt;&lt;a href="https://github.com/dezfowler/MvcDesignMode"&gt;https://github.com/dezfowler/MvcDesignMode&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There's the main MvcDesignMode library and an example MVC app based on the standard template site which has few design time controllers named &amp;quot;...Designer&amp;quot; rather than &amp;quot;...Controller&amp;quot;. When not in design mode this should prevent them ever being accidentally accessed provided you're using the default controller factory. I have the code to enable design mode in the App_Start of Global.asax.cs and it looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;bool designMode = Convert.ToBoolean(ConfigurationManager.AppSettings[&amp;quot;DesignMode&amp;quot;]);
if (designMode)
{
	DesignMode.Activate(typeof(HomeController));
}
else
{
	AreaRegistration.RegisterAllAreas();
	RegisterRoutes(RouteTable.Routes);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here I'm just using a boolean configuration setting in web.config to turn the mode on and off but how you might choose to do it is up to you. If the design mode is activated the standard application startup stuff is skipped mainly because design mode uses a standard set of routes. Any links in your pages built using custom routes wont work correctly but the point of design mode isn't to be able to navigate around the site as normal it is that you can jump straight to a particular page in one click. I’m passing a type in to the Activate method simply to server as a pointer to the assembly where my design time controllers reside.&lt;/p&gt;

&lt;p&gt;Once in design mode the design time controller factory hunts down the special controllers ending with &amp;quot;...Designer&amp;quot; and effectively indexes them pulling out action method names and also the text from a Description attribute defined on the methods. Using this index it builds up a special site map listing each controller and its action methods as links.&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;Have a look at the solution on Github or have a go implementing something similar yourself. On a number of recent projects I could see having a setup like this saving a lot of time and effort not just for styling and markup but probably developing simple JavaScript stuff as well. I'll definitely be using it myself in all my future MVC projects.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-2198727489647024017?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/0zaeL8C2YHE" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/2198727489647024017/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=2198727489647024017" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/2198727489647024017?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/2198727489647024017?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/0zaeL8C2YHE/adding-design-mode-to-your-mvc-app.html" title="Adding a design mode to your MVC app" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/11/adding-design-mode-to-your-mvc-app.html</feedburner:origLink></entry><entry gd:etag="W/&quot;AkcAQns8eip7ImA9Wx9TEUw.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-3297644444510732744</id><published>2010-11-18T22:07:00.001Z</published><updated>2010-11-18T22:07:23.572Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-11-18T22:07:23.572Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="LINQPad" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>Pretty print hex dump in LINQPad</title><content type="html">&lt;p&gt;Was messing around with byte arrays a lot in LINQPad this week and really wanted a pretty hex print of the contents of the array so wrote this:&lt;/p&gt;  &lt;pre&gt;&lt;code class="c#"&gt;public static object HexDump(byte[] data)
{
	return data
		.Select((b, i) =&amp;gt; new { Byte = b, Index = i })
		.GroupBy(o =&amp;gt; o.Index / 16)
		.Select(g =&amp;gt; 
			g
			.Aggregate(
				new { Hex = new StringBuilder(), Chars = new StringBuilder() },
				(a, o) =&amp;gt; {a.Hex.AppendFormat(&amp;quot;{0:X2} &amp;quot;, o.Byte); a.Chars.Append(Convert.ToChar(o.Byte)); return a;},
				a =&amp;gt; new { Hex = a.Hex.ToString(), Chars = a.Chars.ToString() }
			)
		)
		.ToList()
		.Dump();
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You use it like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;byte[] text = Encoding.UTF8.GetBytes(&amp;quot;The quick brown fox jumps over the lazy dog&amp;quot;);

HexDump(text);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;...and it will produce output akin to:&lt;/p&gt;

&lt;p&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="hexdump" border="0" alt="hexdump" src="http://lh3.ggpht.com/_EuFsZMY5ZNU/TOWjmrS7uwI/AAAAAAAAAkw/NW65nyhv7vA/hexdump_thumb%5B2%5D.gif?imgmax=800" width="476" height="109" /&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-3297644444510732744?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/oE7VDYixvWI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/3297644444510732744/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=3297644444510732744" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/3297644444510732744?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/3297644444510732744?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/oE7VDYixvWI/pretty-print-hex-dump-in-linqpad.html" title="Pretty print hex dump in LINQPad" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh3.ggpht.com/_EuFsZMY5ZNU/TOWjmrS7uwI/AAAAAAAAAkw/NW65nyhv7vA/s72-c/hexdump_thumb%5B2%5D.gif?imgmax=800" height="72" width="72" /><thr:total>1</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/11/pretty-print-hex-dump-in-linqpad.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A04BSHg4eyp7ImA9Wx5VEEg.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-4642740032193268009</id><published>2010-10-02T23:51:00.000+01:00</published><updated>2010-10-02T23:52:39.633+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-10-02T23:52:39.633+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".NET" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>The Null Object pattern and the Maybe monad</title><content type="html">&lt;p&gt;Dmitri Nesteruk’s recent post &lt;a href="http://www.codeproject.com/KB/cs/maybemonads.aspx" target="_blank"&gt;Chained null checks and the Maybe monad&lt;/a&gt; struck a chord with me as I had messed about with &lt;a href="http://derek-says.blogspot.com/2010/07/creating-light-weight-visitor-fluently.html" target="_blank"&gt;something similar&lt;/a&gt; for performing a visitor-esque operation. I’ve glanced at a few posts about monads in the past however this is the first time I’ve had a proper look at one of them.&lt;/p&gt;  &lt;p&gt;The purpose of the &lt;a href="http://www.haskell.org/all_about_monads/html/maybemonad.html" target="_blank"&gt;Maybe monad&lt;/a&gt; is essentially to remove the need for null reference checking. If you try to perform some function on an object which turns out to be null you might get a null reference exception. If, however, you perform the function on a Maybe then if the object is null the function is never called. It’s particularly useful if you’re performing a long chain of functions on an object, any of which may return null. In these cases when the null is encountered the remainder of the chain is skipped resulting in more robust, better performing code.&lt;/p&gt;  &lt;p&gt;The implementations in .NET that I could find vary quite widely:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://maybe.codeplex.com/" target="_blank"&gt;Maybe project&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://code.google.com/p/lokad-shared-libraries/" target="_blank"&gt;Maybe monad in Lokad shared libraries&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://sharpmalib.codeplex.com/" target="_blank"&gt;M&amp;lt;’a&amp;gt; Lib&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://weblogs.asp.net/zowens/archive/2009/09/04/maybe-monad-my-c-version.aspx" target="_blank"&gt;Zack Owens’ version&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://stackoverflow.com/questions/1196031/evil-use-of-maybe-monad-and-extension-methods-in-c" target="_blank"&gt;Random one from Stack Overflow (Judah Himango)&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;One aspect shared by most of these implementations, and which was pointed out in the comments of Dmitri’s post, is that they still end up doing all the null checking, it’s just hidden away. They are treating the “nothing” state as a value, effectively just creating a Nullable&amp;lt;T&amp;gt; which wraps reference types and then checking the HasValue at the beginning of each method call. I think a more elegant solution to this is to use the &lt;a href="http://en.wikipedia.org/wiki/Null_Object_pattern" target="_blank"&gt;Null Object pattern&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;A Null Object is a special inert type derived from our real class or a common base class. Each method is overridden by a version which has no effect. By wrapping any non-null objects we encounter in an instance of our real type and any nulls in an instance of our inert type we can continually call the methods of these types without fear of null reference exceptions occurring. Moreover, once we receive our inert type from one of the method calls we’re calling the methods on that type so we don’t need null checks at the beginning of our methods as the implementations we’re calling will have no effect.&lt;/p&gt;  &lt;h3&gt;Example&lt;/h3&gt;  &lt;pre&gt;&lt;code class="c#"&gt;// Simple testing class
class Node
{
	public int Number { get; set; }
	public Node Parent { get; set; }
}


// Arrange
Node node = new Node
{
	Number = 1,
	Parent = new Node
	{
		Number = 2,
		Parent = new Node
		{
			Number = 3
		}
	}
};

// Act
var third = node.Maybe()
	.Apply(n =&amp;gt; n.Parent)
	.Apply(n =&amp;gt; n.Parent)
	.Return();

// Assert
Assert.IsNotNull(third);
Assert.AreEqual(3, third.Number);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we've got a simple test class and object graph and our code is trying to return the grandparent of node. First we use the Maybe extension method to create the Maybe object after this we're calling methods on the Maybe object itself. The Apply method behaves like a Map method and applies the supplied Func to the subject of the Maybe, returning its result as a new Maybe object. The Return then unwraps the Maybe and returns the subject object if there is one. If any of the methods called on the Maybe object fail we'll end up with a null coming back from Return.&lt;/p&gt;

&lt;h3&gt;Implementation&lt;/h3&gt;

&lt;p&gt;The basic structure is an abstract Maybe class with two derived classes; ActualMaybe which contains the real implementation and NothingMaybe which is the Null Object type. The implicit operator on Maybe is where any null is handled.&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;public abstract class Maybe&amp;lt;T&amp;gt; where T : class
{
	public static readonly Maybe&amp;lt;T&amp;gt; Nothing = new NothingMaybe&amp;lt;T&amp;gt;();
 
	public static implicit operator Maybe&amp;lt;T&amp;gt;(T t)
	{
		return t == null ? Nothing : new ActualMaybe&amp;lt;T&amp;gt;(t);
	}
}

class ActualMaybe&amp;lt;T&amp;gt; : Maybe&amp;lt;T&amp;gt; where T : class
{
	readonly T _t;
	public ActualMaybe(T t)
	{
		if (t == null) throw new ArgumentNullException(&amp;quot;t&amp;quot;);
		_t = t;
	}
}

class NothingMaybe&amp;lt;T&amp;gt; : Maybe&amp;lt;T&amp;gt; where T : class
{

}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The implementation for Apply is as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;// Maybe&amp;lt;T&amp;gt; 
public abstract Maybe&amp;lt;TResult&amp;gt; Apply&amp;lt;TResult&amp;gt;(Func&amp;lt;T, TResult&amp;gt; func) where TResult : class;

// ActualMaybe&amp;lt;T&amp;gt;
public override Maybe&amp;lt;TResult&amp;gt; Apply&amp;lt;TResult&amp;gt;(Func&amp;lt;T, TResult&amp;gt; func)
{
	return func(_t);
}

// NothingMaybe&amp;lt;T&amp;gt;
public override Maybe&amp;lt;TResult&amp;gt; Apply&amp;lt;TResult&amp;gt;(Func&amp;lt;T, TResult&amp;gt; func)
{
	return Maybe&amp;lt;TResult&amp;gt;.Nothing;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Apply takes the map function &lt;var&gt;func&lt;/var&gt; which operates on the type T and returns some other type TResult. Apply itself returns the Maybe of TResult. &lt;/p&gt;

&lt;p&gt;The ActualMaybe implementation simply calls func passing _t, which is the contained object, and returns the result of func. There is more going on here though; first _t can't be null because of the check in the ActualMaybe constructor so we don't need a null check, second we return whatever comes out of func but because the method returns a Maybe of TResult the implicit cast takes place and any nul coming out of func is replaced.&lt;/p&gt;

&lt;p&gt;The NothingMaybe implementation ignores func altogether and just returns a NothingMaybe of TResult using the static readonly Nothing field on Maybe&amp;lt;T&amp;gt;.&lt;/p&gt;

&lt;p&gt;The ActualMaybe implementation of Return returns _t while the NothingMaybe implementation always returns null.&lt;/p&gt;

&lt;p&gt;I’ve implemented a couple of other useful methods including Do(Action&amp;lt;T&amp;gt;), If(Predicate&amp;lt;T&amp;gt;), Cast&amp;lt;TResult&amp;gt;() and AsEnumerable() as well as several overloads.&lt;/p&gt;

&lt;h3&gt;Possibilities&lt;/h3&gt;

&lt;p&gt;I think this Null Object approach could be combined with the &lt;a href="http://en.wikipedia.org/wiki/Visitor_pattern" target="_blank"&gt;Visitor pattern&lt;/a&gt; to achieve some extensibility although I’m not entirely sure how it would work or whether it would even be necessary.&lt;/p&gt;

&lt;p&gt;Another possible extension is some kind of Collect method which would allow you to cherry pick particular objects from a graph and then would return an IEnumerable over just those objects at the end.&lt;/p&gt;

&lt;h3&gt;Code&lt;/h3&gt;

&lt;p&gt;I’ve put the code up on Github here: 
  &lt;br /&gt;&lt;a href="http://github.com/dezfowler/Monads" target="_blank"&gt;http://github.com/dezfowler/Monads&lt;/a&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-4642740032193268009?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/i3KSovZLpLM" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/4642740032193268009/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=4642740032193268009" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/4642740032193268009?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/4642740032193268009?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/i3KSovZLpLM/null-object-pattern-and-maybe-monad.html" title="The Null Object pattern and the Maybe monad" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/09/null-object-pattern-and-maybe-monad.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0IFQXk-fip7ImA9Wx5XGEw.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-6456376401938796334</id><published>2010-09-18T14:11:00.001+01:00</published><updated>2010-09-18T14:11:50.756+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-09-18T14:11:50.756+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="ASP.NET" /><category scheme="http://www.blogger.com/atom/ns#" term="Azure" /><title>ASP.NET custom error not shown in Azure</title><content type="html">&lt;p&gt;If you’re using a custom error handler in an ASP.NET Azure web role, for example, to return a branded error page you may find the custom page isn’t surfaced too the browser and instead you receive a standard IIS error. &lt;/p&gt;  &lt;p&gt;When your handler is setting the correct response status, relevant to the type of error e.g. 404, 500 etc, the default web role configuration means the error page content you supply will not be passed on. This is complicated by the DevFabric not using the same configuration i.e. your custom error page will appear as expected when you’re testing in DevFabric. &lt;/p&gt;  &lt;p&gt;The configuration setting requiring tweaking is in the system.webServer section; setting httpErrors’ &lt;a href="http://msdn.microsoft.com/en-us/library/ms690497(VS.90).aspx" target="_blank"&gt;existingResponse&lt;/a&gt; attribute to “PassThrough” will ensure that, if any content is supplied with the ASP.NET error response, it is returned to the browser.&lt;/p&gt;  &lt;pre&gt;&lt;code class="xml"&gt;&amp;lt;configuration&amp;gt;
  &amp;lt;system.webServer&amp;gt;
    &amp;lt;httpErrors existingResponse=&amp;quot;PassThrough&amp;quot;/&amp;gt;
  &amp;lt;/system.webServer&amp;gt;
&amp;lt;configuration&amp;gt;&lt;/code&gt;&lt;/pre&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-6456376401938796334?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/MdwWrNJW2DA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/6456376401938796334/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=6456376401938796334" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/6456376401938796334?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/6456376401938796334?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/MdwWrNJW2DA/aspnet-custom-error-not-shown-in-azure.html" title="ASP.NET custom error not shown in Azure" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/09/aspnet-custom-error-not-shown-in-azure.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CkcDQ3g5fSp7ImA9Wx5QEE8.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-4084090459043011892</id><published>2010-08-28T19:27:00.001+01:00</published><updated>2010-08-28T19:27:52.625+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-08-28T19:27:52.625+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>Aggregate full outer join in LINQ</title><content type="html">&lt;p&gt;I’ve recently been working on adding a feature to &lt;a href="http://codeofrob.com/" target="_blank"&gt;Rob Ashton&lt;/a&gt;’s &lt;a href="http://autopoco.codeplex.com/" target="_blank"&gt;AutoPoco&lt;/a&gt; project, a framework which enables dynamic creation of Plain Old CLR Object test data sets using realistic ranges of values. Rather than explicitly defining sets of objects in code, loading them from a database or deserializing them from a file the framework allows you to pre-define the make-up of the data set and then automatically generates the objects to meet your criteria.&lt;/p&gt;  &lt;p&gt;I had a requirement that, from some sets of possible values for particular properties of a type, I&amp;#160; needed to create an instance for every variation of those values. Defining all the variations manually would take along time, be difficult to maintain and error prone. Dynamic generation seemed the way to go and after checking with Rob whether this was already a feature of AutoPoco and finding out it wasn’t I proceeded to have a go at implementing a GetAllVariations method.&lt;/p&gt;  &lt;p&gt;The principal problem here is that we need to perform an operation analogous to a SQL full outer join on &lt;em&gt;n&lt;/em&gt; sets of values. For example, give the following type:&lt;/p&gt;  &lt;pre&gt;&lt;code class="c#"&gt;public class Blah
{
	public int Integer { get; set; }
	public string StringA { get; set; }
	public string StringB { get; set; }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and the possible values:&lt;/p&gt;

&lt;pre&gt;Integer: [ 1, 2, 3 ]
StringA: [ &amp;quot;hello&amp;quot;, &amp;quot;world&amp;quot; ]
StringB: [ &amp;quot;foo&amp;quot;, &amp;quot;bar&amp;quot; ]&lt;/pre&gt;

&lt;p&gt;the output should be 12 objects with the following property values:&lt;/p&gt;

&lt;table&gt;&lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;#&lt;/th&gt;

      &lt;th&gt;Integer&lt;/th&gt;

      &lt;th&gt;StringA&lt;/th&gt;

      &lt;th&gt;StringB&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;&lt;tbody&gt;
    &lt;tr&gt;
      &lt;th&gt;1&lt;/th&gt;

      &lt;td&gt;1&lt;/td&gt;

      &lt;td&gt;hello&lt;/td&gt;

      &lt;td&gt;foo&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;th&gt;2&lt;/th&gt;

      &lt;td&gt;1&lt;/td&gt;

      &lt;td&gt;hello&lt;/td&gt;

      &lt;td&gt;bar&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;th&gt;3&lt;/th&gt;

      &lt;td&gt;1&lt;/td&gt;

      &lt;td&gt;world&lt;/td&gt;

      &lt;td&gt;foo&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;th&gt;4&lt;/th&gt;

      &lt;td&gt;1&lt;/td&gt;

      &lt;td&gt;world&lt;/td&gt;

      &lt;td&gt;bar&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;th&gt;5&lt;/th&gt;

      &lt;td&gt;2&lt;/td&gt;

      &lt;td&gt;hello&lt;/td&gt;

      &lt;td&gt;foo&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;th&gt;6&lt;/th&gt;

      &lt;td&gt;2&lt;/td&gt;

      &lt;td&gt;hello&lt;/td&gt;

      &lt;td&gt;bar&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;th&gt;7&lt;/th&gt;

      &lt;td&gt;2&lt;/td&gt;

      &lt;td&gt;world&lt;/td&gt;

      &lt;td&gt;foo&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;th&gt;8&lt;/th&gt;

      &lt;td&gt;2&lt;/td&gt;

      &lt;td&gt;world&lt;/td&gt;

      &lt;td&gt;bar&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;th&gt;9&lt;/th&gt;

      &lt;td&gt;3&lt;/td&gt;

      &lt;td&gt;hello&lt;/td&gt;

      &lt;td&gt;foo&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;th&gt;10&lt;/th&gt;

      &lt;td&gt;3&lt;/td&gt;

      &lt;td&gt;hello&lt;/td&gt;

      &lt;td&gt;bar&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;th&gt;11&lt;/th&gt;

      &lt;td&gt;3&lt;/td&gt;

      &lt;td&gt;world&lt;/td&gt;

      &lt;td&gt;foo&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;th&gt;12&lt;/th&gt;

      &lt;td&gt;3&lt;/td&gt;

      &lt;td&gt;world&lt;/td&gt;

      &lt;td&gt;bar&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;&lt;/table&gt;

&lt;h3&gt;Achieving this using LINQ&lt;/h3&gt;

&lt;p&gt;A full outer join can be performed in LINQ as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;var A = new List&amp;lt;object&amp;gt;
	{
		1, 
		2,
		3,
	};

var B = new List&amp;lt;object&amp;gt;
	{
		&amp;quot;hello&amp;quot;,
		&amp;quot;world&amp;quot;,
	};

A.Join(B, r =&amp;gt; 0, r =&amp;gt; 0, (a, b) =&amp;gt; new List&amp;lt;object&amp;gt;{ a, b }).Dump();&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note: I’m using the LINQPad Dump() extension method here.&lt;/p&gt;

&lt;p&gt;Fairly straight forward, we just set the join values to zero which forces a set to be produced where every value in A is joined to every other value in B. Ordinarily the join result selector would create a new anonymous type but I’m creating a new List here for reasons that will become obvious in a second.&lt;/p&gt;

&lt;p&gt;We don’t know in advance how many sets of values we’re going to have, the user may want to set values for two or twenty properties. We need to be able to perform this same join for &lt;em&gt;n&lt;/em&gt; sets, we’ll be working with a collection of these value sets. We can achieve this by combining the join with an aggregate operation e.g.&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;List&amp;lt;List&amp;lt;object&amp;gt;&amp;gt; sources = new List&amp;lt;List&amp;lt;object&amp;gt;&amp;gt;
{
	new List&amp;lt;object&amp;gt;
	{
		1, 
		2,
		3,
	},
	new List&amp;lt;object&amp;gt;
	{
		&amp;quot;hello&amp;quot;,
		&amp;quot;world&amp;quot;,
	},
	new List&amp;lt;object&amp;gt;
	{
		&amp;quot;foo&amp;quot;,
		&amp;quot;bar&amp;quot;,
	},
};

sources.Aggregate(
 	Enumerable.Repeat(new List&amp;lt;object&amp;gt;(), 1),
	(a, d) =&amp;gt; a.Join(d, r =&amp;gt; 0, r =&amp;gt; 0, (f, g) =&amp;gt; new List&amp;lt;object&amp;gt;(f) { g })
).Dump();&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here &lt;var&gt;sources&lt;/var&gt; could contain any number of List objects and those List objects, containing the raw property values, can also contain any number of items. The output of the operation will be an enumeration over every variation of the values in sources, each represented as a List (in this case containing three items, one for each of the sources). We seed the Aggregate with what we expect to get out i.e. an IEnumerable of List objects. Our aggregating function is our join operation with a slight modification, our result selector creates a new List containing the result of the previous join (&lt;var&gt;f&lt;/var&gt;) and the uses the collection initializer syntax to add one additional item (&lt;var&gt;g&lt;/var&gt;), from the current set of values being joined on.&lt;/p&gt;

&lt;p&gt;A relatively complex operation reduced to, effectively, a one-liner using LINQ. Snazzy.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-4084090459043011892?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/XwvSBW4sjM4" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/4084090459043011892/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=4084090459043011892" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/4084090459043011892?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/4084090459043011892?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/XwvSBW4sjM4/aggregate-full-outer-join-in-linq.html" title="Aggregate full outer join in LINQ" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>2</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/08/aggregate-full-outer-join-in-linq.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A0QBRXc7fip7ImA9Wx5RFUw.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-4429180209191237275</id><published>2010-08-22T22:57:00.000+01:00</published><updated>2010-08-23T00:22:34.906+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-08-23T00:22:34.906+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".NET" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>Roll your own mocks with RealProxy</title><content type="html">&lt;p&gt;These days there are more than enough mocking frameworks to choose from but if you need something a bit different, or just fancy having a go at the problem as an exercise, creating your own is easier than you might think. You don’t need to go anywhere near IL generation for certain tasks as where are a couple of types in the Framework which can get us most of the way on their own. &lt;/p&gt;  &lt;p&gt;.NET 4.0 has the &lt;a href="http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx" target="_blank"&gt;DynamicObject&lt;/a&gt; class which can be used for this as it allows you to provide custom implementations for any method or property. However there is another class which has been in the Framework since 1.1 that can be used in a similar way.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.remoting.proxies.realproxy.aspx" target="_blank"&gt;RealProxy&lt;/a&gt; is meant for creating proxy classes for remoting however there’s no reason why we can’t make use of its proxy capabilities and forget the remoting part, instead providing our own mocking implementation. Lets look at a simple example.&lt;/p&gt;  &lt;h3&gt;If it looks like a duck but can't walk it's a lame duck&lt;/h3&gt;  &lt;p&gt;If you're using dependency injection and are writing your code defensively you'll probably have constructors which look something like this:&lt;/p&gt;  &lt;pre&gt;&lt;code class="c#"&gt;public MyClass(ISupplyConfiguration config, ISupplyDomainInfo domain, ISupplyUserData userRepository)
{
 if(config == null) throw new ArgumentNullException(&amp;quot;config&amp;quot;);
 if(domain == null) throw new ArgumentNullException(&amp;quot;domain&amp;quot;);
 if(userRepository == null) throw new ArgumentNullException(&amp;quot;userRepository&amp;quot;);
 // ...assignments...
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The unit test for whether this constructor correctly throws ArgumentNullExceptions when it's expected to will require at least some implementation of ISupplyConfiguration and ISupplyDomainInfo in order to successfully test the last check for userRepository.&lt;/p&gt;

&lt;p&gt;All we need here is something that looks like the correct interface; it needn't be a concrete implementation or work as, for these tests, all we need is for it to not be null. Here’s how we could achieve this with RealProxy and relatively little code.&lt;/p&gt;

&lt;p&gt;First we create a class inheriting from the abstract RealProxy:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;public class RubbishProxy : System.Runtime.Remoting.Proxies.RealProxy
{
 public RubbishProxy(Type type) : base(type) {}

 public override System.Runtime.Remoting.Messaging.IMessage Invoke(System.Runtime.Remoting.Messaging.IMessage msg)
 {
  throw new NotImplementedException();
 }

 /// &amp;lt;summary&amp;gt;
 /// Creates a transparent proxy for type &amp;lt;typeparamref name=&amp;quot;T&amp;quot;/&amp;gt; and 
 /// returns it.
 /// &amp;lt;/summary&amp;gt;
 /// &amp;lt;typeparam name=&amp;quot;T&amp;quot;&amp;gt;&amp;lt;/typeparam&amp;gt;
 /// &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;
 public static T Make&amp;lt;T&amp;gt;()
 {
  return (T)new RubbishProxy(typeof(T)).GetTransparentProxy();
 }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That's all, effectively just the boiler plate implementation code for the abstract class with one constructor specified and a static generic method for ease of use. We can then use it in our test method like so:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ExampleRealWorldTest_EnsureExceptionOnNullConfig()
{
 var myClass = new MyClass(null, null, null);
}

[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ExampleRealWorldTest_EnsureExceptionOnNullDomain()
{
 var config = RubbishProxy.Make&amp;lt;ISupplyConfiguration&amp;gt;();
 var myClass = new MyClass(config, null, null);
}

[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ExampleRealWorldTest_EnsureExceptionOnNullRepository()
{
 var config = RubbishProxy.Make&amp;lt;ISupplyConfiguration&amp;gt;();
 var domain = RubbishProxy.Make&amp;lt;ISupplyDomainInfo&amp;gt;();
 var myClass = new MyClass(config, domain, null);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Not bad for one line of code. How about something more complex?&lt;/p&gt;

&lt;h3&gt;Making a mockery of testing&lt;/h3&gt;

&lt;p&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.remoting.proxies.realproxy.invoke.aspx" target="_blank"&gt;Invoke&lt;/a&gt; method we overrode in RubbishProxy can perform any action we like including checking arguments, returning values and throwing exceptions. In mocking frameworks, the most common method of setting up this behaviour is using a fluent interface e.g.&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;[Test]
public void ReadOnlyPropertyReturnsCorrectValue()
{
	var mock = new Mock&amp;lt;IBlah&amp;gt;();
	mock.When(o =&amp;gt; o.ReadOnly).Return(&amp;quot;thing&amp;quot;);
	var blah = mock.Object;
	Assert.AreEqual(&amp;quot;thing&amp;quot;, blah.ReadOnly);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here the When call captures &lt;var&gt;o.ReadOnly&lt;/var&gt; as an expression, determining which member was the invokation target and returning a Call object. The Call object is then used to set up a return value as in the example above, or to check the passed arguments (CheckArguments) or throw an exception (Throw). It can also be set up to ignore the call or, in the case of a method call, to apply any one of those previous behaviours to only when particular arguments are passed in.&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;[Test]
[ExpectedException(typeof(ForcedException))]
public void MethodCallThrows()
{
	var mock = new Mock&amp;lt;IBlah&amp;gt;();
	mock.When(o =&amp;gt; o.GetThing()).Throw();
	var blah = mock.Object;
	int i = blah.GetThing();
}

[Test]
public void MethodCallValid()
{
	var mock = new Mock&amp;lt;IBlah&amp;gt;();
	mock.When(o =&amp;gt; o.DoThing(5)).CheckArguments();
	var blah = mock.Object;
	blah.DoThing(5);
}

[Test]
[ExpectedException(typeof(MockException))]
public void MethodCallInvalid()
{
	var mock = new Mock&amp;lt;IBlah&amp;gt;();
	mock.When(o =&amp;gt; o.DoThing(5)).CheckArguments();
	var blah = mock.Object;
	blah.DoThing(4);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Source code for the example mock framework is up on GitHub here:
  &lt;br /&gt;&lt;a href="http://github.com/dezfowler/LiteMock"&gt;http://github.com/dezfowler/LiteMock&lt;/a&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-4429180209191237275?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/OnDmj9qb7bA" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/4429180209191237275/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=4429180209191237275" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/4429180209191237275?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/4429180209191237275?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/OnDmj9qb7bA/roll-your-own-mocks-with-realproxy.html" title="Roll your own mocks with RealProxy" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/08/roll-your-own-mocks-with-realproxy.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEMEQ304cCp7ImA9Wx5SFUo.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-2343776575094102666</id><published>2010-08-11T23:32:00.000+01:00</published><updated>2010-08-12T01:20:02.338+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-08-12T01:20:02.338+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="MVC" /><category scheme="http://www.blogger.com/atom/ns#" term=".NET" /><category scheme="http://www.blogger.com/atom/ns#" term="ASP.NET" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>Model binding and localization in ASP.NET MVC2</title><content type="html">&lt;p&gt;When creating an MVC site catering for different cultures, one option for persisting the culture value from one page to the next is by using an extra route value containing some form of identifier for the locale e.g.&lt;/p&gt;  &lt;p&gt;/en-gb/Home/Index    &lt;br /&gt;/en-us/Cart/Checkout     &lt;br /&gt;/it-it/Product/Detail/1234 &lt;/p&gt;  &lt;p&gt;Here just using the Windows standard culture names based on RFC 4646 but you could use some other standard or your own custom codes. This method doesn’t rely on sessions or cookies and also has the advantage that the site can be spidered in each supported language.&lt;/p&gt;  &lt;p&gt;Creating a base controller class for your site allows you to override one of its methods in order to set your current culture. For example if you amend your route configuration to &lt;var&gt;&amp;quot;{locale}/{controller}/{action}/{id}&amp;quot;&lt;/var&gt; you could do the following:&lt;/p&gt;  &lt;pre&gt;&lt;code class="c#"&gt;string locale = RouteData.GetRequiredString(&amp;quot;locale&amp;quot;);
CultureInfo culture = CultureInfo.CreateSpecificCulture(locale);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It's important to set both CurrentCulture and CurrentUICulture as ResourceManager, used for retrieving values form localized .resx files, will refer to CurrentUICulture whereas most other formatting routines use CurrentCulture.&lt;/p&gt;

&lt;p&gt;Once our culture is set, when we output values in our views ResourceManager can pick up our culture specific text translations from the correct .resx file and dates and currency values will be correctly formatted. &lt;var&gt;String.Format(&amp;quot;{0:s}&amp;quot;, DateTime.Now)&lt;/var&gt;, with &amp;quot;s&amp;quot; being the format string for a short date, will produce mm/dd/yyyy for en-US versus dd/mm/yyyy for en-GB.&lt;/p&gt;

&lt;p&gt;This isn't the end of the story however, the problem arises of where in the controller do you perform your culture setting. It can't happen in the constructor because the route data isn't yet available so instead we could put it in an override of OnActionExecuting. This will seem to work fine for values output in your views but you come across a gotcha within model binding. Create a textbox in a form which binds to a DateTime and you'll end up with the string value being parsed using the default culture of the server. Using the US and UK dates example where your server's default culture is US but your site is currently set to UK. If you try to enter a date of 22/01/2010 you'll get a model validation error because it's being parsed as the US mm/dd/yyyy and 22 isn't a valid value for the month. Model binding happens before OnActionExecuting so that's no good.&lt;/p&gt;

&lt;p&gt;A bit of digging around in Reflector and the Initialize method comes out as probably the best candidate for this as it is where the controller first receives route data and it occurs before model binding. We end up with something like (exception handling omitted for brevity):&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;protected override void Initialize(RequestContext requestContext) 
{
    base.Initialize(requestContext);
    string locale = RouteData.GetRequiredString(&amp;quot;locale&amp;quot;);
    CultureInfo culture = CultureInfo.CreateSpecificCulture(locale);
    Thread.CurrentThread.CurrentCulture = culture;
    Thread.CurrentThread.CurrentUICulture = culture;
 }&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Both model binding and output of values will now be using the correct culture.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-2343776575094102666?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/tW5Txd0ArTU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/2343776575094102666/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=2343776575094102666" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/2343776575094102666?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/2343776575094102666?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/tW5Txd0ArTU/model-binding-and-localization-in.html" title="Model binding and localization in ASP.NET MVC2" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/08/model-binding-and-localization-in.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUIGQXs6fSp7ImA9WxFaFEQ.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-2725914509766936438</id><published>2010-07-18T11:30:00.001+01:00</published><updated>2010-07-18T23:52:00.515+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-07-18T23:52:00.515+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".NET" /><category scheme="http://www.blogger.com/atom/ns#" term="design patterns" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>Creating a light-weight visitor, fluently in C#</title><content type="html">&lt;p&gt;In object-oriented programming a common problem is performing some conditional logic based on the type of an object at run-time. For example, one form you may come across is:&lt;/p&gt;  &lt;pre&gt;&lt;code class="c#"&gt;public void DoStuff(MemberInfo memberInfo)
{
 EventInfo eventInfo = memberInfo as EventInfo;
 if(eventInfo != null)
 {
  // do something
  return;
 }

 MethodInfo methodInfo = memberInfo as MethodInfo;
 if(methodInfo != null)
 {
  // do something
  return;
 }

 PropertyInfo propertyInfo = memberInfo as PropertyInfo;
 if(propertyInfo != null)
 {
  // do something
  return;
 }

 throw new Exception(&amp;quot;Not supported.&amp;quot;);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Drawbacks to this being you have to wrap the whole thing in a method to make use of the &amp;quot;bomb out&amp;quot; return statements and it's quite a lot of code repetition which, as I’ve talked about previously, I'm not a fan of. Another example is a dictionary type-&amp;gt;operation lookup:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;// set up some type to operation mappings
static readonly Dictionary&amp;lt;Type, Action&amp;lt;MemberInfo&amp;gt;&amp;gt; operations = new Dictionary&amp;lt;Type, Action&amp;lt;MemberInfo&amp;gt;&amp;gt;();

// probably inside the static constructor...
operations.Add(typeof(EventInfo), memberInfo =&amp;gt; 
{
 EventInfo eventInfo = (EventInfo)memberInfo;
 // do somthing 
});
operations.Add(typeof(MethodInfo), memberInfo =&amp;gt;
{
 MethodInfo methodInfo = (MethodInfo)memberInfo;
 // do something
});
operations.Add(typeof(PropertyInfo), memberInfo =&amp;gt;
{
 PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
 // do something
});

// use it like this...
Type type = memberInfo.GetType();
Type matchingType = operations.Keys.FirstOrDefault(t =&amp;gt; t.IsAssignableFrom(type));
if(matchingType != null)
{
 operations[matchingType](memberInfo);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The major drawback with this method is that you have to use IsAssignableFrom otherwise it doesn't match inherited types. In fact, the above example doesn't work if you just look up the type of memberInfo directly because we'll get types derived from EventInfo etc, not those types themselves. We also still need to cast to the type we want to work with ourselves and enumerating the dictionary isn’t ideal from a performance point of view.&lt;/p&gt;

&lt;p&gt;The GoF pattern for solving this is the &lt;a href="http://en.wikipedia.org/wiki/Visitor_pattern"&gt;visitor&lt;/a&gt; which I’ve &lt;a href="http://derek-says.blogspot.com/2008/05/implicit-polymorphism-and-lazy.html"&gt;blogged about&lt;/a&gt; in the past however this is rather heavy duty, especially if your &amp;quot;do something&amp;quot; is only one line. It is much more performant than the alternatives though, as it’s using low level logic inside the run-time to make the decision about which method to call, so that should be a consideration.&lt;/p&gt;

&lt;p&gt;Then next best alternative to the proper visitor is the first ...as...if...return... form but we can wrap it up quite nicely with a couple of extension methods to cut down on the amount of code we have to write. Here’s a trivial example trying to retrieve the parameters for either a method or a property. Depending on the type we need to call a different method so we identify that method using a fluent visitor:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;private Type[] GetParamTypes(MemberInfo memberInfo)
{
 Func&amp;lt;ParameterInfo[]&amp;gt; paramGetter = null;

 memberInfo
  .As&amp;lt;MethodInfo&amp;gt;(method =&amp;gt; paramGetter = method.GetParameters)
  .As&amp;lt;PropertyInfo&amp;gt;(property =&amp;gt; paramGetter = property.GetIndexParameters)
  .As&amp;lt;Object&amp;gt;(o =&amp;gt; { throw new Exception(&amp;quot;Unsupported member type.&amp;quot;); });

 return paramGetter().Select(pi =&amp;gt; pi.ParameterType).ToArray();
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The As extension attempts to cast “this” as the type specified by the type parameter T and if successful calls the supplied delegate. The overload used in the example above will skip the remaining As calls once one has been successful. There is a second overload which takes a Func&amp;lt;T, bool&amp;gt; rather than an Action&amp;lt;T&amp;gt; and will continue to try the next As if false is returned from the Func. The last As call, by specifying Object as the type, is a catch all and allows providing a default implementation or catering for an error case as shown above. The extensions are implemented like so:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;/// &amp;lt;summary&amp;gt;
/// Tries to cast an object as type &amp;lt;typeparamref name=&amp;quot;T&amp;quot;/&amp;gt; and if successful 
/// calls &amp;lt;paramref name=&amp;quot;operation&amp;quot;/&amp;gt;, passing it in.
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;typeparam name=&amp;quot;T&amp;quot;&amp;gt;Type to attempt to cast &amp;lt;paramref name=&amp;quot;o&amp;quot;/&amp;gt; as&amp;lt;/typeparam&amp;gt;
/// &amp;lt;param name=&amp;quot;o&amp;quot;&amp;gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;operation&amp;quot;&amp;gt;Operation to be performed if cast is successful&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;
/// Null if the object cast was successful, 
/// otherwise returns the object for chaining purposes.
/// &amp;lt;/returns&amp;gt;
public static object As&amp;lt;T&amp;gt;(this object o, Action&amp;lt;T&amp;gt; operation)
 where T : class
{
 return o.As&amp;lt;T&amp;gt;(obj =&amp;gt; { operation(obj); return true; });
}

/// &amp;lt;summary&amp;gt;
/// Tries to cast an object as type &amp;lt;typeparamref name=&amp;quot;T&amp;quot;/&amp;gt; and if successful 
/// calls &amp;lt;paramref name=&amp;quot;operation&amp;quot;/&amp;gt;, passing it in.
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;typeparam name=&amp;quot;T&amp;quot;&amp;gt;&amp;lt;/typeparam&amp;gt;
/// &amp;lt;param name=&amp;quot;o&amp;quot;&amp;gt;&amp;lt;/param&amp;gt;
/// &amp;lt;param name=&amp;quot;operation&amp;quot;&amp;gt;Operation to be performed if cast is successful, must return 
/// a boolean indicating whether the object was handled.&amp;lt;/param&amp;gt;
/// &amp;lt;returns&amp;gt;
/// Null if the object cast was successful and &amp;lt;paramref name=&amp;quot;operation&amp;quot;/&amp;gt; returned true, 
/// otherwise returns the object for chaining purposes.
/// &amp;lt;/returns&amp;gt;
public static object As&amp;lt;T&amp;gt;(this object o, Func&amp;lt;T, bool&amp;gt; operation)
 where T : class
{
 if (Object.ReferenceEquals(o, null)) return null;

 T t = o as T;
 if (!Object.ReferenceEquals(t, null))
 {
  if (operation(t)) return null;
 }
 return o;
}&lt;/code&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-2725914509766936438?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/eO8oscQ1FKM" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/2725914509766936438/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=2725914509766936438" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/2725914509766936438?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/2725914509766936438?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/eO8oscQ1FKM/creating-light-weight-visitor-fluently.html" title="Creating a light-weight visitor, fluently in C#" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/07/creating-light-weight-visitor-fluently.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0UHRH06fSp7ImA9WxFaEUg.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-6955399448171294944</id><published>2010-07-14T23:37:00.001+01:00</published><updated>2010-07-15T00:47:15.315+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-07-15T00:47:15.315+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".NET" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="SQL Server" /><title>UTC gotchas in .NET and SQL Server</title><content type="html">&lt;p&gt;After doing some work with &lt;a href="http://msdn.microsoft.com/en-us/library/system.datetime.aspx" target="_blank"&gt;DateTime&lt;/a&gt; recently I stumbled across the interesting behaviour that a DateTime which is DateTimeKind.Unspecified will be treated as a DateTimeKind.Local whenever you try to perform some operation upon it. You get an “unspecified” DateTime whenever you don’t explicitly say it is Utc or Local. This makes sense because, when you do the following, in most cases what you intended was to use local time:&lt;/p&gt;  &lt;pre&gt;&lt;code class="c#"&gt;DateTime d1 = new DateTime(2010, 07, 01, 12, 0 ,0, 0);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If the current timezone is UTC +01:00 here's what I get when working with the DateTime created above:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;d1.Kind; // =&amp;gt; Unspecified
d1; // =&amp;gt; 01/07/2010 12:00:00
d1.ToUniversalTime(); // =&amp;gt; 01/07/2010 11:00:00
TimeZoneInfo.Local.GetUtcOffset(d1); // =&amp;gt; 01:00:00&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note it’s applied an offset when calculating the UTC value which as we can see for clarification is +1 hour. &lt;/p&gt;

&lt;p&gt;If what we actually wanted was a UTC time we need to explicitly specify the kind e.g.&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;DateTime d2 = new DateTime(2010, 07, 01, 12, 0 ,0, 0, DateTimeKind.Utc);
DateTime d2 = DateTime.UtcNow;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you need to work with timezones other than UTC or the system timezone then you'll want to use &lt;a href="http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx" target="_blank"&gt;DateTimeOffset&lt;/a&gt; rather than DateTime.&lt;/p&gt;

&lt;h3&gt;SQL Server and SqlDataReader&lt;/h3&gt;

&lt;p&gt;Another interesting gotcha arising from this is that the SQL Server &lt;a href="http://msdn.microsoft.com/en-us/library/ms187819.aspx" target="_blank"&gt;datetime&lt;/a&gt; data type is also timezone agnostic. Any datetime values retrieved through the SqlDataReader will be an “unspecified” kind DateTime. This means that, even if you're correctly using the C# DateTime.UtcNow or the SQL GETUTCDATE() to produce the values in the database, when you try to retrieve them they will be shifted incorrectly according to the local timezone. Yikes!&lt;/p&gt;

&lt;p&gt;There are two ways to deal with this.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h4&gt;DateTime.SpecifyKind()&lt;/h4&gt;

&lt;p&gt;The first is in C# using &lt;a href="http://msdn.microsoft.com/en-us/library/system.datetime.specifykind.aspx" target="_blank"&gt;DateTime.SpecifyKind()&lt;/a&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;DateTime d3 = DateTime.SpecifyKind(d1, DateTimeKind.Utc);
d3.Kind; // =&amp;gt; Utc
d3; // =&amp;gt; 01/07/2010 12:00:00
d3.ToUniversalTime(); // =&amp;gt; 01/07/2010 12:00:00&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which could be wrapped up in an extension method for ease of use e.g.&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;public static class SqlDataReaderExtensions
{
 public static DateTime GetDateTimeUtc(this SqlDataReader reader, string name)
 {
  int fieldOrdinal = reader.GetOrdinal(name);
  DateTime unspecified = reader.GetDateTime(fieldOrdinal);
  return DateTime.SpecifyKind(unspecified, DateTimeKind.Utc);
 }
}&lt;/code&gt;&lt;/pre&gt;

&lt;h4&gt;SQL Server 2008 datetimeoffset&lt;/h4&gt;

&lt;p&gt;If you're using SQL Server 2008 you have the option of using the &lt;a href="http://msdn.microsoft.com/en-us/library/bb630289.aspx" target="_blank"&gt;datetimeoffset&lt;/a&gt; data type instead. This will store the +00:00 timezone internally and the SqlDataReader will then retrieve the value correctly as a DateTimeOffset. No need to muck about with Kind.&lt;/p&gt;

&lt;p&gt;If you have an existing database using datetime you can CAST these as a datetimeoffset in your query which usefully uses an offset of +00:00 in this case. (It treats &amp;quot;unspecified&amp;quot; as UTC – tut!)&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-6955399448171294944?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/eHJWtCN9b-Q" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/6955399448171294944/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=6955399448171294944" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/6955399448171294944?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/6955399448171294944?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/eHJWtCN9b-Q/utc-gotchas-in-net-and-sql-server.html" title="UTC gotchas in .NET and SQL Server" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>2</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/07/utc-gotchas-in-net-and-sql-server.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEQMQX4-fyp7ImA9WxFWE08.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-2408335472932780206</id><published>2010-05-31T16:54:00.000+01:00</published><updated>2010-05-31T17:13:00.057+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-05-31T17:13:00.057+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".NET" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><title>JavaScript-style Substring in C#</title><content type="html">&lt;p&gt;One thing that really bugs me when writing code is having to use unnecessary extra constructs to avoid exceptions or useless default values emerging. One such situation is trimming a string to a particular length e.g.&lt;/p&gt;  &lt;pre&gt;&lt;code class="c#"&gt;string sentence = &amp;quot;The quick brown fox jumps over the lazy dog&amp;quot;;
string firstFifty = sentence.Substring(0, 50);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I want the first 50 characters from the sentence but in this example we get an ArgumentOutOfRangeException because there aren’t 50 characters in sentence. Not too helpful and it's an easy mistake to make. To avoid the exception we have to do this:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;firstFifty = sentence.Length &amp;lt; 50 ? sentence : sentence.Substring(0, 50);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Yikes! That’s a lot of extra rubbish when all I want is the equivalent of LEFT(sentence, 50) in SQL.&lt;/p&gt;

&lt;p&gt;We can easily wrap this up in a &amp;quot;Left&amp;quot; method but chances are we’re going to need a “Right” too so instead we can go down the route JavaScript takes with its &amp;quot;slice&amp;quot; function. JavaScript’s string slice can take one integer argument which, if positive, returns characters from the start of the string and, if negative, returns characters from the end of the string. Adding an overload to allow it to take a padding character is probably sensible too. The end result looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;firstFifty = sentence.Slice(50);
// &amp;quot;The quick brown fox jumps over the lazy dog&amp;quot;
	
string firstTen = sentence.Slice(10);
// &amp;quot;The quick &amp;quot;

string lastTen = sentence.Slice(-10);
// &amp;quot;e lazy dog&amp;quot;

firstFifty = sentence.Slice(50, '=');
// &amp;quot;The quick brown fox jumps over the lazy dog==============&amp;quot;

string lastFifty = sentence.Slice(-50, '=');
// &amp;quot;==============The quick brown fox jumps over the lazy dog&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A lot more concise and quite useful.&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;public static class StringExtensions
{
   /// &amp;lt;summary&amp;gt;
   /// Returns a portion of the String value. If value has Length longer than 
   /// maxLength then it is trimmed otherwise value is simply returned.
   /// &amp;lt;/summary&amp;gt;
   /// &amp;lt;returns&amp;gt;
   /// String whose Length will be at most equal to maxLength.
   /// &amp;lt;/returns&amp;gt;
   public static string Slice(this string value, int maxLength)
   {
      if (value == null) throw new ArgumentNullException(&amp;quot;value&amp;quot;);
      
      int start = 0;
      if (maxLength &amp;lt; 0)
      {
         start = value.Length + maxLength;
         maxLength = Math.Abs(maxLength);
      }
      return value.Length &amp;lt; maxLength ? value : value.Substring(start, maxLength);
   }
   
   /// &amp;lt;summary&amp;gt;
   /// Returns a portion of the String value. If value has Length longer than 
   /// length then it is trimmed otherwise value is padded to length with 
   /// shortfallPaddingChar.
   /// &amp;lt;/summary&amp;gt;
   /// &amp;lt;returns&amp;gt;
   /// String whose Length will be equal to length.
   /// &amp;lt;/returns&amp;gt;
   public static string Slice(this string value, int length, char shortfallPaddingChar)
   {
      if (value == null) throw new ArgumentNullException(&amp;quot;value&amp;quot;);
      
      string part = value.Slice(length);
      int abslen = Math.Abs(length);
      if(abslen &amp;gt; part.Length)
      {
         part = length &amp;lt; 0 ? part.PadLeft(abslen, shortfallPaddingChar) : part.PadRight(abslen, shortfallPaddingChar);
      }
      return part;
   }
}&lt;/code&gt;&lt;/pre&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-2408335472932780206?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/ZHcgHeRn3sI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/2408335472932780206/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=2408335472932780206" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/2408335472932780206?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/2408335472932780206?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/ZHcgHeRn3sI/nicer-substring-in-c-with-extension.html" title="JavaScript-style Substring in C#" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/05/nicer-substring-in-c-with-extension.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CU4FQHc6eSp7ImA9WxFXF0k.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-4093108302409589784</id><published>2010-05-25T21:50:00.000+01:00</published><updated>2010-05-25T00:31:51.911+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-05-25T00:31:51.911+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".NET" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="Silverlight" /><title>Silverlight 3 Behavior causing XAML error</title><content type="html">&lt;p&gt;A recent XAML error I received from a Silverlight Behavior had me going round in circles trying to find the cause for quite a while. I was getting an AG_E_PARSER_BAD_PROPERTY_VALUE in code similar to the following:&lt;/p&gt;  &lt;pre&gt;&lt;code class="xml"&gt;&amp;lt;canvas x:name=&amp;quot;Blah&amp;quot;&amp;gt;
   &amp;lt;i:Interaction.Behaviors&amp;gt;
      &amp;lt;myapp:SpecialBehavior Source=&amp;quot;{Binding SomeProperty}&amp;quot; /&amp;gt;
   &amp;lt;/i:Interaction.Behaviors&amp;gt;
   ...
&amp;lt;/canvas&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The error identified the myapp:SpecialBehavior line as the culprit but didn't give me any further information so I proceeded to try and debug the binding to see what was going wrong. This didn’t shed any light on the cause, the binding was being created fine – the error was occurring later on.&lt;/p&gt;

&lt;p&gt;This had me stumped for a couple of hours – I even tried setting up Framework source stepping only to find that the Silverlight 3 symbols weren’t yet available. In the end I stumbled upon the answer by chance – looking at the Canvas class in Reflector I noticed that it didn’t inherit from Control, only FrameworkElement via Panel. A quick check of my Behavior code and I found this:&lt;/p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;public class SpecialBehavior : Behavior&amp;lt;Control&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It was the Behavior itself that was invalid in the Interaction.Behaviors property due to the incompatible type parameter. I changed Control to FrameworkElement and everything started working fine.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-4093108302409589784?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/cl5qXBAFDUw" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/4093108302409589784/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=4093108302409589784" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/4093108302409589784?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/4093108302409589784?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/cl5qXBAFDUw/silverlight-3-behavior-causing-xaml.html" title="Silverlight 3 Behavior causing XAML error" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/05/silverlight-3-behavior-causing-xaml.html</feedburner:origLink></entry><entry gd:etag="W/&quot;A0IAQnszfSp7ImA9WxFQGUs.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-3791189582590131597</id><published>2010-05-16T01:25:00.001+01:00</published><updated>2010-05-16T01:25:43.585+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-05-16T01:25:43.585+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".NET" /><category scheme="http://www.blogger.com/atom/ns#" term="C#" /><category scheme="http://www.blogger.com/atom/ns#" term="Silverlight" /><title>Running UI operations sequentially in Silverlight</title><content type="html">&lt;p&gt;I've been playing around with Silverlight recently and have come across a requirement of needing to wait for the UI to do something before continuing. For example I have a UI with elements such and an image and text bound to properties of a model object. When the model object changes the interface updates to reflect this change but I need to perform an &amp;quot;unload&amp;quot; transition just before the model changes and a &amp;quot;load&amp;quot; transition just after it had changes.&lt;/p&gt;  &lt;p&gt;Instead of this:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh6.ggpht.com/_EuFsZMY5ZNU/S-87f-sbvGI/AAAAAAAAAkU/CqhDAWFKjoM/s1600-h/before%5B6%5D.png"&gt;&lt;img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="before" border="0" alt="before" src="http://lh4.ggpht.com/_EuFsZMY5ZNU/S-87gSaTQUI/AAAAAAAAAkY/HS405TBICco/before_thumb%5B4%5D.png?imgmax=800" width="322" height="94" /&gt;&lt;/a&gt; I want this:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh3.ggpht.com/_EuFsZMY5ZNU/S-87g6EcarI/AAAAAAAAAkc/jY0b72HNSbM/s1600-h/after%5B8%5D.png"&gt;&lt;img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="after" border="0" alt="after" src="http://lh4.ggpht.com/_EuFsZMY5ZNU/S-87hsnqv9I/AAAAAAAAAkg/1RqjOT_EoYo/after_thumb%5B6%5D.png?imgmax=800" width="485" height="206" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The orange arrows representing the transitions.&lt;/p&gt;  &lt;p&gt;I considered having BeforeChange and AfterChange events, hooking my transition storyboards up to them and then firing them in the model setter. The trouble with this is that the storyboards will be playing in a separate thread so as soon as the BeforeChange one starts our code will have moved on and fired the AfterChange one. The result will be that we'll never see the &amp;quot;before&amp;quot; transition which will ruin the whole effect.&lt;/p&gt;  &lt;p&gt;Mike Taulty &lt;a href="http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2008/04/13/10328.aspx"&gt;posted&lt;/a&gt; about this same issue in 2008 highlighting that, to achieve the correct result, we end up needing to chain our code together using the Completed events of our storyboards. His solution was using some classes to wrap this up and I've taken a similar approach apart from that I have the sequence defined fluently and included the option of using visual states rather than explicitly defined storyboards.&lt;/p&gt;  &lt;pre&gt;&lt;code class="c#"&gt;private Album CurrentAlbum
{
   get
   {
      return this.DataContext as Album;
   }
   set 
   {
      if (CurrentAlbum != value)
      {
         new Sequence()
            .GoTo(this, LayoutRoot, &amp;quot;VisualStateGroup&amp;quot;, &amp;quot;AlbumUnloaded&amp;quot;)
            .Execute(() =&amp;gt;
            {
               this.DataContext = value;
            })
            .GoTo(this, LayoutRoot, &amp;quot;VisualStateGroup&amp;quot;, &amp;quot;AlbumLoaded&amp;quot;)
            .Run();		
      }
   }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It ends up being a lot quicker to write the code and I think it's quite obvious by reading it what will happen. If the visual state group or states aren't defined then only the inner assignment occurs.&lt;/p&gt;

&lt;p&gt;The source for the Sequence class is a bit big for this post so the gist is here: &lt;a href="http://gist.github.com/402514" target="_blank"&gt;Sequence.cs&lt;/a&gt;&amp;#160;&lt;/p&gt;

&lt;h4&gt;Considerations&lt;/h4&gt;
&lt;dl&gt;&lt;dt&gt;Deferred execution &lt;/dt&gt;&lt;dd&gt;The storyboard or visual state change Completed event we're waiting for may never happen - do we try to execute the next steps anyway? I’ve taken the approach of firing off the next step in the destructor of the class however it may make more sense to set some arbitrary timeout so if the transition hasn’t completed after say 10 seconds we fire off the next step anyway.&lt;/dd&gt;&lt;dt&gt;Reuse &lt;/dt&gt;&lt;dd&gt;Should we allow a sequence to be created once and then reused many times - we could have an overload of Run() that takes a context object and passes it on to each of the steps. Could run into issues with people using closures like I do in the example. I’ve stuck with single use in the class, throwing an exception if Run() is called a second time.&lt;/dd&gt;&lt;/dl&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-3791189582590131597?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/XRfi0iu9lp8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/3791189582590131597/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=3791189582590131597" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/3791189582590131597?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/3791189582590131597?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/XRfi0iu9lp8/running-ui-operations-sequentially-in.html" title="Running UI operations sequentially in Silverlight" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh4.ggpht.com/_EuFsZMY5ZNU/S-87gSaTQUI/AAAAAAAAAkY/HS405TBICco/s72-c/before_thumb%5B4%5D.png?imgmax=800" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/05/running-ui-operations-sequentially-in.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0QGQXo4eyp7ImA9WxBVGEo.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-7315270357634206266</id><published>2010-02-22T20:42:00.000Z</published><updated>2010-02-22T20:42:00.433Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-02-22T20:42:00.433Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="DLNA" /><title>DLNA in the real world</title><content type="html">&lt;p&gt;In my &lt;a href="http://derek-says.blogspot.com/2007/01/freeing-your-digital-media.html"&gt;very first post of 2007&lt;/a&gt; I talked about the promise of &lt;acronym title="Digital Living Network Alliance"&gt;DLNA&lt;/acronym&gt; and that with compliant devices you could enjoy freedom to consume your digital media wherever or however you wanted. Unfortunately, as I have experienced first hand, the reality is far from the convenient ideal that DLNA professes to provide.&lt;/p&gt;

&lt;p&gt;&lt;img style="float:right; margin:0 0 10px 10px;" src="http://3.bp.blogspot.com/_EuFsZMY5ZNU/S3if6XHDKUI/AAAAAAAAAkA/KVQhKgIHvwk/s400/DLNA_cert_color.gif" border="0" alt="" /&gt;I currently have a &lt;a href="http://www.linksysbycisco.com/UK/en/products/NMH410"&gt;Linksys Media Hub NMH410&lt;/a&gt; and a &lt;a href="http://www.sony.co.uk/product/t32-v-series/kdl-32v5500"&gt;Sony Bravia 32V5500&lt;/a&gt; television connected to my network. Both are DLNA-compliant devices and support streaming pictures, audio and video over the network. The Media Hub runs &lt;a href="http://www.twonkymedia.com"&gt;Twonky Media Server&lt;/a&gt; which, to all intents and purposes, is the reference implementation of a DLNA server. The Bravia has a DLNA compatible renderer, similar to the PS3 which can also stream content over a network.&lt;/p&gt;

&lt;p&gt;The trouble is that, while I can view photos from the Media Hub on the TV fine, both audio and video fail to work. I can browse audio files on the Media Hub however only the first 20 seconds of each file will play and after that I get a "Playback not available" error. Video files on the other hand are a non-starter and can't be browsed or played.&lt;/p&gt;

&lt;p&gt;I suspected my network or the format of files I was trying to stream may have been to blame but after a (lengthy) process of elimination I took both out of the equation. Installing Twonky Media Manager on my PC, which acts as both a server and client, I was able to stream all the content types off the Media Hub fine and was also able to stream content to the TV fine. It was just the particular version of Twonky on the Media Hub and the renderer in the TV that didn't like each other.&lt;/p&gt;

&lt;p&gt;Threads on a fair few forums across the net show that lots of folk are experiencing the same issues:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://forums.linksysbycisco.com/linksys/board/message?board.id=TechnicalSupport2&amp;thread.id=806&amp;view=by_date_ascending&amp;page=1"&gt;Playback not available on Sony KDL-37V5500&lt;/a&gt; on Linksys' forum&lt;/li&gt;

&lt;li&gt;&lt;a href="http://www.avforums.com/forums/sony-owners-forum/1009564-kdl40w5500-nas.html"&gt;KDL40W5500 and NAS&lt;/a&gt; on AVForums&lt;/li&gt;

&lt;li&gt;&lt;a href="http://www.twonkyforum.com/viewtopic.php?f=12&amp;t=6277"&gt;Sony Bravia TVs and Twonky on NAS not working together&lt;/a&gt; on Twonky's forum&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I found this all very odd as surely the DLNA badge on both devices ensures that they're compatible and will have no trouble in streaming the content. This is apparently not the case and Sony themselves confirmed this to me by e-mail saying:&lt;/p&gt;

&lt;blockquote&gt;Unfortunately the KDL-32V5500 Media compatibility results with DLNA Media servers are as follows for Twonky Media 1.0.0.115 you can play back JPG formats. This information is the result of tests performed in Sony laboratories.&lt;/blockquote&gt;

&lt;p&gt;In other words their DLNA-compliance for that particular server only extends to pictures. Quite how they can call this compliance I don't know but luckily they have a nice get out clause:&lt;/p&gt;

&lt;blockquote&gt;Unfortunately the Twonky Media software versions you are currently using are not guaranteed to work, as third party software developers are susceptible to modify the features of their software.&lt;/blockquote&gt;

&lt;p&gt;So basically, "even though we're DLNA-compliant and you're using a DLNA-compliant server we give you no guarantees they'll work together whatsoever". If this is the way companies behave with their DLNA certification, if they can just get around any non-compliance issues by saying "it's the other guy's problem" then one really does wonder what the point of DLNA is.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-7315270357634206266?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/ELIQwoK07B8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/7315270357634206266/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=7315270357634206266" title="2 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/7315270357634206266?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/7315270357634206266?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/ELIQwoK07B8/dlna-in-real-world.html" title="DLNA in the real world" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://3.bp.blogspot.com/_EuFsZMY5ZNU/S3if6XHDKUI/AAAAAAAAAkA/KVQhKgIHvwk/s72-c/DLNA_cert_color.gif" height="72" width="72" /><thr:total>2</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/02/dlna-in-real-world.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0MESH49fip7ImA9Wx9aEE0.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-6895520619097448640</id><published>2010-02-16T20:00:00.001Z</published><updated>2011-03-01T17:43:29.066Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-03-01T17:43:29.066Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".NET" /><category scheme="http://www.blogger.com/atom/ns#" term="SQL Server" /><title>SQL Server Error Severity and .NET</title><content type="html">&lt;p&gt;&lt;em&gt;I actually wrote this almost a year ago but forgot to post it.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The other day I noticed some oddness in the Messages window of SQL Server Management Studio when using RAISERROR with different error severities. Running the following:&lt;/p&gt;

&lt;pre&gt;&lt;code class="sql"&gt;PRINT 'Start.'
RAISERROR (N'Error.', 16, 1)
PRINT 'End.'&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;produces...&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Start.
Msg 50000, Level 16, State 1, Line 2
Error.
End.&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;However if you increase the severity to 17 or 18 you get this...&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Start.
End.
Msg 50000, Level 18, State 1, Line 2
Error.&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Odd as the error message has now moved from between the "Start" and "End" to after the "End". Wondering what the significance of the change from severity 16 to 17 was and why Management Studio should treat them differently I headed over to &lt;a href="http://msdn.microsoft.com/en-us/library/ms164086.aspx"&gt;SQL Server Books Online&lt;/a&gt; which says:
&lt;ul&gt;
&lt;li&gt;0-10 are informational messages&lt;/li&gt;
&lt;li&gt;11-16 are errors that can be corrected by the user&lt;/li&gt;
&lt;li&gt;17-19 are application errors that the user can't correct&lt;/li&gt;
&lt;li&gt;20 and above are fatal errors&lt;/li&gt;
&lt;/ul&gt;
&lt;/p&gt;

&lt;p&gt;So there is a difference but that still doesn't explain Management Studio's behaviour. Management Studio uses the .NET SqlClient for running queries so a brief look at the docs shows the SqlConnection class has a &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.fireinfomessageeventonusererrors.aspx"&gt;FireInfoMessageEventOnUserErrors&lt;/a&gt; property which, when set to true, reports any errors of severity less than 17 to the InfoMessage handler rather than throwing a SqlException.&lt;/p&gt;

&lt;p&gt;I've put together a quick &lt;a href="http://www.sliver.com/dotnet/SnippetCompiler/"&gt;Snippet Compiler&lt;/a&gt; script to test this out which you can download &lt;a href="http://files.dezfowler.com/files/snippets/sql-error-severity.txt"&gt;here&lt;/a&gt;. The script has a connection string at the top which is looking for a local SQL Express instance with integrated security by default so you may need to amend this.&lt;/p&gt;

&lt;h3&gt;Results&lt;/h3&gt;

&lt;h4&gt;Queries 3 and 4&lt;/h4&gt;
&lt;p&gt;These two queries show the differences observed in Management Studio quite nicely with the InfoMessage handler being fired for the severity 16 error but a SqlException being thrown for the severity 18.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;-------------------------------------
Executing Query 3:


PRINT 'Start.'
RAISERROR (N'Error.', 16, 1)
PRINT 'End.'


Messages:

Info message fired: Start.
Info message fired: Error.
Info message fired: End.


Result:
Success.
-------------------------------------
Executing Query 4:


PRINT 'Start.'
RAISERROR (N'Error.', 18, 1)
PRINT 'End.'


Messages:

Info message fired: Start.
Info message fired: End.


Result:
SqlException.
Error severity: 18
Message: Error.
-------------------------------------&lt;/code&gt;&lt;/pre&gt;

&lt;h4&gt;Query 5&lt;/h4&gt;
&lt;p&gt;Query 5 causing a severity 20 error (a fatal error) displays some slightly different behaviour as it both fires the InfoMessage handler and throws a SqlException.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;-------------------------------------
Executing Query 5:


PRINT 'Start.'
RAISERROR (N'Error.', 20, 1) WITH LOG
PRINT 'End.'


Messages:

Info message fired: Start.
Info message fired: Process ID 51 has raised user error 50000, severity 20. SQL
Server is terminating this process.


Result:
SqlException.
Error severity: 20
Message: Error.
A severe error occurred on the current command.  The results, if any, should be
discarded.
-------------------------------------&lt;/code&gt;&lt;/pre&gt;

&lt;h4&gt;Queries 6, 7 and 8&lt;/h4&gt;
&lt;p&gt;These show how the &lt;var&gt;RAISERROR&lt;/var&gt; interacts with a SQL &lt;var&gt;TRY...CATCH&lt;/var&gt; block. The &lt;var&gt;RAISERROR&lt;/var&gt; within the &lt;var&gt;TRY&lt;/var&gt; block only fires the InfoMessage handler in the severity 20 case with the &lt;var&gt;RAISERROR&lt;/var&gt; in the &lt;var&gt;CATCH&lt;/var&gt; block only firing the handler in the severity 16 case.&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;It seems like you could build in some quite nice fine grain logging into your SQL statements, stored procs etc by using hooking up a SqlConnection &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.infomessage.aspx"&gt;InfoMessage&lt;/a&gt; handler and setting &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.fireinfomessageeventonusererrors.aspx"&gt;FireInfoMessageEventOnUserErrors&lt;/a&gt; to true. What's more is that you could write this information out to your application's log file along with the &lt;var&gt;Debug&lt;/var&gt; or &lt;var&gt;Trace&lt;/var&gt; calls from your code. Considering in some cases you may have quite a lot of logic in a stored procedure especially it may turn out to be really helpful having all your debugging information in one place.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-6895520619097448640?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/mOf6n-VNGSs" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/6895520619097448640/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=6895520619097448640" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/6895520619097448640?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/6895520619097448640?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/mOf6n-VNGSs/sql-server-error-severity-and-net.html" title="SQL Server Error Severity and .NET" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/02/sql-server-error-severity-and-net.html</feedburner:origLink></entry><entry gd:etag="W/&quot;AkIMRXo_cCp7ImA9WxBVEUs.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-7312921762485850679</id><published>2010-02-13T17:33:00.004Z</published><updated>2010-02-14T17:29:44.448Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-02-14T17:29:44.448Z</app:edited><title>Windows Update KB977165 causes BSoD</title><content type="html">&lt;p&gt;Had fun and games with Kath's laptop last night as it had mysteriously started blue screening with a &lt;var&gt;PAGE_FAULT_IN_NONPAGED_AREA&lt;/var&gt; error on startup. Safe mode was also affected with the boot getting as far as &lt;var&gt;mup.sys&lt;/var&gt; and then failing.&lt;/p&gt;
&lt;p&gt;&lt;img style="float:right; margin: 0 0 10px 10px;" src="http://3.bp.blogspot.com/_EuFsZMY5ZNU/S3b24SXB55I/AAAAAAAAAj4/_1plrpdRPfQ/s400/Windows_update_icon.gif" border="0" /&gt;She's running Windows XP dual-boot on a MacBook however OS X was unaffected so a hardware issue seemed unlikely. I suspected a recent Windows Update may be to blame although I've never come across such a severe failure resulting from an update before.&lt;/p&gt;
&lt;p&gt;After a quick Google search (using Safari) I found this thread on the Microsoft forums entitled &lt;a href="http://social.answers.microsoft.com/Forums/en-US/vistawu/thread/73cea559-ebbd-4274-96bc-e292b69f2fd1/"&gt;&amp;quot;BLUE SCREEN, UNABLE TO BOOT AFTER WINDOWS XP UPDATE TODAY&amp;quot;&lt;/a&gt;. The thread currently has 336 replies and 132,262 views so it's a fair bet a lot of people's machines have been affected.&lt;/p&gt;
&lt;p&gt;Reading the replies to the post it seems only XP and Vista are affected with the BSoD although the patch applied to all recent versions of Windows. Some replies speculate that it may be down to a previous virus infection which Kath's laptop has had so this could well be the case.&lt;/p&gt;
&lt;p&gt;The culprit is one of Tuesday 9th February's Windows Updates, &lt;a href="http://www.microsoft.com/technet/security/bulletin/ms10-015.mspx"&gt;KB977165&lt;/a&gt;, and you need to boot into Recovery Console using an XP CD and run some commands in order to uninstall it - full details are in Kevin Hau's answer in the thread.&lt;/p&gt;
&lt;p&gt;That's fine for people with an XP CD but pre-installed shop-bought PCs don't normally come with one and Netbooks don't even have a CD drive. Anyone without access to an XP CD will have to either buy a copy or consider upgrading to Windows 7. I suppose any bad publicity Microsoft may get from this won't concern them as they'll be busy watching their Win 7 uptake figures get a healthy bump this month. Of course, maybe people will decide to go with &lt;a href="http://osx86.thefreesuite.com/"&gt;OS X&lt;/a&gt; or &lt;a href="http://www.ubuntu.com/"&gt;Ubuntu&lt;/a&gt; instead.&lt;/p&gt;
&lt;h3&gt;Links&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.theregister.co.uk/2010/02/11/ms_bsod_update_glitch/"&gt;MS update gives some XP boxes the Blue Screen&lt;/a&gt;&lt;br/&gt;The Register&lt;/li&gt;
&lt;li&gt;&lt;a href="www.computerworld.com/s/article/9155419/Windows_patch_cripples_XP_with_blue_screen_users_claim"&gt;Windows patch cripples XP with blue screen, users claim&lt;/a&gt;&lt;br/&gt;Computerworld&lt;/li&gt;
&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-7312921762485850679?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/eXd-0gRlcfc" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/7312921762485850679/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=7312921762485850679" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/7312921762485850679?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/7312921762485850679?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/eXd-0gRlcfc/windows-update-kb977165-causes-bsod.html" title="Windows Update KB977165 causes BSoD" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://3.bp.blogspot.com/_EuFsZMY5ZNU/S3b24SXB55I/AAAAAAAAAj4/_1plrpdRPfQ/s72-c/Windows_update_icon.gif" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dezfowler.com/2010/02/windows-update-kb977165-causes-bsod.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0UHQ34_fip7ImA9WxNSEEk.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-7617445232883911144</id><published>2009-08-22T20:36:00.007+01:00</published><updated>2009-08-23T17:33:52.046+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-08-23T17:33:52.046+01:00</app:edited><title>HTC Hero</title><content type="html">&lt;p&gt;A week and a bit ago I upgraded my phone (a Nokia 6120 - read the saga that led to me getting that one &lt;a href="http://derek-says.blogspot.com/2007/07/mobile-madness.html"&gt;here&lt;/a&gt;) to the HTC Hero and thought I'd share my experiences thus far. I'd been following the progress of Google's Android OS for a while and really quite like the T-Mobile G1 but I'm on Orange with no plans to switch network so was pretty excited when I heard Orange were introducing the HTC Hero just in time for my contract expiring. The big screen, WiFi and GPS were plus points and, whilst I would have preferred a real qwerty keyboard like that of the G1, this being effectively the third version of that phone it should hopefully have a fair few bug fixes and refinements.&lt;/p&gt;

&lt;p&gt;&lt;img style="float: right;" src="http://lh6.ggpht.com/_EuFsZMY5ZNU/SpFoWs1eSGI/AAAAAAAAAhk/LJQluDvKQx0/s144/htc-hero-sml.jpg" border="0" alt="HTC Hero" /&gt;First off it comes in a pretty nice Apple-esque white box and after you've phoned the connections people and turned it on you're presented with a detailed and bright screen. Setup is straight forward and you're up and running in no time.&lt;/p&gt;

&lt;p&gt;I should mention that I'm a pretty big user of Google services; Mail, Calendar, Docs, Reader are apps I use every day. I've &lt;a href="http://derek-says.blogspot.com/2007/05/why-dont-google-support-syncml.html"&gt;blogged in the past&lt;/a&gt; about syncing my phone contacts with those held in Google Mail and it was great to not have to do the usual chore of copying all my contacts over from my old phone. Once I set up my Google account details in the Hero my contacts were all synced down - brilliant! What's better is that my calendar was now synced too which didn't work with SyncML on the old phone. My only criticism of this being that "My Calendar" in the phone is not the same as my "Derek Fowler" Google calendar - this isn't immediately apparent, in fact the two calendars even share the same colour coding, but if you add an event to "My Calendar" it's not synced up to Google. Once you realise this and pick the [your name] calendar that option remains selected and you can even hide "My Calendar" on the phone to make things clearer.&lt;/p&gt;

&lt;p&gt;A really nice extension to the contact list added by HTC themselves is the ability to link phone contacts to their Facebook and Flickr accounts so that whilst browsing contacts you also get their Facebook updates, their Facebook profile picture appears in the contact list and Photo Albums on the phone will also browser your contacts Facebook and Flickr photos in addition to any you have stored on the phone. All in all some brilliantly functional Web 2.0 integration.&lt;/p&gt;

&lt;p&gt;Google Mail on the phone is pretty similar to the app you can get for other handsets and, oddly, is separate to the actual "Mail" app. Admittedly GMail has features like Labels that you don't get with normal e-mail but still. Text messaging is presented nicely with messages between you and a particular contact appearing as a never ending conversation - something that really does make a lot of sense and I'm surprised it's taken handset vendors this long to think of it.&lt;/p&gt;

&lt;p&gt;The browser on the Hero is excellent. It renders pages well and has multi-touch for zooming which is invaluable when you're browsing normal pages rather than those tailored for a small screen. A double-tap zooms in until the object tapped on fills the screen, double-tap again returns to the full page view - very similar to the iPhone browser.&lt;/p&gt;

&lt;p&gt;One of the things that I've found to really let the Hero down is the onscreen qwerty keyboard. Whilst it's quite usable in landscape mode it just isn't big enough in portrait mode and, comparing it to the one on the iPhone you can instantly see it's considerably smaller. Thankfully there's the compact qwerty and phone keypad modes you can switch to which are usable, I've stuck with phone keypad.&lt;/p&gt;

&lt;p&gt;Other let downs are battery life and the odd bit of lag. Initially battery life was pretty poor, being less than a day between changes however after a few full changes it's now up to about two days. Whilst it's not the two weeks I was used to with the Nokia it's okay considering the big screen and multitude of devices inside the handset. Lag wise it's most noticeable when switching from portrait to landscape mode however in general the phone is very responsive and what lag there is generally isn't enough for you to start getting impatient so that's good.&lt;/p&gt;

&lt;p&gt;The Google Market is already full of a wide variety of apps and what's brilliant is that most are free. Highlights I've come across so far are:
&lt;ul&gt;
&lt;li&gt;AndNav - a SatNav app that uses &lt;a href="http://www.openstreetmap.org/"&gt;OpenStreetMap&lt;/a&gt; maps, no 3D view but promising&lt;/li&gt;
&lt;li&gt;beebPlayer - an unofficial BBC iPlayer app that supports both on-demand replay of old TV and radio shows but also live TV and radio!&lt;/li&gt;
&lt;li&gt;Last.fm - streams your recommendations, friends, neighbourhood etc radio&lt;/li&gt;
&lt;li&gt;Layar - augmented reality browser, shows you a view through the phone camera with markers pointing you in the direction of particular things&lt;/li&gt;
&lt;li&gt;Google Maps - excellent use of the built in compass in Street View to allow you to look around as if you're in the place&lt;/li&gt;
&lt;li&gt;Google Sky Map - similar to normal Maps it makes use of the compass to allow you to look around the sky, the app telling you what stars/constellations you're looking at and it even has a search function that will guide you to looking at the correct point in the sky for a particular object&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Finally I have to mention one aspect that had me pleasantly surprised about the Hero. If you read other articles on this blog you'll gather that I'm a pretty big hi-fi nerd so I was very impressed when I plugged my headphones in to the Hero (via the 3.5mm jack) and had a listen. Sound quality is really excellent with an airy detailed delivery - I'd be willing to bet it would give most portable music players a good run for their money.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-7617445232883911144?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/TUgF-O4nx54" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/7617445232883911144/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=7617445232883911144" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/7617445232883911144?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/7617445232883911144?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/TUgF-O4nx54/htc-hero.html" title="HTC Hero" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://lh6.ggpht.com/_EuFsZMY5ZNU/SpFoWs1eSGI/AAAAAAAAAhk/LJQluDvKQx0/s72-c/htc-hero-sml.jpg" height="72" width="72" /><thr:total>0</thr:total><feedburner:origLink>http://blog.dezfowler.com/2009/08/htc-hero.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CUYGRXo6fip7ImA9WxJRFk0.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-9141065463149015567</id><published>2009-05-16T19:55:00.008+01:00</published><updated>2009-05-18T00:32:04.416+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-05-18T00:32:04.416+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="DDD" /><category scheme="http://www.blogger.com/atom/ns#" term="OO" /><title>The always-valid entity anti-pattern</title><content type="html">&lt;p&gt;Jeffrey Palermo wrote an article about &lt;a href="http://jeffreypalermo.com/blog/the-fallacy-of-the-always-valid-entity/"&gt;the fallacy of the always-valid entity&lt;/a&gt; recently in which he highlighted that guarding against an entity becoming invalid by having validation logic in the setters of properties raises more issues than it solves.&lt;/p&gt;

&lt;p&gt;Another way of enforcing an always-valid entity is, what I have &lt;a href="http://usrportage.de/archives/897-Antipattern-the-verbose-constructor.html"&gt;found elsewhere&lt;/a&gt; termed, the "verbose constructor". Having a constructor which requires a value for every property, or every valid combination of properties.&lt;p&gt;

&lt;pre&gt;&lt;code class="c#"&gt;public Car(string make, string model, string serialNumber, 
           decimal engineLitres, int maxPower, decimal urbanMpg, 
           decimal extraUrbanMpg, decimal combinedMpg, 
           int fuelTankCapacity) { ... }

Car myCar = new Car("Audi", "A4", "12345ABCD", 1.8, 120, 
                    28.5, 51.4, 39.8, 65);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The "verbose constructor" is itself a good candidate for an anti-pattern for the following reasons:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Modifying the entity means modifying every instantiation of it also&lt;/li&gt;
&lt;li&gt;Forcing a programmer to set these values when they may not be available will result in garbage data which is useless anyway&lt;/li&gt;
&lt;li&gt;Derived classes must call this verbose constructor either replicating every parameter in their own constructors or hardcoding values for some parameters (&lt;a href="http://en.wikipedia.org/wiki/Hard_code"&gt;another anti-pattern&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;Unreadable code, without help from the IDE it's difficult to identify each parameter&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The method Jeffrey highlighted in his post has to use exceptions to catch validation errors, which forces a programmer to use another anti-pattern; &lt;a href="http://en.wikipedia.org/wiki/Expection_handling"&gt;exception handling&lt;/a&gt;. Where programming logic is implemented by the throwing and catching of exceptions. Any call to a property setter of the entity must be wrapped in a try...catch... block.&lt;/p&gt;

&lt;p&gt;The always-valid entity, however it's implemented, seems to lead to a minefield of bad code. The thinking behind the need for this blurs the line between two important distinctions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;not setting a value vs. setting it to something incorrect&lt;/li&gt;
&lt;li&gt;what makes an object a valid type vs. what makes an object valid for a particular use&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I touched on the first of these before; where it may be the case that a programmer doesn't yet have a value for a particular property available yet. So long as we ensure the entity doesn't leak out in this invalid state we're okay.&lt;/p&gt;
&lt;p&gt;Which leads on to the second item; we should guard against a value being set where that value violates the type e.g. setting Day to 32 for a DateTime, something bad has occurred and this is a real exception case. However, this is a much lower-level problem than enforcing business rules, for example where a credit card applicant's date of birth must be at least 18 years earlier than the date of the application. It could be the case that one company actually requires applicants to be 21 so hardcoding that type of validation into the class is not only restrictive but enforcing this by throwing exceptions is very inefficient.&lt;/p&gt;

&lt;p&gt;The always-valid entity just serves to be very restrictive and limits the entity's uses in its current form. Validating from outside means that its easy to skip validation or make it more stringent when needed. Also, if implemented along the lines Jeffrey describes in his post, it means mechanisms have a common way of validating objects without needing specific knowledge of the particular object or the current validation being applied which makes for more robust code.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-9141065463149015567?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/B-jFfEzYZXg" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/9141065463149015567/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=9141065463149015567" title="4 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/9141065463149015567?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/9141065463149015567?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/B-jFfEzYZXg/always-valid-entity-anti-pattern.html" title="The always-valid entity anti-pattern" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>4</thr:total><feedburner:origLink>http://blog.dezfowler.com/2009/05/always-valid-entity-anti-pattern.html</feedburner:origLink></entry><entry gd:etag="W/&quot;D0MDRn0-eip7ImA9WxVXFkg.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-6951811146778265114</id><published>2009-02-14T23:50:00.000Z</published><updated>2009-02-14T23:51:17.352Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-02-14T23:51:17.352Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term=".NET" /><category scheme="http://www.blogger.com/atom/ns#" term="NHibernate" /><title>OpenSession with connection disables second-level cache in NHibernate</title><content type="html">&lt;p&gt;I've has this post in my drafts for nearly a year now so I decided I'd finish it off.&lt;/p&gt;

&lt;p&gt;I came across an issue when using the second-level cache in NHibernate where none of my objects were being cached and NHibernate was always going to the database for them. What was more odd was the NHibernate debug output suggested the items were being retrieved from the datbase and added to cache but on the next request the items couldn't be resolved in the cache.&lt;/p&gt;

&lt;p&gt;Attatching a debugger and stepping through shows a timestamp passed into Cache's Put() method is equal to MinValue which makes it skip the Cache.Add at the last minute (whilst outputting debug messages to the contrary).&lt;/p&gt;

&lt;p&gt;Tracking this timestamp back revealed it was created when the session is first openned and was due to my passing in my own connection string rather than letting NHibernate provide one. I assume this is a safeguard because IDs aren't necessarily unique between databases so in that case the cache would perform oddly.&lt;/p&gt;

&lt;p&gt;If in your case they are however then you can work around this by casting your ISessionFactory as an ISessionFactoryImplementor. This has an extra overload of OpenSession which takes a IConnection and a ConnectionReleaseMode but doesn't disable the second-level cache.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-6951811146778265114?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/Y2IyLNaHVTY" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/6951811146778265114/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=6951811146778265114" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/6951811146778265114?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/6951811146778265114?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/Y2IyLNaHVTY/opensession-with-connection-disables.html" title="OpenSession with connection disables second-level cache in NHibernate" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://blog.dezfowler.com/2008/03/opensession-with-connection-disables.html</feedburner:origLink></entry><entry gd:etag="W/&quot;DkEASHs8eyp7ImA9WxVSE0o.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-1367572755376716315</id><published>2009-01-07T21:56:00.003Z</published><updated>2009-01-08T00:30:49.573Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2009-01-08T00:30:49.573Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="SQL Server" /><title>ISNULL vs COALESCE</title><content type="html">&lt;p&gt;Consider this SQL Server statement:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT ISNULL(2, 2.0), COALESCE(2, 2.0)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You might assume, as I did, that they're equivalent and will produce the same result, however this is not the case.&lt;/p&gt;

&lt;p&gt;They differ in the way they determine what data type to return. ISNULL always returns the data type of the first argument and the second argument must implicitly cast to that type. COALESCE on the other hand returns the data type of the argument with highest &lt;a href="http://msdn.microsoft.com/en-us/library/ms190309.aspx"&gt;data type precedence&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;As a result what you get out of the example above is:&lt;/p&gt;
&lt;table border="1" cellspacing="2"&gt;
&lt;tr&gt;&lt;td&gt;2&lt;/td&gt;&lt;td&gt;2.0&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;The reason being that the constant "2" is treated as an integer while "2.0" is treated as a decimal. Therefore ISNULL will return an integer because the first argument is an integer but COALESCE returns a decimal because decimal has higher precedence.&lt;/p&gt;

&lt;p&gt;One possible issue I can envisage here is if you were to inadvertently COALESCE a float column in with your decimals and then try to do some arithmetic. You'd end up doing dodgy float arithmetic where you thought you were doing safe decimal arithmetic.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-1367572755376716315?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/Unek8-DtVnc" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/1367572755376716315/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=1367572755376716315" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/1367572755376716315?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/1367572755376716315?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/Unek8-DtVnc/isnull-vs-coalesce.html" title="ISNULL vs COALESCE" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>1</thr:total><feedburner:origLink>http://blog.dezfowler.com/2009/01/isnull-vs-coalesce.html</feedburner:origLink></entry><entry gd:etag="W/&quot;AkICSX05cSp7ImA9WxRSFkU.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-1946047148698042301</id><published>2008-09-17T20:46:00.003+01:00</published><updated>2008-09-17T22:56:08.329+01:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2008-09-17T22:56:08.329+01:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="XSL" /><title>Column layouts with XSL</title><content type="html">&lt;p&gt;Marking up a set of items so that they are laid out in a fixed number of columns from left to right can be tricky if the items vary in height. You need markup something like the example below to achieve this...&lt;/p&gt;

&lt;pre&gt;&lt;code class="html"&gt;&amp;lt;div class=&amp;quot;row&amp;quot;&amp;gt;
 &amp;lt;div&amp;gt; class=&amp;quot;item&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
 &amp;lt;div&amp;gt; class=&amp;quot;item&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
 &amp;lt;div&amp;gt; class=&amp;quot;item&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;div class=&amp;quot;row&amp;quot;&amp;gt;
 &amp;lt;div&amp;gt; class=&amp;quot;item&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
 &amp;lt;div&amp;gt; class=&amp;quot;item&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;...with CSS like this...&lt;/p&gt;

&lt;pre&gt;&lt;code class="css"&gt;.item { float: left; width: 250px; }&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Outputting this from XSL is fairly straight forward and requires relatively little "code" by juggling some XSL and XPath. Here is some example XML:&lt;/p&gt;

&lt;pre&gt;&lt;code class="xml"&gt;&amp;lt;?xml version=&amp;quot;1.0&amp;quot;?&amp;gt;
&amp;lt;items&amp;gt;
 &amp;lt;item title=&amp;quot;Item 1&amp;quot;/&amp;gt;
 &amp;lt;item title=&amp;quot;Item 2&amp;quot;/&amp;gt;
 &amp;lt;item title=&amp;quot;Item 3&amp;quot;/&amp;gt;
 &amp;lt;item title=&amp;quot;Item 4&amp;quot;/&amp;gt;
 &amp;lt;item title=&amp;quot;Item 5&amp;quot;/&amp;gt;
&amp;lt;/items&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The XSL to transform this into HTML of the format shown earlier looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class="xml"&gt;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot;?&amp;gt;
&amp;lt;xsl:stylesheet version=&amp;quot;1.0&amp;quot; xmlns:xsl=&amp;quot;http://www.w3.org/1999/XSL/Transform&amp;quot;&amp;gt;
 &amp;lt;xsl:variable name=&amp;quot;cols&amp;quot; select=&amp;quot;3&amp;quot;/&amp;gt;
 &amp;lt;xsl:template match=&amp;quot;/items&amp;quot;&amp;gt;
  &amp;lt;xsl:apply-templates select=&amp;quot;item[position() mod $cols = 1]&amp;quot; mode=&amp;quot;row&amp;quot;/&amp;gt;
 &amp;lt;/xsl:template&amp;gt;
 &amp;lt;xsl:template match=&amp;quot;item&amp;quot; mode=&amp;quot;row&amp;quot;&amp;gt;
  &amp;lt;div class=&amp;quot;row&amp;quot;&amp;gt;
   &amp;lt;xsl:apply-templates select=&amp;quot;.|./following-sibling::item[position() &amp;amp;lt; $cols]&amp;quot;/&amp;gt;
  &amp;lt;/div&amp;gt;
 &amp;lt;/xsl:template&amp;gt;
 &amp;lt;xsl:template match=&amp;quot;item&amp;quot;&amp;gt;
  &amp;lt;div class=&amp;quot;item&amp;quot;&amp;gt;
   &amp;lt;xsl:value-of select=&amp;quot;@title&amp;quot;/&amp;gt;
  &amp;lt;/div&amp;gt;
 &amp;lt;/xsl:template&amp;gt;
&amp;lt;/xsl:stylesheet&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;First off, we've got a variable named "cols" for setting the number of columns to output. Next, inside the first template matching our root element, we have an apply-templates which selects all the item element with a position that when divided by the number of columns leaves a remainder of one. This should give us items 1, 4, 7, 10 etc and these are then passed to a template in mode "row".&lt;/p&gt;

&lt;p&gt;This apply-templates will match the next template whose job is to output the div element with class row. Within this div there is another apply-templates, this time matching the current item element and a number of its following siblings. That being one less than then number of columns required so in this example we get the context item plus its two following siblings. The template that matches this apply is that last one, without the mode specified.&lt;/p&gt;

&lt;p&gt;The last "item" matching template simply writes out the div with class item surrounding the content of the item itself.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-1946047148698042301?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/q2-hxrwmylI" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/1946047148698042301/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=1946047148698042301" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/1946047148698042301?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/1946047148698042301?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/q2-hxrwmylI/column-layouts-with-xsl.html" title="Column layouts with XSL" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>0</thr:total><feedburner:origLink>http://blog.dezfowler.com/2008/09/column-layouts-with-xsl.html</feedburner:origLink></entry><entry gd:etag="W/&quot;C0IGR3s9fCp7ImA9Wx9aEE0.&quot;"><id>tag:blogger.com,1999:blog-36201586.post-3566699272108348495</id><published>2008-08-21T23:52:00.004+01:00</published><updated>2011-03-01T17:45:26.564Z</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2011-03-01T17:45:26.564Z</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript" /><title>Function overloading in JavaScript</title><content type="html">&lt;p&gt;Trying to write a function so that it will handle different numbers and types of argument always seems to take a lot more code that it should. Today I ended up with some nightmarish &lt;var&gt;if...else...&lt;/var&gt; because I wanted to support:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;var&gt;Object, Object&lt;/var&gt;&lt;/li&gt;
&lt;li&gt;&lt;var&gt;Object, String&lt;/var&gt;&lt;/li&gt;
&lt;li&gt;&lt;var&gt;Object, Object, String&lt;/var&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I remembered a &lt;a href="http://ejohn.org/blog/javascript-method-overloading"&gt;post by John Resig&lt;/a&gt; from a while back on this, however his method doesn't handle different types. A quick Google found &lt;a href="http://snippets.dzone.com/posts/show/842"&gt;this snippet&lt;/a&gt; which does the job but seems a bit clunky, converting constructors to strings and the like. Satisfied that it could probably be improved upon here is &lt;a href="http://files.dezfowler.com/demos/method-overload.htm"&gt;my go at it&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;Implementation&lt;/h3&gt;

&lt;p&gt;Here an &lt;var&gt;Impl&lt;/var&gt; class holds the different method implementations against their signatures, defined as an array of constructors. The &lt;var&gt;add&lt;/var&gt; method maps a new signature to an implementation, the &lt;var&gt;exec&lt;/var&gt; method identifies the correct implementation for the current arguments and executes it and the &lt;var&gt;compile&lt;/var&gt; method returns a function that can be used to overwrite the "daddy" function.&lt;/p&gt;

&lt;pre&gt;&lt;code class="javascript"&gt;function Impl(){
 var _impl = {};
 return {
  add: function(aSignature, fImpl){
   _impl[aSignature] = fImpl;
  },
  exec: function(args, scope){
   var aArgs = Array.prototype.slice.call(args);
   var aCtors = [];
   for(var i in aArgs) aCtors.push(aArgs[i].constructor);
   return (_impl[aCtors] || function(){}).apply(scope, aArgs);
  },
  compile: function(){
   var impl = this;
   return function(){
    return impl.exec(arguments, this);
   };
  }
 };
}&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Usage&lt;/h3&gt;

&lt;p&gt;Here's an example setup of a function &lt;var&gt;stringify&lt;/var&gt; that will take two strings, two numbers or an array and do different things depending on what arguments are passed.&lt;/p&gt;

&lt;pre&gt;&lt;code class="javascript"&gt;function stringify(){
 var someVar = 'Items: ';
 var impl = new Impl();
 
 impl.add([String, String], function(sLeft, sRight){
  return sLeft + ': ' + sRight;
 });
 impl.add([Number, Number], function(iLeft, iRight){
  return 'Sum: ' + (iLeft + iRight).toString();
 });
 impl.add([Array], function(aIn){
  return someVar + aIn.join(', ');
 });
 
 stringify = impl.compile();
 return stringify.apply(this, arguments);
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Each implementation is added with an array of constructors e.g. &lt;var&gt;[Number, Number]&lt;/var&gt; representing the arguments signature to match and the implementation function. Notice that we don't need to do any type checking of the variables in the implementation function, as we have to have matched the signature to get that far, and we can give then relevant names.&lt;/p&gt;

&lt;p&gt;Notice the last two lines are:&lt;/p&gt;

&lt;pre&gt;&lt;code class="javascript"&gt;stringify = impl.compile();
return stringify.apply(this, arguments);&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So on the first execution of the function it is overwritten with a "compiled" version and then that version is called on the next line. Subsequent calls to the function will go straight to the "compiled" version thus speeding things up. This could also be done without the compilation and overwriting bit by just calling &lt;var&gt;exec&lt;/var&gt; directly thus:&lt;/p&gt;

&lt;pre&gt;&lt;code class="javascript"&gt;return impl.exec(arguments, this);&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Calling our function&lt;/h3&gt;

&lt;pre&gt;&lt;code class="javascript"&gt;stringify('foo', 'bar'); // =&gt; 'foo: bar'
stringify(26, 5); // =&gt; 'Sum: 31'
stringify( [ 1, 2, 3 ] ); // =&gt; 'Items: 1, 2, 3'&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Our different numbers and types of argument are giving us the output we'd expect.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/36201586-3566699272108348495?l=blog.dezfowler.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/DerekSays/~4/AxbrO6NMg_8" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://blog.dezfowler.com/feeds/3566699272108348495/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.blogger.com/comment.g?blogID=36201586&amp;postID=3566699272108348495" title="4 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/3566699272108348495?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/36201586/posts/default/3566699272108348495?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/DerekSays/~3/AxbrO6NMg_8/function-overloading-in-javascript.html" title="Function overloading in JavaScript" /><author><name>Derek Fowler</name><uri>http://www.blogger.com/profile/09963865123124577525</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="29" height="32" src="http://4.bp.blogspot.com/_EuFsZMY5ZNU/S27AtNRnjLI/AAAAAAAAAjU/zy7UIvbBBcg/s1600-R/indiana.jpg" /></author><thr:total>4</thr:total><feedburner:origLink>http://blog.dezfowler.com/2008/08/function-overloading-in-javascript.html</feedburner:origLink></entry></feed>

