<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Dr. Random - tips</title>
    <link>http://www.drrandom.org/</link>
    <description>Random Thoughts for Random People</description>
    <language>en-us</language>
    <copyright>Casey Kramer</copyright>
    <lastBuildDate>Tue, 15 Dec 2009 15:08:44 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>casey.kramer@gmail.com</managingEditor>
    <webMaster>casey.kramer@gmail.com</webMaster>
    <item>
      <trackback:ping>http://www.drrandom.org/Trackback.aspx?guid=49ad68e1-3159-4225-ab35-8c1a345429da</trackback:ping>
      <pingback:server>http://www.drrandom.org/pingback.aspx</pingback:server>
      <pingback:target>http://www.drrandom.org/PermaLink,guid,49ad68e1-3159-4225-ab35-8c1a345429da.aspx</pingback:target>
      <dc:creator>Casey Kramer</dc:creator>
      <wfw:comment>http://www.drrandom.org/CommentView,guid,49ad68e1-3159-4225-ab35-8c1a345429da.aspx</wfw:comment>
      <wfw:commentRss>http://www.drrandom.org/SyndicationService.asmx/GetEntryCommentsRss?guid=49ad68e1-3159-4225-ab35-8c1a345429da</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
On November 27th, a beta release of the 9.3 version of the Developer Express components,
including CodeRush and Refactor Pro! was made available to subscribers.  This
release is pretty significant to me because it contains a major feature that I have
been waiting for <a href="http://www.drrandom.org/2007/07/13/TakingTheCodeRushPlunge.aspx" target="_blank">for
a long time</a>: A Unit Test Runner.  There were some teasers released by <a href="http://community.devexpress.com/blogs/markmiller/">Mark
Miller</a> a while back, which only made me want to get my hands on the tool that
much more.  My initial impressions are that it is very nice.  It is similar
to <a href="http://www.testdriven.net">TestDriven.Net</a> in that it provides context
menu options to run tests at various levels of granularity (single test, file, project,
and solution level) and includes a debug option.  At this point it does not contain
some of the additional coolness that TestDriven gives you like NCover/Team Coverage
and TypeMock integration, but it does have the advantage of being extensible. 
I know it was extensible because Mr. Miller <a href="http://community.devexpress.com/blogs/markmiller/archive/2009/11/16/the-test-runner-you-ve-been-waiting-for.aspx">told
me it was extensible</a> (the title “The Extensible Unit Test Runner You’ve Been Waiting
For” was a clue).  I did not realize how extensible, however, until after I submitted
a <a href="http://www.devexpress.com/issue=B142663">bug report</a> to DevExpress. 
The bug I was reporting (the NUnit TestCase attributes were not recognized), it turns
out, was already brought to the attention of the DX team by way of a <a href="http://community.devexpress.com/forums/p/83453/285881.aspx#285881">forum
post</a>, and they had already planned on correcting it with the next 9.3 release,
but I could have saved myself (and Vito on DevExpress team) some time by taking a
peek at the source samples bundled with the 9.3 release.  Yep, you guessed it,
there with a shared source license were all of the test framework implementation projects. 
So this meant I could whip together my own temporary fix while I was waiting for the
next release.  It seemed like something that other folks might want to know about,
so I thought I would share it here.
</p>
        <p>
The biggest piece of the puzzle is a new TestExecuteTask class for handling the TestCaseAttribute. 
Due to my complete lack of creativity, I called mine TestCaseExecuteTask, and it looks
like this: 
</p>
        <pre class="brush: csharp" name="code">using System;
using System.Collections.Generic;
using System.Text;
using DevExpress.CodeRush.Core.Testing;
using System.Reflection;
using DevExpress.CodeRush.Core;

namespace CR_NUnitTesting
{
    public class TestCaseExecuteTask : TestExecuteTask
    {
        public override TaskExecuteResult CollectTestParameters()
        {
            TaskExecuteResult result = TaskExecuteResult.SkippedTaskResult;
            Attribute testCase = GetMethodAttribute("NUnit.Framework.TestCaseAttribute");
            if (testCase == null)
                return result;
            
            foreach(Attribute testCaseItem in TestMethod.GetCustomAttributes(true))
            {
                if(testCaseItem == null)
                    continue;
                var testCaseType = testCaseItem.GetType();
                if(testCaseType == null || testCaseType.FullName != "NUnit.Framework.TestCaseAttribute")
                    continue;
                PropertyInfo prop = testCaseType.GetProperty("Arguments");
                if(prop == null)
                    continue;
                foreach(MethodInfo getter in prop.GetAccessors())
                {
                    object[] parameters = getter.Invoke(testCaseItem, Type.EmptyTypes) as object[];
                    result.AddParameters(parameters);
                }
            }
        }
    }
}
</pre>
        <p>
This could be cleaned up some, and some of the magic strings extracted to constants,
but overall it is pretty simple. Basically what is going on here is that we are looking
for the TestCase attribute, and extracting the arguments for any attributes we find. 
It just so happens that the TestExecuteTask base class has a CollectTestParameters()
method we can override which allows for this sort of Row testing.  The parameters
we extract get stashed in the execution result, which causes the test runner to execute
the test once for each group of parameters (the result has a list of parameters, which
gets populated with an array of objects for each TestCase attribute), and will correctly
display which cases failed if there is a failure.
</p>
        <p>
There are a couple other small changes that need to happen to get this to work. 
There is an NUnitExtension.cs  class, which is the Plug-In class for the NUnit
support, and it handles wiring everything up for us.  First off we need to initialize
our new TestExecuteTask, and add it to the list of tasks that run for NUnit tests. 
We do that in the InitializePlugin method of the NUnitExtension class: 
</p>
        <pre class="brush: csharp">public override void InitializePlugin()
{
    base.InitializePlugin();
    nUnitProvider.AvailableTasks.Add(new NUnitIgnoreTask());
    nUnitProvider.AvailableTasks.Add(new NUnitSetupTearDownTask());
    nUnitProvider.AvailableTasks.Add(new NUnitExpectedExceptionTask());
    nUnitProvider.AvailableTasks.Add(new NUnitValuesTask());
    nUnitProvider.AvailableTasks.Add(new NUnitRowTestTask());
    nUnitProvider.AvailableTasks.Add(new NUnitTimeoutTask());
    nUnitProvider.AvailableTasks.Add(new NUnitExplicitTask());
    nUnitProvider.AvailableTasks.Add(new NUnitTestCaseTask());
}
</pre>Ours
gets added to the end of the list, so it will be executed. The next step is to get
the plug-in to realize that a method with a TestCase attribute is an executable test
method. That trick happens in the handler for the CheckTestMethod event on the UnitTestProvider.
All we're going to do is add another condition to an if statement like so: <pre class="brush: csharp">void nUnitProvider_CheckTestMethod(object sender, CheckTestMethodEventArgs ea)
{
    IMethodElement method = ea.Method;
    if(//method.Name != null &amp;&amp; method.Name.StartsWith("Test")
       ea.GetAttribute("NUnit.Framework", "Test", method) != null
    || ea.GetAttribute("NUnit.Framework.Extensions", "RowTest", method) != null
    || ea.GetAttribute("NUnit.Framework", "TestCase", method) != null)
    {
        ea.IsTestMethod = true;
        ea.Description = ea.GetAttributeText("NUnit.Framework", "Description", method);
        ea.Category = ea.GetAttributeText("NUnit.Framework", "Category", method);
    }
}
</pre><p>
The only change to the original code was the additional GetAttribute call at the end
of the if statement (the comments were there when I got there, I swear).  Now
the only thing left to do is to compile it and drop it in the plug-ins directory. 
Now when you are looking at a test class, you should be able to run TestCase decorated
test methods without problem.  Well, almost.  There is one thing I was not
able to find a clean way to implement, and that is the Result property of the TestCase
attribute.  This allows you to streamline tests which are doing equals assertions
by having the test method return the actual result, and you specify the expected result
by using the result property.  Unfortunately I could not find a way to hook into
the actual execution of the test in such a way that I could have access to the specific
test properties being used, and the result of the test method execution.  But
considering the DevExpress folks will be fixing this issue, I’m sure when they release
it there will be support for this feature.  After all, this is simply a stop-gap
solution until the next CodeRush release is available, so I’m willing to live with
this slight inconvenience.
</p><p>
Happy Testing!   
</p><img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=49ad68e1-3159-4225-ab35-8c1a345429da" /></body>
      <title>More CodeRush Awesomeness</title>
      <guid isPermaLink="false">http://www.drrandom.org/PermaLink,guid,49ad68e1-3159-4225-ab35-8c1a345429da.aspx</guid>
      <link>http://www.drrandom.org/2009/12/15/MoreCodeRushAwesomeness.aspx</link>
      <pubDate>Tue, 15 Dec 2009 15:08:44 GMT</pubDate>
      <description>&lt;p&gt;
On November 27th, a beta release of the 9.3 version of the Developer Express components,
including CodeRush and Refactor Pro! was made available to subscribers.&amp;nbsp; This
release is pretty significant to me because it contains a major feature that I have
been waiting for &lt;a href="http://www.drrandom.org/2007/07/13/TakingTheCodeRushPlunge.aspx" target="_blank"&gt;for
a long time&lt;/a&gt;: A Unit Test Runner.&amp;nbsp; There were some teasers released by &lt;a href="http://community.devexpress.com/blogs/markmiller/"&gt;Mark
Miller&lt;/a&gt; a while back, which only made me want to get my hands on the tool that
much more.&amp;nbsp; My initial impressions are that it is very nice.&amp;nbsp; It is similar
to &lt;a href="http://www.testdriven.net"&gt;TestDriven.Net&lt;/a&gt; in that it provides context
menu options to run tests at various levels of granularity (single test, file, project,
and solution level) and includes a debug option.&amp;nbsp; At this point it does not contain
some of the additional coolness that TestDriven gives you like NCover/Team Coverage
and TypeMock integration, but it does have the advantage of being extensible.&amp;nbsp;
I know it was extensible because Mr. Miller &lt;a href="http://community.devexpress.com/blogs/markmiller/archive/2009/11/16/the-test-runner-you-ve-been-waiting-for.aspx"&gt;told
me it was extensible&lt;/a&gt; (the title “The Extensible Unit Test Runner You’ve Been Waiting
For” was a clue).&amp;nbsp; I did not realize how extensible, however, until after I submitted
a &lt;a href="http://www.devexpress.com/issue=B142663"&gt;bug report&lt;/a&gt; to DevExpress.&amp;nbsp;
The bug I was reporting (the NUnit TestCase attributes were not recognized), it turns
out, was already brought to the attention of the DX team by way of a &lt;a href="http://community.devexpress.com/forums/p/83453/285881.aspx#285881"&gt;forum
post&lt;/a&gt;, and they had already planned on correcting it with the next 9.3 release,
but I could have saved myself (and Vito on DevExpress team) some time by taking a
peek at the source samples bundled with the 9.3 release.&amp;nbsp; Yep, you guessed it,
there with a shared source license were all of the test framework implementation projects.&amp;nbsp;
So this meant I could whip together my own temporary fix while I was waiting for the
next release.&amp;nbsp; It seemed like something that other folks might want to know about,
so I thought I would share it here.
&lt;/p&gt;
&lt;p&gt;
The biggest piece of the puzzle is a new TestExecuteTask class for handling the TestCaseAttribute.&amp;nbsp;
Due to my complete lack of creativity, I called mine TestCaseExecuteTask, and it looks
like this: &lt;pre class="brush: csharp" name="code"&gt;using System;
using System.Collections.Generic;
using System.Text;
using DevExpress.CodeRush.Core.Testing;
using System.Reflection;
using DevExpress.CodeRush.Core;

namespace CR_NUnitTesting
{
    public class TestCaseExecuteTask : TestExecuteTask
    {
        public override TaskExecuteResult CollectTestParameters()
        {
            TaskExecuteResult result = TaskExecuteResult.SkippedTaskResult;
            Attribute testCase = GetMethodAttribute("NUnit.Framework.TestCaseAttribute");
            if (testCase == null)
                return result;
            
            foreach(Attribute testCaseItem in TestMethod.GetCustomAttributes(true))
            {
                if(testCaseItem == null)
                    continue;
                var testCaseType = testCaseItem.GetType();
                if(testCaseType == null || testCaseType.FullName != "NUnit.Framework.TestCaseAttribute")
                    continue;
                PropertyInfo prop = testCaseType.GetProperty("Arguments");
                if(prop == null)
                    continue;
                foreach(MethodInfo getter in prop.GetAccessors())
                {
                    object[] parameters = getter.Invoke(testCaseItem, Type.EmptyTypes) as object[];
                    result.AddParameters(parameters);
                }
            }
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;
This could be cleaned up some, and some of the magic strings extracted to constants,
but overall it is pretty simple. Basically what is going on here is that we are looking
for the TestCase attribute, and extracting the arguments for any attributes we find.&amp;nbsp;
It just so happens that the TestExecuteTask base class has a CollectTestParameters()
method we can override which allows for this sort of Row testing.&amp;nbsp; The parameters
we extract get stashed in the execution result, which causes the test runner to execute
the test once for each group of parameters (the result has a list of parameters, which
gets populated with an array of objects for each TestCase attribute), and will correctly
display which cases failed if there is a failure.
&lt;/p&gt;
&lt;p&gt;
There are a couple other small changes that need to happen to get this to work.&amp;nbsp;
There is an NUnitExtension.cs&amp;nbsp; class, which is the Plug-In class for the NUnit
support, and it handles wiring everything up for us.&amp;nbsp; First off we need to initialize
our new TestExecuteTask, and add it to the list of tasks that run for NUnit tests.&amp;nbsp;
We do that in the InitializePlugin method of the NUnitExtension class: &lt;pre class="brush: csharp"&gt;public override void InitializePlugin()
{
    base.InitializePlugin();
    nUnitProvider.AvailableTasks.Add(new NUnitIgnoreTask());
    nUnitProvider.AvailableTasks.Add(new NUnitSetupTearDownTask());
    nUnitProvider.AvailableTasks.Add(new NUnitExpectedExceptionTask());
    nUnitProvider.AvailableTasks.Add(new NUnitValuesTask());
    nUnitProvider.AvailableTasks.Add(new NUnitRowTestTask());
    nUnitProvider.AvailableTasks.Add(new NUnitTimeoutTask());
    nUnitProvider.AvailableTasks.Add(new NUnitExplicitTask());
    nUnitProvider.AvailableTasks.Add(new NUnitTestCaseTask());
}
&lt;/pre&gt;Ours
gets added to the end of the list, so it will be executed. The next step is to get
the plug-in to realize that a method with a TestCase attribute is an executable test
method. That trick happens in the handler for the CheckTestMethod event on the UnitTestProvider.
All we're going to do is add another condition to an if statement like so: &lt;pre class="brush: csharp"&gt;void nUnitProvider_CheckTestMethod(object sender, CheckTestMethodEventArgs ea)
{
    IMethodElement method = ea.Method;
    if(//method.Name != null &amp;amp;&amp;amp; method.Name.StartsWith("Test")
       ea.GetAttribute("NUnit.Framework", "Test", method) != null
    || ea.GetAttribute("NUnit.Framework.Extensions", "RowTest", method) != null
    || ea.GetAttribute("NUnit.Framework", "TestCase", method) != null)
    {
        ea.IsTestMethod = true;
        ea.Description = ea.GetAttributeText("NUnit.Framework", "Description", method);
        ea.Category = ea.GetAttributeText("NUnit.Framework", "Category", method);
    }
}
&lt;/pre&gt;
&lt;p&gt;
The only change to the original code was the additional GetAttribute call at the end
of the if statement (the comments were there when I got there, I swear).&amp;nbsp; Now
the only thing left to do is to compile it and drop it in the plug-ins directory.&amp;nbsp;
Now when you are looking at a test class, you should be able to run TestCase decorated
test methods without problem.&amp;nbsp; Well, almost.&amp;nbsp; There is one thing I was not
able to find a clean way to implement, and that is the Result property of the TestCase
attribute.&amp;nbsp; This allows you to streamline tests which are doing equals assertions
by having the test method return the actual result, and you specify the expected result
by using the result property.&amp;nbsp; Unfortunately I could not find a way to hook into
the actual execution of the test in such a way that I could have access to the specific
test properties being used, and the result of the test method execution.&amp;nbsp; But
considering the DevExpress folks will be fixing this issue, I’m sure when they release
it there will be support for this feature.&amp;nbsp; After all, this is simply a stop-gap
solution until the next CodeRush release is available, so I’m willing to live with
this slight inconvenience.
&lt;/p&gt;
&lt;p&gt;
Happy Testing!&amp;nbsp;&amp;nbsp; 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=49ad68e1-3159-4225-ab35-8c1a345429da" /&gt;</description>
      <comments>http://www.drrandom.org/CommentView,guid,49ad68e1-3159-4225-ab35-8c1a345429da.aspx</comments>
      <category>.Net</category>
      <category>C#</category>
      <category>CodeRush</category>
      <category>DxCore</category>
      <category>TDD</category>
      <category>tips</category>
    </item>
    <item>
      <trackback:ping>http://www.drrandom.org/Trackback.aspx?guid=c2e87a52-29b5-4ef9-8a22-a61a68031f0c</trackback:ping>
      <pingback:server>http://www.drrandom.org/pingback.aspx</pingback:server>
      <pingback:target>http://www.drrandom.org/PermaLink,guid,c2e87a52-29b5-4ef9-8a22-a61a68031f0c.aspx</pingback:target>
      <dc:creator>Casey Kramer</dc:creator>
      <wfw:comment>http://www.drrandom.org/CommentView,guid,c2e87a52-29b5-4ef9-8a22-a61a68031f0c.aspx</wfw:comment>
      <wfw:commentRss>http://www.drrandom.org/SyndicationService.asmx/GetEntryCommentsRss?guid=c2e87a52-29b5-4ef9-8a22-a61a68031f0c</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I ran into this odd problem recently working with some Linq2SQL based persistence
code.  There is some code someone put together to commit a list of changed entities
to the database as part of a single transaction, which simply iterates through the
list and performs the appropriate action.  The problem I was having was that
I had an object referenced by another object that needed to be persisted first, otherwise
there was a foreign key violation.  To add to the strangeness there seemed to
be some magic going on (most likely utilizing the INotifyPropertyChanged goodness),
so that even if I tried to persist just my dependent object first, both were still
showing up in the list, and always in exactly the wrong order.  Now, I’m okay
with magic.  Magic makes a lot of things a lot easier.  The problem arises
whenever the magic is incomplete, and doesn’t follow through to take care of all of
the operation.  Its like someone comming up to you and saying “Pick A Card”,
at which point you do, and put the card back, and they say “I know what your card
was” and walking away.  Not real convincing.  This is what was going on
here.  There was the smarts to know that changes were being made to more than
one entity, and there were even attributes to define what properties contained dependent
objects, but no smarts to actually deal with a case when you would want to save more
than one object in an object graph at a time.
</p>
        <p>
So it occued to me I should be able to do some linqy magic and create some sort of
iterator that would return dependent objects in the appropriate order, so the lest
dependent of the objects get move to the beginning of the list.  My first step,
since I wasn’t really sure how to do this, was to write a test.  And I made it
more or less mirror the issue I was facing, a list of two items, one of which is a
dependency of the other.  I don’t know if there is a lot of value in posting
all of the test cases here, but the end result was rather nice.  Sure it took
several iterations, and there was plenty of infinite looping and stack overflows (which
does some fun things to studio when your running your tests with TestDriven.Net),
but I think this is a reasonable solution to the problem:
</p>
        <pre class="brush: csharp">public static IEnumerable&lt;T&gt; EnsureDependenciesFirst&lt;T&gt;(this IEnumerable&lt;T&gt; items, Func&lt;T ,IEnumerable&gt; selector)
{
    if(items.Count() &lt; 2)
        return;
    var firstPass = items.SkipWhile(t =&gt; items.Intersect(selector(t)).Count() &gt; 0);
    var remainingItems = items.Except(firstPass);
    if(items.Count() == remainingItems.Count())
        return remainingItems;
    return firstPass.Concat(remainingItems.EnsureDependenciesFirst(selector));
}
</pre>
        <p>
Ok, so what do we have here?  Well to start out I’m checking the item list to
see if there are at least two items in it, if not I just return the list.  This
provides a means to avoid an infinate loop due to the recursive call, and provides
a shortcut for a scenario with only one item.  Next off I use the SkipWhile()
method, combined with the user-supplied selector function to iterate through each
item, retrieve it’s list of dependencies (which is what the selector function does),
and checks to see if the current list contains any of the dependencies for the object. 
The results of this first pass are the objects which have no dependencies at all,
so therefore they need to be first in the list.  The next logical step is to
run the operation again for a list that <strong>does not</strong> contains the items
filtered out by the first pass.  This is done via a recursive call back to the
EnsureDependenciesFirst extension.  You will notice we’re checking the count
of the remaining items against the current list, and returning the list if they are
the same.  This is another safety precaution for dealing with infinite loops. 
If we have a circular dependency, this bit will just return the items that are interdependent.
</p>
        <p>
You will note that this is a generic function that has really noting at all to do
with the entities that I am dealing with.  This was largely due to the fact that
this was built TDD, so I just used a simple class which had a property that could
take another instance of itself.  To use this to overcome my entity committing
problem, I would have to write a not too small function to retrieve the list of dependent
objects from the entity (since there would need to be some reflection magic to look
at attributes on the properties to determine which properties contain dependencies),
but it pretty much will drop in to the foreach statement that is currently being used
to persist the entities.
</p>
        <p>
Incidently, I learned from my dev team what the “official” way of dealing with this
is a “ReorderChanges” method, which takes two entities, in the order in which they
should be persisted.  I think I like my solution better, mostly because it should
mean I don’t have to worry about it again.
</p>
        <img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=c2e87a52-29b5-4ef9-8a22-a61a68031f0c" />
      </body>
      <title>Some code for sorting lists which may contain dependencies</title>
      <guid isPermaLink="false">http://www.drrandom.org/PermaLink,guid,c2e87a52-29b5-4ef9-8a22-a61a68031f0c.aspx</guid>
      <link>http://www.drrandom.org/2009/09/18/SomeCodeForSortingListsWhichMayContainDependencies.aspx</link>
      <pubDate>Fri, 18 Sep 2009 20:08:47 GMT</pubDate>
      <description>&lt;p&gt;
I ran into this odd problem recently working with some Linq2SQL based persistence
code.&amp;nbsp; There is some code someone put together to commit a list of changed entities
to the database as part of a single transaction, which simply iterates through the
list and performs the appropriate action.&amp;nbsp; The problem I was having was that
I had an object referenced by another object that needed to be persisted first, otherwise
there was a foreign key violation.&amp;nbsp; To add to the strangeness there seemed to
be some magic going on (most likely utilizing the INotifyPropertyChanged goodness),
so that even if I tried to persist just my dependent object first, both were still
showing up in the list, and always in exactly the wrong order.&amp;nbsp; Now, I’m okay
with magic.&amp;nbsp; Magic makes a lot of things a lot easier.&amp;nbsp; The problem arises
whenever the magic is incomplete, and doesn’t follow through to take care of all of
the operation.&amp;nbsp; Its like someone comming up to you and saying “Pick A Card”,
at which point you do, and put the card back, and they say “I know what your card
was” and walking away.&amp;nbsp; Not real convincing.&amp;nbsp; This is what was going on
here.&amp;nbsp; There was the smarts to know that changes were being made to more than
one entity, and there were even attributes to define what properties contained dependent
objects, but no smarts to actually deal with a case when you would want to save more
than one object in an object graph at a time.
&lt;/p&gt;
&lt;p&gt;
So it occued to me I should be able to do some linqy magic and create some sort of
iterator that would return dependent objects in the appropriate order, so the lest
dependent of the objects get move to the beginning of the list.&amp;nbsp; My first step,
since I wasn’t really sure how to do this, was to write a test.&amp;nbsp; And I made it
more or less mirror the issue I was facing, a list of two items, one of which is a
dependency of the other.&amp;nbsp; I don’t know if there is a lot of value in posting
all of the test cases here, but the end result was rather nice.&amp;nbsp; Sure it took
several iterations, and there was plenty of infinite looping and stack overflows (which
does some fun things to studio when your running your tests with TestDriven.Net),
but I think this is a reasonable solution to the problem:
&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;public static IEnumerable&amp;lt;T&amp;gt; EnsureDependenciesFirst&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; items, Func&amp;lt;T ,IEnumerable&amp;gt; selector)
{
    if(items.Count() &amp;lt; 2)
        return;
    var firstPass = items.SkipWhile(t =&amp;gt; items.Intersect(selector(t)).Count() &amp;gt; 0);
    var remainingItems = items.Except(firstPass);
    if(items.Count() == remainingItems.Count())
        return remainingItems;
    return firstPass.Concat(remainingItems.EnsureDependenciesFirst(selector));
}
&lt;/pre&gt;
&lt;p&gt;
Ok, so what do we have here?&amp;nbsp; Well to start out I’m checking the item list to
see if there are at least two items in it, if not I just return the list.&amp;nbsp; This
provides a means to avoid an infinate loop due to the recursive call, and provides
a shortcut for a scenario with only one item.&amp;nbsp; Next off I use the SkipWhile()
method, combined with the user-supplied selector function to iterate through each
item, retrieve it’s list of dependencies (which is what the selector function does),
and checks to see if the current list contains any of the dependencies for the object.&amp;nbsp;
The results of this first pass are the objects which have no dependencies at all,
so therefore they need to be first in the list.&amp;nbsp; The next logical step is to
run the operation again for a list that &lt;strong&gt;does not&lt;/strong&gt; contains the items
filtered out by the first pass.&amp;nbsp; This is done via a recursive call back to the
EnsureDependenciesFirst extension.&amp;nbsp; You will notice we’re checking the count
of the remaining items against the current list, and returning the list if they are
the same.&amp;nbsp; This is another safety precaution for dealing with infinite loops.&amp;nbsp;
If we have a circular dependency, this bit will just return the items that are interdependent.
&lt;/p&gt;
&lt;p&gt;
You will note that this is a generic function that has really noting at all to do
with the entities that I am dealing with.&amp;nbsp; This was largely due to the fact that
this was built TDD, so I just used a simple class which had a property that could
take another instance of itself.&amp;nbsp; To use this to overcome my entity committing
problem, I would have to write a not too small function to retrieve the list of dependent
objects from the entity (since there would need to be some reflection magic to look
at attributes on the properties to determine which properties contain dependencies),
but it pretty much will drop in to the foreach statement that is currently being used
to persist the entities.
&lt;/p&gt;
&lt;p&gt;
Incidently, I learned from my dev team what the “official” way of dealing with this
is a “ReorderChanges” method, which takes two entities, in the order in which they
should be persisted.&amp;nbsp; I think I like my solution better, mostly because it should
mean I don’t have to worry about it again.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=c2e87a52-29b5-4ef9-8a22-a61a68031f0c" /&gt;</description>
      <comments>http://www.drrandom.org/CommentView,guid,c2e87a52-29b5-4ef9-8a22-a61a68031f0c.aspx</comments>
      <category>.Net</category>
      <category>TDD</category>
      <category>tips</category>
    </item>
    <item>
      <trackback:ping>http://www.drrandom.org/Trackback.aspx?guid=df7ca78a-8a93-4a21-9245-39514a67aea4</trackback:ping>
      <pingback:server>http://www.drrandom.org/pingback.aspx</pingback:server>
      <pingback:target>http://www.drrandom.org/PermaLink,guid,df7ca78a-8a93-4a21-9245-39514a67aea4.aspx</pingback:target>
      <dc:creator>Casey Kramer</dc:creator>
      <wfw:comment>http://www.drrandom.org/CommentView,guid,df7ca78a-8a93-4a21-9245-39514a67aea4.aspx</wfw:comment>
      <wfw:commentRss>http://www.drrandom.org/SyndicationService.asmx/GetEntryCommentsRss?guid=df7ca78a-8a93-4a21-9245-39514a67aea4</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <title>Some (good?) string extension methods</title>
      <guid isPermaLink="false">http://www.drrandom.org/PermaLink,guid,df7ca78a-8a93-4a21-9245-39514a67aea4.aspx</guid>
      <link>http://www.drrandom.org/2009/02/22/SomeGoodStringExtensionMethods.aspx</link>
      <pubDate>Sun, 22 Feb 2009 17:19:09 GMT</pubDate>
      <description>&lt;p&gt;
So, to take a slightly different turn from my usual meta discussions of process, theory,
and architecture, there have been several people who have offered up some examples
of extension methods that they have found useful, now that .Net 3.5 is roaring along
nicely. There are some collections of such utilities, like the &lt;a href="http://www.codeplex.com/umbrella"&gt;Umbrella
project&lt;/a&gt;, and some folks like &lt;a href="http://srtsolutions.com/blogs/billwagner/default.aspx"&gt;Bill
Wagner&lt;/a&gt; who have &lt;a href="http://www.amazon.com/More-Effective-Specific-Software-Development/dp/0321485890"&gt;written
books&lt;/a&gt; on the subject (okay, there are other things in there too), so I thought
I might as well throw my hat into the ring as well. Specifically, there was this &lt;a href="http://twitter.com/elijahmanor/status/1219521290"&gt;tweet&lt;/a&gt; from &lt;a href="http://twitter.com/elijahmanor"&gt;@elijahmanor&lt;/a&gt; a
few days ago. It points to a positing which includes some extensions on string to
convert from strings to value types (int, long, short, etc). I pointed out that in
our current project we have distilled this down to a single extension method: To&lt;T&gt;
().
&lt;/p&gt;
&lt;p&gt;
He suggested I blog about it, so here it is:
&lt;/p&gt;
&lt;p&gt;
So we actually have two classes of conversions, one converts from a string to a value
type, and they other converts from a string to a Nullable value type. In the case
of our project, the nullable version came first, and so it became very easy to create
the version that returned a non-nullable value. Here are the methods of interest:
&lt;/p&gt;
&lt;pre class="brush: csharp" name="code"&gt;public static T To&lt;T&gt;
(this string input) where T : struct { return input.To&lt;T&gt;
(default(T)); } public static T To&lt;T&gt;
(this string input, T defaultValue) where T: struct { return input.ToNullable&lt;T&gt;
() ?? defaultValue; } public static T? ToNullable&lt;T&gt;
(this string input) where T : struct { if (string.IsNullOrEmpty(input)) return null;
var tryParse = GetTryParse&lt;T&gt;
(); return (T?)tryParse(input); }
&lt;/pre&gt;
&lt;p&gt;&lt;&gt; delegate that will run the string input through the try parse and return either a null (in case the TryParse fails), or a boxed version of the result.  So, lets see what it looks like before we discuss pros and cons&lt;/p&gt;
Okay, so this is pretty straight forward. The non-nullable version calls through to
the nullable version, and if it is null, it returns default(T). But, as I'm sure you
are an astute reader, you will see that there is some magic going on; namely the GetTryParse()
method. This little guy goes off and looks for a TryParse method on whatever T happens
to be, and then returns a Func&lt;pre class="brush: csharp" &gt;&lt;string,object&gt;private static Func GetTryParse&lt;T&gt;
() { var tryParseEx = GetTryParseExpression&lt;T&gt;&lt;Func&lt;string,object&gt;
(); return (s) =&gt; tryParseEx.Compile()(s,default(T)); } private static Expression&gt;
GetTryParseExpression&lt;T&gt;&lt;Func&lt;string, T, object&gt;&lt;Func&lt;string,object&gt;
() { if (_tryParseCache.ContainsKey(typeof(T))) return _tryParseCache[typeof(T)] as
Expression&gt;; MethodInfo tryParse = typeof(T).GetMethod("TryParse", new Type[] { typeof(string),
typeof(T).MakeByRefType() }); Ensure.IsNotNull(tryParse, string.Format("Cannot convert
from type string to type {0} because {0} does not have a TryParse method", typeof(T).FullName));
var stringArg = Expression.Parameter(typeof(string), "input"); var tempArg = Expression.Parameter(typeof(T),
"tmp"); var tryParseEx = Expression.Lambda&gt;( Expression.Condition( Expression.Call(tryParse,
stringArg, tempArg) , Expression.Convert(tempArg, typeof(object)) , Expression.Constant(null))
, stringArg, tempArg); _tryParseCache.Add(typeof(T), tryParseEx); return tryParseEx;
}
&lt;/pre&gt;
&lt;p&gt;
So here we have some code looking for a TryParse method, and building an expression
(using Linq Expression Trees) to execute it. Now, I'll be honest, this is not the
code I'm using in the project where this originally came from...mostly because I didn't
think of it then. In that case I'm actually doing a big case statement, checking the
type of T and running the appropriate method. This is much shorter, but potentially
much slower at runtime. So that is where the _tryParseCache comes in. This is a simple
static dictionary which contains the expressions created for each of the types, which
means you only get the runtime performance hit once when you first ask to parse a
specific type. The declaration for this object looks like this:&lt;br&gt;
&lt;/p&gt;
&lt;pre class="brush: csharp" name="code"&gt;private static Dictionary&lt;Type ,Expression&gt;
_tryParseCache = new Dictionary&lt;type ,Expression&gt;
(); 
&lt;/pre&gt;
&lt;p&gt;
There you have it, my first (and possibly last??) contribution into the world of extension
methods. Please commence criticisms
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=df7ca78a-8a93-4a21-9245-39514a67aea4" /&gt;</description>
      <comments>http://www.drrandom.org/CommentView,guid,df7ca78a-8a93-4a21-9245-39514a67aea4.aspx</comments>
      <category>.Net</category>
      <category>tips</category>
    </item>
    <item>
      <trackback:ping>http://www.drrandom.org/Trackback.aspx?guid=4ec5e15f-86a5-49b2-bdde-569311078d63</trackback:ping>
      <pingback:server>http://www.drrandom.org/pingback.aspx</pingback:server>
      <pingback:target>http://www.drrandom.org/PermaLink,guid,4ec5e15f-86a5-49b2-bdde-569311078d63.aspx</pingback:target>
      <dc:creator>Casey Kramer</dc:creator>
      <wfw:comment>http://www.drrandom.org/CommentView,guid,4ec5e15f-86a5-49b2-bdde-569311078d63.aspx</wfw:comment>
      <wfw:commentRss>http://www.drrandom.org/SyndicationService.asmx/GetEntryCommentsRss?guid=4ec5e15f-86a5-49b2-bdde-569311078d63</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I'm currently finding myself in the midst of an evolutionary change.  And I'm
not talking about my super-human mutant powers, I'm talking about the way I'm thinking
about solving a specific set of problems. 
</p>
        <p>
Let's start with a sample....Lets take something like processing credit-cards as a
benign and IP free place to start.  As a subject that I really have no practical
experience with, it seems like an appropriate choice.  I'm going to assume that
there are different rules for doing checksum validation on credit card numbers, depending
on what the card is (Mastercard/Visa/Discover/etc). Now, here is evolutionary step
1: Use a basic case statement to process the various cards.  Here is what something
like that would look like:<br /></p>
        <pre class="brush: csharp">switch(CardType)
{
    case CardType.MasterCard:
        CardValidators.MasterCardValidator(card.CardNumber);
        break;
    case CardType.Visa:
        CardValidators.VisaValidator(card.CardNumber);
        break;
    case CardType.Discover:
        CardValidators.DiscoverValidator(card.CardNumber);
        break;
}</pre>
        <p>
 
</p>
        <p>
This looks pretty straight-forward, and as it stands it isn't too bad from a maintainability
stand point.  But what happens when there are many different types of cards? 
An then what happens when you find a large amount of duplication between the validation
functions?
</p>
        <p>
Well, any student of GoF should be able to tell you that a Chain Of Responsibility
pattern looks like a perfect fit for this sort of scenario.  So, evolutionary
step 2: Create separate classes to handle the different types of validation, and configure
them in a Chain of Responsibility pattern where each instance decides for itself whether
it can process the input.
</p>
        <p>
Here is a quick and dirty look at what something like that would look like:<br /><img style="border-width: 0px;" alt="ClassDiagram1" src="http://www.drrandom.org/content/binary/ClassDiagram1.png" border="0" height="421" width="571" /></p>
        <p>
 
</p>
        <p>
The two most interesting things here are the GetValidator() method in the AbstractCardValidator,
and the individual CanValidate() methods in the concrete implementations.  What
this does is it allows each class to decide for itself how it is going to determine
whether or not it can be used as a validator for a specific card (thats the CanValidate()
part), and also provides a single point which the consumer of the API can use to get <em>the</em> validator
for the card instance they have.  You would probably want to build and Abstract
Factory around this, which would instantiate all of the ICardValidator classes, and
then run the GetValidator() method to get the correct one.
</p>
        <p>
Now we are at a point where things are looking pretty good; we've got the ability
to do some fairly complex logic to make the decision about which validator to use,
and we have a way to simply ask for one, and the correct one appears.  Pretty
cool.
</p>
        <p>
This is actually the place where I have found myself in the not to distant past. 
I have previously been perfectly content with this arrangement, and been fairly happy
with the separation of concerns among the classes...I mean, after all, who better
to decide whether or not a specific class should be used to validate a card than the
class itself.  So what is the issue?  Well, recently I have become aware
of two problems with this arrangement: Tight Coupling, and a violation of the Single
Responsibility Principle.  Let's start with the first:
</p>
        <p>
          <strong>Tight Coupling<br /></strong>The credit card example may be a bit contrived when it comes to this issue,
but bear with me.  Overall, the issue is that specific instances of ICardValidtor
objects are being created and handed around.  The use of an interface and an
Abstract Factory pattern would actually help the situation out some, but effectively
all it does is move the coupling from the consuming class to the Factory (okay, it
also consolidates coupling to a single class, which makes maintenance a lot easier). 
As I said, contained, but still there.  It would be nice if the factory didn't
need any knowledge of what concrete instances of ICardValidator were out there. 
Before we tackle that, though, lets also look at the second issue:
</p>
        <p>
          <strong>Violation of the "Single Responsibility Principle"<br /></strong>The SRP states that a class should have one, and only one, thing it is responsible
for.  Sounds pretty easy doesn't it?  The problem is that this can be difficult
to obtain without a fair amount of discipline.  The violation of SRP which
I'm seeing is that the ICardValidator is responsible for both validating a credit
card <em>and</em> determining which validator is appropriate.  But wait! 
Didn't I just say that moving this check into the ICardValidator instance was a "Good
Thing"?  Well, lets go as far as saying it is <em>better</em> than the previous
method, but still not perfect.  Applying the SRP would move the task of selecting
a validator from the ICardValidator instance, and put it on it's own somewhere. 
So, thusly we come to our:
</p>
        <p>
          <strong>Inversion Of Control Container</strong>.<br />
That's right, we are now going to get crazy and move the responsibility of creating
these instances to another component all together.  The nice thing about this
is that it allows us to move all of the knowledge about dependencies off somewhere
else.  How does this apply to this example?  Well, lets assume we have an
object of type <em>Card</em> which requires as a dependency an instance of an <em>ICardValidator.  </em>We'll
also assume that <em>Card</em> is subclassed based on the type of credit card. 
It now becomes trivial to configure our IoC container to supply a <em>specific implementation</em> (read
sub-type) of <em>ICardValidator</em> for each implementation (again, read sub-type)
of <em>Card</em>.  Now, when you want a <em>Card</em> instance, you ask the IoC
container for one, and depending on what type of card it is, you will get the appropriate <em>ICardValidator</em> as
well.
</p>
        <p>
What's the catch?  Well there is some additional complexity which will show up
somewhere in the application due to the IoC, but typically IoC configuration can be
delegated down to the configuration file level, so even then the ugliness is pushed
away to it's own dark corner.
</p>
        <p>
But wait!  Why should we have different instances of <em>Card</em>?  What
if the Card class is just a container for the card data?  Well, our Ioc still
gives us some advantages.  If we look back at our first example with the switch
statement, we've got a nice <em>CardType</em> enum, which could be a property of our <em>Card</em> class. 
Using an IoC container like the one provided by the Castle project, you have the ability
to configure a key string for your instances.  This would make it trivial to
map the enum choices to specific keys within the container, which the <em>Card</em> class
would use to get an ICardValidator instance.  This would also make it possible
to make the validators slightly more advanced by adding something like a Decorator
pattern, in which specific aspects of the validation could be factored into separate
classes, and then "stacked" to produce the final validation logic (This is the same
concept used by the Stream classes in .Net and Java.  You can modify the behavior
of a stream by passing it to the constructor of a stream with different behavior).
</p>
        <p>
It is definatly worth mentioning that there is a sudden appearance
of tight coupling to the IoC container itself from our consuming classes.  You
probably want to try to abstract away the fact that the IoC container exists from
the majority of the application.  Factory classes go a fair ways in making this
happen, but another good idea is to introduce a single service to do type resolution. 
The Factory classes can then ask this service for the object they want, and they never
need to know the IoC container is there.  This approach also gives you the ability
to create some objects using IoC and others in another (more traditional) way.
</p>
        <p>
So is this it?  Have I finally found the answer I've been looking for? 
It's hard to say right now.  For the time being this is a decent way to handle
things, provided the complexity of the underlying system, and the need for loose-coupling
are both high enough to justify the additional complexity of the IoC.  But who
knows, in another couple months I may find something new, or even something old, which
seems better, cleaner, simpler.  That, after all, is my final goal....And I need
to remind myself of that regularly, lest I become complacent.
</p>
        <img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=4ec5e15f-86a5-49b2-bdde-569311078d63" />
      </body>
      <title>The evolution of design, and the continued search for &amp;quot;The Way&amp;quot;</title>
      <guid isPermaLink="false">http://www.drrandom.org/PermaLink,guid,4ec5e15f-86a5-49b2-bdde-569311078d63.aspx</guid>
      <link>http://www.drrandom.org/2007/10/02/TheEvolutionOfDesignAndTheContinuedSearchForQuotTheWayquot.aspx</link>
      <pubDate>Tue, 02 Oct 2007 20:53:13 GMT</pubDate>
      <description>&lt;p&gt;
I'm currently finding myself in the midst of an evolutionary change.&amp;nbsp; And I'm
not talking about my super-human mutant powers, I'm talking about the way I'm thinking
about solving a specific set of problems. 
&lt;/p&gt;
&lt;p&gt;
Let's start with a sample....Lets take something like processing credit-cards as a
benign and IP free place to start.&amp;nbsp; As a subject that I really have no practical
experience with, it seems like an appropriate choice.&amp;nbsp; I'm going to assume that
there are different rules for doing checksum validation on credit card numbers, depending
on what the card is (Mastercard/Visa/Discover/etc). Now, here is evolutionary step
1: Use a basic case statement to process the various cards.&amp;nbsp; Here is what something
like that would look like:&lt;br&gt;
&lt;/p&gt;
&lt;pre class="brush: csharp"&gt;switch(CardType)
{
    case CardType.MasterCard:
        CardValidators.MasterCardValidator(card.CardNumber);
        break;
    case CardType.Visa:
        CardValidators.VisaValidator(card.CardNumber);
        break;
    case CardType.Discover:
        CardValidators.DiscoverValidator(card.CardNumber);
        break;
}&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
This looks pretty straight-forward, and as it stands it isn't too bad from a maintainability
stand point.&amp;nbsp; But what happens when there are many different types of cards?&amp;nbsp;
An then what happens when you find a large amount of duplication between the validation
functions?
&lt;/p&gt;
&lt;p&gt;
Well, any student of GoF should be able to tell you that a Chain Of Responsibility
pattern looks like a perfect fit for this sort of scenario.&amp;nbsp; So, evolutionary
step 2: Create separate classes to handle the different types of validation, and configure
them in a Chain of Responsibility pattern where each instance decides for itself whether
it can process the input.
&lt;/p&gt;
&lt;p&gt;
Here is a quick and dirty look at what something like that would look like:&lt;br&gt;
&lt;img style="border-width: 0px;" alt="ClassDiagram1" src="http://www.drrandom.org/content/binary/ClassDiagram1.png" border="0" height="421" width="571"&gt; 
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
The two most interesting things here are the GetValidator() method in the AbstractCardValidator,
and the individual CanValidate() methods in the concrete implementations.&amp;nbsp; What
this does is it allows each class to decide for itself how it is going to determine
whether or not it can be used as a validator for a specific card (thats the CanValidate()
part), and also provides a single point which the consumer of the API can use to get &lt;em&gt;the&lt;/em&gt; validator
for the card instance they have.&amp;nbsp; You would probably want to build and Abstract
Factory around this, which would instantiate all of the ICardValidator classes, and
then run the GetValidator() method to get the correct one.
&lt;/p&gt;
&lt;p&gt;
Now we are at a point where things are looking pretty good; we've got the ability
to do some fairly complex logic to make the decision about which validator to use,
and we have a way to simply ask for one, and the correct one appears.&amp;nbsp; Pretty
cool.
&lt;/p&gt;
&lt;p&gt;
This is actually the place where I have found myself in the not to distant past.&amp;nbsp;
I have previously been perfectly content with this arrangement, and been fairly happy
with the separation of concerns among the classes...I mean, after all, who better
to decide whether or not a specific class should be used to validate a card than the
class itself.&amp;nbsp; So what is the issue?&amp;nbsp; Well, recently I have become aware
of two problems with this arrangement: Tight Coupling, and a violation of the Single
Responsibility Principle.&amp;nbsp; Let's start with the first:
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Tight Coupling&lt;br&gt;
&lt;/strong&gt;The credit card example may be a bit contrived when it comes to this issue,
but bear with me.&amp;nbsp; Overall, the issue is that specific instances of ICardValidtor
objects are being created and handed around.&amp;nbsp; The use of an interface and an
Abstract Factory pattern would actually help the situation out&amp;nbsp;some, but effectively
all it does is move the coupling from the consuming class to the Factory (okay, it
also consolidates coupling to a single class, which makes maintenance a lot easier).&amp;nbsp;
As I said, contained, but still there.&amp;nbsp; It would be nice if the factory didn't
need any knowledge of what concrete instances of ICardValidator were out there.&amp;nbsp;
Before we tackle that, though, lets also look at the second issue:
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Violation of the "Single Responsibility Principle"&lt;br&gt;
&lt;/strong&gt;The SRP states that a class should have one, and only one, thing it is responsible
for.&amp;nbsp; Sounds pretty easy doesn't it?&amp;nbsp; The problem is that this can be difficult
to obtain without a fair&amp;nbsp;amount of discipline.&amp;nbsp; The violation of SRP which
I'm seeing is that the ICardValidator is responsible for both validating a credit
card &lt;em&gt;and&lt;/em&gt; determining which validator is appropriate.&amp;nbsp; But wait!&amp;nbsp;
Didn't I just say that moving this check into the ICardValidator instance was a "Good
Thing"?&amp;nbsp; Well, lets go as far as saying it is &lt;em&gt;better&lt;/em&gt; than the previous
method, but still not perfect.&amp;nbsp; Applying the SRP would move the task of selecting
a validator from the ICardValidator instance, and put it on it's own somewhere.&amp;nbsp;
So, thusly we come to our:
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Inversion Of Control Container&lt;/strong&gt;.&lt;br&gt;
That's right, we are now going to get crazy and move the responsibility of creating
these instances to another component all together.&amp;nbsp; The nice thing about this
is that it allows us to move all of the knowledge about dependencies off somewhere
else.&amp;nbsp; How does this apply to this example?&amp;nbsp; Well, lets assume we have an
object of type &lt;em&gt;Card&lt;/em&gt; which requires as a dependency an instance of an &lt;em&gt;ICardValidator.&amp;nbsp; &lt;/em&gt;We'll
also assume that &lt;em&gt;Card&lt;/em&gt; is subclassed based on the type of credit card.&amp;nbsp;
It now becomes trivial to configure our IoC container to supply a &lt;em&gt;specific implementation&lt;/em&gt; (read
sub-type) of &lt;em&gt;ICardValidator&lt;/em&gt; for each implementation (again, read sub-type)
of &lt;em&gt;Card&lt;/em&gt;.&amp;nbsp; Now, when you want a &lt;em&gt;Card&lt;/em&gt; instance, you ask the IoC
container for one, and depending on what type of card it is, you will get the appropriate &lt;em&gt;ICardValidator&lt;/em&gt; as
well.
&lt;/p&gt;
&lt;p&gt;
What's the catch?&amp;nbsp; Well there is some additional complexity which will show up
somewhere in the application due to the IoC, but typically IoC configuration can be
delegated down to the configuration file level, so even then the ugliness is pushed
away to it's own dark corner.
&lt;/p&gt;
&lt;p&gt;
But wait!&amp;nbsp; Why should we have different instances of &lt;em&gt;Card&lt;/em&gt;?&amp;nbsp; What
if the Card class is just a container for the card data?&amp;nbsp; Well, our Ioc still
gives us some advantages.&amp;nbsp; If we look back at our first example with the switch
statement, we've got a nice &lt;em&gt;CardType&lt;/em&gt; enum, which could be a property of our &lt;em&gt;Card&lt;/em&gt; class.&amp;nbsp;
Using an IoC container like the one provided by the Castle project, you have the ability
to configure a key string for your instances.&amp;nbsp; This would make it trivial to
map the enum choices to specific keys within the container, which the &lt;em&gt;Card&lt;/em&gt; class
would use to get an ICardValidator instance.&amp;nbsp; This would also make it possible
to make the validators slightly more advanced by adding something like a Decorator
pattern, in which specific aspects of the validation could be factored into separate
classes, and then "stacked" to produce the final validation logic (This is the same
concept used by the Stream classes in .Net and Java.&amp;nbsp; You can modify the behavior
of a stream by passing it to the constructor of a stream with different behavior).
&lt;/p&gt;
&lt;p&gt;
It is definatly&amp;nbsp;worth mentioning&amp;nbsp;that there is a&amp;nbsp;sudden appearance
of tight coupling to the IoC container itself from our consuming classes.&amp;nbsp; You
probably want to try to abstract away the fact that the IoC container exists from
the majority of the application.&amp;nbsp; Factory classes go a fair ways in making this
happen, but another good idea is to introduce a single service to do type resolution.&amp;nbsp;
The Factory classes can then ask this service for the object they want, and they never
need to know the IoC container is there.&amp;nbsp; This approach also gives you the ability
to create some objects using IoC and others in another (more traditional) way.
&lt;/p&gt;
&lt;p&gt;
So is this it?&amp;nbsp; Have I finally found the answer I've been looking for?&amp;nbsp;
It's hard to say right now.&amp;nbsp; For the time being this is a decent way to handle
things, provided the complexity of the underlying system, and the need for loose-coupling
are both high enough to justify the additional complexity of the IoC.&amp;nbsp; But who
knows, in another couple months I may find something new, or even something old, which
seems better, cleaner, simpler.&amp;nbsp; That, after all, is my final goal....And I need
to remind myself of that regularly, lest I become complacent.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=4ec5e15f-86a5-49b2-bdde-569311078d63" /&gt;</description>
      <comments>http://www.drrandom.org/CommentView,guid,4ec5e15f-86a5-49b2-bdde-569311078d63.aspx</comments>
      <category>.Net</category>
      <category>IoC</category>
      <category>tips</category>
    </item>
    <item>
      <trackback:ping>http://www.drrandom.org/Trackback.aspx?guid=11a503e2-ba17-47ad-baec-d238fd5dccb4</trackback:ping>
      <pingback:server>http://www.drrandom.org/pingback.aspx</pingback:server>
      <pingback:target>http://www.drrandom.org/PermaLink,guid,11a503e2-ba17-47ad-baec-d238fd5dccb4.aspx</pingback:target>
      <dc:creator>Casey Kramer</dc:creator>
      <wfw:comment>http://www.drrandom.org/CommentView,guid,11a503e2-ba17-47ad-baec-d238fd5dccb4.aspx</wfw:comment>
      <wfw:commentRss>http://www.drrandom.org/SyndicationService.asmx/GetEntryCommentsRss?guid=11a503e2-ba17-47ad-baec-d238fd5dccb4</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I ran into this issue today when trying to find a quick and dirty script to enforce
redirection from HTTP to HTTPS for an intranet site we're enabling for HTTPS (yes,
I know SSL on an intranet???  One word - Audit).  I thought this would be
easy...I half expected that there would be an IIS setting to handle this for me; I
was wrong on both counts.  So what I ended up doing is using an old DNN HttpModule
which was set up to allow the user to specify specific tabs in DNN for SSL, and greatly
simplifying things to work to my advantage.  I thought I would post it so I wouldn't
have to look for it again.
</p>
        <p>
To give a quick overview of what is going on, this is an HTTP Module which looks at
a value in the web.config to determine whether or not to enforce HTTPS or not. 
If the setting is set to true (or yes), then I'm just grabbing the Url property from
the Request object, loading it up in a UriBuilder, and setting the Scheme to "https",
and the port to 443 (this may not be necessary, but it was generating an URL with
a port of 80 before, which defeats the purpose so I decided to play it safe). 
It then feeds the generated URI to Response.Redirect(), and your off.  There
is some additional code in there to disable the feature if your on localhost, which
is mostly to keep from blowing up your dev box.
</p>
        <p>
Here is the class:
</p>
        <pre class="brush: csharp" name="code">using System;
using System.Configuration;
using System.Web;


namespace HTTPSRedirectHandler
{
    /// &lt;summary&gt;
    /// An HttpModule which redirects traffic to HTTPS based on configuration settings.
    /// &lt;/summary&gt;
    public class HttpsRedirector : IHttpModule
    {
        HttpApplication _context;

        public HttpsRedirector()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        #region IHttpModule Members

        /// &lt;summary&gt;
        /// Initializes a module and prepares it to handle
        /// requests.
        /// &lt;/summary&gt;
        /// &lt;param name="context"&gt;An &lt;see cref="T:System.Web.HttpApplication"/&gt; that provides access to the methods, properties, and events common to all application objects within an ASP.NET application&lt;/param&gt;
        public void Init(HttpApplication context)
        {
            _context = context;
            _context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        /// &lt;summary&gt;
        /// Disposes of the resources (other than memory) used by the
        /// module that implements &lt;see langword="IHttpModule."/&gt;
        /// &lt;/summary&gt;
        public void Dispose()
        {
            _context.BeginRequest -= new EventHandler(context_BeginRequest);
            _context.Dispose();
        }

        #endregion

        /// &lt;summary&gt;
        /// Handles the BeginRequest event of the current Http Context.
        /// &lt;/summary&gt;
        private void context_BeginRequest(object sender, EventArgs e)
        {
            bool useSSL = false;
            string result = null;
            if((result = ConfigurationSettings.AppSettings["RequireSSL"]) != null)
            {
                if(result.ToUpper() == "TRUE" || result.ToUpper() == "YES")
                    useSSL = true;
            }
            if (useSSL)
                EnforceSSL();
        }

        /// &lt;summary&gt;
        /// Enforces a redirection to HTTPS if the current connection is using HTTP (port 80).
        /// &lt;/summary&gt;
        private void EnforceSSL()
        {
            if(_context.Request.ServerVariables["SERVER_NAME"].ToLower() != "localhost")
            {
                if(_context.Request.ServerVariables["SERVER_PORT"] == "80")
                {
                    UriBuilder uri = new UriBuilder(_context.Request.Url);
                    uri.Scheme = "https";
                    uri.Port = 443;
                    _context.Response.Redirect(uri.ToString());
                }
            }
        }
    }
}
</pre>
        <p>
          <a href="http://11011.net/software/vspaste">
          </a> 
</p>
        <p>
Here is the web.config settings you need to use it:
</p>
        <pre class="brush: xml" name="code">&lt;httpModules&gt;
    &lt;add name="SSLRedirect" type="HTTPSRedirectHandler.HttpsRedirector, HTTPSRedirectHandler" /&gt;<br />
&lt;/httpModules&gt;</pre>
        <pre class="xml" name="code"> </pre>
        <pre class="brush: xml" name="code">&lt;appSettings&gt;<br />
&lt;add key="RequireSSL" value="True" /&gt; &lt;/appSettings&gt;</pre>
        <p>
        </p>
        <img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=11a503e2-ba17-47ad-baec-d238fd5dccb4" />
      </body>
      <title>Forcing redirection to HTTPS in ASP.Net</title>
      <guid isPermaLink="false">http://www.drrandom.org/PermaLink,guid,11a503e2-ba17-47ad-baec-d238fd5dccb4.aspx</guid>
      <link>http://www.drrandom.org/2007/08/17/ForcingRedirectionToHTTPSInASPNet.aspx</link>
      <pubDate>Fri, 17 Aug 2007 21:02:01 GMT</pubDate>
      <description>&lt;p&gt;
I ran into this issue today when trying to find a quick and dirty script to enforce
redirection from HTTP to HTTPS for an intranet site we're enabling for HTTPS (yes,
I know SSL on an intranet???&amp;nbsp; One word - Audit).&amp;nbsp; I thought this would be
easy...I half expected that there would be an IIS setting to handle this for me; I
was wrong on both counts.&amp;nbsp; So what I ended up doing is using an old DNN HttpModule
which was set up to allow the user to specify specific tabs in DNN for SSL, and greatly
simplifying things to work to my advantage.&amp;nbsp; I thought I would post it so I wouldn't
have to look for it again.
&lt;/p&gt;
&lt;p&gt;
To give a quick overview of what is going on, this is an HTTP Module which looks at
a value in the web.config to determine whether or not to enforce HTTPS or not.&amp;nbsp;
If the setting is set to true (or yes), then I'm just grabbing the Url property from
the Request object, loading it up in a UriBuilder, and setting the Scheme to "https",
and the port to 443 (this may not be necessary, but it was generating an URL with
a port of 80 before, which defeats the purpose so I decided to play it safe).&amp;nbsp;
It then feeds the generated URI to Response.Redirect(), and your off.&amp;nbsp; There
is some additional code in there to disable the feature if your on localhost, which
is mostly to keep from blowing up your dev box.
&lt;/p&gt;
&lt;p&gt;
Here is the class:
&lt;/p&gt;
&lt;pre class="brush: csharp" name="code"&gt;using System;
using System.Configuration;
using System.Web;


namespace HTTPSRedirectHandler
{
    /// &amp;lt;summary&amp;gt;
    /// An HttpModule which redirects traffic to HTTPS based on configuration settings.
    /// &amp;lt;/summary&amp;gt;
    public class HttpsRedirector : IHttpModule
    {
        HttpApplication _context;

        public HttpsRedirector()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        #region IHttpModule Members

        /// &amp;lt;summary&amp;gt;
        /// Initializes a module and prepares it to handle
        /// requests.
        /// &amp;lt;/summary&amp;gt;
        /// &amp;lt;param name="context"&amp;gt;An &amp;lt;see cref="T:System.Web.HttpApplication"/&amp;gt; that provides access to the methods, properties, and events common to all application objects within an ASP.NET application&amp;lt;/param&amp;gt;
        public void Init(HttpApplication context)
        {
            _context = context;
            _context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        /// &amp;lt;summary&amp;gt;
        /// Disposes of the resources (other than memory) used by the
        /// module that implements &amp;lt;see langword="IHttpModule."/&amp;gt;
        /// &amp;lt;/summary&amp;gt;
        public void Dispose()
        {
            _context.BeginRequest -= new EventHandler(context_BeginRequest);
            _context.Dispose();
        }

        #endregion

        /// &amp;lt;summary&amp;gt;
        /// Handles the BeginRequest event of the current Http Context.
        /// &amp;lt;/summary&amp;gt;
        private void context_BeginRequest(object sender, EventArgs e)
        {
            bool useSSL = false;
            string result = null;
            if((result = ConfigurationSettings.AppSettings["RequireSSL"]) != null)
            {
                if(result.ToUpper() == "TRUE" || result.ToUpper() == "YES")
                    useSSL = true;
            }
            if (useSSL)
                EnforceSSL();
        }

        /// &amp;lt;summary&amp;gt;
        /// Enforces a redirection to HTTPS if the current connection is using HTTP (port 80).
        /// &amp;lt;/summary&amp;gt;
        private void EnforceSSL()
        {
            if(_context.Request.ServerVariables["SERVER_NAME"].ToLower() != "localhost")
            {
                if(_context.Request.ServerVariables["SERVER_PORT"] == "80")
                {
                    UriBuilder uri = new UriBuilder(_context.Request.Url);
                    uri.Scheme = "https";
                    uri.Port = 443;
                    _context.Response.Redirect(uri.ToString());
                }
            }
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
Here is the web.config settings you need to use it:
&lt;/p&gt;
&lt;pre class="brush: xml" name="code"&gt;&amp;lt;httpModules&amp;gt;
    &amp;lt;add name="SSLRedirect" type="HTTPSRedirectHandler.HttpsRedirector, HTTPSRedirectHandler" /&amp;gt;&lt;br&gt;
&amp;lt;/httpModules&amp;gt;&lt;/pre&gt;&lt;pre class="xml" name="code"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre class="brush: xml" name="code"&gt;&amp;lt;appSettings&amp;gt;&lt;br&gt;
&amp;lt;add key="RequireSSL" value="True" /&amp;gt; &amp;lt;/appSettings&amp;gt;&lt;/pre&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=11a503e2-ba17-47ad-baec-d238fd5dccb4" /&gt;</description>
      <comments>http://www.drrandom.org/CommentView,guid,11a503e2-ba17-47ad-baec-d238fd5dccb4.aspx</comments>
      <category>tips</category>
    </item>
    <item>
      <trackback:ping>http://www.drrandom.org/Trackback.aspx?guid=b9218a06-498e-4522-8051-eec7bae30730</trackback:ping>
      <pingback:server>http://www.drrandom.org/pingback.aspx</pingback:server>
      <pingback:target>http://www.drrandom.org/PermaLink,guid,b9218a06-498e-4522-8051-eec7bae30730.aspx</pingback:target>
      <dc:creator>Casey Kramer</dc:creator>
      <wfw:comment>http://www.drrandom.org/CommentView,guid,b9218a06-498e-4522-8051-eec7bae30730.aspx</wfw:comment>
      <wfw:commentRss>http://www.drrandom.org/SyndicationService.asmx/GetEntryCommentsRss?guid=b9218a06-498e-4522-8051-eec7bae30730</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">I recently ran across an intranet reporting
app which required IE6 (or, I should say, would not work with IE7 or FireFox 2). 
I upgraded to IE7 originally after numerous javascript errors, and a desire to check
out CardSpace, and thus far had not had too many problems.  This was a potential
issue, however.<br /><br />
Fortunately there is a ready made solution: Multiple IE's.  This little gem is
a single installer, which will allow you to install any version of IE from 3 through
6 in it's own folder so it does not interfere with the default install.  You
can pick it up at <a href="http://tredosoft.com/Multiple_IE">http://tredosoft.com/Multiple_IE</a><br /><br /><br /><p class="poweredbyperformancing">
powered by <a href="http://performancing.com/firefox">performancing firefox</a></p><img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=b9218a06-498e-4522-8051-eec7bae30730" /></body>
      <title>Multiple IEs</title>
      <guid isPermaLink="false">http://www.drrandom.org/PermaLink,guid,b9218a06-498e-4522-8051-eec7bae30730.aspx</guid>
      <link>http://www.drrandom.org/2007/01/08/MultipleIEs.aspx</link>
      <pubDate>Mon, 08 Jan 2007 16:23:33 GMT</pubDate>
      <description>I recently ran across an intranet reporting app which required IE6 (or, I should say, would not work with IE7 or FireFox 2).&amp;nbsp; I upgraded to IE7 originally after numerous javascript errors, and a desire to check out CardSpace, and thus far had not had too many problems.&amp;nbsp; This was a potential issue, however.&lt;br&gt;
&lt;br&gt;
Fortunately there is a ready made solution: Multiple IE's.&amp;nbsp; This little gem is
a single installer, which will allow you to install any version of IE from 3 through
6 in it's own folder so it does not interfere with the default install.&amp;nbsp; You
can pick it up at &lt;a href="http://tredosoft.com/Multiple_IE"&gt;http://tredosoft.com/Multiple_IE&lt;/a&gt;
&lt;br&gt;
&lt;br&gt;
&lt;br&gt;
&lt;p class="poweredbyperformancing"&gt;
powered by &lt;a href="http://performancing.com/firefox"&gt;performancing firefox&lt;/a&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.drrandom.org/aggbug.ashx?id=b9218a06-498e-4522-8051-eec7bae30730" /&gt;</description>
      <comments>http://www.drrandom.org/CommentView,guid,b9218a06-498e-4522-8051-eec7bae30730.aspx</comments>
      <category>tips</category>
    </item>
  </channel>
</rss>