Archive for the ‘Web development’ Category

Unit tests: expose bugs and spend less time fixing them!

Hands-on introduction to creating unit tests that cover your application’s business logic

An extra effort and more code: two major drawbacks that often discourage developers from writing unit tests. They seem hard to write and little to contribute or at least that is what I first experienced when I started using them. And although I still don’t consider myself to be an expert in the field of test-driven development, I have not given up and can say: unit tests are a real time saver. Rather than walking through a long list of benefits, let’s write some code and see for ourselves..

Before you can write a unit test you obviously need to have a chunk of code or some business logic that requires testing. The following example shows you how to add a unit test after writing your initial code and how you can alter the unit test before writing any additional code (e.g. in a second iteration).

Important to note: although the example is created in C# with the Visual Studio unit-testing framework, the principles can be applied to any given library in your preferred programming language.

The full source code of the example can be downloaded here.

Example: Testing the shopping basket of a web shop
Let’s say you are working on a web shop and you are asked to implement some logic that calculates the total price of a shopping basket. You’ve created the shopping basket and price calculation logic in the business tier:

public class WebshopFacade
{
public void AddProductToBasket(ShoppingBasket basket,
Product product)
{
basket.Add(product);
UpdateBasketPrice(basket);
}

public void UpdateBasketPrice(ShoppingBasket basket)
{
double totalPrice = 0;
foreach (ShoppingBasketItem item in basket.GetItems())
{
totalPrice += item.Product.UnitPrice * item.Amount;
}
basket.TotalPrice = totalPrice;
}
}

The code is pretty straightforward: the web shop can create a basket but to add an item it needs to call the façade which will than update the basket’s total price. Now, before creating a web page (and I know you want to) it’s a good practice to set up a unit test. Why? If there are any coding errors in the shopping basket or its price calculation, you want to expose these bugs right now, and not by experiencing strange issues when creating the web page which will eventually have you debug the web application. The unit test may already save you from losing precious time, and surely you want to hold on to it for future testing when the price calculation logic becomes more complicated.

Test method 1: Initial price of the basket
Ok, let’s start out with a basic yet crucial test: you want to make sure that when the web shop creates a basket, the initial total price is zero. You may laugh, but your customers won’t if this is not the case!

[TestClass]
public class ShoppingBasketTest
{
public ShoppingBasketTest()
{
}

[TestMethod]
public void TotalPriceOfEmptyBasketMustBeZero()
{
ShoppingBasket basket = new ShoppingBasket();
Assert.AreEqual(0, basket.TotalPrice, "Expected total price to be zero for empty basket");
}
}

That wasn’t so hard, was it? Running all tests in Visual Studio takes only a few seconds and for me it resulted in a test run completed, results: 1/1 passed. Sweet, an instant confidence boost!

Test method 2: Adding products to the basket
Let’s move on and add a test method that ensures products can be added to the basket:

[TestMethod]
public void ProductsCanBeAddedToTheBasket()
{
ShoppingBasket basket = new ShoppingBasket();
WebshopFacade facade = new WebshopFacade();
MockFactory mocks = new MockFactory();

for (int i = 0; i < 50; i++)
{
facade.AddProductToBasket(basket, mocks.CreateProduct());
}

int totalUnits = 0;
foreach (ShoppingBasketItem item in basket.GetItems())
{
totalUnits += item.Amount;
}

Assert.AreEqual(50, totalUnits, "Expected 50 units in the basket after adding 50 random products");
}

In this test 50 random products are added to the basket, and then the test does a recount by looping through the basket’s items. As the test method cannot create products directly (nor can the web shop for that matter) a mock factory is used to create mock objects, in this case products.

And believe it or not, when I first ran the test it failed because of a bug in the basket. In Visual Studio you can add a breakpoint inside any test method and instantly debug the test method, so I was able to resolve the issue in no time!

Test method 3: Price calculation
Finally, you can add a test method which ensures the total price is calculated correctly:

[TestMethod]
public void BasketTotalPriceIsCalculatedCorrectly()
{
ShoppingBasket basket = new ShoppingBasket();
WebshopFacade facade = new WebshopFacade();
MockFactory mocks = new MockFactory();

double expectedTotal = 0;
for (int i = 0; i < 50; i++)
{
var product = mocks.CreateProduct();
facade.AddProductToBasket(basket, mocks.CreateProduct());
expectedTotal += product.UnitPrice;
}

Assert.AreEqual(Math.Round(expectedTotal, 2),  Math.Round(basket.TotalPrice, 2), "Expected total price does not match basket's total price");
}

The code is mostly copied and pasted from the previous method, but here the price calculation is somewhat mimicked. It may seem obvious that this test will pass, but when you make further progress in developing the basket, this test method can fail, and it will expose any bugs that were introduced by your (or someone else’s) changes.

Another way of testing this logic would be to create some specific products, and to hard code the expected total price. This could include special situations that don’t frequently occur but are part of the business logic, e.g. discounts for certain products, discounts for a specific amount of products, etc.

Creating a unit test before writing any code
The unit test now covers the basic functionality of the basket and you might decide to start a second iteration in which you introduce removal of products or discount logic. In either case you can initiate this iteration by creating new unit tests or updating the existing one allowing you to focus on the requirements before writing any code.

You can start by changing the “interface” of the façade, by adding a method for product removal:

public void RemoveFromBasket(ShoppingBasket basket,
Product product)
{
throw new NotImplementedException();
}

And now you can add new test methods that validate the product removal logic:

[TestMethod]
public void ProductsCanBeRemovedFromTheBasket()
{
ShoppingBasket basket = new ShoppingBasket();
WebshopFacade facade = new WebshopFacade();
MockFactory mocks = new MockFactory();

var addedProducts = new List
();
for (int i = 0; i < 50; i++)
{
var product = mocks.CreateProduct();
facade.AddProductToBasket(basket, product);
addedProducts.Add(product);
}

for (int i = 0; i < 25; i++)
{
var remove = addedProducts[i];
facade.RemoveFromBasket(basket, remove);
addedProducts.Remove(remove);
}

int totalUnits = 0;
foreach (ShoppingBasketItem item in basket.GetItems())
{
totalUnits += item.Amount;
}

Assert.AreEqual(25, totalUnits, "Expected the basket to have 25 remaining units after removal");
}
[TestMethod]
[ExpectedException(typeof(ShoppingBasketException), "Expected shopping basket exception to be thrown")]
public void ProductMustExistInBasketOnRemoval()
{
ShoppingBasket basket = new ShoppingBasket();
WebshopFacade facade = new WebshopFacade();
MockFactory mocks = new MockFactory();

facade.RemoveFromBasket(basket, mocks.CreateProduct());
}

Obviously the unit test will fail if you run it before you have written the actual implementation, but for sure you will gain a great deal of insight in how to set up any interfaces, how objects should behave or interact, how exceptions are thrown, etc.

Try it out yourself!
A demo, including the example’s full source code can be downloaded here. You can run the tests in Visual Studio by pressing CTRL-R A or through the menu as shown in the screenshot below. If you are new to unit testing and can use a little practice, I strongly recommend that you try and write the code for product removal, and see if you can make the failing unit test pass again.

Final considerations
• Any unit tests that you create are there to stay and the more complex a module becomes the more often you will find that bugs are exposed when the module is changed or re-factored, simply by rerunning the tests
• By creating advanced unit tests you are to mimic and validate every possible in- and output of a certain module, allowing you to immediately recognize and debug the most specific / exotic situations when a test fails
• Unit tests may seem like a lot of code to write, but most of the time you are just writing the consuming code that has to be implemented anyway
• Unit tests offer great insight in how a module behaves or is to be used. Developers that are not familiar with the code can walk through the tests as it were code documentation

Hope this helps!

Why Umbraco suits us

It has only been a couple of months since we first started using Umbraco, an open-source CMS built on top of the .NET platform, and a lot of my colleagues will agree when I say that we have grown extremely fond of it. Why, you ask? Well, let me explain a few things.

Finding the right CMS is a challenge

Finding a CMS that suits your needs – not to mention fully embracing one – is not an easy task. It is hard to get your hands on a descent comparison and research is very time consuming as you really need to get your hands dirty. If you are somewhat wary and cautious about using a CMS, you are right, it is to be a tool that assists you in creating and maintaining websites, and it should never dictate the way you handle things as you probably already have a methodology or framework in place. And that is exactly what we have found in Umbraco: a reliable, user-friendly and extensible platform which drastically reduces development time and really fits into our projects.

Umbraco is easy, extensible and reduces development time

After completing several projects with Umbraco, we are very pleased with the results and would like to emphasize the following:

  • Umbraco is easy to learn. Within days you are able to grasp its concept and developers will be writing custom XSLT for dynamic content such as a news pages, FAQ’s, ..
  • As Umbraco is based on ASP.NET, most developers will be very familiar with the environment and configuration settings which eases development and deployment
  • Umbraco has an active community: http://our.umbraco.org/
  • A project can be implemented without writing a single line of .NET code. You may have to write some XSLT or install a package, but you will save a considerable amount of development time nonetheless
  • Umbraco is extensible in many ways, from writing custom XSLT and .NET user controls to installing packages and integrating its API or event-driven model.

Most importantly, its extensibility allows us to choose which parts of an application we wish to implement using Umbraco while we are still able to implement the parts we don’t see fit in the exact same way we would implemented these in other situations.

Completed projects

Although we still have several projects in the pipeline, we would already like to share some of the projects that have been fully implemented using Umbraco:

Plans for the future

We plan to do much more with Umbraco, and the first thing we want to do now is tweak our development environment and make Umbraco integration even easier:

  • Add an abstraction layer to our framework that will abstract the Umbraco API integration and provides a set of global helper classes for Umbraco
  • Create a template solution for Visual Studio that contains a pre-configured Umbraco install and includes our framework projects
  • Moving the template solution to Microsoft’s Web Platform Installer, allowing our developers to install the latest version of the template in no time. See also: http://bit.ly/aj2Uwm

As you can see, many of us have become strong believers and if you are considering using Umbraco as your CMS or you are a strong believer yourself we are always glad to hear from you.

An easy way to detect mobile devices

So you want to deploy a mobile version of your website? You’ve thought about what your target users would do with a mobile version, written your content, created your design and developed your Flash or HTML, CSS and Javascript (if you haven’t done that yet, read this post instead). Now for the task that can seem most daunting to new mobile web developers — detecting devices and serving the correct version of your site. How do you ensure that users with mobile phones will see the mobile version and vice versa?

The answer: WURFL. The Wireless Universal Resource File (WURFL) is an open source project which collects information about all of the different mobile devices in use. It is constantly being updated, so as long as you keep your WURFL definitions up-to-date you don’t have to worry about your detection scripts not recognising new devices. By querying a WURFL database with your visitor’s User Agent string, you can not only determine whether the device they are using is a mobile device, but whether it has a touch screen, can make phone calls, is a tablet (iPad) and more.

It is reasonably straightforward to install a Tera-WURFL service on your PHP enabled web server. If download speed is critical for your website, it would be best to install Tera-WURFL on the same web server. But if you would prefer to avoid the installation process, feel free to use our quick and easy These Days implementation of Tera-WURFL.

It can be as simple as this:

<?php
require_once ('TeraWurflRemoteClient.php');
$wurflObj = new TeraWurflRemoteClient(
    'http://wurfl.thesedays.com/webservice.php' );
$wurflObj->getCapabilitiesFromAgent(null, array('product_info'));
if ($wurflObj->getDeviceCapability("is_wireless_device")) {
    // Show mobile website
} else {
    // Show normal website
}
?>

Don’t forget to give your users a way of overriding automatic device detection. Even WURFL can get it wrong sometimes, and anyway some users prefer to view full sites on their mobile phones. The user is king!

10 tips for designing mobile websites

10 tips for web designers in 2010 – the year of the mobile.

1. Design with a fluid layout, min-width: 320px

There are two factors that make this a necessity. First, mobile device screens are so small that you really need to utilise all of the available space. Second, there are a lot of different screen resolutions out there. The only way to utilise all of the space available on different sized screens is with a fluid layout.

I have found websites with a minimum width of 320px will look good on most high-end mobile devices like the iPhone, Android and Nokia N97. Here are the screen resolutions of some of the most popular devices:

Device Screen res (height x width)
iPhone 320 x 480
iPhone 4 320 x 480 (scaled by a factor of 2)
Nokia N97 360 x 640
HTC Legend 320 x 480
LG eXpo 480 x 800


Technically, the retina display on the iPhone 4 has a screen resolution of 640 x 960 pixels but don’t worry, if you optimise your site for 320 x 480, the iPhone 4 will scale it up by a factor of two so it fits the whole screen. You will need to insert higher resolution images – but more on that in the next section!

2. Include high res images for the iPhone 4 retina display

The iPhone 4 display has four times the number of pixels as that of the original iPhone. To prevent mobile sites from looking tiny, it magnifies them by 200%. That works great on text and vector images like SVG. But its not so hot on bitmap images (or even the HTML5 canvas so it would seem). To avoid pixelation, you need to insert alternative high resolution images for the iPhone 4.

Designers should create their Photoshop documents with a width of 640 pixels. Developers should export the images at full res for iPhone 4 and 50% res for everything else.

Here’s how to use a CSS media query to insert a high resolution image for iPhone 4:

.myImage {
    height: 40px;
    width: 100px;
    -webkit-background-size: 100px 40px;
    background: url("images/myImage.jpg");
}

@media screen and (-webkit-device-pixel-ratio: 2) {
    .myImage {
        background: url("images/myImage@2x.jpg");
    }
}

The first line that might jump out at you as being a little unusual is probably -webkit-background-size: 100px 40px;. The -webkit-background-size CSS property takes two parameters: width and height. The parameters can be lengths, percentages or "auto", and can even be mixed, i.e. -webkit-background-size: 100% auto. This tells the browser to stretch the background image to a specific size.

The second interesting part is the media query @media screen and (-webkit-device-pixel-ratio: 2) {...}. This means that any styles contained within the curly braces only apply if the device has a pixel ratio of 2 (two physical pixels per measurement pixel). Inside the media query selector, we override the .myImage class, and replace the background image with the high resolution image myImage@2x.jpg.

The left half of this screenshot shows the pixelation that occurs on iPhone 4, and the right half shows how it looks when we insert with a high resolution image:

The left half of this screenshot shows the pixelation that occurs on iPhone 4, and the right half shows how it looks when we insert with a high resolution image

3. Turn off auto-scaling

Mobile devices will assume your website is optimised for desktop computers unless you tell them otherwise. Add a viewport meta tag to the head section of your HTML to set the width of your website to match the width of the display, render with a zoom level of 100% and prevent the user from zooming in/out.

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

Mobile phones will also adjust text size when the screen orientation changes unless you include a special CSS parameter:

body {
    -webkit-text-size-adjust: none;
}

4. Make clickable elements big enough for a fingertip, ≈44px²

Your mobile visitors don’t have the accuracy of a mouse – they are often using their fingertips on a touch screen. Don’t make them put their fingers through a pencil sharpener just to click your button! Apple has said that the average finger tap on an iPhone is 44px by 44px (in your high res Photoshop doc that will be 88px by 88px), so aim to make clickable areas at least that size. This doesn’t mean you have to design gigantic looking buttons. Just add some padding to your small buttons to enlarge the clickable area.

5. Don’t use hover states

Today’s touch screens can’t detect when a finger is getting close to touching, so the concept of rollovers does not apply. On the iPhone your :hover style will actually display on click and then remain on screen even after the user takes their finger away, which can be really annoying. So the rule is – don’t use :hover in your CSS or mouseover in your JavaScript.

6. Create icons for your site

Hopefully users will really love your site and add it to their home screen for easy access. Don’t ruin the mood with an ugly default icon! Add these meta tags to the head section of your HTML to define icons.

<!-- 57 x 57 Android and iPhone 3 icon -->
<link rel="apple-touch-icon" media="screen and (resolution: 163dpi)" href="icon57x57.png" />
<!-- 114 x 114 iPhone 4 icon -->
<link rel="apple-touch-icon" media="screen and (resolution: 326dpi)" href="icon57.png" />
<!-- 57 x 57 Nokia icon -->
<link rel="shortcut icon" href="icon57x57.png" />

Note: The iPhone will automatically add rounded corners and a glossy effect to your icon. If you want to turn this off, change the rel attribute to apple-touch-icon-precomposed. Thanks to Jesse Dodds for discovering how to specify a seperate high res icon for the iPhone 4 retina display.

7. Reduce load time by using CSS3 instead of images for gradients, rounded corners, shadows, etc.

Depending on the devices you are targeting, CSS3 can be an excellent option for mobile design. With old school web design techniques, a button with a gradient and rounded corners might consist of 9 separate image slices, a bunch of nasty non-semantic markup and a hefty amount of CSS. With CSS3, you can create this:

CSS3 button

With this:

.redButton {
    color: #B91440;
    font-size: 19px;
    line-height: 25px;
    padding: 10px 30px;
    border: 1px solid #FFFFFF;
    background: -webkit-gradient(linear, left top, left bottom, from(#F2F2F2), to(#FFFFFF));
    -webkit-box-shadow: 0 0 2px #E4E3E3;
    -webkit-border-radius: 5px;
}

Go here for everything you need to know about CSS3.

But be careful! While the iPhone, Android and Nokia all have good CSS3 support, the Windows Mobile 6.5 browser is built on a version of IE6 (sigh…). Define, define, define your target devices before you begin design and development.

8. Use an HTML5 doctype

Not all browsers implement HTML5 features, but they will still accept an HTML5 doctype.

<!DOCTYPE html>

Using this doctype declaration will allow you to display HTML4 elements to all browsers, and then add in additional functionality for the browsers that support HTML5.

9. Make your site operate offline

Your visitors won’t always have a fast Internet connection. If you’re designing the type of site that will have return visitors, consider leveraging the client-side storage capabilities of HTML5. It can be as simple as creating a cache manifest file that tells the browser what files it needs to cache for offline access. A more advanced option is to create an SQLite database on the client with JavaScript.

10. Include an option for your mobile visitors to view the normal website

Detection scripts can get it wrong, or a user might simply prefer not to use the mobile optimised interface. So my final tip is, always offer users a way to switch back to ‘normal mode’.

So there’s a few mobile web tips I’ve picked up over the last few months. I’d love to hear yours too in the comments!

Dependency injection with Spring.NET

Hands-on introduction on how to configure dependency injection using Spring.NET

In a previous post I’ve discussed a simple n-tier approach using a Facade and Dao pattern. The Facade provides a single access point for the business tier, and wraps a data access object that encapsulates the implementation of the persistence mechanism, separating the concerns.

I also mentioned that these objects introduce a large dependency (high coupling) as the Facade does not function without the Dao. I will now show you how this dependency can be overcome, by injecting the Dao into the Facade using the Spring.NET framework.

In the following example we will create a simple web management tool for a Zoo (inspired by amazedsaint). The tool needs to list all animals and caretakers, and allow the manager to rename animals or to assign one or more caretakers to an animal.

We start out by creating the business entities:


public class Caretaker

{

public string Name { get; set; }

public int Age { get; set; }

}

public abstract class Animal

{

public string Name { get; set; }

public IList<Caretaker> Caretakers { get; set; }

}

public class Lion : Animal { }

public class Elephant : Animal { }

We will also create a Facade which allows consumers to have a good understanding of the class library without having to worry about the exact implementation. Therefore, a good practice is to set up an interface:


public interface IZooManagement

{

IList<Animal> GetAllAnimals();

IList<Caretaker> GetAllCaretakers();

void RenameAnimal(Animal a, string newName);

void AssignCaretaker(Animal a, Caretaker c);

}

This should cover all requirements. The animals and caretakers will be stored in some kind of data store, so we’ll create a data access object (Dao) that will handle this for us. We haven’t decided on which type of data store or which ORM to use, so for now, let’s not worry about its implementation and create the interface:


public interface IZooDao

{

IList<Animal> GetAllAnimals();

IList<Caretaker> GetAllCaretakers();

void UpdateAnimal(Animal a);

}

Ok, now let’s implement the Facade. For the sake of simplicity, I will leave out any validation or error handling. Eventually, the minimal implementation will look much like this:


public class ZooManagement : IZooManagement

{

private IZooDao dao;

public virtual IZooDao Dao

{

set { dao = value; }

}

public IList<Caretaker> GetAllCaretakers()

{

return dao.GetAllCaretakers();

}

public IList<Animal> GetAllAnimals()

{

return dao.GetAllAnimals();

}

public void RenameAnimal(Animal a, string newName)

{

a.Name = newName;

dao.UpdateAnimal(a);

}

public void AssignCaretaker(Animal a, Caretaker c)

{

a.Caretakers.Add(c);

dao.UpdateAnimal(a);

}

}

The persistence mechanism has now completely been abstracted from the Facade. Also notice that the Facade does not instantiate a Dao: the property allows us to “inject” the Dao implementation and completely remove the dependency (this can also be done using a constructor parameter).

We now need to find a good way to inject the Dao into the Facade, and this is where the Spring.NET framework provides additional support, as one of its many features allows you to set up dependency injection through configuration.

Before we configure the dependency injection, let us create a “dummy” Dao, one that does not really access a data store, but holds a list of animals and caretakers internally:


public class DummyDao : IZooDao

{

private IList<Animal> animals;

private IList<Caretaker> caretakers;

public DummyDao()

{

animals = new List<Animal>();

animals.Add(new Lion() { Name = "Simba" });

caretakers = new List<Caretaker>();

caretakers.Add(new Caretaker() { Name = "Leo", Age = 25 });

}

public IList<Animal> GetAllAnimals()

{

return animals;

}

public IList<Caretaker> GetAllCaretakers()

{

return caretakers;

}

public void UpdateAnimal(Animal a)

{

throw new NotImplementedException();

}

}

If you want to use the Spring.NET framework, you will first need to add a reference to your web project. The latest version can be downloaded here. Next, you’ll need to configure Spring.NET in the Web.config:


<sectionGroup name="spring">

<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>

<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>

<sectionGroup name="child">

<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>

</sectionGroup>

</sectionGroup>

<spring>

<context name="ParentContext">

<resource uri="config://spring/objects"/>

</context>

<objects xmlns="http://www.springframework.net">

<object id="ZooDao" name="ZooDao" type="TheseDays.Business.DAL.DummyDao, TheseDays.Business">

</object>

<object id="ZooManagement" name="ZooManagement" type="TheseDays.Business.ZooManagement, TheseDays.Business">

<property name="Dao">

<ref local="ZooDao"/>

</property>

</object>

</objects>

</spring>

The first part is standard and announces the Spring.NET configuration. The second part is where the magic happens: the spring/context section is necessary for Spring to create its application context, and the spring/objects section allows you to configure the resources.

The object configuration is pretty straightforward: we tell Spring.NET we want to create an object of type ZooManagement (our Facade) and to set its property with an object we also configured, an object of type DummyDao.

Once we have implemented an actual Dao (rather than a dummy one), in order to start using it all we need to do is reconfigure its type. For example, if we would create a RealDao that also implements the IZooDao interface, and we need to pass a connection string to the constructor, the configuration of the Dao would look like this:


<object id="Dao" name="Dao" type="TheseDays.Business.DAL.RealDao, TheseDays.Business">

<constructor-arg name="connectionString">

<value>Server=.;Initial Catalog=Zoo;User=ZooUsr;Password=ZooPwd;Application</value>

</constructor-arg>

</object>

In the web application we can then access the ZooManagement Facade through the Spring’s application context. Here’s a demonstration of a small helper class I often use:


public class ApplicationContextHolder

{

private static ApplicationContextHolder instance = new ApplicationContextHolder();

public static ApplicationContextHolder Instance

{

get { return instance; }

}

private IApplicationContext applicationContext;

private IZooManagement zoo;

private ApplicationContextHolder()

{

applicationContext = ConfigurationManager.GetSection("spring/context") as IApplicationContext;

zoo = applicationContext.GetObject("ZooManagement", typeof(ZooManagement)) as IZooManagement;

}

public IApplicationContext ApplicationContext

{

get { return applicationContext; }

}

public IZooManagement Zoo

{

get { return zoo; }

}

}

Now you can access the ZooManagement in the web pages with a single line of code:


IZooManagement zoo = (ZooManagement)ApplicationContextHolder.Instance.Zoo;

Surely a nice feature when you’re building your own framework!

You can download the full source code of the example here.