Category Archives: Development - Page 2

How to build an C# Application that can relaunch itself in Admin mode – without UAC prompt

Lets start by emphasizing that this is NOT a way to create a hack. In order for this to work you (the user) needs to be an Administrator and access to be able to launch applications in ‘Admin mode’ anyway. The first time when the application needs to set up this functionality it needs to run in Admin mode as well (for which you’ll have to be prompted by UAC). Only after this and for the future the application in ‘Non-admin’ mode can then relaunch itself in ‘Admin mode’ without showing the UAC prompt.

The ‘trick’ (not hack) is to use the built-in Windows Task scheduler that can launch applications with the ‘highest’ priority setting. Take note that this also stops you from launching the app with any command line parameters – but there are other ways an application can ‘communicate’ with itself/another instance of itself e.g. by saving its own settings before launching the second instance and the second instance reading those settings again.

So how can a (C#) application integrate this easily? My first idea was to call the Task scheduler (Schtasks.exe) manually with the required parameters to create a task of launching the app again later in admin mode. The problem part is finding out if the task already exists or not. Then I came across an article that showed how the COM+ library for the Task Scheduler can be used from .Net which make it a whole lot easier to interact.

Task Scheduler COM+ library

In your application’s references add a reference to ‘TaskScheduler 1.1 Type Library’ (Interop.TaskScheduler.dll) usually located on ‘c:\Windows\SysWow64\taskschd.dll (on 64-bit at least). Then you can add the following type of code in your project:

Code

To test if task exists or is running already:


private string myLaunchTaskName = "RunMeAsAdmin";

private bool LaunchTaskExist()
{
  try
  {
    TaskScheduler.TaskScheduler ts = new TaskScheduler.TaskScheduler();
    ts.Connect(null, null, null, null);
    if (ts.Connected)
    {
      TaskScheduler.ITaskFolder root = ts.GetFolder("\\");
      TaskScheduler.IRegisteredTask task = root.GetTask(myLaunchTaskName);
      if (task != null)
        return true;
    }
  }
  catch { }
  return false;
}
private bool TaskAlreadyRunning()
{
  try
  {
    TaskScheduler.TaskScheduler ts = new TaskScheduler.TaskScheduler();
    ts.Connect(null, null, null, null);
    if (ts.Connected)
    {
      foreach (TaskScheduler.IRunningTask td in ts.GetRunningTasks(0))
      {
        if (td.Name == myLaunchTaskName)
          return true;
      }
    }
  }
  catch { }
  return false;
}

To create the task the first time:

function CreateSelfLaunchTask()
{
  try
  {
    if (AdminModeTools.IsInAdminMode()) //Different library to test if app is in Admin mode
    {
      TaskScheduler.TaskScheduler ts = new TaskScheduler.TaskScheduler();
      ts.Connect(null, null, null, null);
      if (ts.Connected)
      {
        TaskScheduler.ITaskDefinition task = ts.NewTask(0);
        task.RegistrationInfo.Author = "Me";
        task.RegistrationInfo.Description = myLaunchTaskName;
        task.Principal.RunLevel = TaskScheduler._TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST;
        task.Settings.MultipleInstances = TaskScheduler._TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW;
        TaskScheduler.ITimeTrigger trigger = (TaskScheduler.ITimeTrigger)task.Triggers.Create(TaskScheduler._TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
        trigger.Id = "NoTime";
        trigger.StartBoundary = "2000-01-01T12:00:00";
        trigger.StartBoundary = "2000-01-01T12:00:00";
        TaskScheduler.IExecAction action = (TaskScheduler.IExecAction)task.Actions.Create(TaskScheduler._TASK_ACTION_TYPE.TASK_ACTION_EXEC);
        action.Id = "Run exe";
        action.Path = System.Reflection.Assembly.GetExecutingAssembly().Location;
        action.WorkingDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

        TaskScheduler.ITaskFolder root = ts.GetFolder("\\");
        TaskScheduler.IRegisteredTask regTask = root.RegisterTaskDefinition(
          myLaunchTaskName,
          task,
          (int)TaskScheduler._TASK_CREATION.TASK_CREATE_OR_UPDATE,
          null,
          null,
          TaskScheduler._TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN);
      }
    }
    else
    {
      MessageBox.Show("To create the task you must start this program in 'Admin' mode.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
  }
  catch(Exception ex)
  {
    MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  }
}

Then to call the task:

function void RunAppAsAdmin()
{
  try
  {
    if (LaunchTaskExist())
    {
      if (!TaskAlreadyRunning())
      {
        TaskScheduler.TaskScheduler ts = new TaskScheduler.TaskScheduler();
        ts.Connect(null, null, null, null);
        if (ts.Connected)
        {
          TaskScheduler.ITaskFolder root = ts.GetFolder("\\");
          TaskScheduler.IRegisteredTask task = root.GetTask(myLaunchTaskName);
          TaskScheduler.IRunningTask runTask = task.Run(null);
        }
      }
      else
      {
        MessageBox.Show("The task is already running!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }
    else
    {
      MessageBox.Show("The task does not exist yet!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  }
}

If for some reason you need to delete the task you can use this:

private void DeleteRunAsAdminTask()
{
    try
    {
        if (AdminModeTools.IsInAdminMode())
        {
            if (LaunchTaskExist())
            {
                TaskScheduler.TaskScheduler ts = new TaskScheduler.TaskScheduler();
                ts.Connect(null, null, null, null);
                if (ts.Connected)
                {
                    TaskScheduler.ITaskFolder root = ts.GetFolder("\\");
                    TaskScheduler.IRegisteredTask task = root.GetTask(myLaunchTaskName);
                    if (task != null)
                    {
                        root.DeleteTask(myLaunchTaskName, 0);
                    }
                }
            }
            else
            {
                MessageBox.Show("The task does not exist!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        else
        {
            MessageBox.Show("To delete the task you must start this program in 'Admin' mode.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

With all these ‘bits’ you can build an application that can launch itself in ‘Admin’ mode. Have fun kidz but not too much!

I’ve tested this on Windows Vista, 7, 2008/R2 and 8. I don’t have access to any XP machines anymore but I doubt it will work on XP (or 2003)… duhh.. Just remembered XP and 2003 does not have ‘Admin’ mode anyway so this does not apply… silly me.

Update: I now have one of my utilities actually using this code: Service Monitor

A little (versioning) pain with Powershell

First thing to mention is I’m not complaining about PowerShell itself or functionality provided with PowerShell. Rather, this is a problem with referencing it from .Net (C#) and versioning when used on another machine where the .Net App was deployed and happen to have an older version of PowerShell (PS for short).

Scenario

If you want to run PowerShell scripts from a C# program like I’m doing in QuickMon now, you have to add a reference to “System.Management.Automation.dll“. I happen to have Version 4.0 of PowerShell on the computer where the C# app is compiled. Now, this is all fun and games until you want to run the same app on another machine that only have, say Version 2.0 of PowerShell. PS 2 does have a version of System.Management.Automation.dll but somehow it is not compatible (at run time). When I compiled the same app on a computer that only has V2.0 of PowerShell and deploy that app to machines that has either PS v2.0 or v4.0 it works on all of them.

If this was C++ it would have made sense (dll versioning very strict) but this is a C# app that supposively should not care about the version of the referenced assembly (and yes, this is a .Net assembly). The methods (I) used in the dll are all the same of both versions.

I even tried generating the System.Management.Automation.dll file manually on the ‘target’ machine and copy that dll to the App’s directory (using the PS “Copy ([PSObject].Assembly.Location) C:\” command) but this gave other versioning referencing errors.

Possible solution

The solution that seems to work for now is to set the ‘Specific Version‘ property on the referenced dll in the C# project to true (making sure it points to the PS 2.0 related version – dll version 6.1.7601.17514). Interestingly enough when switching the project to ‘release’ configuration it display pointing to ‘C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll’. That tells me the PS version ‘2.0’ of that assembly is still available (on my PS 4.0 computer). As a safety precaution I also set the ‘Copy Local’ property on this referenced dll to True to have it deployed with the app.

Deploying this combination seems to work on all ‘target’ machines – I even saw it working on a computer that only has PS 1.0!

All fun and joy… as long as there’s no lawyer sitting on a loo in the bush… with an angry T-Rex nearby…

How to get the full update for VS2013

This tip applies to all editions and even previous versions (2012, 2012) of Visual Studio.

Since Microsoft has been releasing these updates e.g. VS2013.1 etc) the default behavior for these installers are to just download what is need at the time they are run. This is all good and well if you have only one machine that needs updating. What happens if you have to update a whole bunch of installs?

Luckily the VS2013.x installers support an undocumented (or not well) command line parameter ‘/layout’ that allows you to have the full update downloaded to a local folder. From there you can run the same installer without the parameter and it won’t download any additional stuff again.

Full command: VS2013.1.exe /layout

Happy downloading… only once.

ListViewEx – Auto resize selected column

What do you do when you get fed up having to write the same code over and over again? Write a base class for it… of course.

I regularly use the WinForms ListView control and often want to specify a specific column (in detail view) that must auto resize when the whole control resize. Therefore I created the following class that does all that (and more stuff) to make life easier.

public class ListViewEx : ListView
    {
        public ListViewEx()
            : base()
        {
            DoubleBuffered = true;
            View = View.Details;
            resizeTimer.Tick +=  resizeTimer_Tick;
        }

        [Description("Use one column to auto resize in detail view")]
        public bool AutoResizeColumnEnabled { get; set; }
        [Description("Column index of auto resize column")]
        public int AutoResizeColumnIndex { get; set; }
        public event MethodInvoker EnterKeyPressed;
        public event MethodInvoker DeleteKeyPressed;
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
                if (EnterKeyPressed != null)
                {
                    EnterKeyPressed();
                    e.Handled = true;
                }
            base.OnKeyPress(e);
        }
        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
                if (DeleteKeyPressed != null)
                {
                    DeleteKeyPressed();
                    e.Handled = true;
                }
            base.OnKeyDown(e);
        }
        private Timer resizeTimer = new Timer() { Interval = 100, Enabled = false };
        private void resizeTimer_Tick(object sender, EventArgs e)
        {
            resizeTimer.Enabled = false;
            try
            {
                if (AutoResizeColumnEnabled && View == System.Windows.Forms.View.Details &&
                    AutoResizeColumnIndex > -1 && this.Columns.Count > AutoResizeColumnIndex)
                {
                    int columnsWidth = 0;
                    Application.DoEvents();
                    for (int i = 0; i < this.Columns.Count; i++)
                    {
                        if (i != AutoResizeColumnIndex)
                            columnsWidth += this.Columns[i].Width;
                    }
                    this.Columns[AutoResizeColumnIndex].Width = this.ClientSize.Width - columnsWidth - 2;
                }
            }
            catch { }
        }
        protected override void OnResize(EventArgs e)
        {
            resizeTimer.Enabled = false;
            resizeTimer.Enabled = true;
            base.OnResize(e);
        }
    }

Now all you have to do is set the AutoResizeColumnEnabled property to true and specify a column index for AutoResizeColumnIndex and there you go. Easy hey?

Should I handle Exceptions or not?

I’ll start this post with a statement or answer that might seem controversial.

The answer is ‘NO’

Why? Let me explain. If your code has reached a state where an Exception has been thrown it means you have already missed something (possible) important that should have been addressed. Sure, throwing (excuse the pun) a ‘try… catch’ around every block of code is nice and all – and you should do it anyway (for other reasons) but it is no excuse for writing bad code.

More details

One reason I say these things I recently (re)discovered myself… again is that ‘Performance’ in an application can greatly be influenced by exceptions since the whole process of encountering/throwing an exception in code is a slow thing. When you have code that relies on catching an exception in order to handle an (possibly) expected condition of some variables it is a sign that you are doing it wrong… It may not be a big issue if the affected code is called only once in a blue moon but once it is in a section that is called repeatedly and is expected to perform at speed it becomes a huge issue.

Have a look at this code. It will run fine but and actually be usable but…

try
{
   SomeType tp = SomeObject.SomeVar;
}
catch // null reference exception or something expected the first time
{
  SomeObject = new SomeObjectType();
  ...
}

Now look at a better way

if (SomeObject == null)

SomeObject = new SomeObjectType();

SomeType tp = SomeObject.SomeVar;

...

This code will actually run faster and does not rely on an Exception to handle something that should be done right to start with.

Ok, there you have it…

VS 2013 Express tips

Just thought to share a tip or two about making the user experience better. The following applies to the desktop version but should also work (with some minor adjustment) to the other editions as well.

Change the all UPPERCASE main menus

In the registry, find the key HKEY_CURRENT_USER\Software\Microsoft\WDExpress\12.0\General. Add a (32-bit) DWORD value named SuppressUppercaseConversion and give it a value of 1. Next time you open the IDE the menu’s will be normal Title case again. It also applies to VS2012 editions as well (just change the version number to 11.0). For web express just change the ‘WDExpress’ part.

Update: If you are using the Web express edition the registry path for the change upper case menus are: HKEY_CURRENT_USER\Software\Microsoft\VWDExpress\12.0\General

Adding more themes

By default there are only 3 themes (for the express versions). To add some more options go to http://alinconstantin.blogspot.com/2012/09/using-color-themes-with-visual-studio.html?_sm_au_=isV7sFqHt8JbtbNM

Adding my Source backup tool

My source backup tool id aware of the desktop express version and can automatically add itself as one of the custom tools of the IDE. See SourceBackup.

If I come across more tips I’ll add them here as well.

 

Command line and strings

I’ve blogged about this some time ago under another topic (Creating-daily-log-files) but I find myself regularly searching for it again when I have to create a new batch file for something plus have to output some uniquely named log file.

Situation:

You have some script/batch file that does some stuff/maintenance/imports whatever. It runs from some kind of scheduler unattended so you need to have it generate a log file in case there were errors/issues. Creating an output log file is fairly easy but having it create a new name each day/time is a bit more tricky.

Possible solution:

This script assumes a date time format of yyyy/mm/dd

SET UNIQUESTR=%date:~0,4%%date:~5,2%%date:~8,2%%time:~0,2%%time:~3,2%
MyTool.exe > MyTool%UNIQUESTR%.log

This will create a log file with a date and time stamp each time it is run (assuming you don’t run it twice in the same second)

Have fun kids!

Update: a nice site with some helpful info -> http://www.dostips.com/DosCommandIndex.php

List all servers where I have an RDP session on (even ones where I’m disconnected)

This is something more than just one administrator has had trouble with. How do you find out what servers/machines you have worked on at some point and happened to simply use the ‘disconnect’ feature because you still had windows open? So far I have not found a simple way to do this – however I have created a script that helps with this. Unfortunately it still requires you to specify a list (input text file) of possible servers than needs to be checked. I would have liked if it was possible to have it automatically discover all machines with RDP sessions that use my logon…

The solution I created is simply a powershell script that takes an input text file with the list of machines you want to test connections with. This list would probably contain the usual machines you connect to. The other bit of the ‘solution’ is calling the ‘qwinsta’ utility that queries a specified machine and returns some details about RDP connections active on that machine. The script must then parse the output to figure out if your username is one of them…

param (
    $myAccount #(Read-Host -Prompt "Enter a user name")
    ,$serverListFile #(Read-Host -Prompt "File with list of servers")
)
if ($myAccount -eq $null){
    $myAccount = $env:username
}
if ($serverListFile -eq $null){
    $scriptpath = $MyInvocation.MyCommand.Path
    $dir = Split-Path $scriptpath
    $serverListFile = $dir + "\myservers.txt"
}

$showDebugInfo = $false
$reader = [System.IO.File]::OpenText($serverListFile)
"Listing RDP sessions for " + $myAccount
try {
    for(;;) {
        $server = $reader.ReadLine()
        if ($server -eq $null) { break }
        # process the line
        if(!(Test-Connection -Cn $server -BufferSize 16 -Count 1 -ea 0 -quiet))
        {
            " Error accessing " + $server
        }
        else
        {
            try
            {
                if ($showDebugInfo){
                    "Checking " + $server + "..."
                }
                $qwinstaResults = (qwinsta /server:$server | foreach { (($_.trim() -replace “\s+”,”,”))} | ConvertFrom-Csv)
                ForEach ($queryResult in $qwinstaResults)
                {
                    if ($queryResult -CMatch $myAccount)
                    {
                        "Logged on to " + $server
                    }
                }
            }
            catch
            {
                " Error processing " + $server
            }
        }
    }
}
finally {
    $reader.Close()
}
"Done"

Then using this script is as easy as calling it from (say) a batch file like this:

powershell.exe .\MyRDPConnections.ps1 myusername myservers.txt

Not perfect but at least it helps.

Windows Forms vs WPF

The following short piece is about my opinion of comparing old fashioned Windows Forms development to using WPF (Windows Presentation Foundation).

After some real experimenting, researching, googling, scratching, digging, hair pulling (what is left of it), swearing, yelling, kicking around getting a very simple WPF application to work I can seriously say that WPF is a load of … brown stuff. I’m not denying that it could be used to create really beautiful and powerful applications given enough time, patience (and hair) but, the effort to do this is making me question whether this is worth while. It has a few benefits over WinForms but they are offset by some really annoying and lacking features, not to mention that it also have all the same disadvantages that WinForm applications have (compare to stuff like Web/mobile applications). Essentially, anything you can do with WPF can also be done with WinForms with less time and effort.

Let me give a few examples.

Basic layout and design of a form

I’m sure once you are completely fluent with WPF and all the possible permutations of properties, behavior, styles etc. that you can also do basic layouts of an application very quickly. For me, knowing exactly what I wanted and even what I’m looking for, it took more that two days to create a basic interface (which I could have done in 5 minutes in WinForms). Yes, part of the problem was I’m not fluent in all that is WPF but thanks to Google I could find solution quickly every time. Despite this I had to retest every possible basic behavior of all controls – even simple things like clicking on a blank space inside a control to ensure all ‘basic’ functionality as a plain user would expect (people that have been using Windows app for years), are still the same. One of the most important fundamental concepts of UI design is to have consistency – like behavior of controls. Something like keyboard navigation was seriously not part of the WPF designers ideas.

The ListView control.

This control has been changed in several ways which could both be seen and good and bad. In WinForms this is/was one of my favorites. The way you design, code and use columns are very different from WinForm ListViews. It does give you more powerful ‘formatting’ options but this make it incredibly complex as well. Doing basic stuff like right aligning a column is not straight forward anymore. Yes, it can be done but this requires doing ‘non-standard’ things like ‘Styles’, custom code and so on. Then behavior like selecting items in the ListView has changed and even something like ‘unselecting’ all items by clicking on a blank space inside the control now requires you to write ‘extra’ code just to accomplish it. Essentially this is not the same ListView control that we were used to in WinForms but a new control that superficially looks like it.

There is however one aspect/feature of this control that I really like. The way you can bind columns to properties of an object – which by the way is the only way to use it! In general I do NOT use databinding features because it removes your ability to do really powerful things with the control and more importantly databinding controls never really work well with huge sets of data. For that reason I always populated my controls myself so I have ‘real’ control over them. That does come at the cost of having to manually always sync the displayed values on a control with the underlying data.

Summary

There might be people out there that prefer WPF over an ‘old’ technology like WinForms and possible they can create even better applications if they put their mind to it but I’m still in the WinForms camp. Then you have to keep in mind that WPF just like WinForms as a development technology is in danger of being abandoned thanks to the whole HTML5 and JavaScript mobile revolution.  WPF might become just another one of those potential (good) technologies that Microsoft killed before it had time to evolved into something really good. That is a shame.

Update:

I also discovered that WPF does not even support some VERY basic dialog boxes like browsing for a folder. I mean, FFS Microsoft, what were the developers of WPF smoking when they created this abortion of a tool/technology??

Also, they changed the very standard way of returning results from dialog/messages boxes to use a nullable boolean in stead of a usable structure. WTF??

Adding performance counters to your application (C#)

Nothing about this is exactly new or ground breaking but few developers (enterprise) these days add proper monitoring abilities to their apps. We (now that I mostly do administration and management of other peoples apps) that has to support these things don’t come equipped with x-ray eyes or ESP pills so knowing how the the internals of ‘your’ works is an issue…

Classically developers tend to use stuff like log file, event log and so on to ‘see’ what is going on inside their apps. However, these things also pick up a lot of noise so they usually get turn off for production use but that still leaves us with the requirements that we want to know ‘what your app is doing all the time’ – when we want to track it. Ok, to make a long story shorter, there is such a thing like performance counters that can help us to know if your app is performing or not. What they are and what they can do for you you can go read up on MSDN, Google etc.

Now, it appears most developers are scared of these things – or just too lazy to implement them. I’ve created a little helper class that makes it at least a little easier to implement – without all the worries about what happens if things blow up etc. It is written is such a way that if itself ‘breaks’ it should not break the rest of the app (don’t contribute to a bigger problem).

Setting it all up.

Creating a ‘Category’ is the first step in setting up a performance counter. Once it is created you don’t have to recreate it again (unless you go and delete it which would be rather stupid). The following routine do just that.

PerformanceCounterCategory InitializeCategory(string category, CounterCreationData[] creationData, string instance = "")
        {
            PerformanceCounterCategory pcc = null;
            if (!PerformanceCounterCategory.Exists(category))
            {
                if (instance.Length > 0)
                    pcc = PerformanceCounterCategory.Create(category, category, PerformanceCounterCategoryType.MultiInstance, new CounterCreationDataCollection(creationData));
                else
                    pcc = PerformanceCounterCategory.Create(category, category, PerformanceCounterCategoryType.SingleInstance, new CounterCreationDataCollection(creationData));
            }
            else
                pcc = new PerformanceCounterCategory(category);
            return pcc;
        }

All this does is create the category for you if it doesn’t exist yet or else just returns the existing one. All you specify is the name and the definitions of the counters you want to use. Optionally you can specify an ‘instance name’ which is handy if you have multiple instances of the same set of ‘things’ you want to ‘monitor’. The default is a single instance (e.g. like a global instance). Keep in mind that a single category can only have counters of one of two types – either single instance or multi-instance counters. This cannot be changed unless the whole category is deleted and recreated again.

The next step is to create run-time ‘instances’ of the counters.

PerformanceCounter InitializePerfCounter(string categoryName, string counterName, string instanceName = "")
        {
            PerformanceCounter counter = null;
            try
            {
                if (instanceName.Length > 0)
                {
                    if (IsCategoryMultiInstance(categoryName))
                        counter = new PerformanceCounter(categoryName, counterName, instanceName, false);
                    else
                        RaiseWarningMessage(string.Format("Performance category '{0}' is not set up for multiple instances! ({1})", categoryName, counterName));
                }
                else
                {
                    if (!IsCategoryMultiInstance(categoryName))
                        counter = new PerformanceCounter(categoryName, counterName, false);
                    else
                        RaiseWarningMessage(string.Format("Performance category '{0}' is not set up for single instance use! ({1})", categoryName, counterName));
                }
                if (counter != null)
                {
                    counter.BeginInit();
                    counter.RawValue = 0;
                    counter.EndInit();
                }
            }
            catch (Exception ex)
            {
                RaiseErrorMessage(string.Format("Error initializing performance counter '{0}'!\r\n{1}", counterName, ex.ToString()));
            }
            return counter;
        }

There are a couple of sub-routines not listed yet. Please just ignore for now – they will be included in the attached sample code.

Next step is just how to use them – setting the values. I tend to only use two types of counters – a ‘rate of’ and absolute values. The ‘rate of’ type of counters are typically used to track the number of events or sum of something per second while absolute values track the actual value of something as it is ‘now’ at that moment of tracking – e.g. CPU % usage.

void SetCounterValue(PerformanceCounter counter, long value)
        {
            try
            {
                if (counter == null)
                {
                    RaiseWarningMessage("Performance counter not set up or installed!");
                }
                else
                {
                    counter.RawValue = value;
                }
            }
            catch (Exception ex)
            {
                RaiseErrorMessage(string.Format("Increment performance counter error! : {0}\r\n{1}", counter.CounterName, ex.ToString()));
            }
        }
void IncrementCounter(PerformanceCounter counter)
        {
            IncrementCounterBy(counter, 1);
        }
void IncrementCounterBy(PerformanceCounter counter, long incBy)
        {
            try
            {
                if (counter == null)
                {
                    RaiseWarningMessage("Performance counter not set up or installed!");
                }
                else
                {
                    counter.IncrementBy(incBy);
                }
            }
            catch (Exception ex)
            {
                RaiseErrorMessage(string.Format("Increment performance counter error! : {0}\r\n{1}", counter.CounterName, ex.ToString()));
            }
        }

Events
In order to provide all this functionality without ‘breaking’ anything else I make use of ‘events’ e.g. RaiseWarningMessage and RaiseErrorMessage. The calling class/code don’t have to make use of the events but of course that would make troubleshooting a bit harder if needed. The code for this is fairly simple:

        public event MessageRaisedDelegate ErrorRaised;
        internal void RaiseErrorMessage(string message)
        {
            if (ErrorRaised != null)
            {
                ErrorRaised(message);
            }
        }
        public event MessageRaisedDelegate WarningRaised;
        internal void RaiseWarningMessage(string message)
        {
            if (WarningRaised != null)
            {
                WarningRaised(message);
            }
        }

Implementation
It is possible to use the utility class ‘as is’ but I would recommend doing the following to provide ‘cleaner’ code. Inheriting from the class ‘PerfCounterUtilBase’ (not shown in above code) and implementing all the specific performance counter functionality ‘you’ need is a better way to so it. The following is just example code to initialize the performance counter category and counters you want to use:

void InitializePerformanceCounters()
        {
            string lastErr = "Create performance counter category error!: {0}";
            try
            {
                CounterCreationData[] creationData = new CounterCreationData[]
                    {
                        new CounterCreationData("Clicks/Sec", "Clicks per second", PerformanceCounterType.RateOfCountsPerSecond32),
                        new CounterCreationData("Total X value/Sec", "Sum of X values per second", PerformanceCounterType.RateOfCountsPerSecond32),
                        new CounterCreationData("Total Y value/Sec", "Sum of Y values per second", PerformanceCounterType.RateOfCountsPerSecond32),
                        new CounterCreationData("Last X value", "Last X value", PerformanceCounterType.NumberOfItems32),
                        new CounterCreationData("Last Y value", "Last Y value", PerformanceCounterType.NumberOfItems32)
                    };
                InitializeCategory(Category, creationData, Instance);

                lastErr = "Initialize performance counter(s) error!: {0}";
                clicksPerSecond = InitializePerfCounter(Category, "Clicks/Sec", Instance);
                xValuePerSecond = InitializePerfCounter(Category, "Total X value/Sec", Instance);
                yValuePerSecond = InitializePerfCounter(Category, "Total Y value/Sec", Instance);
                lastXValue = InitializePerfCounter(Category, "Last X value", Instance);
                lastYValue = InitializePerfCounter(Category, "Last Y value", Instance);
            }
            catch (Exception ex)
            {
                RaiseErrorMessage(string.Format(lastErr, ex.Message));
            }
        }

Then you can simply have specific methods like these to use in your own code:

public void IncClicks()
        {
            IncrementCounter(clicksPerSecond);
        }
        public void IncXValues(long value)
        {
            IncrementCounterBy(xValuePerSecond, value);
        }
...

In ‘your’ code you simply do this then:

pcu = new PerfCounterExampleImplemetation();
pcu.ErrorRaised += new MessageRaisedDelegate(pcu_ErrorRaised);
pcu.WarningRaised += new MessageRaisedDelegate(pcu_WarningRaised);
pcu.Category = txtCategory.Text;
pcu.Instance = txtInstance.Text;
pcu.InitializePerformanceCounters();
...
void pcu_ErrorRaised(string message)
        {
            MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

void SomeMethod()
        {
            long val = GetSomeValue();

            if (pcu != null)
            {
                pcu.IncClicks();
                pcu.IncXValues(val);
                ...
            }
        }

Now go have fun…

Example code: ShowPerfCounterUtils