<?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: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-348115887378115761</id><updated>2011-11-07T10:28:38.118-06:00</updated><category term='Introduction'/><category term='PostSharp'/><category term='Data Access'/><category term='SharpMock'/><category term='Rhino Mocks'/><category term='ASP.NET MVC'/><title type='text'>Continuous Disintegration</title><subtitle type='html'>A blog about .NET development and pulling your hair out.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>25</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-3170363044518736059</id><published>2011-09-20T18:21:00.001-05:00</published><updated>2011-09-20T18:21:26.639-05:00</updated><title type='text'>SQL Server Service Broker Guidance</title><content type='html'>Don't use it.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-3170363044518736059?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/3170363044518736059/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=3170363044518736059' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3170363044518736059'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3170363044518736059'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2011/09/sql-server-service-broker-guidance.html' title='SQL Server Service Broker Guidance'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-3408997194408776170</id><published>2011-08-30T19:07:00.000-05:00</published><updated>2011-08-30T19:07:18.785-05:00</updated><title type='text'>Exception Handling? WTF??</title><content type='html'>&lt;p&gt;A recent &lt;a href="http://thedailywtf.com/Comments/The-Rockstars-Guard.aspx"&gt;Daily WTF&lt;/a&gt; explored a &lt;b&gt;Guard&lt;/b&gt; class which throws an &lt;b&gt;ArgumentNullException&lt;/b&gt; if a parameter is null. Most of the commenters correctly point out that the code is not a WTF but rather a good practice because it&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Enforces the code contract - this parameter is not allowed to be null&lt;/li&gt;&lt;li&gt;Provides better stack trace information&lt;/li&gt;&lt;li&gt;Causes the app to &lt;a href="http://en.wikipedia.org/wiki/Fail-fast"&gt;fail fast&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/p&gt;&lt;p&gt;One principle at work here is the idea of &lt;i&gt;adding information&lt;/i&gt; to an exception. Without guarding against potentially invalid input in this situation, a &lt;b&gt;NullReferenceException&lt;/b&gt; will (presumably) be thrown at some point. But why? What's null? What &lt;i&gt;made&lt;/i&gt; it null? Even with the stack trace, this can be painful to debug... annoying at the least. An &lt;b&gt;ArgumentNullException&lt;/b&gt; cuts straight to the problem and tells us exactly what is wrong. Anytime you can add information to an exception (or potential exception in this case), &lt;i&gt;you should do it*&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;I think this is a good principle to follow when deciding whether or not to catch an exception (that you can't recover from) as well. If you can add information by wrapping it in a more specific exception and adding contextual information, you should do so. Otherwise, there's no need to handle and re-throw.&lt;/p&gt;&lt;p&gt;&lt;small&gt;*Well, not if might expose implementation details you want to hide from users.&lt;/small&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-3408997194408776170?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/3408997194408776170/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=3408997194408776170' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3408997194408776170'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3408997194408776170'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2011/08/exception-handling-wtf.html' title='Exception Handling? WTF??'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-8375353989020332284</id><published>2011-08-27T19:49:00.000-05:00</published><updated>2011-08-27T19:49:23.902-05:00</updated><title type='text'>Considerations for Multi-Client Applications</title><content type='html'>&lt;p&gt;Often when dealing with applications/systems that serve multiple clients, we encounter a situation where&lt;br /&gt;&lt;ul&gt;    &lt;li&gt;Clients share some core functionality and algorithms&lt;/li&gt;    &lt;li&gt;Clients have custom logic that extends the core functionality&lt;/li&gt;    &lt;li&gt;Clients have customized data structures that extend core data structures&lt;/li&gt;&lt;/ul&gt;The key to making this work in a maintainable way (that is, without infusing the code with crazy branching statements or writing the whole application in dynamic SQL) is maintaining a distinct separation between core and client.&lt;br /&gt;&lt;/p&gt;&lt;p&gt;&lt;a href="https://github.com/jamarchist/MultiTenancy"&gt;Here&lt;/a&gt; I present components from a simple, hypothetical application that demonstrates such a separation. The application is meant to evaluate whether or not a client should acquire a player for fantasy football. It contains some core functionality for doing the evaluation (it doesn't pick up a player who has never scored a point) and a core data structure that represents a player. There are two clients who extend this core functionality: me and a stupid opponent in my league. The stupid opponent is a Bears fan who only picks up Bears players. I am a player who uses some trivial evaluation strategy and also extends the core data structure with some data that represents my own opinion.&lt;/p&gt;&lt;p&gt;The code shows an example of how to define and extend core functionality. It does &lt;b&gt;not&lt;/b&gt; show how to wire everything together (dependency injection) or how to persist custom data. I may explore these topics in future posts. Also note that I called the code repository '&lt;a href="http://en.wikipedia.org/wiki/Multitenancy"&gt;MultiTenancy&lt;/a&gt;', but this is more likely something you'll find in multi-instance scenario. I'm using the term 'multi-client' to represent both possibilities.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-8375353989020332284?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/8375353989020332284/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=8375353989020332284' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/8375353989020332284'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/8375353989020332284'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2011/08/considerations-for-multi-client.html' title='Considerations for Multi-Client Applications'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-2305353372302671176</id><published>2011-08-15T17:12:00.000-05:00</published><updated>2011-08-15T17:12:06.742-05:00</updated><title type='text'>Duck Typing with Anonymous Types - Part 3</title><content type='html'>&lt;p&gt;Continuing my &lt;a href="http://jamesryangray.blogspot.com/2011/08/duck-typing-with-anonymous-types.html"&gt;short&lt;/a&gt; &lt;a href="http://jamesryangray.blogspot.com/2011/08/duck-typing-with-anonymous-types-part-2.html"&gt;series&lt;/a&gt;, it's time to add some polish to what we have so far.&lt;/p&gt;&lt;h2&gt;Overload Resolution&lt;/h2&gt;&lt;p&gt;At first I thought overload resolution was going to be a huge pain, but really the compiler does everything for us. As long as we have assigned an implementation with exactly matching parameters for the method that the compiler calls, we're good to go. The necessary modifications to the interceptor fit into a small reflection utility method.&lt;/p&gt;&lt;pre class="brush: csharp"&gt;private Delegate GetMethod(IInvocation invocation)&lt;br /&gt;{&lt;br /&gt;    var methodProperty = anonymous.GetPropertyValue(invocation.Method.Name);&lt;br /&gt;    if (methodProperty is Delegate)&lt;br /&gt;    {&lt;br /&gt;        return methodProperty as Delegate;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    var overloads = methodProperty as Delegate[];&lt;br /&gt;    return overloads.Where(m =&gt; m.Method.SignatureMatches(invocation.Method)).First();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;pre class="brush: csharp"&gt;internal static bool SignatureMatches(this MethodInfo method, MethodInfo other)&lt;br /&gt;{&lt;br /&gt;    var theseParameters = method.GetParameters();&lt;br /&gt;    var thoseParameters = other.GetParameters();&lt;br /&gt;&lt;br /&gt;    if (theseParameters.Count() != thoseParameters.Count())&lt;br /&gt;    {&lt;br /&gt;        return false;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    foreach (var parameter in theseParameters)&lt;br /&gt;    {&lt;br /&gt;        var parameterIndex = Array.IndexOf(theseParameters, parameter);&lt;br /&gt;        if (!parameter.ParameterType.Equals(thoseParameters[parameterIndex].ParameterType))&lt;br /&gt;        {&lt;br /&gt;            return false;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return true;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Here is the modified &lt;b&gt;IDuck&lt;/b&gt; interface and corresponding test (note that by explicitly declaring &lt;i&gt;brains&lt;/i&gt; as an &lt;b&gt;object&lt;/b&gt;, the compiler will emit code that calls the overload with &lt;b&gt;object&lt;/b&gt; parameter(s)):&lt;/p&gt;&lt;pre class="brush: csharp"&gt;public interface IDuck&lt;br /&gt;{&lt;br /&gt;    string Color { get; set; }&lt;br /&gt;    Direction Fly();&lt;br /&gt;    Direction Fly(Direction direction);&lt;br /&gt;    string Quack();&lt;br /&gt;    string Quack(int times);&lt;br /&gt;    string Quack(string sound);&lt;br /&gt;    string Quack(object sound);&lt;br /&gt;    string Quack(params object[] sounds);&lt;br /&gt;    object this[string attribute] { get; set; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;pre class="brush: csharp"&gt;[Test]&lt;br /&gt;public void CanInvokeOverloadedMethodsWithSomewhatAmbiguousSignatures()&lt;br /&gt;{&lt;br /&gt;    var zombie = new&lt;br /&gt;    {&lt;br /&gt;        Quack = new Delegate[]&lt;br /&gt;        {&lt;br /&gt;            (Func&amp;lt;int, string&gt;)(i =&gt; String.Format("{0} BRAAAINS!", i)),&lt;br /&gt;            (Func&amp;lt;string, string&gt;)(s =&gt; String.Format("{0} BRAAAINS!", s)),&lt;br /&gt;            (Func&amp;lt;object, string&gt;)(o =&gt; String.Format("{0}", o)),&lt;br /&gt;            (Func&amp;lt;object[], string&gt;)(o =&gt; String.Format("{0} BRAAAIN OBJECTS!", o.Count()))&lt;br /&gt;        }&lt;br /&gt;    }.As&amp;lt;IDuck&amp;gt;();&lt;br /&gt;&lt;br /&gt;    object brains = "BRAAAINS!";&lt;br /&gt;&lt;br /&gt;    Assert.That("10 BRAAAINS!" == zombie.Quack(10));&lt;br /&gt;    Assert.That("EAT BRAAAINS!" == zombie.Quack("EAT"));&lt;br /&gt;    Assert.That("BRAAAINS!" == zombie.Quack(brains));&lt;br /&gt;    Assert.That("3 BRAAAIN OBJECTS!" == zombie.Quack(brains, brains, brains));&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;h2&gt;Indexed Properties&lt;/h2&gt;&lt;p&gt;I'm not going to go through all the changes I had to make to support an indexed property, but it wasn't very complicated. Basically, if we give our anonymous type a property named &lt;b&gt;Item&lt;/b&gt;, it will correspond to an index on an interface (because an indexer is just syntactic sugar around an &lt;b&gt;Item&lt;/b&gt; property). This property should be a &lt;b&gt;Delegate[]&lt;/b&gt; with a method for the getter and/or setter (depending on the interface contract). The setter won't automatically store values unless we implement it that way. Here are some examples:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;[Test]&lt;br /&gt;public void CanInvokeIndexGetter()&lt;br /&gt;{&lt;br /&gt;    var buckshot = new object();&lt;br /&gt;&lt;br /&gt;    var duck = new&lt;br /&gt;    {&lt;br /&gt;        Item = new Delegate[]&lt;br /&gt;        {&lt;br /&gt;            (Func&amp;lt;string, object&gt;)(s =&gt; buckshot)&lt;br /&gt;        }                     &lt;br /&gt;    }.As&amp;lt;IDuck&gt;();&lt;br /&gt;&lt;br /&gt;    Assert.AreSame(buckshot, duck["weakness"]);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Test]&lt;br /&gt;public void CanInvokeIndexSetter()&lt;br /&gt;{&lt;br /&gt;    var isInfected = false;&lt;br /&gt;    var duck = new&lt;br /&gt;    {&lt;br /&gt;        Item = new Delegate[]&lt;br /&gt;        {&lt;br /&gt;            (Action&amp;lt;string, object&gt;)((key,value) =&gt; isInfected = true)               &lt;br /&gt;        }   &lt;br /&gt;    }.As&amp;lt;IDuck&gt;();&lt;br /&gt;&lt;br /&gt;    duck["disease"] = "bird flu";&lt;br /&gt;    Assert.IsTrue(isInfected);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Test]&lt;br /&gt;public void CanStoreAndRetrieveWithIndexedProperty()&lt;br /&gt;{&lt;br /&gt;    var store = new Dictionary&amp;lt;string, object&gt;();&lt;br /&gt;    var duck = new&lt;br /&gt;    {&lt;br /&gt;        Item = new Delegate[]&lt;br /&gt;        {&lt;br /&gt;            (Func&amp;lt;string, object&gt;)(s =&gt; store[s]),&lt;br /&gt;            (Action&amp;lt;string, object&gt;)((s,o) =&gt; store[s] = o)&lt;br /&gt;        }&lt;br /&gt;    }.As&amp;lt;IDuck&gt;();&lt;br /&gt;&lt;br /&gt;    var feathers = new object();&lt;br /&gt;    duck["feathers"] = feathers;&lt;br /&gt;            &lt;br /&gt;    Assert.AreSame(feathers, duck["feathers"]);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;h2&gt;Duck Typing Plain Objects&lt;/h2&gt;&lt;p&gt;A few fairly simple modifications, and we can support duck typing objects that &lt;i&gt;aren't&lt;/i&gt; anonymous types.&lt;/p&gt;&lt;pre class="brush: csharp"&gt;public class ScroogeMcDuck&lt;br /&gt;{&lt;br /&gt;    public string Quack()&lt;br /&gt;    {&lt;br /&gt;        return "Bah! Humbug!";&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Test]&lt;br /&gt;public void CanInvokeMethod()&lt;br /&gt;{&lt;br /&gt;    var scrooge = new ScroogeMcDuck().As&amp;lt;IDuck&gt;();&lt;br /&gt;&lt;br /&gt;    Assert.That("Bah! Humbug!" == scrooge.Quack());&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;h2&gt;Syntax&lt;/h2&gt;&lt;p&gt;Casting the function/action type of the method can look kind of ugly, so I made a utility class that we can pass anonymous methods through to return &lt;b&gt;Delegate&lt;/b&gt;s. We still have to specify parameter types, so it's still pretty crusty, but it's there if we want to use it.&lt;/p&gt;&lt;pre class="brush:csharp"&gt;var duck = new&lt;br /&gt;{&lt;br /&gt;    Quack = Anon.Methods&lt;br /&gt;    (&lt;br /&gt;        Anon.Method(() =&gt; "Quack!"),&lt;br /&gt;        Anon.Method&amp;lt;int, string&gt;(i =&gt; String.Format("{0} quacks!", i))&lt;br /&gt;    )&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;h2&gt;Conclusion&lt;/h2&gt;&lt;p&gt;This is a somewhat serviceable solution for ducktyping adaptation of legacy code or quick mocking, especially of data. We haven't made any special considerations for generics, so it may fail in those scenarios. Named parameters will almost certainly cause problems, and we haven't done any performance tuning. I should also note that I used &lt;a href="http://bugsquash.blogspot.com/2009/05/duck-typing-with-castle-dynamicproxy.html"&gt;this post by Mauricio Scheffer&lt;/a&gt; as a resource when researching how to begin. The code can be found &lt;a href="https://github.com/jamarchist/DuckTyping"&gt;here on github&lt;/a&gt;.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-2305353372302671176?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/2305353372302671176/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=2305353372302671176' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/2305353372302671176'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/2305353372302671176'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2011/08/duck-typing-with-anonymous-types-part-3.html' title='Duck Typing with Anonymous Types - Part 3'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-6639868438443495921</id><published>2011-08-12T15:29:00.000-05:00</published><updated>2011-08-12T15:29:59.107-05:00</updated><title type='text'>Duck Typing with Anonymous Types - Part 2</title><content type='html'>&lt;p&gt;&lt;a href="http://jamesryangray.blogspot.com/2011/08/duck-typing-with-anonymous-types.html"&gt;Previously&lt;/a&gt; I looked at forwarding property calls of an interface to those of an anonymous type instance. Now I'd like to see if we can forward method calls as well. But how? We can't create an anonymous type instance with methods, and we can't assign assign anonymous methods as properties. This doesn't work:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;var duck = new&lt;br /&gt;{&lt;br /&gt;    Color = "white",&lt;br /&gt;    Quack = () =&gt; "Quack!"&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;but this does:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;[Test]&lt;br /&gt;public void CanInvokeMethod()&lt;br /&gt;{&lt;br /&gt;    var duck = new&lt;br /&gt;    {&lt;br /&gt;        Color = "white",&lt;br /&gt;        Quack = (Func&amp;lt;string&amp;gt;)(() =&gt; "Quack!")&lt;br /&gt;    };&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Let's modify our interceptor once again, this time to retrieve a delegate property named the same as the invoked method and invoke it.&lt;/p&gt;&lt;pre class="brush: csharp"&gt;internal class DuckTypingInterceptor : IInterceptor&lt;br /&gt;{&lt;br /&gt;    [... snip ...]&lt;br /&gt;&lt;br /&gt;    public void Intercept(IInvocation invocation)&lt;br /&gt;    {&lt;br /&gt;        [... snip ...]&lt;br /&gt;&lt;br /&gt;        if (invocation.IsMethodCall())&lt;br /&gt;        {&lt;br /&gt;            var method = GetMethod(invocation.Method.Name);&lt;br /&gt;            invocation.ReturnValue = method.DynamicInvoke(invocation.Arguments);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    [... snip ...]&lt;br /&gt;&lt;br /&gt;    private Delegate GetMethod(string name)&lt;br /&gt;    {&lt;br /&gt;        return anonymous.GetPropertyValue(name) as Delegate;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;pre class="brush: csharp"&gt;[Test]&lt;br /&gt;public void CanInvokeMethod()&lt;br /&gt;{&lt;br /&gt;    var duck = new&lt;br /&gt;    {&lt;br /&gt;        Color = "white",&lt;br /&gt;        Quack = (Func&amp;lt;string&amp;gt;)(() =&gt; "Quack!")&lt;br /&gt;    };&lt;br /&gt;&lt;br /&gt;    var typedDuck = duck.As&amp;lt;IDuck&amp;gt;();&lt;br /&gt;&lt;br /&gt;    Assert.That("Quack!" == typedDuck.Quack());&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;It works! Now... what about overloads? This is a bit trickier. We can start by deciding that overloads will be stored as an array of &lt;b&gt;System.Delegate&lt;/b&gt;s.&lt;/p&gt;&lt;pre class="brush: csharp"&gt;[Test]&lt;br /&gt;public void CanInvokeOverloadedMethods()&lt;br /&gt;{&lt;br /&gt;    var launchPad = new&lt;br /&gt;    {&lt;br /&gt;        Fly = new Delegate[]&lt;br /&gt;        {&lt;br /&gt;            (Func&amp;lt;Direction&amp;gt;)(() =&gt; Direction.West),&lt;br /&gt;            (Func&amp;lt;Direction, Direction&amp;gt;)(d =&gt; d)&lt;br /&gt;        }&lt;br /&gt;    };&lt;br /&gt;&lt;br /&gt;    var launchPadMcQuack = launchPad.As&amp;lt;IDuck&amp;gt;();&lt;br /&gt;&lt;br /&gt;    Assert.That(Direction.West == launchPadMcQuack.Fly());&lt;br /&gt;    Assert.That(Direction.South == launchPadMcQuack.Fly(Direction.South));&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;A modified &lt;b&gt;GetMethod&lt;/b&gt; method in our interceptor allows the test to pass.&lt;/p&gt;&lt;pre class="brush: csharp"&gt;private Delegate GetMethod(IInvocation invocation)&lt;br /&gt;{&lt;br /&gt;    var methodProperty = anonymous.GetPropertyValue(invocation.Method.Name);&lt;br /&gt;    if (methodProperty is Delegate)&lt;br /&gt;    {&lt;br /&gt;        return methodProperty as Delegate;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    var overloads = methodProperty as Delegate[];&lt;br /&gt;    return overloads.Where(&lt;br /&gt;        m =&gt; m.Method.GetParameters().Count() == invocation.Arguments.Count()).First();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;This is obviously a naive implementation - overload resolution is extremely difficult. This will fail for overloads with the same number of parameters differentiated by type, methods with the &lt;b&gt;params&lt;/b&gt; keyword, and methods with &lt;b&gt;out&lt;/b&gt;/&lt;b&gt;ref&lt;/b&gt; parameters. For now, though, we have something that will work well for very simple interfaces. In my final post, I'll try to make the overload resolution a little smarter and handle one other scenario I haven't talked about - indexed properties.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-6639868438443495921?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/6639868438443495921/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=6639868438443495921' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/6639868438443495921'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/6639868438443495921'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2011/08/duck-typing-with-anonymous-types-part-2.html' title='Duck Typing with Anonymous Types - Part 2'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-8705342701033656979</id><published>2011-08-12T12:01:00.000-05:00</published><updated>2011-08-12T12:01:59.950-05:00</updated><title type='text'>Duck Typing with Anonymous Types</title><content type='html'>&lt;p&gt;If you can create an &lt;a href="http://msdn.microsoft.com/en-us/library/0yw3tz5k%28v=vs.80%29.aspx"&gt;anonymous method&lt;/a&gt; and an &lt;a href="http://msdn.microsoft.com/en-us/library/bb397696.aspx"&gt;anonymous type&lt;/a&gt;, why not an 'anonymous class'? Wouldn't it be nice to be able to plug properties and methods into and object and then &lt;i&gt;consume that object like any other class or interface&lt;/i&gt;?&lt;/p&gt;&lt;p&gt;What we're talking about is essentially &lt;a href="http://en.wikipedia.org/wiki/Duck_typing"&gt;duck typing&lt;/a&gt; (with strongly-typed ducks). There are examples all over of how to do this, especially with Castle Dynamic Proxy. This is my implementation of the same.&lt;/p&gt;&lt;p&gt;First let's look at a test:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;public interface IDuck&lt;br /&gt;{&lt;br /&gt;    string Color { get; }&lt;br /&gt;    Direction Fly();&lt;br /&gt;    Direction Fly(Direction direction);&lt;br /&gt;    string Quack();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Test]&lt;br /&gt;public void CanStubColorProperty()&lt;br /&gt;{&lt;br /&gt;    var rubberDuck = new { Color = "yellow" };&lt;br /&gt;    var typedRubberDuck = rubberDuck.As&amp;lt;IDuck&amp;gt;();&lt;br /&gt;&lt;br /&gt;    Assert.That(typedRubberDuck.Color == "yellow");&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;That &lt;b&gt;As&amp;lt;IDuck&amp;gt;&lt;/b&gt; part is an extension method that does nothing right now, so this test will fail. What we want that extensions method to do is to return a proxy that implements the &lt;b&gt;IDuck&lt;/b&gt; interface and forwards the method/property calls on to our anonymous type instance. Using Castle Dynamic Proxy, we can start creating this:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;internal class DuckTypingInterceptor : IInterceptor&lt;br /&gt;{&lt;br /&gt;    private readonly object anonymous;&lt;br /&gt;&lt;br /&gt;    public DuckTypingInterceptor(object anonymous)&lt;br /&gt;    {&lt;br /&gt;        this.anonymous = anonymous;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void Intercept(IInvocation invocation)&lt;br /&gt;    {&lt;br /&gt;        if (invocation.IsGetter())&lt;br /&gt;        {&lt;br /&gt;            var property = invocation.PropertyName();&lt;br /&gt;            invocation.ReturnValue = anonymous.GetPropertyValue(property);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;There are some extension methods in there to help with reading method names and reflection, but it's pretty simple - when someone tries to get a property value from the proxy, we give back the value of the property on the anonymous object. Now we can implement that &lt;b&gt;As&amp;lt;TDuck&amp;gt;&lt;/b&gt; extensions method:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;public static TDuck As&amp;lt;TDuck&amp;gt;(this object anonymous) where TDuck : class&lt;br /&gt;{&lt;br /&gt;    var proxyGenerator = new ProxyGenerator();&lt;br /&gt;    var objectImplementingDuckInterface =&lt;br /&gt;        proxyGenerator.CreateInterfaceProxyWithoutTarget(typeof(TDuck), new DuckTypingInterceptor(anonymous));&lt;br /&gt;&lt;br /&gt;    return objectImplementingDuckInterface as TDuck;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Now the test passes! Great, now what if that color property had a setter? Let's whip up some code to set the property on that anonymous type instance too:&lt;/p&gt;&lt;pre class="brush: plain"&gt;[ ... some code that attempts to forward a setter invocation to the anonymous object via reflection ... ]&lt;br /&gt;&lt;/pre&gt;&lt;pre class="brush: csharp"&gt;[Test]&lt;br /&gt;public void CanSetColorProperty()&lt;br /&gt;{&lt;br /&gt;    var lameDuck = new { Color = "whocares" };&lt;br /&gt;    var typedLameDuck = lameDuck.As&amp;ltIDuck&amp;gt;();&lt;br /&gt;&lt;br /&gt;    typedLameDuck.Color = "blue";&lt;br /&gt;&lt;br /&gt;    Assert.That("blue" == typedLameDuck.Color);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;The problem is, anonymous types don't have setters on the their properties. So we'll just set the backing field, right? Nope... anonymous type properties have readonly backing fields. They are immutable. We'd &lt;i&gt;really&lt;/i&gt; like our proxy to behave like the interface it supposedly implements, so we hack around a bit and come up with this:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;internal class DuckTypingInterceptor : IInterceptor&lt;br /&gt;{&lt;br /&gt;    private readonly object anonymous;&lt;br /&gt;    private readonly IDictionary&amp;lt;string, object&amp;gt; properties = new Dictionary&amp;lt;string, object&amp;gt;();&lt;br /&gt;&lt;br /&gt;    public DuckTypingInterceptor(object anonymous)&lt;br /&gt;    {&lt;br /&gt;        this.anonymous = anonymous;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void Intercept(IInvocation invocation)&lt;br /&gt;    {&lt;br /&gt;        if (invocation.IsGetter())&lt;br /&gt;        {&lt;br /&gt;            var property = invocation.PropertyName();&lt;br /&gt;            invocation.ReturnValue = GetPropertyValue(property);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        if (invocation.IsSetter())&lt;br /&gt;        {&lt;br /&gt;            properties[invocation.PropertyName()] = invocation.Arguments[0];&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private object GetPropertyValue(string property)&lt;br /&gt;    {&lt;br /&gt;        if (properties.ContainsKey(property))&lt;br /&gt;        {&lt;br /&gt;            return properties[property];&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        return anonymous.GetPropertyValue(property);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Now we're mixing in a dictionary of property values with the mutable anonymous object instance to give the feel of a single object with &lt;b&gt;IDuck&lt;/b&gt; capabilities.&lt;/p&gt;&lt;p&gt;So what about methods? Well it would be nice if we could construct anonymous types with lambas, like&lt;/p&gt;&lt;pre class="brush: csharp"&gt;var duck = new&lt;br /&gt;{&lt;br /&gt;    Color = "white",&lt;br /&gt;    Quack = () =&gt; "Quack!"&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;but if we try that, the compiler will yell at us because we "Cannot assign lambda expression to anonymous type property". There is something we can do, however, and I'll cover that in my next post.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-8705342701033656979?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/8705342701033656979/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=8705342701033656979' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/8705342701033656979'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/8705342701033656979'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2011/08/duck-typing-with-anonymous-types.html' title='Duck Typing with Anonymous Types'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-3571374710919164450</id><published>2011-06-19T11:20:00.003-05:00</published><updated>2011-08-11T23:19:31.976-05:00</updated><title type='text'>Mercurial / hg-git / Github Setup Link</title><content type='html'>This is just so I don't forget or lose it: this post has probably the best guide to getting TortoiseHg set up as a github client on Windows:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://jamesmckay.net/tag/hg-git/"&gt;james mckay dot net - TortoiseHg as a github client on Windows&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Apparently I don't know how to use Google, because I always struggle to find this.&lt;br /&gt;&lt;br /&gt;UPDATE:&lt;br /&gt;Be careful not to wrap the hggit extension path in quotes in the mercurial config file *even if the path has a directory with a space in it*. I was setting mine like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush: plain"&gt;[extensions]&lt;br /&gt;hggit = "C:\ABC DEF\hg-git\hggit"&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;but that was causing this error:&lt;br /&gt;&lt;pre class="brush: plain"&gt;*** failed to import extension hggit from "C:\ABC DEF\hg-git\hggit": [Errno 22] Invalid argument&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Removing the quotes fixed the problem:&lt;br /&gt;&lt;pre class="brush: plain"&gt;[extensions]&lt;br /&gt;hggit = C:\ABC DEF\hg-git\hggit&lt;br /&gt;&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-3571374710919164450?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/3571374710919164450/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=3571374710919164450' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3571374710919164450'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3571374710919164450'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2011/06/mercurial-hg-git-github-setup-link.html' title='Mercurial / hg-git / Github Setup Link'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-3799604226391751527</id><published>2010-09-10T22:42:00.002-05:00</published><updated>2011-08-11T23:32:27.227-05:00</updated><title type='text'>Serializing Anonymous Methods</title><content type='html'>&lt;p&gt;I’m taking some time off from not blogging to do a little blogging. I hope this doesn’t inconvenience absolutely nobody.&lt;/p&gt;&lt;p&gt;I was doing some [binary] serialization work recently when I came across a problem – I wanted to serialize objects with delegate fields that were populated with anonymous methods at runtime. To wit, I had types like this:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;public delegate void MakeMove();&lt;br /&gt;&lt;br /&gt;public class AdrianPeterson&lt;br /&gt;{&lt;br /&gt;    public int GameOneYards { get; set; }&lt;br /&gt;    public Football Ball { get; set; }&lt;br /&gt;    public MakeMove Move { get; set; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Populated like this:&lt;/p&gt;&lt;pre class="brush:csharp"&gt;var explicitDirections = new List&amp;lt;string&gt; { "left", "right", "left" };&lt;br /&gt;&lt;br /&gt;var ap = new AdrianPeterson();&lt;br /&gt;var apName = ap.GetType().Name;&lt;br /&gt;ap.GameOneYards = 87;&lt;br /&gt;ap.Move = () =&gt; Moves.Weave(apName, explicitDirections);&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;So, I pop a [&lt;span style="color: #2b91af"&gt;Serializable&lt;/span&gt;] on &lt;span style="color: #2b91af"&gt;AdrianPeterson &lt;/span&gt;(and &lt;span style="color: #2b91af"&gt;Football&lt;/span&gt;), and I’m set, right? Wrong. Wrong like getting away from running AP in the second half when the only receiving threat you have is being blanketed by the Saints defensive backfield. You end up with an exception like this:&lt;/p&gt;&lt;pre class="brush: plain"&gt;System.Runtime.Serialization.SerializationException: Type 'BlahBlahBlah+&amp;lt;&gt;c__DisplayClass2' in Assembly 'YadaYadaYada' is not marked as serializable.&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Ah, of course, the backing field for the ‘Move’ property holds an instance to an object with a runtime type of ‘BlahBlahBlah+&amp;lt;&amp;gt;c__DisplayClass2’ – the compiler-generated class that encapsulates the anonymous method and its scope (or something like that… let’s not get too technical). That class isn’t marked as serializable. Hence the exception. Crap! &lt;/p&gt;&lt;p&gt;No problem, a quick google search gave me &lt;a href="http://www.codeproject.com/KB/cs/AnonymousSerialization.aspx"&gt;this code&lt;/a&gt; as the first result. It works very well, except it doesn’t handle fields declared as abstract types. I made a little modification, then I started to get the dreaded &lt;em&gt;refactoring itch&lt;/em&gt;. I started looking at the if/else if/else mess that was mirrored in both the deserialization constructor and ‘GetObjectData’ method and thought “clearly these are strategies determined by the type”. And I thought a little more, “this looks like a good place for a chain of responsibility or something like that.” And I thought a little &lt;em&gt;more&lt;/em&gt;, and I realized that the serialization architecture in the .NET framework &lt;em&gt;is built to handle this exact situation&lt;/em&gt;!&lt;/p&gt;&lt;p&gt;All I really had to do was handle serialization of classes not marked with the aforementioned attribute, and the rest fell into place. Relevant classes:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;public class UnattributedTypeSurrogate : ISerializationSurrogate&lt;br /&gt;{&lt;br /&gt;    private const BindingFlags publicOrNonPublicInstanceFields = &lt;br /&gt;        BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;&lt;br /&gt;&lt;br /&gt;    public void GetObjectData(object obj, &lt;br /&gt;        SerializationInfo info, StreamingContext context)&lt;br /&gt;    {&lt;br /&gt;        var type = obj.GetType();&lt;br /&gt;        foreach (var field in type.GetFields(publicOrNonPublicInstanceFields))&lt;br /&gt;        {&lt;br /&gt;            var fieldValue = field.GetValue(obj);&lt;br /&gt;            var fieldValueIsNull = fieldValue != null;&lt;br /&gt;            if (fieldValueIsNull)&lt;br /&gt;            {&lt;br /&gt;                var fieldValueRuntimeType = fieldValue.GetType();&lt;br /&gt;                info.AddValue(field.Name + "RuntimeType", &lt;br /&gt;                    fieldValueRuntimeType.AssemblyQualifiedName);&lt;br /&gt;            }&lt;br /&gt;            &lt;br /&gt;            info.AddValue(field.Name + "ValueIsNull", fieldValueIsNull);&lt;br /&gt;            info.AddValue(field.Name, fieldValue);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public object SetObjectData(object obj, &lt;br /&gt;        SerializationInfo info, StreamingContext context, ISurrogateSelector selector)&lt;br /&gt;    {&lt;br /&gt;        var type = obj.GetType();&lt;br /&gt;        foreach (var field in type.GetFields(publicOrNonPublicInstanceFields))&lt;br /&gt;        {&lt;br /&gt;            var fieldValueIsSerializable = info.GetBoolean(field.Name + "ValueIsNull");&lt;br /&gt;            if (fieldValueIsSerializable)&lt;br /&gt;            {&lt;br /&gt;                var fieldValueRuntimeType = info.GetString(field.Name + "RuntimeType");&lt;br /&gt;                field.SetValue(obj, &lt;br /&gt;                    info.GetValue(field.Name, Type.GetType(fieldValueRuntimeType)));   &lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        return obj;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class UnattributedTypeSurrogateSelector : ISurrogateSelector&lt;br /&gt;{&lt;br /&gt;    private readonly SurrogateSelector innerSelector = new SurrogateSelector();&lt;br /&gt;    private readonly Type iFormatter = typeof (IFormatter);&lt;br /&gt;&lt;br /&gt;    public void ChainSelector(ISurrogateSelector selector)&lt;br /&gt;    {&lt;br /&gt;        innerSelector.ChainSelector(selector);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public ISerializationSurrogate GetSurrogate(&lt;br /&gt;        Type type, StreamingContext context, out ISurrogateSelector selector)&lt;br /&gt;    {&lt;br /&gt;        if (!type.IsSerializable)&lt;br /&gt;        {&lt;br /&gt;            selector = this;&lt;br /&gt;            return new UnattributedTypeSurrogate();&lt;br /&gt;        }&lt;br /&gt;        return innerSelector.GetSurrogate(type, context, out selector);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public ISurrogateSelector GetNextSelector()&lt;br /&gt;    {&lt;br /&gt;        return innerSelector.GetNextSelector();&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Usage is like this:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;var formatter = new BinaryFormatter();&lt;br /&gt;formatter.SurrogateSelector = new UnattributedTypeSurrogateSelector();&lt;br /&gt;formatter.Serialize(serializedAP, adrianPeterson);&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;This hasn’t been rigorously tested, and there is at least one case where I know it will fail – if the formatter that is doing the serialization gets captured in the compiler-generated class for the anonymous method (which can easily happen if the formatter is a field in the outer class and the anon. method uses another field from that class).&lt;/p&gt;&lt;p&gt;Full code, with tests, can be found &lt;a href="http://code.google.com/p/continuous-disintegration/source/browse/#svn/trunk/ContinuosDisintegrationSerializationSample"&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-3799604226391751527?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/3799604226391751527/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=3799604226391751527' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3799604226391751527'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3799604226391751527'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2010/09/serializing-anonymous-methods.html' title='Serializing Anonymous Methods'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-3184098878698905692</id><published>2010-05-01T14:59:00.004-05:00</published><updated>2011-08-11T23:56:35.491-05:00</updated><title type='text'>Micro Fluency</title><content type='html'>I’ve been having a lot of conversations at work lately about how &lt;a href="http://elegantcode.com/2010/04/18/eliminating-comments-the-road-to-clarity/"&gt;comments&lt;/a&gt; are a &lt;a href="http://www.chadmyers.com/Blog/archive/2007/11/18/1-common-mistake-involving-code-commenting.aspx"&gt;code smell&lt;/a&gt;, and if &lt;a href="http://www.chadmyers.com/blog/archive/2007/12/07/more-on-code-commenting.aspx"&gt;you’re not writing&lt;/a&gt; &lt;a href="http://jeffreypalermo.com/blog/limiting-code-comments-increases-maintainability/"&gt;self-documenting code&lt;/a&gt;, &lt;a href="http://odetocode.com/blogs/scott/archive/2009/02/10/due-diligence-and-code-comments.aspx"&gt;ur doin it rong&lt;/a&gt;.&lt;br /&gt;Then I found myself in a position I’ve been in quite a few times… The general description is this: I have a method that takes two parameters. The action the method performs is best written in English in the form “{SomethingTheObjectDoesWith} {parameter1} {On/With/For/SomeOtherPreposition} {parameter2}”. The only way to name the method is “&lt;strong&gt;SomethingTheObjectDoesOn/With/For(parameter1, parameter2)”&lt;/strong&gt;. It seems like I run into this situation too often. The API for all of the concerned code doesn’t necessitate building out a huge fluent interface for readability, but it would be nice to have things read just a little better in this case.&lt;br /&gt;An example is certainly in order. I have an ASP.NET server control that activates a certain index on an associated &lt;strong&gt;MultiView&lt;/strong&gt;. In order to let client code know whether or not it activates an index, I have this method:&lt;br /&gt;&lt;pre class="brush: csharp"&gt;public bool ActivatesViewOn(int viewIndex, string multiViewId)&lt;br /&gt;{&lt;br /&gt;    // Some logic that determines if the control activates the specified view&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Here is the method in use:&lt;br /&gt;&lt;pre class="brush: csharp"&gt;filterPanel.Visible = itemClicked.ActivatesViewOn(0, contentMultiView.ID);&lt;/pre&gt;This is *kinda* self-documenting, but it doesn’t really read as nicely as it could. So I did this fairly minor refactoring in the control:&lt;br /&gt;&lt;pre class="brush: csharp"&gt;public IActivateViewOn ActivatesView(int viewIndex)&lt;br /&gt;{&lt;br /&gt;    return new ActivateViewOn(viewIndex);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public interface IActivateViewOn&lt;br /&gt;{&lt;br /&gt;    bool On(string multiViewId);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private class ActivateViewOn : IActivateViewOn&lt;br /&gt;{&lt;br /&gt;    private readonly int viewIndex;&lt;br /&gt;&lt;br /&gt;    public ActivateViewOn(int viewIndex)&lt;br /&gt;    {&lt;br /&gt;        this.viewIndex = viewIndex;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public bool On(string multiViewId)&lt;br /&gt;    {&lt;br /&gt;        // Some logic that determines if the control activates the specified view &lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;And now the calling code looks like:&lt;br /&gt;&lt;pre class="brush: csharp"&gt;filterPanel.Visible = itemClicked.ActivatesView(0).On(contentMultiView.ID);&lt;/pre&gt;So here I’ve created a miniature fluent interface that is specific to this method. But at what cost? Have I added needless complexity to the control? Arguably, I’ve made the client code more readable but the control code harder to maintain. Here’s how I see it: &lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;PRO: Consuming code is easier to read. &lt;/li&gt;&lt;li&gt;PRO: Adding nested types (the &lt;strong&gt;IActivateViewOn&lt;/strong&gt; interface and &lt;strong&gt;ActivateViewOn&lt;/strong&gt; class) is no more complicated that adding methods. Basically, I get a nice fluent syntax by breaking my uglier method into a few smaller ones. &lt;/li&gt;&lt;li&gt;PRO: The added private class isn’t exposed to the client, so that piece doesn’t complicate the external API. The added interface is only exposed as a nested class on the control, so it doesn’t pollute the controls namespace. &lt;/li&gt;&lt;li&gt;PRO: I can modify this further pretty easily to keep my client code very readable as dictated by usage. Though it would probably be overkill to have &lt;strong&gt;itemClicked.Activates.FirstView.On(someMultiView)&lt;/strong&gt;, the option is there and the syntax could be easily produced. &lt;/li&gt;&lt;li&gt;PRO: I could rename the nested types for even more clarity in the control’s code. &lt;/li&gt;&lt;li&gt;CON: The &lt;strong&gt;IActivateViewOn&lt;/strong&gt; interface might not aid discovery as a return value as much as &lt;strong&gt;bool&lt;/strong&gt; might. I’m reaching here… I personally think the fluent interface is more discoverable. But how do I know I can eventually get the data that I want? &lt;/li&gt;&lt;li&gt;CON: A developer maintaining the control will think “what the hell is this?!?”. &lt;/li&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-3184098878698905692?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/3184098878698905692/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=3184098878698905692' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3184098878698905692'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3184098878698905692'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2010/05/micro-fluency.html' title='Micro Fluency'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-5575586628801021320</id><published>2010-04-13T22:48:00.004-05:00</published><updated>2011-08-12T00:01:51.704-05:00</updated><title type='text'>When an Object Isn’t an Object</title><content type='html'>I really wish there were more guidance on how to handle static reflection situations. Some kind of helper library would be nice. I’m actually surprised one doesn’t exist given its usefulness and the quirks involved. Consider this scenario – you’re reflecting over the details of a method call and the parameters passed. You actually care about the values that have been passed. How do you discover them?&lt;br /&gt;It goes something like this, &lt;em&gt;I think:&lt;/em&gt;&lt;br /&gt;&lt;pre class="brush: csharp"&gt;var argument = GetExpression();&lt;br /&gt;if (argument.Type.IsValueType)&lt;br /&gt;{&lt;br /&gt;    argument = Expression.Convert(argument, typeof(object));&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;var getValueExpression = Expression.Lambda&amp;lt;Func&amp;lt;object&gt;&gt;(argument);&lt;br /&gt;var getValue = getValueExpression.Compile();&lt;br /&gt;var value = getValue();&lt;br /&gt;&lt;/pre&gt;I found that &lt;a href="http://stackoverflow.com/questions/1803142/get-property-lambda-from-property-name-where-property-type-can-be-nullable"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;If you don’t explicitly convert the value type to an object, you’ll get an exception that will confuse you (something to the effect of “Expression of type 'System.Decimal' cannot be used for return type 'System.Object'”). It’s confusing because, c’mon, isn’t &lt;em&gt;everything&lt;/em&gt; a System.Object? If a function returns object, can’t you return &lt;em&gt;anything&lt;/em&gt;? Well, &lt;a href="http://blogs.msdn.com/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx"&gt;no&lt;/a&gt;. And I’m guessing from what Eric Lippert also says &lt;a href="http://stackoverflow.com/questions/840150/linq-and-the-equality-operator-expression-of-type-system-int32-cannot-be-used"&gt;here&lt;/a&gt;, baking the conversion rules for C# (in this case, that almost everything is convertible to object and so C# does it implicitly) or VB or any other .NET language into LINQ would be doing a disservice to the other languages.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-5575586628801021320?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/5575586628801021320/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=5575586628801021320' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/5575586628801021320'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/5575586628801021320'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2010/04/when-and-object-isnt-object.html' title='When an Object Isn’t an Object'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-3214350916577192702</id><published>2010-04-13T14:00:00.002-05:00</published><updated>2011-08-12T00:12:18.331-05:00</updated><title type='text'>Teaser</title><content type='html'>&lt;p&gt;These tests all pass:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;[Test]&lt;br /&gt;[ExpectedException(typeof(AssertionException))]&lt;br /&gt;public void ThrowsAssertionExceptionForWrongArgument()&lt;br /&gt;{&lt;br /&gt;    Expect.Call(() =&gt; Console.WriteLine("A specific string."));&lt;br /&gt;    StaticClass.CodeUnderTestThatCallsConsoleWriteLine();&lt;br /&gt;    Verify.AllExpectations();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Test]&lt;br /&gt;public void VerifiesCallWithoutActuallyPerformingTheCall()&lt;br /&gt;{&lt;br /&gt;    Expect.Call(() =&gt; Console.WriteLine("You shouldn't see me."));&lt;br /&gt;    StaticClass.CodeUnderTestThatCallsConsoleWriteLine();&lt;br /&gt;    Verify.AllExpectations();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Test]&lt;br /&gt;public void PerformsAlternativeAction()&lt;br /&gt;{&lt;br /&gt;    Expect.Call(() =&gt; Console.WriteLine("YOU SHOULDN'T SEE THIS")).IgnoreArguments()&lt;br /&gt;        .Do(() =&gt; Console.WriteLine("You should see this instead."));&lt;br /&gt;    StaticClass.CodeUnderTestThatCallsConsoleWriteLine();&lt;br /&gt;    Verify.AllExpectations();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Test]&lt;br /&gt;public void IgnoresArguments()&lt;br /&gt;{&lt;br /&gt;    Expect.Call(() =&gt; Console.WriteLine("")).IgnoreArguments();&lt;br /&gt;    StaticClass.CodeUnderTestThatCallsConsoleWriteLine();&lt;br /&gt;    Verify.AllExpectations();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Test]&lt;br /&gt;public void InterceptsBothCalls()&lt;br /&gt;{&lt;br /&gt;    Expect.Call(() =&gt; Console.WriteLine("")).IgnoreArguments();&lt;br /&gt;    StaticClass.CallsConsoleWriteLineTwice();&lt;br /&gt;    Verify.AllExpectations();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Test]&lt;br /&gt;public void InterceptsOnlyOneOverload()&lt;br /&gt;{&lt;br /&gt;    Expect.Call(() =&gt; Console.WriteLine("IGNORED")).IgnoreArguments();&lt;br /&gt;    StaticClass.CallsTwoOverloads();&lt;br /&gt;    Verify.AllExpectations();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Where &lt;strong&gt;StaticClass&lt;/strong&gt; looks like this:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;public static class StaticClass&lt;br /&gt;{&lt;br /&gt;    public static void CodeUnderTestThatCallsConsoleWriteLine()&lt;br /&gt;    {&lt;br /&gt;        Console.WriteLine("You shouldn't see me.");&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static void CallsConsoleWriteLineTwice()&lt;br /&gt;    {&lt;br /&gt;        Console.WriteLine("You shouldn't see me.");&lt;br /&gt;        Console.WriteLine("You shouldn't see me.");&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static void CallsTwoOverloads()&lt;br /&gt;    {&lt;br /&gt;        var characters = "You SHOULD see me.".ToCharArray();&lt;br /&gt;&lt;br /&gt;        Console.WriteLine("You shouldn't see me.");&lt;br /&gt;        Console.WriteLine(characters);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;And the console output as shown by ReSharper is this:&lt;/p&gt;&lt;p&gt;&lt;a href="http://lh6.ggpht.com/_GdP3Wu-JVpE/S8S_YD9dq3I/AAAAAAAAABY/RAvXC01WFhs/s1600-h/teaser_post%5B5%5D.png"&gt;&lt;img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="teaser_post" border="0" alt="teaser_post" src="http://lh4.ggpht.com/_GdP3Wu-JVpE/S8S_YqIFX2I/AAAAAAAAABc/KtvT9x6J0TM/teaser_post_thumb%5B3%5D.png?imgmax=800" width="758" height="446" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-3214350916577192702?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/3214350916577192702/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=3214350916577192702' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3214350916577192702'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3214350916577192702'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2010/04/teaser.html' title='Teaser'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh4.ggpht.com/_GdP3Wu-JVpE/S8S_YqIFX2I/AAAAAAAAABc/KtvT9x6J0TM/s72-c/teaser_post_thumb%5B3%5D.png?imgmax=800' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-5667202273716966003</id><published>2010-03-27T16:51:00.008-05:00</published><updated>2010-03-27T17:09:13.716-05:00</updated><title type='text'>VS Extensibility - It's So Easy!</title><content type='html'>&lt;div style="text-align: left;"&gt;&lt;i&gt;(Note: This is an old post that was stuck in my backlog. I am publishing it now with the intent of writing more VS extensibility posts.)&lt;/i&gt;&lt;/div&gt;&lt;div style="text-align: left;"&gt;&lt;br /&gt;&lt;/div&gt;&lt;div style="text-align: left;"&gt;I have a colleague who laments the desire of developers to have (and tool developers to put) ‘everything in the IDE’. Anyone who has struggled with integrated source control fussing up a solution structure can probably identify with this view to some degree. Still, anyone who has used the NUnit GUI test runner for lack of having ReSharper or TestDriven.NET has had a taste of the case for IDE integration. When building small custom tools to enhance developer productivity and make it easy to perform mechanical tasks, why not stick them in Visual Studio? It turns out, it’s pretty easy to do.&lt;/div&gt;  &lt;p&gt;Consider a situation in which a developer has user accounts for each tenant of a multitenant application. These accounts get deactivated after a period of non-use, so they need to get reactivated in order for the developer to troubleshoot problems that manifest only for a specific tenant. The developer usually just runs a script that resets the account to active; it’s about as simple as a maintenance task could be for a dev. Still, wouldn’t it be nice to have an easy way to track down the script and execute it? And wouldn’t it be nice to make sure all the developers used a standard method of performing this reset to prevent possible anomalies? We can make a little Visual Studio tool window with a button to execute this script. The tool window can be easily located in the Visual Studio menus. &lt;/p&gt;  &lt;p&gt;First, create a Visual Studio Integration Package project&lt;/p&gt;  &lt;p&gt;&lt;span class="Apple-style-span" style="color: rgb(0, 0, 238); -webkit-text-decorations-in-effect: underline; "&gt;&lt;img src="http://4.bp.blogspot.com/_GdP3Wu-JVpE/S65_19UgfXI/AAAAAAAAAAg/Cu4WIpNir7c/s400/CreateVSIntegrationProject.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5453436763762621810" style="display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 400px; height: 259px; " /&gt;&lt;/span&gt;&lt;/p&gt;  &lt;p&gt;This will bring up a wizard, which is pretty self-explanatory. In this example, we’re creating just a tool window:&lt;/p&gt;  &lt;p&gt;&lt;span class="Apple-style-span" style="color: rgb(0, 0, 238); -webkit-text-decorations-in-effect: underline; "&gt;&lt;img src="http://1.bp.blogspot.com/_GdP3Wu-JVpE/S66AYAqwmjI/AAAAAAAAAAo/xV2Xd-2DOtw/s400/SelectToolWindowAsVSPackageOption.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5453437348776811058" style="display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 400px; height: 301px; " /&gt;&lt;/span&gt;&lt;/p&gt;  &lt;p&gt;From there, it’s just a matter of creating a user control to do our bidding. The control is automatically included in the integration package project and named ‘MyControl’ by default. Integration and interoperability with VS is achieved through a Microsoft.VisualStudio.Shell.Package class (named ‘{PackageName}Package’ by default) and a wrapper class (‘MyToolWindow’ by default) which inherits from Microsoft.VisualStudio.Shell.ToolWindow and exposes the control to the IDE through the Window property.&lt;/p&gt;  &lt;p&gt;I’ll spare the boring details on the implementation of this example control. The code can be found &lt;a href="http://continuous-disintegration.googlecode.com/svn/trunk/UserReactivationTool/"&gt;here&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Part of what makes developing the tool window so easy is the debugging experience – running the project launches an experimental hive with our custom tool window installed! Just go to View &amp;gt; Other Windows and select the User Reactivation tool:&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;span class="Apple-style-span" style="color: rgb(0, 0, 238); -webkit-text-decorations-in-effect: underline; "&gt;&lt;img src="http://3.bp.blogspot.com/_GdP3Wu-JVpE/S66AruzksJI/AAAAAAAAAAw/ZrXCTnkx9b8/s400/DebugVSExtensibilityProject.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5453437687579324562" style="display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 373px; height: 400px; " /&gt;&lt;/span&gt;&lt;/p&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="color: rgb(0, 0, 238); -webkit-text-decorations-in-effect: underline; "&gt;&lt;span class="Apple-style-span" style="color: rgb(0, 0, 0); "&gt;&lt;a href="http://4.bp.blogspot.com/_GdP3Wu-JVpE/S66A-sNtlYI/AAAAAAAAAA4/0KpM6_R-pGI/s1600/SelectOtherWindowsUserReactivation.png"&gt;&lt;img src="http://4.bp.blogspot.com/_GdP3Wu-JVpE/S66A-sNtlYI/AAAAAAAAAA4/0KpM6_R-pGI/s400/SelectOtherWindowsUserReactivation.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5453438013301167490" style="display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 400px; height: 333px; " /&gt;&lt;/a&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;span class="Apple-style-span" style="color: rgb(0, 0, 238); -webkit-text-decorations-in-effect: underline; "&gt;&lt;span class="Apple-style-span" style="color: rgb(0, 0, 0); "&gt;&lt;a href="http://2.bp.blogspot.com/_GdP3Wu-JVpE/S66BLZjIPVI/AAAAAAAAABA/yjm24YART-k/s1600/SeeUserReactivationToolWindow.png"&gt;&lt;img src="http://2.bp.blogspot.com/_GdP3Wu-JVpE/S66BLZjIPVI/AAAAAAAAABA/yjm24YART-k/s400/SeeUserReactivationToolWindow.png" border="0" alt="" id="BLOGGER_PHOTO_ID_5453438231629020498" style="display: block; margin-top: 0px; margin-right: auto; margin-bottom: 10px; margin-left: auto; text-align: center; cursor: pointer; width: 400px; height: 313px; " /&gt;&lt;/a&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;This example featured a hardcoded backend with no configuration options. In the future, I’ll explore how to outfit your extensibility projects with configuration.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-5667202273716966003?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/5667202273716966003/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=5667202273716966003' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/5667202273716966003'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/5667202273716966003'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2010/03/vs-extensibility-its-so-easy.html' title='VS Extensibility - It&apos;s So Easy!'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://4.bp.blogspot.com/_GdP3Wu-JVpE/S65_19UgfXI/AAAAAAAAAAg/Cu4WIpNir7c/s72-c/CreateVSIntegrationProject.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-3005154735649500911</id><published>2010-03-02T01:12:00.002-06:00</published><updated>2011-08-12T00:17:59.605-05:00</updated><title type='text'>Defeating the Purpose of a DSL</title><content type='html'>&lt;p&gt;First, I neglected to mention in my &lt;a href="http://jamesryangray.blogspot.com/2010/02/building-simple-data-definition-dsl.html"&gt;previous post&lt;/a&gt; that I found &lt;a href="http://thesoftwaresimpleton.blogspot.com/"&gt;Paul Cowan's blog&lt;/a&gt; to be a tremendous help in figuring out how build a &lt;a href="http://thesoftwaresimpleton.blogspot.com/2009/04/parsing-horn-dsl.html"&gt;DSL with Boo and Rhino DSL&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Second, I wanted to point out that, because this is an internal DSL written in Boo, it's still possible to use familiar programming constructs in the DSL scripts. For example, I could dynamically generate the team definitions from some other datasource, like so:&lt;/p&gt;&lt;pre class="brush: python"&gt;stats = GetData()&lt;br /&gt;&lt;br /&gt;for row as DataRow in stats.Rows:&lt;br /&gt;define row["name"]:&lt;br /&gt;defense Determine.DefenseFromRanking(cast(int,row["defenseRanking"]))&lt;br /&gt;pass_offense Determine.PassOffenseFromRanking(cast(int,row["passOffenseRanking"])), with_qb_type(Determine.QbTypeFromRatingAndExperience(cast(double,row["qbRating"]), cast(int,row["qbExperience"])))&lt;br /&gt;run_offense Determine.RunOffenseFromRanking(cast(int,row["runOffenseRanking"]))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;where &lt;b&gt;GetData()&lt;/b&gt; returns a DataTable with multiple team statistics, and &lt;b&gt;Determine&lt;/b&gt; is a static class that gets the name of different team components based on relevant stats.&lt;/p&gt;&lt;p&gt;The meta methods that define the keywords &lt;i&gt;won't&lt;/i&gt; work as is for this. Remember, they're operating on the AST. In this case, the parameter types simply need to be relaxed from &lt;b&gt;StringLiteralExpression&lt;/b&gt; to &lt;b&gt;Expression&lt;/b&gt;. Here's the new &lt;b&gt;run_offense&lt;/b&gt; meta method as an example:&lt;/p&gt;&lt;br /&gt;&lt;pre class="brush: python"&gt;[Meta]&lt;br /&gt;public static def run_offense(expression as Expression):&lt;br /&gt;return [|&lt;br /&gt;_currentTeam.RunOffense = $expression&lt;br /&gt;|]&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;So, string literals and method calls both work here. One thing that slightly limits the extensibility of the language in this matter is the use of the implicit base class as a container for the script. The body of the script (minus any import statements) goes directly into the implementation of an abstract method declared on the base class, so extending the language by adding methods directly to the script is out. Other than that, everything should work like normal. All the constructs of the language are available. Of course, doing something like what's listed above sort of defeats the purpose of creating a language for easy data scripting in the first place, as it isn't very readable or maintainable...&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-3005154735649500911?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/3005154735649500911/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=3005154735649500911' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3005154735649500911'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3005154735649500911'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2010/03/defeating-purpose-of-dsl.html' title='Defeating the Purpose of a DSL'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-7868356756266995299</id><published>2010-02-25T22:47:00.002-06:00</published><updated>2011-08-12T00:39:13.278-05:00</updated><title type='text'>Building a Simple Data Definition DSL with Boo</title><content type='html'>&lt;p&gt;In my daily work, I find myself writing a lot of one-off SQL scripts to handle various data issues. In particular, I've had to tweak existing sets of metadata with scripts that look something like the following:&lt;/p&gt;&lt;pre class="brush: sql"&gt;DECLARE     @SomeId INT&lt;br /&gt;DECLARE     @SomeOtherId INT&lt;br /&gt;&lt;br /&gt;SELECT      @SomeId = SomeTableId &lt;br /&gt;FROM        SomeTable &lt;br /&gt;WHERE       SomeName = 'Something'&lt;br /&gt;&lt;br /&gt;SELECT      @SomeOtherId = SomeOtherTableid &lt;br /&gt;FROM        SomeOtherTable &lt;br /&gt;WHERE       SomeOtherName = 'SomethingElse'&lt;br /&gt;&lt;br /&gt;IF NOT EXISTS(&lt;br /&gt;    SELECT  1 &lt;br /&gt;    FROM    SomeMetadataTable &lt;br /&gt;    WHERE   Name = 'MetadataName')&lt;br /&gt;BEGIN&lt;br /&gt;    INSERT INTO SomeMetadataTable&lt;br /&gt;        (Name, Property1, Property2)&lt;br /&gt;    VALUES &lt;br /&gt;        ('MetadataName', @SomeId, @SomeOtherId)&lt;br /&gt;END&lt;br /&gt;ELSE&lt;br /&gt;BEGIN&lt;br /&gt;    UPDATE  SomeMetadataTable&lt;br /&gt;    SET     Property1 = @SomeId&lt;br /&gt;        ,   Property2 = @SomeOtherId&lt;br /&gt;    WHERE   Name = 'MetadataName'&lt;br /&gt;END&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Just writing a few of these gets to be tedious, and master scripts to populate entire tables are large, difficult to maintain blobs of SQL.&lt;/p&gt;&lt;p&gt;At the end of last year, I nabbed myself some copies (digital and physical) of Ayende's excellent &lt;a href="http://www.manning.com/rahien/"&gt;DSLs in Boo&lt;/a&gt;. Having thought before that I might use some of the &lt;a href="http://msdn.microsoft.com/en-us/data/ee460940.aspx"&gt;tools&lt;/a&gt; in the SQL Server Modeling space to build a DSL to simplify the scripting of such metadata, I decided to see how easily something workable could be built with Boo. There were a few stumbling blocks along way, mostly regarding my inexperience with Boo and my inability to download and compile &lt;a href="http://github.com/ayende/rhino-dsl"&gt;Rhino DSL&lt;/a&gt; (I'm not used to git, and a directoy with a space in the name wasted some of my time). Once I was past those problems, I found the going very easy.&lt;/p&gt;&lt;p&gt;I wrote this exploratory example before the NFL championship games this year, so I chose to create a language that might describe the attributes of a football team. Here is the final script I ended with:&lt;/p&gt;&lt;pre class="brush: python"&gt;define "New York Jets":&lt;br /&gt;    defense "Superb"&lt;br /&gt;    pass_offense "Game Management", with_qb_type("Rookie")&lt;br /&gt;    run_offense "Power"&lt;br /&gt;&lt;br /&gt;define "Minnesota Vikings":&lt;br /&gt;    defense "Solid"&lt;br /&gt;    pass_offense "High-Powered", with_qb_type("Aging Veteran")&lt;br /&gt;    run_offense "Dynamic"&lt;br /&gt;&lt;br /&gt;define "Indianapolis Colts":&lt;br /&gt;    defense "Speedy"&lt;br /&gt;    pass_offense "High-Octane", with_qb_type("Elite Veteran")&lt;br /&gt;    run_offense "Anemic"&lt;br /&gt;&lt;br /&gt;define "New Orleans Saints":&lt;br /&gt;    defense "Opportunistic"&lt;br /&gt;    pass_offense "Explosive", with_qb_type("Rising Star")&lt;br /&gt;    run_offense "Serviceable"&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;The easiest way to define 'keywords' like &lt;strong&gt;define&lt;/strong&gt; and &lt;strong&gt;defense&lt;/strong&gt; is through &lt;a href="http://ayende.com/Blog/archive/2007/12/21/Meta-Methods.aspx"&gt;meta methods&lt;/a&gt;. Meta methods process AST nodes and return AST nodes during compilation. The meta method for &lt;strong&gt;define&lt;/strong&gt; looks like this:&lt;/p&gt;&lt;pre class="brush: python"&gt;[Meta]&lt;br /&gt;public static def define(expression as StringLiteralExpression, block as BlockExpression):	&lt;br /&gt;    return [|&lt;br /&gt;        _currentTeam.Name = $(expression.Value)	&lt;br /&gt;        DefineTeam($block)&lt;br /&gt;    |]&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;I'm using quasi-quotation here, which basically means that Boo will turn that block of code that I'm returning into an appropriate AST node. So, in this case, when the compiler encounters 'define', it will take the following string and the block that follows that and transform it into a call that sets a property (&lt;strong&gt;Name&lt;/strong&gt;) on a class variable (&lt;strong&gt;_currentTeam&lt;/strong&gt;) with the string, followed by a call to a class method (&lt;strong&gt;DefineTeam&lt;/strong&gt;) that takes the block as an argument. Yeahhhhhhhhhhh, that's confusing. It takes a little bit of time to get your head around exactly what is going on, but once you do, you can crank out meta methods like mad.&lt;br /&gt;So where did that field and method come from? I'm using Ayende's Rhino DSL library to create an 'implicit base class' for the script. The meta methods ultimately call fields and methods that are defined on this base class from which the script inherits. In this case, I'm doing something that might be unorthodox or bad practice by combining all the team definitions together and storing them in a list. In most examples I've seen, the team definitions would be in four different script. For this spike, I went with something quick and dirty. The SQL I'm generating isn't being written to file anywhere or executed; I'm just kicking it out to the console. Here's the script's base class in its entirety:&lt;/p&gt;&lt;pre class="brush: python"&gt;import System&lt;br /&gt;import Boo.Lang.Compiler.Ast&lt;br /&gt;&lt;br /&gt;public abstract class TeamDefinitionScript:&lt;br /&gt;&lt;br /&gt;protected currentNumber as int&lt;br /&gt;&lt;br /&gt;public def constructor():&lt;br /&gt;    CurrentTeam = TeamModel()&lt;br /&gt;&lt;br /&gt;[Property(Teams)]&lt;br /&gt;protected _teams as List[of TeamModel] = List[of TeamModel]()&lt;br /&gt;&lt;br /&gt;[Property(CurrentTeam)]&lt;br /&gt;protected _currentTeam as TeamModel&lt;br /&gt;&lt;br /&gt;abstract def Prepare():&lt;br /&gt;    pass&lt;br /&gt;&lt;br /&gt;protected def DefineTeam(block as callable):&lt;br /&gt;    block()&lt;br /&gt;    Teams.Add(CurrentTeam)&lt;br /&gt;    currentNumber++&lt;br /&gt;&lt;br /&gt;    print "DECLARE @DefenseId${currentNumber} INT"&lt;br /&gt;    print "SELECT  @DefenseId${currentNumber} = DefenseId FROM Defense WHERE DefenseTypeName = '${CurrentTeam.Defense}'"&lt;br /&gt;    print ""&lt;br /&gt;    print "DECLARE @RunOffenseId${currentNumber} INT"&lt;br /&gt;    print "SELECT  @RunOffenseId${currentNumber} = RunOffenseId FROM RunOffense WHERE RunOffenseTypeName = '${CurrentTeam.RunOffense}'"&lt;br /&gt;    print ""&lt;br /&gt;    print "DECLARE @PassOffenseId${currentNumber} INT"&lt;br /&gt;    print "DECLARE @QbTypeId${currentNumber}	  INT"&lt;br /&gt;&lt;br /&gt;    print "SELECT  @QbTypeId${currentNumber} = QbTypeId FROM QbType WHERE QbTypeName = '${CurrentTeam.QbType}'"&lt;br /&gt;    print "SELECT  @PassOffenseId${currentNumber} = PassOffenseId FROM PassOffense WHERE PassOffenseTypeName = '${CurrentTeam.PassOffense}' AND QbTypeId = @QbTypeId"&lt;br /&gt;    print ""&lt;br /&gt;    print "IF NOT EXISTS (SELECT 1 FROM Teams WHERE TeamName = '${CurrentTeam.Name}')"&lt;br /&gt;    print "BEGIN"&lt;br /&gt;    print "    INSERT INTO Teams (TeamName, DefenseId, RunOffenseId, PassOffenseId)"&lt;br /&gt;    print "        VALUES        (${CurrentTeam.Name}, @DefenseId${currentNumber}, @RunOffenseId${currentNumber}, @PassOffenseId${currentNumber})"&lt;br /&gt;    print "END"&lt;br /&gt;    print "ELSE"&lt;br /&gt;    print "BEGIN"&lt;br /&gt;    print "    UPDATE Teams"&lt;br /&gt;    print "    SET    DefenseId = @DefenseId${currentNumber}"&lt;br /&gt;    print "    ,      RunOffenseId = @RunOffenseId${currentNumber}"&lt;br /&gt;    print "    ,      PassOffenseId = @PassOffenseId${currentNumber}"&lt;br /&gt;    print "    WHERE  TeamName = '${CurrentTeam.Name}'"&lt;br /&gt;    print "END"&lt;br /&gt;    print ""&lt;br /&gt;&lt;br /&gt;[Meta]&lt;br /&gt;public static def define(expression as StringLiteralExpression, block as BlockExpression):	&lt;br /&gt;    return [|&lt;br /&gt;        _currentTeam.Name = $(expression.Value)	&lt;br /&gt;        DefineTeam($block)&lt;br /&gt;    |]&lt;br /&gt;&lt;br /&gt;[Meta]&lt;br /&gt;public static def defense(expression as StringLiteralExpression):&lt;br /&gt;    return [|&lt;br /&gt;        _currentTeam.Defense = $(expression.Value)	&lt;br /&gt;    |]&lt;br /&gt;&lt;br /&gt;[Meta]&lt;br /&gt;public static def pass_offense(expression as StringLiteralExpression, withQbType as MethodInvocationExpression):	&lt;br /&gt;    return [|&lt;br /&gt;        _currentTeam.PassOffense = $(expression.Value)	&lt;br /&gt;        $withQbType&lt;br /&gt;    |]&lt;br /&gt;&lt;br /&gt;[Meta]&lt;br /&gt;public static def run_offense(expression as StringLiteralExpression):&lt;br /&gt;    return [|&lt;br /&gt;        _currentTeam.RunOffense = $(expression.Value)	&lt;br /&gt;    |]&lt;br /&gt;&lt;br /&gt;[Meta]&lt;br /&gt;public static def with_qb_type(qbType as StringLiteralExpression):&lt;br /&gt;    return [|&lt;br /&gt;        _currentTeam.QbType = $(qbType.Value)&lt;br /&gt;    |]&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;(NOTE: Whitespace is significant by default in Boo, and I've tinkered with it a bit here, so this wouldn't actually compile.)&lt;/p&gt;&lt;p&gt;That's &lt;i&gt;really&lt;/i&gt; all there is to it. This class contains the bulk of the work. The meta methods are static, and don't need to be members on the base class, but it's a little easier to follow the flow of method calls this way. Now all I need to do is wire up the implicit base class and run the script.  Rhino DSL does this for me:&lt;/p&gt;&lt;pre class="brush: python"&gt;import System&lt;br /&gt;import System.IO&lt;br /&gt;import Rhino.DSL&lt;br /&gt;&lt;br /&gt;factory = DslFactory()&lt;br /&gt;factory.BaseDirectory = System.AppDomain.CurrentDomain.BaseDirectory&lt;br /&gt;factory.Register[of TeamDefinitionScript](TeamDefinitionDslEngine())&lt;br /&gt;&lt;br /&gt;scriptPath = Path.Combine(factory.BaseDirectory, "Scripts\\TeamDefinitions.boo")&lt;br /&gt;&lt;br /&gt;script = factory.Create[of TeamDefinitionScript](scriptPath)&lt;br /&gt;script.Prepare()&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;(NOTE: This script runner console is a different assembly than the one with the script base class.)&lt;/p&gt;&lt;p&gt;I run it, and this is the output (for the last declaration only):&lt;/p&gt;&lt;pre class="brush: sql"&gt;DECLARE @DefenseId4 INT&lt;br /&gt;SELECT  @DefenseId4 = DefenseId FROM Defense WHERE DefenseTypeName = 'Opportunistic'&lt;br /&gt;DECLARE @RunOffenseId4 INT&lt;br /&gt;SELECT  @RunOffenseId4 = RunOffenseId FROM RunOffense WHERE RunOffenseTypeName = 'Serviceable'&lt;br /&gt;DECLARE @PassOffenseId4 INT&lt;br /&gt;DECLARE @QbTypeId4        INT&lt;br /&gt;SELECT  @QbTypeId4 = QbTypeId FROM QbType WHERE QbTypeName = 'Rising Star'&lt;br /&gt;SELECT  @PassOffenseId4 = PassOffenseId FROM PassOffense WHERE PassOffenseTypeName = 'Explosive' AND QbTypeId = @QbTypeId&lt;br /&gt;&lt;br /&gt;IF NOT EXISTS (SELECT 1 FROM Teams WHERE TeamName = 'New Orleans Saints')&lt;br /&gt;BEGIN&lt;br /&gt;INSERT INTO Teams (TeamName, DefenseId, RunOffenseId, PassOffenseId)&lt;br /&gt;VALUES        (New Orleans Saints, @DefenseId4, @RunOffenseId4, @PassOffenseId4)END&lt;br /&gt;ELSE&lt;br /&gt;BEGIN&lt;br /&gt;UPDATE Teams&lt;br /&gt;SET    DefenseId = @DefenseId4&lt;br /&gt;,      RunOffenseId = @RunOffenseId4&lt;br /&gt;,      PassOffenseId = @PassOffenseId4&lt;br /&gt;WHERE  TeamName = 'New Orleans Saints'&lt;br /&gt;END&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Pretty simple. Boo makes everything so easy, you can concentrate on developing syntax and language features instead of hacking out code.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-7868356756266995299?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/7868356756266995299/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=7868356756266995299' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/7868356756266995299'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/7868356756266995299'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2010/02/building-simple-data-definition-dsl.html' title='Building a Simple Data Definition DSL with Boo'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-9133205971128346760</id><published>2009-09-25T21:48:00.003-05:00</published><updated>2011-08-12T00:59:57.995-05:00</updated><title type='text'>A Single-Featured App – Introducing ‘Queue View’</title><content type='html'>&lt;p&gt;I’ve been working with &lt;a href="http://nservicebus.com/"&gt;NServiceBus&lt;/a&gt; at work lately, and it’s useful to be able to look at the messages that are landing in the queues. Unfortunately, the MMC snap-in provided by Microsoft is woefully inadequate when it comes to this task. There are some commercial tools available, but I thought I should be able to find a free tool out there somewhere with this seemingly simple functionality.&lt;/p&gt;&lt;p&gt;I found &lt;a href="http://www.archonaut.se/"&gt;Msmq Studio&lt;/a&gt;, a nice little app that enables you to do many different queue management tasks both locally and remotely. However, it doesn’t seem to work on my machine now (or any of the servers at work), though it did at one time. I need something reliably do &lt;strong&gt;one simple thing&lt;/strong&gt;, so I decided to take the opportunity to experiment with WPF, a platform for which I’ve never written an app. The result is what I’ve tentatively titled ‘Queue View’:&lt;/p&gt;&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_GdP3Wu-JVpE/Sr2CkmgkaCI/AAAAAAAAAAU/4ZV4efkOCdw/s1600-h/queueView.PNG"&gt;&lt;img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 147px;" src="http://2.bp.blogspot.com/_GdP3Wu-JVpE/Sr2CkmgkaCI/AAAAAAAAAAU/4ZV4efkOCdw/s400/queueView.PNG" border="0" alt=""id="BLOGGER_PHOTO_ID_5385604294729033762" /&gt;&lt;/a&gt;&lt;p&gt;&amp;#160;&lt;/p&gt;&lt;p&gt;This app does one thing and one thing only – it shows, in XML format, the contents of messages in private queues on the local machine (assuming, of course, the messages have been serialized and stored in XML). Here is some of the relevant code:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;public class MessageQueueGateway : IMessageQueueGateway&lt;br /&gt;{&lt;br /&gt;    #region IMessageQueueGateway Members&lt;br /&gt;&lt;br /&gt;    public MessageQueue[] GetPrivateQueuesByMachineName(string machineName)&lt;br /&gt;    {&lt;br /&gt;        return MessageQueue.GetPrivateQueuesByMachine(machineName);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class PlainXmlMessageFormatter : IMessageFormatter&lt;br /&gt;{&lt;br /&gt;    #region IMessageFormatter Members&lt;br /&gt;&lt;br /&gt;    public bool CanRead(Message message)&lt;br /&gt;    {&lt;br /&gt;        return true;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public object Read(Message message)&lt;br /&gt;    {&lt;br /&gt;        XmlTextReader xmlReader = new XmlTextReader(message.BodyStream)&lt;br /&gt;        {&lt;br /&gt;            WhitespaceHandling = WhitespaceHandling.Significant,&lt;br /&gt;            ProhibitDtd = true&lt;br /&gt;        };&lt;br /&gt;&lt;br /&gt;        var xml = XDocument.Load(xmlReader);&lt;br /&gt;&lt;br /&gt;        return xml.ToString();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void Write(Message message, object obj)&lt;br /&gt;    {&lt;br /&gt;        throw new NotImplementedException();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion&lt;br /&gt;&lt;br /&gt;    #region ICloneable Members&lt;br /&gt;&lt;br /&gt;    public object Clone()&lt;br /&gt;    {&lt;br /&gt;        throw new NotImplementedException();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #endregion&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Because of the way I used it, there really was no reason to make &lt;strong&gt;PlainXmlMessageFormatter&lt;/strong&gt; implement the &lt;strong&gt;IMessageFormatter&lt;/strong&gt; from &lt;strong&gt;System.Messaging&lt;/strong&gt;, but I figured, “Why the hell not?”&lt;/p&gt;&lt;p&gt;In the UI, the main form’s controller has an event handler that looks like this:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;private void view_MessageSelected(object sender, MessageSelectedEventArgs e)&lt;br /&gt;{&lt;br /&gt;    selectedMessage = (from message in selectedQueue.GetAllMessages()&lt;br /&gt;                       where message.Id == e.SelectedMessageIdentifier.FullIdentifier&lt;br /&gt;                       select message).SingleOrDefault();&lt;br /&gt;&lt;br /&gt;    var messageBodyFormatter = new PlainXmlMessageFormatter();&lt;br /&gt;    var messageBody = messageBodyFormatter.Read(selectedMessage).ToString();&lt;br /&gt;&lt;br /&gt;    view.DisplayMessageBody(messageBody);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;You can get the code &lt;a href="http://continuous-disintegration.googlecode.com/svn/trunk/MSMQView/"&gt;here&lt;/a&gt;. The solution was created in VS 2010 Beta 1. Binaries are included in the ‘Build’ folder. This is essentially pre-alpha software. If you run it on a machine that doesn’t have .NET 3.5 or MSMQ 3.0 installed, it will probably explode.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-9133205971128346760?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/9133205971128346760/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=9133205971128346760' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/9133205971128346760'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/9133205971128346760'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2009/09/single-featured-app-introducing-queue.html' title='A Single-Featured App – Introducing ‘Queue View’'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_GdP3Wu-JVpE/Sr2CkmgkaCI/AAAAAAAAAAU/4ZV4efkOCdw/s72-c/queueView.PNG' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-2973269369177376469</id><published>2009-07-18T17:33:00.002-05:00</published><updated>2011-08-12T01:03:33.295-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Data Access'/><title type='text'>Adapting DataRow to IDataRecord</title><content type='html'>&lt;p&gt;You can find code for adapting a DataRow to the IDataRecord interface all over the place. One scenario in which this might be useful is [when the dregs of coding society are forced to perform] mapping the results of a database call to a custom object with the results sometimes coming back as a DataSet and sometimes as a DataReader.&lt;/p&gt;&lt;p&gt;IDataRecord has a lot of members that you probably wouldn’t use, simply because they are for retrieving strongly-typed values from the record based on numeric index. You’re probably doing these conversions manually and getting the values by named index. If that’s the case, why not constrain the consumption of these types with the following interface:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;public interface IIndexedDataRecord&lt;br /&gt;{&lt;br /&gt;    object this[string name] { get; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;and these adapters:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;public class DataReaderAdapter : IIndexedDataRecord&lt;br /&gt;{&lt;br /&gt;    private readonly IDataReader reader;&lt;br /&gt;&lt;br /&gt;    public DataReaderAdapter(IDataReader reader)&lt;br /&gt;    {&lt;br /&gt;        this.reader = reader;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public object this[string name]&lt;br /&gt;    {&lt;br /&gt;        get { return reader[name]; }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public class DataRowAdapter : IIndexedDataRecord&lt;br /&gt;{&lt;br /&gt;    private readonly DataRow row;&lt;br /&gt;&lt;br /&gt;    public DataRowAdapter(DataRow row)&lt;br /&gt;    {&lt;br /&gt;        this.row = row;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public object this[string name]&lt;br /&gt;    {&lt;br /&gt;        get { return row[name]; }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;I think if I were designing a data layer that used plain ADO.NET (which I would never do), I would use this simplified interface. Of course, the drawback is there would be a need to adapt both IDataReaders and DataRows when passing them to consuming methods, whereas only DataRows would need to be adapted when consuming methods are programmed to the IDataRecord interface.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-2973269369177376469?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/2973269369177376469/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=2973269369177376469' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/2973269369177376469'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/2973269369177376469'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2009/07/adapting-datarow-to-idatarecord.html' title='Adapting DataRow to IDataRecord'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-6809219629640019904</id><published>2009-04-17T11:18:00.001-05:00</published><updated>2009-07-18T20:39:15.161-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ASP.NET MVC'/><title type='text'>I Like to Make Judgments About Things I Am Far from Qualified to Judge</title><content type='html'>&lt;p&gt;I’ve read a few &lt;a href="http://ayende.com/Blog/archive/2009/04/17/kobe-ndash-in-the-nuts-amp-bolts-and-donrsquot-really.aspx"&gt;posts&lt;/a&gt;&amp;#160;&lt;a href="http://codebetter.com/blogs/karlseguin/archive/2009/04/16/kobe-oh-dead-lord-why.aspx"&gt;about&lt;/a&gt;&amp;#160;&lt;a href="http://weblogs.asp.net/rashid/archive/2009/04/16/kobe-ms-new-web-2-0-resource-kit-in-asp-net-mvc-and-my-thoughts.aspx"&gt;Kobe&lt;/a&gt;, a new sample ASP.NET MVC application &lt;em&gt;intended to provide guidance&lt;/em&gt; for web application development. One thing that really jumps out at me (taking the bloggers at their word) as a glaring mistake is the absence of &lt;em&gt;any&lt;/em&gt; unit tests. I mean, &lt;a href="http://www.asp.net/mvc/"&gt;isn't testing one of the driving factors for the creation of ASP.NET MVC&lt;/a&gt; (second bullet point)?&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-6809219629640019904?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/6809219629640019904/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=6809219629640019904' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/6809219629640019904'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/6809219629640019904'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2009/04/i-like-to-make-judgments-about-things-i.html' title='I Like to Make Judgments About Things I Am Far from Qualified to Judge'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-8031152099316546388</id><published>2009-04-15T17:47:00.001-05:00</published><updated>2009-07-18T20:37:50.492-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rhino Mocks'/><title type='text'>Rhino Mocks Caveat: Expect.Call / Setup.For / Stubs and Defaults</title><content type='html'>&lt;p&gt;I got bitten by not knowing some Rhino Mocks API details today. I had some tests written a certain way which were passing and some others written the same way which were failing. (Code can be found &lt;a href="http://groups.google.com/group/RhinoMocks/browse_thread/thread/8d9e8ba9861a8fc1"&gt;here&lt;/a&gt;.) In the case of the successful tests, Rhino Mocks appeared to be properly returning a mock object when a property was called on another mock, and in the case of the failing tests it was returning nulls for the property on a mocked object. There didn’t appear to be any difference in the way I needed to declare and setup the mocks used in the test, but there was a subtle one: the code that passed the tests only accessed the property &lt;strong&gt;once&lt;/strong&gt;, whereas the code that failed accessed it &lt;strong&gt;multiple times&lt;/strong&gt;. Because of the way I set up my mocks, a mock was returned for the property the first time it was accessed only.&lt;/p&gt;  &lt;p&gt;If you use &lt;strong&gt;Expect.Call(…).Return(someObject)&lt;/strong&gt;, by default the method/property will only return the specified object &lt;strong&gt;once&lt;/strong&gt;. If you use a stub or &lt;strong&gt;SetupResult.For(…).Return(someObject)&lt;/strong&gt;, by default the method/property will return the specified object as many times as it is called.&lt;/p&gt;  &lt;p&gt;Since I prefer the consistency of using &lt;strong&gt;Expect.Call&lt;/strong&gt; for any kind of expectation (and I think it reads better), I used &lt;strong&gt;Expect.Call(…).Return(someObject).Repeat.Any()&lt;/strong&gt; to allow the property to return what I wanted every time it was called.&lt;/p&gt;  &lt;p&gt;File this under the &lt;a href="http://ayende.com/Blog/archive/2008/02/25/Zero-Friction-and-why-Defaults-Matters.aspx"&gt;importance of defaults&lt;/a&gt;.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-8031152099316546388?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/8031152099316546388/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=8031152099316546388' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/8031152099316546388'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/8031152099316546388'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2009/04/rhino-mocks-caveat-expectcall-setupfor.html' title='Rhino Mocks Caveat: Expect.Call / Setup.For / Stubs and Defaults'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-3132165853075909883</id><published>2009-04-11T20:42:00.002-05:00</published><updated>2011-08-12T01:18:20.138-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rhino Mocks'/><title type='text'>Strongly-Typed Property Constraints in Rhino Mocks</title><content type='html'>&lt;p&gt;&lt;strong&gt;UPDATE: &lt;/strong&gt;As I suspected, this functionality was right in front of my face – it’s called &lt;strong&gt;PredicateConstraint&lt;/strong&gt; in Rhino Mocks. I also realize that I managed to completely ignore the existence of &lt;strong&gt;Predicate&amp;lt;T&amp;gt;&lt;/strong&gt; in the framework, and write my own predicate delegate. Hey, I was on a roll.&lt;/p&gt;&lt;hr /&gt;&lt;p&gt;Rhino Mocks has a &lt;strong&gt;PropertyConstraint&lt;/strong&gt; class that allows you to check the values on properties of objects passed into the method as part of the verification for that method being called. Unfortunately, the name of the property is specified as a string, which means the benefits of strong-typing that Rhino Mocks is normally so good at preserving are lost. Here’s an example (using Rhino Mocks 3.3 and .NET 2.0):&lt;/p&gt;&lt;pre class="brush: csharp"&gt;[Test]&lt;br /&gt;public void Main_Form_Should_Show_Start_Panel_On_Load()&lt;br /&gt;{&lt;br /&gt;    MockRepository mockRepository = new MockRepository();&lt;br /&gt;    IMainFormView mockView = mockRepository.DynamicMock&amp;lt;IMainFormView&gt;();&lt;br /&gt;&lt;br /&gt;    IEventRaiser loadEventRaiser = GetEventRaiserFor(delegate { mockView.Load += null; });&lt;br /&gt;    Expect.Call(&lt;br /&gt;        delegate&lt;br /&gt;        {&lt;br /&gt;            mockView.SetMainFormControlVisibility(null);&lt;br /&gt;        }).Constraints(new PropertyConstraint("StartPanelIsVisible", Is.Equal(true)));&lt;br /&gt;    mockRepository.ReplayAll();&lt;br /&gt;&lt;br /&gt;    IMainFormController controllerUnderTest = new MainFormController(mockView);&lt;br /&gt;    loadEventRaiser.Raise(mockView, EventArgs.Empty);&lt;br /&gt;&lt;br /&gt;    mockRepository.VerifyAll();            &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Basically, the view’s method &lt;strong&gt;SetMainFormControlVisibility&lt;/strong&gt; takes an object with a property called &lt;strong&gt;StartPanelIsVisible&lt;/strong&gt;. We want to make sure that when the controller calls this method, this property is set to &lt;strong&gt;true&lt;/strong&gt; on the parameter object. In fact, that is the sole reason for the existence of this test. Using a string to specify the property name isn’t very conducive to refactoring, and it would be nice to have intellisense and compile-time argument checking available when we specify the constraints for an object’s state. I found myself writing this class:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;public class PropertyConstraint&amp;lt;T&gt; : AbstractConstraint where T : class&lt;br /&gt;{&lt;br /&gt;    public delegate bool ConfirmPropertyState&amp;lt;U&gt;(U statefulObject);&lt;br /&gt;    private readonly ConfirmPropertyState&amp;lt;T&gt; confirmPropertiesMatch;&lt;br /&gt;&lt;br /&gt;    public PropertyConstraint(ConfirmPropertyState&amp;lt;T&gt; confirmPropertiesMatch)&lt;br /&gt;    {&lt;br /&gt;        this.confirmPropertiesMatch = confirmPropertiesMatch;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public override bool Eval(object obj)&lt;br /&gt;    {&lt;br /&gt;        AssertObjectIsCorrectType(obj);&lt;br /&gt;        T objectToConfirmStateOf = Cast(obj);&lt;br /&gt;&lt;br /&gt;        return confirmPropertiesMatch(objectToConfirmStateOf);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public override string Message&lt;br /&gt;    {&lt;br /&gt;        get { return String.Format(&lt;br /&gt;            "The properties of the passed in {0} do not match the expectations of the constraint.", &lt;br /&gt;            typeof(T).FullName); }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private static void AssertObjectIsCorrectType(object obj)&lt;br /&gt;    {&lt;br /&gt;        if (!(obj is T))&lt;br /&gt;        {&lt;br /&gt;            throw new ArgumentException(&lt;br /&gt;                String.Format(&lt;br /&gt;                    "PropertyConstraint expected to evaluate an object of type {0} but was pass an object of type {1}",&lt;br /&gt;                    typeof (T).FullName,&lt;br /&gt;                    obj.GetType().FullName));&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private static T Cast(object obj)&lt;br /&gt;    {&lt;br /&gt;        return obj as T;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;Which changes our test to look like this:&lt;/p&gt;&lt;pre class="brush: csharp"&gt;[Test]&lt;br /&gt;public void Main_Form_Should_Show_Start_Panel_On_Load()&lt;br /&gt;{&lt;br /&gt;    MockRepository mockRepository = new MockRepository();&lt;br /&gt;    IMainFormView mockView = mockRepository.DynamicMock&amp;lt;IMainFormView&gt;();&lt;br /&gt;&lt;br /&gt;    IEventRaiser loadEventRaiser = GetEventRaiserFor(delegate { mockView.Load += null; });&lt;br /&gt;    PropertyConstraint&amp;lt;MainFormControlVisibility&gt; startPanelIsVisible = &lt;br /&gt;        new PropertyConstraint&amp;lt;MainFormControlVisibility&gt;(&lt;br /&gt;            delegate(MainFormControlVisibility match) &lt;br /&gt;            {&lt;br /&gt;                return match.StartPanelIsVisible; &lt;br /&gt;            });&lt;br /&gt;    Expect.Call(&lt;br /&gt;        delegate&lt;br /&gt;        {&lt;br /&gt;            mockView.SetMainFormControlVisibility(null);&lt;br /&gt;        }).Constraints(startPanelIsVisible);&lt;br /&gt;    mockRepository.ReplayAll();&lt;br /&gt;&lt;br /&gt;    IMainFormController controllerUnderTest = new MainFormController(mockView);&lt;br /&gt;    loadEventRaiser.Raise(mockView, EventArgs.Empty);&lt;br /&gt;&lt;br /&gt;    mockRepository.VerifyAll();&lt;br /&gt;}   &lt;br /&gt;&lt;/pre&gt;&lt;p&gt;I admit this is pretty clunky (it looks better with lambdas), but it achieves the object of getting rid of the string for property specification. &lt;/p&gt;&lt;p&gt;I’m almost sure something like this exists in Rhino Mocks as it is, but I couldn’t find it, so I thought I’d share this. Again, I’m using an older version of Rhino Mocks (3.3).&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-3132165853075909883?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/3132165853075909883/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=3132165853075909883' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3132165853075909883'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3132165853075909883'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2009/04/strongly-typed-property-constraints-in.html' title='Strongly-Typed Property Constraints in Rhino Mocks'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-4990156896671916112</id><published>2009-04-10T22:56:00.001-05:00</published><updated>2009-04-10T22:56:30.454-05:00</updated><title type='text'>The Misadventures of a .NET Dev</title><content type='html'>&lt;p&gt;Sooo... long time, no post! All zero readers of this blog might be curious about why I disappeared. The short story is I’ve been sidetracked by personal issues combined with a butt-ton (sorry to those in far away lands; I don’t know how to convert this to metric) of work at my paying gig. We’ve all been there and done that. I’m sure you can relate, non-existent reader. But I’m not making any more excuses! This post serves as a list of topics I want to cover in future posts. It’s long, so I doubt I’ll get to all of these.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;More ‘SharpMock’ – &lt;/strong&gt;I haven’t abandoned this project, but I was saddened when I realized I had forgotten all I learned about PostSharp when I cracked open the [smelly from having gone so long without bathing] spike code. &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Creating DSLs with MGrammar&lt;/strong&gt; – I’ve noticed a lot of bloggers are unsure about the vision Microsoft has for ‘Oslo’. Count me among them. But I definitely have had some fun playing around with Intellipad and MGrammar recently. I see a lot of potential for making my development life easier when it comes to &lt;em&gt;maintaining&lt;/em&gt; metadata. I also have an idea for a little project to make it easier to author certain scripts that perform a certain development function which currently depend on some ugly XML (I’m awesome at starting projects and terrible at finishing them). &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;ASP.NET WebForms and the MVP Pattern: What &lt;em&gt;Not&lt;/em&gt; to Do&lt;/strong&gt; – I wish I had time to even play the the new (or old for that matter) MVC bits. I wish I had time to learn Silverlight 3 (or 2, or 1 for that matter). I wish I had time to use jQuery (or some other cool JS framework for that matter) and improve my piss poor JavaScript skills. Alas, we’re stuck in the stone age of web development at my job. I’ve done my best to reduce code duplication and improve testability with the MVP pattern, and along the way I’ve done a lot of stupid things that I think others should avoid. Actually, I probably shouldn’t write about MVP at all. Meh. &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Persisting Abstract Expression Trees: What &lt;em&gt;Not&lt;/em&gt; to Do –&lt;/strong&gt; Again, the stone age (hmm, I should probably be capitalizing that) of development means not using an ORM. I have some advice about what to avoid if you have to persist expression trees &lt;em&gt;and&lt;/em&gt; write all of the data access code. This will mainly be about persisting inheritance hierarchies (table per class, table per subclass, etc.) and coping with object model changes. &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Building a LINQ Provider&lt;/strong&gt; – I have no idea why, but I want to do this. I’m specifically thinking of a fun little project called either ‘LINQ to MP3’ or ‘LINQ to ID3’ (I’m good at naming things and horrible and building them). I figure it’s time to start learning .NET 3.5 since .NET 4.0 will be out sometime soon. On that note… &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;.NET Certification Fun!&lt;/strong&gt; – I never got any MS development certifications (I did manage to fail one test… seriously), and I’ve listed getting my MCPD as a goal at work. I have some opinions on the certifications in general, and occasionally I run across interesting things in the process of studying (okay, I don’t study). I’ll blog about this. P.S. We’re talking .NET &lt;em&gt;2.0&lt;/em&gt; here :( &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Ruby, Ruby, Rubyyyyy&lt;/strong&gt; – I’m not talking about a Kaiser Chiefs song. I’ve been playing around with Ruby a little (and reading &lt;a href="http://poignantguide.net/ruby/"&gt;Why's (Poignant) Guide to Ruby&lt;/a&gt;, which is absolutely hilarious), and it’s a lot of fun. I actually probably won’t blog about this, as I don’t have much to say. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Well, that’s all I can think of for now. Talk to you again in 6 months!&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-4990156896671916112?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/4990156896671916112/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=4990156896671916112' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/4990156896671916112'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/4990156896671916112'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2009/04/misadventures-of-net-dev.html' title='The Misadventures of a .NET Dev'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-9051724777499103168</id><published>2008-11-09T14:53:00.001-06:00</published><updated>2009-07-18T20:38:51.494-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='PostSharp'/><category scheme='http://www.blogger.com/atom/ns#' term='SharpMock'/><title type='text'>Hello, PostCompiler World!</title><content type='html'>&lt;p&gt;Sometimes doing the simplest things is difficult. In order to make any headway on SharpMock, I’ll need to be able to understand the basics of PostSharp. What could be more basic than getting PostSharp to execute a task that ouputs a ‘Hello World’ message during the postcompilation process? We’re not decorating any types with attributes; we’re not intercepting any calls; we’re not outputting any IL. This should be a snap! And yet, I haven’t posted in weeks….&lt;/p&gt;  &lt;p&gt;First thing’s first – we need a ‘Hello World’ task. In a project called &lt;strong&gt;PostSharpPlugin&lt;/strong&gt; I have defined the following class:&lt;/p&gt; &lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;style type="text/css"&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;.csharpcode, .csharpcode pre&lt;br /&gt;{&lt;br /&gt;	font-size: small;&lt;br /&gt;	color: black;&lt;br /&gt;	font-family: consolas, "Courier New", courier, monospace;&lt;br /&gt;	background-color: #ffffff;&lt;br /&gt;	/*white-space: pre;*/&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;.csharpcode pre { margin: 0em; }&lt;br /&gt;&lt;br /&gt;.csharpcode .rem { color: #008000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .kwrd { color: #0000ff; }&lt;br /&gt;&lt;br /&gt;.csharpcode .str { color: #006080; }&lt;br /&gt;&lt;br /&gt;.csharpcode .op { color: #0000c0; }&lt;br /&gt;&lt;br /&gt;.csharpcode .preproc { color: #cc6633; }&lt;br /&gt;&lt;br /&gt;.csharpcode .asp { background-color: #ffff00; }&lt;br /&gt;&lt;br /&gt;.csharpcode .html { color: #800000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .attr { color: #ff0000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .alt &lt;br /&gt;{&lt;br /&gt;	background-color: #f4f4f4;&lt;br /&gt;	width: 100%;&lt;br /&gt;	margin: 0em;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;.csharpcode .lnum { color: #606060; }&lt;/style&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; PostSharp.Extensibility;&lt;br /&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;namespace&lt;/span&gt; PostSharpPlugin&lt;br /&gt;{&lt;br /&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; SayHelloTask : Task&lt;br /&gt;    {&lt;br /&gt;        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; Execute()&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Hello, PostCompiler!&amp;quot;&lt;/span&gt;);&lt;br /&gt;&lt;br /&gt;            &lt;span class="rem"&gt;// Task executed successfully&lt;/span&gt;&lt;br /&gt;            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;true&lt;/span&gt;;&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;I have also created a .psplugin file that looks like this:&lt;/p&gt;&lt;br /&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;style type="text/css"&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;.csharpcode, .csharpcode pre&lt;br /&gt;{&lt;br /&gt;	font-size: small;&lt;br /&gt;	color: black;&lt;br /&gt;	font-family: consolas, "Courier New", courier, monospace;&lt;br /&gt;	background-color: #ffffff;&lt;br /&gt;	/*white-space: pre;*/&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;.csharpcode pre { margin: 0em; }&lt;br /&gt;&lt;br /&gt;.csharpcode .rem { color: #008000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .kwrd { color: #0000ff; }&lt;br /&gt;&lt;br /&gt;.csharpcode .str { color: #006080; }&lt;br /&gt;&lt;br /&gt;.csharpcode .op { color: #0000c0; }&lt;br /&gt;&lt;br /&gt;.csharpcode .preproc { color: #cc6633; }&lt;br /&gt;&lt;br /&gt;.csharpcode .asp { background-color: #ffff00; }&lt;br /&gt;&lt;br /&gt;.csharpcode .html { color: #800000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .attr { color: #ff0000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .alt &lt;br /&gt;{&lt;br /&gt;	background-color: #f4f4f4;&lt;br /&gt;	width: 100%;&lt;br /&gt;	margin: 0em;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;.csharpcode .lnum { color: #606060; }&lt;/style&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;?&lt;/span&gt;&lt;span class="html"&gt;xml&lt;/span&gt; &lt;span class="attr"&gt;version&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;1.0&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;encoding&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;utf-8&amp;quot;&lt;/span&gt; ?&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;PlugIn&lt;/span&gt; &lt;span class="attr"&gt;xmlns&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;http://schemas.postsharp.org/1.0/configuration&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;TaskType&lt;/span&gt; &lt;span class="attr"&gt;Name&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;SayHello&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Implementation&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;PostSharpPlugin.SayHelloTask, PostSharpPlugin&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Phase&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Analyze&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;TaskType&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;PlugIn&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;So, there we have a plugin that will perform some tasks during postcompilation. We want this task to be performed during postcompilation of some other assembly if it references this plugin, so we need some way to tell PostSharp about this requirement. To do so, we add an attribute to &lt;strong&gt;PostSharpPlugin&lt;/strong&gt;:&lt;/p&gt;&lt;br /&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;style type="text/css"&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;.csharpcode, .csharpcode pre&lt;br /&gt;{&lt;br /&gt;	font-size: small;&lt;br /&gt;	color: black;&lt;br /&gt;	font-family: consolas, "Courier New", courier, monospace;&lt;br /&gt;	background-color: #ffffff;&lt;br /&gt;	/*white-space: pre;*/&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;.csharpcode pre { margin: 0em; }&lt;br /&gt;&lt;br /&gt;.csharpcode .rem { color: #008000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .kwrd { color: #0000ff; }&lt;br /&gt;&lt;br /&gt;.csharpcode .str { color: #006080; }&lt;br /&gt;&lt;br /&gt;.csharpcode .op { color: #0000c0; }&lt;br /&gt;&lt;br /&gt;.csharpcode .preproc { color: #cc6633; }&lt;br /&gt;&lt;br /&gt;.csharpcode .asp { background-color: #ffff00; }&lt;br /&gt;&lt;br /&gt;.csharpcode .html { color: #800000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .attr { color: #ff0000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .alt &lt;br /&gt;{&lt;br /&gt;	background-color: #f4f4f4;&lt;br /&gt;	width: 100%;&lt;br /&gt;	margin: 0em;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;.csharpcode .lnum { color: #606060; }&lt;/style&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="csharpcode"&gt;[assembly: ReferencingAssembliesRequirePostSharp(&lt;span class="str"&gt;&amp;quot;SayHello&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;PostSharpPlugin&amp;quot;&lt;/span&gt;)]&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;I have created another assembly called (very cleverly) &lt;strong&gt;ReferencingAssembly&lt;/strong&gt; and added a reference to &lt;strong&gt;PostSharpPlugin&lt;/strong&gt;. That assembly contains this .psproj file:&lt;/p&gt;&lt;br /&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;style type="text/css"&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;.csharpcode, .csharpcode pre&lt;br /&gt;{&lt;br /&gt;	font-size: small;&lt;br /&gt;	color: black;&lt;br /&gt;	font-family: consolas, "Courier New", courier, monospace;&lt;br /&gt;	background-color: #ffffff;&lt;br /&gt;	/*white-space: pre;*/&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;.csharpcode pre { margin: 0em; }&lt;br /&gt;&lt;br /&gt;.csharpcode .rem { color: #008000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .kwrd { color: #0000ff; }&lt;br /&gt;&lt;br /&gt;.csharpcode .str { color: #006080; }&lt;br /&gt;&lt;br /&gt;.csharpcode .op { color: #0000c0; }&lt;br /&gt;&lt;br /&gt;.csharpcode .preproc { color: #cc6633; }&lt;br /&gt;&lt;br /&gt;.csharpcode .asp { background-color: #ffff00; }&lt;br /&gt;&lt;br /&gt;.csharpcode .html { color: #800000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .attr { color: #ff0000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .alt &lt;br /&gt;{&lt;br /&gt;	background-color: #f4f4f4;&lt;br /&gt;	width: 100%;&lt;br /&gt;	margin: 0em;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;.csharpcode .lnum { color: #606060; }&lt;/style&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Project&lt;/span&gt; &lt;span class="attr"&gt;xmlns&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;http://schemas.postsharp.org/1.0/configuration&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;ReferenceDirectory&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{$ReferenceDirectory}&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;SearchPath&lt;/span&gt; &lt;span class="attr"&gt;Directory&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{$SearchPath}&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Using&lt;/span&gt; &lt;span class="attr"&gt;PlugInFile&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;../PostSharpPlugin/bin/Debug/PostSharpPlugin.psplugin&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Tasks&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;AutoDetect&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;SayHello&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Compile&lt;/span&gt; &lt;span class="attr"&gt;TargetFile&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{$Output}&amp;quot;&lt;/span&gt;&lt;br /&gt;     &lt;span class="attr"&gt;IntermediateDirectory&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{$IntermediateDirectory}&amp;quot;&lt;/span&gt;&lt;br /&gt;     &lt;span class="attr"&gt;CleanIntermediate&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{$CleanIntermediate}&amp;quot;&lt;/span&gt;&lt;br /&gt;     &lt;span class="attr"&gt;SignAssembly&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{$SignAssembly}&amp;quot;&lt;/span&gt;&lt;br /&gt;     &lt;span class="attr"&gt;PrivateKeyLocation&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{$PrivateKeyLocation}&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Tasks&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Project&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;The &lt;strong&gt;Using&lt;/strong&gt; element tells PostSharp where to get the definition for the task &lt;strong&gt;SayHello&lt;/strong&gt;. This is critical. I spent every spare hour I had for weeks trying to get this seemingly simple example to work without defining or importing the definition of the &lt;strong&gt;SayHello&lt;/strong&gt; task in this file. In fact, I don’t think I should have to explicitly specify the &lt;strong&gt;SayHello&lt;/strong&gt; task to be executed here either. All the tracing, debugging, and specifying different search paths I could do didn’t help me get this example working, so for now importing the task definition like so is the solution I’m rolling with. It will allow us to make some headway, like figuring out how to check a test assembly for methods that need to be mocked. Ultimately, though, we’ll need PostSharp to automatically detect and use tasks that provide services like &lt;strong&gt;ICustomAttributeProvider&lt;/strong&gt;, and this solution won’t handle that.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Oh, by the way, don’t forget that we need to invoke PostSharp when we compile our assembly. For that we need to import the PostSharp MSBuild task. The modified &lt;strong&gt;ReferencingAssembly.csproj&lt;/strong&gt; file for this example looks like this at the end (the second element is what has been added):&lt;/p&gt;&lt;br /&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;style type="text/css"&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;.csharpcode, .csharpcode pre&lt;br /&gt;{&lt;br /&gt;	font-size: small;&lt;br /&gt;	color: black;&lt;br /&gt;	font-family: consolas, "Courier New", courier, monospace;&lt;br /&gt;	background-color: #ffffff;&lt;br /&gt;	/*white-space: pre;*/&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;.csharpcode pre { margin: 0em; }&lt;br /&gt;&lt;br /&gt;.csharpcode .rem { color: #008000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .kwrd { color: #0000ff; }&lt;br /&gt;&lt;br /&gt;.csharpcode .str { color: #006080; }&lt;br /&gt;&lt;br /&gt;.csharpcode .op { color: #0000c0; }&lt;br /&gt;&lt;br /&gt;.csharpcode .preproc { color: #cc6633; }&lt;br /&gt;&lt;br /&gt;.csharpcode .asp { background-color: #ffff00; }&lt;br /&gt;&lt;br /&gt;.csharpcode .html { color: #800000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .attr { color: #ff0000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .alt &lt;br /&gt;{&lt;br /&gt;	background-color: #f4f4f4;&lt;br /&gt;	width: 100%;&lt;br /&gt;	margin: 0em;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;.csharpcode .lnum { color: #606060; }&lt;/style&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="csharpcode"&gt;  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Import&lt;/span&gt; &lt;span class="attr"&gt;Project&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;$(MSBuildToolsPath)\Microsoft.CSharp.targets&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;br /&gt;  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Import&lt;/span&gt; &lt;span class="attr"&gt;Project&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;..\ThirdParty\PostSharp.targets&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;I have uploaded the code for this example &lt;a href="http://continuous-disintegration.googlecode.com/svn/trunk/HelloPostCompilerWorld/"&gt;here&lt;/a&gt;. I have included all of the needed PostSharp files in the &lt;strong&gt;ThirdParty&lt;/strong&gt; directory. (I’m not sure this distribution is allowed.) So, it should “just work”… you can open the solution in Visual Studio, build, and see something like this in the build output window:&lt;/p&gt;&lt;br /&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;style type="text/css"&gt;&lt;br /&gt;&lt;br /&gt;.csharpcode, .csharpcode pre&lt;br /&gt;{&lt;br /&gt;	font-size: small;&lt;br /&gt;	color: black;&lt;br /&gt;	font-family: consolas, "Courier New", courier, monospace;&lt;br /&gt;	background-color: #ffffff;&lt;br /&gt;	/*white-space: pre;*/&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;.csharpcode pre { margin: 0em; }&lt;br /&gt;&lt;br /&gt;.csharpcode .rem { color: #008000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .kwrd { color: #0000ff; }&lt;br /&gt;&lt;br /&gt;.csharpcode .str { color: #006080; }&lt;br /&gt;&lt;br /&gt;.csharpcode .op { color: #0000c0; }&lt;br /&gt;&lt;br /&gt;.csharpcode .preproc { color: #cc6633; }&lt;br /&gt;&lt;br /&gt;.csharpcode .asp { background-color: #ffff00; }&lt;br /&gt;&lt;br /&gt;.csharpcode .html { color: #800000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .attr { color: #ff0000; }&lt;br /&gt;&lt;br /&gt;.csharpcode .alt &lt;br /&gt;{&lt;br /&gt;	background-color: #f4f4f4;&lt;br /&gt;	width: 100%;&lt;br /&gt;	margin: 0em;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;.csharpcode .lnum { color: #606060; }&lt;/style&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="csharpcode"&gt;...&lt;br /&gt;PostSharp 1.0 [1.0.11.424] - Copyright (c) Gael Fraiteur, 2005-2008.&lt;br /&gt;&lt;br /&gt;Hello, PostCompiler!&lt;br /&gt;...&lt;/pre&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-9051724777499103168?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/9051724777499103168/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=9051724777499103168' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/9051724777499103168'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/9051724777499103168'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2008/11/hello-postcompiler-world.html' title='Hello, PostCompiler World!'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-8478304536150553390</id><published>2008-10-17T00:12:00.004-05:00</published><updated>2009-07-18T20:38:51.495-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='PostSharp'/><category scheme='http://www.blogger.com/atom/ns#' term='SharpMock'/><title type='text'>Misindirection</title><content type='html'>&lt;p&gt;The first time I popped open the solution after I did my ‘SharpMock’ spike, I was met with a surprise – the one test was failing! Surely I didn’t commit a cardinal sin and write a post about something that didn’t even work. It turns out I had been messing around with the &lt;strong&gt;OnMethodInvocationAspectOptions&lt;/strong&gt; returned by overriding the &lt;strong&gt;GetOptions&lt;/strong&gt; method of &lt;strong&gt;OnMethodInvocationAspect&lt;/strong&gt;. Here’s the code that was in &lt;strong&gt;MockableAttribute&lt;/strong&gt;:&lt;/p&gt;  &lt;pre&gt;public override OnMethodInvocationAspectOptions GetOptions()&lt;br /&gt;{&lt;br /&gt;    return OnMethodInvocationAspectOptions.WeaveSiteCall;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;The original incarnation of &lt;strong&gt;Expect.Call(….)&lt;/strong&gt; took a string to specify which method on which class to call, so the test passed with the above code. Now we have this syntax:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;Expect.Call(() =&amp;gt; PersonDao.GetPerson(0), ryan);&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;And the test doesn't pass. This means that if we want to have syntax like this (and we do!), we have to do the weaving in the class we’re calling. Much more importantly, if we want to preserve this syntax and not modify the called class (and in the future we will!), we’ll have to intercept calls made &lt;em&gt;in the test&lt;/em&gt; as well.&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-8478304536150553390?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/8478304536150553390/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=8478304536150553390' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/8478304536150553390'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/8478304536150553390'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2008/10/misindirection.html' title='Misindirection'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-4431502761505456179</id><published>2008-10-17T00:12:00.001-05:00</published><updated>2009-07-18T20:38:51.495-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='PostSharp'/><category scheme='http://www.blogger.com/atom/ns#' term='SharpMock'/><title type='text'>One Post Wonder?</title><content type='html'>&lt;p&gt;I figured the first hurdle to tackle in proving that we can use PostSharp to bend assemblies to our unit testing wills was to get rid of the need to decorate the targets of our mocking desires with attributes. I spent some time going over the &lt;a href="http://doc.postsharp.org/1.0/"&gt;documentation&lt;/a&gt;, browsing the &lt;a href=""&gt;forums&lt;/a&gt;, and looking through samples. Gael pretty much told me in the comments to my previous post to look into &lt;b&gt;ICustomAttributeProvider&lt;/b&gt; and &lt;b&gt;CompoundAttribute&lt;/b&gt;. I tried and failed to implement ICustomAttributeProvider; I think I don't quite understand how a PS plugin works yet. I thought going through &lt;a href="http://www.sitechno.com/Blog/IntroducingEntityFrameworkContribEasyIPocoImplementationV01.aspx"&gt;Ruurd Boeke's examples&lt;/a&gt; would be enlightening... no such luck. So, instead of doing the smart thing and actually asking for help, I'm going to continue to waste time trying to figure it out on my own. &lt;/p&gt;  &lt;p&gt;Eventually I'll get fed up and ask for some help, but in the meantime I need to make some progress &lt;i&gt;somewhere&lt;/i&gt; in this experiment. I might as well take what I have done and at least build out some real functionality. This brings up a whole slew of interesting decisions I need to make: &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;How should I structure the solution? I'm going to put any serious decisions this off until I gain better understanding of the way PS works, the licensing issues, what it is I actually want to accomplish, whether or not it's feasible, etc. I'm making a note now that the structure of the solution is going to drastically change. &lt;/li&gt;    &lt;li&gt;What should the API look like? Do I support multiple models for constructing unit tests (Arrange/Act/Assert &lt;b&gt;and/or&lt;/b&gt; Record/Replay)? How do I initialize the mocks? What threading considerations do I need to make? &lt;/li&gt;    &lt;li&gt;How do I test? I plan on using TDD, but testing a framework &lt;i&gt;used for testing&lt;/i&gt; seems to throw me into some sort of backwards meta-testing scenario that just feels weird. &lt;/li&gt; &lt;/ul&gt; Since I can't clearly explain it, I probably need to illustrate what I mean by that last point.   &lt;p&gt;As it stands right now in my very simple implementation, the data about the calls that need to be faked, their arguments, and the faked return values are stored in static fields of the &lt;strong&gt;Expect&lt;/strong&gt; class. In order for tests to be atomic, independent units, these fields need to be reset for each test. The requirement is simple, but how do we write an individual test &lt;em&gt;to test&lt;/em&gt; this functionality? I don’t know either. What I ended up with was this:&lt;/p&gt;  &lt;pre&gt;[Test]&lt;br /&gt;public void Will_Get_Person_From_Mocked_Call()&lt;br /&gt;{&lt;br /&gt;    var ryan = new Person { Id = 11, Name = &amp;quot;Ryan&amp;quot; };&lt;br /&gt;&lt;br /&gt;    // Set the expectation for the dao call&lt;br /&gt;    Expect.Call(() =&amp;gt; PersonDao.GetPerson(0), ryan);&lt;br /&gt;&lt;br /&gt;    // Note that we don't care about the person id argument&lt;br /&gt;    var commandUnderTest = new PersonGetCommand();&lt;br /&gt;    var resultingPerson = commandUnderTest.Execute();&lt;br /&gt;&lt;br /&gt;    Assert.That(resultingPerson == ryan);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Test]&lt;br /&gt;public void Wont_Get_Person_From_Mocked_Call()&lt;br /&gt;{&lt;br /&gt;    var commandUnderTest = new PersonGetCommand();&lt;br /&gt;    var resultingPerson = commandUnderTest.Execute();&lt;br /&gt;&lt;br /&gt;    Assert.That(resultingPerson.Id != 11);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;These two tests work together to signal whether or not the Expectations are being correctly discarded at the end of a test/before the next test. If the second test fails, they aren’t. So I started with this, wrote some crappy code in the &lt;strong&gt;Expect&lt;/strong&gt; class, and ended up adding these setup and teardown methods to the &lt;strong&gt;TestFixture&lt;/strong&gt;:&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;[SetUp]&lt;br /&gt;public void InitializeMockFramework()&lt;br /&gt;{&lt;br /&gt;    Expect.Initialize();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[TearDown]&lt;br /&gt;public void UnloadMockFramework()&lt;br /&gt;{&lt;br /&gt;    Expect.UnLoad();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Don’t panic… I know this is ugly, especially considering what must be on the other side of Initialize and UnLoad, but this is strictly to illustrate a point – the whole fixture together functions as a single unit. Not ideal, but it’s the best solution I can come up with at the moment to &lt;em&gt;test testing&lt;/em&gt;. It allows me to refactor the Expect class and verify that I haven’t broken functionality.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;(Side thought: I’m thinking I should take a second look at that &lt;a href="http://www.amazon.com/"&gt;XUnit Test Patterns&lt;/a&gt; book; I labeled it ‘boring’ the first time I skimmed through it.)&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-4431502761505456179?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/4431502761505456179/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=4431502761505456179' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/4431502761505456179'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/4431502761505456179'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2008/10/one-post-wonder.html' title='One Post Wonder?'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-6429450025001655800</id><published>2008-10-12T14:29:00.001-05:00</published><updated>2009-07-18T20:38:51.495-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='PostSharp'/><category scheme='http://www.blogger.com/atom/ns#' term='SharpMock'/><title type='text'>Stubbing Static Methods with PostSharp</title><content type='html'>&lt;a href="http://www.typemock.com/"&gt;TypeMock&lt;/a&gt; uses the &lt;a href="http://msdn.microsoft.com/en-us/magazine/cc300553.aspx"&gt;Profiler API&lt;/a&gt; to allow &lt;a href="http://martinfowler.com/articles/mocksArentStubs.html"&gt;mocking, stubbing, etc.&lt;/a&gt; of classes used by code under test. It has the ability to handle sealed classes, static classes, non-virtual methods, and other troublesome-yet-oft-encountered scenarios in the world of unit testing. Other frameworks rely on proxies to intercept method calls, limiting them to be able to only fake virtual, abstract, and interface members. They also rely on &lt;a href="http://martinfowler.com/articles/injection.html"&gt;dependecy injection&lt;/a&gt; to place the proxies as the concrete implementation of calls to the abstracted interface members.&lt;br /&gt;&lt;br /&gt;Anyone working with a &lt;a href="http://www.amazon.com/Working-Effectively-Legacy-Robert-Martin/dp/0131177052"&gt;legacy codebase&lt;/a&gt; is bound to run into static method calls (especially in the data access layer), dependencies on concrete types with non-virtual methods, and sealed class dependencies (HttpContext anyone?). The only way to unit test this &lt;i&gt;without refactoring&lt;/i&gt; is with TypeMock. I've never used TypeMock, and I'm sure it's a great product, but it's not free. I decided to spike some code to see if I could solve the problem of mocking static method calls through &lt;a href="http://ayende.com/Blog/archive/2007/07/02/7-Approaches-for-AOP-in-.Net.aspx"&gt;AOP&lt;/a&gt; with &lt;a href="http://www.postsharp.org/"&gt;PostSharp&lt;/a&gt;. What I came up with was a pretty ugly solution with limited applicability that will probably help no one. Let's take a look!&lt;br /&gt;&lt;br /&gt;The example codebase is trivial: we have a &lt;b&gt;PersonGetCommand&lt;/b&gt; representing the business logic we want to test and a &lt;b&gt;PersonDao&lt;/b&gt; class with a static &lt;b&gt;GetPerson&lt;/b&gt; method representing a method we want to stub. &lt;b&gt;GetPerson&lt;/b&gt; returns, you guessed it, a &lt;b&gt;Person&lt;/b&gt;.&lt;br /&gt;&lt;br /&gt;To intercept calls to the static method, we're going to place a &lt;b&gt;MockableAttribute&lt;/b&gt; on the method. It looks like this:&lt;br /&gt;&lt;br /&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;br /&gt;&lt;pre class="csharpcode"&gt;&lt;br /&gt;[Mockable]&lt;br /&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Person GetPerson(&lt;span class="kwrd"&gt;int&lt;/span&gt; personId)&lt;br /&gt;{&lt;br /&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; Person { Id = personId, Name = String.Format(&lt;span class="str"&gt;"Person {0}"&lt;/span&gt;, personId) };&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The code for the attribute talks to our 'mock framework'. It looks like this:&lt;br /&gt;&lt;br /&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;br /&gt;&lt;pre class="csharpcode"&gt;&lt;br /&gt;[Serializable]&lt;br /&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MockableAttribute : OnMethodInvocationAspect&lt;br /&gt;{&lt;br /&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; OnInvocation(MethodInvocationEventArgs eventArgs)&lt;br /&gt;    {&lt;br /&gt;        MethodInfo invokedMethod = eventArgs.Delegate.Method;&lt;br /&gt;&lt;br /&gt;        &lt;span class="rem"&gt;// If this gets called during recording, we have to register the expectations&lt;/span&gt;&lt;br /&gt;        &lt;span class="kwrd"&gt;if&lt;/span&gt; (Expect.IsInRecordMode)&lt;br /&gt;        {&lt;br /&gt;            Expect.RegisterExpectedCall(invokedMethod);&lt;br /&gt;            Expect.RegisterExpectedArguments(invokedMethod, eventArgs.GetArgumentArray());&lt;br /&gt;            Expect.RegisterExpectedReturnValue(invokedMethod, Expect.CurrentlyExpectedReturnValue);&lt;br /&gt;        }&lt;br /&gt;        &lt;span class="rem"&gt;// If not, we need to check to see if we're mocking the method&lt;/span&gt;&lt;br /&gt;        &lt;span class="kwrd"&gt;else&lt;/span&gt;&lt;br /&gt;        {&lt;br /&gt;            &lt;span class="rem"&gt;// If it is mocked, we intercept the call&lt;/span&gt;&lt;br /&gt;            &lt;span class="kwrd"&gt;if&lt;/span&gt; (Expect.MethodIsMocked(invokedMethod))&lt;br /&gt;            {&lt;br /&gt;                eventArgs.ReturnValue = Expect.GetExpectedReturnValue(invokedMethod);&lt;br /&gt;            }&lt;br /&gt;            &lt;span class="rem"&gt;// Otherwise, we invoke the method&lt;/span&gt;&lt;br /&gt;            &lt;span class="kwrd"&gt;else&lt;/span&gt;&lt;br /&gt;            {&lt;br /&gt;                eventArgs.ReturnValue = eventArgs.Delegate.Method.Invoke(eventArgs.Delegate.Target, eventArgs.GetArgumentArray());&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;    &lt;br /&gt; To prove that the example codebase works correctly, we have this test:&lt;br /&gt; &lt;br /&gt; &lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;br /&gt;&lt;pre class="csharpcode"&gt;&lt;br /&gt;[Test]&lt;br /&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Will_Get_Person()&lt;br /&gt;{&lt;br /&gt;    var expectedName = &lt;span class="str"&gt;"Person 23"&lt;/span&gt;;&lt;br /&gt;    var personId = 23;&lt;br /&gt;&lt;br /&gt;    var commandUnderTest = &lt;span class="kwrd"&gt;new&lt;/span&gt; PersonGetCommand { PersonId = personId };&lt;br /&gt;    var resultingPerson = commandUnderTest.Execute();&lt;br /&gt;&lt;br /&gt;    Assert.That(resultingPerson.Name == expectedName);&lt;br /&gt;    Assert.That(resultingPerson.Id == personId);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;        &lt;br /&gt;And this test shows our &lt;b&gt;MockableAttribute&lt;/b&gt; (as well as our makeshift mock framework) in action:&lt;br /&gt;&lt;br /&gt;&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;&lt;br /&gt;&lt;pre class="csharpcode"&gt;&lt;br /&gt;[Test]&lt;br /&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Will_Get_Person_From_Mocked_Call()&lt;br /&gt;{&lt;br /&gt;    var ryan = &lt;span class="kwrd"&gt;new&lt;/span&gt; Person { Id = 11, Name = &lt;span class="str"&gt;"Ryan"&lt;/span&gt; };&lt;br /&gt;&lt;br /&gt;    &lt;span class="rem"&gt;// Set the expectation for the dao call&lt;/span&gt;&lt;br /&gt;    Expect.Call(&lt;span class="kwrd"&gt;delegate&lt;/span&gt; { PersonDao.GetPerson(0); }, ryan);&lt;br /&gt;&lt;br /&gt;    &lt;span class="rem"&gt;// Note that we don't care about the person id argument&lt;/span&gt;&lt;br /&gt;    var commandUnderTest = &lt;span class="kwrd"&gt;new&lt;/span&gt; PersonGetCommand();&lt;br /&gt;    var resultingPerson = commandUnderTest.Execute();&lt;br /&gt;&lt;br /&gt;    Assert.That(resultingPerson == ryan);       &lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;        &lt;br /&gt;Note that I chose a &lt;a href="http://ayende.com/projects/rhino-mocks.aspx"&gt;Rhino&lt;/a&gt;-like syntax for the expecations. Also note that we aren't really 'mocking' the call because we aren't verifying expectations or arguments. This could easily be done, however.&lt;br /&gt;&lt;br /&gt;This is all dreadfully simple thanks to PostSharp. But is this approach ready for primetime? It's far from it, in fact, and here are the reasons:&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;It only works for classes you control (and currently only for static methods). So if you're making a call to a static method in a third-party dll or a .NET framework class, this is useless.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Requires the use of an attribute. It may only be metadata, but testing concerns shouldn't be leaking into application source.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;It modifies that actual assemblies being tested. Technically, this approach tests only a modified-for-test assembly, not the assembly that we &lt;i&gt;want&lt;/i&gt; to release into production.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;The assembly under test requires a reference to &lt;b&gt;PostSharp.Public.dll&lt;/b&gt; and &lt;b&gt;PostSharp.Laos.dll&lt;/b&gt;.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Performance could be poor. Code weaving adds overhead to the compilation process. Tests and the code they test are frequently compiled.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;del&gt;PostSharp is tied to MSBuild. NAnt tasks running on a build server might not be able to execute tests using this mock framework.&lt;/del&gt; (See comments to this post from PostSharp creator &lt;a href="http://gael.fraiteur.net/"&gt;Gael Fraiteur&lt;/a&gt;.)&lt;/li&gt;&lt;br /&gt;&lt;li&gt;A bunch of other things I forgot.&lt;/li&gt; &lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;&lt;br /&gt;Some of these concerns can be alleviated, and some cannot. I would like to prove this out soon (though I doubt I'll be able to):&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;br /&gt;&lt;li&gt;Interception can be done at the call site &lt;i&gt;without&lt;/i&gt; modifying the called assembly.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;The code weaver can be provided with interception points (join points? advice points? I don't understand AOP terminology at all) without them being marked with attributes. This has to be true if we want to do (1) anyway. Unfortunately, it's not going to be easy (otherwise Laos would probably already do it).&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Nothing can be done about modifying the assemblies being tested; that's the whole point. We're weaving code to achieve interception.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;del&gt;Nothing can be done about referencing PostSharp. Again, that's the point.&lt;/del&gt; Gael corrected me on this. We'll tackle this in the distant future.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Overhead per-compilation isn't too bad. It's better than overhead per-test.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;There are ways to invoke PostSharp from the command line&lt;del&gt;, so NAnt tasks the coupling to MSBuild can be overcome&lt;/del&gt; (Deleted not only for being obvious typo nonsense but also because Gael points out that there is already a NAnt task for PS 1.5). I don't really care about this right now (still true anyway).&lt;/li&gt;&lt;br /&gt;&lt;li&gt;I sometimes remember things I previously forgot.&lt;/li&gt;&lt;br /&gt;&lt;/ol&gt;&lt;br /&gt;&lt;br /&gt;If anyone ever reads this post and is interested, I will find a way to provide the solution I used to spike this.&lt;br /&gt;&lt;br /&gt;(Side thought: I wonder, if I were to start an open source project called 'SharpMock' as an alternative TypeMock, could I get a &lt;a href="http://www.typemock.com/free_open_source_license_form.php"&gt;free version&lt;/a&gt; of TypeMock to aid in its development?)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-6429450025001655800?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/6429450025001655800/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=6429450025001655800' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/6429450025001655800'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/6429450025001655800'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2008/10/stubbing-static-methods-with-postsharp.html' title='Stubbing Static Methods with PostSharp'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-348115887378115761.post-3483649633891125635</id><published>2008-04-20T22:36:00.000-05:00</published><updated>2008-04-20T20:41:28.094-05:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Introduction'/><title type='text'>Who I'm Is</title><content type='html'>I am a junior .NET developer currently working in Chicago, IL. I am starting this blog in order to enhance my knowledge of programming subject matter. Hopefully, someone else will be helped along the way. This first post will probably be edited soon...&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/348115887378115761-3483649633891125635?l=jamesryangray.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jamesryangray.blogspot.com/feeds/3483649633891125635/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=348115887378115761&amp;postID=3483649633891125635' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3483649633891125635'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/348115887378115761/posts/default/3483649633891125635'/><link rel='alternate' type='text/html' href='http://jamesryangray.blogspot.com/2008/04/who-im-is.html' title='Who I&apos;m Is'/><author><name>Ryan</name><uri>http://www.blogger.com/profile/10921225487124288754</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>
