Profiling .NET Code with StopWatch

One of the new diagnostics tools introduced in .NET 2.0 is the System.Diagnostics.StopWatch class. It lets you time your code with simplest profiling code possible! And I use this class very regularly during my development/desting. I use it especially when calling out to external APIs such as web services, remoting, etc. Here is an example:
using System;
using System.Diagnostics;
... ...
StopWatch sw = new StopWatch();
sw.Start();
// Code calling web service, database, etc.
sw.Stop();
Console.WriteLine ("Elapsed time (in ms): " + sw.ElapsedMilliseconds);

As a side note, StopWatch is a friendly wrapper .NET class for the QueryPerformanceCounter Win32 API. StopWatch.Start() invokes this API and stores the tick value and StopWatch.Stop() does it again and the difference in the ticks is exposed as the elapsed duration. what this means is that you can use the Win32 API directly in .NET 1.x applications to profile your code.

Switch Internet Explorer to Offline Mode

I saw a newsgroup post today asking about programmatically (.NET way) switching Internet Explorer to offline mode (checking IE’s File | Work Offline menu item). I posted a small C# code that accomplishes this to the newsgroup. Thought would make a blog entry on it for everyone’s benefit.

NOTE: This code was tested on Windows XP SP2 and Vista RC1.

[DllImport ("wininet.dll")]
private extern static bool InternetSetOption (int hInternet,
int dwOption, ref INTERNET_CONNECTED_INFO lpBuffer, int dwBufferLength); [StructLayout (LayoutKind.Sequential)] struct INTERNET_CONNECTED_INFO { public int dwConnectedState; public int dwFlags; }; private readonly int INTERNET_STATE_DISCONNECTED = 16; private readonly int INTERNET_STATE_CONNECTED = 1; private readonly int ISO_FORCE_DISCONNECTED= 1; private readonly int INTERNET_OPTION_CONNECTED_STATE = 50; void SetIEConnectionMode (bool offline) { INTERNET_CONNECTED_INFO ici = new INTERNET_CONNECTED_INFO (); if (offline) { ici.dwConnectedState = INTERNET_STATE_DISCONNECTED; ici.dwFlags = ISO_FORCE_DISCONNECTED; } else { ici.dwConnectedState = INTERNET_STATE_CONNECTED; } InternetSetOption (0, INTERNET_OPTION_CONNECTED_STATE, ref ici, Marshal.SizeOf (ici)); }
To swich back to online mode, set INTERNET_STATE_CONNECTED to dwConnectedState member of the structure. dwFlags is not required in this case.

Getting Windows Process Owner Name

The System.Diagnostics.Process class gives almost every data about a running process. But, the most-wanted information it doesn’t give about a process is the process owner name. And I ran across a situation recently that asked for the same thing – here is the code I used. However, this method will not work for certain processes because the current user will most likely not have permissions to query about those processes (but it was sufficient for my needs).

[DllImport ("advapi32.dll", SetLastError = true)]
static extern bool OpenProcessToken (IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);

[DllImport ("kernel32.dll", SetLastError = true)]
[return: MarshalAs (UnmanagedType.Bool)]
static extern bool CloseHandle (IntPtr hObject); 

static uint TOKEN_QUERY = 0x0008;

foreach (Process p in Process.GetProcesses ())
{
  ph = IntPtr.Zero;
  try
  {
    OpenProcessToken (p.Handle, TOKEN_QUERY, out ph);
    WindowsIdentity wi = new WindowsIdentity(ph);
    Console.WriteLine (p.ProcessName + " owned by " + wi.Name);
  }
  catch (Exception xcp)
  {
    Console.WriteLine (p.ProcessName + ": " + xcp.Message);
  }
  finally
  {
    if (ph != IntPtr.Zero) {CloseHandle (ph);}
  }
}