Welcome to DevAuthority.Com Sign in | Join | Help

Context is often a problem when unit testing code, for example if your code utilizes HttpContext.Current this can be a real problem. There are several ways to get around this problem, I'll try and explain the approach we're currently taking, hopefully if someone else out there have a better approach they'll provide a link in comments.

Basically we wrap all the calls to HttpContext.Current in a HttpContextWrapper class, below is a very simplified example to try and get the basics across, you could extend this to include your favourite mocking framework:

 

1 /* 2 * Created by: 3 * Created: 12 February 2007 4 */ 5 6 using System; 7 using System.IO; 8 using System.Web; 9 10 namespace BlogExamples 11 { 12 public class HttpContextWrapper 13 { 14 [ThreadStatic] 15 private static HttpContext _context; 16 17 private static HttpContext Current 18 { 19 get 20 { 21 if (HttpContext.Current == null) 22 { 23 if (_context != null) 24 { 25 StringWriter writer = new StringWriter(); 26 HttpRequest request = new HttpRequest("null.html", "http://localhost/null", ""); 27 HttpResponse response = new HttpResponse(writer); 28 _context = new HttpContext(request, response); 29 } 30 } 31 else 32 { 33 return HttpContext.Current; 34 } 35 return _context; 36 37 } 38 } 39 } 40 }

This approach has one major downfall, namely that you have to use the HttpContextWrapper in your code rather than just straight calls to HttpContext, this means you will need to control the code your trying to test, which for the most part is the case, however as with everything in life, there are exceptions.

How would you solve this problem ? Im quite interested in seeing how other people apporach this as it is a fairly common scenario, leave a comment if you have any suggestions.

I saw my friend Josh over at www.thejoyofcode.com had a couple of great tips on how to shorten your code a bit, but is shorter always better?

First let me just say I think the examples Josh posted are fine, they don't take away from the readability of the code, however consider other techniques like conditional expressions.

Say we wanted to do something like this:  

/* * Created by: Nicolai Sorensen * Created: 12 February 2007 */ namespace BlogExamples { public class ShorterCode { public void ConditionalBLOCKED EXPRESSION { int x = 5; int y = 10; int z = 0; if (x > 3 && y < 10) { z = x*y; } else { z = x - y; } //or you could just write it like so z = x > 3 && y < 10 ? x*y : x - y; } } }

Which is shorter and while I understand it fine, someone whos not familiar with conditional expressions, might be scratching their head for a few minutes.

I've come across this a couple of times so I felt It was probably a good idea to post this technique here so I can remember it for the next time and who knows, maybe someone else will get some use out of it.

Basically I have a generic list and I want to find a specific item, the new generic collections allow you to specify a Predicate which can handle this for you. At first I just passed in a private static method on the class as the predicate, but this only really works if you're filtering a list using specific hardcoded criteria, you could just add new members to the class and use those from your predicate method, but it tends to get ugly quite fast on more complex scenarios.

Instead just define your predicate function on a separate internal class and setup the criteria's as properties on that class and then pass that instead, like so:

 

using System; using System.Collections.Generic; namespace BlogExamples { public class GenericListPredicate { public OperatingSystem FindOperatingSystem(PlatformID platform, string servicePack) { //Populate the list with some data.... List<OperatingSystem> operatingSystems = new List<OperatingSystem>(); //Setup your predicate class OperatingSystemFindPredicate findPredicate = new OperatingSystemFindPredicate(); findPredicate.PlatFormID = platform; findPredicate.ServicePack = servicePack; //Pass the predicate class to the find method. return operatingSystems.Find(new Predicate<OperatingSystem>(findPredicate.FindOperatingSystem)); } } internal class OperatingSystemFindPredicate { private PlatformID _platformID; public PlatformID PlatFormID { get { return _platformID; } set { _platformID = value; } } private string _servicePack; public string ServicePack { get { return _servicePack; } set { _servicePack = value; } } public bool FindOperatingSystem(OperatingSystem operatingSystem) { return operatingSystem.Platform == _platformID && operatingSystem.ServicePack == _servicePack; } } }

Its not big secret that I'm a keen user of Resharper from JetBrains, a while back one of my collegues challenged the idea that Resharper was worth the cost if you already had VS2005. Since VS2005 now supports refactoring. So instead of getting into an hour long discussion boring everyone on the joys of resharpering, I figured I would post a comparison here.

 

Aside from the basic 7 refactoring patterns supported by VS2005:

  • Rename
  • Extract method
  • Encapulate Field
  • Extract Interface
  • Promote Local variable to Parameter
  • Reorder Parameters
  • Remove Parameters

Resharper supports:

  • Move
    • Move Type
    • Move Type to Outer Scope
    • Move Static Member
  • Copy Type
  • Change Signature
  • Extract
    • Extract Superclass
    • Extract Class from Parameters
  • Introduce
    • Introduce Variable
    • Introduce Field
    • Introduce Parameter
  • Inline Variable
  • Convert
    • Convert Method to Property
    • Convert Property to Method(s)
    • Convert Interface to Abstract Class
    • Convert Abstract Class to Interface
  • Pull Members Up
  • Push Members Down
  • Make Method Static
  • Make Method Non-static
  • Safe Delete
  • Replace Constructor with Factory Method
  • Use Base Type Where Possible

I could go through every single pattern here and the reasons why they are really cool, but Im gonna try and contrain myself and simply try and make the point that when it comes to refactoring, theres plenty more to this practice than the mere basics that are offered in VS2005.

Instead if you want to know more about each pattern, I suggest you read www.refactoring.com

Navigation

But as I said, resharper is now so much more than a refactoring tool, so lets get onto how it improves visual studio's navigation.

Resharpers navigation functionality can be divided into 3 categories :

  1. Go to ...
    Resharper allows you to quickly find any type, file, decleration, base, inheritor, usage, next / previous method , next/ previous error and last edit location.
    If your like me and like as much screen real-estate focused on the actual code as possible, using these, I find that I never really have to go scanning through my solution explorer, hence I save both time finding the peice of code I want and I can see my code without scrolling the screen.
  2. Find usage
    Defenaitly one of my favorite features, it allows you to find anywhere in the code where a namespace, type, member or method is used.
  3. Navigation Views
    These are basically different views of your files and types. I especially like the File Structure Window, which allows you to see all your methods and members within a file and re orginize them by dragging and dropping, so you can for examle make sure you have your private members on top, then your constructor, then your properties, then public methods, then private methods.
    You can also surround with region tags as well as access the refactor this method.

Build Files Support

Resharper also adds full code completion and refactoring support for msbuild and nant build scripts. This means that you can now rename your targets and it will automatically update the targets that depend on those targets.

Some of the navigation features make it in there as well, such as the find usages for properties and targets. Goto decleration also works for targets :)

Unit Testing Support

But it dosn't end there, unit testing is also supported by resharper. You can run nunit tests directly from within the UI and unlike TestDriven.NET resharper gives you a nice UI with red and green dots rather than just  the failures logged to the task bar as errors.

Another nice feature, is resharper integration with dotTrace profiler. It will allow you to  run your unit tests and profile your application while doing so, this is incredibly useful if your investigating performance issues or your just curious whether one approach is better than another.

But..

Resharper isnt for everyone, namely those poor souls that for one reason or another insist on using VB.NET. Resharper currently does not support VB.NET (why would you encourage people to use VB anyway ?)

But, JetBrains is currently adding readonly VB support to Resharper 2.5 so atleast if your stuck having to read VB code (ohh the horror), you wont have to use ctrl + f every 2 seconds.

Anyhows, I can only recommend resharper. It will easily repay its cost in a matter of weeks.

Disclaimer : I dont really hate VB.NET, nor do I hate VB.NET Developers, infact I myself am from a VB background...but we all have to grow up sometime ;)

So as I've officially been doing my first consulting gig for 6 months now, I thought now would be a good time to reflect and write a bit about the tips I've picked up so far.

 

Travelling Tips

Get used to travelling, in the past 3 months I've taken more trains, stayed in more hotels and taken more flights than the first 25 years of my life combined. However travelling isnt all bad, it takes a bit of getting used to but here's a few pointers that might make your journey's and hotel stay's more enjoyable.

  • Get one of them fancy luggage bags with wheels, it just plain sucks having to carry your luggage around with you (especially if you have alot of changeovers), altho dont make the same mistake I did and get a cheap 15£ one from your local CO-OP that does a distinct kangaroo impression as your strolling along. Spend a little and get a nice one, that bag will be a big part of your life for the forseable future.
  • Order your tickets online and about a month in advance, for my travel I would have to pay 120£ for a return ticket on stardard class. Instead when ordering online and ordering single tickets rather than returns, I get my trips on FIRST class as low as 24£. Your saving your employer money and travelling is now ....tolerable.
  • Find one taxi firm and stick with em, make sure you open an account with them and have them bill your credit card weekly or monthly. When you take 2 cabs every day this can SERIOUSLY cut down on the amount of reciepts you have to send of to your finance department to claim expenses back. They will also be much more flexible when you fancy that 5 min extra in bed in the morning :p

Accomondation

Find a nice hotel and then stick with it. Setup a corporate account so you can afford the nice executive rooms on your expense budget, having a nice hotel room can make alot of difference.

 

Expenses

Its a bit unreal how much cash you spend being a consultant. If your employeer like mine wants you to fork out for it first and then claim it back, your in for a bit of a shock when you first start out. Here's a few tips that could help you avoid sleeping under a park bench for a night or two while waiting for your expenses to come through.

  • Shop around for a decent credit card. Its worth getting one that will give you cash back etc, since your going to be spending all that money you might as well take advantage of it. 
    However I'm probably not the right person to ask about which ones, since I have a HORRIBLE history with credit cards (I always tend to get the 27% APR ones for some reason) but by far the best creditcard I've had so far is my American Express Corporate card, the only real downside to it is that its not as widely accepted as mastercard or visa over here, but their customer service and flexability more than makes up for this.
  • Do expenses as often as your company allows it, always travel with envolopes and postage stamps so you can do them when your bored in your hotel room.

Online Access

Currently the client I work for dont allow us to connect our laptops to the network at their site and while the hotel does have wifi access, its usually rather limited and have download restrictions, not to mention being very expensive (3£ an hour!!!). However, 3G data cards have started coming out in 1.8 mbit versions, these are absolutly ideal for travellers. Here in the UK you can get a vodaphone one for 50£ and an unlimited connection for 45£ a month.

 

Dealing with clients

This really isnt as easy as it sounds, when at client sites, you have to deal with a number of different people in different roles and to be honest, half the time the client has no idea what they want or different people have different ideas about what it is they want. I've included a few pointers below that might save you some headache.

  • Do your homework, make sure you understand the people you deal with directly and what role they fill within the company. Get up to speed on any company terminoligy as fast as you can, big companies seem to LOVE acronyms, learn them all.
  • Be friendly and approachable at all times, even when your feeling grumpy that you've spent the last  3 hours trying to explain a really simple concept for the n'th time. Its all worth it when their boss notice it and publicly state how impressed he was with the way you handled the situation.  Yes we have to deliver on promises, but it does us no good if we piss off the client while rushing through out own work.
  • Critizise ideas, not people. Its really easy to label a client as dumb or stupid, afterall they wouldnt have called you in to fix their problems in the first place if they were able to handle it themselves. While I appreciate that sometimes, you really do have to deal with stupid people, your client is much more likely to fire you than fire old man john who's been with the company for 35 years. Critizising people also breeds a "them vs us" culture if your working at a client site, which to be honst really isnt a productive environment. So instead of critizising people critisize their ideas, question them, provide alternatives and educate them.

A while ago I attended the Essential Unified Process launch at the Museum of Natural History in London, below is a fairly confusing write-up of my notes and thoughts on the matter. Please keep in mind that I am by no means and expert on this subject.

So what's it all about?

I guess you could describe the Essential Unified Process as a Framework in which you can evolve your own process. The process is defined by what’s called a process Kernel, the Kernel consists of different Practices, these practices are all “self validating” which means that in theory your able to mix and match them with your existing practices.

At the launch event Ivar Jacobsen listed 4 key innovations in EssUP that he believed gave them the right to brand this a “Next Generation Process”.

· Practice Separation

· Practice Eco-System

· Practice User Experience

· Practice Smartness

Practice Separation
This is the idea that all practices are autonomic and that they can both be used separately and implemented separately over time. This makes the process easier to adopt since you can re-use the practices you already have in place. You just define them as an EssUP practice and stick them in the process kernel.

Practice Eco-System
IJC (Ivar Jacobsen Consulting) suspects that we will see hundreds of custom practices rather than just the 8 core practices they have put in. You will see sub practices for architecture such as SOA Architecture. You will see other requirement practices such as user stores and straight up use-cases.

The idea of a practice Eco-System is that IJC provides a central repository for storing the definition for these practices. This is somewhat similar to patternshare.org. This will encourage re-use and evolution of the practices.

Practice User Experience

This appears to relate to two things. Firstly, the adoption of cards as the primary media for process definitions, artifacts, practices etc. forcing people to be concise and to the point rather than writing 500 page books about it. Ivar gave quite a nod to Ward Cunningham and Kent Beck for showing them the way on this, saying their only regret was it took them 20 years to realize they had it right all along.

Secondly are their electronic systems for managing EssUP, the team system template and their own system called project Genie. First, they said that support in team system was going to be limited to the process guidance html files. This, in my opinion, makes it as good as useless.

The demo of project genie was very unimpressive, I would go as far as to say that based on what they showed, I would rather track everything with pen and paper as much as I hate the idea.

So in summary, cards = great, their electronic alternatives = lame.

Process Smartness
This very much relates to the concept of intelligent agents. The idea is that you essentially have computer programs advising you and auto generating skeleton deliverables based on what actions your currently trying to do. I guess its a bit like intellisense for the whole of the lifecycle rather than just when your cutting your code. All in all a good idea, however I cant say I was impressed with the product they showed, in fact I cant even remember the name of it.

So what’s the Essential thing about ?
Currently EssUP consist of 8 core practices which is what’s considered “Essential”.

· Team Essentials

· Process Essentials

· Iterative Essentials

· Architecture Essentials

· Component Essentials

· Use-Case Essentials

· Model Essentials

· Product Essentials.

Sadly we weren’t told a whole lot about the individual practices, we did however get a few of the cards to play with. I’ll try and see if I can’t get a hold of a few digital copies of these and post them here.

Each practice is defined by the following elements:

· Things to produce (artifacts)

· Things to do (activities)

· Key Competencies

You might notice that testing is noticeably absent from the listed essential practices, this is because testing in EssUP cuts across all practices, you simply cannot have a practice without it validating itself. This supposedly is the key to achieving Practice Separation.

We also briefly touched on the games, which

The three games

· Development Game

· Planning Game

· Process Improvement Game

Not much were said about them other than the Planning Game didn’t really see many (if any) changes from its implementation in XP and Scrum.

For now the best (and only) place to start is the Essential Unified Process – Introduction whitepaper which can be found here : http://www.ivarjacobson.com/html/content/publication_1_1.html

Hope this didn't confuse everyone too much, as I stated above, this was mainly to try and give myself an overview of what was discussed at the launch event. If I'm wrong about any of the stuff above, by all means post a comment and let me know.

All the best

Nicolai

Ok its been a while since I've last posted here. But I do have a really good excuse this time.

Ok maybe its not that great, but as of march this year I quit my job at RE-Media and started my new role as a Consultant.

Now obviously that shouldn't really stop me from blogging and technically it hasn't. It did however mean I've been blogging on another site, namely my current employers internal blog.

But that's all going to change now, I've decided to try and maintain both blogs for the time being. What this means is I will be transferring some of my more tech specific entries from my internal company blog to here.

So stay tuned..

Ok, so I'm stuck doing some work with Visual Studio 2003 (why cant they just support 1.1 in 2005 ?) and a few weeks back I had to add some client script code to the page from a web control.

Easy, I’ll just use Page.RegisterClientScriptBlock, right ? Wrong! much to my surprise Visual Studio’s Intellisense doesn't trigger, so I must be doing something wrong?

To make a long story short, I got around it by rendering the script tags as HtmlGenericControls and that worked…however today I had to do a change to the control that involved registering a startup script that would run as soon as the page did.

Now, I checked MSDN and sure enough, there is a Page.RegisterStartupScript method I can use. But as before…it didn't show up using intellisense. So now I was starting to get a bit pissed and got the idea to fiddle around with my options.

And sure enough Tools —> Options —> Text Editor —> C#  and un-check hide advanced members and everything works.

Now WHY on earth did I have to go through that.

At least it seems like Visual Studio 2005 have it unchecked by default.

 

Recently I’ve had the opportunity to trial VersionOne for the company I work for, while the company chose to go another way (they aren't quite ready to go 100% agile just yet) I was very impressed with the system. so I thought it deserved a mention here.

Being a big fan and practitioner of Extreme Programming, I off course tried their XP version.

At first I was a bit overwhelmed by the sheer amount of functionality, but VersionOne were kind enough to set up a web conference with some of their developers talking us through the system. In fact the VersionOne team have been extremely helpful through the entire process , I wish more companies supplied that level of customer care.

But back to the system, the part I was particularly impressed with was the planning phase. VersionOne doesn’t just rely on you moving user stories around by selecting their iterations through list boxes etc…no they’ve got proper drag and drop support, I cannot stress how nice this is for planning meetings, being able to just move user stories, iterations and releases around as I see fit.

Now, I think I’ve raved about this product enough, you can test it out for yourself at www.versionone.com, if you are serious about using it, I would recommend arranging for them to give you a tour of the product.

Life has been rather busy lately, so there's not been much time to blog.

As most of you have probably seen, Visual Studio 2005 and SQL Server 2005 are now available on MSDN downloads. Download speeds are still horrendous (I'm getting 25kb/sec) but at least I should have it to play with in the weekend.

Speaking of the new releases, I’ll be at the Launch Tour event at the ICC in Birmingham, UK. So if anyone wants to hook up so we don't look like sad lonely geeks, shoot me an email.

So what have I been up to lately ? Well, I've finished my .NET Skype API, it was quite an educational experience learning how to use windows messenging from a .NET API using pinvoke etc.

Currently I'm working on a new calendar web control…using the same ideas that Microsoft uses in their datelense technology demo. It should be quite sweet once its finished, again I'm learning A LOT of dhtml / java-script and Atlas playing with this.

Some of my other pet projects include a new visual designer for the new site-map xml files in visual studio. Some of the projects I work on are rather large (hundreds of pages) and having a nice site-map is invaluable.

Anyways, hopefully I will be able to share some more details of my new projects with you soon, I cant wait to show the new calendar control off.

 

I’ve just installed 2 new applications for all my blogging needs, Blogjet and FeedDemon, I have previously used sauce reader and was quite happy with it, but it had a few flaws in terms of sorting using dates etc.

Im quite impressed with both applications so far, they work nicely together and both were painless to set up and configure. Im sure I will find something I dont like at some point, but for now its my new favorite combo :)

Hi all,

First of all, thanks alot to Dave Balzer for providing me with this blog here, I originally had my blog over at dotnetjunkies but due to the technical problems over there, I pretty much gave it up. Alot of things have been happening to me lately tho, I've recently assumed a new role at my workplace as a .NET Architect and so far its been quite a ride.

At the moment I'm working on the new architecture for our flagship product, a CRM thats used alot in the inward investment sector over here, we will have the actual implementation of the project outsourced to one of our partners in India and I'm going down there on Sunday to present the project.

The project will be developed on the .NET 2.0 platform and we will be using the TDD approach. Now the question is, what unit testing framework would you use for .NET 2.0. I've narrowed it down to the following candidates so far.

Visual Studio 2005 Unit Testing : I like the new visual studio, but Im not sure we will be forking out for Team System  and as far as I understand its not included in the Pro version ?

NUint : This is what I started out using, it works nicely and it does the job, but it lacks a few of the nicer features of the competition. Im also not sure how it will work with .NET 2.0 ?

MBUnit : What I ended up using in the end for all my 1.1 projects, I loved the integration with Testdriven.NET and it gave me all the features I needed, again Im not sure how it will work with .NET 2.0 ?

Zanebug : Gotta love the GUI. But dosnt look like it will support 2.0 untill october ?

Now, normally I would just try them out for myself and see if I could get them working or not, but as Im pressed for time at the moment, I figured I would seek the advice of my fellow developers since there surely must be someone out there thatsbeen faced with the same descision ?