Tuesday, 20 October 2009

Testing Objects Without Interfaces Using an Interface Wrapper and a Partial Class

I've found that often I'm using a framework that doesn't lend itself to unit testing very well. In the past I've used wrappers, a class that contains an instance of the object that is not testable and inheriting an interface that I can mock, but this is a lot of work.

A colleague of mine recently came up with a great idea using partial classes. If you create a partial class of your class you wish to mock and have the partial class inherit from an interface then you will be able to mock the interface for testing. All you need to do is create your stubs of any methods you wish to use in your interface and you're away.

It's not quite as clean as if your original object instantiated it's own interface, but it's much cleaner than a wrapper class. I thought that it was ingenious, for some reason I never thought of it. Oddly enough since he thought of it I've been finding implementations of it everywhere. A couple of instances of the idea online and then when I was interviewing a guy the other day, he suggested the same thing as if it was just common sense.

It's really true that there is no such thing as a professional developer.

Thursday, 24 September 2009

The Guild Season 3 Ep 3

This show is great,

<br/><a href="http://video.msn.com/video.aspx?mkt=en-US&amp;vid=80a029bc-7a7a-4f6e-b63c-8c4e73975e20" target="_new" title="Season 3 - Episode 3: Player Down">Video: Season 3 - Episode 3: Player Down</a>

Migrating Classic ASP.NET to ASP.NET MVC 2 – Project

I always laugh when I see ASP.NET referenced as Classic ASP.NET after I was exposed to “Classic” asp for a little while last year.  I mean no insult to anyone, it’s still a very relevant and popular framework, but it makes it easier for me to differentiate it in my blog.

This post by Maarten Balliauw is old, but still very relevant on how to migrate ASP.NET to ASP.NET MVC.  It was put together during the beta of version 1 so there are a few things missing, but it does include 95% of what you need to do.  I don’t want to re-cover someone else’s work, so I’ll assume you’ve started there before you found this page.

Extra Bits

One thing the article leaves out is that you won’t have the ability to right click your Controllers folder to add a new controller.  While this doesn’t really stop you from adding controllers as they are just classes, it does cause you to spend extra time writing the wrapper information and leaves the possibility of error more open.  Fortunately this is easy to enable.  In the project file (aspmvcwebsite.csproj or whatever) you’ll find this line in bold:

   1: <PropertyGroup>
   2:     <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
   3:     <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
   4:     <ProductVersion>9.0.30729</ProductVersion>
   5:     <SchemaVersion>2.0</SchemaVersion>
   6:     <ProjectGuid>{9383F928-27DF-4A63-B30B-F79FF733B034}</ProjectGuid>
   7:     <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
   8:     <OutputType>Library</OutputType>
   9:     <AppDesignerFolder>Properties</AppDesignerFolder>
  10:     <RootNamespace>AdminWebUI</RootNamespace>
  11:     <AssemblyName>AdminWebUI</AssemblyName>
  12:     <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
  13: </PropertyGroup>

It won’t, of course, be in bold in the csproj file, the ProjectTypeGuids define the flavour of project you chose when you started the project and it’s what the MVC framework looks for to setup your context sensitive menu.  All you need to do is add another flavour so your project type looks like an ASP.NET MVC project type.  If you create an ASP.NET MVC project and check out the csproj file you’ll see the extra guid you need, I’m not sure if it’s all the same for all flavours of MVC but mine was:

   1: {F85E285D-A4E0-4152-9332-AB1D724D3325};

Add this in first and you’ll have

   1: <ProjectTypeGuids>{F85E285D-A4E0-4152-9332-AB1D724D3325};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>

Reload your project and you’ll have ASP.NET MVC context sensitive menus.  You can still add web forms and whatever else you like throughout your project.

View Web.config

If you’re going to have strongly typed views, very important for ASP.NET MVC, then you’ll also need the Web.config file in your Views folder.  I would suggest creating a new ASP.NET MVC project and then copying the file into the folder in your migration application.

Conclusion

That’s pretty much all you need.  You can run the two side by side with very little effort.  If you have any other issues, just compare the web.config files from a new ASP.NET MVC site with the config file that you already have and move the differences.  ASP.NET MVC 2 has this for example:

<dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
</dependentAssembly>

That you’ll need when it gets to IIS, but is not needed locally. 

 

Hopefully someone finds this useful.

Thursday, 10 September 2009

The Guild Season 3 Episode 2

I love this show, and now it’s embeddable.

<br/><a href="http://video.msn.com/video.aspx?mkt=en-US&amp;vid=bdab0fe5-ecc7-4f5e-a946-feefa45d531b" target="_new" title="Season 3 - Episode 2: Anarchy!">Video: Season 3 - Episode 2: Anarchy!</a>

SHB6100 Works with iPhone 3.1

I love my Philips headset, I used to use it with my nokia all the time. Alas even with bluetooth my iPhone has never been able to use them. With the advent of 3.0 I was promised AD2P, but again my hopes were dashed when they didn’t work due to a protocol issue apparently. Finally my dreams of listening to music wirelessly have come to fruition with the advent of iPhone 3.1.

The Philips SHB6100 and I suspect all the SHB models will now work with the iPhone as a music player. Just connect them and you’re good to go. Not only that, but the volume, play / pause all work for me now too (skip buttons are no good) as well as answering calls and of course talking.

So if you’ve been hanging out for the iPhone to start working with this truly quality bluetooth headset, wait no longer.

Tuesday, 8 September 2009

Assert that a method was called with Rhino Mocks

This is not all that hard or difficult to figure out on your own, but hopefully it helps someone who’s stuck.  If you want to test that a method was called with Rhino Mocks, it’s easy!

Usually you want to assert that a method was called if you’re testing one class that has to call another.  This is particularly useful when testing the repository pattern and you want to ensure that it’s calling your data context’s submit changes method.  You will have to mock the data context for this to work, and of course you’ll need to wrap your data context in an interface, but that’s a post for another day.  I’ll post a link when I do it.

   1: MockRepository mocks = new MockRepository();
   2: IDataContextWrapper context = mocks.DynamicMock<IDataContextWrapper>();
   3: mocks.ReplayAll();
   4:  
   5: IWebProxyRepository target = new WebProxyRepository(_Proxies.AsQueryable(), context);
   6: target.Delete("1.1.1.1", 200);
   7:  
   8: context.AssertWasCalled(c => c.DeleteOnSubmit(_Proxies[0]));
   9: context.AssertWasCalled(c => c.SubmitChanges);

It’s pretty straight forward.  If you’re not sure what parameters were used, or don’t care, or if you want to assert that it was called a certain number of times you can use the options that are available ot you when you setup your results like so:

   1: context.AssertWasCalled(c => c.DeleteOnSubmit(_Proxies[0]), o => o.IgnoreParameters().Repeat.Times(2));

Monday, 31 August 2009

CruiseControl.NET failing on SVN (or other source control) failure

Our SVN is offsite and hosted by another company.  It works really well, but occasionally the CruiseControl.NET server is unable to make a connection (for whatever reason) and the build fails.  This happens a lot when we’re doing backups, or if we have an outage or just occasionally for no reason at all.  We do 1440 build tests a day (that’s one a minute) so I suppose it’s no surprise.  We do roughly 2 check ins a day (small team) per project and we get roughly 2 failures a day, so my build history is roughly 50% failure (more if you count the weekends).

Well I’ve finally found out how to stop this from happening.  With the newer version of CruiseControl (well it’s not that new now, but no matter) there is a tag to allow for source control errors and decide what to do when they happen.

The attributes are added to your <project> tag:

   1: <maxSourceControlRetries>10</maxSourceControlRetries>
   2: <stopProjectOnReachingMaxSourceControlRetries>true</stopProjectOnReachingMaxSourceControlRetries>
   3: <sourceControlErrorHandling>ReportOnRetryAmount</sourceControlErrorHandling>

This is fairly straight forward, those tags will allow my source control to retry 10 times.  It will stop building my project when it fails 10 times and it will do nothing but report the number of retries if it fails.  Add these 3 lines to each of your projects and then when you bring down your version control system your build won’t fail.

Monday, 24 August 2009

jQuery Ajax submissions and invalid characters (like single quotes)

I’ve recently posted about submissions to ASMX services using Ajax to allow asynchronous data transfer to the client in a browser.  This works pretty well, but I’ve come across a problem with a particular invalid character when using my method.  The apostrophe.

Previously:

   1: $.ajax({   
   2:     url: "ReviewHandler.ashx",   
   3:     data: “{   
   4:         'name': '" + $("#ReviewerName").val() + "',
   5:         'location': '" + $("#ReviewerLocation").val() + "'
   6:     }",   
   7:     processData: true,       
   8:     type: "POST",   
   9:     beforeSend: function() { startSubmit(); },  
  10:     complete: function() { submitComplete(); },  
  11:     error: function(xhr, statusText, errorThrown) { alert(errorThrown); },  
  12:     success: function(data) { submitSuccess(data); }  
  13: });

And this works fine.  But if you have an ‘ in your data, then obviously you’re code is going to explode.  Worst part is that it’s not going to be immediately obvious.  Your error text will just give you an internal server error message and you’ll need to use something like fiddler to nail the real reason that it failed unless you have great exception handling.

Well it’s very easy to make your code much more robust.  JSON.js is a set of standard JSON methods that can be used to serialise your objects into JSON strings and escape all your characters correctly for you.  Using JSON.js, the former becomes the following:

   1: var myObj = { 
   2:     name: name: $("#Name").val(),
   3:     location: $("#Location").val()
   4: }
   5:  
   6: $.ajax({
   7:     url: "ReviewHandler.ashx",
   8:     data: JSON.encode(myObj),
   9:     processData: true,
  10:     type: "POST",
  11:     beforeSend: function() { startSubmit(); },
  12:     complete: function() { submitComplete(); },
  13:     error: function(xhr, statusText, errorThrown) { alert(errorThrown); },
  14:     success: function(data) { submitSuccess(data); }
  15: });

It’s neater for sure, and cleaner.  The encode method will escape all the illegal characters and allow it to work nicely with ASMX web service parameters.