Using WatiN to automate Sitecore

As a tester, one aspect of my job that takes up a lot of my time is regression testing. This becomes even more of a problem when we have to upgrade Sitecore to a new version. This can often take days, so a way to automate Sitecore to complete basic tasks such as editing, saving and publishing content would save me a lot of time.

I had been using Selenium to automate all of my tests and most of the time I get exactly what I need from it, however when I tried to use Selenium to automate Sitecore I hit a brick wall.

The Selenium IDE uses CSS ID and class selectors to find elements on the web page. Sitecore generates different IDs for elements of its desktop every time you launch it so the Selenium selectors do not work as expected when you use the Selenium IDE recording functionality. This was really frustrating because I felt that automating Sitecore could save me a lot of time and effort, so after some googling I found out about WatiN, a powerful testing tool which enables you to automate your tests with Internet Explorer and Firefox using .Net.

After a bit research I finally found out how to write a test using the WatiN library to automate Sitecore. The test involves editing a content item, publishing it and then checking that the changes have been made on the front end.

To create your own WatiN test scripts you will need the following:

WatiN (http://watin.org/) – Inspired by Watir development of WatiN started in December 2005 to make a similar kind of Web Application Testing possible for the .Net languages. Since then WatiN has grown into an easy to use, feature rich and stable framework.

There is a handy video on the WatiN website which will give you a step by step guide to setting up and creating your first WatiN test script.

NuGet (http://nuget.org) – NuGet is a Visual Studio extension that makes it easy to install and update third-party libraries and tools in Visual Studio.

NUnit (http://www.nunit.org/) – NUnit is a unit-testing framework for all .Net languages. Initially ported from JUnit, the current production release, version 2.6, is the seventh major release of this xUnit based unit testing tool for Microsoft .NET. It is written entirely in C# and has been completely redesigned to take advantage of many .NET language features, for example custom attributes and other reflection related capabilities. NUnit brings xUnit to all .NET languages.

Here is an example of how to create a test script that will automate the Sitecore login process.

The first thing that we need to do is create a new project in Visual Studio and add the WatiN and NUnit packages using NuGet. We then need to add a reference to the WatiN.Core and the NUnit.Framework namespaces.

Now we have our test setup let’s write some code to demonstrate the API’s usage.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WatiN.Core;
using NUnit.Framework;

namespace Test
{
    //These attributes mark the class as a NUnit test fixture
    [TestFixture]
    [RequiresSTA]

    public class EditContent
    {
        [Test]
        public void Sitecore()
        {   
            //Create a new instance of IE and navigates to a specified URL
            using (var browser = new IE("http://www.test.com/sitecore"))
            {
                //Finds the username field and types the text specified

                browser.TextField(Find.ByName("Login$UserName")).TypeText("username");

                //Finds the password field and types the text specified

                browser.TextField(Find.ByName("Login$Password")).TypeText("password");

                //Finds and clicks the options link

                browser.Link(Find.ByText("Options")).Click();

                //Finds and clicks the desktop button

                browser.Button(Find.ById("AdvancedDesktop")).Click();

                //Finds and clicks the login buton

                browser.Button(Find.ByName("Login$Login")).Click();
            }
        }
    }
}

The example code above opens an Internet Explorer instance and points it to your specified URL, it then uses the method ”Find.ByName” to search for the text field with the name ‘Login$UserName”. Finally we add the “TypeText” command so that it types the text “username”. It does the same again for the “Login$Password” field but this time types the text “password”.

We then find the desktop and login buttons using “Find.ById” and then we perform a “Click()” event. At this point if you try to run this test using NUnit, the test will fail. This is because the file Interop.SHDocVw.dll is not found, we need to make a change to the properties of the refence in the solution so that this file is created. To do this find and select the reference, then set ‘Embed Interop Types’ to ‘False’.

If you want more information on this please visit: http://stackoverflow.com/questions/5433990/watin-system-io-filenotfoundexception-interop-shdocvw

Now we can build the solution and run our test in NUnit successfully!

iPad Touch Events: an Idiot’s Guide

This blog is the result of a surprisingly useful tracer bullet we undertook looking into introducing iPad support and Touch functionality.  An initial comment would be to note how easy I found implementing this functionality and responding to the Touch events.

The investigation was carried out using two main approaches.

The first approach was to implement the functionality in the most basic possible way, ensuring maximum flexibility.

This involved hooking into the core JavaScript functions.  This is done the same way as hooking up to a JavaScript click method, so the html to create a coloured div that responds to click events is simply:

<div id="box" style="height:225px;width:225px;background:red;position:absolute;" ontouchmove="touchMove(event)" ontouchstart="touchStart(event)"></div>

Then, all that’s needed is to declare the two functions in JavaScript functions as shown in the following example:

function touchStart( e ) {
var box = document.getElementById("box");
box.style.background = "green";
e.preventDefault();
return false;
}

function touchMove( e ) {
var targetEvent =  e.touches.item(0);
var box = document.getElementById("box");
box.style.background = "yellow";
box.style.left = targetEvent.clientX + "px";
box.style.top= targetEvent.clientY + "px";
e.preventDefault();
return false;
}

Note that the e.preventDefault(); command prevents the event from propagating to the browser and e.g. causing page scrolling.

A more comprehensive example that this was based upon can be found at: http://gregmurray.org/ipad/touch-events.html

So, I don’t know about you guys but I think that was a lot easier than I expected!  I know the above example is only very basic, but this just starts to show how you can easily start to interact with Touch events, and hence start  to provide a better iPad user experience – and you shouldn’t be afraid to do so!

The second approach I took was to adapt the previous approach so as to use an external library.  I looked at several libraries available online and chose Hammer.js – the reasons I selected this library were that it is completely standalone, implements a wide variety of functionality by default and is simple to use.

The final example I built used Hammer and JQuery.  The HTML needed for this touchable box has only slightly changed slightly:

<div id="box" style="left:200px;height:225px;width:225px;background:red;position:absolute;" ></div>

Note that we are not connecting the ontouchmove and ontouchstart events ourselves – instead the Hammer code will do this for us.

The JavaScript required to attach to these events is simply as follows:

var el = document.getElementById('box');
var hammer = new Hammer(el, {
drag_min_distance: 50,
drag_horizontal: true,
drag_vertical: true,
transform: true,
scale_treshold: 0.1,
hold: true,
hold_timeout: 400,
swipe: true,
swipe_time: 200, // ms
swipe_min_distance: 20, // pixels
prevent_default: true
});

As you can see, Hammer provides many variables in this declaration, allowing us to simply determine things such as swipe time and how long the object must be held before the hold event is triggered.  This is a very easy-to-use way to tweak the functionality as required.

We then attach simple handlers to the events when they are called:

hammer.onhold = function (ev) {
var width = $('#box').width();
width = width * (0.85);
$('#box').width(width);
var height = $('#box').height();
height = height * (0.85);
$('#box').height(height);
};

In the full example (see the bottom of this article), this results in a red box on the screen that can be dragged, swiped, tapped, held and scaled using two fingers – all of which are implemented in the same manner as above!

So, in summary, hopefully you have all gained a basic introduction to how we can support Touch events with the iPad – and hopefully you were also surprised at the ease with which this can be achieved!

Full Example Code:

<html>
<head>
<script src=”http://code.jquery.com/jquery-1.7.2.min.js”></script&gt;
<script src=”http://eightmedia.github.com/hammer.js/hammer.js”></script&gt;

<script type=”text/javascript”>

$(document).ready(function () {

var logDetailsDiv = document.getElementById(“logDetails”);

var el = document.getElementById(‘box’);

var hammer = new Hammer(el, {
drag_min_distance: 50,
drag_horizontal: true,
drag_vertical: true,
transform: true,
scale_treshold: 0.1,
hold: true,
hold_timeout: 400,
swipe: true,
swipe_time: 200, // ms
swipe_min_distance: 20, // pixels
prevent_default: true
});

var drag = {};
var container_size = el.getBoundingClientRect();
var drag_el;
var drag_el_size = {};
var drag_timer;
var drag_pos = {};
var zIndex = 10;

var touchOffsetx = 0;
var touchOffsety = 0;

hammer.ontap = function (ev) {
var touches = ev.originalEvent.touches || [ev.originalEvent];
for (var t = 0; t < ev.touches.length; t++) {
var el = touches[t].target;
if (el.className.search(‘box’) > -1) {
el.style.zIndex = zIndex++;
}
}
};

hammer.ondrag = function (ev) {
drag = [];
var touches = ev.originalEvent.touches || [ev.originalEvent];
for (var t = 0; t < touches.length; t++) {
var el = touches[t].target;

if (el && el.className.search(‘box’) > -1) {
var offsetwidth = $(‘#box’).width();
var offsetheight = $(‘#box’).width();
log(offsetwidth + “:” + offsetheight)
drag.push({
el: el,
size: { width: offsetwidth, height: offsetheight },
pos: ev.touches[t]
});
}
}
};

setInterval(watchDrag, 10);

function watchDrag() {
if (!drag.length) {
return;
}

for (var d = 0; d < drag.length; d++) {
var left = drag[d].pos.x – (drag[d].size.width / 2) – touchOffsetx;
var top = drag[d].pos.y – (drag[d].size.height / 2);

if (left < 0) {
left = 0;
}
if (top < 0) {
top = 0;
}

drag[d].el.style.left = left + ‘px’;
drag[d].el.style.top = top + ‘px’;
}
}

hammer.onswipe = function (ev) {
if (ev.direction == ‘right’) {
log(“swipeRight” + $(‘#cont’).width() + ‘px’);
$(‘#box’).attr(“Left”, $(‘#cont’).width() + ‘px’);
}
if (ev.direction == ‘left’) {
log(“swipeLeft” + $(‘#cont’).width() + ‘px’);
$(‘#box’).attr(“Left”, ‘0’ + ‘px’);
}

}
hammer.ondoubletap = function (ev) {
var width = $(‘#box’).width();
log(“touchOffset =” + width);

width = width * (1.2);
$(‘#box’).width(width);

var height = $(‘#box’).height();
log(“touchOffset =” + width);

height = height * (1.2);
$(‘#box’).height(height);
};

hammer.onhold = function (ev) {
var width = $(‘#box’).width();
log(“touchOffset =” + width);

width = width * (0.85);
$(‘#box’).width(width);

var height = $(‘#box’).height();
log(“touchOffset =” + width);

height = height * (0.85);
$(‘#box’).height(height);

};

hammer.ontransformstart = function (ev) { };
var oldScale = 0.0;
hammer.ontransform = function (ev) {

var width = $(‘#box’).width();
var height = $(‘#box’).height();
var scale = 1 + ev.scale – oldScale;
log(“scale =” + scale);

width = width * (scale);
$(‘#box’).width(width);

height = height * (scale);
$(‘#box’).height(height);
oldScale = ev.scale;
};

hammer.ontransformend = function (ev) {

};
});

function log(text) {
document.getElementById(“log”).innerHTML = text;
}
</script>
</head>
<body>
<div id=”cont” style=”height:250px”>
<div id=”log”> log me</div>
<div id=”logDetails”></div>
<div id=”box” style=”left:200px;height:225px;width:225px;background:red;position:absolute;” ></div>
</div>
</body>
</html>

What Do ScrumMasters Do Again?

In my time working with agile, I’ve heard ScrumMasters described as many things:

  • ScrumMasters are secretaries to the development team, doing the things the developers don’t have time for
  • ScrumMasters are Project Managers
  • ScrumMasters act between the team and the Product Owner
  • ScrumMasters are an arbiter
  • ScrumMasters are responsible for chasing customers
To be fair, I think the title ‘ScrumMaster’ itself is a little misleading. The word ‘Master’ conjures up images of authority and expertise that I don’t believe are a fair representation of the role. The amount of times I’ve heard ScrumMasters represented as ‘waste’ in agile in scary. Hearing comments such as ‘I would never pay somebody to do this role full time’ just makes me wonder what experiences people have had with ScrumMasters and how much these companies invest in continuous improvement which I hope you’d agree is essential for longevity of any business.

“A system cannot understand itself. The transformation requires a view from outside.”–W. Edwards Deming, The New EconomicsA system cannot understand itself. The transformation requires a view from outside.

How do you know you’ve got a sticky-note on your back marked ‘Kick-me’ without someone pointing it out (or stumbling across a mirror)? Interactions between team members are similar, and according to Deming’s statement, cannot be understood from inside the team.

A ScrumMaster is like a football coach, standing on the side-lines during the game. A football coach doesn’t play a position but they are constantly looking at how the team are interacting with each other. They know if the defensive line is being held too high and how the team aren’t working together to achieve a common vision. After the game the coach helps the team look at their performance for strengths and weaknesses, they’ll identify actions for potential changes and implement them incrementally to avoid boiling frog syndrome. Although a football team may be able to play 1 or 2 games without a coach, other teams may eventually overtake them in ability and effectiveness. Does this sound familiar?

Describing what a ScrumMaster does every day is hard to describe because every team is different. As I’ve changed from team to team over the years my activities and levels of involvement vary depending on what constraintis holding the team back from increasing their effectiveness. This may be anything, from the obvious impediments like the team not chasing feedback from a Product Owner/Customer, right through to the team feeling demotivated when senior management impose a well-meant but miscalculated delivery of the latest process initiative. In Agile Development, we’ve moved away from requirements documents to value people over processes. We know the value of a powerful vision over detailed requirements when developing software. Why should our jobs be any different? I can’t remember the last time a job description actually described what I did every day. Instead of a Job Description why not buy into a Job Vision? A powerful and ambitious statement that inspires us to do our job well?

As ScrumMaster I am striving to make myself redundant.

Yes, I really mean it. In my opinion, a ScrumMaster or Agile Coach for a team should be striving to put themselves out of work. You’ll never get there of course but that doesn’t make it any less important to try. We should be identifying constraints and impediments to the team becoming self-organising (not necessarily self-directing – future blog post on this one perhaps?). This doesn’t mean chasing the Product Owner/Customer or writing code for them when the team are busy, why are they so busy? Why couldn’t they write the code themselves? As soon as you put yourself in the system you lose the ability to understand the system.

So what’s the Vision for your role in the company? I’d be especially interested to hear ideas on vision statements for Product Owners.

Keeping in lane – optimising Stories for “swim-speed”

It’s always interesting to find something your team has independently adopted as good practice is also more widely discussed as best practice.

This happened recently to me, in the Scrum team I work with.  For those not familiar with Scrum, it’s a framework used in Agile development, and more info can be found  on Scrum Alliance‘s site.  We’ve been doing Scrum for about 9 months or so now, although the teams were reorganised about 3 months ago.

In an attempt to improve the effectiveness of our teams, we’ve recently been looking at implementing elements of Kanban on top of the Scrum base, to try and apply more Lean thinking to the underlying Agile process.  This approach is sometimes now referred to as “ScrumBan”.

During the retrospective meetings at the end of each sprint, we had been reviewing the relative size of stories we were doing in our sprints, as we suspected there was some correlation between the distribution of story sizes and the overall success of the sprint.

To give some background, our team has a velocity of about 55-60 story points in a 2-week sprint.  In line with generally accepted Scrum practice, we give our Stories a point value, representing the overall complexity and “size” of the work involved, on a Fibonacci-based scale.

Working from this, we noted over the course of our first few sprints with the new team that we seemed to be more effective when dealing with stories with a “mid-range” value of 3, 5, 8 or 13 points (corresponding to around 5-25% of a sprint for us), rather than the smaller ones (0.5, 1 or 2 points) or the larger ones (21 points and above).

Thinking about this, it did make a certain amount of sense.

The overhead and background work needed to get a story set up and progress it doesn’t seem to vary linearly, so a 1-pointer will not take 20% of the overhead of a 5-pointer – it will generally take more.  This means that there can be higher overheads per point of value actually delivered when dealing with stories at the very small end.

Conversely, we were also finding that once stories got above a 21 (which represents about a third of a sprint’s value in one story), there seemed to be a significantly higher risk of the story not being fully defined and there being areas of uncertainty that were openings for scope creep, which sometimes caused issues with getting the work accepted by the client as Done.

Both of these issues were given even more importance by the implementation of “swim-lanes”, which are a way of limiting the amount of Work-In-Progress (or WIP), a key objective of Kanban.   An explicit policy was introduced for the company whereby a team should never have more than 3 “lanes” of WIP on our scrum board open at once (with no more than one Story in each), and any breach of this required approval from the Directors.

A Story could not be removed from a swim-lane until the client had accepted it as Done, so the focus came down very firmly on getting early UAT feedback and turning this around to get the lane clear for another Story.

This thinking is informed by the Theory of Constraints and the idea that you can improve the flow of work through the team by limiting the WIP and focusing on getting Stories through to being accepted as Done individually as quickly as possible, rather than doing a lot of work on several stories at once, and there then being one or more bottlenecks to getting these approved.

The way I personally visualise this is as “swim-speed” – how quickly a Story can be “swum” through the lane and out the far end.

If the Story was too small, then it would potentially spend more time waiting whilst the client reviewed it and signed it off than it actually took to do, blocking the swim-lane for that additional length of time.  If there were a sizable number of these small stories, that presented a risk of whether they would all make it all the way through to being accepted as Done within the sprint.

If the Story was too large, then it would potentially be occupying the lane for the majority of the sprint before the client was able to finish providing UAT feedback, which again risked it not making it all the way to accepted as Done within the sprint.

In both these cases, the swim-speed had been reduced.

Given this, we made an unofficial team policy to try and keep Stories within that range of 3-13 points – anything smaller than that, we would look to see if it could reasonably be combined with other Stories in a logical way that still provided value to the client; anything larger we would look to see if it could be broken down, again whilst keeping to stories that delivered real value.

In this way, we were looking to maximise the value of stories that could be accepted as Done by the client within a sprint, and hence the all-important cashflow for the company!

Lo and behold, having decided on this off our own bat, I did a bit of reading around online (particularly looking into other teams that are practising “ScrumBan” and other Scrum/Kanban hybrids) and discovered that plenty of other people have had the same “brainwave” – although often quoting different ranges of points, Scrum being what it is and these being totally team-dependent.

Now we just have to hope that it’s a case of great minds thinking alike, rather than fools seldom differing…