Monday, 27 April 2009

How to uninstall MSSQL server 2008

I have had into some troubles with my computer and I wanted to reinstall MSSQL server 2008 but I was not able to find out how to unintall it. Here is the command which will do it for you:
"c:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Release\x86\SetupARP.exe" /x86

Tuesday, 21 April 2009

Tortoise SVN 1.6.0 not compatibile with AnkhSVN 2.0

Recently I was forced to reinstall Windows and also Visual Studio 2008. I wanted to intall latest versions of TortoiseSVN and AnkhSVN 2.0 but the versions are not compatible.

There are two possible solutions:
1. download and install daily build of AnkhSVN 2.0 (stack overflow),
2. if you for some reason do not want to install daily build then there is possible to install TortoiseSVN 1.5.9 which is compatible with stable version of AnkhSVN.

Monday, 20 April 2009

Mocking in C#

During my last assignement I worked on refactoring of our project and part of that was to refactor our test. I find out that we use mocks in there. To be more specific we used Rhino Mocks. I was curious how it works, what are advantages/disadvantages and wanted to learn more.

What are mocks (mock objects)

Mock objects are special testing objects which allow developers to test in easier way the behavior of real objects. Classical unit test tests rather the state of objects then their behavior. This is probably the biggest difference between those two test approaches.

For better understanding of differences, there are used and a bit modified examples from Martin Fowler's article. The examples are adapted for .NET environment.

For testing there are used following classes:
IWarehouse interface
public interface IWarehouse
{
int GetInvetory(string name);
void Add(string name, int count);
bool HasInventory(string name, int count);
void Remove(string name, int count);
}
WarehouseImpl class
public class WarehouseImpl : IWarehouse
{
private Dictionary store = new Dictionary();

public int GetInvetory(string name)
{
if (store.ContainsKey(name))
return store[name];
else
return 0;
}

public void Add(string name, int count)
{
if (store.ContainsKey(name))
store[name] = store[name] + count;
else
store.Add(name, count);
}

public bool HasInventory(string name, int count)
{
if (store.ContainsKey(name))
if (store[name] >= count)
return true;
else
return false;
else
return false;
}

public void Remove(string name, int count)
{
store[name] = store[name] - count;
}
}
Order class
public class Order
{
private string name;
private int count;
private bool isFilled;

public bool IsFilled { get { return isFilled; } }

public Order(string n, int c)
{
name = n;
count = c;
isFilled = false;
}

public void Fill(IWarehouse warehouse)
{
if (warehouse.HasInventory(name, count))
{
warehouse.Remove(name, count);
isFilled = true;
}
}
}

Classical (NUnit) test example

This is example how usually NUnit tests are written and as you can see there we do some actions (order.Fill()) and check that results are as expected.

[TestFixture]
public class NUnitTest
{
private IWarehouse warehouse;
private const string TALISKER = "Talisker";
private const string HIGHLAND_PARK = "Highland Park";

[SetUp]
public void Setup()
{
warehouse = new WarehouseImpl();
warehouse.Add(TALISKER, 50);
warehouse.Add(HIGHLAND_PARK, 25);
}

[Test]
public void TestOrderIsFilledIfEnoughInWarehouse()
{
Order order = new Order(TALISKER, 50);
order.Fill(warehouse);
Assert.IsTrue(order.IsFilled);
Assert.AreEqual(0, warehouse.GetInvetory(TALISKER));
}

[Test]
public void testOrderDoesNotRemoveIfNotEnough()
{
Order order = new Order(TALISKER, 51);
order.Fill(warehouse);
Assert.IsFalse(order.IsFilled);
Assert.AreEqual(50, warehouse.GetInvetory(TALISKER));
}
}

Rhino Mock example

This code shows how to use Rhino.Mocks to test behavior is as expected.

[TestFixture]
public class RhinoTest
{
private const String TALISKER = "Talisker";

[Test]
public void TestFillingRemovesInventoryIfInStock()
{
Order order = new Order(TALISKER, 50);
MockRepository mock = new MockRepository();
IWarehouse warehouseMock = mock.CreateMock();

Expect.Call(warehouseMock.HasInventory(TALISKER, 50)).Return(true).Repeat.Once();
Expect.Call(delegate { warehouseMock.Remove(TALISKER, 50); }).Repeat.Once();

mock.ReplayAll();
order.Fill(warehouseMock);
mock.VerifyAll();
Assert.IsTrue(order.IsFilled);
}

public void TestFillingDoesNotRemoveIfNotEnoughInStock()
{
Order order = new Order(TALISKER, 51);

MockRepository mock = new MockRepository();
IWarehouse warehouseMock = mock.CreateMock();

Expect.Call(warehouseMock.HasInventory(TALISKER, 51)).Return(false).Repeat.Once();

mock.ReplayAll();
order.Fill(warehouseMock);
mock.VerifyAll();
Assert.IsFalse(order.IsFilled);
}
}

Differences between NUnit test and test which uses Rhino.Mocks

As you can see in the examples above, mocking can help you to test easier in cases you do not want your unit tests e.g. access database, send real emails etc. You only test the behavioural of the classes you are insterested in.

References

Mocks aren't stubs by Martin Fowler
NUnit
Rhino.Mocks

Saturday, 7 February 2009

How to remove diacritics in C#

Sometimes it is useful to work with the text without diacritics. How to do it properly in .NET is well described in the following post How to remove diacritics (written in Czech).

Friday, 11 April 2008

Big number calculations in C#

I needed to work with very big numbers (numbers which exceeded int or long types). Imagine for example you need to calculate factorial of 100 or even 1000 or more. How can you do this? The algorithm of factorial calculation is easy but how can you store the result? You can think out solution where you can store your big numbers like strings but solution like this can be difficult to implement. You have to implement own math operation on the string etc.

The other solution is to use F# math library. Because F# is also .NET language you can use it from other .NET languages e.g. C#. So what you need to start? What is necessary to install? F# downloads are available on Microsoft research pages. After you download F# libraries you need to install it and simply create new project in Visual Studio and the FSharp.Core.dll library as reference.

Example calculation of factorial using F# classes:

using System;
using Microsoft.FSharp.Math;

namespace BigNumberCSharp
{
public class TestFactorial
{
public void CalculateFactorial(int x)
{
BigInt factorial = BigIntModule.factorial(BigInt.FromInt32(x));
Console.WriteLine(factorial);
}
}
}


Here is the result for factorial of 100.

Wednesday, 6 February 2008

Windows Management Instrumentation code examples

I would like to describe what Windows Management Instrumentation (WMI) is and what it can be used for. There are included examples on all covered areas.

What is WMI?

WMI is Windows management technology, it allows to manage and control local or remote computers. WMI allows you do a lot by modeling objects such as disks, processes, or other objects found in Windows systems. For each system object there is created WMI class e.g. Win32_NetworkAdapter, Win32_Directory or Win32_Process. You can use WMI classes from .NET applications and even from visual basic script.

What can WMI be used for?

  • Query for data from a WMI class (e.g. get list of processes on local or remote computer)

  • Execute a method (e.g. start a new process or or share a directory from your harddisk)

  • Receive an event (e.g. wait until specified process started )

Query for data from a WMI class

Following section contains examples of how to query for some interesting data from WMI classes.
How you can get MAC addresses of you network adapters
  ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_NetworkAdapter");

foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("Win32_NetworkAdapter instance");
Console.WriteLine("Caption: {0}", queryObj["Caption"]);
Console.WriteLine("MACAddress: {0}", queryObj["MACAddress"]);
}
How to get current CPU usage
  ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor");

foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("Win32_PerfFormattedData_PerfOS_Processor instance");
Console.WriteLine("PercentProcessorTime: {0}", queryObj["PercentProcessorTime"]);
}

Execute a method

This section shows in examples how methods of WMI classes can be used.
How can you logoff from you computer?
  ManagementClass classInstance = new ManagementClass("Win32_OperatingSystem");
// Obtain in-parameters for the method
ManagementBaseObject inParams = classInstance.GetMethodParameters("Win32Shutdown");

// Add the input parameters.
inParams["Flags"] = 0; // logoff
inParams["Reserved"] = 0;

// Execute the method and obtain the return values.
ManagementBaseObject outParams = null;
foreach (ManagementObject mo in classInstance.GetInstances())
outParams = mo.InvokeMethod("Win32Shutdown", inParams, null);

Recieve na event

This section shows how to wait until WMI event happen.
How to wait until specific process started
  WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName = 'notepad.exe'");

ManagementEventWatcher watcher = new ManagementEventWatcher(query);
Console.WriteLine("Waiting for an event...");

ManagementBaseObject eventObj = watcher.WaitForNextEvent();

Console.WriteLine("{0} event occurred.", eventObj["__CLASS"]);
foreach (PropertyData pd in eventObj.Properties)
{
Console.WriteLine(pd.Name + " " + pd.Value);
}

// Cancel the event subscription
watcher.Stop();

WMI on remote computer

This section will show you how you can do WMI queries on remote computer.
How to get list of drives on remote computer
  ConnectionOptions connection = new ConnectionOptions();
connection.Username = "username";
connection.Password = "password";
connection.Authority = "ntlmdomain:domain_name";

ManagementScope scope = new ManagementScope("\\\\10.98.8.52\\root\\CIMV2", connection);
scope.Connect();

ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_DiskDrive");

ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("Name: {0}", queryObj["Name"]);
}

Useful links

  • WMICodeCreator - very useful for beginners. It can generate WMI code for C#, Visual Basic and Visual Basic Script.

Thursday, 24 January 2008

Visual Studio 2008 - Project Creation Failed

I have recently installed Visual Studio 2008 QFE - it is useful if you want to look into .Net framework sources. You can find details on ScottGu's blog. But after that when I needed to create new project in VS2008 I always get Project creation failed error. What to do when it happens is described here.