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.

Wednesday, 16 January 2008

How to create unit tests for Windows services in Visual Studio 2005

I needed to write couple of unit tests but it also included to write unit tests for Windows service.

First of all I wanted to create NUnit tests but I do not know how to do that and what should I test. Solution for this was use Visual Studion integrated tests. I added Test project to my solution and after that I used wizard for creating new test classes. Visual Studio created skeletons for testing methods and I only implemented what was necesary to check in the test itself. One thing which is quite cool is that VS generated tests also for private methods. This can be accomplished by using reflection.

Other problem was after I implemented tests and wanted to run them. All tests failed. It was because there was no windows service configuration file. It was necessary to copy app.config from other project to the place where is project test dll (name has to be project_test.dll.config). I set project copy app.config everytime the test project is successfully built (as post build event).

Wednesday, 2 January 2008

How to use Gmail as you SMTP server

Detail description can be found on the following link How to use Gmail as your SMTP server.