Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Derik Whittaker

Thoughts on Software Development, .Net, OOP, Design Patterns and all things cool

October 2008 - Posts

  • .Net gets a new logo and I like it

    It turns out the team over in Redmond has decided that the .Net logo needed a little sprucing up.  They have put together a pretty slick new logo and it was unveiled at the PDC.  The new logo will be referred to as the Wave.

     

     

    Here are a few links that talk about the new logo.

    Till next time,

  • How is interacting with your data repository in your controller 'Different' or 'Better' than doing it in your code behind?

    Today I was looking through a sample Asp.Net MVC application and the first thing I noticed is that one of the controllers had 4 repositories injected into the controller (hey, at least they are injected right :) ).  The code then went onto to interact with the various repositories in each of the various controller actions.  In one case a controller chatted with a single repository 5 times.....:(

    My question is this.  How is having the controller chat with a repository different than having your code behind do so? 

    To me this is just NOT good.  In my opinion the controller should only interact with either services (if you buy into that design pattern) or other business layer objects.  I like the idea that my controller actions are skinny (thanks for that term Chris) and contain very little 'logic'.  My fear with MVC is that controller actions will turn into the click events we have today with WebForms.

    Am I off base?  Thoughts... Comments.... Lets Debate this

    Till next time,

  • Notes from upgrading from StructureMap 2.4.9 to StructureMap 2.5.0

    Tonight I updated the Dimecasts codebase from the 2.4.9 version of StructureMap to 2.5.0 and ran into few scenarios where some 'hefty' changes were required.  I thought I would share the 2 major areas that needed change.

    Adding named concrete instances for a given interface:

    Was

    AddInstanceOf<IAddin>().UsingConcreteType<DotNetKicksAddin>().WithName("DotNetKicks");
    

    Is

    ForRequestedType().AddInstances( x =>
                                        {
                                            x.OfConcreteType().WithName( "DotNetKicks" );
                                            x.OfConcreteType().WithName( "DZone" );
                                            x.OfConcreteType().WithName( "Digg" );
                                            x.OfConcreteType().WithName( "ShareThis" );
                                        }
                    );
    

     

    Registering Registry's at application startup:

    Was

    StructureMapConfiguration.AddRegistry( new IoCWebRegistration() );

    Is

    ObjectFactory.Initialize( scanner =>
    	{ 
    		scanner.AddRegistry( new IoCWebRegistration() );
    		scanner.AddRegistry( new IoCDomainRegistration() );
    		scanner.AddRegistry( new IoCRepositoryRegistration() );} 
    	);
    


     Till next time,

    [----- Remember to check out DimeCasts.Net -----]

  • Mocks vs. Stubs and my 'Ah ha' moment

    Last night on twitter Aaron Jenson made the statement

    'moq's expect method needs to be renamed'

    'setting the expectation is not what you should be doing. you don't *care* if it's called.'

    I then started a short conversation with Aaron about this.  I have been using RhinoMocks for 2+ years and never really gave a second thought to the 'real' difference between a Mock and a Stub. 

    I have mostly used Mocks with the Expect syntax and rarely ever used Stubs and their syntax.  But after re-reading the Rhino 3.5 WIKI I now have an understanding of what Aaron was referring to and why the point he made me finally go 'Ah ha' I have been thinking about it in the right way, but implementing it in the wrong fashion.

    What is a Mock?
    A mock is an object that we can set expectations on, and which will verify that the expected actions have indeed occurred.

    In English...This is a method call that must take place, but you do not directly care about its results.

    What is a Stub?
    A stub is an object that you use in order to pass to the code under test. You can setup expectations on it, so it would act in certain ways, but those expectations will never be verified.

    In English...This is a method call that must take place, and you DO care about its results because these results will be used in your class under test.


    If you start to think about Mocks/Stubs in this light it does make sense.  In fact it even starts to clear things up (assuming you were still a bit foggy on the subject).

    I think that if authors of the various mocking frameworks really want to make sure people use the correct terminology and syntax, they should limit the framework to ONLY work as the intent specifies.

    Till next time,

  • Upgrading to Mvc Beta Gotcha to look for

    I forgot to mention in my upgrading to MVC beta post to mention one little gotcha.  Since the MVC team renamed Html.Form() to Html.BeginForm you will have to update all your references.  However, you will also have to swap the logic that is being used.

    When using Html.Form the parameter order was "Controller" then "Action" (on the simple overload),

    Now, when using Html.BeginForm the paramter order is "Action" then 'Controller" (on the simple overload).

    If you do not notice this subtle change you will assume everything is good to go.  You will only notice the problem when you run your application.

    Just thought I would mention this, happy upgrading.

    Till next time,

  • Upgrading Dimecasts.Net to the MVC Beta

    Today is the official launch of the Asp.Net MVC beta (can get the bits here) so I can finally blog about the upgrade process for Dimecasts.net

    First things first, what is new in this drop:

    • The added the MVC assemblies into the GAC.  This was done to allow global system usage.  Please note you can (and still should) do \bin deployment with the needed MVC assemblies for your application
    • They changed, moved, renamed a few of the HtmlHelpers.  For example Html.Form is now Html.BeginForm
    • The created an HttpVerbs enum for usage in the AcceptVerbs attribute.  This is nice because now i do not have to have 'magic' strings.

      Was
      [AcceptVerbs("Post")]

      Now
      [AcceptVerbs( HttpVerbs.Post ) ]
    • Made great improvements to the ModelBinding process (more on this in another post)
    • Many, many more.  Read the release notes for more information

    Onto the actual upgrade process:

    • Changes to the Web.Config class
      • Add the following line to the <compilation><assemblies> section
        <add assembly="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      • Add the following to the <namespaces> section
        <add namespace="System.Web.Mvc.Html"/>
      • Added the following to the <httpHandlers> section
        <add verb="*" path="*.mvc" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    • Looks like Microsoft.Web.Mvc is no longer in use so I needed to remove that.  Was not a big deal as I was only using 1 method from that assembly anyway.
    • Needed to make various changes based on Html helpers being changed (ie needed to change my Html.Form to Html.Begin form)
    • Needed to copy the new assemblies into my local /library folder because I do not want to use the GAC version.  This is because the hosting company I use may not have the beta installed and I am not going to count on it ever being installed.

    Well I guess that does it.  Was not near as painful as other releases, but was still a bit of effort.

    Please note that www.dimecasts.net has NOT been upgraded publicly yet.  This is because I have some pending changes that are not ready for prime time yet.

    Hope this helps someone.

    Till next time,

  • Setup up StructureMap 2.5 to Auto Configure your dependencies

    One of the great new features with StructureMap 2.5 is the ability to have the container auto-wire you dependencies.  This means that if you want to you do not need to register all your types.

    Prior to this release if you wanted to map IFoo to Foo you needed to do something like this:

    StructureMapConfiguration.ForRequestedType<IFoo>().TheDefaultIsConcreteType<Foo>();

    Although this was not a major pain or even a major issue to me, I would love the ability to not have to create TONS of lines of wasted code simply to wire my interfaces to my concretes.

    With 2.5 you can do the following and have the container do all the grunt work for you.

    ObjectFactory.Initialize(
        x =>
            {
                x.Scan( scanner =>
                            {
                                scanner.TheCallingAssembly();
                                scanner.WithDefaultConventions();
                            } );
            }
        );
    
    

     

    You will notice that I am using the ObjectFactory.Initialize all my stuff.  This is because StructureMapConfiguration has officially been deprecated and SHOULD not be used.  Also pay close attention to the way I am using x.Scan().  In my initial testing I was having NO luck getting the auto wiring to work because I was doing this.

    ObjectFactory.Initialize(
        x =>
            {
                x.Scan( scanner =>
                        {
                            scanner.TheCallingAssembly();
                        } );
    
                x.Scan( scanner =>
                        {
                            scanner.WithDefaultConventions();
                        } );
            }
        );
    

    I am not 100% sure of the reason why, but I think it is because that each time Scan is called the list of internal 'scanners' gets reset (was walking through the code).

    Also, keep in mind this will only auto wire your dependencies if the naming is as follows IFoo maps to Foo.

    Hope this helps,

    Till next time,

    [----- Remember to check out DimeCasts.Net -----]

  • Partial Mocks with the StructureMap AutoMocker

    If you have not checked out the new AutoMocking Container that is part of StructureMap 2.5 I would highly suggest you do, it rocks.

    I thought I would show how simple it is to create a PartialMock on the Class under Test (CUT) when using the RhinoAutoMocker.

    Our Class we want to mock

    public class VisitReassignmentRule : PersistingRule
    {
    
        public VisitReassignmentRule( ISynchronizationRepository synchronizationRepository, 
    	IValidationRepository validationRepository, 
            IValidationLogger validationLogger ) : base( validationRepository, validationLogger )
        {
            SynchronizationRepository = synchronizationRepository;
        }
    
        public override InvocationActions ProcessRule( DataSet ds )
        {
    
    	// logic goes here
    
            return null;
        }
    
        public override bool DataIsInviolationOfRule( DataSet dataSet )
        {
            return false;
        }
    
        private ISynchronizationRepository SynchronizationRepository { get; set; }
    }
    
    

    Mocking Code

    [Test]
    public void ProcessRule_ViolatesRule()
    {
        	var rule = new RhinoAutoMocker();
    
    	// This line here tell the mocking container to make it a partial ( I know, the method name tells u that to)
        	rule.PartialMockTheClassUnderTest();
        	rule.ClassUnderTest.Expect( x => x.DataIsInviolationOfRule( null ) ).IgnoreArguments().Return( false ).Repeat.Any();
    
    	// actually call the method
        	rule.ClassUnderTest.ProcessRule( dataset );
    }
    

    As you can see, telling the AutoMocking container that you want the Class under Test to be a partial is very easy.  The one thing you want to make sure you do is not use the .Get<> syntax and just use the .ClassUnderTest syntax to set your expectation.

    Till next time,

    [----- Remember to check out DimeCasts.Net -----]

  • Chicago Alt.Net Meeting location for tomorrow has changed.

    Sorry for the last minute notice, but we have to change locations for tomorrow’s meeting.  If you are planning on coming (and you should) please take not of the new location

    NEW LOCATION
    Redpoint Technologies
    Sears Tower
    233 South Wacker Dr.
    Suite 750
    Chicago, Illinois 60606

    Same time, same everything else.

    Sorry again for the late notice.

    Till next time,

  • Save Dataset contents to XML and Null Values

    Today I needed to save a fully populated dataset as xml to my drive in order to simplfly unit testing.  I thought this would be pretty straight forward, but as it turns out it was not.  There is one little wrinkle that may bite you if you are not careful.  Below I will describe what I tried and why it failed and finally what worked.

    Problem: I need to save a fully populated Dataset as XML to disk

    Solution Attempt 1: Use DataSet.WriteXml( LocationOnDisk )

    This worked, mostly.  I was able to get the XML document and reload it into a a dataset using DataSet.ReadXml( LocationOnDisk ).  A problem arose because one of my columns was always null.  And by default simply doing a WriteXml does not save schema information. More information on this here.

    Solution Attempt 2: Use DataSet.WriteSchema (LocationOnDisk) then user DataSet.WriteXml( LocationOnDisk)

     This worked.  By saving my schema information for the dataset I am later able to repopulate the data and have my null values replaced.  In order to do this all you have to do is the following.

    DataSet ds = new DataSet();
    ds.ReadXmlSchema( XsdFileLocation );
    ds.ReadXml( XmlFileLocation );

    I know this seems pretty trival, but If you do not understand how Xml and schemas work you could spin your wheels for a while trying to figure out why your column/data was not repopulated.

    Hope this helps someone,

    Till next time,

    [----- Remember to check out DimeCasts.Net -----]

  • Using the RhinoAutoMocker that is part of StructureMap 2.5

    One of the new features that is part of the next release of StructureMap 2.5 is a AutoMocking Container. 

    What is an AutoMocking Container, well per Jacob over at Eleutian an AutoMocker is

    AutoMockingContainer is simply a IoCContainer with a custom facility and dependency resolver that supplies a Mock (RhinoMock) for any interface that is resolved.

    My definition is a little more straight forward and uses simpler word (remember I am a simpleton :))

    An AutoMocking container is simply a tool that will inject mock dependencies into your object for you.

    What I want to do today is show how an AutoMocking Container can reduce the amount of code/noise from your tests.   I am going to first show a tests that simply uses RhinoMocks then that same test that uses the RhinoAutoMocker

    Test with only RhinoMocks

    [Test]
    public void NoAutoMocker()
    {
    	var mockProvider = MockRepository.GenerateMock<IPersistingRulesProvider>();
            var mockRepository = MockRepository.GenerateMock<ISynchronizationRepository>();
            var mockPersistanceProvider = MockRepository.GenerateMock<IPersistanceProvider>();
            var mockLogger = MockRepository.GenerateMock<ILogger>();
    
    	// Expectations
            mockProvider.Expect(x => x.ExecuteRules(null)).IgnoreArguments().Throw(new Exception("Do not care what this is"));
            mockRepository.Expect(x => x.StartTransaction()).Repeat.Once();
            mockRepository.Expect(x => x.RollbackTransaction()).Repeat.Once();
            mockRepository.Expect( x => x.CommitTransaction() ).Repeat.Never();
    
    	var persitingPipeline = new PersistingPipeline(mockProvider, mockPersistanceProvider, mockRepository, mockLogger);
            var result = persitingPipeline.PersistChanges(new DataSet(), 0, 0, 0);
    
    	Assert.That( result, Is.Not.Empty );
    
    	mockRepository.VerifyAllExpectations();
    }
    
    

    This code above has a bit of noise.  Because my object has a dependency on 4 other objects i need to create mocks for each of these.  This creates more work and just adds to the test noise.

    Test with the RhinoAutoMocker

    [Test]
    public void WithAutoMocker()
    {
    	var mockPipeline = new RhinoAutoMocker<PersistingPipeline>();
    
    	mockPipeline.Get<IPersistingRulesProvider>().Expect( x => x.ExecuteRules( null ) ).IgnoreArguments().Throw( new Exception( "Do not care what this is" ) );
    	mockPipeline.Get<ISynchronizationRepository>().Expect(x => x.StartTransaction()).Repeat.Once();
            mockPipeline.Get<ISynchronizationRepository>().Expect(x => x.RollbackTransaction()).Repeat.Once();
            mockPipeline.Get<ISynchronizationRepository>().Expect(x => x.CommitTransaction()).Repeat.Never();
    
    	var result = mockPipeline.ClassUnderTest.PersistChanges( new DataSet(), 0, 0, 0 );
    
    	Assert.That( result, Is.Not.Empty );
    
    }
    

    The code above does not require me to create mocks for each of my dependencies, the AutoMocker will do that for me.

    Also notice that when I need to set an expectation for a dependencies I can access it via the .Get<>() method. 

    Till next time,

    [----- Remember to check out DimeCasts.Net -----]

  • Speaking engagements on the horizon

    I thought I would just drop a little note on some speaking engagements I will be doing over the next month or so.

    Oct 30th - Lake County (IL) .Net Users Group - Gorking the Asp.Net MVC Framework

    Nov 12th - TriNug - Raleigh .Net Users Group - Taking tests to the next level with Mocks (will dive into AutoMockers as well)

    Nov 15th - Raleigh Code Camp - Bending the Asp.Net MVC to do you bidding, the virtues of extensibility

    I would love to see all 3 of my readers come out to mock and ridicule me at any of these 3 sessions.

    Till next time,

  • Unit Tests to the rescue

    Today started off in a bad, bad way.  Because of some issues I had earlier in the week with my source control repository (SCR) I was doing a ton of work offline.  Today I was able to regain access to my SCR I decided to do a full get.  I was fully expecting SourceOffSite (crappy overlay tool on top of VSS -- BTW, VSS is the devil) to prompt me for conflicts or do merges...... NOPE

    When I finished doing my SCR pull I re-opened Visual Studio and did a compile.  To my dismay I had TONS of build errors.  After about 3 seconds of looking into the errors I knew I was screwed.  It turns out I lost about 2 days worth of code because the source files were not merged they were overwritten....THIS SUCKS

    The good news for me is that much of the code that was overwritten was plumbing work and was fixed in about 1 hour.  However, there was a bit of logic code that was overwritten as well.  This is where my unit tests came to the rescue.

    Because I has pretty good code coverage with my tests I was able to re-create the logic with very little fear that the new implementation changed the intent of the original logic.  Also because I had my tests I was able to infer logic based on what the tests were meant to verify.

    I am not trying to say that tests made this all ok, but having my tests did make me feel a little better in thinking that I have not broken anything.  Sadly, I wasted a large portion of my morning doing this.

    Till next time,

    [----- Remember to check out DimeCasts.Net -----]

  • 2 of the Devlicio.us crew is awarded the Microsoft MVP

    It is that time of year again, the time where Microsoft hands out the MVP awards.

    This time round both myself (C#) and Michael Neel (aka ViNull) (asp.net) were awarded the MVP.  This is pretty cool and I hope we can live up to the MVP'ness

    Till next time,

More Posts

Our Sponsors

Proudly Partnered With


This Blog

Syndication

News