Showing posts with label how to. Show all posts
Showing posts with label how to. Show all posts

Dec 17, 2013

View the Password of a Disconnected WiFi Network in Windows 8

Disclaimer: This post is a 'note to self' reminder post, though if you find it useful I'm happy I could help.

As a consultant I tend to jump around various networks and when working with other consultants it's not uncommon to need to share WiFi passwords for networks that you aren't currently connected to. The problem is, Windows 8 dropped the "Manage Wireless Networks" feature so this isn't as easy as it used to be but there is a simple way.

How to:
1. Open a command prompt
2. netsh wlan show profile name=[network name] key=clear

That's about it. Simple.

Credit to LifeHacker where I originally found the info.

P.S. netsh is also useful for deleting profiles of the various public hotspots you've used. Why? Just ask Troy Hunt and his Pineapple :-)

Feb 5, 2011

Branch per Story Pattern and TFS

The TFS branching guide is a very detailed run through of the various situations and scenarios under which branching can be performed and the different strategies that exist, however because the guide covers so many scenarios it’s difficult for some people to know what approach they should follow, and when they look at some of the advanced diagrams they freak out at the complexity.

For this post I’m going to keep it simple and just show one approach, the one that I feel is best for agile teams implementing using user stories.  It’s effectively the feature branch approach, and I’ve been tempted not to write this post, however I find that that feature-branch approach can be a little confusing for some people.  “What is a feature?” “Is it multiple stories?” “Is it an epic?” “Is it a bug fix?” “Should a feature live across multiple sprints?” These are all questions I hear and it’s probably because the terminology is a little too generic and becomes open to interpretation and thus misunderstanding.  So, let’s make it easy and use Agile terminology.

Why Story Branches

So before we get into it, what exactly is wrong with working in trunk or using a branch per sprint approach? If you can make it work then there is nothing wrong with that approach, but it does come with some with hidden dangers.

Consider the following situation.  A team accepts 3 product backlog items for a sprint and only completes 2 of those items.  The third story was in progress when the sprint concluded but was far from complete and the team now has a section of unfinished code in their code base.

What should the team do with that unfinished code? Should they go back and comment it out or delete it?  Maybe, but how will they be sure they got it all?  What if some of the changes they were making affected the system architecture and those changes had been used in the implementation of the other two stories? What if the code was also merged to another branch in preparation for a release?

What if they take a different approach and try wrapping all changes in if-blocks during development to try and isolate the changes?  Sure, this can work.  But again it has challenges.  The team needs to maintain a set of variables or pre-processor tokens related to each item that are used to decide if a feature is available or not.  There’s also going to be a large number of if statements that will add noise to the code and in a complex system you can easily imagine how out of control this could get.

What if they just ignore these challenges (or forget the code) and leave the unfinished code as is? At best they have code that is unused and simply adds bloat to the system, at worst it results in the system being released with broken functionality and open security attack vectors that have never been checked or tested.

If we also remind ourselves that sprints should produce production ready, potentially releasable increments of the system, then we really, really don’t want to have work in progress code in the system at sprint conclusion.

For all of these reasons we should ensure our development of a feature is isolated from the rest of the development team and only made generally available when complete and ready for integration testing.

There’s an interesting side effect to taking this approach.  If we develop features in isolation and consider Conway’s law which when paraphrased says that system architectures reflect the way the organisation communicates, then by nature the systems we develop using a branch per story model will likely be architected and designed as componentised and modular systems, mirroring the development approach we are using.

Downsides

What are the downsides, then? Surely the administration overhead goes up and chances of screwing up merges increases, and yes, there is an element of that, but it isn’t as bad as you think.

Administration time goes up because we now have to remember to create a branch, and we have to remember to switch branches when we work on different stories in the same sprint.  Is this really an issue though? Maybe it is.  However maybe it’s a hidden blessing in disguise.  When working in an agile manner we want to minimise wasted effort and keep our work in progress as low as we can. We know that the costs of multi-tasking, working on different stories at the same time, means we’re go slower overall than if we just work on one story at a time because of the mental context switch and yet the temptation to multi-task is high, especially if the stories we work on are somewhat boring.

By following a branch per story strategy we discourage ourselves from multitasking since the simple annoyance of switching to a solution file on a different branch gives us a natural prevention mechanism.  Note that this annoyance doesn’t work with DVCS systems like git and mercurial since branch switching is very quick and easy, but in TFS, SubVersion and similar branches are represented as folders and switching means swapping folders, and thus closing and re-opening the solution.

What about merging? Branching is easy but a great deal of pain can be had in the merging of branches.  This pain is most often encountered when the two branches have diverged significantly.  However, in a branch-per-story model most branches are short lived and thus merging fairly straightforward.  It doesn’t mean merge conflicts can’t occur, just that the merges are likely to have small amounts of conflicts.

Visual Branching Model

So let’s have a look at what we’re doing with the branching model.  For each story in the sprint we work on we’re create a story branch by branching the main integration branch.

Let’s say the team picks up three stories for the sprint.  We create the story branches and the team commences work:

image

Let’s say Story 1 gets completed first.  The code for story 1 is merged back to the integration branch, the integration code is checked and verified and when all the tasks for the story are complete the branch is killed off.

Next, Story 2 is completed so the developers pull from the integration branch, merge the changes, confirm things are OK locally, then push their changes back to the integration branch.  Again, the developers check the code in the integration branch is OK, and when it is the story 2 branch is killed off.

Finally Story 3 is code complete.  Again, the developers pull the branch code down to their story branch, do the merge and make sure it’s OK.  When it looks good they push their changes back to the integration branch, make sure the integration branch is OK and kill of the Story 3 branch.

Pretty simple process, right?

Doing it with TFS

So, enough with the explanations let’s see how we do this with TFS.

Creating branches is easy enough, but how do you name the branches?  We don’t want to try and embed the story name in the branch name since that will increase folder length and makes it far more likely that we’ll hit the file path length limit (yes, there is one and it’s smaller than you think).

The strategy I prefer is simple.  Because we are using TFS and stories are just TFS work items, I like to use the story number as the branch name.  Here’s an example:

image

Now let’s do some work on story 2639 (aka “Make this system more awesome!”) and check it in. Now we need to make sure that we’re on par with the integration branch by doing a merge.  We simply right click the Integration branch and select Merge:

image

Then merge to the appropriate story branch

image

Select the latest version to make sure we’re current and hit the button

image

It appears there are no changes to merge.  Excellent, we’re current.

image

So now we merge our changes from the story to the integration branch (same process, just start by right-clicking the story branch).  Also, don’t forget that merges are made as local changes and still have to be committed, so add a check in comment and do just that.

Wait for the integration build to pass and check the acceptance tests pass to let us know that the story is complete.  Once it is we can now kill the story branch.  To do this, simply right click the branch in source control explorer and select delete!

image

Again the delete’s are pending changes until we check them in.  So again, add a comment and check in the changes.

Our branch hierarchy now changes from this:

image

to this:

image

Nice and simple.  And not a lot of overhead.

As for the other stories we follow the exact same procedure when they are complete:

1. Make the changes needed for the story in the story branch
2. Pull and merge changes from the integration branch into the story branch
3. Deal with any merge conflicts
4. Check that the story is still OK
5. Push and merge the changes back up to the integration branch.  You shouldn’t have any merge conflicts for this merge.
6. Check that the Continuous Integration build passes
7. Run any other tests on the integrated code as required.

And we’re done!

When all stories are complete in the sprint there should be no story branches left. The only time this won’t be true is when the team finished the sprint with incomplete stories.

What About Bugs?

Bugs in an agile team are just the same as stories.  Create a bug fix branch each time you need to fix a bug just the same as we do for stories.

About the only time you might not do this is when you are doing really simple bug fixes such as spelling mistakes where the changes are just cosmetic and there are no real logic or functional changes.

What About the Build Server?

So a question you may have is what do we do with builds and the build server? Answer: it’s up to you.  Given how short lived the story branches are likely to be it’s probably not worth creating build definitions for each story, but again, it’s completely up to you. Regardless of wether you have a build per story or not, you should have a continuous integration build tied to the integration branch.  When each story is complete and merged back to the integration branch a build should be triggered that compiles the code, runs all the unit tests and so forth to confirm that the code in the integration branch is OK and nothing went wrong during the merge.

Nov 23, 2010

How to Build Linux Code with TFS 2010 Team Build

With the release of Team Foundation Server 2010 and Team Explorer Everywhere Microsoft extended the reach of TFS beyond just the Microsoft ecosystem and provided a way for people doing Linux and Mac development to use TFS to meet their Application Lifecycle Management (ALM) needs.

Whilst TFS works great for source control and work items for Linux development it doesn’t include a Linux specific build agent so many people think it can’t be done.  But that’s not quite true. And yes, before people point out the obvious, there are a number of excellent Linux specific build engines that can do automated builds from TFS source by calling the tf command line, but they don’t integrate into TFS in anywhere near the same way that Team Build does which is why Team Build a desirable option for many places.

Anyway, back to the issue at hand, thanks to tools like PuTTY we can do remote shell calls to Linux boxes as part of the build process, and you we can also copy files to and from the Linux box as part of the same process which gives us the ability to compile on Linux and still get the compiled binaries placed in the drop location as per normal windows builds.

For example I have a customer at the moment who is moving their Progress source code (yuck!) out of Roundtable and into TFS, and as part of that transition we’re moving the build from a custom set of shell scripts into Team Build.  Without going into the specifics of their particular needs, let’s have a quick look at some of the key ingredients needed to get Team Build successfully executing commands on a remote Linux server.

Install and Configure PuTTY on the Windows Build Agent

As mentioned before we’re going to use some of the PuTTY tools to connect to the remote Linux box.  If you haven’t already done so, go grab the Windows PuTTY installer from the download page and install it on your build server.

Now we need to configure PuTTY so it knows how to connect to the remote server.  We’re going to use SSH to do this, and since we don’t want to store passwords in our build scripts we want to use a public key for authentication.

Login to your build server using the build service account.  Note: This is important! If you don’t do this then you will likely have issues the first time you run a build as ssh will prompt the first time you use a public key for authentication and the build will hang waiting for a response.

Now open a command prompt, go to the install folder for PuTTY and run puttygen.exe.  A dialog will appear.

image

Click Generate and move the mouse around a little as requested (such fun!) until you get a key generated.

image

Note that we’re intentionally leaving the passphrase blank so that we don’t get prompted for a password during the build process.  This of course means there is a potential security hole if someone attacks the windows build agent machine, so make sure that the account you will log in to on the Linux box is not a privileged account.  Save both your public and private keys.

Next, login to your Linux box and open the $HOME/.ssh/authorized_keys file in vim and paste in the public key as a new entry in that file, then save the changes, close the file and log off.

Now to test it and get through that first configuration prompt.

From your windows command prompt run plink to do a listing of your home directory on the Linux box.  For example:

plink –batch –ssh –i privateKey.ppk linuxBuildAccount@linuxServer “ls –l”

When prompted to store the key answer with a “y"es.  Once that’s been done once we won’t get asked again when we run automatic builds.

Assuming this works, and you see something coming back then we’re right to move on.

Customising TFS Team Build to Build on Linux

From here it’s pretty simple and works much the same as the customisation for VB6 builds I’ve posted about in the past.  This won’t be a complete blow-by-blow on how to do it – just enough information to cover the important parts you need to know.

For all the remote Linux interactions we’re going to rely on the InvokeProcess workflow activity to make the calls we need for our build process.

As a note, I usually take the existing Default Process template and gut it – removing most of the activities from after the workspace has synced (i.e. the get latest section) and the code has been pulled down to the build agent and use that as a starting point for building up the Linux build process.

Regardless, once the code has been pulled down into the build agent’s workspace we have two choices for making the source available to Linux.  We could define a network share that points to the build agent’s $(Sources) folder and get Linux to build the sources using a UNC path (via samba), or alternatively we could use PuTTY’s pscp command to copy the sources to the Linux machine for local compilation and copy the compiled output back when the build completes.  You should do whatever you are more comfortable with, and since both have pros and cons it will be a matter of how your Linux build works that dictates the best approach.

For this example let’s do a copy of code onto the Linux box and then call the compile.

Begin by dragging an InvokeProcess activity into your build process workflow at an appropriate point:

image

and set the properties of it as follows

FileName: """" & Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) & "\PuTTY\pscp.exe" & """"
Arguments: "-batch -scp -i """Path\to\\privateKey.ppk"" “ & SourcesDirectory &  “ linuxBuildAccount@linuxServer:/build/sources"""

Don’t forget to check for error conditions when the task completes.

Next drag another InvokeProcess activity into your workflow and this time use plink instead of pscp and call the command or script you need to do the compile. The following activity properties show an example:

FileName: """" & Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) & "\PuTTY\plink.exe" & """"
Arguments: "-batch -ssh -i ""Path\to\privateKey.ppk""  linuxBuildAccount@linuxServer ""<command to run – e.g. make all>"""

Again, don’t forget to check for errors.

Finally when the build is done use another InvokeProcess activity to call pscp as shown above and copy any compiled output to the drop location.  For reference the drop location folder can be found using the BuildDetail.DropLocation property.

 

Hopefully this is enough to get you on your way to building your Linux applications via TFS 2010’s Team Build.  Good luck!

Apr 6, 2010

How to Add Assert.Throws() to MSTest

One of the frustrations with MSTest is that it is falling behind the times for unit testing when compared to other testing frameworks.

I find it a real shame this this is happening and that MSTest didn’t gain an Assert.Throws method at any point along the way and that we still have to stick the ExpectedException attribute on our test methods, not to mention the fact that the expected message in the attribute still doesn’t get checked properly.

Now you may be asking “What’s wrong with just using the attribute on the test method?” Simple – consider what happens if the exception your looking for gets thrown by a line other than the one you were expecting it to be thrown on? You will get a false positive.  A test that passes even though it should be breaking.  Nasty stuff that.

I think the Assert.Throws() method from xUnit is so much better because it’s very explicit.  When you use it you know exactly what line the exception should be thrown on and you can also check that the message provided by the exception matches your expectations.

So, why not just use the xUnit asserts thent?  Well, we can.  We can actually keep the MSTest runner and use all the xUnit Asserts instead of the MSTest ones.  Not only do we gain the Assert.Throws() method but we also get xUnits Assert.Equals() method, which can compare arrays and lists, and more.

Here’s how…

  1. Add a reference to xUnit to your test project
  2. Add “using Assert=Xunit.Assert;” to your code
  3. Use the Assert.Throws method as you would in an xUnit test.

Pretty tough, huh?  Here’s an example of it in action:

using System;
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Assert=Xunit.Assert;

namespace MyTests
{
[TestClass]
public class SomeSillyTests
{
[TestMethod]
public void ShouldThrowNullReferenceException()
{
string myNullString = null;
int length;
Assert.Throws(() => length = myNullString.Length);
}

[TestMethod]
public void ShouldCompareListEquality()
{
List<string> List1 = new List<string>() { "a", "b", "c" };
List<string> List2 = new List<string>() { "a", "b", "c" };
Assert.Equal(List1, List2);
}
}
}

Enjoy your new found Assert freedoms! :-)  P.S. The same techniques can be applied to using the NUnit or MBUnit Asserts or your own Assertion library of choice.

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!

Mar 24, 2010

Personal Time Management and Agile

Agile frameworks and approaches put a high degree of attention on getting things done quickly and efficiently.  The end goal being to get software into production as efficiently as possible with a level of quality that makes the customer happy and provides a good return on investment.  You will often hear people talking about agile (and lean for that matter) also talking about waste and using “inspect and adapt” to minimize wasted effort.

One of the things I see teams doing regularly is taking a day to day approach to development that completely ignores personal time management.  A team may estimate a task to take, say 8 hours, and generally it will get done in or around that timeframe (it is an estimate after all), but if you actually watch how people approach completing that task it soon becomes apparent that the 8 hours spent on that task isn’t really 8 hours of good solid effort at all.

The task may have had 8 hours elapse between when it was started and when it was finished – but the actual time spent on the task is typically somewhere between 4 and 6.  Where did the other 2 to 4 hours of time go?  Sure there’s toilet breaks, coffee runs and helping out others on the team out, but that’s not 2 to 4 hours each and every day is it?

This lost time is what teams typically refer to in planning meetings as their “focus factor”. Some teams have a focus factor of 50%, other teams a focus factor of 75%, whatever.  Either way, teams are looking a potential performance improvement of between 33% and 100% right in the face and doing absolutely nothing about it! In fact, they are institutionalising low productivity and calling it good planning. Really, all they are doing is admitting that change is hard and giving up before they even try and improve things.

This is where a team doing retrospectives and wanting to improve can really make a big gain.

As an example of this lost time, let’s have a look at just two things that tend to suck up those non-development hours.

Email is the Great Evil of Our Time!

Maybe that’s going a little too far :-) However the next time you get an email from someone, see how long it takes to put your response together.  If you write a response that has more than one or two lines in it then I’m going to guess that it will take you a LOT longer to write that response than it would have if you had just talked to the person in person or over the phone.

In fact if you really want to scare yourself, go grab a copy of ManicTime and use it see just how much time you spend in your email client of choice. In fact, do it anyway.  Download it, install it and run it just for one day and look at the results.  You might just find that your focus factor of 75% was too high!  Maybe that explains the difficulty you’re having getting sprints completed well.

Oh, if you’re in one of those organisations where email is used as the ass-covering tool of choice, don’t forgo conversations and revert to email just to cover your butt.  Use email as a confirmation tool and note down bullet points from your conversation – during the conversation – to later send through a “just confirming what we talked about in our phone call” email instead.  It’s much quicker.

Multitasking and Self Induced ADD

Multi Tasking is the other great way to slow yourself down.  The cost of task switching for humans is nasty – our brains just aren’t wired up the right way to be able to swap in and out of context quickly.  We may convince ourselves that we can, and we may try to lie to ourselves about how the tech generation are all skilled multi taskers, but really, it’s all bubcus and an excuse for being unable to concentrate for more than 2 minutes at a time.

squirrel In fact all we really do when we have multitasking as our modus operandi  is become really good at starting things and become really terrible at finishing them.  Why? Because constant task switching trains our brains to have short attention spans.  Short attention spans mean that we have a problem whenever a squirrel shows up.  We’ll get distracted and go chasing after it and to get back on track we have to sniff around what we were doing before and try and piece back all the various things we had in our head before the distraction showed up in the first place.

Short attention spans create an illusion of being productive through the act of being busy. We generate lots of movement and energy when we’re busy, but in reality all that movement just creates a big dust cloud that masks just how little progress we make.

For us humans, the best way to finish tasks as quickly as possible is to do them sequentially.  This costs us a single context switch between tasks instead of a context switch each time we change from one task to another.  For us developers locking in on a single task also gives us the opportunity we need to get us into the zone – that magical place where high quality code just seems to fly out of our fingers, where we flow from one thing to the next with ease, and where we get stuff done ten times faster than we would have normally.

Sure it sounds great, but development has so many chances for distraction.  Not sure how to do something?  Google it, see something else interesting and go investigate that instead.  The task we’re doing is boring? Let’s take a little break and play solitaire for a few minutes.  This compile is taking more than 5 seconds?  Maybe we’ll just check email while we wait.  it’s all self induced ADD and we need to learn to stop.

So What’s The Answer?

It comes to this: Personal time management, discipline and focus.  How do you, yourself, personally, manage your time as an individual? How do you maintain focus? How long do you maintain it for? When do you take a breather since all that concentrating can be tiring?  How tired are you right now?

First up, let’s deal with some simple distractions.  Have a look around you right now at all the possible distractions you have – twitter, facebook, rss feeds, email, news sites, instant messenger, a side conversation you could join in on, that delicious smell coming from the kitchen, txting, flash games, the list goes on.  Things like twitter, outlook and IM in particular can be really nasty because of their interrupting “new message” toaster notifications and beeps.  Turn those notifications off.  Do it.  Go into settings and turn them off.  Right now.  It’s OK to leave those apps running, just delay checking for new tweets, emails and messages until until you finish what you’re doing.

What if you’re waiting for that compile or CI build to complete, what do you do? Press Alt+Tab and go read a blog entry or 5 for the next few minutes?  It’s easy for that few minutes to turn into 10 or 20.  And yet the compile itself only took 3 minutes to complete. That’s a lot of wasted time and a definite mental context switch you have to deal with.  Yet watching a compile is mind numbingly dull. So why don’t you think about some refactoring you could apply, or the next test that you could write, or the design for the next task that you’ll get started on next.  There’s plenty of non-keyboard activities you can do that keep you focused on the task at hand and not chasing squirrels.

This is also where techniques such as the Pomodoro Technique and pair programming can help.

Pairing provides a focus boost simply because you have someone next to you who is also focused on the same goal as you. The two of you keep each other on track.  I’m not going to delve to much into pairing here, however if you consider what it does for our focus factor you can see how teams that use pairing can easily get a return on the supposed cost of putting two people onto a single task,  simply because they won’t get as easily distracted and can thus complete their tasks faster.

imageFor individuals not in a pairing situation, the Pomodoro Technique is a simple process they can follow and works like this:

1. Choose a task to be accomplished
2. Set the Pomodoro to 25 minutes (the Pomodoro is the timer)
3. Work on the task until the Pomodoro rings, then put a check on your sheet of paper
4. Take a short break (5 minutes is OK)
5. Every 4 Pomodoros take a longer break

Quite simply it says focus on just one task until either the task is complete or 25 minutes is up.  When that happens, give yourself a mental break.  It’s effectively a series of short, sharp personal sprints.

When you’re working on your 25 minute pomodoro you don’t open email, you don’t look at twitter, you don’t check news sites, you don’t get a coffee or anything else.  You just work on the task.  All those other things are for filling those 5 minute breaks you have.  And if you’re in an organisation with a plethora of email – then one of your pomodoros should probably be spent dealing with that email!

Oh, don’t worry if you don’t have a clock that looks like a tomato either.  Just grab yourself one of the many pomodoro timer apps, such as FocusBooster, and use it instead.

You may find this hard at first, but once you do it a few times, you’ll find it becomes easier and easier to do.  You’ll find that without any changes to technology, skills, work hours, or otherwise that doing this will result in an increase in team productivity and velocity – and all you’ve had to do is be a little more disciplined and a little more focused on the task at hand.

Let’s work smarter, not harder, right?

P.S. The irony that a long post like this isn’t likely to be read all the way through by people with short attention spans isn’t lost on me! ;-)

Good luck!

Jan 27, 2010

How to get Git and TFS Working Together

Update: There's now a second approach for doing this that you may want to look at

TFS has a lot going for it and from a team perspective it’s a fantastic tool and something I wouldn’t pass up willingly.  That said it is a little lacking in some areas and one of those is the source control story.  For some time now I’ve been toying with writing a Git-TFS bridge but just haven’t had the time to really get stuck into it.  For that reason I decided to see if I can get Git talking to TFS via the TFS SvnBridge utility.  I know what you’re thinking and yes, it’s a 3-headed monster if ever I’ve seen one, but I’m a brave (or foolhardy) adventurer and I don’t mind the occasional challenge.

As a note I’m not going to go into a lot of detail on some of the Git commands.  This is more about how to get Git and TFS working together, not how to use Git.

Getting started

Download the SvnBridge client from http://svnbridge.codeplex.com/.  Extract the SvnBridge.exe from the zip file and run it.  It will appear in your system tray and will show you the base URL to use for your SVN commands when you mouse over it.

image

To make sure it’s all working try browsing the TFS server via TortoiseSVN (repo-browser). I found this to be a little slow, but it worked fine.  The URL I used in SVN was something like this http://localhost:8080/tfs.server.name/projectName/Trunk

Assuming that’s OK you can then create an empty folder, open a command prompt and set the new folder as your current directory. Now you can clone (i.e. copy) the TFS repository into Git using the command below (as a note I use msysgit for my git work and have the git bin folder in my path).

git svn clone http://localhost:8080/tfs.server.name/projectName/Trunk/SubFolder SubFolder

This admittedly did take quite a while to do.  It was a large source tree and the TFS server is in a remote location but even so, it’s a lot slower than just doing a full get latest from TFS.  Also, be aware that cloning a repository is making a copy of the whole repository, including history. If you just want the latest revisions and you’re not worried about history (it’s in TFS after all) then I’d recommend you use the –r option and supply a recent changeset number (or range).

I also noticed that failing to put the target folder name at the end (even when it’s the same) can result in errors like this so make sure you include it.

Invalid filesystem path syntax: REPORT request failed on '/tfs.server/!svn/vcc/default': Target path does not exist at c:\Program Files (x86)\Git/libexec/git-core/git-svn line 4567

Now go get a coffee and come back.  Once the download completes you should be able to browse your source folder and see everything is there.

We’re all set now, right?

OK, so now we have all the files from TFS locally, and because we used the SvnBridge we don’t have the annoying TFS read-only flag set on our files.  Nice.  We can start working on our project again, right?

Well not quite.  Visual Studio has this nasty “feature” where it puts source control binding information into the solution and project files.  It’s a major pain in the butt and is something you’ll have to work around if you’re in a team environment where not everyone is using this Git/Svn/TFS combo.  We’ll need to manually remove all that binding information from the solution, however we have to think of our team members.  We can’t just edit the solution file directly as other TFS users will/may be relying on it.

Also, before we make this change we’re going to do one other thing.  We’re going to create a local branch and use that as our working folder.

You can either use the Git Gui (see the branch menu) or you can do it via the command line using the git branch or git checkout –b NewBranch commands.  I’ll leave it up to you to choose the method you prefer.

So now we should have both a master and a local branch. Before we proceed just confirm that you are in the correct branch by doing a git branch command (no arguments) at the command line – the current branch should be highlighted.  If you’re using the GUI then the branch name is shown near the top.

Now, to remove the bindings open the solution file in notepad++ (or the text editor of your choice) and find the section that looks like this and simply remove it.

GlobalSection(TeamFoundationVersionControl) = preSolution
    SccNumberOfProjects = 15
    SccEnterpriseProvider = {4CA534B2-18FA-4F9D-95D4-32DDF27D184C}
    SccTeamFoundationServer = http://tfs.server:8080/
    SccLocalPath0 = .
EndGlobalSection

Save the file and then open it with Visual Studio.  When you do, you’ll be told that the source control provider can’t be installed and then presented with a choice.

image

Since you’re in your local branch you can take either option.  I prefer to choose to work uncontrolled so that visual studio doesn’t remove all the source bindings from the project files (which would break things for others on the team) and it means there’s one less thing to worry about when pushing changes back to TFS.  Regardless, once you make a choice the solution will open as expected and you can make the changes you need to.

P.S. If you haven’t already done so, you may want to create a .gitignore file to ignore those pesky artefacts that get created during development.  There’s an example of one here - http://gist.github.com/233903.  Just put it in the root of your source tree (the folder with the .git subfolder).  You may also want to commit it to your repository so you can track any changes.

Now we’re cooking! Let’s update TFS!

OK so now we’re all set.  Sweet! Go ahead and do your normal development work.  It’s OK.  You’re allowed to :-)

When you’ve made changes you can commit them to Git using either the command line or the Git Gui (which I tend to use) and do any of the other normal things you would do when using Git.

When you’re ready we can now push your changes up to the TFS server.  First we’ll want to push our local branch changes to the master branch (remember to be aware of changes in the solution file).  You may also want to do a git rebase (example) on your local branch to consolidate all your small changes into a single commit before merging to master in preparation for pushing to TFS.

The workflow is basically: git rebase (optional) –> git checkout master  –> git merge –> push to TFS

And the command to commit to TFS is simply

git svn dcommit

Git will push all your local changes to the server and if everything is OK you should be able to switch to team explorer and see the changes in there.  Nice :-)

How do I do a “Get Latest”?

I almost forgot, you will no doubt want to do a “get latest” at some point.  From the command prompt simply do this:

git svn fetch

And it will get the latest changes for you and update your local git repository.  Note that git won’t just get the latest change, it will actually get all the individual changesets from TFS so that the local Git history is up to date.  This is slightly different from TFS where the local workspace is just being brought up to the current changeset.

Pros and Cons?

So, what are the benefits and where do things fall over?

Well, obviously the biggest benefit is that you are now able to use git and work in a truly offline manner from TFS.  You can branch locally and make changes in isolation of others without messing things up for anyone other than yourself, and the speed when working locally is blindingly fast (no over the wire communication with TFS)

On the downside SvnBridge is quite slow and the process to get code in and out of TFS involves more steps than clicking a few buttons in Visual Studio. 

Also, with Git holding all the history, you’ll chew up quite a bit more disk space locally.  I know disk is cheap but in many organisations developers are forced to work with puny boxes and miniscule amounts of space so it may be an issue.

Caveat Emptor:  I haven’t done a lot of work this way as yet and there are many things I haven’t come across as yet (check in policies blocking a commit for instance) so your mileage may vary. You have been warned :-)

If you do try this, I’d be keen to hear how you get along with it.  Good luck!

Dec 21, 2009

How to Test Web Sites with IE6 on Windows 7

We’re doing a bit of work testing web sites with IE6 (still! I know!!) since it’s in our browser compatibility list, yet we do all our development using Windows 7.

One little trick we’ve done to make this somewhat easier is to install Windows XP Mode on our machines.  So we can launch the Windows XP VM now and run IE6 inside it, but what we really want to do is just have it appear as an XP Mode application in our Windows 7 start menu like this:

image

This is pretty easy, but it’s not there by default when you install XP Mode.

To get it working just start the XP Mode VM and create a shortcut in the “All Users” start menu to IE6.  Once you do that, it should appear in the normal Windows 7 start menu almost straight away as shown above and you should be all set to go.

I hope that makes testing IE6 just that little bit easier…

Of course the better solution is to drop IE6 support completely and tell people to upgrade to a real browser using a little JavaScript from http://ie6nomore.com

Dec 16, 2009

Learning To Podcast

For a bit of fun I decided to try and record a podcast just to see how it’s done.  As it turns out, it’s not too hard at all.

For my little experiment I wanted to try and do one of those interview style podcasts, not just one where it’s me talking by myself but one with another real live human being at the other end of the line.  Here’s what I did.

  1. Watched a “how to use Skype for Interviews” presentation on slideshare.  Thank you Doug Kaye and Paul Figgiani!
  2. Found a human guinea pig for my little experiment.  Thank you “Subject A”.
  3. Grabbed a utility for recording Skype conversations.  Thank you Call Graph!
  4. Grabbed another utility for post-editing audio files.  Thank you Audacity!
  5. Made a Skype call with Subject A, did the interview and recorded it.  Kind of important.
  6. Did some post editing with Audacity to remove as much microphone bumping and kids screaming in the background as I could.
  7. Exported the edited audio as an MP3 file and done!

I think the end result was reasonably good, though listening to it a few times I realise I need to improve my vocal skills, but hey, it’s a first time go at interviewing and playing with the technology as well so I’ll give myself some latitude for improvement.  I also had a play around with making Subject A sound like they were on a telephone using a VST plugin for Audacity which helped create a nice “calling in to the show” feel.

All up I found it pretty easy to put together, the hard part was finding some useful tips on how to do it.  If you’re thinking of creating a podcast of your own then hopefully this will give you a starting point.

Nov 16, 2009

Raising Events With Rhino Mocks AAA Syntax

There’s various posts on the web showing how to raise events in Rhino Mocks but they typically show you how to do it using the Record/Replay syntax, which I personally find quite awkward.

I was just helping out someone today and showing them how to do it using the Arrange, Act, Assert (AAA) syntax in Rhino Mocks 3.5 and I thought you might be interested in know how to do this as well.

Let’s start with a basic scenario… let’s assume that in our class under test we wanting to check that when we call a method on another object, that it will raise a CancelEvent and we can listen to that event and take action as appropriate.  I like to test behaviour in my classes, so in my test I want to be sure that my class under test correctly subscribes to the event and that it will set the cancel flag correctly..

Here’s some code.
public interface IProcessor
{
 string AMethodThatRaisesAnEvent(int value);
 event EventHandler<CancelEventArgs> AboutToProcess;
}

public class EventListener
{
    IProcessor processor;
    public EventListener(IProcessor processor)
    {
        this.processor = processor;
        this.processor.AboutToProcess += HandleTheEvent;
    }

    public string MakeItHappen()
    {
        return processor.AMethodThatRaisesAnEvent(0);
    }

    public void HandleTheEvent(object sender, CancelEventArgs args)
    {
        if (sender is IProcessor)
        {
            args.Cancel = true;
        }
        return;
    }
}
So as we can see, the constructor takes in the processor object and starts listening for the AboutToProcess event.  When it fires it checks the senders type and and sets the Cancel flag.  It’s a silly thing to do in reality since normally you would check property values on the sender and decide wether to cancel or not, but for the purposes of the post, it will do.

Now let’s write our behaviour test.
[Test]
public void TheEventListenerShouldCauseProcessingToBeCancelled()
{
    var processor = MockRepository.GenerateStub<IProcessor>();
    var args = new CancelEventArgs();
    var listener = new EventListener(processor);
    processor.Stub(p => p.AMethodThatRaisesAnEvent(0)).IgnoreArguments()
        .Do(new Func<int , string>(value =>
                {
                    processor.Raise(x => x.AnEvent += null, processor, args);
                    Assert.IsTrue(args.Cancel);
                    return string.Empty;
                }));
    listener.MakeItHappen();
}
So what’s happening here?

In the first few lines we arrange the objects we want for the test, then we get into the juicy bit.

It may look a little scary but if you break it down into it’s components, it’s actually prettty easy to grok.  First we set up a stub for when the AMethodThatRaisesAnEvent() is called.  We ignore any argument values that may be passed into it and we then supply a method implementation using Rhino’s Do() method.

Inside Do we supply a new function that takes an int as a parameter and returns a string – the same signature as the AMethodThatRaisesAnEvent() method that we are stubbing.  Inside it we Raise() the event we want to fire and have an Assert that will check if the Cancel flag has been set to true.  Note that we also need to supply a return value otherwise the code won’t compile.

Look a little closer at the Raise() method.  You’ll see that you don’t just say what event to raise, you actually supply a lambda that subscribes to the event you want to raise.  It looks a little wierd but it’s a workaround for the language limitations.  The second two parameters are the event sender and eventargs parameters.

Finally we make a call on our class under tests MakeItHappen() method.  There’s no asserts aftrer that because we are only wanting to check the event handling behaviour, not the return value from the mock object.  Also, if you set a breakpoint inside the Do method, you’ll see that the event raising happens after the MakeItHappen() call, even though it appears before it in the source.

And there you have it – raising events from mock objects using Rhino Mocks.

P.S. Some of you will have noticed that I’m using Stubs instead of Mocks.  This is because I’m not asserting anything on the fake object itself and I’m simply stubbing out code.  Please don’t get too hung up on this.  There’s a whole world of pointless arguments about what to call fake objects; stubs, mocks, fakes, whatever.  I certainly don’t care and the code works just the same if you use GenerateMock and processor.Expect() so do what you’re comfortable with and ignore the storm in a teacup argument over what to call them.

Aug 3, 2009

Windows 7 Virtual Machines and Host Networking

Let’s assume you’ve got a Windows 7 Virtual Machine and you want to do networking between the Host and the Guest operating systems with it.

I’m going to give you a run through of how I set this up on my laptop using the loopback adapter.  There may be other ways, but this works quite well for my needs.

1. Install the Loopback Adapter

Go to device manager (in Control Panel) and select the Add Legacy Hardware option

image

In the ensuing wizard select: Install manually –> Network Adapters –> Microsoft Loopback Adapter

image

2. Setup the Loopback Adapter

Once the installation is complete we need to configure the loopback adapter.  My preference is to use fixed IP addresses for this so that I can use machine names to identify the VM easily, just make sure you pick an address range that isn’t used :-)

So go to the Networking and Sharing Center and select “Change Adapter Settings” on the left. You should see something like this:

image

Now go to the Loopback Adapters properties and then go to the properties of the IPv4 TCP/IP settings:

image

Simply set the IP address you wish to use for communicating with the VM.  I normally use a 10.x.x.x address range with the Class C subnet to minimise conflicts with other networks I may be connected to.

Not that I normally disable the IPv6 settings on the loopback adapter to make the configuration simpler.

3. Configure the Virtual Machine Networking

Assuming you already have a virtual machine configured you now need to go to your virtual machines settings and set up the networking as follows:

image

Set adapter 1 to be the loopback adapter and adapter 2 to be your physical network adapter so that I can access the internet and other networks from the VM should I need to.

4. Configure the VM’s Operating System

Now we need to start the VM and change some settings in the networking to use the fixed IP for the loopback adapter in much the same way as we did for the Host Operating System.

image

You may notice that in the network adapters it’s hard to tell which adapter is which since they are all the same type (i.e. the virtualised network).  The trick is to remember which network adapter is which in the VM settings – Adapter 1 is “Local Area Connection”, Adapter 2 is “Local Area Connection 2”, etc.

5. Don’t Forget Your Firewalls

So if we were to try pinging the Host OS from the VM we would probably find we don’t get a response, and the same would happen if we did it the other way around.  If that’s the case you probably forgot to adjust your firewall settings.

Here’s how it’s done in Windows 7 on the Host:

Go to Control Panel –> Windows Firewall then choose “Advanced Settings”

Select the Inbound Rules from the left side and then choose the New Rule action from the right.

image

Choose “Custom” in the dialog and then in the scope step add the IP address for the VM in the Remote settings area (as shown).  For extra security you should also ensure that the local address is set to the IP address of the loopback adapter on the host (10.2.1.1 in my case).

image

Allow all connections through on that rule and don’t forget to give it a meaningful name such as “Windows VM Loopback” or something like that.

You’ll also need to do that same in your guest operating system (assuming it also has a firewall enabled).

Once that’s done you should then be able to ping the Host from the VM as shown and do the same in the reverse direction.

image

6. One Last Step

Trying to use IP addresses can be somewhat of a pain, especially if something you’re accessing is wanting you to use host names instead.  The way to improve this situation is to edit the HOSTS file and add entries for the remote machines in both the Host OS and also in the Guest OS (the VM).

On Windows 7 start Notepad as Administrator since you need Administrator privileges to edit the HOSTS file.  The Hosts file can be found in C:\Windows\System32\drivers\etc.  Note that there is no extension on the Hosts file so you may have to change the filter in the Open File dialog to show all files before you’ll see it.

Once you have it open add an entry at the end of the file on a new line in the format of <ip address> <machine name>.  For example I use:
10.2.1.2    tfs2008-vm

Save the file and check that things are working by opening up a command prompt and pinging the virtual machine using the name you just gave it:

image

Don’t forget to do the same on the Guest OS in the Virtual Machine.

Once that’s done you should be all set to go and your Windows 7 Host and you Virtual Machine should now be able to talk to each other without a problem.

Enjoy!