Tuesday, March 31, 2009

Round a double to x significant figures after decimal point

Microsoft .Net frame work doesn't have any number in function to a double to a significant digits. This can be achievable by the following:

Scale your number scale so that so that your first significant digit is right after the decimal point, round (or truncate), then scale back. The following code should do the trick:

static double RoundToSignificantDigits(this double d, int digits)
{
double scale = Math.Pow(10, Math.Floor(Math.Log10(d)) + 1);
return scale * Math.Round(d / scale, digits);
}

To Truncate:

static double TruncateToSignificantDigits(this double d, int digits)
{
double scale = Math.Pow(10, Math.Floor(Math.Log10(d)) + 1 - digits);
return scale * Math.Truncate(d / scale);
}

Sunday, March 22, 2009

Windows Services with Timer Objects C#.NET 2008

Timer events can be very useful when you need to run a routine on a regular basis. In .NET, creating Windows services with the timer object is very easy to do. In this article we are going to create a timer which writes text to a file on regular intervals, and we’ll employ a Windows Service to control the timer.
Timer Object Concept

From the timer object (in the System.Timers namespace) we use the following properties and events:

Elapsed: Everything in the timer evolves around the Elapsed event, which is the event that is raised every interval. You create code to be executed and call that code in the Elapsed event.

Interval: Used to set the time between raising the Elapsed event.

AutoReset: Ensures that the timer will be reset after every Elapse event. Therefore, if you would only like to execute the Elapse event once, you set the AutoReset property to false. When you omit the AutoReset property, it is assumed to be true.

Enabled: Used to tell the timer to start or stop.

Windows Service Concept

A Windows Service has very defined start and stop events. Starting and stopping timers using these events is very organized and is run as a background process. If you define the Windows Service to start automatically, you need not worry about starting the timer again; this background process will keep on running until you stop the service and disable it. Since this is a background process, there will not be a user interface to dialog with the user. In case of exceptions, messages would be written to the Windows Event Log.

Every Windows Service must have a Main method where you issue a Run command, which loads the service into the Services Control Manager. However, if you use Visual Studio.NET, all this code will be generated automatically.

Windows Services with Timer Objects C#.NET - Setting up the Project

1. Create a C# Windows Service project and name it TimerSrv.


The project will come with a class, Service1.cs. Double-click Service1.cs in the project explorer to reveal the properties. Name the service TimerSrv and in the ServiceName field also fill in TimerSrv.



2. Next we are going to add an installer to the project. Right Click on the design page and click Add Installer. A design screen will be added to the project with 2 controls: serviceProcessInstaller1 and ServiceInstaller1.

3. Click the serviceProcessInstaller1 control and, in the properties dialog, change the account to LocalSystem.


4. In the serviceInstaller control, change the start type to Automatic, and give it a nice display name, like Timer Service.



Windows Services with Timer Objects C#.NET - Adding Code
(Page 3 of 5 )

1. Switch to the code view of the Service1.cs file.

Note: we renamed the service to TimerSrv, so we need to change the Run command in the Main method of this class. Find the following line:

ServicesToRun = new System.ServiceProcess.ServiceBase[]
{ new Service1() };

Now, change this to the following:

ServicesToRun = new System.ServiceProcess.ServiceBase[]
{ new TimerSrv() };

2. In the top of the file add use statements:

Use System.IO;
// we need this to write to the file
use System.Timers;
//we need this to create the timer.

3. Somewhere in the class, add a new private void AddToFile() method. We will use this to write text to a file.

private void AddToFile(string contents)
{

//set up a filestream
FileStream fs = new
FileStream(@”c:\timerserv.txt”,

FileMode.OpenOrCreate, FileAccess.Write);

//set up a streamwriter for adding text

StreamWriter sw = new StreamWriter(fs);

//find the end of the underlying filestream

sw.BaseStream.Seek(0, SeekOrigin.End);

//add the text
sw.WriteLine(contents);
//add the text to the underlying filestream

sw.Flush();
//close the writer
sw.Close();
}

Now we can start coding the events.

Windows Services with Timer Objects C#.NET - Coding the Windows Service Start and Stop Event Handlers

In the Service1.cs file we only need to write code for the OnStart and OnStop events. In the OnStart() void method, add the following line of code:

AddToFile(“Starting Service”);

Now, in the OnStop event add the following line:

AddToFile(“Stopping Service”);

This is all we need to do to have a working Windows Service. Next we’ll add the timer to the service.

Creating the Timer

Just under the class definition in the Service1.cs file, add the following global variables:

//Initialize the timer
Timer timer = new Timer();

The idea behind the timer is that it sleeps for a specified period (defined by the interval method), and then executes the code specified with the elapsed event. We need to define a method that will be executed when the Elapsed event occurs, and we do this with the following code, which adds a line of text to the file:

Private void OnElapsedTime(object source, ElapsedEventArgs e)
{
AddToFile(“ Another entry”);
}

Now we can setup the timer.

In the OnStart method we add code to reflect what to do when the elapsed event is raised. In this case, we need to invoke the OnElapsedTime method we defined above, set the interval (in milliseconds) the project needs to sleep, and enable the timer so it raises the Elapsed event.

The complete OnStart method looks like this:

protected override void OnStart(string[] args)

{

//add line to the file
AddToFile(“starting service”);

//ad 1: handle Elapsed event
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

//ad 2: set interval to 1 minute (= 60,000 milliseconds)

timer.Interval = 60000;

//ad 3: enabling the timer
timer.Enabled = true;
}

The OnStop event also needs to be modified. A mere timer.Enabled = false suffices. The complete OnStop method looks like this:

protected override void OnStop()
{
timer.Enabled = false;
AddToFile(“stopping service”);
}


That’s all the coding we need to do!

After doing all the above your service1.cs will looks like bellow:
///////////////////
///////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.IO;

namespace TimerSrv
{
public partial class TimerSrv : ServiceBase
{
//Initialize the timer
Timer timer = new Timer();

public TimerSrv()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
AddToFile("Starting Service");

//ad 1: handle Elapsed event
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

//ad 2: set interval to 1 minute (= 60,000 milliseconds)

timer.Interval = 60000;

//ad 3: enabling the timer
timer.Enabled = true;

}

protected override void OnStop()
{
timer.Enabled = false;
AddToFile("Stopping Service");
}

private void OnElapsedTime(object source, ElapsedEventArgs e)
{
AddToFile(" Another entry");
}

private void AddToFile(string contents)
{

//set up a filestream
FileStream fs = new FileStream(@"c:\timerserv.txt",FileMode.OpenOrCreate, FileAccess.Write);

//set up a streamwriter for adding text

StreamWriter sw = new StreamWriter(fs);

//find the end of the underlying filestream

sw.BaseStream.Seek(0, SeekOrigin.End);

//add the text
sw.WriteLine(contents);
//add the text to the underlying filestream

sw.Flush();
//close the writer
sw.Close();
}

}
}
////////////////
///////////////

Windows Services with Timer Objects C#.NET - Building and Installing the Service

Build the executable: Build->Build Solution

In order to install the service we need to use the installutil console command, which comes with the .NET Framework.

Open a command line window by going to Start -> Programs -> Microsoft Visual Studio.Net -> Visual Studio.Net Tools -> Visual Studio.Net Command Prompt, and change to the directory where the executable is located. Enter the following command:

installutil TimerServ.exe
// Whatever you defined the executable
// name to be




Now the service is installed. To start and stop the service, go to Control Panel -> Administrative Tools -> Services. Right click the service and select Start.

Now the service is started, and you will be able to see entries in the log file we defined in the code.

Wednesday, March 18, 2009

Fitnesse Acceptance Testing Framework

Introduction:

FitNesse is a Wiki built on top of Fit framework which is used for automating Acceptance test cases. FitNesse enables customers, testers and programmers to learn what their software should do, and to automatically compare that to what it actually does do. In very simple terms, it compares customer's expectations to actual results. This tool is built on top of FIT framework. Fit and FitNesse, both believe that great software requires collaboration and communication. These tools enhance the collaboration between customer, testers and programmers by providing a single platform for communication. FitNesse can be seen as a software testing tool, a WIKI or a web server.

Why do we need FitNesse?
Unit testing is a well-known practice that helps developers validate the functionality of components and identify bugs early when they are easy to fix. By leveraging frameworks like JUnit, Nnit tests are very easy to write and execute, and therefore provide very rapid feedback about the status of the system. The problem with unit tests by themselves is that they test such fine-grained pieces of functionality that it is easy to end up with gaps in coverage for the system overall. And, because unit tests are strictly a developer tool, any miscommunication or misunderstanding about requirements cannot be caught, and the business users have no visibility into these tests.
Acceptance tests, on the other hand, test coarse-grained services within the application, which complements the coverage gained by unit tests. The same people who write acceptance tests also generally write and maintain the requirements; therefore, the tests usually reflect the requirements more accurately. Despite the benefits of writing and running acceptance tests early, this type of testing is rarely done until late in the project's life cycle. Why? The problem with these tests is that they are generally very expensive to write and automate. The people defining the acceptance criteria, the customers or business analysts as their proxies, usually aren't programmers and don't have the skills or time necessary to write effective automated test scripts.

The Framework for Integrated Test (Fit) and FitNesse address these issues. Fit is an open source acceptance testing framework, and FitNesse is a wiki-based test execution engine that allows users to write, edit, and run Fit tests over the web. Together these tools enable developers and users to express acceptance tests in a tabular format and execute them from a simple web interface. Using Fit and FitNesse, teams can reduce drastically the effort required to create automated acceptance tests, all while increasing the accessibility of the tests and their results.


Advantages of FitNesse:

Ÿ Advantage of FIT and FitNesse for acceptance testing is that they use an approach that enables users and user representatives to write acceptance tests via a spreadsheet-like approach. This feature decouples the creation of acceptance test suites from dependence on developers.
Ÿ FitNesse tests can give us feature feedback very early in the project. In fact, the tests ought to be written first, so programmers can code to the tests.
Ÿ FitNesse tests can give us feature feedback very frequently. They can be run manually or automatically by anyone with web access to the server, as frequently as required. Every week, every day, every hour in a crunch.
Ÿ FitNesse tests are deterministic: they either run green or red. If they run green for a given requirement, either the requirement is done and we move on to others, or the set of tests is not yet exactly right, in which case we refine them. Either way, we are successively refining the system in an orderly way. With each new test running green, we can all see the system getting better, more valuable, closer to what we need.
Ÿ Test data in FitNesse is developed either by the customers or by development or quality team with the help of customer representative. Since this data is developed from the user stories and is specified in a deterministic manner, it ensures that expectation from the system is clear to everyone.
Ÿ Being based on example data, FitNesse tests exercise more paths through the business logic. When you use FitNesse, you run less risk of missing important features or functional behavior.
Ÿ Only automated acceptance testing (such as that provided by FitNesse) enables you to measure Running, Tested Features, which is a key metric for measuring software project progress and success.
Ÿ FitNesse automated acceptance testing is a natural complement to xUnit (NUnit) based unit testing. The former helps you build the right code, while the latter helps you build the code right. Consider using both tools.
Ÿ Fit and FitNesse can be used to easily create a suite of automated acceptance tests that can be shared and maintained by an entire team. The libraries provided by Fit and FitNesse are very extensible and allow to create fixtures that can execute any table as a test.
Ÿ It also enables a mixture of documentation and testing that can result in testing documents that also provide considerable insight into how systems should work.Such test suites can really help when the time comes to produce formal documentation and training materials.
Ÿ Fitnesse can be used as a tool to support the user acceptance test driven development process for agile development method such as ExtremeProgramming.Planning and feedback loops in Extreme Programming (XP) with the time frames of the multiple loops.




How it is implemented?
Tables are the crux of FitNesse. Acceptance tests in FitNesse are defined in the tabular format. This deterministic tabular format is understood by the FIT library. These tests or tables are defined in terms of input and expected output data. In order to read those tables and test the application under test with the data used in these tables Fixture code need to be write. Fixture Code is a bridge between the table and
application under test. It understands the language of table and uses this information to exercise the functionality of application.



FitNesse Test System

A FitNesse test is composed of three basic elements: the test page, the test fixture, and the execution engine. The first component, the test page, is simply a wiki page that contains one or more test tables in addition to any no executable tables or text that describe the test or requirements in more detail. When FitNesse executes a test page, the test tables are run sequentially, which means that not only can you put multiple test tables on a given page but you can also have subsequent test tables rely on the state that was set up by previous tables.

The second component, the test fixture, is a class that interprets the information provided in a table and uses it to exercise the application. The examples discussed here demonstrate using Java to write the fixture code; however, there is also a version of FitNesse included in the main distribution that runs on the .NET framework, and it would be relatively trivial to port any of these examples to C# or VB.Net.

All fixture classes ultimately extend the base Fixture class provided in the FitNesse libraries. In addition to the base Fixture class there are a number of fixture subclasses that can be used as extension points that provide additional functionality and make writing the fixtures for common types of test tables very easy. The vast majority of test fixtures that the average team must write will extend from one of these subclasses.

The execution engine is the third component that is provided by the FitNesse libraries and is completely abstracted away from the users of the tool.

Just two steps are required to automate user acceptance tests using FIT:
1. Express a test case in the form of a FIT table
2. Write the code in Java or C#, called a fixture, that bridges the test case and system under test.