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

<channel>
	<title>{(something&#124;&#124;other).soft()} &#187; csharp</title>
	<atom:link href="http://www.somethingorothersoft.com/tag/csharp/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.somethingorothersoft.com</link>
	<description>About Software Development And Other Stuff By Igor Zevaka</description>
	<lastBuildDate>Tue, 17 Aug 2010 00:42:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Handling 404, unhandled and unsafe URL errors in ASP.NET MVC application</title>
		<link>http://www.somethingorothersoft.com/2010/06/18/handling-404-unhandled-and-unsafe-url-errors-in-asp-net-mvc-application/</link>
		<comments>http://www.somethingorothersoft.com/2010/06/18/handling-404-unhandled-and-unsafe-url-errors-in-asp-net-mvc-application/#comments</comments>
		<pubDate>Fri, 18 Jun 2010 00:15:36 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[asp.net-mvc]]></category>
		<category><![CDATA[csharp]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=411</guid>
		<description><![CDATA[Spent a bit of time recently to try and get my MVC application handle 404 errors exactly as I want. The solution that I ended up choosing is based on this excellent SO answer. The advantage of rendering the Error view by calling ErrorController.Execute, as opposed to making an entry in web.config, is that you <a href="http://www.somethingorothersoft.com/2010/06/18/handling-404-unhandled-and-unsafe-url-errors-in-asp-net-mvc-application/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Spent a bit of time recently to try and get my MVC application handle 404 errors exactly as I want. The solution that I ended up choosing is based on this excellent <a href="http://stackoverflow.com/questions/619895/how-can-i-properly-handle-404s-in-asp-net-mvc/2577095#2577095">SO answer</a>.</p>

<p>The advantage of rendering the Error view by calling <code>ErrorController.Execute</code>, as opposed to making an entry in web.config, is that you get to preserve the URL without a browser redirect.</p>

<p>If you think about which scenarios warrant a 404 response a more involved strategy is justifiable:</p>

<ol>
<li>Non-supported controller name &#8211; captured by <code>{controller}/{action}/{parameter}</code> rule.</li>
<li>Supported controller but bad action &#8211; captured by <code>Controller.HandleUnknownAction</code>.</li>
<li>Non-supported URL format &#8211; captured by the catch-all rule.</li>
</ol>

<p>Using <code>ErrorController.Execute</code> allows to preserve the URL for all of those scenarios. Now, to trap all unhandled exceptions in order to not show a Yellow Screen of Death, you would need to do some error handling in <code>Application.Error</code> event handler. Something similar is described in <a href="http://stackoverflow.com/questions/619895/how-can-i-properly-handle-404s-in-asp-net-mvc/620559#620559">this answer</a>.</p>

<p>There is a catch, however. If the anti-XSS features kick in and disallow a URL containing, say, angle brackets, executing error controller from global exception handler will throw an exception resulting in a YSOD.</p>

<p>The best solution i found was to catch the exception when doing <code>Execute</code> and do a browser redirect then. This prevents the runtime from creating a YSOD due to an unhandled exception in the exception event.</p>

<div>
<pre class="brush: csharp;">
IController errorController = ControllerBuilder.Current.GetControllerFactory().CreateController(null, &quot;error&quot;);
try {
    errorController.Execute(new RequestContext(
            contextBase, errorRoute));
} catch(Exception) {
    //If we are here it means that the URL is unsafe and the only way to handle it gracefully is to redirect.
    Response.Redirect(&quot;~/Error/BadRequest&quot;); //Controller/View pair that returns 400 - Bad Request
}

</pre>
</div>

<p>It&#8217;s probably not the best idea to handle 400 error as 404, hence we redirect to a &#8220;BadRequest&#8221; action in the <code>ErrorController</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/06/18/handling-404-unhandled-and-unsafe-url-errors-in-asp-net-mvc-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Converting an Expression to a compiled Lambda</title>
		<link>http://www.somethingorothersoft.com/2010/06/18/converting-an-expression-to-a-compiled-lambda/</link>
		<comments>http://www.somethingorothersoft.com/2010/06/18/converting-an-expression-to-a-compiled-lambda/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 23:45:08 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[expressions]]></category>
		<category><![CDATA[lamdbas]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=398</guid>
		<description><![CDATA[A quick guide on how to convert an expression to a compiled lambda.]]></description>
			<content:encoded><![CDATA[<h3>Compiling an expression to a lambda</h3>

<p>Today I had to convert a binary expression to a lambda and then use in a where clause on a collection. Easy enough, I thought, make an <code>ExpressionLambda</code>, compile it, substitute it into the where clause, no worries.</p>

<p>This is the first cut of the code:</p>

<div>
<pre class="brush: csharp;">

public class ClassWithProperties {
    public string Prop { get; set; }
}

static void ExpressionCrashes() {

    var expr = Expression.Equal(Expression.Property(Expression.Variable(typeof(ClassWithProperties)), &quot;Prop&quot;), Expression.Constant(&quot;value2&quot;));

    var props = new[] { Expression.Parameter(typeof(ClassWithProperties)) };
    //Throws &lt;variable '' of type 'SOCSTest.ClassWithProperties' referenced from scope '', but it is not defined&gt;
    var lambda = Expression.Lambda&lt;Func&lt;ClassWithProperties, bool&gt;&gt;(expr, props).Compile();

    var items = new List&lt;ClassWithProperties&gt; { 
        new ClassWithProperties{Prop = &quot;value1&quot;},
        new ClassWithProperties{Prop = &quot;value2&quot;},
        new ClassWithProperties{Prop = &quot;value2&quot;}
    };

    //Should return &lt;&quot;value2&quot;, &quot;value2&quot;&gt;
    items.Where(lambda);
}

</pre>
</div>

<p>The expression is a basic one &#8211; it calls an equality comparison on a property off an object and a constant. It is equivalent to this:</p>

<div>
<pre class="brush: csharp;">
value.Prop == &quot;value2&quot;
//Where value is a parameter of type ClassWithProperties
</pre>
</div>

<p>Googling for this exception and just general expression and lambda stuff kinda hints at people having the same problem as I am but with no fast solution. It was Jon Skeet&#8217;s <a href="http://stackoverflow.com/questions/1574427/lambda-parameter-not-in-scope-while-building-binary-lambda-expression/1574455#1574455">answer to question I didn&#8217;t understand</a> on StackOverflow that finally put me onto the right track.</p>

<p>In order to compile a lambda from an expression, you need to provide <strong>all instances of <code>ParameterExpression</code></strong> that appear in the expression tree when creating a lambda expressionn (i.e. when calling <code>Expression.Lambda&lt;T&gt;(Expression, params ParameterExpression[])</code>). The Expression engine will not match types and names parameters in an expression &#8211; as far as it&#8217;s concerned different instances of <code>ParameterExpression</code> are discrete parameters.</p>

<p>Rewriting the above code yields something that doesn&#8217;t crash:</p>

<div>
<pre class="brush: csharp;">
static void ExpressionWorks() {
    var variable = Expression.Variable(typeof(ClassWithProperties));
    var expr = Expression.Equal(Expression.Property(variable, &quot;Prop&quot;), Expression.Constant(&quot;value2&quot;));

    var props = new []{ variable };
    var lambda = Expression.Lambda&lt;Func&lt;ClassWithProperties, bool&gt;&gt;(expr, props).Compile();

    var items = new List&lt;ClassWithProperties&gt; { 
        new ClassWithProperties{Prop = &quot;value1&quot;},
        new ClassWithProperties{Prop = &quot;value2&quot;},
        new ClassWithProperties{Prop = &quot;value2&quot;}
    };

    //Returns &lt;&quot;value2&quot;, &quot;value2&quot;&gt;
    items.Where(lambda);
}
</pre>
</div>

<p>As you can see, we reused the instance <code>variable</code> in both expression declaration and <code>Expression.Lambda</code> call. Everything works fine now.</p>

<h3>Getting the parameters from Expression at runtime</h3>

<p>My situation was such as that I had to deal with an already created expression. So I couldn&#8217;t simply take the variable parameters that are used to create an expression and reuse them when creating a lambda. The solution was to traverse the expression tree and get a list of all the <code>ParameterExpression</code> instances that are contained in the expression and pass those to <code>Lambda</code> function.</p>

<p>Luckily, <a href="http://msdn.microsoft.com/en-us/library/bb546136%28v=VS.90%29.aspx"><code>ExpressionVisitor</code></a> API provides an easy way to achieve this. All you have to do is inherit from <code>ExpressionVisitor</code> and implement one function to trap all the goodies we need:</p>

<div>
<pre class="brush: csharp;">
public class ParameterVisitor : ExpressionVisitor{

    List&lt;ParameterExpression&gt; m_Parameters;

    public IEnumerable&lt;ParameterExpression&gt; GetParameters(Expression expr) {
        m_Parameters = new List&lt;ParameterExpression&gt;();
        Visit(expr);
        return m_Parameters;
    }
        
    protected override System.Linq.Expressions.Expression VisitParameter(System.Linq.Expressions.ParameterExpression p) {

        if(!m_Parameters.Contains(p))
            m_Parameters.Add(p);
            
        return base.VisitParameter(p);
    }
}
</pre>
</div>

<p>We can even create an extension method to hide all complexity of creating a lambda:</p>

<div>
<pre class="brush: csharp;">
public static Func&lt;TSource, TResult&gt; CreateLambda&lt;TSource, TResult&gt;(this Expression expression) {
    var visitor = new Bluecap4.Core.Expressions.ParameterVisitor();
    var parameters = visitor.GetParameters(expression);
            
    return Expression.Lambda&lt;Func&lt;TSource, TResult&gt;&gt;(expression, parameters).Compile();
}
//Usage
static void ExpressionWorks() {
    var expr = Expression.Equal(Expression.Property(Expression.Variable(typeof(ClassWithProperties)), &quot;Prop&quot;), Expression.Constant(&quot;value2&quot;));

    var items = new List&lt;ClassWithProperties&gt; { 
        new ClassWithProperties{Prop = &quot;value1&quot;},
        new ClassWithProperties{Prop = &quot;value2&quot;},
        new ClassWithProperties{Prop = &quot;value2&quot;}
    };

    //Returns &lt;&quot;value2&quot;, &quot;value2&quot;&gt;
    items.Where(expr.CreateLambda&lt;Func&lt;ClassWithProperties,bool&gt;&gt;());
}
</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/06/18/converting-an-expression-to-a-compiled-lambda/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Tests As A Refactoring Tool</title>
		<link>http://www.somethingorothersoft.com/2010/02/20/unit-tests-as-a-refactoring-tool/</link>
		<comments>http://www.somethingorothersoft.com/2010/02/20/unit-tests-as-a-refactoring-tool/#comments</comments>
		<pubDate>Sat, 20 Feb 2010 07:23:34 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[unit-testing]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=283</guid>
		<description><![CDATA[So I have this class that is a bit too fat and has no unit tests. It&#8217;s way overdue for a clean up. I thought I would investigate how to refactor with unit tests. Application The application in question is a fairly normal case of a business DSL where the domain rules are expressed in <a href="http://www.somethingorothersoft.com/2010/02/20/unit-tests-as-a-refactoring-tool/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>So I have this class that is a bit too fat and has no unit tests. It&#8217;s way overdue for a clean up. I thought I would investigate how to refactor with unit tests.</p>

<h3>Application</h3>

<p>The application in question is a fairly normal case of a business DSL where the domain rules are expressed in XML and the compiler generates an application for different platforms (web, mobile web, PDA, WPF). Code is written in C#, tested with MbUnit v.3 and NMock2.</p>

<p>This particular class parses XML and generates JSON to be later consumed by ExtJS library. The JSON is a declaritive form of the control that users will eventually see. This control is complicated and has many options. Hence the fatness.</p>

<h3>Enter the unit tests</h3>

<p>Now, unit tests are touted to be great for refactoring. They are. The usual approach is to write the tests, make sure they pass, then refactor and make sure the tests don&#8217;t break. Well, I want to take it one step further and let the writing of the tests guide the refactoring.</p>

<p>Thoroughly unit tested code tends to have really good code smells. This is mainly due to fact that in order to test all aspects of a large block of code, you must isolate all of its constituents. This is evident in all projects that are written in a TDD way. They are all very modular and modular is good(I think :-) ).</p>

<p>So my goal here is just simply write the unit tests and see where it takes me. I would imagine that just by making the code testable, it will become a little bit better.</p>

<p>I never invisaged this to become a full blown article, but now that I am here, lets introduce some numbers to make this more scientific. I will be using Microsoft Team Studio Analysis Tools throughout the process. Here is a snapshot of what the class looks like at the start:</p>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/start.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/start.png" alt="" title="start" width="808" height="173" class="alignnone size-full wp-image-284" /></a></p>

<p>As you can see the <code>Build</code> method is too big &#8211; 250 lines. This is bad. It&#8217;s one of those <code>DoIt</code> methods that does everything.</p>

<h3>First refactor</h3>

<p>Alright, lets get cranking. Straight away I noticed that I was reading a particular bit of XML and making decisions based on the node contents. This particular functionality has already been abstracted away in another class, so I might as well use that class. So I just refactored that without writing any tests before or after. That&#8217;s pretty naughty :)) Lets make it proper and rip this code into another function so we can test it.</p>

<p>Starting from the top of the method I am looking at a bit of code that parses an atribute and calls a method that is defined in the base class depending on whether or not the attribute exists.</p>

<h3>Base class dependency</h3>

<p>Now refactoring that into a method is not a problem, the problem is isolating the call to the base class. There is case to be made for having the base class contain all the dependencies that are required for all of its subclasses, however, just by skimming the code it looks like a lot of the methods there are simply in one place for convinience. So this could potentially be a case of Inheritance vs. Composition. Lets start off by abstracting  this particular method into an interface and have our base derive from the interface. Then in our derived class we access that method through a reference to the interface, not implicitly.</p>

<p>This is what it looks like now:</p>

<div>
<pre class="brush: csharp;">
class Builder {
   public DoStuff(string blah){
      //impl
   }
}

class GridBuilder : Builder{
   public void Build() {
      var elem = Element.GetAttribute(&quot;Blah&quot;);
      DoStuff(blah);
   }
}
</pre>
</div>

<p>Let&#8217;s tweak it as described in the previous paragraph:</p>

<div>
<pre class="brush: csharp;">
interface IBuilder {
    DoStuff(string blah);
}

[code lang=&quot;csharp&quot;]
class Builder : IBuilder {
   [Obsolete]
   public DoStuff(string blah){
      //impl
   }
}

class GridBuilder {
   
   IBuilder _Builder;
   
   public GridBuilder() {
     _Builder = this;
   }
   
   public GridBuilder(IClientBuilder b) {
            m_ClientBuilder = b;
    }
   
   public void Build() {
      var elem = Element.GetAttribute(&quot;Blah&quot;);
      _Builder = DoStuff(blah);
   }
}
</pre>
</div>

<p>So what I have done is put that <code>DoStuff</code> into an interface and marked the implementation as Obolete. This is more out of convinience to get the compiler to show me where else this method is being used. Turns out this was the only case where it was used in <code>GridBuilder</code>. I could have just as well used text search, but hey, if there is a fancy compiler feature, why not use it? Notice that I also added a dependency constructor so I can compose <code>GridBuilder</code> in a unit test.</p>

<p>Let's make a unit test for this use of <code>DoStuff</code>. As I am doing that I realised that my base class is in a different assembly and required some code duplication from another test project to make the test not crash. The fact that I had to do that is a pretty bad, but my copying the common setup file and including it in my test project is even worse. We can come back to that later, lets concentrate on what we are doing now. Might as well use the <code>Obsolete</code> attribute to remind me to refactor the unit test later on.</p>

<h3>Finally, I can test <code>Build</code></h3>

<p>So, after a long time setting up <code>GridBuilder</code>'s dependencies I am finally here - the test runs. Lets review what I've achieved so far and have a peek at the metrics. So here is the summary of what was required just to make the test run:</p>

<ul>
<li>Two instances of referring to the base class have been abstractes into two interfaces.</li>
<li>Found a bug where if a required element is present but contains no nodes the builder crashes.</li>
<li>The test creates a total of three mock objects with a total of five <code>Stubs</code> and one <code>Expect</code>.</li>
<li>The test needs to pass in an Xml element with two elements and one atribute.</li>
<li>Found a small refactoring job that is not really related to the unit testing aspect of this excercise.</li>
</ul>

<p>Code metrics:</p>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step1.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step1.png" alt="" title="step1" width="954" height="210" class="alignnone size-full wp-image-286" /></a></p>

<p>So I didn't get anywhere as far as most metrics are concerned, in fact I almost went backwards, if anything. Let's keep going. So now I have a unit test that runs the <code>Build</code> method lets keep trying to test more and more parts of it.</p>

<p>Before I go on, I would like to emphasize the fact that I had to create lots of mocks and pass in lots of dependencies just to make one method not crash. Here is the unit test. Definitely too much for ONE method:</p>

<div>
<pre class="brush: csharp;">

        [SetUp]
        public void Setup() {
            m_Mocks = new Mockery();
            m_Settings = new InlineBuilderSettings {
                Compiler = m_Mocks.NewMock&lt;IWebCompiler&gt;(),
                ComponentName = &quot;Test&quot;
            };
            //Used by setup method
            Stub.On(m_Settings.Compiler).GetProperty(&quot;ServerCompiler&quot;).Will(Return.Value(null));
            Stub.On(m_Settings.Compiler).GetProperty(&quot;ServerType&quot;).Will(Return.Value(typeof(Data.ServerAplication)));
        }
        
        [Test]
        public void BuildShouldCallRequireComponentWhenViewAttribute() {

            var iClientBuilder = m_Mocks.NewMock&lt;IClientBuilder&gt;();
            var iBuilder = m_Mocks.NewMock&lt;IWebBuilder&gt;();

            Builder builder = new Builder(iClientBuilder, iBuilder);
            m_Settings.Element = 
                new XElement(&quot;Grid&quot;, new XAttribute(&quot;View&quot;, &quot;test&quot;), 
                    new XElement(&quot;Source&quot;, new XAttribute(&quot;View&quot;, &quot;DataTest&quot;)),
                    new XElement(&quot;Fields&quot;));

            Expect.Once.On(iClientBuilder).Method(&quot;RequireComponent&quot;).With(&quot;test&quot;, m_Settings.Element).Will();
            Stub.On(iClientBuilder).Method(&quot;GetComponentInfo&quot;).Will(Return.Value(new ComponentInfo()));
            Stub.On(iBuilder).Method(&quot;AddConfig&quot;).Will();
            Stub.On(m_Settings.Compiler).Method(&quot;AddInclude&quot;).Will();
            
            builder.Setup(m_Settings);
            builder.Build();
        }
</pre>
</div>

<p>Realistically, in order to complete the build process we need all those dependencies. That's pretty fundamental. However, it should be possible to reduce the amount of dependencies ONE method has.</p>

<h3>Next refactor</h3>

<p>My next target was a reasonably self contained code block that I did "Extract Method" method on. Two more unit tests. Slight improvement in maintainability and complexity.</p>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step2.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step2.png" alt="" title="step2" width="996" height="236" class="alignnone size-full wp-image-287" /></a></p>

<p>Next one is a big sucker. This block produces about 5 output objects that are dumped to JSON later on. I actually moved to another two classes. One to perform the build and another to store the output.</p>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step3.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step3.png" alt="" title="step3" width="896" height="236" class="alignnone size-full wp-image-288" /></a></p>

<p>Good improvement on all counts. Lets keep splitting the Build method and writing tests for it. As I am doing this I decided to make the GridBuilder a namespace within a project. There are a number of classes in it by now, might as well contain them in a folder.</p>

<h3>Day later.</h3>

<p>I have somewhat abandoned refactoring GridBuilder as I found a whole bunch of other tightly coupled classes. The unit tests have proven to be a great tool exposing those dependencies. They also become usefull when the refactoring becomes non-trivial - i.e. goes beyond just moving a block of code out of a method.</p>

<p>This is what the class looked like once I finished with it:</p>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step4.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/02/step4.png" alt="" title="step4" width="975" height="230" class="alignnone size-full wp-image-289" /></a></p>

<p>Now that I ran out of time that I gave myself for this task I think I have a few notes for future.</p>

<ul>
<li>Parsing an XML collection is ugly and tends to get messy when things need to be addded to the inner loop. I think for this scenario I would need some sort of visitor pattern implemented so that you could add things to the inner loop without having to alter the loop itself.</li>
<li>Having implicit dependencies (like a dependency on a property of an actual dependency) totally breaks the unit tests. A situation where you create one mock and then have its method return another mock is a bit ridiculous.</li>
<li>A unit test for a monstrous method will too be monstrous. There is almost 1-to-1 relationship between how fat the method is and how fat its unit test is. I think that if one aims to make unit test simpler, the code under test will in turn become simpler.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/02/20/unit-tests-as-a-refactoring-tool/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
