<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-3603442416802102417</id><updated>2024-08-29T03:35:13.029-07:00</updated><category term="Programming"/><category term="C#"/><category term="Functional"/><category term="Lambda"/><category term="Cloud"/><category term="Languages"/><category term="Windows Azure"/><category term="COS204"/><category term="SQL Azure"/><category term="TechEd 2011"/><category term="Expression"/><category term="Ordered Guids"/><category term="SwissKnife"/><category term="Feber"/><category term="Reflection"/><category term="Database Design"/><category term="Database Theory"/><category term="Fun"/><category term="AZR331"/><category term="Azure"/><category term="C++"/><category term="Casablanca"/><category term="Cloud Architecture Patterns"/><category term="Performance"/><category term="TechEd 2012"/><category term="TechEd 2013"/><category term="Unsafe Code"/><title type='text'>A Scrum Of One</title><subtitle type='html'>Teetering on the brink of reason...</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default?start-index=26&amp;max-results=25&amp;redirect=false'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>29</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-3607977841505579004</id><published>2013-11-03T20:33:00.000-08:00</published><updated>2013-11-14T11:16:55.873-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Functional"/><category scheme="http://www.blogger.com/atom/ns#" term="Lambda"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><category scheme="http://www.blogger.com/atom/ns#" term="Reflection"/><category scheme="http://www.blogger.com/atom/ns#" term="SwissKnife"/><title type='text'>Classes and Memoization - A Neat C# Trick</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&lt;em&gt;This post talks about a set of utilities provided in the BrightSword SwissKnife library (&lt;a href=&quot;http://www.nuget.org/packages/BrightSword.SwissKnife/&quot; target=&quot;_blank&quot;&gt;nuget&lt;/a&gt;, &lt;a href=&quot;http://swissknife.codeplex.com/&quot; target=&quot;_blank&quot;&gt;codeplex&lt;/a&gt;).&lt;/em&gt;&lt;/p&gt; &lt;p&gt;&lt;em&gt;When programming in the real world (as opposed to programming for an academic exercise), we and (and should) combine concepts to synergistically improve our solution.&lt;/em&gt;&lt;/p&gt; &lt;p&gt;&lt;em&gt;We have visited Memoization as a technique, and have seen the use of functional programming to provide more succinct, maintainable code in discussing the Reflection Utility.&lt;/em&gt;&lt;/p&gt; &lt;p&gt;&lt;em&gt;In this post, we will combine those two concepts (and derive a programming rule-of-thumb) to provide a more efficient utility for Reflection. &lt;/em&gt;&lt;/p&gt; &lt;p&gt;&lt;em&gt;You will find this utility &lt;a href=&quot;http://swissknife.codeplex.com/SourceControl/latest#Library.BrightSword.SwissKnife/Reflection/TypeMemberDiscoverer.cs&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;, and can access it as &lt;font face=&quot;Courier New&quot;&gt;BrightSword.SwissKnife.TypeMemberDiscoverer&amp;lt;T&amp;gt;&lt;/font&gt;&lt;/em&gt;&lt;/p&gt; &lt;h4&gt;The Simple Approach&lt;/h4&gt; &lt;p&gt;The Reflection Utility extension method surface is simple to use and highly maintainable, because there is minimal code-duplication.  &lt;p&gt;To re-cap, our extension method surface for properties looks like:  &lt;p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static IEnumerable&amp;lt;PropertyInfo&amp;gt; GetAllProperties(this Type _this, BindingFlags bindingFlags = DefaultBindingFlags)&lt;br&gt;{&lt;br&gt;    return _this.GetAllMembers((_type, _bindingFlags) =&amp;gt; _type.GetProperties(_bindingFlags), bindingFlags);&lt;br&gt;}&lt;br&gt;&lt;/pre&gt;which allows for usage like this: &lt;br&gt;&lt;br /&gt;&lt;p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;var readonlyProperties = typeof (T).GetAllProperties().Where(_ =&amp;gt; !_.CanWrite || _.GetSetMethod() == null);&lt;br&gt;&lt;/pre&gt;One of the immediately evident drawbacks is that each invocation of the extension method involves reflection over the type’s members, and therefore we pay a linear cost for reflection. &lt;br&gt;&lt;br /&gt;&lt;p&gt;One approach might be to consider Memoization to store and reuse the result of the reflection utilities, and pay the price for reflection just once. This post discusses the approach SwissKnife takes in order to do this. &lt;br&gt;&lt;br /&gt;&lt;p&gt;The real problem with simple memoization is the &lt;code&gt;BindingFlags&lt;/code&gt; parameter, which may select different sets of members each time. In order to optimally reduce the required computation, we could restrict the &lt;code&gt;BindingFlags&lt;/code&gt; value to some reasonable default (such as ‘all public members’) and memoize the result-set of members by Type. &lt;br&gt;&lt;br /&gt;&lt;p&gt;This line of thought leads to something like this: &lt;br&gt;&lt;br /&gt;&lt;p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static class TypeMemberDiscoverer&lt;br&gt;{&lt;br&gt;    private const BindingFlags DefaultBindingFlags = BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public;&lt;br&gt;&lt;br&gt;    public static ConcurrentDictionary&amp;lt;Type, IEnumerable&amp;lt;PropertyInfo&amp;gt;&amp;gt; _propertySetCache = &lt;br&gt;        new ConcurrentDictionary&amp;lt;Type, IEnumerable&amp;lt;PropertyInfo&amp;gt;&amp;gt;();&lt;br&gt;&lt;br&gt;    public static IEnumerable&amp;lt;PropertyInfo&amp;gt; GetAllProperties(this Type type)&lt;br&gt;    {&lt;br&gt;        return _propertySetCache.GetOrAdd(type,&lt;br&gt;                                          _ =&amp;gt; _.GetAllMembers((_type,&lt;br&gt;                                                                _bindingFlags) =&amp;gt; _type.GetProperties(_bindingFlags),&lt;br&gt;                                                               DefaultBindingFlags));&lt;br&gt;    }&lt;br&gt;}&lt;br&gt;&lt;/pre&gt;This approach still provides an extension method, and now the default property set is cached and the &lt;code&gt;GetAllMembers&lt;/code&gt; call is only performed once. &lt;br&gt;&lt;br /&gt;&lt;p&gt;However, we can use a feature of the C# language to get a slightly more elegant solution, and simultaneously derive a programming rule-of-thumb. &lt;br&gt;&lt;br /&gt;&lt;p&gt;&amp;nbsp; &lt;h4&gt;Static Fields in Generic Types&lt;/h4&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Because C# generic classes are true classes, a static field defined in an &lt;i&gt;open generic&lt;/i&gt; class will actually be defined as a &lt;b&gt;separate &lt;/b&gt;static field in each corresponding &lt;i&gt;closed generic&lt;/i&gt; class. &lt;br&gt;&lt;br /&gt;&lt;p&gt;Consider the open generic type:&lt;pre class=&quot;brush: csharp;&quot;&gt;public class Foo&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;    private static int _bar;&lt;br&gt;}&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Consider now, a &lt;code&gt;Foo&amp;lt;int&amp;gt;&lt;/code&gt; and a &lt;code&gt;Foo&amp;lt;string&amp;gt;&lt;/code&gt;. &lt;br&gt;&lt;br /&gt;&lt;p&gt;Both of these closed generic types will have a static field of type &lt;code&gt;int&lt;/code&gt; called &lt;code&gt;_bar&lt;/code&gt;. &lt;br&gt;&lt;br /&gt;&lt;p&gt;As expected, all instances of &lt;code&gt;Foo&amp;lt;int&amp;gt;&lt;/code&gt; will share a static _bar field, and all instances of &lt;code&gt;Foo&amp;lt;string&amp;gt;&lt;/code&gt; will share a static &lt;code&gt;_bar&lt;/code&gt; field. &lt;br&gt;&lt;br /&gt;&lt;p&gt;What you might not expect, however is that &lt;code&gt;Foo&amp;lt;int&amp;gt;&lt;/code&gt; will &lt;i&gt;not&lt;/i&gt; be the same as &lt;code&gt;Foo&amp;lt;string&amp;gt;&lt;/code&gt;. In fact, Resharper™ and Microsoft Code Analysis both have warnings alerting you that this behaviour might be potentially unexpected – you might expect that the field is shared across all types that close the open generic type, but it won’t be! &lt;br&gt;&lt;br /&gt;&lt;p&gt;However, in our case, this is &lt;i&gt;exactly&lt;/i&gt; the behaviour we want! Because static fields in generic classes are actually only shared by instances of the corresponding closed generic type, we can use a generic class itself as a kind of memoization container, where we can cache something by &lt;code&gt;Type&lt;/code&gt;! &lt;br&gt;&lt;br /&gt;&lt;p&gt;&lt;em&gt;So the general rule-of-thumb is: If you find yourself trying to cache against a type name for whatever reason, consider using a generic class as a cache container. The static initializers of a class are guaranteed thread-safe, and you can write more readable code and let the language provide the cache! &lt;/em&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;So we can write a generic type with one type parameter, as follows: &lt;br&gt;&lt;br /&gt;&lt;p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static class TypeMemberDiscoverer&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;    private const BindingFlags DefaultBindingFlags = BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public;&lt;br&gt;&lt;br&gt;// ReSharper disable StaticFieldInGenericType&lt;br&gt;    private static readonly IEnumerable&amp;lt;PropertyInfo&amp;gt; _properties = &lt;br&gt;        typeof(T).GetAllMembers((_type,&lt;br&gt;                                 _bindingFlags) =&amp;gt; _type.GetProperties(_bindingFlags), DefaultBindingFlags);&lt;br&gt;// ReSharper restore StaticFieldInGenericType&lt;br&gt;&lt;br&gt;    public static IEnumerable&amp;lt;PropertyInfo&amp;gt; GetAllProperties()&lt;br&gt;    {&lt;br&gt;        return _properties;&lt;br&gt;    }&lt;br&gt;}&lt;br&gt;&lt;/pre&gt;The usage is:&lt;pre class=&quot;brush: csharp;&quot;&gt;var readonlyProperties = TypeMemberDiscoverer&amp;lt;int&amp;gt;.GetAllProperties()&lt;br&gt;                                                  .Where(_ =&amp;gt; !_.CanWrite || _.GetSetMethod() == null);&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;In the class above, we pay the price to discover the properties exactly once – when the &lt;code&gt;TypeMemberDiscoverer&amp;lt;int&amp;gt;&lt;/code&gt; type is initialized. We can use the &lt;code&gt;Lazy&amp;lt;T&amp;gt;&lt;/code&gt; pattern to further defer the evaluation to when the &lt;code&gt;GetAllProperties()&lt;/code&gt; call is first invoked. &lt;pre class=&quot;brush: csharp;&quot;&gt;public static class TypeMemberDiscoverer&amp;lt;T&amp;gt;&lt;br&gt;{&lt;br&gt;    private const BindingFlags DefaultBindingFlags = BindingFlags.Default | BindingFlags.Instance | BindingFlags.Public;&lt;br&gt;&lt;br&gt;// ReSharper disable StaticFieldInGenericType&lt;br&gt;    private static readonly Lazy&amp;lt;IEnumerable&amp;lt;PropertyInfo&amp;gt;&amp;gt; _propertiesL = &lt;br&gt;        new Lazy&amp;lt;IEnumerable&amp;lt;PropertyInfo&amp;gt;&amp;gt;(&lt;br&gt;            () =&amp;gt; typeof(T).GetAllMembers((_type,&lt;br&gt;                                           _bindingFlags) =&amp;gt; _type.GetProperties(_bindingFlags),&lt;br&gt;                                          DefaultBindingFlags));&lt;br&gt;// ReSharper restore StaticFieldInGenericType&lt;br&gt;&lt;br&gt;    public static IEnumerable&amp;lt;PropertyInfo&amp;gt; GetAllProperties()&lt;br&gt;    {&lt;br&gt;        return _propertiesL.Value;&lt;br&gt;    }&lt;br&gt;}&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;This is both efficient and easier-to-read, and it doesn&#39;t need a &lt;code&gt;ConcurrentDictionary&lt;/code&gt; to work! &lt;br&gt;&lt;br /&gt;&lt;p&gt;&amp;nbsp; &lt;h4&gt;Summary&lt;/h4&gt;&lt;br&gt;&lt;br /&gt;&lt;ul&gt;&lt;br&gt;&lt;br /&gt;&lt;li&gt;We can use the functional programming principle of &lt;i&gt;memoization&lt;/i&gt; to cache the result of an expensive operation (recursive reflection). This eliminates repeated computation at the expense of memory. &lt;br&gt;&lt;br /&gt;&lt;li&gt;We can do this elegantly by using a feature of the C# language which allows static fields in a generic type to act as a cache keyed by the type parameters. &lt;br&gt;&lt;br /&gt;&lt;li&gt;We can further reduce wasted effort by using the Lazy pattern provided by the runtime, and only compute (and cache) results when first used&lt;/li&gt;&lt;/ul&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/3607977841505579004/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2013/11/classes-and-memoization-neat-c-trick.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/3607977841505579004'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/3607977841505579004'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2013/11/classes-and-memoization-neat-c-trick.html' title='Classes and Memoization - A Neat C# Trick'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-1650083762313788531</id><published>2013-11-03T15:00:00.001-08:00</published><updated>2013-11-14T11:15:54.126-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Functional"/><category scheme="http://www.blogger.com/atom/ns#" term="Lambda"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><category scheme="http://www.blogger.com/atom/ns#" term="SwissKnife"/><title type='text'>Functions as Function Results</title><content type='html'>&lt;p&gt;&lt;em&gt;&lt;/em&gt;&amp;nbsp; &lt;p&gt;&lt;em&gt;This post talks about a set of utilities provided in the BrightSword SwissKnife library (&lt;a href=&quot;http://www.nuget.org/packages/BrightSword.SwissKnife/&quot; target=&quot;_blank&quot;&gt;nuget&lt;/a&gt;, &lt;a href=&quot;http://swissknife.codeplex.com/&quot; target=&quot;_blank&quot;&gt;codeplex&lt;/a&gt;).&lt;/em&gt;  &lt;p&gt;&lt;em&gt;Learning to write performance-sensitive code is a journey. There are many programming tools and techniques which contribute to different aspects of improving code performance.&lt;/em&gt;  &lt;p&gt;&lt;em&gt;The most elegant of these are the fundamentally timeless classics – mathematical methods and proofs that are agnostic to technologies. However, understanding these techniques generally requires a rigorous understanding and application of logic and mathematical technique.&lt;/em&gt;  &lt;p&gt;&lt;em&gt;Memoizing is a commonly used mathematical technique to improve the performance of the act of calculations – historically, great care was taken to compute, verify and publish the values resulting from the calculation of formulae – logarithms, arithmetic and trigonometric functions, for example.&lt;/em&gt;  &lt;p&gt;&lt;em&gt;You will find a general-purpose &lt;font face=&quot;Courier New&quot;&gt;Memoize&lt;/font&gt; function &lt;a href=&quot;http://swissknife.codeplex.com/SourceControl/latest#Library.BrightSword.SwissKnife/Functional.cs&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;, but its implementation is more advanced than is discussed by this post. We will cover the advanced issues in a future post which addresses recursion.&lt;/em&gt; &lt;h4&gt;&amp;nbsp;&lt;/h4&gt; &lt;h4&gt;Introduction&lt;/h4&gt; &lt;p&gt;We’ve seen that we can abstract away boilerplate code and parameterize logic using functions as function arguments.  &lt;p&gt;We also had a stab at memoizing a function parameterized only by a single generic type parameter. We’re going to spend a little more time talking about memoizing functions now.  &lt;p&gt;Consider the following snippet using the Math.Sqrt function, which computes the square root of a given positive real number. &lt;pre class=&quot;brush: csharp;&quot;&gt;&lt;br&gt;var y = Math.Sqrt (Math.Sqrt (a)) + 2 * Math.Sqrt (b) * Math.Sqrt (a);&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;A function, such as Math.Sqrt, which always returns the same result for the same arguments without changing any other state is called a “pure” function. Such functions have a property known as &lt;i&gt;referential transparency&lt;/i&gt;, which means that the result value of the function can replace its invocation in an expression. Because of this property, we do not need to evaluate Math.Sqrt(a) twice in the expression above. We could simply store the result against the argument somewhere and return it whenever the function is invoked with the same argument. Such a technique is called &lt;i&gt;memoization&lt;/i&gt;.&lt;br&gt;&lt;br /&gt;&lt;p&gt;&amp;nbsp; &lt;h4&gt;Memoizing&lt;/h4&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;We could take several approaches to memoize a function: the most naïve approach might be to use code such as:&lt;br&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static ConcurrentDictionary&amp;lt;double, double&amp;gt; GlobalCacheForSqrt = new ConcurrentDictionary&amp;lt;double, double&amp;gt;();&lt;br&gt;public static double sqrt_memoized(double x)&lt;br&gt;{&lt;br&gt;    return GlobalCacheForSqrt.GetOrAdd(x,&lt;br&gt;                                       Math.Sqrt);&lt;br&gt;}&lt;br&gt;&lt;br&gt;...&lt;br&gt;&lt;br&gt;var y = sqrt_memoized(sqrt_memoized(a)) + 2 * sqrt_memoized(b) * sqrt_memoized(a);&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;This would work, but what price have we paid to make this happen?&lt;br&gt;&lt;br /&gt;&lt;ul&gt;&lt;br&gt;&lt;br /&gt;&lt;li&gt;We have created a &lt;i&gt;global&lt;/i&gt; value cache to store the results of the &lt;u&gt;Math.Sqrt&lt;/u&gt; function.&lt;br&gt;&lt;br /&gt;&lt;li&gt;We have created a wrapper function to return the cached value and only invoke the Math.Sqrt function if we haven’t done it once before.&lt;br&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;If we wanted to memoize another function, we would have to do the same two steps all over again, which is somewhat tedious. But somewhat more seriously, we are memoizing the results in mutable global state – making the system impure. &lt;br&gt;&lt;br /&gt;&lt;p&gt;What we really want is to localize the cache somewhere local and safe, and also remove the tedium of writing the wrapping function. &lt;br&gt;&lt;br /&gt;&lt;p&gt;Something that looks like this:&lt;br&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;&lt;br&gt;public class MemoizedSqrt&lt;br&gt;{&lt;br&gt;    private readonly ConcurrentDictionary&amp;lt;double, double&amp;gt; _cache = new ConcurrentDictionary&amp;lt;double, double&amp;gt;();&lt;br&gt;&lt;br&gt;    public double Sqrt(double x)&lt;br&gt;    {&lt;br&gt;        return _cache.GetOrAdd(x,&lt;br&gt;                               Math.Sqrt);&lt;br&gt;    }&lt;br&gt;}&lt;br&gt;&lt;br&gt;...&lt;br&gt;&lt;br&gt;var sqrt_memoized = Memoize&amp;lt;double, double&amp;gt;(Math.Sqrt);&lt;br&gt;var y = sqrt_memoized(sqrt_memoized(a)) + 2 * sqrt_memoized(b) * sqrt_memoized(a);&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;&amp;nbsp; &lt;p&gt;This is much nicer – it has now hidden away the cache inside of a class, but we still have to write a different class for each function we want to memoize. &lt;br&gt;&lt;br /&gt;&lt;p&gt;So let’s look at a different way of doing this – imagine we had a magic box which took in a function like Math.Sqrt, and returned the sqrt_memoized for us, automatically encapsulating a class with the cache in it.&lt;br&gt;&lt;br /&gt;&lt;p&gt;Imagine no further – we can build such a box. It’s simply a &lt;i&gt;higher-order &lt;/i&gt;function which takes a function as an argument and returns another function.&lt;br&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;&lt;br&gt;public static Func&amp;lt;TDomain, TRange&amp;gt; Memoize&amp;lt;TDomain, TRange&amp;gt;(Func&amp;lt;TDomain, TRange&amp;gt; f)&lt;br&gt;{&lt;br&gt;    private class M&lt;br&gt;    {&lt;br&gt;        private readonly ConcurrentDictionary&amp;lt;TDomain, TRange&amp;gt; _cache = new ConcurrentDictionary&amp;lt;TDomain, TRange&amp;gt;();&lt;br&gt;        private readonly Func&amp;lt;TDomain, TRange&amp;gt; _f;&lt;br&gt;&lt;br&gt;        public M(Func&amp;lt;TDomain, TRange&amp;gt; f)&lt;br&gt;        {&lt;br&gt;             _f = f;&lt;br&gt;        }&lt;br&gt;&lt;br&gt;        public TRange MemoizedF(TDomain x)&lt;br&gt;        {&lt;br&gt;             return _cache.GetOrAdd(x,&lt;br&gt;                                    _f);&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;&lt;br&gt;    return new M&amp;lt;TDomain, TRange&amp;gt;(f).MemoizedF;&lt;br&gt;}&lt;br&gt;&lt;br&gt;...&lt;br&gt;&lt;br&gt;var sqrt_memoized = Memoize&amp;lt;double, double&amp;gt;(Math.Sqrt);&lt;br&gt;var y = sqrt_memoized(sqrt_memoized(a)) + 2 * sqrt_memoized(b) * sqrt_memoized(a);&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;And there you have it – one single function to memoize &lt;i&gt;any&lt;/i&gt; single-argument function, all neatly packaged into a static method.&lt;br&gt;&lt;br /&gt;&lt;p&gt;All done!&lt;br&gt;&lt;br /&gt;&lt;p&gt;What? Howls of protest? This couldn’t work?&lt;br&gt;&lt;br /&gt;&lt;p&gt;Of course it won’t work! There’s no way to embed the class M inside the Memoize function. But we have a nice, elegant solution and we don’t want to mess it up by making the class M public…what do we do?&lt;br&gt;&lt;br /&gt;&lt;h4&gt;Getting some Closure&lt;/h4&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;The trick to getting that inner embedded class inside the function is to let the compiler put it there instead of writing the class ourselves.&lt;br&gt;&lt;br /&gt;&lt;p&gt;Remember that we are writing a higher-order function, so we could just build and return the memoizing function in place.&lt;br&gt;&lt;br /&gt;&lt;p&gt;Consider the following code:&lt;br&gt;&lt;pre class=&quot;brush: csharp&quot;&gt;public static Func&amp;lt;TDomain, TRange&amp;gt; Memoize&amp;lt;TDomain, TRange&amp;gt;(Func&amp;lt;TDomain, TRange&amp;gt; f)&lt;br&gt;{&lt;br&gt;    var _cache = new ConcurrentDictionary&amp;lt;TDomain, TRange&amp;gt;();&lt;br&gt;    return _ =&amp;gt; _cache.GetOrAdd(_, f);&lt;br&gt;}&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Let’s break this down – ignoring the type arguments:&lt;br&gt;&lt;br /&gt;&lt;ul&gt;&lt;br&gt;&lt;br /&gt;&lt;li&gt;&lt;code&gt;Memoize&lt;/code&gt; is a function which takes in a function f and returns an anonymous function.&lt;br&gt;&lt;br /&gt;&lt;li&gt;The function has a local variable _cache to cache appropriately typed results against arguments.&lt;br&gt;&lt;br /&gt;&lt;li&gt;The result is a function which references the cache. The salient point to notice is that the _cache variable is &lt;i&gt;outside the scope&lt;/i&gt; of the result function. We say that the result function &lt;i&gt;closes over&lt;/i&gt; the _cache variable.&lt;br&gt;&lt;br /&gt;&lt;li&gt;The function returned requires a proper reference to the _cache variable even after the Memoize function exits.&lt;br&gt;&lt;br /&gt;&lt;li&gt;In order to keep the reference alive, the compiler creates an inner, anonymous class storing the closed variable and exposing a method representing the resultant function.&lt;br&gt;&lt;br /&gt;&lt;li&gt;The compiler then instantiates the class and returns a reference to the method, which now references the closed variable legally.&lt;br&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;In fact the anonymous class looks and behaves almost exactly the class we tried to sneak in.&lt;br&gt;&lt;br /&gt;&lt;p&gt;This construct is called a &lt;i&gt;closure&lt;/i&gt;, and is an excellent way to encapsulate state without creating classes and objects.&lt;br&gt;&lt;br /&gt;&lt;p&gt;In fact, the last code snippet is a general purpose memoizing function for functions of one argument, and you will agree is much more elegant than any of the other alternatives!&lt;br&gt;&lt;br /&gt;&lt;p&gt;&amp;nbsp; &lt;h4&gt;Summary&lt;/h4&gt;&lt;br&gt;&lt;br /&gt;&lt;ul&gt;&lt;br&gt;&lt;br /&gt;&lt;li&gt;SwissKnife provides a Memoize function to elegantly provide memoized versions of pure single-argument functions.&lt;br&gt;&lt;br /&gt;&lt;li&gt;We can use the functional programming principle of &lt;i&gt;higher-order functions&lt;/i&gt; to memoize pure functions to leverage &lt;i&gt;Referential Transparency&lt;/i&gt;. Memoizing functions ensure that functions are evaluated only once per argument value and the cached value of the result can be used subsequently.&lt;br&gt;&lt;br /&gt;&lt;li&gt;We use &lt;i&gt;closures&lt;/i&gt; to encapsulate the state associated with the cache.&lt;br&gt;&lt;/li&gt;&lt;/ul&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/1650083762313788531/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2013/11/functions-as-function-results.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/1650083762313788531'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/1650083762313788531'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2013/11/functions-as-function-results.html' title='Functions as Function Results'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-8709730654965181759</id><published>2013-11-02T20:15:00.001-07:00</published><updated>2013-11-14T11:12:33.016-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Functional"/><category scheme="http://www.blogger.com/atom/ns#" term="Lambda"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><category scheme="http://www.blogger.com/atom/ns#" term="Reflection"/><category scheme="http://www.blogger.com/atom/ns#" term="SwissKnife"/><title type='text'>Functions as Function Arguments</title><content type='html'>&lt;p&gt;&lt;em&gt;&lt;/em&gt;&amp;nbsp; &lt;p&gt;&lt;em&gt;This post talks about a set of utilities provided in the BrightSword SwissKnife library (&lt;a href=&quot;http://www.nuget.org/packages/BrightSword.SwissKnife/&quot; target=&quot;_blank&quot;&gt;nuget&lt;/a&gt;, &lt;a href=&quot;http://swissknife.codeplex.com/&quot; target=&quot;_blank&quot;&gt;codeplex&lt;/a&gt;).&lt;/em&gt;  &lt;p&gt;&lt;em&gt;Reflection is a commonly used meta-programming technique where run-time inspection of types allows for more elegant solutions in some cases. The .NET framework provides powerful primitives to use reflection, which have a nice orthogonal and consistent interface for the various type elements.&lt;/em&gt;  &lt;p&gt;&lt;em&gt;A necessary, but less desirable, consequence of an orthogonal interface is the ‘boilerplate’ nature of the code which uses different elements. There is typically a great deal of symmetry and similarity in the code, which generally leads to a cut-copy-paste kind of code-proliferation – and results in unmaintainable code. &lt;/em&gt; &lt;p&gt;&lt;em&gt;In this post, we’ll talk about the software techniques we can use to mitigate this form of code-proliferation, and actively develop a lean and maintainable utility without sacrificing flexibility.&lt;/em&gt;  &lt;p&gt;&lt;em&gt;You will find these utilities &lt;a href=&quot;http://swissknife.codeplex.com/SourceControl/latest#Library.BrightSword.SwissKnife/Reflection/TypeMemberDiscoverer.cs&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;, where there are a set of extension methods on the &lt;font face=&quot;Courier New&quot;&gt;Type &lt;/font&gt;type.&lt;/em&gt;&amp;nbsp; &lt;h3&gt;&amp;nbsp;&lt;/h3&gt; &lt;h4&gt;Reflection Utilities&lt;/h4&gt; &lt;p&gt;One of the fundamental principles of functional programming is the concept of a &lt;b&gt;First-Class Function&lt;/b&gt;.  &lt;p&gt;A language with a First Class function is one that allows functions to be treated exactly the same way as other first class entities such as variables and constants. This generally means that there is the concept of being able to pass in a function as an argument to another function (just like one can pass in a string as an argument), assign a function to a variable, or return the function as the result of a function.  &lt;p&gt;This is a very powerful concept, as it allows us to parameterize&lt;i&gt; logic&lt;/i&gt; just like we traditionally parameterize values.  &lt;h5&gt;GetAllProperties|GetAllMethods|GetAllEvents&lt;/h5&gt; &lt;p&gt;Consider the problem of reflecting over a type and enumerating over its properties:  &lt;p&gt;A naïve implementation of a function to enumerate a type’s properties might look like this: &lt;pre class=&quot;brush: csharp;&quot;&gt;public static IEnumerable&amp;lt;PropertyInfo&amp;gt; GetProperties(Type t) &lt;br&gt;{ &lt;br&gt;    foreach (var item in t.GetProperties()) &lt;br&gt;    { &lt;br&gt;        yield return item; &lt;br&gt;    } &lt;br&gt;}&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;An analogous method to enumerate methods would then be: &lt;pre class=&quot;brush: csharp;&quot;&gt;public static IEnumerable&amp;lt;MethodInfo&amp;gt; GetMethods(Type t) &lt;br&gt;{ &lt;br&gt;    foreach (var item in t.GetMethods()) &lt;br&gt;    { &lt;br&gt;        yield return item; &lt;br&gt;    } &lt;br&gt;}&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;The reason this is a naïve implementation is that interfaces do &lt;i&gt;not&lt;/i&gt; inherit, in the traditional sense of the term, the members of their base interfaces – rather they inherit the &lt;i&gt;requirement&lt;/i&gt; that the base interface is implemented as well. See &lt;a href=&quot;http://scrumofone.blogspot.com.au/2011/04/interfaces-and-inheritance.html&quot;&gt;my earlier post&lt;/a&gt; for the background to this problem. &lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;The complete solution involves recursively walk up the inheritance chain for interfaces, whilst keep track of interfaces seen before, and enumerating the members of each interface encountered. &lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;The code to do this is somewhat more involved: &lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static IEnumerable&amp;lt;PropertyInfo&amp;gt; GetInterfaceProperties(this Type type,&lt;br&gt;                                                               ISet&amp;lt;Type&amp;gt; processedInterfaces = null) &lt;br&gt;{&lt;br&gt;    Debug.Assert(type.IsInterface); &lt;br&gt;    &lt;br&gt;    processedInterfaces = processedInterfaces ?? new HashSet(); &lt;br&gt;    &lt;br&gt;    if (processedInterfaces.Contains(type)) &lt;br&gt;    { &lt;br&gt;        yield break;&lt;br&gt;    } &lt;br&gt;    &lt;br&gt;    foreach (var _pi in type.GetProperties())&lt;br&gt;    { &lt;br&gt;        yield return _pi; &lt;br&gt;    } &lt;br&gt;    &lt;br&gt;    foreach (var _pi in type.GetInterfaces()&lt;br&gt;                            .SelectMany(_ =&amp;gt; _.GetInterfaceProperties(processedInterfaces))) &lt;br&gt;    { &lt;br&gt;        yield return _pi;&lt;br&gt;    } &lt;br&gt;    &lt;br&gt;    processedInterfaces.Add(type);&lt;br&gt;}&lt;br&gt;&lt;/pre&gt;After taking a single glance at this code, one can imagine what the analogous code for Methods and Events might be – a lot of similar code with a few method calls and types changed. &lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;This is an ideal situation to use the functional programming support provided by C#. &lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;We can wrangle out the boilerplate code out of this to get: &lt;pre class=&quot;brush: csharp;&quot;&gt;public static IEnumerable&amp;lt;TMemberInfo&amp;gt; GetInterfaceMembers(this Type type, &lt;br&gt;                                                           Func&amp;lt;Type, IEnumerable&amp;lt;TMemberInfo&amp;gt;&amp;gt; accessor,&lt;br&gt;                                                           ISet&amp;lt;Type&amp;gt; processedInterfaces = null)&lt;br&gt;    where TMemberInfo : MemberInfo &lt;br&gt;{&lt;br&gt;    Debug.Assert(type.IsInterface); &lt;br&gt;    &lt;br&gt;    processedInterfaces = processedInterfaces ?? new HashSet(); &lt;br&gt;    &lt;br&gt;    if (processedInterfaces.Contains(type)) &lt;br&gt;    { &lt;br&gt;        yield break; &lt;br&gt;    } &lt;br&gt;&lt;br&gt;    foreach (var _pi in accessor(type)) &lt;br&gt;    { &lt;br&gt;        yield return _pi; &lt;br&gt;    } &lt;br&gt;&lt;br&gt;    foreach (var _pi in type.GetInterfaces()&lt;br&gt;                            .SelectMany(_ =&amp;gt; _.GetInterfaceMembers(accessor, processedInterfaces))) &lt;br&gt;    { &lt;br&gt;        yield return _pi; &lt;br&gt;    } &lt;br&gt;&lt;br&gt;    processedInterfaces.Add(type); &lt;br&gt;}&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;So by introducing the &amp;lt;TMember&amp;gt; type parameter to represent a MemberInfo generically, and providing a function argument accessor which provides a collection of members of the specified type, we can abstract out the boilerplate code and parameterize the accessor logic. &lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;SwissKnife uses this approach to provide a set of &lt;i&gt;extension methods&lt;/i&gt; on the Type type, which simply parameterize a common function: &lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static IEnumerable&amp;lt;PropertyInfo&amp;gt; GetAllProperties(this Type _this, BindingFlags bindingFlags = DefaultBindingFlags) &lt;br&gt;{ &lt;br&gt;    return _this.GetAllMembers((_type, _bindingFlags) =&amp;gt; _type.GetProperties(_bindingFlags), bindingFlags); &lt;br&gt;} &lt;br&gt;&lt;br&gt;public static IEnumerable&amp;lt;MethodInfo&amp;gt; GetAllMethods(this Type _this, BindingFlags bindingFlags = DefaultBindingFlags) &lt;br&gt;{ &lt;br&gt;    return _this.GetAllMembers((_type, _bindingFlags) =&amp;gt; _type.GetMethods(_bindingFlags), bindingFlags); &lt;br&gt;} &lt;br&gt;&lt;br&gt;public static IEnumerable&amp;lt;EventInfo&amp;gt; GetAllEvents(this Type _this, BindingFlags bindingFlags = DefaultBindingFlags) &lt;br&gt;{ &lt;br&gt;    return _this.GetAllMembers((_type, _bindingFlags) =&amp;gt; _type.GetEvents(_bindingFlags), bindingFlags); &lt;br&gt;}&lt;/pre&gt;which allows for usage like this: &lt;pre class=&quot;brush: csharp;&quot;&gt;var readonlyProperties = typeof (T).GetAllProperties()&lt;br&gt;				   .Where(_ =&amp;gt; !_.CanWrite || _.GetSetMethod() == null);&lt;/pre&gt;&lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;A functional approach to coding up these functions has reduced coding noise and resulted in simpler, easier-to-use, easier-to-understand and easier-to-maintain code.&lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;h4&gt;Summary&lt;/h4&gt;&lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;ul&gt;&lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;li&gt;SwissKnife provides a utility mechanism to simplify reflection over a type to enumerate different types of members. This is especially useful in the case of interface hierarchies. &lt;br&gt;&lt;br&gt;&lt;br /&gt;&lt;li&gt;We can use the functional programming principle of &lt;i&gt;first-class functions&lt;/i&gt; to extract boilerplate code and parameterize logic in addition to values. This makes code easier to maintain. &lt;/li&gt;&lt;/ul&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/8709730654965181759/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2013/11/functions-as-function-arguments.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/8709730654965181759'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/8709730654965181759'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2013/11/functions-as-function-arguments.html' title='Functions as Function Arguments'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-4765496816704161737</id><published>2013-10-31T04:59:00.001-07:00</published><updated>2013-11-05T18:57:41.638-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Functional"/><category scheme="http://www.blogger.com/atom/ns#" term="Languages"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><category scheme="http://www.blogger.com/atom/ns#" term="SwissKnife"/><title type='text'>Putting the Fun in Functional Programming</title><content type='html'>&lt;h4&gt;&amp;nbsp;&lt;/h4&gt; &lt;h4&gt;Introduction&lt;/h4&gt; &lt;p&gt;Like everyone who has been programming for some time, I have a set of tools and utility functions which I have developed over time, and reuse often.  &lt;p&gt;My library of utilities has been available for some time both as &lt;a href=&quot;http://swissknife.codeplex.com&quot;&gt;open-sourced code&lt;/a&gt; and a free-to-use &lt;a href=&quot;https://www.nuget.org/packages/BrightSword.SwissKnife/&quot;&gt;NuGet package&lt;/a&gt;.  &lt;p&gt;The purpose of this series of posts is to talk about observations in my evolution as a functional programmer, and how the implementation and approaches I tend to take these days increasingly use functional concepts.  &lt;p&gt;As you browse the code, you’ll come across more utilities than the ones discussed in this blog series. This series is going to try and focus on those utilities which demonstrate some facet of functional programming.  &lt;h4&gt;&amp;nbsp;&lt;/h4&gt; &lt;h4&gt;What is Functional Programming? Why do I care?&lt;/h4&gt; &lt;p&gt;Functional Programming is a programming paradigm that treats programs as the evaluation of mathematical functions and expressions.  &lt;p&gt;One can conceive of a kind of spectrum of programming abstraction:  &lt;ul&gt; &lt;li&gt;Assembly Language which abstracts away parameterized opcodes  &lt;li&gt;FORTRAN, COBOL and BASIC introduce control flow statements and subroutines  &lt;li&gt;Pascal and C which allow for rich user-defined types, abstracting data and largely obviating the GOTO construct  &lt;li&gt;Modula-2 and C++ which introduce concepts of objects maintaining state, encapsulating both data and related functions  &lt;li&gt;Java and C# 1.0 which introduce concepts of managed memory and a virtual runtime environment, allowing for simpler creation of objects and popularizing Exceptions  &lt;li&gt;Modern C# which introduces concepts of true type parameterization, lambdas and attributes. LINQ is a very powerful programming extension which is available here.  &lt;li&gt;Scala introduces type classes and F# provides full type inference. These languages also use pattern-matching and recursion constructs to obviate some familiar imperative programming patterns.  &lt;li&gt;LISP, a proto-functional language, is actually a multi-paradigm language, and as such, generally provides a great introduction to programming. LISP relies heavily on recursion, obviates some of the familiar programming constructs such as &lt;i&gt;for&lt;/i&gt; loops and variables, introduces the concept of isomorphic code and data which makes it trivial to generate and immediately execute a function, and provides powerful meta-programming support.  &lt;li&gt;Haskell, which emphasizes purity to the extent of introducing the concept of IO Monads to limit the impact of side-effects on a pure functional language.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Other &lt;a href=&quot;http://www.paulgraham.com/avg.html&quot; target=&quot;_blank&quot;&gt;authors&lt;/a&gt; have spoken cogently about the experience of a programmer skilled in a language somewhere in the spectrum (say a Java expert) looking up towards a more abstract language and not being able to comprehend &lt;i&gt;why&lt;/i&gt; a construct or concept from that language would be useful or even necessary.  &lt;p&gt;Therefore, it isn’t unreasonable to ask &lt;i&gt;why&lt;/i&gt; we would need a functional programming perspective when we can do almost all we need with our daily programming language. Hopefully, as we go through this blog series, we’ll get a flavour of the kinds of things that functional programming makes easier, or possible!  &lt;h4&gt;&amp;nbsp;&lt;/h4&gt; &lt;h4&gt;What’s coming down the track?&lt;/h4&gt; &lt;ul&gt; &lt;li&gt;&lt;a href=&quot;http://scrumofone.blogspot.com/2013/11/functions-as-function-arguments.html&quot;&gt;Functions as Function Arguments&lt;/a&gt;  &lt;li&gt;&lt;a href=&quot;http://scrumofone.blogspot.com/2013/11/functions-as-function-results.html&quot;&gt;Functions as Function Results&lt;/a&gt; &lt;li&gt;&lt;a href=&quot;http://scrumofone.blogspot.com/2013/11/classes-and-memoization-neat-c-trick.html&quot;&gt;Classes and Memoization - A Neat C# Trick&lt;/a&gt;&amp;nbsp; &lt;li&gt;Introduction to Monads  &lt;li&gt;The trouble with Exceptions!  &lt;li&gt;Static methods and Classes&lt;/li&gt;&lt;/ul&gt; &lt;h4&gt;&amp;nbsp;&lt;/h4&gt; &lt;h4&gt;Acknowledgements&lt;/h4&gt; &lt;p&gt;My involvement with functional programming goes all the way back to college, where teachers like &lt;a href=&quot;https://twitter.com/takis_metaxas&quot;&gt;Dr. Takis Metaxis&lt;/a&gt; introduced me to symbolic computing with LISP.  &lt;p&gt;I highly recommend reading &lt;a href=&quot;http://www.amazon.com/dp/1933988924&quot;&gt;Real-World Functional Programming: With Examples in F# and C#&lt;/a&gt; by &lt;a href=&quot;https://twitter.com/tomaspetricek&quot;&gt;Tomas Petricek&lt;/a&gt; and &lt;a href=&quot;https://twitter.com/jonskeet&quot;&gt;Jon Skeet&lt;/a&gt;.  &lt;p&gt;If you get a chance to listen to the &lt;i&gt;“Programming with Purity”&lt;/i&gt; talk by &lt;a href=&quot;https://twitter.com/linqpad&quot;&gt;Joseph Albahari&lt;/a&gt;, do so – he has one of the most lucid explanations of Monads around!  &lt;p&gt;I have stood on the shoulders of giants by reading their blogs: The relevant posts by &lt;a href=&quot;http://ericlippert.com/category/monads/&quot;&gt;Eric Lippert&lt;/a&gt;, &lt;a href=&quot;http://blogs.msdn.com/b/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx&quot;&gt;Wes Dyer&lt;/a&gt; and &lt;a href=&quot;http://blogs.msdn.com/b/pfxteam/archive/2013/04/03/tasks-monads-and-linq.aspx&quot;&gt;Stephen Toub&lt;/a&gt; are especially enlightening. &lt;a href=&quot;http://mikehadlow.blogspot.com.au/2011/01/monads-in-c1-introduction.html&quot;&gt;Mike Hadlow’s&lt;/a&gt; blog is also good reading.  &lt;p&gt;For a truly mind-blowing experience, see the &lt;a href=&quot;http://channel9.msdn.com/Series/C9-Lectures-Erik-Meijer-Functional-Programming-Fundamentals/Lecture-Series-Erik-Meijer-Functional-Programming-Fundamentals-Chapter-1&quot;&gt;13-part series&lt;/a&gt; on Functional Programming by the one and only &lt;a href=&quot;https://twitter.com/headinthebox&quot;&gt;Erik Meijer&lt;/a&gt;, who, of course, has the last word on &lt;a href=&quot;http://www.infoq.com/interviews/meijer-monads&quot;&gt;monads&lt;/a&gt; and Category Theory!  &lt;p&gt;Do stick around, and I’ll try to explain how I synthesize some of these concepts into tools that I use frequently.&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/4765496816704161737/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2013/10/putting-fun-in-functional-programming.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/4765496816704161737'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/4765496816704161737'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2013/10/putting-fun-in-functional-programming.html' title='Putting the Fun in Functional Programming'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-7792303468434084048</id><published>2013-10-29T04:08:00.001-07:00</published><updated>2013-10-29T04:46:24.466-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Cloud Architecture Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><category scheme="http://www.blogger.com/atom/ns#" term="TechEd 2013"/><category scheme="http://www.blogger.com/atom/ns#" term="Windows Azure"/><title type='text'>It’s been a while…but a lot has happened!</title><content type='html'>&lt;p&gt;Can’t believe it’s been a whole year since I blogged anything!&lt;/p&gt; &lt;p&gt;And what a year it’s been!&lt;/p&gt; &lt;p&gt;This year has turned out to be one of the more interesting ones in my career – lots of very cool stuff that’s been taking up all my time…now that it’s coming to a close, I’m going to write up some blog posts to talk about what has happened!&lt;/p&gt; &lt;h3&gt;Daily work stuff&lt;/h3&gt; &lt;p&gt;In my day job, I work for a software development company that builds accounting software which runs in the cloud. The flagship product – the one I work on – is a .NET rewrite of a very successful C++/ISAM desktop app. The rewrite began as a desktop application replacement so it was designed as such, but with the emergence of cloud technologies, we decided to make the app a hybrid and offer a rich client interface to a cloud service.&lt;/p&gt; &lt;p&gt;The basic premise was a good one – the architecture was well layered so we were able to stick the internet between the server and the client and get the thing to run. However, the devil in the details was performance – the desktop application, quite reasonably, expected to have a fast, fat connection to a local database, but that changed once we separated the UI from the server.&lt;/p&gt; &lt;p&gt;Over the last couple of years, we tried all the quick wins and got the app out, but performance was still sub-optimal and we needed to come up with some fundamental changes to break the problem.&lt;/p&gt; &lt;p&gt;At the start of this year, a couple of us was given the opportunity to go in with a sledgehammer and try to break the problem out. In six weeks we had a pattern for some drastic improvements and we’ve spent the better part of this year rolling that pattern out through the most performance sensitive areas.&lt;/p&gt; &lt;p&gt;Big win! &lt;/p&gt; &lt;p&gt;I’ll blog about some of the technical approaches we have taken to get these dramatic improvements, but it’s safe to say that they are not for the faint-hearted!&lt;/p&gt; &lt;p&gt;We actually rounded off the last year with 3 months of really creative work building the first cut of the MYOB API. Working with &lt;a href=&quot;https://twitter.com/h_desai&quot; target=&quot;_blank&quot;&gt;@H_Desai&lt;/a&gt; and building stuff with ASP.NET Web API was a pretty satisfying experience!&lt;/p&gt; &lt;h3&gt;Open Source Mania&lt;/h3&gt; &lt;p&gt;In my copious free time (ha ha) I decided to clean up and open source a whole bunch of stuff. &lt;/p&gt; &lt;p&gt;Amongst the weaponry that is now public are:&lt;/p&gt; &lt;h4&gt;&lt;a href=&quot;http://swissknife.codeplex.com/&quot;&gt;BrightSword SwissKnife&lt;/a&gt;&lt;/h4&gt; &lt;p&gt;A&amp;nbsp; (mostly functional-programming based) set of utilities to help with everyday programming. &lt;/p&gt; &lt;p&gt;I’ve got a blog series on practical functional programming which centres around SwissKnife coming.&lt;/p&gt; &lt;p&gt;Warning: Contains Monads.&lt;/p&gt; &lt;h4&gt;&lt;a href=&quot;https://bitbucket.org/johnazariah/brightsword.squid&quot;&gt;BrightSword Squid&lt;/a&gt;&amp;nbsp;&lt;/h4&gt; &lt;p&gt;Rhino Mocks is a nice way to create anonymous types for interfaces but it is slow as all heck and a bit unwieldy, so I decided to write a fast library to generate DTOs with behaviours for general purpose use. MVVM patterns with Property Change Notifications work straight from the tin! And it’s 3 orders of magnitude faster than Rhino!&lt;/p&gt; &lt;p&gt;Contains lots of nasty nasty IL and Reflection.Emit!&lt;/p&gt; &lt;h4&gt;BrightSword Pegasus &lt;/h4&gt; &lt;p&gt;A reference library for CQRS and (Dynamic) Queue Centric Workflows based on Windows Azure. This thing is seriously cool and makes short work of writing extensible, scalable cloud applications.&lt;/p&gt; &lt;p&gt;Most of the stuff is pretty well tested – and I even set up my own automated build-pipeline to monitor source control, compile, test and upload to nuget. So all these libraries can be referenced and used through nuget.&lt;/p&gt; &lt;p&gt;Use the Nuget Packages. Fork the repos. Submit Pull requests. &lt;/p&gt; &lt;h3&gt;The Cloud Architecture Talk&lt;/h3&gt; &lt;p&gt;&lt;a href=&quot;https://twitter.com/maheshkrishnan&quot; target=&quot;_blank&quot;&gt;@MaheshKrishnan&lt;/a&gt; and I have been doing talks together for a few years now, and we spend a fair bit of our time idly gossiping about technology and trends. We observed that the best-practice software patterns for the cloud aren’t well articulated and well understood by the community at large, so we decided to build a talk around the most common patterns.&lt;/p&gt; &lt;p&gt;We built a application to demonstrate the patterns as well, and drew up some diagrams. Unlike most of our other talks, we demonstrate very little code in the talk itself, but the code is all open source.&lt;/p&gt; &lt;p&gt;We are both humbled and pleasantly surprised by its reception!&lt;/p&gt; &lt;p&gt;So far, we’ve given it at:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;The DDD! Melbourne Conference  &lt;li&gt;MYOB technical brown bag series  &lt;li&gt;Melbourne Azure Meetup &amp;amp; VIC.NET  &lt;li&gt;Singapore .NET Dev SIG  &lt;li&gt;&lt;a href=&quot;http://channel9.msdn.com/Events/TechEd/Australia/2013/AZR322&quot; target=&quot;_blank&quot;&gt;TechEd Australia 2013&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;em&gt;&lt;strong&gt;And we have been invited to give it at NDC London!&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt; &lt;p&gt;Yes. That’s right! We’re speaking at NDC London!&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;http://www.ndc-london.com/&quot; target=&quot;_blank&quot;&gt;&lt;img title=&quot;ndc_london&quot; style=&quot;border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px&quot; border=&quot;0&quot; alt=&quot;ndc_london&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbtrNrUi02PXOloRk_wshwEyXEKAwCLPq_nukFmrJl_WBv-Zbxc3-O5HMgrEchufuQbuaB2yR3w7nW7Ssjb9lRk2XA6dP76_sn0fmSZd96Govh9-YfKUlgEePlgmBlCQGDpmtSaNNbW2IC/?imgmax=800&quot; width=&quot;438&quot; height=&quot;128&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;TechEd Australia 2013&lt;/h3&gt; &lt;p&gt;This year’s TechEd was pretty special!&lt;/p&gt; &lt;p&gt;Went to the Gold Coast with &lt;a href=&quot;https://twitter.com/simonraikallen&quot; target=&quot;_blank&quot;&gt;@simonraikallen&lt;/a&gt;, &lt;a href=&quot;https://twitter.com/couchcoder&quot; target=&quot;_blank&quot;&gt;@couchcoder&lt;/a&gt; and &lt;a href=&quot;https://twitter.com/shaun_a_wilde&quot; target=&quot;_blank&quot;&gt;@shaun_a_wilde.&lt;/a&gt; &lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhygSBwQ-jlEzdU_JVgZMiTaC-VCYkOe98B2rNFcMjGk7gi2VrfnySZRohQyJ8qesHiF35hfjALk5BgmFgnk1J-InJ7zGkgbT3bYdXjXe7pbBmG0keC25Ifxkv9SDaOE8S_rRdMZlGHgJ7g/s1600-h/20130905_174921%25255B4%25255D.jpg&quot;&gt;&lt;img title=&quot;20130905_174921&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;20130905_174921&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhEdTtoP3Bld55-0kwynaZKEOeFi7Co0rz3rv32GyMJFivW1t14jObOlV31Sgm1T2V2GDAK6DqldTecenB-wFZ36H_rPLY4MLWhPamQVekdnqazbccuMK35Dq2pcPjz7uDVvTA37YVSuEH8/?imgmax=800&quot; width=&quot;569&quot; height=&quot;430&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Hanging with @shaun_a_wilde and @couch_coder&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiZgiIrk3QbhidNO601BK__dkTeswwK7maBI88LOm4-z8y4yZEbMgFVTK-RrFQznqFcj16Hon9G-gk5EuV_aZcbWHEpJtSlYN4FPB0gIXMtkTKR0vjrJL5kc0fTYH8YM78q9KljPK70bGC/s1600-h/IMG_9933%25255B3%25255D.jpg&quot;&gt;&lt;img title=&quot;IMG_9933&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;IMG_9933&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhHjgctedVBBShNxmn6kcwoQUbBtA95LId8JXXeNKg8DIosuG8InE5MH2gDpIj41kVJnpntPpOSmTWUNj9DcUe-UgYN8rIka5sWeNIuug0qt0LzLUbi_bJLjPPr04tUbJzPWfAUKsudL8YL/?imgmax=800&quot; width=&quot;569&quot; height=&quot;381&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;With &lt;a href=&quot;https://twitter.com/maheshkrishnan&quot; target=&quot;_blank&quot;&gt;@MaheshKrishnan&lt;/a&gt; at the Microsoft stand&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-y3lDQydZgroUL9-g7iX9oQFU47JD1qudHYMq9R09tKv-g94dmLIkD_8OpzJ9zYMMgCN7hgg3VAlArFdVrNaqzmd5ycFovKxZV13wtMXayH1kmimU9cp5O85285_JzkRM227LEtxNRd0i/s1600-h/20130906_164019%25255B5%25255D.jpg&quot;&gt;&lt;img title=&quot;20130906_164019&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;20130906_164019&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgOfLJeDRAkVQtPlAOu8sW0nWkrv8ft0na5kduilBtQ8SLc1ocI2R_La6d7x02b0FFmksgCAE_FjNrAOfI_xza-AXehAyJFCSswMfZBaW3cROYAMHCS1oDtJa5o8fAYa1myPhORyCr9zlzR/?imgmax=800&quot; width=&quot;569&quot; height=&quot;431&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-IvoOWP-hpq70Obr0d7fOjIdRHj5mebsbrugZxeRBlJySSvTNjPmru83vbqm2r3mxK1A78DL4xB9G-b6X2T1GuoMdwoKIIpIVcQYLlfiVEXaRk3UhmHf1rB04usHsadhXh2MFfw0yHNDk/s1600-h/20130906_164100%25255B4%25255D.jpg&quot;&gt;&lt;img title=&quot;20130906_164100&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;20130906_164100&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgUY-270-x5c_ZDScJT3ohqTGTeIbRp_QDk59D3OUC7DSn9XUVYLhHGTVKFd0uTz84AEsTB2HCgxoPCskF5zP7ySdbSL8C4qUDXUHU9oi5SDbLo2s6m5GpW9qkHFt1aLbnauSs7-WlrS8vs/?imgmax=800&quot; width=&quot;569&quot; height=&quot;430&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://twitter.com/maheshkrishnan&quot; target=&quot;_blank&quot;&gt;@MaheshKrishnan&lt;/a&gt; and I gave a slightly modified version of the Cloud Architecture Patterns talk focusing on the implementation aspects. It was pretty well received, and we got a fair bit of good feedback from the audience. Lively discussion and lots of questions are always a good sign that people paid attention to the material and that it was relevant.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZpgHumO5azOR05hqRAaoN0Ut9LCbMxXro3UFCuqxj6HFDL3DFRhrcxwl2mFVUv4zStLZTMzRLgvFCvzeaQvi0WFEeNhvsFA2lQdt1KPAfwm0F4CWM3MnzzoO_rVJH1wktNhrrnF-OC2SU/s1600-h/IMG_9957%25255B3%25255D.jpg&quot;&gt;&lt;img title=&quot;IMG_9957&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;IMG_9957&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPW4aYkCm9qzdiigBw3Z3KwhYPVRVhOrwrRMLT-9ZIkEnN62RgZIPOlO39vjq5nSiaWxtGJq4-xopHo6VPlDozYqirSxhf-nx21EXCt8fWfj6LNumx2QXEVv6BugRbbkcMjLBFysFT1gk9/?imgmax=800&quot; width=&quot;569&quot; height=&quot;381&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgibiEUnWbXFTxpEvSUQ0NEMvzkTH5oY_hi0Oc8vqxMi8xWtpWHX0Wip3vE6-T_fFaEmkZGRvrgECmlAwDzY6a_HqftFg4gY0AFSMwNHfvixhA4G_jQ-YFpNgVz_IQKgWX3pkR8Tbrqxw43/s1600-h/IMG_9962%25255B3%25255D.jpg&quot;&gt;&lt;img title=&quot;IMG_9962&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;IMG_9962&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikLC0Okl99IDGNTAXzkIYgYDjU3kmc0df5hTjfOAx_iPTYgExak-wMAdCNQBR6pfGg9aaxJtGw4_IvcPgSSwpOprcQFG7lg54dTEi7OhyIw_gzYMErcVpMQaDAW_CEqAFA_rbZqD2ggW0X/?imgmax=800&quot; width=&quot;569&quot; height=&quot;381&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Got to meet &lt;a href=&quot;https://twitter.com/linqpad&quot; target=&quot;_blank&quot;&gt;@linqpad&lt;/a&gt; – would’ve loved to have an hour pairing with him on some stuff to do with monads, but perhaps another day.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiI6PvlrKl40g0zrFE78Y0A2_mD5zVOc4NQBFlzEIt0vA7Pfc4PlT_ZWEM-7HHQvHXZs66m_0x_Ik_UMqkebX_23xayvgWor_uTFT9v5SthfpZpoNpOvV7s_ht1qmZFC6k3cVgWsqKeU-cX/s1600-h/20130904_211817%25255B3%25255D.jpg&quot;&gt;&lt;img title=&quot;20130904_211817&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;20130904_211817&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxy1wxSRoRj5vW61L9cBsDPn-rE-1mVYK8QLr9nct8s_D7KefJ4e_Fk0JW4ubY37p654aBL7JFfztQOckW550dwAOLWAGcQyJdYOEuqGdz0_ns5rrFfNKY0XVvTb5KaNxEUq_-aN-SUUba/?imgmax=800&quot; width=&quot;569&quot; height=&quot;429&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Met and hung out with the usual suspects…&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhB5CsEl4D1vJgflyVlc-Sx-Kvtc4Vtli6QqlD3raT3brepEdWRYYjvmnDHr0mZRgKJxc0NMohruWLOUguUO8iroFy-X0T99t1560tHl8Iax0Eh3vcd89guqPNTiFGEeDY64Ml1xfwKw8EY/s1600-h/3F0C9904%25255B7%25255D.jpg&quot;&gt;&lt;img title=&quot;3F0C9904&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;3F0C9904&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibPAFVD5am3bHMw4U7mRoQc8uFLpVlKgGe9YiuYqselnWNX2Kuujr0iyqVJ5dmiVxaBF_Sg21Q8x9P5tRY5cj8W4dH5dEPFRpvfpwnNMZx5jnTfWcyNCe9tVR3MCrI06MqPX3TVvtq-3wZ/?imgmax=800&quot; width=&quot;569&quot; height=&quot;383&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Hanging with &lt;a href=&quot;https://twitter.com/rockyh&quot; target=&quot;_blank&quot;&gt;@RockyH&lt;/a&gt;…&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEifNkJ8wBNYghyphenhyphentTYnvQn3jvlGmwEFBBHFw2bf8yXqce3SpAM_hhtXTFeeOzipSlno0VgbHIXr2XBy4VQRmqgOLaovkps59AYEuhCmW3MxrcbDF350kDgGeXedaNadAstuCPMtiG01twUpg/s1600-h/IMG_0523%25255B6%25255D.jpg&quot;&gt;&lt;img title=&quot;IMG_0523&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;IMG_0523&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiM7PSZ6GSReR2_IT6HV1UPr52meKWI1rhYcUiZ7oIWuHUTyITHIuylA7hS7xDaf_3whPC6dzaZXfasBd2ay1b0xMTWMZdDKwP9lUNGFM2_yR9N82N8r9NoPEZDMmO_hCU80CD_ChZaRohf/?imgmax=800&quot; width=&quot;569&quot; height=&quot;384&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;… &lt;a href=&quot;https://twitter.com/drmcghee&quot; target=&quot;_blank&quot;&gt;@drmcghee&lt;/a&gt; and &lt;a href=&quot;https://twitter.com/frankarr&quot; target=&quot;_blank&quot;&gt;@frankarr&lt;/a&gt;. Didn’t know at the time that this was the last TechEd Frank Arrigo was going to be at – so I’m glad we got this shot! &lt;/p&gt; &lt;p&gt;I won a 3D printer at the raffle, but wasn’t around to collect it so I lost it! I still get guys poking fun at me for this!&lt;/p&gt; &lt;p&gt;Our company had been selected as a case study for our use of Azure, and it was a pretty special privilege to represent them at the last, conference-wide Lock Note session. &lt;/p&gt; &lt;p&gt;It was made all the more special because the Microsoft CVP responsible for Azure – Scott Guthrie – was presenting the Lock Note, and I got a chance to get on stage with him and talk for five minutes about how we used Azure. &lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWQQLUH1VDzLa9H2wV3CT-BhnKvEKbS3nVomJmxxgt6M6VKi2az0c-cjFPLDOeAuATQ972RHJwHmo-0tF3yB3jqYF_9JWX4BxJku5zBrTGWrZk0gq2aFexmyMXDm4QFtM1S9o3LK-sWULa/s1600-h/20130906_154952%25255B3%25255D.jpg&quot;&gt;&lt;img title=&quot;20130906_154952&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;20130906_154952&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxxmsZT0q6yJyPV6-wJx_f0Ahj8Ar9Dd-HGfP-WQ2RZDX1Y_-3p1L6gf-TNytXmStV7YSkBBwvu8wgXFDw3GdTgEaoTqMvlwacki1Oa_DMWd3ppkWO6czVKSBXarULTGrWBLEgvCXhh06z/?imgmax=800&quot; width=&quot;569&quot; height=&quot;428&quot;&gt;&lt;/a&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFaYfl0BMf2QdZXE4qkFQ-UqYqMdNZDwNp-gpARJWPBvfwNFGPXWTDYFFqBG2UBZesW3XIAHd_PryxHXaVbmQ3Ndj6jo-lOU1g374lk35VOama9jUMBKEInYhQfdTZ62dPtHpCJBcRUhiY/s1600-h/IMG_0017%25255B3%25255D.jpg&quot;&gt;&lt;img title=&quot;IMG_0017&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;IMG_0017&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgRNoe-nMbmkpznPDig1iYeR262HgTuKjsk4EjZx9AwQLo47R31AwjMKIrWsyVAFuduBKPlFnjnQgjDSjKbNEluzviJY8coRcH-bEaCvUO_WTF_jQkqULie0TcLk7-VJRGOyS-PGk_yKOkG/?imgmax=800&quot; width=&quot;569&quot; height=&quot;381&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIaiDpCrdEZrN51QYxtYbZ47GhefHs96YWS5FjX7rkTMkWH57jFBDOoh51l94bQF2mgKLk3g3XyhKaKCIVPDjQ416MNTWLGvM4aDQoQPZ9UQaBtCb0s32kPXTN9-M9kD_mMtxIGH6gAPZP/s1600-h/IMG_0019%25255B3%25255D.jpg&quot;&gt;&lt;img title=&quot;IMG_0019&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;IMG_0019&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSvt_-kzRnyGH8IM4ikn58ENYUAnIcwDFdi37_wVzzVwn9wCR2Q-mGZnuCV-18Ujq5YhHAvS_1YzyqVgHWHT8WAQe4qOV9ip15DzEtNu_EIepYYISeP-RBHeYhJF0SIMPPFhjCxHmdUYYU/?imgmax=800&quot; width=&quot;569&quot; height=&quot;381&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-imdensPGq9pBWp2HJVwGSDwj8y8ksT-agl9qCX0Lgql5n2r5TDlNYjdkFIBi7PCuNrUzZRVZAOpRifNPoyt0Z5BUIPJJyMOAtVbqz7TsV74S5pdNwv_3G4j6tHmv7bhB_F2owjUaGUO0/s1600-h/IMG_0021%25255B3%25255D.jpg&quot;&gt;&lt;img title=&quot;IMG_0021&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;IMG_0021&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizCEvPsuP6-eSnpJqzgEFEmn8quqx-tILyeplWJWAzl3_BwOiEFH0eIMKruRemMw2_E-Cr-c6ogMhZQ7crWDKcn3iMhtDuxguV9Zt2wVLXNW9WPRDg1P2EX9AqfIPmB-Uv3wIOY22KGOs3/?imgmax=800&quot; width=&quot;304&quot; height=&quot;454&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;So the reason I wasn’t around to claim my printer was that I was hanging out with &lt;a href=&quot;https://twitter.com/scottgu&quot; target=&quot;_blank&quot;&gt;@ScottGu&lt;/a&gt;, rehearsing for the Lock Note, and I got to spend about half an hour just hanging with the Gu, who is, for the record, a very friendly, down-to-earth guy.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCsaDwaClFQwXBE1WzI8LmZ9PmKo9phmDN7ve7xd8oaSitbNJgke7QaudoRFSyDALTnqqJd_2kLAWtau8s7SjWWsqaWZ2eR6BYbzx2u1fNvg-aYTv9tKY8j8caRzoPt8TdENtoi1xtWUiL/s1600-h/IMG_0030%25255B3%25255D.jpg&quot;&gt;&lt;img title=&quot;IMG_0030&quot; style=&quot;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&quot; border=&quot;0&quot; alt=&quot;IMG_0030&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjfM4jH5j0rEpuXi9AsPVkRigVEclterczwn-UTAa8es0ursgOP9zn7tyR6qXMvFwBN3COgxILaZcVihCOH1srCSu1AVwsjI5OEi3uc-FbVtgSOhREH1lmtvldMWWuyCYvEPvfvG37vuSd6/?imgmax=800&quot; width=&quot;569&quot; height=&quot;381&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Pretty awesome, all told!&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/7792303468434084048/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2013/10/its-been-whilebut-lot-has-happened.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/7792303468434084048'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/7792303468434084048'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2013/10/its-been-whilebut-lot-has-happened.html' title='It’s been a while…but a lot has happened!'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbtrNrUi02PXOloRk_wshwEyXEKAwCLPq_nukFmrJl_WBv-Zbxc3-O5HMgrEchufuQbuaB2yR3w7nW7Ssjb9lRk2XA6dP76_sn0fmSZd96Govh9-YfKUlgEePlgmBlCQGDpmtSaNNbW2IC/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-9110372561870247735</id><published>2012-09-27T05:09:00.001-07:00</published><updated>2012-09-27T05:34:42.454-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="AZR331"/><category scheme="http://www.blogger.com/atom/ns#" term="Azure"/><category scheme="http://www.blogger.com/atom/ns#" term="C++"/><category scheme="http://www.blogger.com/atom/ns#" term="Casablanca"/><category scheme="http://www.blogger.com/atom/ns#" term="Cloud"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><category scheme="http://www.blogger.com/atom/ns#" term="TechEd 2012"/><title type='text'>Casablanca: C++ on Azure</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;We (&lt;em&gt;John Azariah and Mahesh Krishnan&lt;/em&gt;) gave a talk at Tech Ed Australia this year titled &lt;strong&gt;Casablanca: C++ on Azure&lt;/strong&gt;. The talk itself was slotted in at 8:15 am on the last day of Tech.Ed after a long party the night before. The crowd was small, and although we were initially disappointed by the turn out, we took heart in the fact that this was the most viewed &lt;a href=&quot;http://channel9.msdn.com/Events/TechEd/Australia/2012/AZR331&quot;&gt;&lt;font color=&quot;#ffff00&quot;&gt;online video&lt;/font&gt;&lt;/a&gt; at Tech.Ed this year – lots of five star ratings, Facebook likes and tweets.&amp;nbsp; This post gives you an introduction to Casablanca and highlights the things we talked about in the Tech.Ed presentation.  &lt;p&gt;&lt;em&gt;So, what is Casablanca?&lt;/em&gt; Casablanca is an incubation effort from Microsoft with the aim of providing an option for people to run C++ on Windows Azure. Until now, if you were a C++ programmer, the easiest option for you to use C++ would be to create a library and then &lt;em&gt;P/Invoke &lt;/em&gt;it from C# or VB.NET code. Casablanca gives you an option to do away with things like that.  &lt;p&gt;If you are a C++ developer and want to move your code to Azure right away, all we can say is “&lt;em&gt;Hold your horses!”&lt;/em&gt; It is, like we said, an incubation effort and&amp;nbsp; not production ready, yet. But you can download it from the Devlabs site, play with it and provide valuable feedback to the product team.  &lt;p&gt;You are also probably thinking, “&lt;em&gt;Why use C++?”&lt;/em&gt; The answer to that question is really &lt;em&gt;“Why not?”&lt;/em&gt; Microsoft has been providing developers the option to use various other languages/platforms such as java and Node.js to write for Azure, and now they are giving the same option to C++ programmers – use the language of their choice to write applications in Azure. Although there has been a bit of resurgence in C++ in the last couple of years, we are not really trying to sell C++ to you. If we are writing a Web App that talks to a database, then our first choice would probably still be ASP.NET MVC using C#, and maybe Entity Frameworks to talk to the DB. What we are trying to say is that you still need to use the right language and framework that works best for you, and if C# is the language you are comfortable with, then why change.  &lt;p&gt;On the other hand if you are using C++, then you probably already know why you want to continue using it. You may be using it for cross-platform compatibility or better performance or maybe you have lots of existing legacy code that you can’t be bothered porting across. Whatever the reason, Casablanca gives you an option to bring your C++ code to Azure without having to use another language to talk to its libraries.  &lt;p&gt;&amp;nbsp; &lt;h3&gt;The Node influence&lt;/h3&gt; &lt;p&gt;When you first start to look at Casablanca code, you will notice how some of the code has some resemblance to Node.js. A simple Hello World example in node will look like this -&lt;pre class=&quot;brush: js;&quot;&gt;var http = require(&#39;http&#39;);&lt;br /&gt;&lt;br /&gt;http.createServer(function (request, response) {&lt;br /&gt;&lt;br /&gt;  response.writeHead(200, &lt;br /&gt;                  {&#39;Content-Type&#39;: &#39;text/plain&#39;});&lt;br /&gt;  respose.end(&#39;Hello World!&#39;);&lt;br /&gt;&lt;br /&gt;}).listen(8080, &#39;127.0.0.1&#39;);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;The equivalent Hello World in C++ would look something like this -&lt;pre class=&quot;brush: cpp;&quot;&gt;using namespace http;&lt;br /&gt;&lt;br /&gt;http_listener::create(&quot;http://127.0.0.1:8080/&quot;,&lt;br /&gt;    [](http_request request)    &lt;br /&gt;    {        &lt;br /&gt;        return request.reply(status_codes::OK, &lt;br /&gt;                      &quot;text/plain&quot;, &quot;Hello World!&quot;);&lt;br /&gt;    }).listen();&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Notice the similarity? This isn’t by accident. The Casablanca team has been influenced a fair bit by Node and the simplicity by which you can code in node. &lt;br /&gt;&lt;p&gt;&amp;nbsp; &lt;h3&gt;Other inclusions&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;The proliferation of HTML, Web servers, web pages and the various languages to write web applications based on HTML happened in the 90s. C++ may have been around a lot longer than that, but surprisingly, it didn’t ride the HTML wave. Web servers were probably written in C++, but the applications themselves were written using much simpler languages like PHP. Of course, we did have CGI, which you could write using C++, and there were scores of web applications written in C++ but somehow, it really wasn’t the language of choice for writing them. (It didn’t help that scores of C++ developers moved on to things like Java, C#, and Ruby). What C++ needed was a good library or SDK to work with HTTP requests, and process them. &lt;br /&gt;&lt;p&gt;In addition to this,&lt;font style=&quot;background-color: #ffff00&quot;&gt;&lt;/font&gt; &lt;a href=&quot;http://en.wikipedia.org/wiki/Representational_state_transfer&quot;&gt;&lt;font color=&quot;#ffff00&quot;&gt;RESTful&lt;/font&gt;&lt;/a&gt; applications are becoming common place, and is increasingly becoming the preferred way to write services. So, the ability to easily process GET, PUT, POST and DELETE requests in C++ was also needed. &lt;br /&gt;&lt;p&gt;When we talk about RESTful apps, we also need to talk about the format in which the data is sent to/from the server. JSON seems to be the format of choice these days due to the ease with which it works with Javascript. &lt;br /&gt;&lt;p&gt;The Casablanca team took these things into consideration and added classes into Casablanca to work with the HTTP protocol, easily create RESTful apps and work with JSON. &lt;br /&gt;&lt;p&gt;To process the different HTTP actions and write a simple REST application to do CRUD operations, the code will look something like this:&lt;pre class=&quot;brush: cpp;&quot;&gt;auto listener = http_listener::create(L&quot;http://localhost:8082/books/&quot;);&lt;br /&gt;&lt;br /&gt;listener.support(http::methods::GET, [=](http_request request)&lt;br /&gt;{&lt;br /&gt;    //Read records from DB and send data back&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;listener.support(http::methods::POST, [=](http_request request)&lt;br /&gt;{&lt;br /&gt;    //Create record from data sent in Request body&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;listener.support(http::methods::PUT, [=](http_request request)&lt;br /&gt;{&lt;br /&gt;    //Update record based on data sent in Request body&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;listener.support(http::methods::DEL, [=](http_request request)&lt;br /&gt;{&lt;br /&gt;    //Delete&lt;br /&gt;});&lt;br /&gt;&lt;br /&gt;/* Prevent Listen() from returning until user hits &#39;Enter&#39; */ &lt;br /&gt;listener.listen([]() { fgetc(stdin); }).wait();&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Notice how easy it is to process the individual HTTP actions? So, how does conversion from and to Json objects work? To convert a C++ object to a Json object and send it back as a response, the code will look something like this:&lt;pre class=&quot;brush: cpp;&quot;&gt;using namespace http::json;&lt;br /&gt;...&lt;br /&gt;&lt;br /&gt;value jsonObj = value::object();&lt;br /&gt;jsonObj[L&quot;Isbn&quot;] = value::string(isbn);&lt;br /&gt;jsonObj[L&quot;Title&quot;] = value::string(title);&lt;br /&gt;...&lt;br /&gt;&lt;br /&gt;request.reply(http::status_codes::OK, jsonObj);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;To read json data from the request, the code will look something like this:&lt;pre class=&quot;brush: cpp;&quot;&gt;using namespace http::json;&lt;br /&gt;&lt;br /&gt;...&lt;br /&gt;&lt;br /&gt;value jsonValue = request.extract_json().get();&lt;br /&gt;&lt;br /&gt;isbn = jsonValue[L&quot;Isbn&quot;].as_string();&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;You have a collection? no problem, the following code snippet shows how you can create a Json array&lt;pre class=&quot;brush: cpp;&quot;&gt;...&lt;br /&gt;auto elements = http::json::value::element_vector();&lt;br /&gt;for (auto i = mymap.begin(); i != mymap.end(); ++i) &lt;br /&gt;{&lt;br /&gt;    T t = *i;&lt;br /&gt;&lt;br /&gt;    auto jsonOfT = ...; // Convert t to http::json::value&lt;br /&gt;    elements.insert(elements.end(), jsonOfT);&lt;br /&gt;}&lt;br /&gt;return http::json::value::array(elements);&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h3&gt;&amp;nbsp;&lt;/h3&gt;&lt;br /&gt;&lt;h3&gt;Azure Storage&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;If you are running your application in Windows Azure, then chances are you may also want to use Azure storage. Casablanca provides you with the libraries to be able to do this. The usage, again is quite simple, to create the various clients for blobs, queues and tables the usage is as follow:&lt;pre class=&quot;brush: cpp;&quot;&gt;storage_credentials creds(storageName, storageKey);&lt;br /&gt;&lt;br /&gt;cloud_table_client table_client(tableUrl, creds);&lt;br /&gt;cloud_blob_client blob_client(blobUrl, creds);&lt;br /&gt;cloud_queue_client queue_client(queueUrl, creds);&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Notice the consistent way of creating the various client objects. Once you have initialized them, then their usage is quite simple too. The following code snippet shows you how to read data from Table storage:&lt;pre class=&quot;brush: cpp;&quot;&gt;cloud_table table(table_client, tableName);&lt;br /&gt;query_params params;&lt;br /&gt;	...&lt;br /&gt;auto results = table.query_entities(params)&lt;br /&gt;                      .get().results();&lt;br /&gt;&lt;br /&gt;for (auto i =  results.begin(); &lt;br /&gt;          i != result_vector.end(); ++i) &lt;br /&gt;{&lt;br /&gt;    cloud_table_entity entity = *i;&lt;br /&gt;    entity.match_property(L&quot;ISBN&quot;, isbn);&lt;br /&gt;    ...&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Writing to Table storage is not difficult either, as seen in this code snippet:&lt;pre class=&quot;brush: cpp;&quot;&gt;cloud_table table(table_client, table_name);&lt;br /&gt;cloud_table_entity entity(partitionKey, rowKey);&lt;br /&gt;&lt;br /&gt;entity.set(L&quot;ISBN&quot;, isbn, cloud_table_entity::String);&lt;br /&gt;	...&lt;br /&gt;&lt;br /&gt;cloud_table.insert_or_replace_entity(entity);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Writing to blobs, and queues follow a similar pattern of usage. &lt;br /&gt;&lt;p&gt;&amp;nbsp; &lt;h3&gt;Async…&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;nother one of the main inclusions in Casablanca is the ability to do things in an asynchronous fashion. If you’ve looked at the way things are done on Windows Store applications or used &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/dd492418.aspx&quot;&gt;&lt;font color=&quot;#ffff00&quot;&gt;Parallel Patterns Library&lt;/font&gt;&lt;/a&gt; (PPL), then you would already be familiar with the “promise” syntax. In the previous code snippets, we resisted the urge to use it, as we hadn’t introduced it yet. &lt;br /&gt;&lt;p&gt;&amp;nbsp; &lt;h3&gt;… and Client-Side Libraries&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Also, we have been talking mainly about the server side use of Casablanca, but another thing to highlight is the fact that it can also be used to do client side programming. The following code shows the client side use of Casablanca and how promises can be used:&lt;pre class=&quot;brush: cpp;&quot;&gt;http::client::http_client client(L&quot;http://someurl/&quot;);&lt;br /&gt;client.request(methods::GET, L&quot;/foo.html&quot;)&lt;br /&gt;.then(&lt;br /&gt;      [=](pplx::task task)&lt;br /&gt;      {&lt;br /&gt;         http_response response = task.get();&lt;br /&gt;         //Do something with response&lt;br /&gt;         ...&lt;br /&gt;      });&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;If you need to find out more about ppl and promises, then you should read the article &lt;font color=&quot;#ffff00&quot;&gt;“&lt;/font&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/magazine/hh781020.aspx&quot;&gt;&lt;font color=&quot;#ffff00&quot;&gt;Asynchronous Programming in C++&lt;/font&gt;&lt;/a&gt;&lt;font color=&quot;#ffff00&quot;&gt;”&lt;/font&gt; written by Artur Laksberg in the MSDN magazine. &lt;br /&gt;&lt;p&gt;&amp;nbsp; &lt;h3&gt;Wait, there is more…but first lets get started&lt;/h3&gt;&lt;br /&gt;&lt;p&gt;Casablanca has also been influenced by Erlang, and the &lt;a href=&quot;http://ruben.savanne.be/articles/concurrency-in-erlang-scala&quot;&gt;&lt;font color=&quot;#ffff00&quot;&gt;concept of Actors&lt;/font&gt;&lt;/a&gt;&lt;font color=&quot;#ffff00&quot;&gt;,&lt;/font&gt; but let’s talk about it another post. To get started with Casablanca, download it from the &lt;a href=&quot;http://msdn.microsoft.com/en-us/devlabs/casablanca.aspx&quot;&gt;&lt;font color=&quot;#ffff00&quot;&gt;DevLabs&lt;/font&gt;&lt;/a&gt; site. It is available for both VS 2010 and 2012. &lt;br /&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtFwJcPFvl4p9TsWd8QTCaX71j-wuLcDjv9DThJFdpSOGU9aevdXKfY-ycu6hVKYg3Nrl3ltFesLx6ADJv1QlQH6Q7JRHxnIqnS_zMjs8PZ1HeX0JT0GomuLyVFx0EZPhbRhvddtOY7djC/s1600-h/image012%25255B3%25255D.jpg&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;image012&quot; border=&quot;0&quot; alt=&quot;image012&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhG8hWpIGr3nYqFD-QW8BBRfFAQX5gBd666siNwWxiM0BaEaglVy1tWnSIBKkFqZQ2DJj_G6b0nXLF6CrAjhoqdxLVxQERrXncRfhrJVanrrbCT50Rj0dTlNhq5wTHZ2Gj0NpCHBOsjNHJX/?imgmax=800&quot; width=&quot;538&quot; height=&quot;213&quot;&gt;&lt;/a&gt;&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/9110372561870247735/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2012/09/casablanca-c-on-azure.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/9110372561870247735'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/9110372561870247735'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2012/09/casablanca-c-on-azure.html' title='Casablanca: C++ on Azure'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhG8hWpIGr3nYqFD-QW8BBRfFAQX5gBd666siNwWxiM0BaEaglVy1tWnSIBKkFqZQ2DJj_G6b0nXLF6CrAjhoqdxLVxQERrXncRfhrJVanrrbCT50Rj0dTlNhq5wTHZ2Gj0NpCHBOsjNHJX/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-4257721281658203288</id><published>2012-09-25T16:37:00.001-07:00</published><updated>2012-09-25T16:37:33.462-07:00</updated><title type='text'>I’m back!</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;It’s been a crazy year since TechEd Australia 2011, and I’ve been strangely quiet…&lt;/p&gt; &lt;p&gt;But I’m back now…&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/4257721281658203288/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2012/09/im-back.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/4257721281658203288'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/4257721281658203288'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2012/09/im-back.html' title='I’m back!'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-119789124204738038</id><published>2011-08-27T10:38:00.001-07:00</published><updated>2011-08-27T10:46:24.706-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Cloud"/><category scheme="http://www.blogger.com/atom/ns#" term="COS204"/><category scheme="http://www.blogger.com/atom/ns#" term="SQL Azure"/><category scheme="http://www.blogger.com/atom/ns#" term="TechEd 2011"/><category scheme="http://www.blogger.com/atom/ns#" term="Windows Azure"/><title type='text'>Migrating a Web Application to Azure: Step 4</title><content type='html'>&lt;h3&gt;&lt;font color=&quot;#4bacc6&quot;&gt;Moving the application to Windows Azure&lt;/font&gt;&lt;/h3&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;h2&gt;A New Project&lt;/h2&gt; &lt;p&gt;The first step is to add a new cloud project to the solution.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxoJs87_ZMPFYVhqRCu-rXMB82lxXkQqHBlMGto2kSM1EQ4HDdeRN5pfyPjnjIeNq468TH9tkA1AxthD8Y74lYMSsYmeRUEjnFUvbSW_4V7QSGGZIzY-YDGecQd3QEdisztMKDzlLhF2LY/s1600-h/create_new_cloud_project%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;create_new_cloud_project&quot; border=&quot;0&quot; alt=&quot;create_new_cloud_project&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinWxrxzrYf2Vm6gfULcPmKgG-tH5-q88otKwok_6sFziKCdldvgd9tqIGchBQ-kA-INMXEEhDPiOYIPXQl50SBg37KX2dnqwyQ9D1vpIoZDyKZITSLZrDfwwJumCt3A3JyOzAZ57tleCyJ/?imgmax=800&quot; width=&quot;604&quot; height=&quot;419&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Ensure that you do &lt;em&gt;not &lt;/em&gt;add any web or worker roles.&lt;/p&gt; &lt;p&gt;We will convert the existing web application within the solution to a Web Role in the Azure Project.&lt;/p&gt; &lt;p&gt;Right Click on the ‘Roles’ folder in the Azure Project, select ‘Add’ and then ‘Web Role Project in solution…’. &lt;/p&gt; &lt;p&gt;Select the web application – in this case ‘SharPix_Step2’&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTQ6ijiY4Rm3w1shK798DhAZjDmbKpYZYv18qiGT8z8Vig23q_RsEf6_V-vGwQ33Qty9B_5gjDU17rqQ-Co1t0aeSFcp7Lq4nsnEYzXHCh0WitT5cZqfxYZVh4cPHEHW_4huvYbFyzo7YU/s1600-h/add_web_role%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;add_web_role&quot; border=&quot;0&quot; alt=&quot;add_web_role&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAW3YkIDpSgAcMUPlhf2-Oq3aBUFuTbI1RfelqYYtEj2Umjxqf06z8n-5bGWSth-7GlgzmtyoFR-fz8MEIIN70GFlb6ggMqdigoe2ngYIAKg_duHxm4SQEnPmo6X6hVcGJlNh9ydEMM9cX/?imgmax=800&quot; width=&quot;604&quot; height=&quot;269&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;After adding the project as a Web Role, it should look like this:&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiN-VZWW9nEhxF8zNSh-wcMjQtF-AhPT8uqSo4nt7e8miz2dM6F3RHSouh3B9XuLRMppPrtdedRp_ECq-NAVtfkZvWkpEQxaPYnS26lmxHWvZzAFFfYHqKOYL4E2qpqvoGK6HoudYTXkAtR/s1600-h/web_role_added%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;web_role_added&quot; border=&quot;0&quot; alt=&quot;web_role_added&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhO8dAQXDQVDhLwyCrRN50bjtnXCGbO_8mhipIYZijgLFcVnBt8SpvilCo-jImNXB5RRpM01BnVRG4ZehXcuhqEBlcE51zjfoYbTj4nmXfRWAg9ypAjLeBtF9P5ICS4WtnC-Zkq-EgOiicx/?imgmax=800&quot; width=&quot;485&quot; height=&quot;204&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Right-Click on the ‘SharPix_Step2’ role and select ‘Properties’&lt;/p&gt; &lt;p&gt;In this dialog, under normal circumstances, you should set Instance count to at least 2 to enable fail-over and scaling, and you would pick an appropriate VM size.&lt;/p&gt; &lt;p&gt;Also, we will start by using the Compute and Storage Emulators, so specify ‘UseDevelopmentStorage=true’ as the Diagnostics storage account.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3OLgnZhGkSuuPlbdgJ3IHrZb4F9bZAFxW1TgHau8DWOTWUBHNZXUU6VvF3lgdc514WiyRfwt9X2k-lqtsVhTYUEbO4cYCC5FjY9YimiyzbNk8g6u3ApztqGHbNS2hhX_3hrJBNn1L46Iv/s1600-h/web_role_properties%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;web_role_properties&quot; border=&quot;0&quot; alt=&quot;web_role_properties&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEij1PLqIRg9Dc7tdoUuMyfYTOR0NlZ7mq0FdemoYaLI4ph5QxaM-xerww6U9On_LEiaU1J8MSeiXAZH5lWZ_r2oiJdaiDzLEjL2AFv7qTU2CbRhTX2RppSE5KErHjDEPlCO5vGDxCSjFfgy/?imgmax=800&quot; width=&quot;604&quot; height=&quot;486&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h2&gt;Running In Emulator…&lt;/h2&gt; &lt;p&gt;Visual Studio comes with a tiny taste of the cloud built-in, in the form of the Storage and Compute Emulators. &lt;/p&gt; &lt;p&gt;Simply running our new Azure Project gives us:&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0fUbgAZlaRqS1Zp4XRYQE81BoEor4m3lJx0S3KC8DreHQs9NLCqnbX3HGiPnjP-aQhyxs_A3Sq_RrETH9xYaTgjDS2HdErUfOaiYB6bpUn9d45b_JKDL39CRDy999unMpQwWXHjYBaVg8/s1600-h/web_role_on_compute_emulator%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;web_role_on_compute_emulator&quot; border=&quot;0&quot; alt=&quot;web_role_on_compute_emulator&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgNPDV2LssYmOF_08Bpi9aVWWBXH0w872vp94RH-WDNNEf94UMrkbvG-ZpFBeuW7JNtyqPgAUydOyybgyud0IupUvvZ4QDE1s8UhRTPOzNkh9z4yC6zI-fybg_C2xqm7sYVzK1GH6myb7Ns/?imgmax=800&quot; width=&quot;604&quot; height=&quot;404&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Note the URL and the port number. This is no longer the Visual Studio Development Web Server, but the Compute Emulator in action. Examining the Windows Tray shows us that the emulators are running….&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgRx6voZdJGfcEg9nNqUsIGQdQ9AU7vzXrBLplTyU-y44kEJAJ4GevfeqAjsZ7BuFSuJBxjGcphe6ROzkNMmtRsO3fWaZRqL1kutTkNp4b8HsdOCKNDVuaGHIcsH2oLVzRMJmhJ0b_c4TSf/s1600-h/compute_emulator_is_running%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;compute_emulator_is_running&quot; border=&quot;0&quot; alt=&quot;compute_emulator_is_running&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxMvv5t0iWTmqgYi0mzVjBNbw_86MsN1pOcAGrD4iQ5L5atNIUb-1XGMGm0uEk1DvM88FO3RuF5ssGOY8LMzEGvBwTsulI-RKbzgFJXcbmtXY0ICXJBv8W2H4fqBTF5K6RXyHnWdNkl2rH/?imgmax=800&quot; width=&quot;304&quot; height=&quot;205&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h2&gt;To the cloud!&lt;/h2&gt; &lt;p&gt;In order to push the Azure Project to our cloud environment, we need to configure Visual Studio and set up our credentials to ensure that we carefully control access to our Azure environment.&lt;/p&gt; &lt;p&gt;Right-Click on the Azure Project and select ‘Publish’. We could use previously issued certificates here, or issue a new one for this project by selecting ‘Add’.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEix46cqfdqQVQdKwr4MqoLsc9pJhFsJImgyd5rscGcCw3luqEwKHxc2vANcYVhHb9SlDrNNbZnXaBd5MgLJSYs-uJoFEFyJjQXukITbgYsR7JOw0gtJuxlEZs7We9zUbVXFFcqQIj26HGud/s1600-h/publish_settings%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;publish_settings&quot; border=&quot;0&quot; alt=&quot;publish_settings&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjptIj8Huy9IEz5ij8otgNF8p3XP0zd6lRAUsWJ3u6cBk-uZX5z72o1h-_af7Oe22sFhG4Fl6UFHdO3ddX4CvqbeVTPzMixIzdMOQ15FI7RJ8o11_FEOQxQu7Y3xUfc751boSuWbsj-j3u6/?imgmax=800&quot; width=&quot;424&quot; height=&quot;503&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Create a New Certificate, and fill in the details required.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJJLbsKqwNMqjoGEkPPRC75qT3L03e_1LUMkUZ8LbYZ5RfwcKQzqBr-oxLXPhNHoPCi-yiYAHMDvzJV5ifkMI7xElXiA-soQOjyzvU-IZMCbu3IyiBHiwLBvh2jfju-sM_nky1Zq869PxL/s1600-h/credentials_create_new%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;credentials_create_new&quot; border=&quot;0&quot; alt=&quot;credentials_create_new&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgo5WvPt-UkExt4-R57tQfAjS_bb0eP-l4iIxw2T7xTpugjDU90BsR7-dZYBh4lVvRHQjt8u6uyLkARwfT6bGJx1JIzxuJROK7MzPTIT2Vt39fx978jOMy84hdygfmvcCQ09qP7-Qx3SEiN/?imgmax=800&quot; width=&quot;428&quot; height=&quot;509&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Visual Studio creates a new certificate and stores it in a temporary, obscure, folder. Copy the path from this dialog onto your clipboard and head over to the Windows Azure Management portal.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiljlE2o2ZIlsjHAEE5Kg5hK6csJpl5PaT9bcLjEE6D9TWS1kErjP4fknWQmh3rYJpXfFzZvRpFrlCwepppLg4VKfq65qzquypMNYvMlDEC5GMba7e9S4E7D8ZZAgNueWlb8acfP_jUb63j/s1600-h/copy_certificate_path%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;copy_certificate_path&quot; border=&quot;0&quot; alt=&quot;copy_certificate_path&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdSRHa9QbSMzR_sC9qEUYFbsEaLhF1zRx_GDlExj7C_wmgOe7AaXylGOYR6h3GWI2eyXaGhwXiy5yt5GVA-GaMQg5HhH5VQvcyyyI5crvmJi6013uQsEtjxJ1J2uJRf8sneKN6tN8MA8Ac/?imgmax=800&quot; width=&quot;604&quot; height=&quot;535&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Click on ‘Management Certificates’, select the Azure Subscription you want to deploy to, and select ‘Add Certificate’ from the right-click context menu.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicw5l57uVRTfb2vcKZ6aPvypkJ_8pTn7-R4askqffkadgv05a7YBQ5-sxLBZC73n7akf8rb3uVPGzVPk93mBiyBu9JiaYcHkmL09gioZLaxO991c2XlZtIrhITAzZ0zA0_4enJhZWVYHOC/s1600-h/add_management_certificate%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;add_management_certificate&quot; border=&quot;0&quot; alt=&quot;add_management_certificate&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiON9Kms1QtFA9N-obN0X1QViVlsTFIIiwul5SBYdXqYM4oDvUMaCi3tEbS0daQJKx2RxlW7jbybVxSsIHOr4s-P7heUBqdfiK5Gk1AaH8YXafWsugaQhlcB12-2NBcS2OH88ubL53Wue7q/?imgmax=800&quot; width=&quot;604&quot; height=&quot;404&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Once the certificate is uploaded, select and copy the Subscription ID from the portal and fill it into (3) of the Windows Azure Project Management Authentication dialog shown above. Give the Project some reasonable name and click ‘OK’&lt;/p&gt; &lt;p&gt;After dispatching all the other dialogs, you will be left with the first ‘Publish Windows Azure Application’ dialog. Ensure you have selected a Production Environment, and specify the storage account to use.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcb4ItTRj0b4_zzTuKARC6M_Pej1_BvJRFGSjYF8r35hyrKC_b9lLVhXJSobVI7ingvNgYz1cYC2ODgM8NPt1xqPX2ID-qt4tXCbSfmC4NiY-lwxw5d9wcP3l6LWnAZ9GXl5a3TpRwK2Pw/s1600-h/ready_to_publish%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;ready_to_publish&quot; border=&quot;0&quot; alt=&quot;ready_to_publish&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg8ku8WUfiun6Xljg0SjPyEVq80KwJ1pt3nEg4NxOi_ZpwZZe_ohWa6J9GMBwuxHuFZgx30xSqP9DBK5miH4DezZbw1xhfjgL-8UfzEdqdLI_rfCi_CcjK0NfJwYyzTtA7f8a2ZGTpzcTSp/?imgmax=800&quot; width=&quot;424&quot; height=&quot;503&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;h2&gt;Hurry Up and Wait&lt;/h2&gt; &lt;p&gt;Clicking ‘Publish’ on the dialog above begins the deployment process, which can easily take 15 minutes or more. During this time, some information is relayed through to Visual Studio about the actions being taken and their various statuses.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-e5VuDCThBxKpbh4_NmN9maVRlAWyQd8plgUuiVoPJcTRbxlsicV0060AnkcbmIoeOlez0z8QMQvjF_aLTM1hG1v8KGhO_lXkYAe-byo3oHGr9Ro-PChMoFKZQcwBOAN_dnGOunPxffMc/s1600-h/deployment_in_process%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;deployment_in_process&quot; border=&quot;0&quot; alt=&quot;deployment_in_process&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj38zk9Kv1cC7jb4zO_qB7HPe74gU6puhOjKzcdzaSlhVBKkQDOjQKKp2Il9sMom9icZFBgFApfyyaFsl8CMRXI-jo05sdPLsjfGOfFSyS0EFgUeich-Ii5SEALzFZEKD8QZnzgyemY5Lc6/?imgmax=800&quot; width=&quot;604&quot; height=&quot;449&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;When the deployment is complete, click on the ‘Website URL’ link, or view the deployment in the Server Explorer and select ‘View in Browser’ from the right-click context menu.&lt;/p&gt; &lt;p&gt;The application finally appears. Note the URL is now that of an Azure cloud application.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimPai-tfXRDCUGEhzyx-kzlmm6_y3qvfknftelXywU08bjszsPLVTe188TAR2cmQsIvjv2PtsDJUtyfqxnpGCBYicyx1zJvubQImgLb_XsQhhhgIOuHw-G1Lb_Xr4k3uz9KcVb9Nya9x1I/s1600-h/in_the_cloud%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;in_the_cloud&quot; border=&quot;0&quot; alt=&quot;in_the_cloud&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSIfayX7JZOUsVWBScOhn-G4EJbulDDSHFQDx0Xs-iIdu91T33neAftolY3Sz6Rwav6-bIg12SxrgOY8aqR4p3koc-2Qyh3RwC5_vm75y6T-4NRoxdXDc45ngo9crwfjZRpEhuhrRgnVpR/?imgmax=800&quot; width=&quot;604&quot; height=&quot;402&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;In the Management Portal, expanding the Azure Subscription will show the Deployment node and all the compute instances fired up in the production environment. In our case, we have just one instance, but we could add more.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjhLUglvDs3KWwozXJ1KqW286KKGkv2ZkLA6VOLXwtVje0yQBnUFTpVy7v2D-K7WQooWhQZYzEuB3kkn6Ro-lTsihtpIWR1hy2z5Y5Rj_YzNU2QVowVrc3uzZuy3z57-2dMRUcHp-y6voq9/s1600-h/in_the_cloud_mgmt%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;in_the_cloud_mgmt&quot; border=&quot;0&quot; alt=&quot;in_the_cloud_mgmt&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmYCfbAZpCKGwKlDKsKAKvuD1AseZg-ihqZZSMwXASbv6wgzNQf7015m-6-R0hciilIyemkfFF4DXdYOJyOxF1LbnkcOJmfwcZmpZ4IMClSd0i26TkK_bCB6-TkJ0T1_U7veMXoUkxO_d2/?imgmax=800&quot; width=&quot;604&quot; height=&quot;402&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;And there it is. A fully local web application that is now running in the cloud and using cloud-based blob and database storage.&lt;/p&gt; &lt;p&gt;Next we’ll talk about federating authentication to this application.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&lt;a title=&quot;TechEd Australia 2011; COS204; Migrating your applications to Azure&quot; href=&quot;http://australia.msteched.com/topic/details/COS204#showdetails&quot; target=&quot;_blank&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;blogBling_150x150_02333&quot; border=&quot;0&quot; alt=&quot;blogBling_150x150_02333&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiS9Z_eRb4Jh0pwWe9D14GOwmIlBpVJHQarL0XwOyNLUYBNzsCKW_EWAH1D5dgI-dJf2FODjY9Zdd_c2uMgoO9Qjxyx10tt8bfkd2vOUAMNSEQPWri3GlTjfoz77oyDMBqM5037nMnu3od_/?imgmax=800&quot; width=&quot;154&quot; height=&quot;154&quot;&gt;&lt;/a&gt;&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/119789124204738038/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/08/migrating-web-application-to-azure-step_9628.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/119789124204738038'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/119789124204738038'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/08/migrating-web-application-to-azure-step_9628.html' title='Migrating a Web Application to Azure: Step 4'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinWxrxzrYf2Vm6gfULcPmKgG-tH5-q88otKwok_6sFziKCdldvgd9tqIGchBQ-kA-INMXEEhDPiOYIPXQl50SBg37KX2dnqwyQ9D1vpIoZDyKZITSLZrDfwwJumCt3A3JyOzAZ57tleCyJ/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-1202607738911412641</id><published>2011-08-27T08:32:00.001-07:00</published><updated>2011-08-27T19:28:42.989-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Cloud"/><category scheme="http://www.blogger.com/atom/ns#" term="COS204"/><category scheme="http://www.blogger.com/atom/ns#" term="SQL Azure"/><category scheme="http://www.blogger.com/atom/ns#" term="TechEd 2011"/><category scheme="http://www.blogger.com/atom/ns#" term="Windows Azure"/><title type='text'>Migrating a Web Application to Azure: Step 3</title><content type='html'>&lt;h3&gt;&lt;font color=&quot;#4bacc6&quot;&gt;Getting rid of file access&lt;/font&gt;&lt;/h3&gt; &lt;p&gt;One issue to watch out for with an application in the cloud is file access.&lt;/p&gt; &lt;p&gt;File-Access in a highly-elastic environment such as Azure is generally a bad idea because it reduces the ability for a request to be correctly handled by multiple server instances. To combat this, generally, all access to the file system should be changed to access Azure storage, which &lt;em&gt;does&lt;/em&gt; scale across multiple server instances.&lt;/p&gt; &lt;p&gt;In our example, we have contrived to have a picture stored in the database, but cached on the file-system on its first use, and subsequent access is to the cached file.&lt;/p&gt; &lt;h2&gt;Local Application, Images from Server Files&lt;/h2&gt; &lt;p&gt;We have code that looks like this in the original code:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public ServerPath EnsureImage(Picture picture)&lt;br /&gt;{&lt;br /&gt;    // ensure the directory exists&lt;br /&gt;    var directoryPath = EnsureDirectory(RelativePathToImagesDirectory);&lt;br /&gt;&lt;br /&gt;    // now ensure the file exists&lt;br /&gt;    var filePath = EnsureFile(&lt;br /&gt;        directoryPath,&lt;br /&gt;        picture.OriginalFilename,&lt;br /&gt;        _path =&amp;gt;&lt;br /&gt;        {&lt;br /&gt;            using (var stream = new FileStream(&lt;br /&gt;                _path.Absolute,&lt;br /&gt;                FileMode.OpenOrCreate,&lt;br /&gt;                FileSystemRights.TakeOwnership | FileSystemRights.Write,&lt;br /&gt;                FileShare.None,&lt;br /&gt;                1024,&lt;br /&gt;                FileOptions.None))&lt;br /&gt;            {&lt;br /&gt;                stream.Write(picture.Image.ToArray(), 0, picture.Image.Length);&lt;br /&gt;            }&lt;br /&gt;        });&lt;br /&gt;&lt;br /&gt;    return filePath;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;internal ServerPath EnsureFile(ServerPath root,&lt;br /&gt;                               string filename,&lt;br /&gt;                               Action&amp;lt;ServerPath&amp;gt; fileCreateFunc)&lt;br /&gt;{&lt;br /&gt;    var path = new ServerPath(Path.Combine(root.Relative, filename), Server.MapPath);&lt;br /&gt;&lt;br /&gt;    if (!(File.Exists(path.Absolute)))&lt;br /&gt;    {&lt;br /&gt;        fileCreateFunc(path);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return path;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;which results in&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKx7A_9ALr3QbRZ9mOre59waUYOvfUhDcTHayiZqq3dDImJ0sDHnidMOaLQZFnCcMGD0C2i-7xvJRsOLSZ9W8OtXaUAXQ5q3tiALFzc_7y2OnqVmdGhXxPXjS2sGIWWqHndAaHI4W7uY8n/s1600-h/images_from_filesystem3.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;images_from_filesystem&quot; border=&quot;0&quot; alt=&quot;images_from_filesystem&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2NNiD8yQ04UP34AiVERGWQqBh2C7XlohrWpmPo_P6IqoDVAuEn9_0GAUaUy8Wuxx4vWMFuCNeOlfYoucqpaClBfUitqAxd6QiygZXn5RQeGB-WYtCy1MPRFcglmkIp3PL7m5Sml5CDDKz/?imgmax=800&quot; width=&quot;604&quot; height=&quot;404&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Note that the web application is still running locally, and the images refer to files located at relative paths within the server.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;To remove the dependency on the file-system, we can use Azure Blob Storage to store the cached files.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;The Rise Of The Blob…&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;Blob storage Azure is very cool. It presents a REST-based API to upload, tag, list and retrieve unstructured binary data like images, documents and videos. &lt;/p&gt;&lt;br /&gt;&lt;p&gt;So we can switch the application to interact with the Azure Blob store, referring to the images from the storage in the cloud.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;To do this, we use the Azure storage account we created earlier.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEisuafJGpnh3T7eWGG-4N6nSN9P2QVZFH0dOeRxNT5Cf0cJuU1KmV1Q5Q3WK69tU7HDTlwhDAXhBJV0vrqFgH5jB7Wc8qL9xbLQ50glBYLkGddB-h33Z8dZ4D1M3CCQrqxvfpUJHGsL014V/s1600-h/configure_blob_storage3.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;configure_blob_storage&quot; border=&quot;0&quot; alt=&quot;configure_blob_storage&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMJ5FT7MFf5wBP2S77c6XcpfMPTE_nGfL48Y47TzkqDD-p9MpQcx_-AAdfLl8KfCrmyrDV5UTuWZol0b_hZ0u9q_C2eynyKswztCpk9npraauiN11NLzemdJtdiMcCGVUmqZNw0OHlkEUW/?imgmax=800&quot; width=&quot;604&quot; height=&quot;374&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;The important pieces of information to capture are the Access Key (you get this when you click on the button with the orange outline), and the Azure storage account name which is highlighted.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;We then initialize access to the blob storage account and container from within the application:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public void Initialize()&lt;br /&gt;{&lt;br /&gt;    if (CloudStorageAccount == null)&lt;br /&gt;    {&lt;br /&gt;        CloudStorageAccount = CloudStorageAccount.Parse(&quot;AccountName=cos204;AccountKey=&amp;lt;put_your_key_here&amp;gt;;DefaultEndpointsProtocol=http&quot;);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    if (CloudBlobClient == null)&lt;br /&gt;    {&lt;br /&gt;        CloudBlobClient = new CloudBlobClient(CloudStorageAccount.BlobEndpoint, CloudStorageAccount.Credentials);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    if (ThumbnailsContainer == null)&lt;br /&gt;    {&lt;br /&gt;        ThumbnailsContainer = CloudBlobClient.GetContainerReference(&quot;thumbnails&quot;);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    ThumbnailsContainer.CreateIfNotExist();&lt;br /&gt;&lt;br /&gt;    if (ThumbnailsContainer.GetPermissions().PublicAccess != BlobContainerPublicAccessType.Container)&lt;br /&gt;    {&lt;br /&gt;        ThumbnailsContainer.SetPermissions(new BlobContainerPermissions&lt;br /&gt;                                               {PublicAccess = BlobContainerPublicAccessType.Container});&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    if (ImagesContainer == null)&lt;br /&gt;    {&lt;br /&gt;        ImagesContainer = CloudBlobClient.GetContainerReference(&quot;images&quot;);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    ImagesContainer.CreateIfNotExist();&lt;br /&gt;&lt;br /&gt;    if (ImagesContainer.GetPermissions().PublicAccess != BlobContainerPublicAccessType.Container)&lt;br /&gt;    {&lt;br /&gt;        ImagesContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Container });&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;What we are doing here is initializing the Blob Storage infrastructures and creating containers for Thumbnails and Images.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;It’s important to note that the demo code shows a hardcoded Azure Connection String just to simplify the code snippet for reference. Normally this would be hidden away in a configuration file.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;Local Application, Remote Images&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;We can now replace the file-access code shown above with its Azure Blob equivalent.&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public ServerPath EnsureImage(Picture picture)&lt;br /&gt;{&lt;br /&gt;    var filePath = EnsureBlob(&lt;br /&gt;        ImagesContainer,&lt;br /&gt;        picture.OriginalFilename,&lt;br /&gt;        _blob =&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                var blobStream = _blob.OpenWrite();&lt;br /&gt;                try&lt;br /&gt;                {&lt;br /&gt;                    blobStream.Write(picture.Image.ToArray(), 0, picture.Image.Length);&lt;br /&gt;                }&lt;br /&gt;                finally&lt;br /&gt;                {&lt;br /&gt;                    blobStream.Flush();&lt;br /&gt;                    blobStream.Close();&lt;br /&gt;                }&lt;br /&gt;            });&lt;br /&gt;&lt;br /&gt;    return filePath;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;internal ServerPath EnsureBlob(CloudBlobContainer blobContainer,&lt;br /&gt;                               string filename,&lt;br /&gt;                               Action&amp;lt;CloudBlob&amp;gt; blobCreateFunc)&lt;br /&gt;{&lt;br /&gt;    var blob = blobContainer.GetBlobReference(filename);&lt;br /&gt;&lt;br /&gt;    if (blobContainer.ListBlobs().FirstOrDefault(_blob =&amp;gt; _blob.Uri.AbsoluteUri == blob.Uri.AbsoluteUri) == null)&lt;br /&gt;    {&lt;br /&gt;        blobCreateFunc(blob);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return new ServerPath(filename, blob.Uri.AbsoluteUri);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;With this implementation of EnsureImage(), we get:&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibsw5Xy7mjhy5cJ4WkA3HxeNj6NYvK_rumiY2WEqYXzKzkTx_HacwKrZ9m0Li9GFEsLV3xoDSm96NDMpTGkysx4kT-hcSxXUgdRWfZa6bxe-jbekuKIXz5gpphSbd4I8g3jI18ZbeqyILC/s1600-h/images_from_blob3.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;images_from_blob&quot; border=&quot;0&quot; alt=&quot;images_from_blob&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgV1KYDcUfoTZu3UupAryjc52rR583BEfCPBq-D1D7mrmiGI4D5tnokkwlda_WRtUJhhIct-ExnQg-POrmjy4LG6PZWv0p5u-LGCDtDYl_pPe6rrBndIuhHh1VwNOURfRYt45ujyJwy-rOG/?imgmax=800&quot; width=&quot;604&quot; height=&quot;404&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Pretty cool.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;We now have a web application running on the local server, with data in the cloud, caching files and referencing Azure Blob storage also in the cloud!&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;Inspecting Blob Storage&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;While developing and debugging this stage of the migration, it’s useful to see exactly what is being stored in the Azure Blob storage. &lt;/p&gt;&lt;br /&gt;&lt;p&gt;The Windows Azure Management Portal does not have a handy tool to inspect the structure and contents of the Azure Storage account, so we turn to some other tools to do that.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;The pack of Windows Azure Tools for Visual Studio 2010 v1.4 enables a storage account browser, which can be configured with the storage account and the key as before, allowing for full access to the storage account.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTyxjDspnv1LhivtCYRwW42Ad68eXdGGf_50hL31gE5bmXv3uRHmfC5ON6lXDFO9Pr8KVc5ab1RRYDNmgwdyhVIUuygYXf0lPjGfuHYtHvGOD082Mgfefz2Gxglwy1EhmewDCMngl1usce/s1600-h/azure-storage-browser%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;azure-storage-browser&quot; border=&quot;0&quot; alt=&quot;azure-storage-browser&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiHBTE97BSJrlglxhw0LkrfH1fbEQoL4kjJqgUMTQVrq5ezQYtHcxWyQIOof7xpcIhHC1aOlZcJQT9oQugwfwLyaLQYn0_v1NxAyXHlsDzxDXFM1j7KM9Pc0Y1QEEsRc9wUrJYhmvlVR4TQ/?imgmax=800&quot; width=&quot;604&quot; height=&quot;222&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;We can use this to ensure that the blob storage account is structured as we expect, and filled with the contents we expect.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Next, we’ll move the application itself to Azure.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a title=&quot;TechEd Australia 2011; COS204; Migrating your applications to Azure&quot; href=&quot;http://australia.msteched.com/topic/details/COS204#showdetails&quot; target=&quot;_blank&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;blogBling_150x150_02333&quot; border=&quot;0&quot; alt=&quot;blogBling_150x150_02333&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi44q-UnbpXkRARB1PgCG5GvSaCM1oXIauA3WqdbXvFbDzsd8qzBlRGo6t9kkTWrSJs86Bck0PBA20DktfaS8wFrd5A8I577Rrk5xjfY7XjUvQXM7sqSZ7zhpGcGMXK8nIkthc7quvn-tpI/?imgmax=800&quot; width=&quot;154&quot; height=&quot;154&quot;&gt;&lt;/a&gt;&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/1202607738911412641/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/08/migrating-web-application-to-azure-step_27.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/1202607738911412641'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/1202607738911412641'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/08/migrating-web-application-to-azure-step_27.html' title='Migrating a Web Application to Azure: Step 3'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2NNiD8yQ04UP34AiVERGWQqBh2C7XlohrWpmPo_P6IqoDVAuEn9_0GAUaUy8Wuxx4vWMFuCNeOlfYoucqpaClBfUitqAxd6QiygZXn5RQeGB-WYtCy1MPRFcglmkIp3PL7m5Sml5CDDKz/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-2407230402019286947</id><published>2011-08-26T20:33:00.001-07:00</published><updated>2011-08-27T19:23:48.132-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Cloud"/><category scheme="http://www.blogger.com/atom/ns#" term="COS204"/><category scheme="http://www.blogger.com/atom/ns#" term="SQL Azure"/><category scheme="http://www.blogger.com/atom/ns#" term="TechEd 2011"/><category scheme="http://www.blogger.com/atom/ns#" term="Windows Azure"/><title type='text'>Migrating a Web Application to Azure: Step 2</title><content type='html'>&lt;h3&gt;&lt;font color=&quot;#4bacc6&quot;&gt;Migrating the database to SQL Azure&lt;/font&gt;&lt;/h3&gt; &lt;p&gt;Now that we have a local web-application with a database, and a SQL Azure instance up and running, we can start the application migration by moving the database to SQL Azure.&lt;/p&gt; &lt;p&gt;SQL Azure is a modified version of SQL Server 2008 R2, and there are some small, but significant limitations on the SQL DDL commands that can be run on Azure. See &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ee336241.aspx&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt; and &lt;a href=&quot;http://www.keepitsimpleandfast.com/2009/12/main-differences-between-sql-azure-and.html&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt; for more information.&lt;/p&gt; &lt;p&gt;The upshot is, if you already have a local SQL Server database, then you’re really much better off using some specialized migration tools to move it to Azure. The tool of choice for us is the &lt;a href=&quot;http://sqlazuremw.codeplex.com/&quot; target=&quot;_blank&quot;&gt;SQL Azure Migration Wizard&lt;/a&gt; off codeplex.&lt;/p&gt; &lt;p&gt;Download and install the latest version of this tool on your development box. You’ll thank the tool-developer later!&lt;/p&gt; &lt;p&gt;Fire up the tool, and select “SQL Database” under “Analyze / Migrate”&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLnZRhR-j7L2QFLKCziXkhziCeC9tVGOcjuYOypRaFA_9qxB7qWh7hMMaJ9PX4vYJ3Z6HKAm5SOER_gjZa-fPd7hPzeQeJ-d83yC-90f2s0aMybPZeg6a7x1KUuCbg6ObiwiajhyphenhyphenaLc1Bs/s1600-h/sql_azure_mw_0%25255B2%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;sql_azure_mw_0&quot; border=&quot;0&quot; alt=&quot;sql_azure_mw_0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmdJG2Ri3Okg0cxhXCsUb3WoGI_uEdgZBXwgfXVi0LAiyUmhAQAvg4OM6mxwP6MvZ3BBSeO2rzt2hmx1w6GbKyD3hmh9ggPsCwQAetLzMAtntVEjfUIvADNR15E1uJE_Lq4eWjAuR9vhMe/?imgmax=800&quot; width=&quot;404&quot; height=&quot;448&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Select the local database server which hosts the instance you want to migrate&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh0aqc64jA6pFgxMasGdFhKY8kO3jn8xl5UHakojJblVUYPRLOZAE2-_uYA8ocCxNTzoWoEKwtyPy88PeFqrtQsnsy6qIF8qX7jAshj8oc7HpW22m4fkk5FjsMN3xtEEVXV5JiF0l-tZp1R/s1600-h/sql_azure_mw_1.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;sql_azure_mw_1&quot; border=&quot;0&quot; alt=&quot;sql_azure_mw_1&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyKFmok2Zh-iTfCpPvWWybl4EJzDXLfb_7YC-fz5q3nJHHNlsJgwbc6LQ11QTx4PPRNEGLNgyGPK17jJJ1sYteWfnXh6aOcskYZLT0SqivuCk2sz4x7Ajeo5bv2fm64rGAuYiAv94JOcoE/?imgmax=800&quot; width=&quot;404&quot; height=&quot;446&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Select the database(s) to migrate in turn.&lt;/p&gt; &lt;p&gt;In our case, we will have to migrate both the ASPNETDB and PICTURES databases.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgD0b27VyS-hUmWWWtsJimYnh4UYBbG8xGvyKI4RaB9DA-mT3M3Zvohp45EPwKRrqhfir86fgh5qKUg7UgDJU26-frxf1ETp0sTASJ7wfH-oPFHTSV9IttPJvaw_G0bjYqsgIEuRh9C4yo6/s1600-h/sql_azure_mw_2%25255B1%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;sql_azure_mw_2&quot; border=&quot;0&quot; alt=&quot;sql_azure_mw_2&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgr7ov-jKHeMcJF-sHqYEJyWryzg5X01oTvD8qng7ET6A0i3I5JU3-8FIDEArE0HvHtvP2gs2AbgVxGYiM9Zr6knkiRAece8DiE3zyXD1gjR7iacqFsYa4Qz-pvRY9Ne4332qXDhueyBIU4/?imgmax=800&quot; width=&quot;404&quot; height=&quot;448&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Click through the dialogs, and migrate database object present in the database.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEim14yas6IPHZTTJse3ZO8I9AwofwgtJqnbF_9zmD-htntfrocVIM_PxfVOfPAffMdE9fKTTAmrVg0wI5YR4vMboDmN79nESWmgRfkKOfMXxtO9uzrESHN1FS_A-O-zn2E_asQYqONDTXRx/s1600-h/sql_azure_mw_3%25255B1%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;sql_azure_mw_3&quot; border=&quot;0&quot; alt=&quot;sql_azure_mw_3&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizcYIiiZQiHpg2f9cw84sZpW_RFxNJQZP7S1rX_A3oAmiHPcA-HOnkc8Oac58YADOKU_dbjVWWAH4QrUw17EZx8aY8rRSX1tAwY0coP8Z2nRBgTpaFwVSA4703eKzMIScs10t40KOF0kfZ/?imgmax=800&quot; width=&quot;404&quot; height=&quot;448&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;The Migration Wizard has created the script to use for the migration, and will now require your credentials to migrate to. This is where you fill in the details from the SQL Azure instance screen in the previous step.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi5RBWbEBou8O4p3jakZhNwRt1yj_Hsxl60MeLUCjVBTu_i71BWzKoDQEbLR7gjuQLlOBQSL3Qz8mYjF9pbuvNmcuX3YWCrGKxBy_EVlwRUfBQ_VHhxKfge3uD0r8Tur0R3bhv1lvN_-ihi/s1600-h/sql_azure_mw_4%25255B1%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;sql_azure_mw_4&quot; border=&quot;0&quot; alt=&quot;sql_azure_mw_4&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJZzlXEB0BDkivUsUKdkgCHRF3bxghKg7wdzFAJY3CEFzaSUaOMlF3K2hUVaatY-3sRa3OXP0d4Q5wJ3FPg6B3SQaV7DmPwriVtiOdFYDpJoYE8NsirkTG3lveVTnyaWgSYLFuNFaNHVOI/?imgmax=800&quot; width=&quot;404&quot; height=&quot;448&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Let’s let the migrator create a PICTURES database on the Azure Server&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEih1gA-LRQ-KrYhsmUlgh3hg01ak-bEBC3DefEIyXlRhNhKPu44Oi5__o5D9LpPNp55bva9UNQU-cph1PodeUdAJ3DArw7r-sDT2gDYiyyoWtPUsBxupZbNyRlkMQAPcY1JJAu9y8rWU7VX/s1600-h/sql_azure_mw_6%25255B1%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;sql_azure_mw_6&quot; border=&quot;0&quot; alt=&quot;sql_azure_mw_6&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgWjkUh-b000OwTBhRPF1QGOZ052SbHNER-eJoQ0d3h0FYkFwPqeYtjJ0KBYbWcqg19oiQyNbcJIRTUEr7-6AzRdFj4c2n_OCRf56rTk6QVMqd8KZOEa01GTIumwi_XsuzpKVKuu9PLt3z/?imgmax=800&quot; width=&quot;404&quot; height=&quot;448&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;…and begin the migration work&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiFu4pATYjSJxv9flLXtTIOcE413KonqGdvzm_R8PwqlhCgyoax7Pq_Q4oeoT22_73IrncqsnqiusKC8bjArThJU0Nrwi5MZdBSEDQxXCUQyLAeLVqAoe1-_GzXtojkZkqWuWecA0ydctYq/s1600-h/sql_azure_mw_7%25255B1%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;sql_azure_mw_7&quot; border=&quot;0&quot; alt=&quot;sql_azure_mw_7&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhV15Of6PIOYzjX5NSBmeVxcb9pLOFXP5rXPo6WtBuINE66TCkO9otgqHDYepvbhru4ZqviYuajnvJNMSUFOIxKhZ1xIK0Sl-mpWISyQxY44CizwRvy4_AhlUuWsOWaLBBK1xkMrQZABlWv/?imgmax=800&quot; width=&quot;404&quot; height=&quot;448&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;…and we are done!&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhWemi8SY_vLS463YmZpbHcq2UehziNGiV58weFjCq6o-RZED74PR5X5Pc4RS8xIjdVMCsZwUbVsndEZ1LLoZzen9V07EiUoxWbO8-EftAHWHf8VWcdXWcpjaqQg9OB3Dv_a0zuqM2AxSNJ/s1600-h/sql_azure_mw_8%25255B1%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;sql_azure_mw_8&quot; border=&quot;0&quot; alt=&quot;sql_azure_mw_8&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgyyNH4M8GE0l4MNg1aCh_jyNYeBM_Z0uDCEXyfDMkJxh4I0us5mqa4vGwBusjep66nTe1UqvpfA5WBC4eBF4k_qWqQ_5Kvm80scuGGmelkjyf4FFTvH60LbsmkI9U_mBzQPYJYRB_oKHBx/?imgmax=800&quot; width=&quot;404&quot; height=&quot;448&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;The Azure portal shows the two databases created and ready for use.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9eaBk2omIP-ADZgrxb-sGgYC-vMCPNZkOpdSyxMGlXXB8fj1EembEgF1AWUzyt2Cdv0hrI3zztWKvgxUYP8NYOOBROM_mgQfhAaPX1D2_m0FScSDlBLK7XA9kjYLM77F6cjuQ-PnBuBOD/s1600-h/sql_azure_portal%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;sql_azure_portal&quot; border=&quot;0&quot; alt=&quot;sql_azure_portal&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXqAiQ3HF9Im7YMdPo67JHlmpdBROwDB1HJanu8ibIrHt5z_dJydrGGgexUnqVO0FS97S38mhPDW6RDNvAwX8iwMSqAswaJe5oE5I48-IsrKztWCqPTA5peQhd-QsfwB22dnaf34Wz9mBT/?imgmax=800&quot; width=&quot;604&quot; height=&quot;374&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Now, let’s hook up the application we wrote to use these databases in the cloud. To do this, we point the connection strings in the Web.Config of the web application to the databases in the cloud. &lt;/p&gt; &lt;p&gt;Thusly:&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjR7k1xtjw3gtqTutgojdqYTaj4V2wXyObxcyjJy74VtQfRuUdUwfW-9RZq6fBKIV8kd27SL1ADwY4fRbXgAbal84QUX1uzacyf23f6D7Rlg3dM7racRXLOrkW5aV9NSUhhNSRiDgli_B47/s1600-h/web_config_2%25255B5%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;web_config_2&quot; border=&quot;0&quot; alt=&quot;web_config_2&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiX8qIIFBuJR2MAUhJWkCqUh4dWv8OqGaIoGO5m_s0FLuOLB8btt5zUHscIBFF4ag0y80gW0JCNkoGfpiaLOMFCYAKyyokKkQvLsVrWEU4QI9D2g4VuV7EtxLcxue_g7PzHCe1GbA5F0cM8/?imgmax=800&quot; width=&quot;604&quot; height=&quot;81&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;And that’s it. Here’s the application running &lt;strong&gt;locally &lt;/strong&gt;but with the &lt;strong&gt;data in the cloud&lt;/strong&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjdABDqOWhDjtmwOV7Cb8V2Ss70rziAus84Z6TvQsyJhjvYr69cx57vpSTXqPaUqrZ38RRVUttbXL63wGJTNgTqfcdStwtkzSutJHghUxcLR7GqzcUCGkVi5cPAipP5nN8PiaM4FolPRZj1/s1600-h/localapp_remotedata%25255B6%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;localapp_remotedata&quot; border=&quot;0&quot; alt=&quot;localapp_remotedata&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjDBXXI2LBxHj5wLC9rEBtW15VJxCe1WTcu69a0V4H11R58FyY1j7I5MpW4nAEvtNmmWG_zQrrFnPfFrFzYuNnjvqzIltt7IfNyEOFofoar6o5ciN0dAI5ZlmxJPQzce2AA0aUi91rxldHm/?imgmax=800&quot; width=&quot;604&quot; height=&quot;404&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;I’ve created a new album called “Clouds” now, and uploaded three new pictures. If we look at the Azure database instance and look at the data in the PICTURES instance, we see the data there:&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjM3wRcdP1BtPbSYB0f0d0zxYqrb0zsCPeJMUfRYvPTxGzi3CUcVdSTqW4rA2qvgeQsEs1geS_L6fMcjtUbu8nain9bEJ-FK5jh6UyT3E_Be_vJL1Qp1L3ZoKV3GrjfU3Dl9d5CTMaxBPif/s1600-h/data_in_the_cloud%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;data_in_the_cloud&quot; border=&quot;0&quot; alt=&quot;data_in_the_cloud&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9YYjngzX6sPyjE5JKoOLmJrmAsUSI7IJgVvpYi5Fgcio2y0Xp-t_joFLG7VP47JYWsjukIEKun3TwsLnXAGIM3A1KhEeGikBps04pWofEuYHK0vpzySgyRU9d6kty4BIJ8GVMThgdOglI/?imgmax=800&quot; width=&quot;604&quot; height=&quot;404&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Next, we’ll talk about setting up the Azure workspace so we can move our application there…&lt;/p&gt; &lt;p&gt;&lt;a title=&quot;TechEd Australia 2011; COS204; Migrating your applications to Azure&quot; href=&quot;http://australia.msteched.com/topic/details/COS204#showdetails&quot; target=&quot;_blank&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;blogBling_150x150_02333&quot; border=&quot;0&quot; alt=&quot;blogBling_150x150_02333&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgT1c6r9GGmMPjovUJRKy3ABiy4d3Hvbps3p70dLs0DpopLR4EFoHADrwc1yHuIZld9EJ3wNRr1mF5pWT4ufo-RZkRCcws3rDFo_mhhAkLeL-sMKlNq4opgi9-h2necl9RCv4H-BUC16X4d/?imgmax=800&quot; width=&quot;154&quot; height=&quot;154&quot;&gt;&lt;/a&gt;&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/2407230402019286947/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/08/migrating-web-application-to-azure-step_5558.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/2407230402019286947'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/2407230402019286947'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/08/migrating-web-application-to-azure-step_5558.html' title='Migrating a Web Application to Azure: Step 2'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmdJG2Ri3Okg0cxhXCsUb3WoGI_uEdgZBXwgfXVi0LAiyUmhAQAvg4OM6mxwP6MvZ3BBSeO2rzt2hmx1w6GbKyD3hmh9ggPsCwQAetLzMAtntVEjfUIvADNR15E1uJE_Lq4eWjAuR9vhMe/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-624515777731191651</id><published>2011-08-26T19:34:00.001-07:00</published><updated>2011-08-27T08:35:01.234-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Cloud"/><category scheme="http://www.blogger.com/atom/ns#" term="COS204"/><category scheme="http://www.blogger.com/atom/ns#" term="SQL Azure"/><category scheme="http://www.blogger.com/atom/ns#" term="TechEd 2011"/><category scheme="http://www.blogger.com/atom/ns#" term="Windows Azure"/><title type='text'>Migrating a Web Application to Azure: Step 1</title><content type='html'>&lt;h3&gt;&lt;font color=&quot;#4bacc6&quot;&gt;Setting up your Azure workspace&lt;/font&gt;&lt;/h3&gt; &lt;p&gt;So we have a working web-application which we want to move to Azure.&lt;/p&gt; &lt;p&gt;The first thing to do is to get a Windows Live ID and line up one Windows Azure subscription and one SQL Azure subscription.&lt;/p&gt; &lt;p&gt;Sign into windows.azure.com with your Live ID&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhy0hqimuuorcDN4HkGiMJqwyci9j-1iib5UKtjI1JWNXMyzZrkr2Tp4ANYemx7oLZot7tONYKSfwWquX4Q2Mn48qtmfXTuCBPMuffxh0SDNRICIVliKvP2vm_9CYpgHwaBEZst4nCh2yvm/s1600-h/azure_homepage%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;azure_homepage&quot; border=&quot;0&quot; alt=&quot;azure_homepage&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEho3TAeYr2MTA7TWJSEaKaMhucspIlAZUHEooWyoAnJjQ04psn8R-C6imTDGEAFP9u-F59IXYe8ZeA8xocdI0DxKxON6_Ym722Cz-kBGwysvC_HQjiA4VJD5wWdKBcuJio6J7Edw98Hnzyc/?imgmax=800&quot; width=&quot;604&quot; height=&quot;439&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Click on the “Hosted Services, Storage Accounts and CDN” button on the bottom left panel, then on “Hosted Services” on the top left panel. &lt;/p&gt; &lt;p&gt;Right-Click on your Azure Subscription in the main panel and select “New Hosted Service”&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjp50eNjLIapMPjNDED-c749Z8lXRugnxr6gLmiuOIqr11qYurdf-Ff6eWQUqEBTVWqsb-XNp8B9TDoQpxCSCv9VXOkurElfTFnaW3e5toWUgp1csu-K5xEIynKxwEZfTNwxxlXpOJL_fyz/s1600-h/new_hosted_service%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;new_hosted_service&quot; border=&quot;0&quot; alt=&quot;new_hosted_service&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOXDlU1uNFWVmx6mxhifsUC8on-GF0cch9teUxO1cFftwjbpajioBbJRvEv4UAT5e5kvJsq29kzmC_BlHk0I1mdkTey5rKAIbOvRdTZQdOFUZsZdZDs8c5diyfbdgNgfPpf6WTA0Z4cRtw/?imgmax=800&quot; width=&quot;604&quot; height=&quot;412&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Choose not to deploy at this stage!&lt;/p&gt; &lt;p&gt;Similarly create a Storage Account on the same subscription.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpjymJZveNcDn1lkmhFgMmuyrUhhNWLgrNosMvqhMlY7agbVacH8IXIDBmyqakbaNRbkqylaJdGkUfseiaWUEcHeRh5E8chNGWaFK6yReMcj9EVOVMEj4T-1jPxBeCbFkNbgaP8fk4faNC/s1600-h/new_storage_service%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;new_storage_service&quot; border=&quot;0&quot; alt=&quot;new_storage_service&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj08zTKDUS934VGIVh6BKs_g7ZS0-JGETxra4IkFjXMWeTNfx_LlAuB_9hIubqxCN7QnshT9Q80zkKdS__NLq9HjvJAbl679FZ5_VKS4xKUXzlZfbOGtjYBA1g8eNok6-ct4XWpWiS9s8yY/?imgmax=800&quot; width=&quot;604&quot; height=&quot;412&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Now create a database server on the SQL Azure Subscription.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicXXcF81rrk_NrtGvgsGDkzM4abP0SwFY5kBz4OdXNCyCFK5SGva9wFGvA2-xd8P9PKiqeTZh7oejJdsAAXYMIk47wLwWGI7HKxny0M2vv-FNZM-vUS2-rlzeycnVlcA7njx-dSaQZ8AJV/s1600-h/new_sqlazure_database%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;new_sqlazure_database&quot; border=&quot;0&quot; alt=&quot;new_sqlazure_database&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpf_N2F_J6QfFP3gUAFwiARYgD9BfGSkW4NOuBe5qVLMK1commfMeAlMMLLFuwfWyUJ9T2nbozpV6XtlO-yrr-tJKBs1qhyNIepYTaw1myQd1ylu7LKN7Y7AkPD3DJYSW71f34Ax1ni_dG/?imgmax=800&quot; width=&quot;604&quot; height=&quot;434&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Ensure you set the firewall rules to include both your machine’s IP address and other Azure services. Your SQL Azure instance will need to be accessed from the Windows Azure instance,&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEheO1f4N9utMSJUEwrlasE7dj3BFFFzZCr5SLru9t-V7KBVk6bplSemlbYGuHLUEqX-mjiSIpAcJtzgqFaKhZqaQTeM21w7_YVogv8DUvFU1NOdPyTA-3l3qNfTcFrEbL5_NdVICfUacysG/s1600-h/setting_firewall_rules_after%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;setting_firewall_rules_after&quot; border=&quot;0&quot; alt=&quot;setting_firewall_rules_after&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsNkmQDfzrvqeuANubuRmjR-7A0EeGkHVvJ7C05Xka-ALvmSlfGzdZCYAuzasfy9bi1LACC6fn51KianguByTlK12bVH3K-_UastVhIluRNFXBLSdDBdmM2LM9ZLkDprTQDD2anUN6-hwc/?imgmax=800&quot; width=&quot;604&quot; height=&quot;434&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Once you create the database server, you should make a note of the following pieces of information:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;The subscription id  &lt;li&gt;Your administrator login and password  &lt;li&gt;The instance name, and the fully-qualified database server DNS name&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVRHTUe06aqy7E29A6M-0XRPlblVN96-SgTkHVLHfZ4Ws0r13QhhbI1dUDcU1N8NXNPls2V9Ifvn9b5yyYeyOPpWq7AnHEAahUZZNtup8lDM6hMdpx2XQPeNX1tYIZ5hKdG8xYHWcacisR/s1600-h/database_server_ready%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;database_server_ready&quot; border=&quot;0&quot; alt=&quot;database_server_ready&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgY-Z3fkvkZIF5bogDstu3w-IRrlQ8zx4qe-_yw2OeUcFTCmmkQd-0wspk0GenlhLIzHabCpL7HeFCTUBWofwUom0ND2TxcoZ-m0K3CUQwIJd7PRoaT6I0nvJ_uEg0ZI_0N7_fYd3vKIyh8/?imgmax=800&quot; width=&quot;604&quot; height=&quot;414&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Now we have Windows Azure and SQL Azure instances set up for use. &lt;/p&gt; &lt;p&gt;Next we’ll migrate our database to SQL Azure.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&lt;a title=&quot;TechEd Australia 2011; COS204; Migrating your applications to Azure&quot; href=&quot;http://australia.msteched.com/topic/details/COS204#showdetails&quot; target=&quot;_blank&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;blogBling_150x150_0233&quot; border=&quot;0&quot; alt=&quot;blogBling_150x150_0233&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfpmUeQwq0ETGoKYh4hhkTU_-mcbIVyxhQtHaidK2GkANBMi_5Db2eh92A7pNR7imjMsfy_lvlMraOQZQy1a3mLQVIWsuZMxXgnTVK8S7yKeKB7Bg4P6ho3ZFkcr55tBtJ4QYpWJ3xvyOR/?imgmax=800&quot; width=&quot;154&quot; height=&quot;154&quot;&gt;&lt;/a&gt;&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/624515777731191651/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/08/migrating-web-application-to-azure-step_26.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/624515777731191651'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/624515777731191651'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/08/migrating-web-application-to-azure-step_26.html' title='Migrating a Web Application to Azure: Step 1'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEho3TAeYr2MTA7TWJSEaKaMhucspIlAZUHEooWyoAnJjQ04psn8R-C6imTDGEAFP9u-F59IXYe8ZeA8xocdI0DxKxON6_Ym722Cz-kBGwysvC_HQjiA4VJD5wWdKBcuJio6J7Edw98Hnzyc/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-6101143376050089336</id><published>2011-08-25T10:53:00.001-07:00</published><updated>2011-08-27T19:27:56.535-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Cloud"/><category scheme="http://www.blogger.com/atom/ns#" term="COS204"/><category scheme="http://www.blogger.com/atom/ns#" term="SQL Azure"/><category scheme="http://www.blogger.com/atom/ns#" term="TechEd 2011"/><category scheme="http://www.blogger.com/atom/ns#" term="Windows Azure"/><title type='text'>Migrating a Web Application to Azure: Step 0</title><content type='html'>&lt;h3&gt;&lt;font color=&quot;#4bacc6&quot;&gt;Creating a traditional, locally run web application&lt;/font&gt;&lt;/h3&gt; &lt;p&gt;Let’s start with a simple, traditional web application. &lt;/p&gt; &lt;p&gt;&lt;em&gt;&lt;font color=&quot;#ffc000&quot;&gt;This is a contrived application, built specifically for demonstrating the issues we want to address in the process of migrating to Azure. &lt;/font&gt;&lt;/em&gt;&lt;/p&gt; &lt;p&gt;&lt;em&gt;&lt;font color=&quot;#ffc000&quot;&gt;Please do not consider this application as indicative of following best-practices for web application development!&lt;/font&gt;&lt;/em&gt;&lt;/p&gt; &lt;p&gt;&lt;em&gt;&lt;font color=&quot;#ffc000&quot;&gt;Also, the purpose of this web application is not to wow anyone with a slick user interface! :)&lt;/font&gt;&lt;/em&gt;&lt;/p&gt; &lt;p&gt;Let’s imagine a site where someone logs on, creates a photo album or two, and uploads a few images to each album.&lt;/p&gt; &lt;h2&gt;Prerequisites&lt;/h2&gt; &lt;p&gt;You will need the following applications and tools to follow along the process of migrating an application to Azure&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Visual Studio 2010 (SP1 strongly recommended)  &lt;li&gt;SQL Server 2008 R2; you’ll be using SQL Server Management Studio  &lt;li&gt;Windows Azure SDK 1.4&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;We’ll introduce a few more tools along the way, but we can get started with this.&lt;/p&gt; &lt;h2&gt;Steps&lt;/h2&gt; &lt;p&gt;Let’s create this application the simplest way possible:&lt;/p&gt; &lt;p&gt;First, create the ASPNETDB Application Services database on the SQL Server 2008 instance. You may need to run aspnet_regsql.exe from the .NET framework directory.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh5yaqyAYCPC0vCuzJAklvO1ux_46QPip2kn-dmTkic5IFc1_uirU6EI319rmhVsKwyZTjTXBX-n5xIwshqrJazYg-HxyGcaZm6hFlvK1W5BSX4V8rY7QkwXZADDtYiQlq2Pgg8vxWybQcF/s1600-h/aspnet_regsql%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;aspnet_regsql&quot; border=&quot;0&quot; alt=&quot;aspnet_regsql&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjMjRDfBcnjwgOfI7-5dYOTyzHbxyFGhxb0Pg8jyFGAzee9qAQ7XSu3Cre77yW_gBlKRshmkziSAZgScdZZnvfDd7cCSX2sEdYp8I4ENrxX0uRXDFZ4X4OTTldOEiTEXWvbXmqOH29ukCn7/?imgmax=800&quot; width=&quot;604&quot; height=&quot;486&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Then create a basic web application in Visual Studio:&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjug2SxxD1D8TPTXTg2CpwjxsXl44VFNR4bAnMh3uF8KWCKh0sYwKEn72mTPQKpOsQar-znPPhFkRcf2oPiS0ixM6nhTq2ACnmZBXtRtJ4Hbv0vuSesV6YUMtw0jBJlP0l8gWAx0XqQbneQ/s1600-h/create_web_application%25255B8%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;create_web_application&quot; border=&quot;0&quot; alt=&quot;create_web_application&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXYx_9YRhKYYim5ejqvWNDtoR3xZM_clttjmzuAClOgf7IfpcSgL6LhUJuMlyrtwwGQlwkWKl8am8dRFf0ZIBYp2_6aSaw6eQl4VNucgBbPKPJQyTQcajMJQlE6Q8w1KCqN17hfv16jnKS/?imgmax=800&quot; width=&quot;604&quot; height=&quot;419&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Modify the Web.Config on the web application to point the Application Services Providers to our database.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOIaxMpyZN5zuEcVjTVeQlNF_QnPE1j6Ny-1saV7GW7XQOm3DAN7suTr__yUJ3DTufqCCc9fWnwl4fLlWS5pH6XtqE1FvubDVaQBmEpJrWLS_49esDTJGMjW3SpPkhFYbL9JyiHWSPss5w/s1600-h/non_local_aspnetdb%25255B5%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;non_local_aspnetdb&quot; border=&quot;0&quot; alt=&quot;non_local_aspnetdb&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0fr4lm7N77IWmMsRhUVjxMh8AIyBOTdSjSWBpTWep3hkOYQNkVVpl_414Os6JSUv_hJ-Np_OCDg16NKIfijsGKlXyatYvZr3RfNcE9Zu906e56T5H8vjoq2-X9CQVwJdsJy6XRy0OUnPx/?imgmax=800&quot; width=&quot;604&quot; height=&quot;54&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Pressing F5 to run/debug the web application should fire up the default application, and allow you to create an account to authenticate against in future. The default home page after logging in should look like this:&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFdIlqJitYRSWsne1zxsnSKIfRMMk-b8xfFPFdL3M4LbOGlWwZ-bYg8XBA-vO7bb-PMxWsAnTjRNl5oZMOCIuivZzX8rc3T65bfuqmmWMv43HjLymVGGl0x6H_k-wTRO9h79Zs6YwI04W6/s1600-h/default_home%25255B11%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;default_home&quot; border=&quot;0&quot; alt=&quot;default_home&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjuAuppnVs0MpBQdo278wSXzore1_0xcvAtHT4ObWxDniwLQ4_Q04Pj6jAAsZvYFhFUApQ5iatvDmnVi0r4wGMC5zeXAtLqS1dFWjCjHasnk1klYOi6QaiFZRjSNo2jltHbQMJXt6Otzd9b/?imgmax=800&quot; width=&quot;604&quot; height=&quot;374&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;To create the picture album site, we create a new database with this simple schema:&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-I9OuGiOOjVwdDAadKW9OYvoQU2sn5EcuX5faQHsYdY7Z_IeK4YclTA_tM2vjJBcSxtjf733SwhVcC6GtkwPwVe5QYSw_V9C2Vc7MF_YV1J9Wmk7Peh4kksqZNIo_DF8JMDjc39V30458/s1600-h/pictures_schema%25255B4%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;pictures_schema&quot; border=&quot;0&quot; alt=&quot;pictures_schema&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibKGCDYe5q6jnWcNJBwSjqQu3pV1oQ4F1_DkVb8PMYJ_u5HWdBbT3H5vLRpND1GPyVQPznUtmC1OAbG7ecdM4dMALmYhJrjc4ZFMNqwTJx5Dyuyax2fFQRBe1NphAynluQK0NH7iff60vC/?imgmax=800&quot; width=&quot;304&quot; height=&quot;369&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Note that for this demonstration, we will store the uploaded picture in an image column on the Picture table, in the database. &lt;/p&gt; &lt;p&gt;We’ll use Linq 2 SQL to create a data-model for our application.&lt;/p&gt; &lt;p&gt;When we’re done with adding the Linq2Sql classes, the connectionStrings collection in our Web.Config looks like:&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjv4ZDG2-UPVenwM1oFGQqm9d425hNI0BILQencosWiR-KRLUiRSSOVneRYkg6ansdhguZcBPwB7iSQNuPVzfFlhsWc6ezuzcccecWwLO_pypEskH5hzzY_4Dr-3xedu9nQyKfjasul4ZUk/s1600-h/connection_strings%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;connection_strings&quot; border=&quot;0&quot; alt=&quot;connection_strings&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgswigIAfR2qq5NcwYPXyboqtCK8cV4aVFzTb_LOFSSZAc9_iwl5aB0Sjw2lcxr4EhauABZTspcteRKw76pBZbGaZdUD_8GPEga2fpUuFScQk6YWHD6UcV9QbMYMEnY3ye1bNxcDGbZWnZN/?imgmax=800&quot; width=&quot;604&quot; height=&quot;59&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Now we’ll actually develop the application, and let’s say we finally land up with:&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCGf8Df5Tgv0Rmo53-0Lg-XXUM_3FBI65Ubl4LDc2yUjzgelZYgcYgFI01EhWQS72zvZ6B9Jrryi8W-P9uxXlbW9Ltt8OS6CGc9GywGHY6P1p8LYZro1CbegJRydP_pUPpVlxy_C8NdwnA/s1600-h/sharpix%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;sharpix&quot; border=&quot;0&quot; alt=&quot;sharpix&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiupN_Hf7m57lk9uIYPfMRhGhymtPkULfrT8rENPifNX_wh5MlNTixoRYsOIVmvLDMfPn64FLVwWRTcHThmowTD-rYPZB_u8iGGXy4M2N9Jytd8k2OWYNZuXzrsRFeGk5v6gw4vNA7CFOe3/?imgmax=800&quot; width=&quot;604&quot; height=&quot;386&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Let’s also assume that the application contains, &lt;em&gt;for the sake of this demonstration&lt;/em&gt;, the following code to extract the binary data from the database and cache the file on the file system, so that the images on the rendered page refer to the cached file:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;var relativePathToDirectory = &quot;~/.cache&quot;;&lt;br /&gt;&lt;br /&gt;// ensure the directory exists&lt;br /&gt;var absolutePathToDirectory = Server.MapPath(relativePathToDirectory);&lt;br /&gt;if (!Directory.Exists(absolutePathToDirectory))&lt;br /&gt;{&lt;br /&gt;    Directory.CreateDirectory(absolutePathToDirectory);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// now ensure the file exists&lt;br /&gt;var relativePathToFile = Path.Combine(relativePathToDirectory, picture.OriginalFilename);&lt;br /&gt;var absolutePathToFile = Server.MapPath(relativePathToFile);&lt;br /&gt;&lt;br /&gt;if (File.Exists(absolutePathToFile)) return absolutePathToFile;&lt;br /&gt;&lt;br /&gt;using (var stream = new FileStream(&lt;br /&gt;        absolutePathToFile,&lt;br /&gt;        FileMode.OpenOrCreate,&lt;br /&gt;        FileSystemRights.TakeOwnership | FileSystemRights.Write,&lt;br /&gt;        FileShare.None,&lt;br /&gt;        1024,&lt;br /&gt;        FileOptions.None))&lt;br /&gt;{&lt;br /&gt;    stream.Write(picture.Image.ToArray(), 0, picture.Image.Length);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;We have a rudimentary, but fully functional web application that runs on our local web server in the traditional manner.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;We will need to consider the specific changes to make when we want to migrate this application to the cloud.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;PS:&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;We’ll put the source code on github and stick the link in here just after the talk.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a title=&quot;TechEd Australia 2011; COS204; Migrating your applications to Azure&quot; href=&quot;http://australia.msteched.com/topic/details/COS204#showdetails&quot; target=&quot;_blank&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;blogBling_150x150_023&quot; border=&quot;0&quot; alt=&quot;blogBling_150x150_023&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiauTfWDpDcBRtfCWF4guDN5KYed580QxxTSQv0C7bcfgECMf3GCEYUnRbFqOd_kx5Wq_hy5zG3f-h95lPi86gQE8ov6fnZChlRxJnhaBfgW2GrHJCHpxDksVNFdnw1Wx62G-KUUC23HGol/?imgmax=800&quot; width=&quot;154&quot; height=&quot;154&quot;&gt;&lt;/a&gt;&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/6101143376050089336/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/08/migrating-web-application-to-azure-step.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/6101143376050089336'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/6101143376050089336'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/08/migrating-web-application-to-azure-step.html' title='Migrating a Web Application to Azure: Step 0'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjMjRDfBcnjwgOfI7-5dYOTyzHbxyFGhxb0Pg8jyFGAzee9qAQ7XSu3Cre77yW_gBlKRshmkziSAZgScdZZnvfDd7cCSX2sEdYp8I4ENrxX0uRXDFZ4X4OTTldOEiTEXWvbXmqOH29ukCn7/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-3290339355434681402</id><published>2011-08-25T08:59:00.001-07:00</published><updated>2011-08-27T08:35:01.236-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Cloud"/><category scheme="http://www.blogger.com/atom/ns#" term="COS204"/><category scheme="http://www.blogger.com/atom/ns#" term="SQL Azure"/><category scheme="http://www.blogger.com/atom/ns#" term="TechEd 2011"/><category scheme="http://www.blogger.com/atom/ns#" term="Windows Azure"/><title type='text'>Migrating a Web Application to Azure: Introduction</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;This is a series of posts relating to the details of the talk Mahesh Krishnan and I will be giving at &lt;a href=&quot;http://australia.msteched.com/default.aspx&quot; target=&quot;_blank&quot;&gt;TechEd Australia 2011&lt;/a&gt;. You can follow along in this series of posts for more details and gotchas that we can’t cover in the 60 minute talk at TechEd!&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;http://australia.msteched.com/topic/details/COS204#showdetails&quot; target=&quot;_blank&quot;&gt;Here&lt;/a&gt; are the details of the talk:&lt;/p&gt; &lt;p&gt;We’ll be taking a contrived, but simple, traditional data-driven web application, and outlining the issues to consider, and steps to take, to move the application to Windows Azure/Sql Azure.&lt;/p&gt; &lt;p&gt;We’ll show you how to set up your Azure subscription, migrate your database to Sql Azure, manage session state with Azure’s Session State Manager, move file-system based actions to Windows Azure blob storage, and secure your application with Azure’s ACS 2.0 Federated Authentication.&lt;/p&gt; &lt;p&gt;We’ll show you what tools you need and how to use Visual Studio 2010 SP1 to simplify the process of migrating.&lt;/p&gt; &lt;p&gt;There’s some code, but mostly we’re going to be discussing issues, tips and tricks. &lt;/p&gt; &lt;p&gt;See you there!&lt;/p&gt; &lt;p&gt;&lt;a title=&quot;TechEd Australia 2011; COS204; Migrating your applications to Azure&quot; href=&quot;http://australia.msteched.com/topic/details/COS204#showdetails&quot; target=&quot;_blank&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;blogBling_150x150_02&quot; border=&quot;0&quot; alt=&quot;blogBling_150x150_02&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9x9DkK3pYwZy5y3v03EWOCrah625l2htfpo8wIcL8kKiOLPeKE6UO9REJGBuDUE0_c82VD-eQW1vBOBiQ-UXO08P8PDCN9A-G5cElOxNhm6y5sSc9bQleDH_iH7cyRRGmtKXpZtwnzHXt/?imgmax=800&quot; width=&quot;154&quot; height=&quot;154&quot;&gt;&lt;/a&gt;&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/3290339355434681402/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/08/migrating-web-application-to-azure.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/3290339355434681402'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/3290339355434681402'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/08/migrating-web-application-to-azure.html' title='Migrating a Web Application to Azure: Introduction'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9x9DkK3pYwZy5y3v03EWOCrah625l2htfpo8wIcL8kKiOLPeKE6UO9REJGBuDUE0_c82VD-eQW1vBOBiQ-UXO08P8PDCN9A-G5cElOxNhm6y5sSc9bQleDH_iH7cyRRGmtKXpZtwnzHXt/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-6940171216624430562</id><published>2011-07-10T21:30:00.001-07:00</published><updated>2011-07-11T16:46:38.500-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Feber"/><category scheme="http://www.blogger.com/atom/ns#" term="Functional"/><category scheme="http://www.blogger.com/atom/ns#" term="Lambda"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><title type='text'>Functional Object Manipulation</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;In the &lt;a href=&quot;http://scrumofone.blogspot.com/2011/06/fast-object-copier.html&quot; target=&quot;_blank&quot;&gt;last&lt;/a&gt; &lt;a href=&quot;http://scrumofone.blogspot.com/2011/07/object-copier-revisited.html&quot; target=&quot;_blank&quot;&gt;couple&lt;/a&gt; of posts, we’ve looked at ways to copy scalar properties from one object to another, with the high performance of explicit assignments and the low maintenance of reflection.&lt;/p&gt; &lt;p&gt;The approach of creating a lambda to operate on the object instance as a whole shows a lot of promise. For example, we may want to compare two object instances property-by-property, and the code for that would look quite similar.&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static class Comparer&lt;br /&gt;{&lt;br /&gt;    public static bool Compare&amp;lt;T&amp;gt;(this T source, T destination) { return CompareClosure&amp;lt;T&amp;gt;.Compare(source, destination); }&lt;br /&gt;&lt;br /&gt;    private static class CompareClosure&amp;lt;T&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        private static Func&amp;lt;T, T, bool&amp;gt; BuildComparerLambda(Func&amp;lt;PropertyInfo, bool&amp;gt; propertyFilter = null)&lt;br /&gt;        {&lt;br /&gt;            propertyFilter = propertyFilter ?? (_ =&amp;gt; true);&lt;br /&gt;&lt;br /&gt;            var sourceParameterExpression = Expression.Parameter(typeof(T), &quot;_left&quot;);&lt;br /&gt;            var destinationParameterExpression = Expression.Parameter(typeof(T), &quot;_right&quot;);&lt;br /&gt;&lt;br /&gt;            var properties = typeof(T).GetProperties().Where(propertyFilter);&lt;br /&gt;            var expressions = properties.Select(_pi =&amp;gt; Expression.Equal(Expression.Property(destinationParameterExpression, _pi), Expression.Property(sourceParameterExpression, _pi)));&lt;br /&gt;            var conjoinedExpression = expressions.Aggregate&amp;lt;Expression, Expression&amp;gt;(Expression.Constant(true), Expression.AndAlso);&lt;br /&gt;&lt;br /&gt;            var lambdaExpression = Expression.Lambda&amp;lt;Func&amp;lt;T, T, bool&amp;gt;&amp;gt;(conjoinedExpression, sourceParameterExpression, destinationParameterExpression);&lt;br /&gt;            return lambdaExpression.Compile();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private static readonly Func&amp;lt;T, T, bool&amp;gt; _compare = BuildComparerLambda();&lt;br /&gt;        public static bool Compare(T source, T destination) { return _compare(source, destination); }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;which gives us: &lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjo1aWYeiBVWtvdODF3z1CaAiHzGEAzUaSPZI0xKQQ3_X13cVAh9bI1y2lHyC2uOi3FhSwfJrk90EZFeao7G8AGqxe_jWe1cR5Rqy_VMqtcuYYMdAZSN7y8SO4gzvH2cR6NMEL3zFxBNZSQ/s1600-h/comparer%25255B3%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;comparer&quot; border=&quot;0&quot; alt=&quot;comparer&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdL_8mvo0qd3GO54Tc3wZAIiRH5JqNp1TjEluaWp3F9T0DvyWlpLeMwXSKvoMJ-OUz1STT0IXk6ILtCqXGlpHOLVN4fQjLPaiO9XpIsHfd48QxuoJp2iaZkymEzcDhd-cuGY1cSwwgDJkB/?imgmax=800&quot; width=&quot;688&quot; height=&quot;232&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;What are are doing in the code is mapping each property to a boolean value indicating whether the two instances have the same value for the property, and then folding that set of boolean values to a single boolean value by aggregating it with the &amp;amp;&amp;amp; operator (and a seed value of ‘true’).&lt;/p&gt;&lt;br /&gt;&lt;p&gt;We can readily see a pattern emerging here:&lt;/p&gt;&lt;br /&gt;&lt;p&gt;There are two types of operations possible for a given arity. In the case of Compare and Copy where the operation arity is 2, we can create either an Action&amp;lt;T, T&amp;gt; or a Func&amp;lt;T, T, TResult&amp;gt;.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;The Action&amp;lt;&amp;gt; case is a lambda that performs an operation on each property with reference to the given argument instances. &lt;/p&gt;&lt;br /&gt;&lt;p&gt;We can create a general operation builder by lifting a parameter which specifies the desired operation on a property, with reference to the lambda arguments.&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static Action&amp;lt;T, T&amp;gt; BuildOperationAction&amp;lt;T&amp;gt;(&lt;br /&gt;    Func&amp;lt;PropertyInfo, ParameterExpression, ParameterExpression, Expression&amp;gt; operationExpressionFactory)&lt;br /&gt;{&lt;br /&gt;    var leftParameterExpression = Expression.Parameter(typeof (T), &quot;_left&quot;);&lt;br /&gt;    var rightParameterExpression = Expression.Parameter(typeof (T), &quot;_right&quot;);&lt;br /&gt;&lt;br /&gt;    var properties = typeof (T).GetProperties();&lt;br /&gt;    var expressions = properties.Select(_ =&amp;gt; operationExpressionFactory(_, leftParameterExpression, rightParameterExpression));&lt;br /&gt;&lt;br /&gt;    var blockExpression = Expression.Block(expressions);&lt;br /&gt;    var lambdaExpression = Expression.Lambda&amp;lt;Action&amp;lt;T, T&amp;gt;&amp;gt;(blockExpression, leftParameterExpression, rightParameterExpression);&lt;br /&gt;&lt;br /&gt;    return lambdaExpression.Compile();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;The Func&amp;lt;&amp;gt; case is a lambda that maps the set of properties to a set of values with reference to the argument instances, and then aggregates this set of values to a single value using an aggregator. &lt;/p&gt;&lt;br /&gt;&lt;p&gt;We can create a general operation builder by lifting:&lt;/p&gt;&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;a parameter which specifies the desired operation on a property, with reference to the lambda arguments &lt;br /&gt;&lt;li&gt;a parameter which specifies the aggregate operation to fold the set of computed values to a single value, and &lt;br /&gt;&lt;li&gt;a parameter specifying the initial value for the aggregator. &lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;&lt;p&gt;Thusly:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static Func&amp;lt;T, T, TResult&amp;gt; BuildOperationFunc&amp;lt;T, TResult&amp;gt;(&lt;br /&gt;    Func&amp;lt;PropertyInfo, ParameterExpression, ParameterExpression, Expression&amp;gt; operationExpressionFactory,&lt;br /&gt;    Func&amp;lt;Expression, Expression, Expression&amp;gt; conjunction, Expression seed)&lt;br /&gt;{&lt;br /&gt;    var leftParameterExpression = Expression.Parameter(typeof (T), &quot;_left&quot;);&lt;br /&gt;    var rightParameterExpression = Expression.Parameter(typeof (T), &quot;_right&quot;);&lt;br /&gt;&lt;br /&gt;    var properties = typeof (T).GetProperties();&lt;br /&gt;    var expressions = properties.Select(_ =&amp;gt; operationExpressionFactory(_, leftParameterExpression, rightParameterExpression));&lt;br /&gt;&lt;br /&gt;    var joinedExpression = expressions.Aggregate(seed, conjunction);&lt;br /&gt;    var lambdaExpression = Expression.Lambda&amp;lt;Func&amp;lt;T, T, TResult&amp;gt;&amp;gt;(joinedExpression, leftParameterExpression, rightParameterExpression);&lt;br /&gt;&lt;br /&gt;    return lambdaExpression.Compile();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;This allows us to implement Copy() and Compare() as follows:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static bool CompareWith&amp;lt;T&amp;gt;(this T source, T destination) { return CompareClosure&amp;lt;T&amp;gt;.Compare(source, destination); }&lt;br /&gt;private static class CompareClosure&amp;lt;T&amp;gt;&lt;br /&gt;{&lt;br /&gt;    private static readonly Func&amp;lt;T, T, bool&amp;gt; _compare =&lt;br /&gt;        BuildOperationFunc&amp;lt;T, bool&amp;gt;(&lt;br /&gt;            (_pi, _src, _dest) =&amp;gt; Expression.Assign(Expression.Property(_dest, _pi), Expression.Property(_src, _pi)),&lt;br /&gt;            Expression.AndAlso,&lt;br /&gt;            Expression.Constant(true));&lt;br /&gt;&lt;br /&gt;    public static bool Compare(T source, T destination) { return _compare(source, destination); }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static void CopyTo&amp;lt;T&amp;gt;(this T source, T destination) { CopyClosure&amp;lt;T&amp;gt;.Copy(source, destination); }&lt;br /&gt;private static class CopyClosure&amp;lt;T&amp;gt;&lt;br /&gt;{&lt;br /&gt;    private static readonly Action&amp;lt;T, T&amp;gt; _copy =&lt;br /&gt;        BuildOperationAction&amp;lt;T&amp;gt;(&lt;br /&gt;            (_pi, _src, _dest) =&amp;gt; Expression.Assign(Expression.Property(_dest, _pi), Expression.Property(_src, _pi)));&lt;br /&gt;&lt;br /&gt;    public static void Copy(T source, T destination) { _copy(source, destination); }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Very neat.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;We could develop more operations than Copy and Compare, building fast, automatically maintained mappers for data access (think ORMs) and UI field access, by simply specifying the equivalent expression. The development effort is simply in the development of the expression.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;For example, here is a mapper which maps properties defined on type T, from a dynamic source object to backing fields on a target object of type T:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;private static readonly Action&amp;lt;T, T&amp;gt; _copyDynamicToStaticBackingFields = &lt;br /&gt;	BuildOperationAction&amp;lt;T&amp;gt;(&lt;br /&gt;	    (_pi, _src, _dest) =&amp;gt;&lt;br /&gt;	    {&lt;br /&gt;	        var sourceBinder = RuntimeBinder.GetMember(CSharpBinderFlags.InvokeSpecialName, _pi.Name, typeof (T), new [ ] { ThisArgument });&lt;br /&gt;	        var sourceGetExpression = Expression.Convert(Expression.Dynamic(sourceBinder, typeof (object), _src), _pi.PropertyType);&lt;br /&gt;&lt;br /&gt;	        var fieldName = String.Format(&quot;_{0}{1}&quot;, _pi.Name.Substring(0, 1).ToLower(), _pi.Name.Substring(1));&lt;br /&gt;&lt;br /&gt;	        var fieldInfo = typeof (T).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);&lt;br /&gt;	        if (fieldInfo == null) return Expression.Default(typeof (void));&lt;br /&gt;&lt;br /&gt;	        var destinationAccessExpression = Expression.Field(_dest, fieldInfo);&lt;br /&gt;	        return Expression.Assign(destinationAccessExpression, sourceGetExpression);&lt;br /&gt;	    });&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;We could further develop this approach by developing the BuildOperationXXX functions for Action&amp;lt;&amp;gt;s and Func&amp;lt;&amp;gt;s of arity 1, which would allow us to quickly develop fast, low-maintenance object printers and serializers. &lt;/p&gt;&lt;br /&gt;&lt;p&gt;I believe that this set of generating functions is likely to be more generally useful, so I’ve created a &lt;a href=&quot;http://feber.codeplex.com/&quot; target=&quot;_blank&quot;&gt;CodePlex&lt;/a&gt; project for this. Please visit it and let me know how you used it!&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/6940171216624430562/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/07/functional-object-manipulation.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/6940171216624430562'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/6940171216624430562'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/07/functional-object-manipulation.html' title='Functional Object Manipulation'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdL_8mvo0qd3GO54Tc3wZAIiRH5JqNp1TjEluaWp3F9T0DvyWlpLeMwXSKvoMJ-OUz1STT0IXk6ILtCqXGlpHOLVN4fQjLPaiO9XpIsHfd48QxuoJp2iaZkymEzcDhd-cuGY1cSwwgDJkB/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-7054880275307067865</id><published>2011-07-10T17:48:00.001-07:00</published><updated>2011-07-11T16:46:38.501-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Feber"/><category scheme="http://www.blogger.com/atom/ns#" term="Functional"/><category scheme="http://www.blogger.com/atom/ns#" term="Lambda"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><title type='text'>The Object Copier, revisited.</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;We saw in the &lt;a href=&quot;http://scrumofone.blogspot.com/2011/06/fast-object-copier.html&quot; target=&quot;_blank&quot;&gt;previous post&lt;/a&gt; how we could improve the maintainability of reflection-based code by building lambdas using reflection, and then gain the performance benefits by applying the lambdas at execution time.&lt;/p&gt; &lt;p&gt;Taking the idea a step further, we can easily see that what we are really doing is generating a function to do the copy operation on the entire object and applying the copy function.&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;(T _source, T _destination) =&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        _destination.Id = _source.Id;&lt;br /&gt;        _destination.Name = _source.Name;&lt;br /&gt;        ...&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Based on the approach we took last time, this is easily achievable by wrapping the individual assignments into a block statement, wiring through the parameter expressions from the block into the individual lambdas, and then compiling out a full copy. Thusly:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static class Copier&lt;br /&gt;{&lt;br /&gt;    public static void CopyTo&amp;lt;T&amp;gt;(this T source, T destination) { CopyClosure&amp;lt;T&amp;gt;.Copy(source, destination); }&lt;br /&gt;&lt;br /&gt;    private static class CopyClosure&amp;lt;T&amp;gt;&lt;br /&gt;    {&lt;br /&gt;        private static Action&amp;lt;T, T&amp;gt; BuildCopierLambda()&lt;br /&gt;        {&lt;br /&gt;            var sourceParameterExpression = Expression.Parameter(typeof(T), &quot;_source&quot;);&lt;br /&gt;            var destinationParameterExpression = Expression.Parameter(typeof(T), &quot;_destination&quot;);&lt;br /&gt;&lt;br /&gt;            var properties = typeof(T).GetProperties();&lt;br /&gt;            var expressions = properties.Select(_pi =&amp;gt; Expression.Assign(Expression.Property(destinationParameterExpression, _pi), Expression.Property(sourceParameterExpression, _pi)));&lt;br /&gt;&lt;br /&gt;            var blockExpression = Expression.Block(expressions);&lt;br /&gt;            var lambdaExpression = Expression.Lambda&amp;lt;Action&amp;lt;T, T&amp;gt;&amp;gt;(blockExpression, sourceParameterExpression, destinationParameterExpression);&lt;br /&gt;&lt;br /&gt;            return lambdaExpression.Compile();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        private static readonly Action&amp;lt;T, T&amp;gt; _copy = BuildCopierLambda();&lt;br /&gt;        public static void Copy(T source, T destination) { _copy(source, destination); }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;There are a few things to note about the code:&lt;/p&gt;&lt;br /&gt;&lt;p&gt;The outer, public, static&amp;nbsp; Copier class is non-generic to allow the CopyTo operation to be defined as an extension property on generic type T.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;The compiler will create a special, unique CopyClosure class for each type T. This ensures that the _copy Action is unique for each type T. Also, the _copy Action is initialized in a thread-safe manner, because the compiler guarantees thread-safety on field initializers.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;This approach actually improves performance, because there is no run-time iteration!&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgYNy_QT9shG4kPPKoCPVNXOQlrkHTZIkyCG_t24LPdfL7bZuGKBwLxODf6BH1EQkb-0Wmiqji9Xsw2jIo-sY60aKRKwV_Q9nMWVek1O_N0C02AX9imT7b8dWtH_9l6dbfx_rtmjLF2A97u/s1600-h/copy_block_expression%25255B5%25255D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;copy_block_expression&quot; border=&quot;0&quot; alt=&quot;copy_block_expression&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXta-usQ47yR74qwy7o74A0td5dfNtuB6_sAB4hFq4KfwGHDHNOr6jj478cs8jwXnp-JHdUjLOaA7l9AdyGn9dQPm5Nh0Hbw5smb_2ZkO1cLNAcZrQrNq6sd7OMZxfcifXBIQP51b35Fuw/?imgmax=800&quot; width=&quot;688&quot; height=&quot;263&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Stay tuned for more improvements…&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/7054880275307067865/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/07/object-copier-revisited.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/7054880275307067865'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/7054880275307067865'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/07/object-copier-revisited.html' title='The Object Copier, revisited.'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXta-usQ47yR74qwy7o74A0td5dfNtuB6_sAB4hFq4KfwGHDHNOr6jj478cs8jwXnp-JHdUjLOaA7l9AdyGn9dQPm5Nh0Hbw5smb_2ZkO1cLNAcZrQrNq6sd7OMZxfcifXBIQP51b35Fuw/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-8251097074184447219</id><published>2011-06-27T14:54:00.001-07:00</published><updated>2011-07-11T16:46:38.501-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Feber"/><category scheme="http://www.blogger.com/atom/ns#" term="Functional"/><category scheme="http://www.blogger.com/atom/ns#" term="Lambda"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><title type='text'>A (Fast) Object Copier</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;A colleague of mine asked me today to help with the onerous task of “twisting-off” the data in an entity into a DTO. Something about serialization, he said…&lt;/p&gt; &lt;p&gt;He said that he didn’t mind if the copying was slow – just that he didn’t want to put in hundreds of lines of code each saying&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;destination.Id = source.Id;&lt;br&gt;destination.Name = source.Name;&lt;br&gt;destination.DateAndTimeOfBirth = source.DateAndTimeOfBirth;&lt;br&gt;destination.BirthWeightInKilograms = source.BirthWeightInKilograms;&lt;br&gt;destination.IsMultipleBirth = source.IsMultipleBirth;&lt;br&gt;destination.BirthOrder = source.BirthOrder;&lt;br&gt;...&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;So I sat down and knocked off the traditional reflection-based code:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;internal static T Map&amp;lt;T&amp;gt;(T source, T destination) where T : class&lt;br&gt;{&lt;br&gt;    foreach (var pi in typeof (T).GetProperties())&lt;br&gt;    {&lt;br&gt;        pi.SetValue(destination,&lt;br&gt;                    pi.GetValue(source, BindingFlags.GetProperty | BindingFlags.Instance, null, null, null),&lt;br&gt;                    BindingFlags.SetProperty | BindingFlags.Instance,&lt;br&gt;                    null,&lt;br&gt;                    null,&lt;br&gt;                    null);&lt;br&gt;    }&lt;br&gt;    return destination;&lt;br&gt;}&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;(I’ve removed the error checking just to keep things simple for this post)&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Neat and all, and does the job. &lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;But I couldn’t help wondering if I could do better – specially since I knew that the performance would potentially be too terrible to bear…&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;h2&gt;Express(ion) yourself!&lt;/h2&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;It would be nice to use the tricks we learned with expressions to create, for a given type, a set of assignment expressions for each of the properties, and then simply apply all expressions one by one to the source and destination, and that way the cost of reflection is borne only once.&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Fair enough. I got home, and after dinner, knocked off this piece of code:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static class FastCopier&lt;br&gt;{&lt;br&gt;    public static T Copy&amp;lt;T&amp;gt;(T source, T destination) where T : class&lt;br&gt;    {&lt;br&gt;        return FastCopierInternal&amp;lt;T&amp;gt;.Copy(source, destination);&lt;br&gt;    }&lt;br&gt;&lt;br&gt;    private static class FastCopierInternal&amp;lt;T&amp;gt;&lt;br&gt;    {&lt;br&gt;        private static readonly IDictionary&amp;lt;PropertyInfo, Action&amp;lt;T, T&amp;gt;&amp;gt; _copyFunctions = typeof (T).GetProperties().ToDictionary(_pi =&amp;gt; _pi, GetCopyFunc);&lt;br&gt;    &lt;br&gt;        private static Action&amp;lt;T, T&amp;gt; GetCopyFunc(PropertyInfo propertyInfo)&lt;br&gt;        {&lt;br&gt;            Trace.WriteLine(String.Format(&quot;Creating mapping func for {0}.{1}&quot;, propertyInfo.DeclaringType.Name, propertyInfo.Name));&lt;br&gt;            var sourceParameterExpression = Expression.Parameter(typeof (T), &quot;_source&quot;);&lt;br&gt;            var destinationParameterExpression = Expression.Parameter(typeof (T), &quot;_destination&quot;);&lt;br&gt;    &lt;br&gt;            var sourceAccessExpression = Expression.Property(sourceParameterExpression, propertyInfo);&lt;br&gt;            var destinationAccessExpression = Expression.Property(destinationParameterExpression, propertyInfo);&lt;br&gt;    &lt;br&gt;            var sourceAssignmentExpression = Expression.Assign(destinationAccessExpression, sourceAccessExpression);&lt;br&gt;    &lt;br&gt;            var lambdaExpression = Expression.Lambda&amp;lt;Action&amp;lt;T, T&amp;gt;&amp;gt;(sourceAssignmentExpression,&lt;br&gt;                                                                   sourceParameterExpression,&lt;br&gt;                                                                   destinationParameterExpression);&lt;br&gt;    &lt;br&gt;            return lambdaExpression.Compile();&lt;br&gt;        }&lt;br&gt;    &lt;br&gt;        public static T Copy(T source, T destination)&lt;br&gt;        {&lt;br&gt;            foreach (var func in _copyFunctions.Values)&lt;br&gt;            {&lt;br&gt;                func(source, destination);&lt;br&gt;            }&lt;br&gt;    &lt;br&gt;            return destination;&lt;br&gt;        }&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Here we have a static class with a single public method to do the Copy for a given type T.&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Internally, we have a static generic copier class which only gets instantiated once for each type T, and which builds up an associative array of the properties of the type and the function required to copy each property from source to destination.&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Here’s what the lambda expression looks like as it is built:&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJ9PsgdaoDz6fDRU509iL3BQ3I-4jxntqQREzxMexLUJeou1GSyo4UchQr-eK7tPQsXaK-S4-eogcMdykq7EpEFTwZAqsn3NDY6XsDWCUJg_M-VUsnPnX4_E0_5LDd3287X8VATHI5gfi8/s1600-h/assignment_lambda8.jpg&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;assignment_lambda&quot; border=&quot;0&quot; alt=&quot;assignment_lambda&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjHMT04VmPkPIXr37eJ4rEZq0QT31BuG_rUtwjzlnKsxlac32jGauj4CTNFZcX_nRf9lCWyS24DoytczYRJLDGyn9NePHjJiscUpnWVlOzI1j1Gjz5O-QJNgHLYDW0ghFbVbJd_0aIZJJt/?imgmax=800&quot; width=&quot;684&quot; height=&quot;180&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;When the public Copy method on the outer class is called, it calls the Copy method on the (implicitly initalized) inner static class, which applies each of the copy functions in turn to copy the source to the destination one property at a time.&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Pretty cool. So how much faster are we?&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;Explicit copy of object 1000000 times took 204 ms&lt;br&gt;Fast copy of object 1000000 times took 790 ms&lt;br&gt;Slow copy of object 1000000 times took 23801 ms&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Running over a million objects, the fastest, as expected, is when we explicitly code the DTO initialization, and let the compiler optimize.&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;The lambda version is around 3.5x slower, but still pretty darn fast compared with the basic, slow, all-reflection version – which is two orders of magnitude slower!&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Not a bad option to have, when the development and maintenance cost of creating the DTOs and keeping them up to date is factored in!&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/8251097074184447219/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/06/fast-object-copier.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/8251097074184447219'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/8251097074184447219'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/06/fast-object-copier.html' title='A (Fast) Object Copier'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjHMT04VmPkPIXr37eJ4rEZq0QT31BuG_rUtwjzlnKsxlac32jGauj4CTNFZcX_nRf9lCWyS24DoytczYRJLDGyn9NePHjJiscUpnWVlOzI1j1Gjz5O-QJNgHLYDW0ghFbVbJd_0aIZJJt/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-4477354467252740263</id><published>2011-06-05T19:26:00.001-07:00</published><updated>2011-07-11T16:46:03.548-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Functional"/><category scheme="http://www.blogger.com/atom/ns#" term="Lambda"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><title type='text'>Memoization Is Your Friend</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;I just came across some gems regarding memoization &lt;a href=&quot;http://blogs.msdn.com/b/wesdyer/archive/2007/01/26/function-memoization.aspx&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;, &lt;a href=&quot;http://blogs.msdn.com/b/wesdyer/archive/2007/02/05/memoization-and-anonymous-recursion.aspx&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;, &lt;a href=&quot;http://bartdesmet.net/blogs/bart/archive/2008/10/21/memoization-for-dummies.aspx&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt; and &lt;a href=&quot;http://mullr.wordpress.com/2006/05/02/easy-c-memoization/&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. As a side note, I’d like to go on record and say that Wes Dyer’s derivation of fixed-point combinators is second to none! Even I could understand what he was saying! :) Another great discussion of fixed-point combinators is &lt;a href=&quot;http://blogs.msdn.com/b/madst/archive/2007/05/11/recursive-lambda-expressions.aspx&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. For more theoretical underpinnings, &lt;a href=&quot;http://citeseer.ist.psu.edu/47853.html&quot; target=&quot;_blank&quot;&gt;this paper&lt;/a&gt; discusses memoization of fixed-point functions.&lt;/p&gt; &lt;p&gt;We’re being plagued by performance issues in the project I’m currently working on, and it would be really nice to have a quick way to to automatically memoize some functions to gain the benefits of laziness and good book-keeping.&lt;/p&gt; &lt;p&gt;So, here is my implementation of a Memoize() function, which uses the fixed-point combinator concepts explained in Wes’ blog.&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static Func&amp;lt;TArgument, TResult&amp;gt; MemoizeFix&amp;lt;TArgument, TResult&amp;gt;(Func&amp;lt;Func&amp;lt;TArgument, TResult&amp;gt;, Func&amp;lt;TArgument, TResult&amp;gt;&amp;gt; func)&lt;br /&gt;{&lt;br /&gt;    // ReSharper disable AccessToModifiedClosure&lt;br /&gt;    Func&amp;lt;TArgument, TResult&amp;gt; funcMemoized = null;&lt;br /&gt;&lt;br /&gt;    funcMemoized = func(_ =&amp;gt; funcMemoized(_));&lt;br /&gt;    funcMemoized = funcMemoized.Memoize();&lt;br /&gt;&lt;br /&gt;    return funcMemoized;&lt;br /&gt;    // ReSharper restore AccessToModifiedClosure&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private static Func&amp;lt;TArgument, TResult&amp;gt; Memoize&amp;lt;TArgument, TResult&amp;gt;(this Func&amp;lt;TArgument, TResult&amp;gt; func)&lt;br /&gt;{&lt;br /&gt;    var _map = new ConcurrentDictionary&amp;lt;TArgument, TResult&amp;gt;();&lt;br /&gt;    return _ =&amp;gt; _map.GetOrAdd(_, func);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;In MemoizeFix(), we create the funcMemoized variable as null so that we get around the &lt;a href=&quot;http://blogs.msdn.com/b/ericlippert/archive/2006/08/18/706398.aspx&quot; target=&quot;_blank&quot;&gt;definite assignment&lt;/a&gt; problem. Because we defer the assignment to after the application of the memoization, we actually &lt;em&gt;want to have access to the modified closure&lt;/em&gt;. &lt;br /&gt;&lt;p&gt;The other nice thing with .NET 4.0 is the ability to use the ConcurrentDictionary as a thread-safe result cache, with the added bonus of a very terse invocation to GetOrAdd().&lt;/p&gt;&lt;br /&gt;&lt;p&gt;We can use the memoization routines this way:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;private static readonly Func&amp;lt;int, long&amp;gt; FastFibonacci = Functional.MemoizeFix&amp;lt;int, long&amp;gt;(&lt;br /&gt;    fib =&amp;gt; n =&amp;gt; (n &amp;lt;= 0 ? 0 : (n &amp;lt;= 2 ? 1 : fib(n - 1) + fib(n - 2)))&lt;br /&gt;);&lt;br /&gt;&lt;br /&gt;private static readonly Func&amp;lt;int, long&amp;gt; FastLucas = Functional.MemoizeFix&amp;lt;int, long&amp;gt;(&lt;br /&gt;    luc =&amp;gt; (n =&amp;gt; FastFibonacci(n) + FastFibonacci(n + 2))&lt;br /&gt;);&lt;br /&gt;&lt;br /&gt;private static readonly Func&amp;lt;int, double&amp;gt; FastFactorial = Functional.MemoizeFix&amp;lt;int, double&amp;gt;(&lt;br /&gt;    fact =&amp;gt; n =&amp;gt; n &amp;lt; 2 ? 1.0d : n*fact(n - 1)&lt;br /&gt;);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;For functions with more than one argument, I’d create a Tuple&amp;lt;&amp;gt; with all the arguments as the cache key as the simplest extension. Thusly:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;private static Func&amp;lt;TArg1, TArg2, TResult&amp;gt; Memoize&amp;lt;TArg1, TArg2, TResult&amp;gt;(this Func&amp;lt;TArg1, TArg2, TResult&amp;gt; func)&lt;br /&gt;{&lt;br /&gt;    var _map = new ConcurrentDictionary&amp;lt;Tuple&amp;lt;TArg1, TArg2&amp;gt;, TResult&amp;gt;();&lt;br /&gt;    return (_a1, _a2) =&amp;gt; _map.GetOrAdd(new Tuple&amp;lt;TArg1, TArg2&amp;gt;(_a1, _a2), _ =&amp;gt; func(_.Item1, _.Item2));&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static Func&amp;lt;TArg1, TArg2, TResult&amp;gt; MemoizeFix&amp;lt;TArg1, TArg2, TResult&amp;gt;(Func&amp;lt;Func&amp;lt;TArg1, TArg2, TResult&amp;gt;, Func&amp;lt;TArg1, TArg2, TResult&amp;gt;&amp;gt; func)&lt;br /&gt;{&lt;br /&gt;    // ReSharper disable AccessToModifiedClosure&lt;br /&gt;    Func&amp;lt;TArg1, TArg2, TResult&amp;gt; funcMemoized = null;&lt;br /&gt;&lt;br /&gt;    funcMemoized = func((_a1, _a2) =&amp;gt; funcMemoized(_a1, _a2));&lt;br /&gt;    funcMemoized = funcMemoized.Memoize();&lt;br /&gt;&lt;br /&gt;    return funcMemoized;&lt;br /&gt;    // ReSharper restore AccessToModifiedClosure&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Pretty slick :)&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/4477354467252740263/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/06/memoization-is-your-friend.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/4477354467252740263'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/4477354467252740263'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/06/memoization-is-your-friend.html' title='Memoization Is Your Friend'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-1292421020987115016</id><published>2011-04-20T21:43:00.001-07:00</published><updated>2011-04-21T00:04:53.414-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Fun"/><category scheme="http://www.blogger.com/atom/ns#" term="Languages"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><title type='text'>C# Abuse</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;So I just watched &lt;a href=&quot;http://vimeo.com/19431830&quot; target=&quot;_blank&quot;&gt;this video presentation&lt;/a&gt; by Jon Skeet about some of the edges of our understanding of the C# language.&lt;/p&gt; &lt;p&gt;In &lt;a href=&quot;http://msmvps.com/blogs/jon_skeet/archive/2010/11/02/evil-code-overload-resolution-workaround.aspx&quot; target=&quot;_blank&quot;&gt;this blog post&lt;/a&gt;, he threw open the challenge to define three static methods such that the following code compiles:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;static void Main() &lt;br /&gt;{ &lt;br /&gt;    Foo&amp;lt;int&amp;gt;(); &lt;br /&gt;    Foo&amp;lt;string&amp;gt;(); &lt;br /&gt;    Foo&amp;lt;int?&amp;gt;(); &lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;While watching the video and playing around on my own, I came up with:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;class Program&lt;br /&gt;{&lt;br /&gt;    static void Foo&amp;lt;T&amp;gt;() { Console.WriteLine(typeof(T).Name); }&lt;br /&gt;&lt;br /&gt;    class Inner : Program&lt;br /&gt;    {&lt;br /&gt;        struct R&amp;lt;T&amp;gt; where T : class { }&lt;br /&gt;&lt;br /&gt;        static void Foo&amp;lt;T&amp;gt;(params R&amp;lt;T&amp;gt;?[] _) where T : class { Console.WriteLine(typeof(T).Name); }&lt;br /&gt;        static void Foo&amp;lt;T&amp;gt;(params T?[] _) where T : struct { Console.WriteLine(typeof(T).Name); }&lt;br /&gt;&lt;br /&gt;        static void Main()&lt;br /&gt;        {&lt;br /&gt;            Foo&amp;lt;int&amp;gt;();&lt;br /&gt;            Foo&amp;lt;string&amp;gt;();&lt;br /&gt;            Foo&amp;lt;int?&amp;gt;();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;which prints out the correct result. The analysis of how this works is given brilliantly over at Jon’s blog!&lt;/p&gt;&lt;br /&gt;&lt;p&gt;The key is the inner class, which forces the compiler to first check signature suitability for the two methods defined therein, before allowing the base class to catch-all with the most generalized signature.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi1KTaSdhVsLOAguPramO8FCTWRm38iT32qXW5Tta7FkWkSoh3KHYdQPZ9oM5SHRzs_uTL-VCeG1r0nwZDOB7xfjft3Uoog26idXKwXgbvhhi6Bk68YhIs2jXIVI6o8Z3i71iZQZozK3TyT/s1600-h/Figure%201%5B5%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Figure 1&quot; border=&quot;0&quot; alt=&quot;Figure 1&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWehkt1UkNkqA0DWWmcF7-UcUXIi-SQq0Rg3xhn5r1TmOlsc73gMiOWBL2g4niyOSZ00Wbx1yEDe1_U5hIB4YtyupTR0omSKOBq3EN_5qaSXOvGAbxtAIhiF6zr_mVd_k-sbWar366dUuH/?imgmax=800&quot; width=&quot;284&quot; height=&quot;113&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;The same caveat that Jon specified in his blog applies – such code should *never* be written!&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/1292421020987115016/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/04/c-abuse.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/1292421020987115016'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/1292421020987115016'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/04/c-abuse.html' title='C# Abuse'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWehkt1UkNkqA0DWWmcF7-UcUXIi-SQq0Rg3xhn5r1TmOlsc73gMiOWBL2g4niyOSZ00Wbx1yEDe1_U5hIB4YtyupTR0omSKOBq3EN_5qaSXOvGAbxtAIhiF6zr_mVd_k-sbWar366dUuH/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-9120988095464433201</id><published>2011-04-17T03:11:00.001-07:00</published><updated>2011-07-11T16:46:20.832-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Expression"/><category scheme="http://www.blogger.com/atom/ns#" term="Functional"/><category scheme="http://www.blogger.com/atom/ns#" term="Lambda"/><category scheme="http://www.blogger.com/atom/ns#" term="Languages"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><title type='text'>Lambda Wrangling For Fun : Part 4 – Sorting Multiple Columns</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;We can approach the problem of sorting a dataset by multiple properties using the same techniques as for the filter case.&lt;/p&gt; &lt;p&gt;A single-property sorting lambda looks like:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;….OrderBy(_ =&amp;gt; _.property) or ….OrderByDescending(_ =&amp;gt; _.property)&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;If we wanted to sort by more than one property, we would do something like:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;….OrderBy(_ =&amp;gt; _.property1).OrderByDescending(_ =&amp;gt; _.property2)&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;It’s important to notice two points:&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;The lambdas for each sort clause are self-contained – unlike the composite filter lambda where the same parameter is threaded through each predicate. &lt;br /&gt;&lt;li&gt;The &lt;em&gt;direction&lt;/em&gt; of the sort is specified by the use of either the &lt;font face=&quot;Courier New&quot;&gt;OrderBy&lt;/font&gt; or &lt;font face=&quot;Courier New&quot;&gt;OrderByDescending&lt;/font&gt; extension method. This means that the composite sort criteria will be represented by a chain of &lt;font face=&quot;Courier New&quot;&gt;OrderBy&lt;/font&gt; and/or &lt;font face=&quot;Courier New&quot;&gt;OrderByDescending&lt;/font&gt; methods.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p&gt;Bearing these points in mind, we can develop a general Sort action specification:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public interface ISort&amp;lt;TSource&amp;gt;&lt;br /&gt;{&lt;br /&gt;    string PropertyName { get; }&lt;br /&gt;    SortDirection SortDirection { get; }&lt;br /&gt;&lt;br /&gt;    Expression&amp;lt;Func&amp;lt;TSource, object&amp;gt;&amp;gt; GetSelectorLambda();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;The properties are as we expected, and we have encountered a variant &lt;font face=&quot;Courier New&quot;&gt;GetSelectorLambda&lt;/font&gt; &lt;a href=&quot;http://scrumofone.blogspot.com/2011/04/lambda-wrangling-for-fun-part-1-sorting.html&quot; target=&quot;_blank&quot;&gt;before&lt;/a&gt;.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Applying a composite sort on an enumerable can be achieved by:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static IOrderedEnumerable&amp;lt;T&amp;gt; Sort&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; _this, IEnumerable&amp;lt;ISort&amp;lt;T&amp;gt;&amp;gt; sortOperations)&lt;br /&gt;{&lt;br /&gt;    var parameterExpression = Expression.Parameter(typeof (IEnumerable&amp;lt;T&amp;gt;), &quot;_&quot;);&lt;br /&gt;&lt;br /&gt;    Expression items = parameterExpression;&lt;br /&gt;    foreach (var sortOperation in sortOperations)&lt;br /&gt;    {&lt;br /&gt;        // selector :  __ =&amp;gt; __.{sortOperation.PropertyName}&lt;br /&gt;        var selector = sortOperation.GetSelectorLambda();&lt;br /&gt;&lt;br /&gt;        // items.OrderBy&amp;lt;T, object&amp;gt;(__ =&amp;gt; __.Property) &lt;br /&gt;        //   is actually&lt;br /&gt;        // Enumerable.OrderBy&amp;lt;T, object&amp;gt;(items, __ =&amp;gt; __.Property)&lt;br /&gt;        items = Expression.Call(typeof (Enumerable),&lt;br /&gt;                                sortOperation.SortDirection == SortDirection.Ascending ? &quot;OrderBy&quot; : &quot;OrderByDescending&quot;,&lt;br /&gt;                                new [ ] { typeof (T), typeof (object) },&lt;br /&gt;                                items,&lt;br /&gt;                                selector);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // _ =&amp;gt; _.OrderBy[Descending](__ =&amp;gt; __.Property1)...OrderBy[Descending](__ =&amp;gt; __.PropertyN)&lt;br /&gt;    var lambda = Expression.Lambda&amp;lt;Func&amp;lt;IEnumerable&amp;lt;T&amp;gt;, IOrderedEnumerable&amp;lt;T&amp;gt;&amp;gt;&amp;gt;(items, parameterExpression);&lt;br /&gt;&lt;br /&gt;    // compile the lambda...&lt;br /&gt;    var func = lambda.Compile();&lt;br /&gt;&lt;br /&gt;    // ...call the chain of extension methods on (_this)&lt;br /&gt;    return func(_this);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;The function generates calls to either the ‘OrderyBy’ or the ‘OrderByDescending’ method on the Enumerable type, using the previous result as the first argument, thus generating the chain.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9Fif87Uz05RXdoTlyq2KlmMx4DXBgJvmWZhDQb1HX6QCi-pxLgjpp-IS53A1E4AWi2z_8BpGmYoaddbt9NgnyHLxsvAAzGU2suZ0J5HtUzYIQEtKbEIKRxw5DY5rNRIsEd3jj6wnE1aHO/s1600-h/Figure1%5B7%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Figure1&quot; border=&quot;0&quot; alt=&quot;Figure1&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiyZ8NBMeRKXG1_lMqGyDgxBeDvbDhgWonwb7eX1oA3oVtaR8xcGNZJSgsOltaSnfFgkF_j5RaKhwqY8WRakWpCHKPcwCWWU9PDjVNjCcbWYJFkLCqNFycZ5wmPkgz8oxbBDeA1kUOIrlx/?imgmax=800&quot; width=&quot;684&quot; height=&quot;114&quot;&gt;&lt;/a&gt;It finally compiles and executes the chain of methods on the actual enumerable instance passed in.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Here is a typical use:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;var sorts = new List&amp;lt;ISort&amp;lt;IPerson&amp;gt;&amp;gt; {&lt;br /&gt;                                        new Sort&amp;lt;IPerson&amp;gt;(&quot;Timestamp&quot;, SortDirection.Descending),&lt;br /&gt;                                        new Sort&amp;lt;IPerson&amp;gt;(&quot;Name&quot;, SortDirection.Ascending),&lt;br /&gt;                                     };&lt;br /&gt;&lt;br /&gt;var sortedPersons = persons.Sort(sorts);&lt;/pre&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/9120988095464433201/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/04/lambda-wrangling-for-fun-part-4-sorting.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/9120988095464433201'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/9120988095464433201'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/04/lambda-wrangling-for-fun-part-4-sorting.html' title='Lambda Wrangling For Fun : Part 4 – Sorting Multiple Columns'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiyZ8NBMeRKXG1_lMqGyDgxBeDvbDhgWonwb7eX1oA3oVtaR8xcGNZJSgsOltaSnfFgkF_j5RaKhwqY8WRakWpCHKPcwCWWU9PDjVNjCcbWYJFkLCqNFycZ5wmPkgz8oxbBDeA1kUOIrlx/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-1375548723194340594</id><published>2011-04-16T01:32:00.001-07:00</published><updated>2011-07-11T16:46:20.832-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Expression"/><category scheme="http://www.blogger.com/atom/ns#" term="Functional"/><category scheme="http://www.blogger.com/atom/ns#" term="Lambda"/><category scheme="http://www.blogger.com/atom/ns#" term="Languages"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><title type='text'>Lambda Wrangling For Fun : Part 3 – Filtering Multiple Columns</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;We &lt;a href=&quot;http://scrumofone.blogspot.com/2011/04/lambda-wrangling-for-fun-part.html&quot; target=&quot;_blank&quot;&gt;now know&lt;/a&gt; how to generate a dynamic predicate to filter a collection of items by a single property value.&lt;/p&gt; &lt;p&gt;It is often useful to be able to apply multiple filters to a collection to support more sophisticated searching and filtering operations.&lt;/p&gt; &lt;p&gt;Let’s define a general-purpose filter interface to encapsulate the property, the target value and the comparison function.&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public interface IFilter&lt;br /&gt;{&lt;br /&gt;    string PropertyName { get; }&lt;br /&gt;    dynamic TargetValue { get; }&lt;br /&gt;    Expression&amp;lt;Func&amp;lt;dynamic, dynamic, bool&amp;gt;&amp;gt; Comparison { get; }&lt;br /&gt;    Expression&amp;lt;Func&amp;lt;TSource, bool&amp;gt;&amp;gt; GetPredicateLambda&amp;lt;TSource&amp;gt;();&lt;br /&gt;    Expression BuildComparisonExpression&amp;lt;TSource&amp;gt;(Expression parameterExpression = null);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;The three properties are what we expect to see, and we’ve already seen a variant of the &lt;font face=&quot;Courier New&quot;&gt;GetPredicateLambda&lt;/font&gt; function &lt;a href=&quot;http://scrumofone.blogspot.com/2011/04/lambda-wrangling-for-fun-part.html&quot; target=&quot;_blank&quot;&gt;before&lt;/a&gt;.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Before we see what the other method is needed for, let’s analyse what it means to filter multiple columns first:&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;One Fish, Two Fish…&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;A filter with a single predicate comparing against a value looks thus:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;….Where(_ =&amp;gt; predicate0(_.property0, value0))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;and if we had to filter by more than one predicate would look like:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;….Where(_ =&amp;gt; predicate0(_.property0, value0) &lt;br /&gt;          &amp;amp;&amp;amp; predicate1(_.property1, value1))&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Notice that what we need to do is to create &lt;em&gt;just&lt;/em&gt; the comparison part part of the lambda for each filter, with the &lt;em&gt;same&lt;/em&gt; parameter injected into each predicate call.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;This is exactly what the &lt;font face=&quot;Courier New&quot;&gt;BuildComparisonExpression&lt;/font&gt; function does. Here is the implementation:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public virtual Expression BuildComparisonExpression&amp;lt;TSource&amp;gt;(Expression parameterExpression = null)&lt;br /&gt;{&lt;br /&gt;    // This gives us * _ *&lt;br /&gt;    parameterExpression = parameterExpression ?? Expression.Parameter(typeof (TSource), &quot;_&quot;);&lt;br /&gt;&lt;br /&gt;    var propertyInfo = typeof (TSource).GetProperty(PropertyName, true);&lt;br /&gt;    if (propertyInfo == null)&lt;br /&gt;    {&lt;br /&gt;        throw new MemberAccessException(String.Format(&quot;No such property exists: {0}&quot;, PropertyName));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    // This gives us * _.property *&lt;br /&gt;    var accessorExpression = Expression.Property(parameterExpression, propertyInfo);&lt;br /&gt;    &lt;br /&gt;    // This gives us * value *&lt;br /&gt;    var valueExpression = Expression.Constant(TargetValue);&lt;br /&gt;&lt;br /&gt;    // This gives us * comparison(_property, value) *&lt;br /&gt;    return Expression.Invoke(Comparison, accessorExpression, valueExpression);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;The key to this method is the last line. Expression.Invoke generates an expression which invokes the Comparison expression with the accessorExpression and valueExpression as its arguments.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Also, we do &lt;em&gt;not&lt;/em&gt; generate the Lambda with this expression, as we may have more than one Comparison to chain together.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;We do that as follows:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static Expression&amp;lt;Func&amp;lt;TSource, bool&amp;gt;&amp;gt; GetFilterExpression&amp;lt;TSource&amp;gt;(this IEnumerable&amp;lt;IFilter&amp;gt; filterCollection)&lt;br /&gt;{&lt;br /&gt;    if (filterCollection == null) return _ =&amp;gt; true;&lt;br /&gt;&lt;br /&gt;    var parameterExpression = Expression.Parameter(typeof (TSource), &quot;_&quot;);&lt;br /&gt;&lt;br /&gt;    var aggregateFilterExpression = filterCollection.Aggregate(&lt;br /&gt;           (Expression) Expression.Constant(true),&lt;br /&gt;           (current, filter) =&amp;gt; Expression.AndAlso(current, &lt;br /&gt;                     filter.BuildComparisonExpression&amp;lt;TSource&amp;gt;(parameterExpression)));&lt;br /&gt;&lt;br /&gt;    return Expression.Lambda&amp;lt;Func&amp;lt;TSource, bool&amp;gt;&amp;gt;(aggregateFilterExpression, parameterExpression);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;This function aggregates all the filter expressions, threading through the same parameterExpression, and builds the lambda function to call.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;This is what a complex filter expression looks like:&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggA-_dRVgHWXzgHR0U6oMCRmbeRPcbNHF6hivlWg3ewOyTaIcSanJX8Ki07dQfZl_zcTKm7ulIbBBE9RHH10GZYg98UhH7z0vtMPO2ya7ozXpQEasu97YLsqACeRYTj71caDhThy4gjkBB/s1600-h/Figure%201%5B14%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Figure 1&quot; border=&quot;0&quot; alt=&quot;Figure 1&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgm1qrnd5Me2IX2kSNIju47sMVScPIsmab1aoMbq_-vE5uL4tHRKD52PqJ3ifiZPr1HVjP3XN7MUaE6Lf5U-jZTM-RJ5OcO7YueWrHDydKoQb83CFLN8-0YM_L3HnbCmb23sjiF8kYmMd4D/?imgmax=800&quot; width=&quot;684&quot; height=&quot;160&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Clean and straightforward lambdas.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;We can now extend this approach to use conjunctions other than &lt;font face=&quot;Courier New&quot;&gt;AndAlso&lt;/font&gt;, and perhaps special-case some comparison operations.&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/1375548723194340594/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/04/lambda-wrangling-for-fun-part-3.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/1375548723194340594'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/1375548723194340594'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/04/lambda-wrangling-for-fun-part-3.html' title='Lambda Wrangling For Fun : Part 3 – Filtering Multiple Columns'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgm1qrnd5Me2IX2kSNIju47sMVScPIsmab1aoMbq_-vE5uL4tHRKD52PqJ3ifiZPr1HVjP3XN7MUaE6Lf5U-jZTM-RJ5OcO7YueWrHDydKoQb83CFLN8-0YM_L3HnbCmb23sjiF8kYmMd4D/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-1522517800950157262</id><published>2011-04-12T23:31:00.001-07:00</published><updated>2011-07-11T16:46:20.833-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Expression"/><category scheme="http://www.blogger.com/atom/ns#" term="Functional"/><category scheme="http://www.blogger.com/atom/ns#" term="Lambda"/><category scheme="http://www.blogger.com/atom/ns#" term="Languages"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><title type='text'>Lambda Wrangling For Fun : Part 2 – Filtering Single Columns</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;In the &lt;a href=&quot;http://scrumofone.blogspot.com/2011/04/lambda-wrangling-for-fun-part-1-sorting.html&quot; target=&quot;_blank&quot;&gt;previous post&lt;/a&gt;, we developed a way of dynamically generating a lambda based on a property name to pass through to the &lt;font face=&quot;Courier New&quot;&gt;OrderBy&lt;/font&gt; or &lt;font face=&quot;Courier New&quot;&gt;OrderByDescending&lt;/font&gt; LINQ function in order to sort a collection of items by the specified property.&lt;/p&gt; &lt;p&gt;We can do the same thing to dynamically generate a filter predicate to use in several LINQ extension methods that accept predicates.&lt;/p&gt; &lt;h2&gt;Anatomy of a Filter&lt;/h2&gt; &lt;p&gt;A filter predicate has three parts:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;A constant value or expression to compare against  &lt;li&gt;A comparison operator  &lt;li&gt;A target property on the object which should be compared with the constant value&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;We already know how to express property selectors – we used them here.&lt;/p&gt; &lt;p&gt;Let’s approach the rest of the problem in stages:&lt;/p&gt; &lt;h2&gt;&lt;em&gt;Ceteris paribus…&lt;/em&gt;&lt;/h2&gt; &lt;p&gt;Let’s fix the comparison operator to be the equality operator&amp;nbsp; - “ == “.&lt;/p&gt; &lt;p&gt;Then we can write a naive lambda generator thus:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static Func&amp;lt;TSource, bool&amp;gt; GetPropertyFilterLambda&amp;lt;TSource&amp;gt;(this TSource _this, string propertyName, object filterValue)&lt;br&gt;{&lt;br&gt;    // Given that propertyName = &quot;Foo&quot; and filterValue = blah&lt;br&gt;    //  we want the lambda expression * _ =&amp;gt; _.Foo == blah *&lt;br&gt;&lt;br&gt;    // This gives us the * _ =&amp;gt; * part&lt;br&gt;    var parameterExpression = Expression.Parameter(typeof (TSource), &quot;_&quot;);&lt;br&gt;&lt;br&gt;    // This gives us the * .Foo * part - see the interfaces and inheritance blog post&lt;br&gt;    var propertyInfo = typeof(TSource).GetProperty(propertyName, true);&lt;br&gt;&lt;br&gt;    // This gives us the * _.Foo * part&lt;br&gt;    var accessorExpression = Expression.Property(parameterExpression, propertyInfo);&lt;br&gt;&lt;br&gt;    // This gives us the * blah * part&lt;br&gt;    var valueExpression = Expression.Convert(Expression.Constant(filterValue), propertyInfo.PropertyType);&lt;br&gt;&lt;br&gt;    // This gives us the * _.Foo == blah * part&lt;br&gt;    var equalityComparisionExpression = Expression.Equal(accessorExpression, valueExpression);&lt;br&gt;&lt;br&gt;    // This gives us the * _ =&amp;gt; _.Foo == blah * part&lt;br&gt;    return Expression.Lambda&amp;lt;Func&amp;lt;TSource, bool&amp;gt;&amp;gt;(equalityComparisionExpression, parameterExpression).Compile();&lt;br&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;We need to incorporate the type conversion into the constant expression because it’s very likely that the constant value is a string (passed in from an ASP.NET MVC Controller, for example) while the property is an integer property.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;You’re not my Type!&lt;/h2&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;By happy coincidence, the C# language does the right thing for the equality operator on strings and compares values even though strings are a reference type. But other reference types will pose a problem since the equality operator only compares references. &lt;/p&gt;&lt;br /&gt;&lt;p&gt;So let’s strongly type the constant value:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static Func&amp;lt;TSource, bool&amp;gt; GetPropertyFilterLambda&amp;lt;TSource, TValue&amp;gt;(this TSource _this, string propertyName, TValue filterValue)&lt;br&gt;{&lt;br&gt;    // Given that propertyName = &quot;Foo&quot; and filterValue = blah&lt;br&gt;    //  we want the lambda expression * _ =&amp;gt; _.Foo == blah *&lt;br&gt;&lt;br&gt;    // This gives us the * _ =&amp;gt; * part&lt;br&gt;    var parameterExpression = Expression.Parameter(typeof (TSource), &quot;_&quot;);&lt;br&gt;&lt;br&gt;    // This gives us the * .Foo * part - see the interfaces and inheritance blog post&lt;br&gt;    var propertyInfo = typeof (TSource).GetProperty(propertyName, true);&lt;br&gt;&lt;br&gt;    // ensure the property is of the same type as the value&lt;br&gt;    if (!propertyInfo.PropertyType.IsAssignableFrom(typeof (TValue)))&lt;br&gt;    {&lt;br&gt;        throw new MemberAccessException(String.Format(&quot;Property {0}.{1} is not of type {2}&quot;,&lt;br&gt;                                                      typeof (TSource).Name,&lt;br&gt;                                                      propertyInfo.Name,&lt;br&gt;                                                      typeof (TValue).Name));&lt;br&gt;    }&lt;br&gt;&lt;br&gt;    // This gives us the * _.Foo * part&lt;br&gt;    var accessorExpression = Expression.Property(parameterExpression, propertyInfo);&lt;br&gt;&lt;br&gt;    // This gives us the * blah * part&lt;br&gt;    var valueExpression = Expression.Convert(Expression.Constant(filterValue), propertyInfo.PropertyType);&lt;br&gt;&lt;br&gt;    // This gives us the * _.Foo == blah * part&lt;br&gt;    var equalityComparisionExpression = Expression.Equal(accessorExpression, valueExpression);&lt;br&gt;&lt;br&gt;    // This gives us the * _ =&amp;gt; _.Foo == blah * part&lt;br&gt;    return Expression.Lambda&amp;lt;Func&amp;lt;TSource, bool&amp;gt;&amp;gt;(equalityComparisionExpression, parameterExpression).Compile();&lt;br&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;So far so good. &lt;/p&gt;&lt;br /&gt;&lt;h2&gt;&lt;i&gt;&lt;b&gt;sed ceteris non paribus…&lt;/b&gt;&lt;/i&gt;&lt;/h2&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;But there’s no way to specify a different operation than simple equality comparison with this. There is not even a way to do a deep equality comparison on non-string reference objects. &lt;/p&gt;&lt;br /&gt;&lt;p&gt;What we really need is a way to provide our own comparison functions, which will give us the flexibility to compare two objects and decide if they satisfy the predicate.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Here is such a function:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static Expression&amp;lt;Func&amp;lt;TSource, bool&amp;gt;&amp;gt; GetPropertyFilterLambda&amp;lt;TSource, TValue&amp;gt;(this TSource _this,&lt;br&gt;                                                                                       string propertyName,&lt;br&gt;                                                                                       TValue filterValue,&lt;br&gt;                                                                                       Func&amp;lt;TValue, TValue, bool&amp;gt; compareFunc)&lt;br&gt;{&lt;br&gt;    // Given that propertyName = &quot;Foo&quot; and filterValue = blah&lt;br&gt;    //  we want the lambda expression * _ =&amp;gt; compareFunc(_.Foo, blah) *&lt;br&gt;&lt;br&gt;    // This gives us the * _ =&amp;gt; * part&lt;br&gt;    var parameterExpression = Expression.Parameter(typeof (TSource), &quot;_&quot;);&lt;br&gt;&lt;br&gt;    // This gives us the * .Foo * part - see the interfaces and inheritance blog post&lt;br&gt;    var propertyInfo = typeof (TSource).GetProperty(propertyName, true);&lt;br&gt;&lt;br&gt;    // ensure the property is of the same type as the value&lt;br&gt;    if (!propertyInfo.PropertyType.IsAssignableFrom(typeof (TValue)))&lt;br&gt;    {&lt;br&gt;        throw new MemberAccessException(String.Format(&quot;Property {0}.{1} is not of type {2}&quot;,&lt;br&gt;                                                      typeof (TSource).Name,&lt;br&gt;                                                      propertyInfo.Name,&lt;br&gt;                                                      typeof (TValue).Name));&lt;br&gt;    }&lt;br&gt;&lt;br&gt;    // This gives us the * _.Foo * part&lt;br&gt;    var accessorExpression = Expression.Property(parameterExpression, propertyInfo);&lt;br&gt;&lt;br&gt;    // This gives us the * blah * part&lt;br&gt;    var valueExpression = Expression.Convert(Expression.Constant(filterValue), propertyInfo.PropertyType);&lt;br&gt;&lt;br&gt;    // This gives us the * compareFunc(_.Foo, blah) * part&lt;br&gt;    var compareExpression = Expression.Call(null, compareFunc.Method, accessorExpression, valueExpression);&lt;br&gt;&lt;br&gt;    // This gives us the * _ =&amp;gt; compareFunc(_.Foo, blah) * part&lt;br&gt;    return Expression.Lambda&amp;lt;Func&amp;lt;TSource, bool&amp;gt;&amp;gt;(compareExpression, parameterExpression);&lt;br&gt;}&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;which can be invoked thus:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;&amp;lt;…&amp;gt;.Where(default(IIngredient)&lt;br&gt;    .GetPropertyFilterLambda(&lt;br&gt;        &quot;Name&quot;, &lt;br&gt;        &quot;Cheese&quot;, &lt;br&gt;        (_l, _r) =&amp;gt; _l.Contains(_r)));&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;so we aren’t constrained to an equality operation any more!&lt;/p&gt;&lt;br /&gt;&lt;p&gt;We raise the stakes one more level and &lt;em&gt;&lt;a href=&quot;http://en.wikipedia.org/wiki/Currying&quot; target=&quot;_blank&quot;&gt;curry&lt;/a&gt;&lt;/em&gt; the constant into the comparison lambda thus:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static Expression&amp;lt;Func&amp;lt;TSource, bool&amp;gt;&amp;gt; GetPropertyFilterLambda&amp;lt;TSource, TValue&amp;gt;(this TSource _this,&lt;br&gt;                                                                                       string propertyName,&lt;br&gt;                                                                                       Func&amp;lt;TValue, bool&amp;gt; predicate)&lt;br&gt;{&lt;br&gt;    // Given that propertyName = &quot;Foo&quot;&lt;br&gt;    //  we want the lambda expression * _ =&amp;gt; predicate(_.Foo) *&lt;br&gt;&lt;br&gt;    // This gives us the * _ =&amp;gt; * part&lt;br&gt;    var parameterExpression = Expression.Parameter(typeof(TSource), &quot;_&quot;);&lt;br&gt;&lt;br&gt;    // This gives us the * .Foo * part - see the interfaces and inheritance blog post&lt;br&gt;    var propertyInfo = typeof(TSource).GetProperty(propertyName, true);&lt;br&gt;&lt;br&gt;    // ensure the property is of the same type as the value&lt;br&gt;    if (!propertyInfo.PropertyType.IsAssignableFrom(typeof(TValue)))&lt;br&gt;    {&lt;br&gt;        throw new MemberAccessException(String.Format(&quot;Property {0}.{1} is not of type {2}&quot;,&lt;br&gt;                                                      typeof(TSource).Name,&lt;br&gt;                                                      propertyInfo.Name,&lt;br&gt;                                                      typeof(TValue).Name));&lt;br&gt;    }&lt;br&gt;&lt;br&gt;    // This gives us the * _.Foo * part&lt;br&gt;    var accessorExpression = Expression.Property(parameterExpression, propertyInfo);&lt;br&gt;&lt;br&gt;    // This gives us the * predicate(_.Foo) * part&lt;br&gt;    var compareExpression = Expression.Call(null, predicate.Method, accessorExpression);&lt;br&gt;&lt;br&gt;    // This gives us the * _ =&amp;gt; predicate(_.Foo) * part&lt;br&gt;    return Expression.Lambda&amp;lt;Func&amp;lt;TSource, bool&amp;gt;&amp;gt;(compareExpression, parameterExpression);&lt;br&gt;}&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;which can be invoked like this:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;&amp;lt;…&amp;gt;.Where(default(IIngredient)&lt;br&gt;    .GetPropertyFilterLambda(&lt;br&gt;        &quot;Name&quot;, &lt;br&gt;        (string _l) =&amp;gt; _l.Contains(&quot;Cheese&quot;));&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Neat-o!&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/1522517800950157262/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/04/lambda-wrangling-for-fun-part.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/1522517800950157262'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/1522517800950157262'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/04/lambda-wrangling-for-fun-part.html' title='Lambda Wrangling For Fun : Part 2 – Filtering Single Columns'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-2971479691871026832</id><published>2011-04-10T17:51:00.000-07:00</published><updated>2011-07-11T16:46:20.833-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Expression"/><category scheme="http://www.blogger.com/atom/ns#" term="Functional"/><category scheme="http://www.blogger.com/atom/ns#" term="Lambda"/><category scheme="http://www.blogger.com/atom/ns#" term="Languages"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><title type='text'>Lambda Wrangling For Fun : Part 1 – Sorting Single Columns</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;No doubt that a lot of us remember the good old days when we wrote web applications with grids that had sortable columns. For those crazy old timers like myself who were writing this sort of thing before the naff ASP.NET grids came out, we remember the process to go something along these lines:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Obtain the name of the column to sort the data set on.  &lt;li&gt;Obtain the direction of the sort  &lt;li&gt;Construct the ORDER BY clause in the SELECT query to be executed to return the data sorted in the correct way.  &lt;li&gt;Execute said query and render the data set appropriately&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Setting aside all the discussion about the crudeness of the solution, one thing can be said in favour of this approach – it was simple.&lt;/p&gt; &lt;p&gt;With a more formal service-oriented approach, one constructs a method on the service for each column to be sorted on and implements the appropriate LINQ query statically. &lt;/p&gt; &lt;p&gt;(&lt;em&gt;Yes, I’m aware of Dynamic LINQ, but pretend it doesn’t exist for now.&lt;/em&gt;)&lt;/p&gt; &lt;p&gt;The object of this post is to discuss an approach with the flexibility of run-time column selection and the type-safety and inherent power of LINQ.&lt;/p&gt; &lt;h2&gt;Dissecting a Lambda&lt;/h2&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;System.Linq.Enumerable&lt;/font&gt; has a few extension methods which provide ordering semantics. Let’s consider the most commonly used one – ‘&lt;font face=&quot;Courier New&quot;&gt;OrderBy&lt;/font&gt;’. In its simplest form, it looks like this:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static System.Linq.IOrderedEnumerable OrderBy(this System.Collections.Generic.IEnumerable source, &lt;br /&gt;                                                     System.Func keySelector)&lt;br /&gt;&lt;br /&gt;    Member of System.Linq.Enumerable&lt;br /&gt;&lt;br /&gt;Summary:&lt;br /&gt;Sorts the elements of a sequence in ascending order according to a key.&lt;br /&gt;&lt;br /&gt;Type Parameters:&lt;br /&gt;TSource: The type of the elements of source.&lt;br /&gt;TKey: The type of the key returned by keySelector.&lt;br /&gt;&lt;br /&gt;Parameters:&lt;br /&gt;source: A sequence of values to order.&lt;br /&gt;keySelector: A function to extract a key from an element.&lt;br /&gt;&lt;br /&gt;Returns:&lt;br /&gt;An System.Linq.IOrderedEnumerable whose elements are sorted according to a key.&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;So this OrderBy function takes a collection of items to be sorted, and a lambda which selects a property on each item on which to sort by.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;The lambda itself specifies the type of the item (which is known because we have a strongly typed collection) and the type of the sorting property. This can be inferred if the lambda is present at compile time.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;Creating a Lambda on the fly&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;Given a property name string, we want to somehow concoct a lambda which can be given to the OrderBy function.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Here is a function which does that – analysis to follow:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static Func&amp;lt;TSource, object&amp;gt; GetPropertySelectorLambda&amp;lt;TSource&amp;gt;(this TSource _this, string propertyName)&lt;br /&gt;{&lt;br /&gt;    // Given that propertyName = &quot;Foo&quot;, we want the lambda expression * _ =&amp;gt; _.Foo *&lt;br /&gt;&lt;br /&gt;    // This gives us the * _ =&amp;gt; * part&lt;br /&gt;    var parameterExpression = Expression.Parameter(typeof(TSource), &quot;_&quot;);&lt;br /&gt;&lt;br /&gt;    // This gives us the * .Foo * part - see the interfaces and inheritance blog post&lt;br /&gt;    var propertyInfo = typeof(TSource).GetProperty(propertyName, true);&lt;br /&gt;&lt;br /&gt;    // This gives us the * _.Foo * part&lt;br /&gt;    var unboxedAccessorExpression = Expression.Property(parameterExpression, propertyInfo);&lt;br /&gt;&lt;br /&gt;    // Guid, int and other value types can&#39;t strictly be return types in expressions&lt;br /&gt;    // Why? Because &#39;object&#39; is a reference type&lt;br /&gt;    // So we convert value types to Object&lt;br /&gt;    var accessorExpression = (unboxedAccessorExpression.Type.IsValueType&lt;br /&gt;                                  ? (Expression)Expression.Convert(unboxedAccessorExpression, typeof(object))&lt;br /&gt;                                  : unboxedAccessorExpression);&lt;br /&gt;&lt;br /&gt;    // Build the lambda to the strong Func type and compile it down to a Func&lt;br /&gt;    return Expression.Lambda&amp;lt;Func&amp;lt;TSource, object&amp;gt;&amp;gt;(accessorExpression, parameterExpression).Compile();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;The Expression wrangling above is typical of functions which generate lambdas on the fly – it’s not as elegant as a truly functional language, but it works even though it’s a bit unwieldy.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;The NullReferenceException that wasn’t!&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;The eagle-eyed reader will notice that the only use of ‘&lt;font face=&quot;Courier New&quot;&gt;_this&lt;font face=&quot;Arial&quot;&gt;’ is to make the function an extension method – so that it becomes accessible in a reasonably fluent manner.&lt;/font&gt;&amp;nbsp;&lt;/font&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;What we’re really interested is in the &lt;em&gt;type&lt;/em&gt; of ‘&lt;font face=&quot;Courier New&quot;&gt;_this&lt;/font&gt;’. &lt;font face=&quot;Arial&quot;&gt;T&lt;/font&gt;he value of ‘&lt;font face=&quot;Courier New&quot;&gt;_this&lt;/font&gt;’ is never used. This means that ‘&lt;font face=&quot;Courier New&quot;&gt;_this&lt;/font&gt;’ can be null – or even more mysteriously, it can refer to something that can never exist!&lt;/p&gt;&lt;br /&gt;&lt;p&gt;So typically, as in an MVC controller, this method may be used thus:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;// GET: /T/&lt;br /&gt;public virtual ActionResult Index(string sort_column = &quot;Timestamp&quot;)&lt;br /&gt;{&lt;br /&gt;    var orders = Service.Get(null, default(TOrder).GetPropertySelectorLambda(sort_column));&lt;br /&gt;    return View(orders);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;TOrder&lt;/font&gt; could be an interface, so we use &lt;font face=&quot;Courier New&quot;&gt;default(TOrder)&lt;/font&gt; instead of &lt;font face=&quot;Courier New&quot;&gt;new(TOrder)&lt;/font&gt; as the anchor for the extension method. Now, since &lt;font face=&quot;Courier New&quot;&gt;TOrder&lt;/font&gt; is defined as a reference type, &lt;font face=&quot;Courier New&quot;&gt;default(TOrder)&lt;/font&gt; can never be anything but null, but the extension method still works very nicely!&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Cool!&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/2971479691871026832/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/04/lambda-wrangling-for-fun-part-1-sorting.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/2971479691871026832'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/2971479691871026832'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/04/lambda-wrangling-for-fun-part-1-sorting.html' title='Lambda Wrangling For Fun : Part 1 – Sorting Single Columns'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-4701598791660849889</id><published>2011-04-09T16:43:00.000-07:00</published><updated>2011-04-16T02:39:28.994-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Languages"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><category scheme="http://www.blogger.com/atom/ns#" term="Reflection"/><title type='text'>Interfaces and inheritance</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;Quite often, we would like to reflectively use properties defined on types.&lt;/p&gt; &lt;h2&gt;Basic Reflection&lt;/h2&gt; &lt;p&gt;The &lt;font face=&quot;Courier New&quot;&gt;Type&lt;/font&gt; class has a &lt;font face=&quot;Courier New&quot;&gt;GetProperties&lt;/font&gt;() method which returns all the properties on it.&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;var properties = typeof(Foo).GetProperties()&lt;/pre&gt;&lt;br /&gt;&lt;div id=&quot;codeSnippetWrapper&quot;&gt;&lt;br /&gt;&lt;div id=&quot;codeSnippet&quot; class=&quot;csharpcode&quot;&gt;&lt;pre class=&quot;alt&quot;&gt;&lt;font face=&quot;Arial&quot;&gt;Consider the following inheritance hierarchy:&lt;/font&gt;&lt;font face=&quot;Arial&quot;&gt;&lt;/pre&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;internal class Base&lt;br /&gt;{&lt;br /&gt;    public string BaseProperty { get; set; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;internal class Derived : Base&lt;br /&gt;{&lt;br /&gt;    public string DerivedProperty { get; set; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;var properties = typeof(Derived).GetProperties();&lt;/pre&gt;&lt;/font&gt;&lt;font face=&quot;Arial&quot;&gt;&lt;/font&gt;&lt;!--CRLF--&gt;&lt;/div&gt;&lt;/div&gt;&lt;br /&gt;&lt;p&gt;We expect the properties collection to have two items corresponding with BaseProperty and DerivedProperty respectively.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh-p5YTAOL2hb7yWCqtUOEdT3MxrRl6hNp1DzJcRpwf70t3w5CS1jagsrimCSvdav6c62rkCmWa0_eKOGpOvpjoZ9u_lQTSkBOYZjOfLGFrsJsQ7VbI2FgqI3yayb3rHSqWKODmjF8gbBdK/s1600-h/Figure1.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Figure1&quot; border=&quot;0&quot; alt=&quot;Figure1&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9DuXw5jCgw2yCLXxoXYxXaeHge5HDcrtP57Hw0Rru_AQv8KPpAj-8YBRmj-XR9UjZbH72BSuBdwDy1lThk4c40GbJOuqACnU8h3934qHeKMmT98hrUkmNG3qVPPFTePlquthnyR9Y-1kG/?imgmax=800&quot; width=&quot;684&quot; height=&quot;191&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;The Trouble with Interfaces&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;Now consider the following inheritance hierarchy:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;internal interface IBase&lt;br /&gt;{&lt;br /&gt;    string BaseProperty { get; set; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;internal interface IDerived : IBase&lt;br /&gt;{&lt;br /&gt;    string DerivedProperty { get; set; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;var properties = typeof(IDerived).GetProperties();&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;Do we expect anything different? Running this gives us:&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2xmwX1SmKXsf_MGhssEB1oePneJRDCx5SYlYmmRSGvDoeWQ-ePAGHkjJ374gyQ9hiQz9p6wYnENsVVlTyq5VXwoRzzSvO-MFjS4GJgDam8gu6IEu0cnA3Rgdy9A7ShTqaOnucVlr5e2Ve/s1600-h/Figure2.png&quot;&gt;&lt;img style=&quot;background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px&quot; title=&quot;Figure2&quot; border=&quot;0&quot; alt=&quot;Figure2&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgUzCDkCTBGFU5xW_1IM7fD62iXYHrzPuZiuC3Jwj65zIxSaoMySgQD0WuMXPKK-voFELZ0uQusSmtlVba6FGiBgpSDgD6aiVkgQd6LOE-q7BtpyxYJubGGfvnBeu1JF81GxaT5VWzPla59/?imgmax=800&quot; width=&quot;684&quot; height=&quot;188&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Now, there is only &lt;em&gt;one&lt;/em&gt; property: the DerivedProperty on the IDerived interface – why?&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;Legalese…&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;It turns out that this behaviour is by design, and it hinges on the way in which &lt;em&gt;inheritance&lt;/em&gt; is interpreted by the language designers.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;This is made clear in &lt;a href=&quot;http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-335.pdf&quot; target=&quot;_blank&quot;&gt;&lt;font color=&quot;#4bacc6&quot;&gt;section 8.10 of the ECMA CLI specifications&lt;/font&gt;&lt;/a&gt; where it says (&lt;strong&gt;&lt;em&gt;&lt;font style=&quot;background-color: #ff0000&quot;&gt;emphasis&lt;/font&gt;&lt;/em&gt;&lt;/strong&gt; mine): &lt;/p&gt;&lt;cite&gt;8.10 Member inheritance Only object types can inherit implementations, hence only object types can inherit members (see §8.9.8). &lt;strong&gt;&lt;font style=&quot;background-color: #ff0000&quot;&gt;While interface types can be derived from other interface types, they only “inherit” the requirement to implement method contracts, never fields or method implementations&lt;/font&gt;&lt;/strong&gt;.&lt;/cite&gt; &lt;br /&gt;&lt;p&gt;Reading through the legalese, what this means is that derived interfaces do not &lt;em&gt;contain&lt;/em&gt; their base interface properties like derived classes do – they only specify the requirement that any implementer of the interface must implement both derived and base properties.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;It’s a very fine line, but&amp;nbsp; I’m not immediately aware of why such a line exists!&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;The way out&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;We can quite easily write a little extension function to iterate over all the properties of a class, recursively including any base classes and interfaces.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;There are a few key points to notice which will be pointed out, but first, the code:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static IEnumerable&amp;lt;PropertyInfo&amp;gt; GetAllProperties(this Type _this,&lt;br /&gt;                                                         IList&amp;lt;Type&amp;gt; processedInterfaces = null,&lt;br /&gt;                                                         BindingFlags flags =&lt;br /&gt;                                                             BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)&lt;br /&gt;{&lt;br /&gt;    processedInterfaces = processedInterfaces ?? new List&amp;lt;Type&amp;gt;();&lt;br /&gt;&lt;br /&gt;    if (!processedInterfaces.Contains(_this))&lt;br /&gt;    {&lt;br /&gt;        foreach (var _pi in _this.GetProperties(flags))&lt;br /&gt;        {&lt;br /&gt;            yield return _pi;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        if (_this.BaseType != null)&lt;br /&gt;        {&lt;br /&gt;            foreach (var _pi in _this.BaseType.GetAllProperties(processedInterfaces, flags))&lt;br /&gt;            {&lt;br /&gt;                yield return _pi;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        if (_this.IsInterface)&lt;br /&gt;        {&lt;br /&gt;            foreach (var _pi in _this.GetInterfaces().SelectMany(_ =&amp;gt; _.GetAllProperties(processedInterfaces, flags)))&lt;br /&gt;            {&lt;br /&gt;                yield return _pi;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        processedInterfaces.Add(_this);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    yield break;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;The first thing to note is that we treat a single class atomically. That is to say, we consider a class to potentially have a base class and some interfaces. We recursively treat the base class &lt;em&gt;the same way&lt;/em&gt;.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;However, to prevent double-counting of the base class properties, we limit the properties considered for each class to be just those specified in the class itself.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Furthermore, multiple classes and interfaces can implement the same interface, so we keep a list of interface types that we have processed, and only process them once. This allows for complex interface hierarchies to be expressed in their simplest form. We use a default argument for this to keep the function signature as minimal as possible without sacrificing functionality.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;The last bit of elegance is to use the &lt;font face=&quot;Courier New&quot;&gt;yield&lt;/font&gt; operator to only process the enumeration at iteration time. As a bonus, this keeps the code very readable!&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Enjoy!&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/4701598791660849889/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/04/interfaces-and-inheritance.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/4701598791660849889'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/4701598791660849889'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/04/interfaces-and-inheritance.html' title='Interfaces and inheritance'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9DuXw5jCgw2yCLXxoXYxXaeHge5HDcrtP57Hw0Rru_AQv8KPpAj-8YBRmj-XR9UjZbH72BSuBdwDy1lThk4c40GbJOuqACnU8h3934qHeKMmT98hrUkmNG3qVPPFTePlquthnyR9Y-1kG/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-905440223424525318</id><published>2011-03-10T21:53:00.001-08:00</published><updated>2011-04-17T03:48:13.949-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Fun"/><category scheme="http://www.blogger.com/atom/ns#" term="Performance"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><category scheme="http://www.blogger.com/atom/ns#" term="Unsafe Code"/><title type='text'>Never leave well enough alone…until you understand what’s going on!</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;We &lt;a href=&quot;http://scrumofone.blogspot.com/2011/03/making-it-fast.html&quot;&gt;now&lt;/a&gt; have built a fast generator for predictably unique but ordered Guids.&lt;/p&gt; &lt;p&gt;Before the profiler indicated that &lt;font face=&quot;Courier New&quot;&gt;DateTime.Now.Ticks&lt;/font&gt; was quite an expensive call, I suspected the process of reversing the bytes in a 64-bit integer was too unwieldy.&lt;/p&gt; &lt;p&gt;Having addressed the Ticks counter issue, I decided to investigate the byte-reversing operation anyway. They don’t call me a geek for nuthin’!&lt;/p&gt; &lt;p&gt;This is the code I had my suspicions about:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static byte[] GetReversedBytesSlow(this Int64 value)&lt;br&gt;{&lt;br&gt;    var rgb = BitConverter.GetBytes(value);&lt;br&gt;    Array.Reverse(rgb);&lt;br&gt;&lt;br&gt;    return rgb;&lt;br&gt;}&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;You can tell that I was looking back fondly to my C/C++ days, where we could cast the integer to an array of 8 bytes and do some pointer math!&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;h2&gt;Entering ‘unsafe’ territory…&lt;/h2&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;I created a new Class Library project, and marked it as containing unsafe code.&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSTtyrTd5st6yDfdSrarmtok9tH2VY1rtmIuI5TEyWWo7LKQHbD4aKfoRwQJ1n-tKhtbdrHuJKBOjrslLILXozXyEAf6g2vvW244orpypbbWQiCbLuIObh3tvo2srZrtHv7R9ubCIv-uTg/s1600-h/UnsafeProject%5B3%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;UnsafeProject&quot; border=&quot;0&quot; alt=&quot;UnsafeProject&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhjhLZaCW-sRV4oM5-lFyiBOLll2svsLMAuze0GA7tBsXdx9N_wIdjsXzgAGaoWU9lQ7bx7fOaB6P810velArIuHu2WtlG68B8UmU7TAknehTrnYjxpApLprtyiKsyYbw9lycj6caeyTwJx/?imgmax=800&quot; width=&quot;380&quot; height=&quot;156&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Then I went at the unsafe code leaving caution to the winds:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;public static unsafe class Convert&lt;br&gt;{&lt;br&gt;    private static byte[] GetReversedBytesFor64BitValue(byte * rgb)&lt;br&gt;    {&lt;br&gt;        return new[]&lt;br&gt;               {&lt;br&gt;                   rgb[7], rgb[6], rgb[5], rgb[4], rgb[3], rgb[2], rgb[1], rgb[0]&lt;br&gt;               };&lt;br&gt;&lt;br&gt;    }&lt;br&gt;&lt;br&gt;    public static byte[] GetReversedBytes(this UInt64 _this)&lt;br&gt;    {&lt;br&gt;        return GetReversedBytesFor64BitValue((byte*)&amp;amp;_this);&lt;br&gt;    }&lt;br&gt;&lt;br&gt;    public static byte[] GetReversedBytes(this Int64 _this)&lt;br&gt;    {&lt;br&gt;        return GetReversedBytesFor64BitValue((byte*)&amp;amp;_this);&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Now, that felt really good to do &lt;img style=&quot;border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none&quot; class=&quot;wlEmoticon wlEmoticon-smile&quot; alt=&quot;Smile&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjuIqAuAXNm4xFvy65vXZd3spAO_rZTualar2PjtuybC4fVuw-yVqvtWGGtvQRhPdaIbSqPRq9LJO3GnbUe3WIrOQRMAVQGkGiV9lrtgbKZVFh2JdOiakW2j4g-2TVIeVQKIE8ABDxnDRrI/?imgmax=800&quot;&gt;&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;By hand-unrolling the pointer arithmetic, I was sure that I would definitely be faster than the general reversal algorithm that &lt;font face=&quot;Courier New&quot;&gt;Array.Reverse&lt;/font&gt; would use.&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;h2&gt;The proof of the pudding…&lt;/h2&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;First, we need to make sure we’re doing the right thing in our unsafe speed-demon. &lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;We write a test:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;private static void EnsureArraysAreIdentical(byte[] expected, byte[] actual)&lt;br&gt;{&lt;br&gt;    Assert.AreEqual(expected.Length, actual.Length);&lt;br&gt;&lt;br&gt;    for (var i=0;i&amp;lt;expected.Length; i++)&lt;br&gt;    {&lt;br&gt;        Assert.AreEqual(expected[i], actual[i]);&lt;br&gt;    }&lt;br&gt;}&lt;br&gt;&lt;br&gt;private const long TEST_MIN = -10000000L;&lt;br&gt;private const long TEST_MAX = 10000000L;&lt;br&gt;&lt;br&gt;[TestMethod]&lt;br&gt;public void TestReverseBytes64Bit()&lt;br&gt;{&lt;br&gt;    for(var l = TEST_MIN; l &amp;lt; TEST_MAX; l++)&lt;br&gt;    {&lt;br&gt;        EnsureArraysAreIdentical(GetReversedBytesSlow(l), l.GetReversedBytes());&lt;br&gt;    }&lt;br&gt;}&lt;br&gt;&lt;br&gt;&lt;/pre&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;which tests both reversal methods for identical results from –10 million to +10 million, zero inclusive.&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;The results speak for themselves:&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdYSRY94E6rgOmM0UQfikMHsm8qYMPBpISz_Xv6K62L7dqfE-8jm1y9oGtUK6elI0iHi3GJV3zyRimwZfovpbnbGZfzoO24yK6JXyW84TAIZZjLfJZ6YNlgGfpjmaKWjop5VA7mvhNCFZ6/s1600-h/UnsafeProjectTestsPassed%5B3%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;UnsafeProjectTestsPassed&quot; border=&quot;0&quot; alt=&quot;UnsafeProjectTestsPassed&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhD5cHG9IUar4eYWYt86L1xbibm32Hqbh0piNZsT5gJHY-DlJ8aLz2BTop06ZhUms06t4O3onWjYTzhD0jS0kZhVO-EBKwcrIyKtGr3ueBuwq09Ym8W7xXe6FsWEaEXiEvu1i1tak3Uxd1m/?imgmax=800&quot; width=&quot;364&quot; height=&quot;76&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Now to see if we’ve actually made any difference in the performance!&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjt9dEXrZVwQxg3zFi9etG0G0DF5MOFklQTFdt6GPdYc0MelicK7aRJDhyW2rHYqlMr_aLFWGjaXBTo1hSXXiJvIc_AFDrpxmuj-qwkz9jTOAVYvIYsqj-dgPYtZlmab6RTA_dxCFoY8jyX/s1600-h/FastByteReversal%5B5%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;FastByteReversal&quot; border=&quot;0&quot; alt=&quot;FastByteReversal&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh5evQ5i2NHFE8tVfR_tO_QqZiWxOIusO8APBTXeV0Qm9qLMGX_T2OtY_FH0jZ6i-ZCVHJWTi0T2GwY9MFGY4eeawWGTrJHspnK6GcqlQNua31AVsdDasm0rrNwpXeaE-jcl2xYkBjViTPw/?imgmax=800&quot; width=&quot;454&quot; height=&quot;56&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Nice!&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;We’ve improved the performance almost 3x – it’s just that the results only become noticeable after 20 million integer reversals!&lt;/p&gt;&lt;br&gt;&lt;br /&gt;&lt;p&gt;Now that’s what I call a productive afternoon!&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/905440223424525318/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/03/never-leave-well-enough-aloneuntil-you.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/905440223424525318'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/905440223424525318'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/03/never-leave-well-enough-aloneuntil-you.html' title='Never leave well enough alone…until you understand what’s going on!'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhjhLZaCW-sRV4oM5-lFyiBOLll2svsLMAuze0GA7tBsXdx9N_wIdjsXzgAGaoWU9lQ7bx7fOaB6P810velArIuHu2WtlG68B8UmU7TAknehTrnYjxpApLprtyiKsyYbw9lycj6caeyTwJx/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3603442416802102417.post-3197219136255848306</id><published>2011-03-10T19:46:00.001-08:00</published><updated>2011-03-10T22:12:41.703-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Ordered Guids"/><category scheme="http://www.blogger.com/atom/ns#" term="Programming"/><title type='text'>Making it fast!</title><content type='html'>&lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;In the &lt;a href=&quot;http://scrumofone.blogspot.com/2011/03/first-cut.html&quot;&gt;last post&lt;/a&gt;, I outlined a strategy to generate Guids in a strictly increasing order to address the issues outlined &lt;a href=&quot;http://scrumofone.blogspot.com/2011/03/familiar-debate.html&quot;&gt;here&lt;/a&gt;. &lt;/p&gt; &lt;p&gt;While &lt;font face=&quot;Courier New&quot;&gt;Guid.NewGuid()&lt;/font&gt; natively takes quite a bit of time to create a random Guid, it would be interesting to see if our implementation is slower, or faster – and to investigate ways to speed it up.&lt;/p&gt; &lt;p&gt;Our first run &lt;/p&gt; &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjf0SBKAw39FiGunuoVPI8f0Le-8_vtcB4rARa5GZ1SVKS_lcIsxSEJetEAu795FedrHzlHibJU1k1KassKsJYZEMBkcHttJeXu7w3VSGQ_1rMHTL6DWQzsKsGc73BZ1EKusQeXDCgTMjW/s1600-h/FirstImplementationTiming%5B3%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;FirstImplementationTiming&quot; border=&quot;0&quot; alt=&quot;FirstImplementationTiming&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg6_N24GdEyeKgX3h_NIRZY2AuXeQ0xQvXz3_qTqax67HGfdbg0sj5y6Eb1QR_M-EbVh3aLJxfkx_CzlTTIoQgEs1_ZrNT5v-E3AnoTNBCKis5a2WlVmNwf_Pg3R04bsDLyEZBHGS12QTfE/?imgmax=800&quot; width=&quot;364&quot; height=&quot;78&quot;&gt;&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Hmm.. that seems to be pretty good – but inspecting the code should point a steady finger at the &lt;font face=&quot;Courier New&quot;&gt;Thread.Sleep(1)&lt;/font&gt; call. So how does one make the sequence increase, without the &lt;font face=&quot;Courier New&quot;&gt;Sleep()&lt;/font&gt; call.&lt;/p&gt; &lt;h2&gt;Enter Interlocked.Increment()&lt;/h2&gt; &lt;p&gt;A strategy to ensure monotonically increasing numbers would be to initialize a counter with &lt;font face=&quot;Courier New&quot;&gt;DateTime.Now.Ticks&lt;/font&gt;, and then in the generation method, to increment it in a thread-safe manner – thus:&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;private static long _counter;&lt;br&gt;&lt;br&gt;public static Guid NewSequentialGuid()&lt;br&gt;{&lt;br&gt;    lock (LockObject)&lt;br&gt;    {&lt;br&gt;        Interlocked.CompareExchange(ref _counter, DateTime.Now.Ticks, 0);&lt;br&gt;        Interlocked.Increment(ref _counter);&lt;br&gt;&lt;br&gt;        var rgb = BitConverter.GetBytes(_counter);&lt;br&gt;        Array.Reverse(rgb);&lt;br&gt;&lt;br&gt;        return new Guid(_a, _b, _c, rgb);&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;The tests continue to pass, assuring us that&amp;nbsp; the Guids are still unique. Measuring the performance, we get:&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUWPrQRj2mSuvqsxcVOt_uhehz7t7vG2SI_jQ93wPCrHGchDecRyyT0I-8q59BU8D00_iKMQ9LJQd3Y5AAETEsManOvTVQb92UAYwdrUhm5cDF9WzL6lQmype3copB6CHsLS0wCCIpSgfp/s1600-h/InterlockedSlowTiming%5B4%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;InterlockedSlowTiming&quot; border=&quot;0&quot; alt=&quot;InterlockedSlowTiming&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiemh4MAwxtTtOrpo2QE6JOWUrkYDWnxxSow4PXNW6bBDCZ07eL69wnCu6dgF5rHCcULMK1gowwCgeioxb-Rfquo6JOBGE0AoND8vOyV99yUl0dWQSPfFa3L-bt-7WxVhWr-leIm1BWJMg/?imgmax=800&quot; width=&quot;364&quot; height=&quot;76&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Much better – we’ve made things around&amp;nbsp; twice as fast. I would leave things as they are now – except I’m quite curious to see if I can extract some more performance out of it.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;The importance of profiling&lt;/h2&gt;&lt;br /&gt;&lt;p&gt;We have only five lines of code there – where do we start speeding things up?&lt;/p&gt;&lt;br /&gt;&lt;p&gt;The best way to find out would be to fire up the profiler in Visual Studio 2010 and run the program in there. That points us to:&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhsX1IrIUwvPA2-aaPEXGkc0WM5_e5Ooxz7IJnEBYJDpyA0kpABeCeApEBH8gKZcBozHQE__2P3LnH3MG7QvDO7dhzk-T8LJGHcFcXhHXq_Oi-Wu9LY3ZvTJBDNdH7qzTre25J9-C2R0Ylf/s1600-h/InterlockedSlowProfiling%5B3%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;InterlockedSlowProfiling&quot; border=&quot;0&quot; alt=&quot;InterlockedSlowProfiling&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhcLdP2BBrIZ3k8sG3mY2kW4E-eGagooT3EK-qeTco-PVcJuDkgdMSefIk71ccv6P1WM3ADTCZ8cWlPUqkhjr_oRgequ9WDCENGuS-D5XVq59BphfZmFH0WVkwGg1XUzJ8ILaUBLioC77SZ/?imgmax=800&quot; width=&quot;364&quot; height=&quot;79&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Hmm… looks like we’re spending most of our time getting the &lt;font face=&quot;Courier New&quot;&gt;Ticks&lt;/font&gt; count, even if we never use it more than once – definitely wasteful.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Why don’t we cache the &lt;font face=&quot;Courier New&quot;&gt;Ticks&lt;/font&gt; count once, and just use the &lt;font face=&quot;Courier New&quot;&gt;Interlocked.Increment&lt;/font&gt; call to make it unique?&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;private static long _counter = DateTime.Now.Ticks;&lt;br&gt;&lt;br&gt;public static Guid NewSequentialGuid()&lt;br&gt;{&lt;br&gt;    lock (LockObject)&lt;br&gt;    {&lt;br&gt;        Interlocked.Increment(ref _counter);&lt;br&gt;&lt;br&gt;        var rgb = BitConverter.GetBytes(_counter);&lt;br&gt;        Array.Reverse(rgb);&lt;br&gt;&lt;br&gt;        return new Guid(_a, _b, _c, rgb);&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;That results in&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj19GP1JXd1GUHyxfKvoKaNjZIOr1tN8P3xAwWa0Fm9oUTIE-kttW9aNzE7AxYSWDaq-jVBcgw7mS_zdFwNvu2oqXUMo0m3Wthc82TcXOIv5hOkZS_4SUElacxqyd8mLKc0FRh-4Gex09Iw/s1600-h/InterlockedFastTiming%5B3%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;InterlockedFastTiming&quot; border=&quot;0&quot; alt=&quot;InterlockedFastTiming&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhzSzBlIJBuL4Wa7E96WhD_clyVpu2pUuVeoZeQdbrUeBWJjerFJ4zaKCoZrnB8DVM206GtbQxxdJLRn912Xl1EyxWRwa5GDT6QEC2FQpOe__md00eP3YVy0-O8cEiHXt7efX55t98PP9JJ/?imgmax=800&quot; width=&quot;364&quot; height=&quot;79&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;Pretty good. So let’s look at a sequence of Guids created 50ms apart.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEifwGKby54jYqjy_7-595-98Ea3Cv3HsTBX1LVHpHnJLBlFtd5IBs3Aked_QHJ-WRnZ3RnVgD6Cnqn_6siS0MLdwQzMCBd7W2k4h0-4iX6GmntSz5eYBWiF8l-TCajf96jP1Lis-eTKWIok/s1600-h/InterlockedFastGuids%5B3%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;InterlockedFastGuids&quot; border=&quot;0&quot; alt=&quot;InterlockedFastGuids&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8IiIi2cDz9Byv8kD0J7bG-H8eCxDU7krhMeojd3s1hiN0omaXUzskKDATNkMe5k7YV_PEi88vcW05mIIzwxIjpUsdFOLYHinIotNZjEkEhbMGHYRkkLHCKioo2KfBRDmnz-25uE-ZiHrN/?imgmax=800&quot; width=&quot;364&quot; height=&quot;222&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;The implication of this is that every time the OrderedGuid class is initialized, the _counter would get set, and thereafter it would be a simple incremented sequence – even though there was a time delay of 50ms between each Guid being created. &lt;/p&gt;&lt;br /&gt;&lt;p&gt;If we wanted the creation of the Guid to be more ‘random’ and be more closely tied to the &lt;font face=&quot;Courier New&quot;&gt;Ticks&lt;/font&gt; count, we could keep the &lt;font face=&quot;Courier New&quot;&gt;_counter&lt;/font&gt; refreshed every so often with a &lt;font face=&quot;Courier New&quot;&gt;Timer&lt;/font&gt;.&lt;/p&gt;&lt;pre class=&quot;brush: csharp;&quot;&gt;private static readonly Timer Timer = new Timer(ResetCounter, null, 0, 100);&lt;br&gt;&lt;br&gt;private static void ResetCounter(object arg = null)&lt;br&gt;{&lt;br&gt;    lock (LockObject)&lt;br&gt;    {&lt;br&gt;        _counter = DateTime.Now.Ticks;&lt;br&gt;    }&lt;br&gt;}&lt;br&gt;&lt;br&gt;static OrderedGuid()&lt;br&gt;{&lt;br&gt;    lock (LockObject)&lt;br&gt;    {&lt;br&gt;        ResetCounter();&lt;br&gt;    }&lt;br&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;This would keep the _counter up to date reasonably frequently.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEip7LeQbQfGOdhZ97d1VuSpgMXgqscM4OeZLvmAdTVG1bXOLyMdSbMVDGpGJhuMvvghBcNtSctoCXI64RBiWDLvpSKn3kDGqMGLr09-pAAONf0tIcY1QSUZ81GLZCl6Gd-LYuOqRxW7ijgl/s1600-h/InterlockedFastGuidsTimer%5B3%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;InterlockedFastGuidsTimer&quot; border=&quot;0&quot; alt=&quot;InterlockedFastGuidsTimer&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqsYVtKJ_5D2DH8k59W8F4DQhN-VKHTNihtLFQFEnAqu8o5IlSKxp89IofrS3zq65IpmJAGG3SE3gi6MeMwKqBFjYd9O5woiRjxrXfkXFjPzNXCD5edu8D2S9UaeYKfjn2tn_iUEdgXvTI/?imgmax=800&quot; width=&quot;364&quot; height=&quot;227&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;As you can see, we have a good somewhat random distribution between Guids created 50ms apart.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiBibBmb8QjdRUj8pUtgbf8Wyh1KjKPelVlVd2NLzE8f9rwVsYqfuc7Ruh9MFJnoRbJJk9q9hWeqa6wDS4yOkgZN1XKtA3tjPkuNUE1KvWvY3oQedQfWL47tiP65LiGWeRpPPB1LjNDnngT/s1600-h/InterlockedFastGuidsTimerTiming%5B3%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;InterlockedFastGuidsTimerTiming&quot; border=&quot;0&quot; alt=&quot;InterlockedFastGuidsTimerTiming&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiDg8tmNh10MIB_X-j6kGH9ZXk64iV5uarBsVikod-Ikt3STMnBaWzOfB41RFR-IxK_DzOZ9tDorYllwikIklNdvwAoXrN4Nyeoi-mrFiuDmwZsC3gQSuspmzOBGc3LiKVSr5edqLBdUy1n/?imgmax=800&quot; width=&quot;364&quot; height=&quot;84&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;We’ve done this without appreciably slowing things down – given the coarse granularity of the tick-counting approach to timing, all we can say is that we haven’t made things &lt;em&gt;very&lt;/em&gt; much different by introducing the timer.&lt;/p&gt;&lt;br /&gt;&lt;p&gt;And now we have a viable, fast way of generating predictably-unique, ordered Guids.&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://scrumofone.blogspot.com/feeds/3197219136255848306/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://scrumofone.blogspot.com/2011/03/making-it-fast.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/3197219136255848306'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3603442416802102417/posts/default/3197219136255848306'/><link rel='alternate' type='text/html' href='http://scrumofone.blogspot.com/2011/03/making-it-fast.html' title='Making it fast!'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/15003030360576324824</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg6_N24GdEyeKgX3h_NIRZY2AuXeQ0xQvXz3_qTqax67HGfdbg0sj5y6Eb1QR_M-EbVh3aLJxfkx_CzlTTIoQgEs1_ZrNT5v-E3AnoTNBCKis5a2WlVmNwf_Pg3R04bsDLyEZBHGS12QTfE/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></entry></feed>