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.

Wednesday, 11 July 2007

Web.config problem: The entry '' has already been added

We are going to production with our ASP.NET 2.0 application and we had a problem with configuration of logger from Micosoft Enterprise libraries. It depends on how the application is configured in IIS server. We had configured access to application from two different addresses and if we accessed from the nested one. It gives the error.

The error is described on the following url:

Enterprise Library Error: The entry 'ExceptionPolicy' has already been added

Wednesday, 20 June 2007

ASP.NET and infragistics WebDateChooser component

I needed to implement couple of javascript things into ASP.NET application. I had problem with infragistics component for dates (WebDateChooser). I needed two peaces of this component to have disabled after page load in some cases. On the page should be several radio buttons and some other components which need to be enabled only if the appropriate radio button is selected. But there were following problems with the component:
1) when the component was disabled in codebehind, I could not easily enable it in javascript if needed.
2) when I wanted to disable the component after page loaded, the component was not initialized so I could not work with it.

The solution in both cases was found, maybe it can help somebody who works with the infragistics components which sometimes do not work as you need.

1) component was disabled in codebehind in PageLoad method.

this.CurrentDateChooser.Enabled = false;

In javascript which handles click on radiobutton you need to get the following:

var currentChooser = igdrp_getComboById(currentChooserName);
currentChooser.setEnabled(true);
currentChooser.elemCal.disabled = false;

Let me explain the javascript. Method igdrp_getComboById retrieves the date chooser component by id. On the second row we need to enable the component but unfortunatelly this is not enough. Component is enabled but at least in IE 6.0 the calendar is still not enabled and you can not choose the date. This is solved by the last row. In FF 2.0 it works even without the last row of code. Maybe it is problem of the old IE.

2) The solution is quite easy. It says run the script after the page is loaded and all other initialization scripts are finished. I had to place the code at the end of master page like in the following code:

<script language="javascript">
if (typeof(checkState) != "undefined") checkState();
</script>

And now we have to define the checkState() method. This method will call the same code as the method which handles selection of radio buttons. So I added in the aspx page the following code, which calls the same method.

<script language="javascript">
function checkState() {
OnRadioClick(<%= this.SelectedRadioButton %>,
'<%= this.IntervalDropDownList.ClientID %>',
'<%= this.CurrentDateChooser.ClientID %>',
'<%= this.PreviousDateChooser.ClientID %>')
}
</script>


I prefer the solution number 1 because it is much clearer for me.