Archive for the ‘.Net’ category

Where did Alt.Net go?

August 11th, 2010

These last few weeks have seen a flurry of emotions from the .Net community.  It appears that a few product releases and a presumptive priority change for IronRuby have caused the world to come crashing down and passengers of the .Net ship to jump overboard.  I’m glad I don’t work for these emotionally unstable individuals, because if we had any debate (I’m aggressive and loud) I’d be concerned they would run from the room crying or worse yet, quit (seems more likely from the rhetoric I hear).  If this is what the Alt.Net community is made of then OSS in the world of .Net has absolutely no chance and the outside OSS world should fear their new recruits.

During the late ‘90s and early 2000s immense business systems where built on the powerhouse platform known as Microsoft Office.  Having worked, well, at all, I’ve seen first hand the ugly, but quite impressive apps built by accountants and marketiers (mark it down, that’s my word) generating great revenues or savings for their companies.  I have replied to requests to “make that an enterprise web app” with “that will fail miserably, keep using it.”  The apps are a disaster waiting to happen themselves, but that’s why we have enterprise backup systems.  It’s just not worth the IT Department’s time to rebuild Excel when it is perfectly suited for their purpose.

In come WebMatrix, LightSaber, I mean LightSwitch, and all the other “low-end” tools.  These are obviously a trend that show Microsoft is abandoning the “high-end” developer (are we really that pompous that we consider ourselves “high-end”, get over yourself you geek.  I bet they make more cash per feature than you).  Or could it be that they are making up for the fact that the last great act of feature development shown by Microsoft to the “low-end”, revenue generating, feature shipping developer is the Ribbon Bar.  I guess you could add SharePoint in there, but I won’t bate you. 

Since 2002, we’ve seen 4 iterations of Silverlight, 4 versions of the Framework, WPF, WCF, the rise of PnP, 5 versions of Visual Studio, Azure, Hyper-V, Team Foundation Server (like it or not), and a dearth of other tools in the same time that Excel has received… drum role… the Ribbon.  Yes there are nicer icons to represent values and you can make prettier tables or charts, but seriously they still use VBA!  In that same time period we’ve seen 2, count them, 2 releases of  the platform on which many businesses survive.

So yes, Microsoft has thrown the Excel and Access productivity worker (not lowend developer) a bone.  They’ve made it easier for you to say, “Sorry, I don’t do Master-Details forms.  Here’s WebMatrix, call me when you want to ship.”  Get over it, start an OSS project or, if you liked it so much, help the IronRuby team build that platform up.  Whatever you do, stop whining and do something.

ReSharper Test Runner and MSTest Projects

July 21st, 2010

One of my biggest irritants with the Unit Testing ecosystem is that each runner does things a little different. Gallio has helped solve this to some extent, but even that hasn’t solved all the problems that come with content or resource file deployments, coverage settings, etc.  Gallio’s goal is noble if not arrogant, become the Runner to Rule Them All. 

Unlikely. 

ReSharper, on the other hand, has taken the Switzerland approach and tries to be true to each testing frameworks settings and run modes.  It has a gap in regards to MSTest at this point, though.  (Who uses MSTest you say?  Lots of people.  You wanted unit testing to become common place, remember?  Stop complaining.)  ReSharper gives you this nasty warning when running your MSTests with Code Coverage enabled.

image

See MSTest is actually pretty sweet when it comes to data capture.  It might not be blazing fast, but it lets you capture an awful lot of information in different situations.  In order to support those different situations nicely there is this file type called Test Settings (*.testsettings).  imageTest Settings files live in your solution folder and you can have a bunch of them.  In fact, Visual Studio 2010 gives you two by default: Local.testsettings and TraceAndTestImpact.testsettings. 

Local.testsettings doesn’t capture anything by default, but one of the first thing everyone tends to look for when running tests is code coverage.  Since Local.testsettings are their default and people don’t realize you can change your active test settings they open Local.testsettings, choose Data and Diagnostics and check Code Coverage (and probably other things that sound interesting).

Enable Code Coverage in Data and Diagnostics of Local.testsettings

Now you’ve eliminated Resharper as a Test Runner.  But you don’t have too!  Remember how I said you can have a bunch of those .testsettings files and eluded to the fact that one can be made Active.  Here’s what you’re going to do:

  1. Right click the Solution Items folder (don’t put them in a different solution folder, VS doesn’t like that, sorry).
  2. Click Add –> New Item
  3. Under Installed Templates (VS 2010) select Test Settings.
  4. Name the new file ReSharper.testsettings (or whatever makes you happy really) and click ok.

The Test Settings editor dialog will come up, but you don’t need to change a thing if you don’t want or need.  Data and Diagnostics will be empty which is good for ReSharper.  At this point, you can go to the Test menu option, open Select Active Test Settings and choose your new settings (ReSharper.testsettings in our example).

That’s it, use ReSharper all you like.  There are some other nice things that ReSharper will do for you in regards to abiding by deployment options for content files and things like that, but we’ll save that for a different day.  Here’s a quick video that highlights everything I’ve outlined here.

Strategy Pattern with Castle Windsor

October 30th, 2009

One of the tangent patterns associated with isolation or Single Responsibility is the Strategy Pattern.  I use Castle Windsor as my IoC of choice and I had hoped there was some black magic built in to make the Strategy Pattern dead simple.  Turns out there is and there isn’t.

What is the Strategy Pattern

The strategy pattern is a way of isolating what would often be found in a case statement.  The bland example being calculating Sales tax on an Order.  Each state and/or country has its own tax calculation and rather than

   1: public void Process(Order order) {
   2:     switch(order.Country) {
   3:         case "USA":
   4:             order.Total = order.Subtotal * .07;
   5:             break;
   6:         case "Canada":
   7:             order.Total = order.Subtotal * .0985;
   8:             break;
   9:     }
  10: 
  11:     // ...
  12: }

you should be breaking each calculation out into different ITaxStrategy implementations and consuming them like so:

   1: public void Process(Order order) {
   2:     var strategy = _taxStrategyFactory.GetStrategyForOrder(order);
   3: 
   4:     var salesTax = strategy.CalculateSalesTax(order);
   5: 
   6:     order.SalesTax = salesTax;
   7:     order.Total = order.SubTotal + order.SalesTax;
   8: }

The question remains, how to eliminate the conditional logic in TaxStrategyFactory determining which strategy is chosen.  The solution is to set up a convention for discovering the available strategies and delegating the criteria to the Strategy itself.

Discovery

The concept here is that we don’t have to “hook up” any new Tax Strategy to our Processing mechanism, we just “publish” new ones in a known way and they are picked up simply based on their existence.  This is often referred to as Convention Over Configuration.  We accomplish this with Castle Windsor with the Fluent Registration API:

   1: container
   2:     .Register(AllTypes
   3:                   .FromAssembly(Assembly.GetExecutingAssembly())
   4:                   .Where(x => x.Name.EndsWith("Strategy"))
   5:                   .WithService.FirstInterface());

This will register all classes found in the executing assembly which have the suffix “Strategy” as implementing the ITaxStrategy interface.  The second half of convention based discovery is consuming the ITaxStrategy implementations.  We can want to get all of these into the TaxStrategyFactory via a constructor array dependency:

   1: public TaxStrategyFactory(params ITaxStrategy[] taxStrategies)
   2: {
   3:     _taxStrategies = taxStrategies;
   4: }

Unfortunately, Windsor doesn’t support arrays as dependencies by default.  Windsor has the concept of Resolvers (a strategy implementation itself) and we are going to have to tell it about the ArrayResolver which knows how to, err, resolve array dependencies:

   1: container
   2:     .Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel));

Cool, so put these all together in our registration code and we get:

   1: container
   2:     .Register(Component
   3:                   .For<IOrderProcessor>()
   4:                   .ImplementedBy<OrderProcessor>())
   5:     .Register(Component
   6:                   .For<ITaxStrategyFactory>()
   7:                   .ImplementedBy<TaxStrategyFactory>())
   8:     .Register(AllTypes
   9:                   .FromAssembly(Assembly.GetExecutingAssembly())
  10:                   .Where(x => x.Name.EndsWith("Strategy"))
  11:                   .WithService.FirstInterface());

At this point we can kick of the true discovery chain of events through:

   1: var processor = container.Resolve<IOrderProcessor>();
   2: 
   3: processor.Process(order);

Delegating Criteria

So in OrderProcessor.Process we are asked the TaxStrategyFactory for the applicable ITaxStrategy implementation:

   1: var strategy = _taxStrategyFactory.GetStrategyForOrder(order);
   2: 
   3: var salesTax = strategy.CalculateSalesTax(order);
   4: 
   5: //...

  The question is, how did the factory determine which of the boundless implementations applies?  That’s the job of each ITaxStrategy itself.  Here’s the implementation of our factory:

   1: class TaxStrategyFactory : ITaxStrategyFactory
   2: {
   3:     private readonly ITaxStrategy[] _taxStrategies;
   4: 
   5:     public TaxStrategyFactory(params ITaxStrategy[] taxStrategies)
   6:     {
   7:         _taxStrategies = taxStrategies;
   8:     }
   9: 
  10:     public ITaxStrategy GetStrategyForOrder(Order order)
  11:     {
  12:         return _taxStrategies.FirstOrDefault(x => x.IsApplicable(order));
  13:     }
  14: }

Notice how the TaxStrategyFactory depends on all of the ITaxStrategy implementations.  It then uses the ITaxStrategy.IsApplicable(Order) method as criteria for a FirstOrDefault call.  Here’s an example TaxStrategy for any Order with country “USA”:

   1: public class USTaxStrategy : ITaxStrategy
   2:     {
   3:         private static readonly IDictionary<string, double> TaxRates = new Dictionary<string, double>()
   4:                                                                    {
   5:                                                                        {"OH", 7.0},
   6:                                                                        {"MI", 6.25},
   7:                                                                    };
   8:         public double CalculateSalesTax(Order order)
   9:         {
  10:             var rate = TaxRates[order.State];
  11: 
  12:             return (order.SubTotal * (rate / 100));
  13:         }
  14: 
  15:         public bool IsApplicable(Order order)
  16:         {
  17:             return order.Country == "USA";
  18:         }
  19:     }

 

You can download the sample project that goes along with this here.

Property Undo/Redo Support

July 4th, 2009

Undo/Redo support is one of those golden features that really differentiate a client app from many web apps.  There have been a number of methods/techniques to provide this support that I’ve run across from brute force, to the memento pattern, but none that lit any fire for me.

Here’s my answer to the problem using Anonymous methods and my first real attempt at creating (versus using) a Fluent Api.

The most common scenario for Undo/Redu support is form completion.  In your Domain or View Model this is often tied to Two Way bound properties.  Take the simple Person class:

public class Person
{
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }
}

The question is how to provide undo/redo support for a form (WPF often in my case) bound to a Person.  First, I create a ViewModel or Presenter for the Person class:

public class PersonViewModel : ViewModelBase
{
    private readonly Person _person;
 
    public PersonViewModel(Person person)
    {
        _person = person;
    }
 
    public string Name
    {
        get { return _person.Name; }
        set
        {
            _person.Name = value;
            OnPropertyChanged("Name");
        }
    }
 
    public DateTime BirthDate
    {
        get { return _person.BirthDate; }
        set
        {
            _person.BirthDate = value;
            OnPropertyChanged("BirthDate");
            OnPropertyChanged("Age");
        }
    }
 
    public int Age
    {
        get
        {
            var now = DateTime.Now;
            var age = now.Year - _person.BirthDate.Year;
 
            if (now < _person.BirthDate.AddYears(age))
                age--;
 
            return age;
        }
    }
}

Notice that we have a calculated property Age based on the BirthDate.  Any time we change BirthDate we want to make sure to notify that the Age is also changed, obviously. 

Here is the Fluent way to register Undo/Redo support for our PersonViewModel.Name property:

   1: public string Name
   2: {
   3:     get { return _person.Name; }
   4:     set
   5:     {
   6:         var oldName = _person.Name;
   7:  
   8:         _undoRedoManager
   9:             .WithUndo(() => _person.Name = oldName)
  10:             .RepeatAfterBoth(() => OnPropertyChanged("Name"))
  11:             .Do(() => _person.Name = value);
  12:     }
  13: }

Cool, but what is that doing?  Well, it’s pretty simply.  We are simply maintaining two queues; An Undo and a Redo queue.  Here is the longer syntax, without the Fluent helper Api that makes that a little clearer:

public string Name
{
    get { return _person.Name; }
    set
    {
        var oldName = _person.Name;
 
        _undoRedoManager.Push(() =>
                                  {
                                      _person.Name = oldName;
                                      OnPropertyChanged("Name");
                                  },
                                  () =>
                                  {
                                      _person.Name = value;
                                      OnPropertyChanged("Name");
                                  });
    }
}

This may not seem like much more, but if your Repeat part is more than one line, it gets a bit fragile.  Being able to specify the “After” stuff once is important.

From here you can use the IUndoRedoManager.CanUndo(), IUndoRedoManager.CanRedo(), IUndoRedoManager.Redo() methods to go back and forth.  Hook this up to your favorite ICommand implementation and you have most of what you might need.

 

Here is the full project with a WPF Sample and a VB sample.  The VB version is a little ugly since it doesn’t support anonymous methods without a return, but it works.

If you have suggestions (on the Fluent Api especially) let me know.  I’d really like to hear them.

Why Plain Old LINQ is so powerful

July 31st, 2008

Ian Griffiths posted a great example of how powerful and cool LINQ is when used in everyday code (it’s not all about databases people).

If you haven’t started to learn how to incorporate this awesome toolset into your daily coding life, you’re killing yourself.  No excuses.

Roadblock to Mocking Unit Tests

July 15th, 2008

I’ve been a faithful unit tester for a few years now.  I may not do everything by the book (I think end-to-end unit tests are helpful), but I do get good coverage most of the time.  That said, I’ve found myself unable to use any of the Mock frameworks out there, because I don’t use your typical Dependency Injection pattern.  That is, I don’t like “building up” very freaking instance with all the “Provider” or “Service” interfaces I’m might need in the possible life of a business object.  Yes, if your Customer class is only going to create or save an Order, it feels OK, but my objects are busy dude, so I’d need the longest constructor of all time.

I prefer Dependency Resolution.  I don’t use any fancy framework, I just use a good old, DI.Resolve<IBusyBee>() and go about my business.  It works wonderfully, it’s light-weight (cause I don’t use configuration based DI frameworks), and it’s my baby.

That said, it’s also been the roadblock to my mocking foray.  That was, until I “got it” today.  Long story short, here’s how I roll:

Create a Mock DI Container…

Mock<IDIContainer> mockContainer = new Mock<IDIContainer>();

Create the Injected Mock instances…

Mock<INotificationManager> mockNotifMgr = newMock<INotificationManager>();
Mock<IRepository> mockRepository = newMock<IRepository>();

Tell the mock IDIContainer to return the mock instances when asked…

mockContainer.Expect(c => c.Resolve<INotificationManager>(null)).Returns(mockNotifMgr.Object);
mockContainer.Expect(c => c.Resolve<IRepository>(null)).Returns(mockRepository.Object);

Mock your heart out…

mockNotifMgr.Expect(mgr => mgr.NotifyEmailConfirmation(It.IsAny<Member>())).AtMostOnce();
Member.Register("username", "firstname", "lastname", "ryan@myus.com");

mockContainer.VerifyAll();
mockNotifMgr.VerifyAll();

I’m very happy to have finally jumped on the Moq bandwagon as it will certainly make some unit tests much easier to write.  Maybe I’ll even do the test first part more faithfully now. 

FYI, I use my own DI framework which is just a glorified HashTable.  It works for me and it is quick.  Moq has also become my Mock framework of choice for no good reason other than I downloaded it first.

Why WPF? This is why…

July 2nd, 2008

http://dnrtv.com/default.aspx?showID=115

Just awesome!  I didn’t see anything far fetched other than they must have a great designer on staff.  I wonder if the designer was doing the Blend work?

Visitor Pattern with Anonymous Methods

July 2nd, 2008

I don’t often have the need to implement the Visitor Pattern, but today I was that day.  I looked around really quick for an example of how to do this with Lambda Expressions and Anonymous Methods, which seemed like they were the way to go.  It may be that my search skills have deteriorated right along with my sense of style, but I didn’t find much.

I played around for a few minutes and here is what I came up with:

public abstract class CarBase
{
    public void Visit(Action<CarBase> action)
    {
        if (action != null)
            action(this);
    }
}

public class BigCar : CarBase
{
    public void RunOverLittleCar()
    {
        Console.WriteLine("Me smash little car!");
    }
}

public class LittleCar : CarBase
{
    public virtual void RunAwayFromBigCar()
    {
        Console.WriteLine("Go Faster!");
    }
}

public class EcoCar : LittleCar
{
    public override void RunAwayFromBigCar()
    {
        Console.WriteLine("Ouch.");
    }
}
class Program
{
    static void Main(string[] args)
    {
        IList<CarBase> cars = new List<CarBase>(new CarBase[] {
                                                                new BigCar(),
                                                                new LittleCar(),
                                                                new EcoCar()
                                                              });
        foreach (CarBase car in cars)
        {
            car.Visit(delegate(CarBase c)
            {
                if (c is BigCar)
                    ((BigCar)c).RunOverLittleCar();
                else if (c is LittleCar)
                    ((LittleCar)c).RunAwayFromBigCar();
                else if (c is EcoCar)
                    ((EcoCar)c).RunAwayFromBigCar();
            });
        }

        if (Debugger.IsAttached)
            Console.ReadLine();
    }
}

In many implementations of the visitor pattern there is an adapter or actual Visitor interface and implementation class which is passed into the Visit() method.  This is just smooth.

My visit method above is a little big to look good as a lambda expression, though maybe I just don’t have the eye for it. 

Virtual Property C# Code Snippet

July 2nd, 2008

For those of you who use NHibernate you may find this convenient, if you don’t already have your own.  Below is a C# code snippet for creating a public virtual property (code and file are both there).  Just put it in your <Visual Studio 2005/2008>\Code Snippets\Visual C#\My Code Snippets folder and you’re off and running.  No restart required.

File

Code

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>propv</Title>
            <Shortcut>propv</Shortcut>
            <Description>Code snippet for an automatically implemented virtual property</Description>
            <Author>Microsoft Corporation</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>type</ID>
                    <ToolTip>Property type</ToolTip>
                    <Default>int</Default>
                </Literal>
                <Literal>
                    <ID>property</ID>
                    <ToolTip>Property name</ToolTip>
                    <Default>MyProperty</Default>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[public virtual $type$ $property$ { get; set; }$end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>
 
 

NHibernate Thinks Your Enum is Dirty

June 30th, 2008

Get your head out of the gutter.

It’s important to look at your mapping files closely when trying to diagnose unexpected results.  One of our developers had recently added two properties to our big honkin’ CustomerOrder entity.  These both happened to be enumeration values, which are represented by Int values in the database.  Of course, NHibernate mapping files (hbm’s) are from the POCO perspective, which means the <property type=”…” />  value should be the Enumeration’s themselves.  If you use Int32, though, things will appear to work, but you’re actually causing NHibernate to do an incompatible type comparison during it’s “Dirty” checks.  This will cause your lazily, loaded entities to be dirty as soon as you get them.

So, be careful in reviewing your mappings, because it doesn’t take much to screw up something small that has a big impact.