(c) 2002 Visual Studio Magazine 
Fawcette Technical Publications

Issue: March 2002
Section: ASP.NET
Author: Jonathan Goodyear

C#	Create Performance Counters in the Application_Start Event
Listing 1	The Application_Start event fires when your Web application first starts, so it's the perfect time to create the custom performance counters your ASP.NET Web application will use. However, custom performance counters survive Web application re-starts, so you must first make sure the performance counters don't exist already.

protected void Application_Start(Object sender, 
	EventArgs e)
{
	if(!PerformanceCounterCategory.Exists
		("XYZ Products"))
	{
		//create a holder for your performance 
		//counters
		CounterCreationDataCollection perfCounters 
			= new CounterCreationDataCollection();

		//create two performance counters to 
		//monitor your sales
		CounterCreationData itemsSoldCounter = new 
			CounterCreationData(
			"Items Sold","This counter tracks the "
				"total number of items sold.",
			PerformanceCounterType.NumberOfItems32
				);
		perfCounters.Add(itemsSoldCounter);

		CounterCreationData salesPerSecond = new 
			CounterCreationData(
			"Sales per Second","This counter "
				"tracks the number of sales per "
				"second.",
			PerformanceCounterType.RateOfCountsPerSecond32
		);
		perfCounters.Add(salesPerSecond);

		//add the performance counters to the 
		//Performance Counter utility
		PerformanceCounterCategory.Create
			("XYZ Products",
			"Sales counters for XYZ Products",
				perfCounters);
	}
}

C#	Manipulate Performance Counters in the Click Event
Listing 2	In the recordSale button's Click event, create instances of the Items Sold and Sales per Second performance counters and increment them according to the Web Form data on the SalesPanel.aspx page. Make sure your PerformanceCounter object instances are writable by passing "false" as a parameter to their constructors.

private void recordSale_Click(object sender, 
	System.EventArgs e)
{	
	//increment the performance counters
	PerformanceCounter itemsSoldCounter = new 
		PerformanceCounter("XYZ Products",
		"Items Sold",false);
	itemsSoldCounter.IncrementBy(Convert.ToInt32
		(quantity.Text));

	PerformanceCounter salesPerSecond = new 
		PerformanceCounter("XYZ Products",
		"Sales per Second",false);
	salesPerSecond.Increment();
}
