Showing posts with label tools. Show all posts
Showing posts with label tools. Show all posts

Nov 7, 2013

GitViz: Live Git Repository Visualisation

Screenshot animationTatham Oddie, Dietloff Giliomee and I are currently delivering developer uplift training for a large number of developers over multiple courses. Part of this training involves teaching the developers, who are very familiar with centralised version control, how to use Git.

What we have found is that explaining git concepts by drawing pictures on whiteboards and waving our hands around in the air works, but only to a point.

To try and alleviate this problem Tatham put together a great little tool over the past two days that provides a way for people to see what is happening in their git repository as they work, in real time. Now we students can see what git is doing simply by using the commands and visualising the repository changes with GitViz  How cool is that!

Even better, it’s all open source which means you can head over to the GitHub project to grab the code yourself, submit pull requests or simply make suggestions for improvements. We hope you enjoy it!

Mar 3, 2012

Git-TFS Presentation at the 2012 MVP Summit

The day before the 2012 Microsoft MVP Summit kicked off in earnest there was an MVP-to-MVP day. For those of us in the Visual Studio ALM area we had a day long series of lightning talks about all sort of TFS related subjects, making for a good and wide-ranging day.

For something different, I did a talk about git and TFS integration and how git-tfs can be used to hide many of the problems with TFS source control.  Below is a slightly modified version of the slide deck I used.

I hope you find it useful.

Improved Unit Testing with Visual Studio 11 Beta

imageThere’s just so much new stuff in the Visual Studio 11 Beta! In fact, someone should write a book about it… Oh wait, I am! (more on that when the time is right). For now, let’s have a look at one feature that makes me so very happy: Visual Studio’s new and improved unit testing capabilities.
It’s widely recognised by those with a desire to do unit testing that there are better unit test frameworks out there than MSTest but given that Visual Studio has always been so tightly coupled with MSTest it’s always been more difficult than it should be to get other test frameworks working well in Visual Studio.  The TestDriven.NET and ReSharper test runners have helped, but the integration back to visual studio was always lacking.
That all changes with the Visual Studio 11. Now it’s a case of “Use the framework that makes you happy. We don’t mind”.
You want to use XUnit? No problem!
NUnit? Easy!
MSTest (without the baggage it usually has)? Sure thing!
QUnit for JavaScript? Bring it on!
Something random that we’ve never heard of? Write an adapter and it’ll work just fine!

Dogs and Cats Living Together!

Visual Studio 11 introduced a test adapter model so that any test framework can run inside Visual Studio if there is an adapter for it.  The adapter model also means that you can not only run XUnit, NUnit, or any other type of test but you can run them in the same test assembly if you really wanted to! Why? I don’t know! But you can :-)
Maybe you have a suite of MSTest tests but you also want use XUnit’s data driven test features because MSTest sucks for unit testing. You can do just that.  It’s really nice.
Note: In MSTest’s favour, in this release when MSTest is used in a plain old class library for unit testing the MSTest test adapter uses a cut down, light weight version of MSTest with just the features needed for unit testing and none of the baggage that it normally comes with, making it quite usable for most unit testing needs. For most developers with an existing investment in MSTest tests they will see an improvement in performance as a result.

Pre-Requisites

Get yourself started by loading the appropriate adapter for your unit test framework from the Visual Studio Extension Manager.  MSTest is already in the box so you don’t have to worry about that one.  In this screen shot I’ve loaded up the XUnit, NUnit and Chutzpah test adapters.
SNAGHTML5b8384c

Running Unit Tests

Create a new C# Assembly project (NOT a test project) and add the XUnit and NUnit test frameworks to your project using NuGet
SNAGHTML5c26ddd
You can also add a reference to Microsoft.VisualStudio.QualityTools.UnitTestFramework so that you can do MSTest based unit tests.
Here, I’ve started by adding a simple XUnit test, then building the code and running the unit test as shown:
SNAGHTML5d08bb9
As you can see in the output window there is now a “Discover test started” phase where Visual Studio looks at the assemblies and determines what tests are in the system so that it can spin up the right framework and execute the tests.
The Unit Test explorer on the left shows the tests that were run, the time it took and any error information for failed tests.
In the same code I have then added MSTest and NUnit tests as shown, however at this stage I have not yet built the project – take note of the unsaved changes icon in the document tab, indicating that the project is neither saved nor built as yet:
image

Run Tests After Build (Almost Continuous Testing)

Continuous Testing is the idea that as you do your work all the unit tests are constantly running in the background and giving you live feedback when there are problems code by highlighting where tests have failed and where your code is broken.  The immediate feedback cycle makes test driven development an even faster development process since there’s no waiting around for all the tests to run.
Visual Studio has taken a step towards this ideal with the “Run Tests After Build” option as shown in the image below. Turn that setting on and as soon as you compile your code Visual Studio will run the tests automatically on a background thread so that you don’t end up with a blocked UI and can get on with coding the next thing on your list.
image
If a test failed the unit test explorer goes red and it’s obvious that there’s a problem.  The interesting thing is that in smaller projects the tests often run so fast that you don’t even notice them happening!
SNAGHTML5de845a
As a tip, once you’ve been using the test after build feature for a while you will probably want to stop the Output window from popping up every time you build so that you don’t have to keep closing it.  You can do this in the Visual Studio Options as shown
SNAGHTML5e0d612

Don’t Forget JavaScript Unit Tests!

OK, I won’t.  Make sure you have the Chutzpah test adapter Visual Studio extension installed (see above).
In a standard web project include QUnit or Jasmine in your project and then create a JavaScript file for your tests.  Once you have your tests written run them as you normally would and Chutzpah will do the tricky work of finding the tests and running them.  Here’s a screen shot of a web project with a QUnit test in it
SNAGHTML6029dd3

Conclusion

So there you have it! A brief overview of the new unit testing features in Visual Studio 11 Beta. Go and get it now and start playing with it.
Having Visual Studio automatically running your tests each time you do a build will change your development workflow for the better and keep you more focused on coding and help you stay in the mythical zone if you ever get there.
Remember that since all tests run in the background and this removes the time spent waiting for tests to finish that you can have tens of thousands of tests taking minutes to run each time and you won’t even feel a delay in your development activities.  Fantastic!

Jun 6, 2011

Anaesthetic for your #region-itis

If your code (or the rest of your team) suffers from a bad case of #region-itis then help is at hand.

There’s a lovely little Visual Studio extension over at http://teamsearchapp.com/region-tool that will automatically expand #regions, and also make those #region lines much smaller and harder to read than your normal code.  No more pressing shortcuts to expand all those blocks, less visual clutter and optionally, the ability to prevent collapsing of #regions.  What’s not to like?

Borrowing a few pictures from their site, it takes the #region afflicted code (on the left) and reveals it’s ugly inner truth (on the right):

Regions1 Regions2 

Ahh! That’s much better.

Aug 2, 2010

Viemu and Visual Studio 2010

If you’ve been keeping your ears open over the last few months you’ll have heard noises from a number of folks who have been talking vim up as a replacement editor.

On the other hand there have been people like Yehuda Katz claiming that it’s all hype and everyone should go back to their homes and shut the doors because the crazies will be gone soon (ok, I’m paraphrasing a lot there).

Of course, all of this made me chuckle and scratch my head at the same time.

Why? Because 20 years ago I was C++ on unix, using vi, as part of my Uni degree.  I even wrote a vi clone as one of my Uni team projects!  At the time I knew how to get around the editor reasonably well, though by no means was I a ninja, but I also thought it was as ugly as warts on your bum and compared to just being able to edit text the way you could with every other editor in the world at the time other than emacs, all that switch in/out of edit mode just felt like overhead.

As Uni turned into career I started worked on platforms and languages where vi didn’t exist (Wang VS, VAX/VMS, Linux, Windows, 4GLs, VB4+, Visual Studio, etc) and I gradually forgot all my vi editing skills, got used to living in a constant edit mode and never missed vi for a minute.

That said, it’s always good to question what you do and how you do it, and so if vi is being picked up by a whole new generation of developers then maybe this old fossil had better challenge his assumptions and re-evaluate wether vi is better than what I’m using currently and cut through all the talk with a little bit of personal experience. That said, I didn’t really want to lose my Visual Studio IDE and all the goodness ReSharper brings to it and my usual development workflow (i.e. the stuff that goes beyond just typing code) so I actually wanted the best of both worlds.

And thankfully it turns that there is something like this out there.  There’s a Visual Studio add-in that brings all the good bits of vi into Visual Studio called viemu and I’ve been using it for a while now and really liking it.  The guys who make it have also put together a great article explaining why people use vi/vim, and what some of the problems are in adopting it.  It’s well worth a read and just as soon as you finish reading this post you should go have a read of that one as well.

Now, I will say up front that viemu is a commercial product, but since it has a 30-day trial there’s plenty of time for you to work out wether viemu will help you or not.  Personally, I’ve found it improving my productivity quite a lot and it’s really reduced my hand movements and mouse usage even more than R# did, so I’ve gone and acquired a licence.

One of the issues I had initially was clashes with other extensions I have loaded (I have quite a few) so if you have ReSharper, the Visual Studio 2010 Productivity Power Tools or other similar extensions loaded then you may need to turn off a few options in them.  What sort of clashes, you ask? Well, as vi uses a normal keyboard characters for navigation such as braces, brackets and parentheses other extensions pick up the key presses and think they are just normal typing so they go ahead and helpfully auto insert the matching closing characters, leaving random characters littered around your code if you’re not paying attention.  Just go into your tools and find the relevant auto completion options and turn them off.

I should also mention, there’s a very handy shortcut to enable/disable viemu at any point in VS2010 so if someone else comes to your machine to do some pairing you can easily switch it off, let them work the way they wish and switch it back on when you have the keyboard again.  Nice!

Finally, if you’re just learning the vi/vim commands I’d recommend you run through the visual cheat sheet and tutorials on the viemu site.  It really helped me a lot in that regard, and made adoption much quicker.  So with that said, if you want to save your hands and wrists then go download it and give it a try today.  I’m really enjoying it, and you may just do so too!

Apr 3, 2010

Git & TFS Working Together – Version 2

UPDATE: Recent changes mean that the shelveset approach to checking in changes is no longer required. See Git-TFS Recent Improvements for more information


I posted a while ago on how to get Git and TFS version control working together, however there are some limitations with that approach that reduces it’s usefulness for some people, specifically that checking in doesn’t deal with check-in policies or being able to associate work items with a changeset.

Well, recently on the Australian Alt.Net mailing list the discussion came up again in reference to getting Mercurial working with TFS, and during the conversation we were pointed to the git-tfs project which I was unaware of before then.  Curiosity appropriately piqued, I went and grabbed the code to see how it worked, and I’m pleased to say that the approach is much better that the previous approach I blogged about, though the issues with solution files still exist, though it’s somewhat alleviated with this approach.

What is This git-tfs Thingy Anyway?

OK, introduction time, the git-tfs project is a git plug-in, much like git-svn, and it defines some git commands that let git work against TFS source control.  The nice thing about the approach it takes git tfs workflowis that instead of trying to commit directly to TFS and having to deal with check in policies and all that jazz it creates a shelveset instead. You can then switch to Team Explorer and do an unshelve and check in using the normal TFS practices.  The normal development workflow follows the path shown in the diagram on the left.

Getting Started

First up, you’ll need a version of git installed.  I’ve tested using msysgit and it works well, so grab a copy of that if you haven’t already. Then either download git-tfs or go grab yourself a copy of the source either from Matt Burke’s (@spraints) repository or from my own fork. My fork includes changes to make it work with TFS2010 and alternate user accounts, and hopefully Matt will take those onboard for his next release.

Remember, if you download the source you’ll need the Visual Studio SDK in order to build it.

Also you’ll need to add the folder where the compiled output to your path, so that git knows where to look for the “git tfs” commands you are going to use.

Clone TFS

You should now be able to get the source from TFS via git using the “git tfs clone” command, as shown here

git tfs clone http://tfs2008-vm:8080 $/TeamProject0 local_git_folder

Just pass in the source control folder you want to clone and the local folder you want the repository created in and wait for the code to download.  If you need to supply non-default credentials as I do when working with my virtual machines, then you’ll need to supply the –username option, for example:

git tfs clone --username tfs2008-vm\tfssetup http://tfs2008-vm:8080 $/TeamProject0 local_git_folder

Note that the –username option only works if you grab my fork (at least until the changes are merged back into spraints version).  When you use that option you’ll be prompted with the usual TFS credentials dialog box so you can enter your password every time you do a git tfs command.

Oh! Be aware that the folder you check out your git source to should be different than the folder used for your normal TFS workspace controlled work.

Yes, this means you’ll have 2 copies of the source.  One workspace/tfs controlled copy and one git controlled copy.

What About Those Solution Files?

Yes, I know, those pesky solution files with their inbuilt source control links that force you to connect to TFS when you open the solution.  They’re enough to drive a person to drink!

So, here’s the easy way to deal with it.  After cloning your repository, pull out the network cable from your PC or turn off wireless and then open the solution.  When prompted to go into offline mode, simply say “Yes! Of course I want to go offline you great lump!" and watch the solution open normally.  You can then plug your network cable back in and carry on as if nothing had ever happened.  Visual Studio will keep the solution in offline mode until such time as you tell it otherwise, and considering we’re using git for source control, that means we never will.

Option Two? Create a local branch of your code and remove the source control bindings from the solution in your local branch.  It’s a little more work, and you’ll have some more merging to do between your master and local branches, but it is just that tiny bit safer.

The choice is up to you, though I’d probably lean towards the first option for now.

Shelve Your Changes

OK, so now go make some changes in your git version of the code and commit them to the repository.  Once you’ve finished we can think about pushing them up to the TFS server.

The way this works is that all local changes you make are aggregated into a shelveset and placed on the server.  This way you don’t need to worry about rewriting local history or having multiple shelvesets on the server that you would have to process in chronological order.

Push your changes using “git tfs shelve” as follows:

git tfs shelve "my shelveset name"

Now switch to the TFS controlled version of the project, go to the pending changes window and Unshelve your newly created shelveset.  Check that everything is OK and do your normal TFS check in, with all the normal policies and association with work items applied that you need to.

Fetching Updates

Nice! OK, so now we have our local changes in TFS.  What about the reverse? What if we now want to get updates from TFS down to update our local git repository?

All we need to do is a “git tfs fetch”.  When we do, git-tfs will go off and grab the latest changesets from the server and bring them down as tagged objects.  They won’t get directly applied to the master copy, so it’s up to you to bring those changesets in yourself.

This is where you need to do a local “git merge” to take those tagged objects and merge them into your working copy.  You can do this via the command line or using the Git Gui as shown here

image

Once the merge is done you should be able to see all the changes from TFS, and visualise it using the git gui tools, for example:

image

And that’s it, we have a workable approach to using git with TFS.  Obviously there’s room for improvement with the possibility of committing directly to TFS, but for now this approach works well and I think it’s much better than the svn-bridge based approach I was using earlier.

 

Kudos to Matt Burke (@spraints) for the great work in getting this together.  It’s a great solution!

Sep 24, 2009

How I Learnt To Love A Password Manager

For the longest time (i.e. since I first used a password) I’ve always kept passwords in my head.  In the early days it was easy since systems were isolated and pesky password policies hadn’t yet become the norm.  It was usually easy to remember, because the number of unique passwords I had was, um, just one.

Then over time those password policies started to appear and I had to start thinking of new passwords for more places that wanted more security, typically by varying my single core password.  Then they introduced password history, and dictionary checks and all sorts of things which now meant I had to remember what all the various incarnations were.  My capacity for password rememberising was fast reaching full.

What made it harder is that with more and more things being on the internet I was also getting an account explosion and starting to forgetting what login id I was using, especially when it was for a site I hardly used, so I’d often find myself doing the ol’ “forgotten password” thing.  Side note: It’s a scary experience when the forgotten password thing results in you being emailed your current password.  Yikes!

Anyway, I knew this wasn’t best practice,and there were plenty of people saying “use a password manager” but the conceived hassle for me of trying to keep passwords in sync between different machines was a massive turn off.

Anyway, after reading Jeff Atwood’s little cautionary tale and his follow up about how his own password got hax0red I decide enough was enough, time to man up and get over my anti-password-manager mentality.

KeePass screenshot So first things first, I did some poking around the googleweb and found KeePass and decided to give it a try.

Why this one and not others? Well, first – it’s free! :-) But mainly it’s because

it’s portable and because it has a really cool AutoType feature where with a single key combo (ctrl_alt_a) I can get my passwords autotyped into whatever app I happen to be using.  So it’s now not only is it remembering my passwords for me, but it’s also saving me keystrokes.  Heaven!  There’s a slew of other things it does as well which I really like, but you can go check those out for yourself.

Anyways, I used it for a while to see if it worked for me and got to enjoy and appreciate what it did.  But it still didn’t solve my problem of wanting to maintain my passwords only once but have them available on any of the machines I have, even when I don’t have an internet connection.  This is where the portability factor becomes valuable.  You can take the app, copy it to a USB stick and just plug it into whatever computer you happen to be using and it’ll work.  However the idea of chewing up a USB slot just for the password manager didn’t appeal to me.  It’s too clumsy to keep plugging the thing in all the time and there’s a good chance I’d do something stupid and lose the USB drive.

imageEnter Live Mesh.  To get the “on every machine” thing working I just created a live mesh folder and synchronised the KeePass folder with my mesh.  Now whenever I update my passwords all I have to do on the other machines is make sure Mesh had synced and do a quick restart of KeePass to pick up my new changes and I’m all set.  Everything just works beautifully

I’ve been doing this now for about 3 months and I’m loving it!  I’m gradually replacing all my crappy passwords with stringer ones generated by the tool and feeling a lot more secure about my online identity.

As a note, I probably won’t change my twitter password as I use twitter from web kiosks, my windows mobile phone (though there is an unofficial KeePass port for the mobile) and other places where I don’t have access to my mesh folder.

If you’re in the same situation i was in before, then maybe it’s time you started looking at how you too can get to love a password manager :-)

Jul 31, 2009

NUnit for Team Build Gets an Update

For those of you using NUnit with TFS you may want to go and visit the NUnit4TeamBuild project site on CodePlex and get the latest release.

It fixes some issues with support NUnit 2.5 and test names longer than 255 characters, but most importantly it removes the need to have MSTest available for publishing the results back to the TFS server through the inclusion of a new utility that makes the appropriate WCF calls directly instead of doing so through the MSTest executable.

Many thanks to Kev Watkins for the contribution! I love seeing open source working so well :-)

For more info on how the whole thing works go and see Kev Watkins blog post or visit the project site.

May 27, 2009

My Visual Studio Environment (R# and more)

At the most recent Oz Virtual Alt.Net meeting I gave a run through of the various things I have installed on my box for making Visual Studio work the way I want it to, and making myself much more productive in the process.  The recording of that session can be seen either down below or over on the OzAlt.Net blog.

For reference here are the links to the various things I was showing off:

There’s actually more stuff I have installed, but since I didn’t show them off I won’t list them now.  Maybe in another blog post I’ll go through what those things do.

 

Feb 24, 2009

Aspect Oriented Programming & INotifyPropertyChanged

Normally when people talk about aspect oriented programming (AOP) and try and provide a sample they typically talk about logging.  It’s the easiest example for most people to get their head around and it usually involves minimal code.  They might also talk about (but not show) how aspects can be used for security and “so much more”.

Well, since logging is hardly an interesting aspect to talk about and there’s “so much more” out there, I started thinking about what some of the more interesting uses for aspects might be, and my mind turned to something we typically do when implementing binding for WPF applications.

public class WithoutAspects : INotifyPropertyChanged
{
private int myProperty;
public int MyProperty
{
get
{
return myProperty;
}
set
{
if (value != myProperty)
{
myProperty = value;
NotifyPropertyChanged("MyProperty");
}
}
}

public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}

The properties in particular bug me.  After all, we now have C# 3.0’s shortcut syntax it would be nice if we could do something like this:

[NotifyPropertyChanged]
public class WithAspects
{
public int MyProperty { get; set; }
}

Here’s where aspects can really help.  Consider the INotifyPropertyChanged implementation and all that binding code that is in our class and think about how it cuts across the purpose of the class itself.  This is exactly what aspects can be used to help with.


If we were to write an aspect that looked for a [NotifyPropertyChanged] attribute on a class and then performed all the work that we are currently hard coding we could then move all that “noise” code out of our class and let the class focus on whatever it is that our class does.


It makes sense, right? So let’s do it.  Let’s write an aspect for INotifyPropertyChanged that does what we want.


First, Which Framework Should We Use?


So the first question that comes to mind is which AOP framework should we use?  Should we use Castle Windsor (or another IoC container), the Policy Injection Application Block or PostSharp?


Windsor and PIAB both have a shortfall that we can’t overcome.  Neither of them can alter the type of a class they are providing aspects for – they simply provide proxies that add hooks to intercept method calls.  We would still need to implement INotifyPropertyChanged in our class for binding to work.


PostSharp on the other hand, applies aspects by altering the compiled code after compilation, meaning that we can create a POCO class and use an aspect to add the INotifyPropertyChanged interface to it.  We’ll go with that for now.


Disclaimer: This Has Already Been Done (Kind Of)


The good news is that there are already examples for doing this out there and in fact a binding aspect is provided as one of the samples in the PostSharp documentation (part of the download).  So, instead of pretending I write all this code from scratch I’ll point you to where I got my starting point


http://thetreeknowseverything.net/2009/01/21/auto-implement-inotifypropertychanged-with-aspects/#


OK, so now that you’re back, did you notice a problem with the implementations?  Neither of them check the existing value of the property to determine if the PropertyChanged(…) method should be fired, they just fire the event every time someone calls the setter.


I don’t want to do that, I want only fire the event when the property value change.  So, let’s run have a run through the code and see how this can be done.


The NotifyPropertyChanged Attribute


So first up we need to decorate our class with an attribute that PostSharp can use to know where to do it’s stuff.


First, we’ll add some references:


image


And then we’ll create the custom attribute.

[Serializable]
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class
, AllowMultiple = false, Inherited = false)]
[MulticastAttributeUsage(MulticastTargets.Class, AllowMultiple = false)]
public class NotifyPropertyChangedAttribute : CompoundAspect
{
public int AspectPriority { get; set; }

public override void ProvideAspects(object element
, LaosReflectionAspectCollection collection)
{
Type type = (Type)element;

collection.AddAspect(type,
new PropertyChangedAspect { AspectPriority = AspectPriority });

foreach (PropertyInfo propertyInfo
in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(pi => pi.GetGetMethod() != null && pi.GetSetMethod() != null))
{
collection.AddAspect(propertyInfo.GetSetMethod(),
new NotifyPropertyChangedAspect(propertyInfo.Name
, propertyInfo.PropertyType
, propertyInfo.DeclaringType)
{ AspectPriority = AspectPriority });
}
}
}

Notice that this attribute inherits from the CompondAspect class – this is a PostSharp class used to provide developers with more control over how aspects are applied.  We’re doing this by providing an implementation of the ProvideAspects method.


As you can see, when the ProvideAspects method is called we create a new aspect called PropertyChangedAspect and apply it to the class.  We then run through all the properties on the class, checking that the have both a setter and a getter.  If they do we then create a new NotifyPropertyChangedAspect (written by us) to each of the setters.


What’s in the PropertyChangedAspect and the NotifyChangedAspect? Well, this is where it gets interesting.


The PropertyChangedAspect


This is an aspect we want to apply at the class level.  It’s here that we want to do what it is we need to in order to ensure that the class implements the INotifyPropertyChanged interface,


Now because we’re using aspects we still need to ensure that we have an implementation of INotifyPropertyChanged somewhere in our codebase.  We could get fancy and use Emit to generate something, but there’s no real benefit in doing so.


You’ll also note that the implementation is using a slightly different interface (it still inherits from INotifyPropertyChanged) because we want to be able to call NotifyChanged using a PropertyInfo object as well as using the name of the property.

public interface IPropertyChanged : INotifyPropertyChanged
{
void NotifyChanged(string propertyName);
void NotifyChanged(PropertyInfo property);
}

[Serializable]
internal class PropertyChangedImplementation : IPropertyChanged
{
private readonly object instance;

public PropertyChangedImplementation(object instance)
{
if (instance == null)
throw new ArgumentNullException("instance");

this.instance = instance;
}

public event PropertyChangedEventHandler PropertyChanged;

public void NotifyChanged(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
throw new ArgumentNullException("propertyName");

PropertyChangedEventHandler eventHandler = PropertyChanged;
if (eventHandler != null)
eventHandler(instance, new PropertyChangedEventArgs(propertyName));
}

public void NotifyChanged(PropertyInfo property)
{
if (property == null)
throw new ArgumentNullException("property");

NotifyChanged(property.Name);
}
}

Here you can see the NotifyChanged implementation looks much the same as in our original class, though our original class actually forgot to check if the passed in string was null.


So now that we have that in place, let’s implement our PropertyChanged aspect.  We can see here that this aspect is a CompositionAspect. The PostSharp docs describe it as follows: The Composition aspect injects new interfaces into an existing type and defers the implementation of these interfaces to another object that implements them.


What that means is that we can combine our PropertyChangedImplementation class with any other class we like, as long as we attach the PropertyChangedAspect to it.  Way cool.


Let’s do just that

[Serializable]
internal class PropertyChangedAspect : CompositionAspect
{
public override object CreateImplementationObject
(InstanceBoundLaosEventArgs eventArgs)
{
return new PropertyChangedImplementation(eventArgs.Instance);
}

public override Type GetPublicInterface(Type containerType)
{
return typeof(IPropertyChanged);
}

public override CompositionAspectOptions GetOptions()
{
return CompositionAspectOptions.GenerateImplementationAccessor;
}
}

OK, so now we’ve accomplished most of what we need.  We’ve taken our class without any INotifyPropertyChanged interface defined for it, and added that interface to it, as well as providing an implementation of that interface in the class itself by composing it with the PropertyChangedImplementation class.


We’re not quite done yet – we still need to implement the changed to the properties themselves so that they fire the event when they change.


The NotifyPropertyChanged Aspect


Remember back in our NotifyPropertyChangedAttribute class that we were attaching the NotifyPropertyChanged aspect to properties in the target class? If you go an look at that code again you’ll see that we have a number of parameters in the constructor we are using.  What are they for?


Let’s have a look:

[Serializable]
internal class NotifyPropertyChangedAspect : OnMethodBoundaryAspect
{
private readonly string propertyName;
private readonly Type propertyType;
private readonly PropertyInfo propertyInfo;

public NotifyPropertyChangedAspect(string propertyName
, Type propertyType, Type classType)
{
if (string.IsNullOrEmpty(propertyName))
throw new ArgumentNullException("propertyName");
if (propertyType == null)
throw new ArgumentNullException("propertyType");
if (classType == null)
throw new ArgumentNullException("classType");

this.propertyName = propertyName;
this.propertyType = propertyType;
propertyInfo = classType.GetProperty(propertyName);
}

So we’re simply storing the property name, the type and getting the reflection PropertyInfo for the property that the aspect is attached to.  Why?  Because we’re going to be reusing it of course :-)  Reflection is slow and we don’t want to do more of it than we need to.


What you might also notice with this class is that it inherits from the OnMethodBoundaryAspect class.  That means that PostSharp will intercept calls to the method and give you the chance to do what you want before making the call.


Lets do just that – we only want to call our property setter when the value of the property has changed.  Since we have an automatic property we need to make that check before the setter gets  executed.  PostSharp lets you do this by providing an OnEntry method.  Let’s implement that method as follows:

public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
var originalValue = Convert.ChangeType(
propertyInfo.GetValue(eventArgs.Instance,null), propertyType);
var newValue = eventArgs.GetReadOnlyArgumentArray()[0];
if ((newValue != null && newValue.Equals(originalValue))
|| (newValue == null && originalValue == null))
{
eventArgs.FlowBehavior = FlowBehavior.Return;
}
}

So, what’s happening here?


First, we grab the current value of the property and ensure it is unboxed (the Convert call).
Next, we get the new value from the eventArgs parameter and check if it’s null
Then we see if the new value is different to the old value. If they’re the same then we set the FlowBehavior to Return so that the actual, real call to the property setter never gets made.


(P.S. If someone knows reflection better than me, they could probably do a better job of the value comparisons.  At least this works)


So now all that’s left is to call the code to fire the event.  PostSharp gives you an OnSuccess method that will get fired when the real method call has completed successfully, so we’ll use that for what we need to do.

public override void OnSuccess(MethodExecutionEventArgs eventArgs)
{
var theObject =
(PropertyChangedImplementation)
((IComposed<IPropertyChanged>)eventArgs.Instance)
.GetImplementation(eventArgs.InstanceCredentials);
theObject.NotifyChanged(propertyName);
}

So, what is going on here now? Well, if you remember that the NotifyChanged code is actually implemented in a different class, we need to be able to get to it.  Without going into the details at this point (you can read through it in the docs) we simply need to get a hold of the object that has the PropertyChangedImplementation for the object we are targeting.  Once we have that, it’s then just a case of calling the NotifyChanged(…) method on it.


Some Obvious? Questions


OK, so now that we have our aspects implemented and we can tag a POCO class with [NotifyPropertyChanged] and get binding working, what does that change in our code.


What happens with the composition of types?


How does that effect our coding.  Unfortunately because PostSharp does IL weaving after compilation you' won’t get Visual Studio knowing that your POCO class has a PropertyChanged event on it.


The following test shows how you have to work with things

[TestMethod]
public void PropertyChangedEventIsFired()
{
var w = new WithAspects();
INotifyPropertyChanged c = w as INotifyPropertyChanged;
c.PropertyChanged += c_PropertyChanged;
eventFired = false;
w.MyProperty = 10;
Assert.IsTrue(eventFired);
eventFired = false;
w.MyProperty = 10;
Assert.IsFalse(eventFired);
w.MyProperty = 12;
Assert.IsTrue(eventFired);
}
We have to cast our object to INotifyPropertyChanged in order to get a handle on the event.  Not perfect, but better than nothing.  Hopefully over time Visual Studio will provide native AOP that

deals with this problem, but I wouldn’t hold my breath :-)


What about the debugging experience?


Debugging still works great.  You can set a breakpoint in your code and step through things like you would expect to.


What about performance?


Aspects slow performance down a fair bit.  I did a test with 200,000 property sets/gets using both the normal method and the AOP method.


The AOP method took 0.265 seconds.  The normal method took 0.003s.  That’s quite a bit slower.


But wait, it’s really not that bad.  That’s 200,000 property changes I’ve done.  And we’re talking about binding – which is a UI related problem.  I don’t think anyone is going to notice that 0.2 second different in their UI if they are changed 200,000 property values in one go.  I’d suspect there are bigger issues at play there if that was happening.


So while performance is slower, in the large scale of things, I doubt there will be a human noticeable difference.


What about the IL?


PostSharp does IL weaving, so what does the IL look like after compilation.  Here’s the property after PostSharp has done it’s thing:


image


You can see where it’s wrapped the setter, and how it’s provided the OnEntry and OnSuccess hooks.  You’ll also note that there are OnException and OnExit hooks if you have situations that need those [think logging :-)]


 


So there you have it, an implementation of INotifyPropertyChanged using Aspect Oriented Programming.  I hope that all made sense to you and that you found it useful.  Comments are welcome, as always, and be aware that I haven’t extensively tested this – it is just sample code, so your mileage may vary. If you do find problems feel free let me know (letting me know the fixes is even more useful).

Dec 17, 2008

DataDude 2008 Impressions

DataDude, or as it’s more formally known – Visual Studio Team System 2008 Database Edition GDR (*phew*) has been released for a few weeks now and I spent part of today showing a number of people how it all fits together.

By the way, if you already have the 2005 edition installed, go get this version right now.  The improvements it makes over the 2005 version are massive – this product is now a useable and worthwhile addition to your toolbox, plus it supports SQL2008 databases.

Projects

The project system is now quite different.  The biggest (and I think the most needed) change was the separation of the build process from the deployment process.  You can now build the project to make sure that your SQL is correct without creating a deployment script.  When you build you get a DBSCHEMA file with you database definition in it.  Deployment is also improved with the option to just create the deploy script to target a database or you can create the script and run it against your target database in one operation:

image

The project file itself is now structured in a simpler manner with specific configuration files for various aspects of the configuration and deployment:

image

Oh – I should also mention this one : no more design time database!  Yay!!  DataDude now uses the SqlServerCE data engine for checking syntax and no longer creates those temporary databases with the GUIDs in the name.  Of course it does mean you need SqlServerCe (3.5 SP1) installed otherwise you might run into errors opening database projects with “Could not load assembly…” errors.

Code Analysis

Another very cool addition to DataDude is the inclusion of FxCop style code analysis rules.  While you can’t ensure that your SQL code is brilliant, you can at least be sure it doesn’t completely suck and break common rules.  As you can see it includes checks for things like the use of @@IDENTITY and SELECT * … etc.

image

The Schema View window

One of the other painful things about the 2005 edition of data dude was the schema management.  With 2005 by far the easiest way to edit your schema was to make changes via management studio and then do a schema comparison to bring the changes you wanted into your project.  While you can still do this it’s now pretty easy to manage the schema inside visual studio since there is a Schema View window with all the various things you might expect.

image

You still edit the table definitions using SQL (no designers) but it’s pretty simple to manage this stuff now.

What’s also nice is the improved things you can do in the schema view window as seen here:

image

Apart from much improved database refactoring support, there is now also the ability to view the dependencies of an object – both the things depending on it, and the things it depends on.  This really helps in understanding what you’ll be breaking when you make those crazy schema changes your thinking of :-).

Unit Testing

Woo-hoo!! Unit testing for stored procedures is very, very nice now.  To get started with a unit test hit the Create Unit Tests… button

image

Run through the dialogs and you’ll end up with a generated test that looks something like this:

image

See all that SQL code calling the proc?  What’s it doing inside a *.cs file?  Well, DataDude has added a designer experience to the database unit tests.  You can now write some SQL and add your test conditions from a list.  Test conditions are adjusted through the properties pages for each condition.

image

You can also do pre & post test scripts as well which can be very handy.

image

Behind the scenes you have normal code so if you really wanted to you can always go and add further code to assert and test conditions to suit whatever the specific needs are that you have

 

There’s a whole slew of other changes in the new version of DataDude and all of them are valuable and probably deserver a blog post in their own right, but these three areas of improvement are to me the changes that make the most difference.  If you want to know what the other changes are, go and check Gert’s blog where he gives a run through of each of them or go and grab the documentation and have a read of it for yourself – even better, go download it and have a play with it yourself and discover the improvements.

Dec 5, 2008

TFS Build Monitor v0.3

For those of you who are interested in having your very own continuous integration build light for TFS or want to be able to tweet build status information automatically, a new version of the TFS Build Monitor (formerly the Twitter Build Publisher) is now available from Codeplex at http://www.codeplex.com/BuildMonitor

The changes in v0.3 are that the application is now a WPF application instead of a console app and it can be minimized to the system tray, thus keeping it out of your way when you're doing real work.

There's also a few minor changes related to handling errors when the Delcom device isn't attached or when the TFS server can't be reached, etc.

If you've got any problems - submit an issue on the codeplex site.

Enjoy!

Dec 1, 2008

Using Gaming Tools for Improved Communications

I haven't tried this yet - I'm more curious than anything else as to your opinions.

I use Ventrilo (a VOIP utility) for gaming quite a bit and I never seem to get the voice glitches that Skype & Live Messenger seem to get. It's low on CPU (important when gaming) and high on sound quality – a pretty good mix in my book.

Since I regularly have up to 6 way conversations with it, I was then wondering how well it might work for remote software development teams. I can imagine an arrangement where everyone would run Ventrilo during the day and could chat with the rest of the team at any time they needed. They could also use the push-to-talk feature so that background noise wouldn’t be coming through all day long, and because it's so low on CPU usage it wouldn't affect the all important activity of software compilation :-)

So, do you think it would create a better sense of connectedness between team members? Do you already do something like this in your remote teams? Or am I just day dreaming here?

Opinions welcome.

Oct 7, 2008

A Quick Play With IBatis.NET

You may remember a few posts back that I was working with a team trying to use a pure stored procedure approach to access a database, and trying to do so using an OR/M. One of the commenters on the post mentioned iBATIS. Now I always thought iBATIS was a competitor to NHibernate, Linq2SQL, et al. but it's actually a different approach where instead of being a fully blown OR/M it just does simple data mapping of business objects to and from SQL statements and nothing more than that.

So I decided to have a bit of a play with it and I must say it looks pretty good. Here's a quick bit of sample code I knocked up to see how it works.

Assume I have the following sproc:

CREATE PROCEDURE InsertSaleHeader
@Tax money,
@TotalValue money,
@SaleNumber int output
AS
BEGIN
SET NOCOUNT ON;

INSERT INTO [dbo].[SaleHeader]
([Tax]
,[TotalValue]
,[ModifiedDate])
VALUES
(@Tax,@TotalValue,GETDATE())
SET @SaleNumber = scope_identity()

END

It's just a basic insert sproc that updates a modified date on insert and also returns a new identity value for the record we just added using an out parameter. This is the sort of thing that was a real pain to so with many of the full featured OR/M's.


I then wrote an integration test (p.s. please forgive my incorrect casing in places):

using IBatisNet.DataMapper;
using SalesDAL.ibatis;

namespace SalesIntegrationTests
{
[TestClass]
public class ibatisSaleRepositoryTests
{
[TestMethod]
public void CreateSaleAndGetSalesUsingIBatis()
{
ISqlMapper mapper = Mapper.Instance();
ISaleRepository repository = new ibatisSaleRepository(mapper);
ISale sale = new SalesTax.Sale();
sale.Add(new SalesTax.SaleLine(1, "imported box of chocolates", 10.00m, true));
bool result = repository.CreateSale(sale);
Assert.IsTrue(result);
}
}
}

This just creates an instance of a sale object and sends it to a sale repository class. The code for the ibatisSaleRepository is shown below.

namespace SalesDAL.ibatis
{
public class ibatisSaleRepository : ISaleRepository
{
private ISqlMapper mapper;

public ibatisSaleRepository(ISqlMapper mapper)
{
this.mapper = mapper;
}

public bool CreateSale(ISale sale)
{
mapper.Insert("InsertSaleHeader", sale);
LastSaleId = sale.SaleNumber;
return true;
}

public int LastSaleId
{
get;
private set;
}

As you can see the only actual work that happens is in the CreateSale() method where the IBatis Insert() method is called, passing in the object to be saved (note that I’m only saving the sale header here – we could extend this to save the sale lines easily enough).

And that’s it for the code. Nothing too complex at all. The rest of the work is done through the config files that IBatis loads during the Mapper.Instance() method call in the unit test. When it's initialised iBATIS loads up the SqlMap.config file and then processes it any other config files that are reference by it to create the mapping behaviours it needs to know.

The IBatis SqlMap.config file I used is shown here:

<?xml version="1.0" encoding="utf-8" ?>
<
sqlMapConfig xmlns="http://ibatis.apache.org/dataMapper" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<
settings>
<
setting useStatementNamespaces="false"/>
</
settings>
<
providers embedded="providers.config, SalesIntegrationTests" />
<
database>
<
provider name="sqlServer2.0"/>
<
dataSource name="SalesData" connectionString="Data Source=.;Initial Catalog=SalesDatabase;Integrated Security=True"/>
</
database>
<
sqlMaps>
<
sqlMap embedded="ibatis.SalesMap.xml, SalesDAL"/>
</
sqlMaps>
</
sqlMapConfig>

And finally the SalesMap.xml file is as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<
sqlMap namespace="SalesDAL" xmlns="http://ibatis.apache.org/mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<
alias>
<
typeAlias alias="SaleHeader" type="SalesInterfaces.ISale, SalesInterfaces" />
</
alias>
<
statements>
<
procedure id="InsertSaleHeader" parameterMap="InsertSaleHeader-Params">
dbo.InsertSaleHeader
</procedure>
</
statements>
<
parameterMaps>
<
parameterMap id="InsertSaleHeader-Params" class="SaleHeader">
<
parameter property="Tax" />
<
parameter property="TotalValue" />
<
parameter property="SaleNumber" direction="Output" column="SaleNumber" />
</
parameterMap>
</
parameterMaps>
</
sqlMap>


I won't go into all the details of the configuration, but as you can see it's not onerous in any way. In fact I found that overall iBATIS it’s a lot simpler to use than NHibernate for this type of operation and it's much easier and faster using it than doing the alternative and writing ADO.NET by hand.

Oh, I should also mention that there is a Castle Windsor facility that loads iBatis up for you so you don’t have to maintain dependencies throughout your application.

So when is using IBatis a good choice? I'll let the IBatis team say it in their own words (taken from the documentation):

So, how do you decide whether to OR/M or to DataMap? As always, the best advice is to implement a representative part of your project using either approach, and then decide. But, in general, OR/M is a good thing when you
  1. Have complete control over your database implementation
  2. Do not have a Database Administrator or SQL guru on the team
  3. Need to model the problem domain outside the database as an object graph.
Likewise, the best time to use a Data Mapper, like iBATIS, is when:
  1. You do not have complete control over the database implementation, or want to continue to access a legacy database as it is being refactored.
  2. You have database administrators or SQL gurus on the team.
  3. The database is being used to model the problem domain, and the application's primary role is to help the client use the database model.
In the end, you have to decide what's best for your project. If a OR/M tool works better for you, that's great! If your next project has different needs, then we hope you give iBATIS another look. If iBATIS works for you now: Excellent!

Oct 2, 2008

Using Mind Mapping to Capture User Stories

I've been doing a fair amount of requirements gathering lately across a number of projects that I've been working on. At the start of each project I needed some way to get a handle on the size of the project and I wanted to do so in a way that improved customer collaboration while helping me structure what the project was all about..

Enter user stories.  For those who don't know - user stories are requirements written in the form of "as a <role> I want <something> so I can <reason>".  They're short one sentence structures that act as a mechanism for drawing out not only what a system needs to do, but also why.  The why often being the thing that is overlooked in traditional requirements documentation.  Stories are also of great use when trying to compile a product backlog and prioritise the order in which work should be carried out.

Now in times past I would've sat down with the customer, opened an Excel sheet or One Note section, and started writing stories right there and then. On the screen.  In front of them.  In one great big long list.

And this works really well.

The customer gets involved in the story writing, in the flow of developing stories and describing roles.  It's engaging and fun and the customers love the involvement.  Now here's the wrinkle - we like to write stories in groups of related items so it's easier to keep track of what our thinking is, but unfortunately people aren't linear creatures.  We tend to jump around, go off on sidetracks and tangents, work our way around a problem, attack it from different angles and generally approach things in a somewhat random but related manner.

When you try recording stories in an excel sheet and you get more than a few hundred of them it starts to get really hard to figure out what stories relate to which parts of a system.  The customer asks "can we go back to where we were talking about thing X? I want to add a few related stories because I've forgotten some stuff".  So we look at the list, realise we can't remember where those other stories were and start searching for keywords until we find the area we want.  Over time it gets kind of confusing.  Also, unless you tag your stories with a functional area they relate to, when you come to collate stories later on you can waste a lot of time and gets things mixed up very easily.  Didn't we cover this already? What should this be related to? etc.

Enter Mind Mapping

Mind mapping, for those who don't know, is a technique where you start by drawing up a few basic ideas and then expanding on those ideas as you think further about them, creating other sub-ideas and so forth.  When you find related ideas you link them together or branch off ideas based on a core theme or concept.  Over time you end up with a whole raft of ideas that are all interrelated and linked in some way.  Mind maps are a great tool for visualising this approach.

So these days when I'm gathering requirements I use this technique but instead of starting with a core idea I start with a placeholder ("the system") and then branch off into the things that people want the system to do. 

Normally people start off with some very high level concepts, and then you start to flesh out those ideas eventually working down into the details. When there is enough detail to write stories in then I start adding the stories directly to the mind map.

Here's an example:

image

Where this gets useful is in the way people think - you can now visually jump around the mind map and easily navigate to where concepts and functionality are located.  Also, you end up talking about things from the customers view - it's their mind map you are helping to draw up.

If you keep at this for a while you can create some fairly large and complex requirements maps - for example the one pictured below has over 1,200 nodes on it yet it's still easy to navigate and find items plus the customer is able to understand what it is that they are asking from the system without getting lost in the details.  I find it hard to do that effectively in an excel sheet, or with story cards alone, so I shudder to think what a struggle it is for my customers.

image 

Don't Forget

Don't confuse things here. A mind map is not the ONLY thing I use for requirements.  I still work with user stories, I still do sizing (though often on the mind map itself), I'll still record stories in excel or TFS or <tool of choice> and I still prioritise them with the customer.

The mind map is just a tool to assist in the effective gathering of requirements, and it helps my customers think through what they want more clearly.  This helps reduce the number of missed requirements and improves understanding between us and I think that's a good thing.

Mind mapping is just one more tool for your agile development toolbox. A useful tool, but not at the exclusion of anything else.

P.S. The software I've used here is FreeMind.  It's a little more structured than some of the other mind mapping tools out there, which I find useful when working through requirements and wish list items.