In my day job I recently moved full-time into the land of Microsoft’s Team Foundation Server to manage source control. While it hasn’t been a smooth transition from Subversion, and an even rougher one from git, Matt Burke’s amazing git-tfs tool has come in super handy. In fact, thanks to recent pull requests by Jimmy Bogard, it even supports gated checkins against Visual Studio 2010.
One feature that is still on the wish list for git-tfs is support for translating TFS branches directly into git branches. I’d love to find the time to contribute that patch, but in the meantime I manage my TFS branches by having one distinct local git repo mapped to each TFS branch that I want to track.
The power of git allows me to connect these git branches locally, under the covers and unknown to TFS, by locally adding git remotes that point from one to the other. With those remotes in place locally I can pull changes from one local repo to the other, effectively rebasing changesets from one TFS branch to another by way of git.
When checking out a new TFS branch into a new local git repo, I have to remember the URL to the TFS server and the TFS working path to that branch as arguments into the git-tfs clone or git-tfs quick-clone commands, and for some reason I can never remember them.
For git remotes, the ‘git remote –v’ command does a great job of showing you the urls that existing remotes map to but that list never shows the tfs urls for branches checked out via git-tfs. Also, running ‘git tfs remote’ does nothing, so I went digging into the .git folder.
Turns out that git-tfs stashes that info in the [local repo root]/.git/config file
It contains a section that looks like this:
[tfs-remote "default"]
url = [url to tfs server]
repository = [$/path/to/source/repository]
fetch = refs/remotes/default/master
where default is effectively the remote name.
If you have to work with TFS but prefer git for source control check out git-tfs.
You’ll never look back.
Today I was working with a repository that looked like this:
public interface IRepository
{
...
IQueryable<T> Get<T>();
IQueryable<T> Get<T>(Expression<Func<T, bool>> predicate);
....
}
This allows consumers of the repo to shorten
var result = repo.Get<IWidget>().Where(w => w.Price > 10.00m);
to this:
var result = repo.Get<IWidget>(w => w.Price > 10.00m);
Not complicated but sure convenient when you are issuing a lot of queries against the repo.
In one test I had mocked the repo like so:
List<IWidget> fakeWidgets; IRepository mockRepo = MockRepository.GenerateMock<IRepostory>(); mockRepo.Expect(r => r.Get<IWidget>()).Return(fakeWidgets.AsQueryable());
What this does is create a fake IRepository instance and then set it up so that when any consumer calls Get<IWidget() it returns our collection of fakeWidgets. The AsQueryable() call on the end is to transform our fake List<IWidget> into the IQueryable<IWidget> returned by Get<IWidget>().
That worked great for calls like
var result = repo.Get<IWidget>().Where(… some predicate …);
but failed, predictably, with a NullReferenceException on calls like
var result = repo.Get<IWidget>(… some predicate …);
So here’s how I first set up an expectation that would delegate this predicate:
List<IWidget> fakeWidgets;
IRepository mockRepo = MockRepository.GenerateMock<IRepostory>();
mockRepo.Expect(r => r.Get<IWidget>()).Return(fakeWidgets.AsQueryable());
mockRepo.Expect(r => r.Get<IWidget>(Arg<Expression<Func<IWidget, bool>>>.Is.Anything))
.WhenCalled(invocation =>
{
var predicate = invocation.Arguments.First() as Expression<Func<IWidget, bool>>;
invocation.ReturnValue = mockRepo.Get<IWidget>().Where(predicate);
});
Don’t let the angle-brackets scare you; Arg<Expression<Func<IWidget, bool>>>.Is.Anything is simply Rhino Mocks’ way of saying accept any argument which looks like a function that takes an IWidget and returns a bool.
Then magic of the WhenCalled(…) method in line 8 is that it lets you manipulate a model of the actual method invocation which you are expecting. In this case on line 10 I’m grabbing that predicate argument matched in line 7 and then, on line 11, applying the predicate to the previously mocked Get<IWidget>() and stuffing it back into the method invocation as the actual ReturnValue.
What this effectively accomplishes is to make a call to the Get<IWidget>(predicate) method on that mocked IRepository act like a call to the Get<IWidget>() that has had the predicate applied.
Method … requires a return value or an exception to throw.
When I ran my test I got this error:
Method ‘IRepository.Get<IWidget>(anything);’ requires a return value or an exception to throw.
It took me a while to make sense of this message.
I had set the ReturnValue of the MethodInvocation passed to WhenCalled(…) so I figured Rhino Mocks knew the return value and I could safely drop the explicit Return(…) call that ends line 5
So what was going on?
Return(…) is required
Turns out Google and this post by Carlos Mendible came to my rescue.
The important part is that Rhino Mocks requires a Return(…) call at the end of an Expect(…) chain in order to determine the type of the return result.
Hence my delegating WhenCalled(…) code had to look like this:
mockRepo.Expect(r => r.Get<IWidget>(Arg<Expression<Func<IWidget, bool>>>.Is.Anything))
.WhenCalled(invocation =>
{
var predicate = invocation.Arguments.First() as Expression<Func<IWidget, bool>>;
invocation.ReturnValue = mockRepo.Get<IWidget>().Where(predicate);
})
.Return(Enumerable.Empty<IWidget>().AsQueryable());
Now my calling client that used the shorter syntax behaves exactly as expected.
Lately for a side project I have been poking at Nancy, the “micro web framework” that was born when Andreas Håkansson (a.k.a. @thecodejunkie) decided to port Sinatra-style syntax from the Ruby world over to .NET, and I love it’s simplicity.
While not quite as terse as it’s inspiration, I’m still impressed that you can write a “hello world” Nancy app in less than 140 characters:
This self-contained app will run inside an Empty ASP.NET Web Application with the Nancy.Hosting.Aspnet nuget package installed.
Sure, that gist wouldn’t fit in a tweet, but tweak a few names for brevity, and voila!
It’s all about Modules
Nancy is set up to organize your code into Modules like the simple one I quoted above. In the constructor of a Nancy Module you register a URL pattern and its handler by inserting the pair into one of the provided RouteBuilders (there is one each for Get, Post, Put, and Delete) via syntax that feels like dropping items into a Dictionary.
Handlers, in turn, take a single dynamic argument that is populated with URL parameters and must return a Nancy.Response which could range from a simple String or Stream to Nancy’s version of a View result.
Within the closure of your handler you also have optional access to the Module’s Request and Context properties (both custom POCO abstractions) with handles to the standard details including HTTP method, HTTP headers, QueryString values, request body, etc
Notice how the Request, Context, and Response objects are all unique to Nancy? I’ll come back to that later.
NancyModules allow you to organize your routes into related groups, and in a stroke of genius each Module can optionally pass a base URI to it’s ancestor, thereby nesting it’s routes under a common header, somewhat like ASP.NET MVC Areas:
This Module registers the following routes:
- /blog/posts/
- /blog/tags/
- /blog/categories/
All in all, it’s pretty simple to set up some basic routes and get your app up and running and you have your choice of ViewEngines; Nancy currently supports Razor, Spark, NDjango, and DotLiquid.
Another layer of abstraction
Remember those unique Request, Context, and Response objects?
The reason that is so exciting is that Nancy is completely abstracted away from any dependencies on System.Web and IIS; those live in the Nancy.Hosting.Aspnet nuget I mentioned above.
This means that your single app, as expressed through your Modules and related code, can be set up to run anywhere you like.
WCF anyone?
Want to host your Nancy routes and handlers inside WCF? There’s a package for that, and a demo bundled with the Nancy source on Github.
Other options
Want to host your Nancy routes and handlers in-process? There’s a package and demo for that, too!
Or maybe OWIN is more your speed? They’ve got that covered as well.
You can even do funky custom Response objects that pre- or post-process the response stream, perfect for International Talk-Like-A-Pirate day.
Futher reading on Nancy
- Nancy on Github
https://github.com/NancyFx/ - a Video intro to Nancy
http://www.nicholascloud.com/2011/05/nancy-net-micro-web-frameworks-part-1/ - Andreas’ blog
http://thecodejunkie.com/ - Andreas on Hanselminutes
http://www.hanselminutes.com/default.aspx?showID=290
Stay tuned for more
Why, might you ask, would I be interested in Nancy? What nefarious side-project do I have cooking off to stage-left? Hopefully I can take off the wraps sometime in the next couple weeks.
Over the next 6 weeks I will be presenting at a handful of upcoming tech events.
Regina Code Retreat
| Time: | June 12, 2011 from 8am to 5pm |
| Location: | Delta Regina |
| Street: | 1919 Saskatchewan Drive |
| City/Town: | Regina Saskatchewan, S4P 4H2 |
| Website: | http://coderetreat.ning.com/events/regina-coderetreat |
First up Amir Barylko and I will be co-facilitating the Regina Code Retreat that is kicking off this summer’s Prairie Developer Conference.
For the uninitiated, a Code Retreat is a day-long opportunity to practice writing code with a focus on pair-programming, TDD, and the 4 rules of Simple Design.
Amir and I ran a similar event a few weeks ago here in Winnipeg with the help of Steve Rogalsky, Marc Jeanson, and our 18 participants and we all had a great time.
Prairie Developer Conference
Next up is Prairie Dev Con organized by Winnipeg’s very own D’Arcy Lussier:
Featuring more than 30 presenters,over 60 sessions, and including session styles such as hands-on coding, panel discussions, and lectures, Prairie Developer Conference is an exceptional learning opportunity!
This year I’m on the board for a pair of talks on User Experience:
Designing for Success 101 – Why UX Matters For Your App
As software developers, we love to solve problems. Too often, however, we start mapping out solutions using our favourite patterns and technologies before we fully understand the goal, or we focus on functional requirements and lose sight of the big picture. In this session we’ll cover the basics of what a User Experience approach brings to the table and how it can make a difference in the success of your application.
June 13, 2011 @ 2:45pm
Designing for Success 102 – 7 Ways to Make your App Learnable, Usable, and Enjoyable
Why are some apps a pleasure to use while others a source of endless pain? In this follow-up to Designing for Success 1, we’ll focus on end-user interactions. Looking at several design patterns we’ll explore how to generate less frustration and more delight for our clients and their customers.
June 14, 2011 @ 1:15pm
Winnipeg .NET User Group
Finally, at the end of June, I’m speaking at the Winnipeg .NET User Group on my recent adventures with NServiceBus.
NServiceBus – Event Aggregation at Large
NServiceBus provides an easy-to-use platform for sending and receiving messages across process and machine boundaries. Join us for an overview of NServiceBus and a demo showing how to get it up and running. Put your events on the bus!
During my recent adventures implementing NServiceBus and configuring it to play nicely with StructureMap I ran across a confusing exception.
Below I present the error, denial, solution, and moral of my story.
If you’re under deadline, feel free to skip to the end.
The exception that started it all
StructureMap.Exceptions.StructureMapConfigurationException: StructureMap configuration failures:
Error: 104
Source: Registry: StructureMap.Configuration.DSL.Registry, StructureMap, Version=2.6.2.0, Culture=neutral, PublicKeyToken=e60ad81abae3c223
Type Instance 'b9b47db6-ca34-433c-878d-7c05092dc29b' (Configured Instance of NServiceBus.Installation.INeedToInstallSomething, NServiceBus.Core, Version=3.0.0.0, Culture=neutral, PublicKeyToken=9fc386479f8a226c) cannot be plugged into type NServiceBus.Installation.INeedToInstallSomething, NServiceBus.Core, Version=3.0.0.0, Culture=neutral, PublicKeyToken=9fc386479f8a226c
Denial
At first this had me baffled. After much googling, binging, and waiving my arms up and down while turning in circles, I was downright frustrated.
“What do you mean I can’t plug a type implementing INeedToInstallSomething into a dependency that needs an INeedToInstallSomething?” I shouted at the heavens.
Eventually calmer heads prevailed and I realized that I had misread the exception message.
StructureMap was actually trying to tell me was that I (or someone acting on my behalf) had asked it to wire up the INeedToInstallSomething interface as if it were a concrete type that implemented itself.
If that seems a bit self-referential, do not panic.
It is.
The problem
While any given interface has the same signature as itself, StructureMap doesn’t know how to create instances of interfaces, only of the concrete types that are bound to them.
Stepping though the source code for NServiceBus to see how it’s magic pluggable IOC configuration works, I noticed that the exception was thrown by the following code:
If you look closely, you’ll notice that typeof(INeedToInstallSomething) is actually assignable from INeedToInstallSomething so in addition to all the concrete types that implement that interface, the code above also tried to register the interface itself as if it were a concrete type.
The Solution
Here’s my solution:
If you have trouble seeing my change, head on over to github and check out the pull request
Have to hand it to the NServiceBus folks, my pull request as acknowledged, pulled, and integrated within 12 hours.
The Moral(s)
- If it looks like an interface, and acts like an interface, maybe it is an interface and can’t be treated like a concrete type;
- When running on the edge of an open source project, always be ready to step through the source;
- If you find a problem, step up and submit a patch!
Happy StructureMapping!
Found out the hard way that the CreditCardPayment class has internal validation that runs when you set the ExpirationYear and ExpirationMonth properties:
- ExpirationYear must be between 1000 and 9999;
- ExpirationMonth must be between 1 and 12;
This became problematic when we integrated with Beanstream and Authrorize.NET; without PCI compliance we don’t receive the expiration date of the purchaser’s credit card.
Without hacking into the payment system and substituting in our own CreditCardPayment class we had to pick values within those ranges to represent the “empty” state.
Recently while developing an eCommerce solution for a client using Microsoft Commerce Server 2009 and SharePoint 2007 we ran into an interesting bug.
Our client is populating their Commerce Server catalog with a data dump from an existing back-end system. They generate a valid XML file and import it using Commerce Server’s Catalog Manager application, then we use some standard Commerce Server starter site web parts to pull out products and apply custom XSL style sheets.
This setup worked fine during initial phases of the project, but about a week ago we suddenly started getting:
System.Xml.XmlException: An error occurred while parsing EntityName.
For reference, the complete stack trace is available here.
The culprit
Given the nature of the exception and my previous experience with XSL transforms choking on invalid XML we started looking at the XML data dump from our client searching for funky characters in odd places. Sure enough, it turns out that the client had decided to use the ‘&’ character in their Variant IDs.
The client had thought ahead and properly escaped that ampersand such that the Variant ID in the XML data dump was coded like this:
<variantid='458960&56'>
When that gets imported into Commerce Server via the Catalog Manager it gets correctly decoded to a Variant ID of “458960&56”. When the ProductDetails Web Part pulled the Variant ID out of Commerce Server and generated new XML in-memory against which to apply our XSL, it failed to re-encode that pesky ampersand and the XSL transform choked on an invalid literal ‘&’.
The solution
Turns out the solution was fairly simple:
Double escape that ‘&’ in the initial XML data dump.
Our doubly-escaped ampersand now looks like this:
<variantid='458960&amp;56'>
When loaded into Commerce Server’s Catalog Manager it is correctly decoded once so that the Variant ID that lives inside Commerce Server’s database now looks like “458960&56” and when loaded into the XSL transformation engine it is properly parsed as “458960&56”.
Simple, right?
SharePoint looks like a 5,000 page web application with needlessly complex architecture that’s been refactored into 3rd normal form, reorganized by a software architect working without the benefit of a front-end engineer, then pulled off the file system and thrown into SQL Server behind an API that presents a different “view” on the “files” depending on how you authenticate at the time.
As such, while it is getting easier with time and practice, it still runs counter to much of my 15 years experience as a web developer and seems like I have to jump through hoops of complexity that don’t add any immediate value.
Stay tuned for more as the project goes on.
I’m quite excited lately by the movement buzzing around Nubular (a.k.a. #nuproj), a package management system for .NET.
The smart folks behind Nu have decided to use Ruby, the Ruby Gems package manager, and RubyGems.org to host, deploy, and install .NET libraries. One of those folks, Rob Reynolds, has done a good write-up of the past, present, and future of .NET Open Source Software Delivery from the Nu perspective, so I won’t repeat that here.
Today I took my first foray into creating a “nugget” building one for an open source library I’ve contributed to and use regularly.
On a Windows box with Ruby and the Nu gem installed, adding the latest version of Should to your project is now as easy as
c:\> cd c:\dev\myProject c:\dev\myProject\> nu install should
Nu will check for the Should gem, download it if necessary, and unpack it into .\lib\should for you.
Nu already has lots of packages available for a quick and easy install; check out the list and try the nuggets for some of the tools that you arleady use.
Follow @nuproj on twitter or search on #nuproj to see updates to the tool.
I’ve seen several developers recently give or refer to presentations on “UI Design Patterns” and then proceed to talk about Model-View-Controller, Model-View-Presenter, and Model-View-ViewModel.
I think as an industry we need to push our language a bit.
MVC, MVP, and MVVM are UI Architecture Patterns; they refer how to organize UI-level code so that it is modular, cleanly separated, and easy to maintain.
On the other hand, UI Design Patterns, sometimes called UX Patterns, attempt to document common interaction challenges and the existing affordances or established design principles that have proven effective in addressing those challenges.
The difference, I would argue, is that architecture patterns focus on execution principles (how to organize code) while design patterns focus on experience principles (how to organize information, flow, visual cues, etc).
Here are a few examples to help illustrate the difference.
UI Architecture Pattern examples
- Recapping UI Architectural Patterns
- Choosing a UI Pattern (MVC, MVP, and ASP.Net MVC)
- WPF Apps With The Model-View-ViewModel Design Pattern