views:

162

answers:

2

I have a performance counter category. The counters in this category may change for my next release so when the program starts, I want to check if the category exists and it is the correct version - if not, create the new category. I can do this by storing a GUID in the help string but this is obviously smelly. Is it possible to do this more cleanly with the .NET API?

Existing smelly version...

if (PerformanceCounterCategory.Exists(CATEGORY_NAME))
{
    PerformanceCounterCategory c = new PerformanceCounterCategory(CATEGORY_NAME);
    if (c.CategoryHelp != CATEGORY_VERSION)
    {
        PerformanceCounterCategory.Delete(CATEGORY_NAME);
    }
}

if (!PerformanceCounterCategory.Exists(CATEGORY_NAME))
{
      // Create category
}
A: 

I don't think there is a better way. IMHO, I don't think this is a terrible solution.

Bryan
+1  A: 

In our system, each time the application starts we do a check for the existing category. If it isn't found, we create the category. If it exists, we compare the existing category to what we expect and recreate it (delete, create) if there are missing values.

var missing = counters
.Where(counter => !PerformanceCounterCategory.CounterExists(counter.Name, CategoryName))
.Count();

if (missing > 0)
{
 PerformanceCounterCategory.Delete(CategoryName);

 PerformanceCounterCategory.Create(
  CategoryName,
  CategoryHelp,
  PerformanceCounterCategoryType.MultiInstance,
  new CounterCreationDataCollection(counters.Select(x => (CounterCreationData)x).ToArray()));
}
Chris Patterson