//
// Copyright (c) 2002
// Ronald Kevin Burton
//
// Z poniższym kodem nie jest związana żadna gwarancja poprawności działania.
// Program został dołączony do książki ".NET CLR. Księga eksperta" w celu
// ilustracji koncepcji i zasad przedstawionych w tej książce. Program może być 
// używany na własne ryzyko.
//
// Przyznaje się prawo do użycia lub kopiowania tego oprogramowania do dowolnego celu
// bez konieczności ponoszenia żadnych opłat pod warunkiem, że powyższe uwagi zostaną 
// zachowane we wszystkich kopiach. Przyznaje się także prawo do modyfikacji kodu
// i dystrybucji zmodyfikowanego kodu pod warunkiem zachowania powyższych uwag
// oraz dołączenia informacji mówiącej o modyfikacji kodu.
//
//  
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;

namespace PerformanceMonitor
{
	/// <summary>
	/// Podsumowanie dla PerformanceMonitorForm.
	/// </summary>
	public class PerformanceMonitorForm : System.Windows.Forms.Form
	{
		private System.Windows.Forms.RadioButton localRadioButton;
		private System.Windows.Forms.RadioButton remoteRadioButton;
		private System.Windows.Forms.ComboBox computerList;
		private System.Windows.Forms.Label performanceObjectLabel;
		private System.Windows.Forms.ComboBox categoryList;
		private System.Windows.Forms.Label counterLabel;
		private System.Windows.Forms.ListBox counterList;
		private System.Windows.Forms.ListBox instanceList;
		private System.Windows.Forms.Label instanceListLabel;
		private System.Windows.Forms.RichTextBox counterHelp;
		private System.Windows.Forms.Label helpLabel;
		private System.Windows.Forms.ListView samples;
		private System.Windows.Forms.ColumnHeader type;
		private System.Windows.Forms.ColumnHeader timeStamp;
		private System.Windows.Forms.ColumnHeader value;
		private PerformanceCounter currentPerformanceCounter;
		private System.Timers.Timer timer;
		private System.Windows.Forms.ColumnHeader counter;

		/// <summary>
		/// Wymagana zmienna.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public PerformanceMonitorForm()
		{
			//
			// Wymagane do obsługi Windows Form Designer
			//
			InitializeComponent();
			PerformanceCounterCategory [] pcc  = PerformanceCounterCategory.GetCategories();
			foreach(PerformanceCounterCategory p in pcc)
			{
				categoryList.Items.Add(p.CategoryName);
			}
			localRadioButton.Checked = true;
			computerList.Enabled = false;
			computerList.Text = SystemInformation.ComputerName;
			computerList.Items.Add(SystemInformation.ComputerName);
			computerList.SelectedItem = SystemInformation.ComputerName;
		}

		/// <summary>
		/// Oczyszczenie używanych zasobów.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
				timer.Dispose();
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Metoda wymagana do obsługi Designera - nie należy modyfikować
		/// zawartości tej metody przy użyciu edytora kodu.
		/// </summary>
		private void InitializeComponent()
		{
			this.counterHelp = new System.Windows.Forms.RichTextBox();
			this.instanceList = new System.Windows.Forms.ListBox();
			this.timeStamp = new System.Windows.Forms.ColumnHeader();
			this.value = new System.Windows.Forms.ColumnHeader();
			this.counterList = new System.Windows.Forms.ListBox();
			this.counterLabel = new System.Windows.Forms.Label();
			this.helpLabel = new System.Windows.Forms.Label();
			this.remoteRadioButton = new System.Windows.Forms.RadioButton();
			this.categoryList = new System.Windows.Forms.ComboBox();
			this.type = new System.Windows.Forms.ColumnHeader();
			this.samples = new System.Windows.Forms.ListView();
			this.performanceObjectLabel = new System.Windows.Forms.Label();
			this.instanceListLabel = new System.Windows.Forms.Label();
			this.timer = new System.Timers.Timer();
			this.computerList = new System.Windows.Forms.ComboBox();
			this.localRadioButton = new System.Windows.Forms.RadioButton();
			this.counter = new System.Windows.Forms.ColumnHeader();
			((System.ComponentModel.ISupportInitialize)(this.timer)).BeginInit();
			this.SuspendLayout();
			// 
			// counterHelp
			// 
			this.counterHelp.Location = new System.Drawing.Point(240, 56);
			this.counterHelp.Name = "counterHelp";
			this.counterHelp.Size = new System.Drawing.Size(216, 72);
			this.counterHelp.TabIndex = 9;
			this.counterHelp.Text = "";
			// 
			// instanceList
			// 
			this.instanceList.Location = new System.Drawing.Point(240, 168);
			this.instanceList.Name = "instanceList";
			this.instanceList.Size = new System.Drawing.Size(216, 160);
			this.instanceList.Sorted = true;
			this.instanceList.TabIndex = 7;
			this.instanceList.SelectedIndexChanged += new System.EventHandler(this.OnInstanceSelect);
			// 
			// timeStamp
			// 
			this.timeStamp.Text = "Znacznik czasowy";
			this.timeStamp.Width = 110;
			// 
			// value
			// 
			this.value.Text = "Wartość";
			this.value.Width = 94;
			// 
			// counterList
			// 
			this.counterList.Location = new System.Drawing.Point(8, 168);
			this.counterList.Name = "counterList";
			this.counterList.Size = new System.Drawing.Size(216, 160);
			this.counterList.Sorted = true;
			this.counterList.TabIndex = 6;
			this.counterList.SelectedIndexChanged += new System.EventHandler(this.OnCounterSelect);
			// 
			// counterLabel
			// 
			this.counterLabel.Location = new System.Drawing.Point(8, 144);
			this.counterLabel.Name = "counterLabel";
			this.counterLabel.Size = new System.Drawing.Size(216, 16);
			this.counterLabel.TabIndex = 5;
			this.counterLabel.Text = "Lista liczników wydajności";
			// 
			// helpLabel
			// 
			this.helpLabel.Location = new System.Drawing.Point(240, 32);
			this.helpLabel.Name = "helpLabel";
			this.helpLabel.Size = new System.Drawing.Size(216, 16);
			this.helpLabel.TabIndex = 12;
			this.helpLabel.Text = "Opis";
			// 
			// remoteRadioButton
			// 
			this.remoteRadioButton.Location = new System.Drawing.Point(8, 32);
			this.remoteRadioButton.Name = "remoteRadioButton";
			this.remoteRadioButton.Size = new System.Drawing.Size(216, 24);
			this.remoteRadioButton.TabIndex = 1;
			this.remoteRadioButton.Text = "Wybierz liczniki:";
			this.remoteRadioButton.CheckedChanged += new System.EventHandler(this.OnRemoteCheckedChanged);
			// 
			// categoryList
			// 
			this.categoryList.DropDownWidth = 216;
			this.categoryList.Location = new System.Drawing.Point(8, 112);
			this.categoryList.Name = "categoryList";
			this.categoryList.Size = new System.Drawing.Size(216, 21);
			this.categoryList.Sorted = true;
			this.categoryList.TabIndex = 4;
			this.categoryList.SelectionChangeCommitted += new System.EventHandler(this.OnCategoryChanged);
			// 
			// type
			// 
			this.type.Text = "Typ";
			this.type.Width = 116;
			// 
			// samples
			// 
			this.samples.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
																					  this.counter,
																					  this.type,
																					  this.timeStamp,
																					  this.value});
			this.samples.GridLines = true;
			this.samples.Location = new System.Drawing.Point(8, 336);
			this.samples.MultiSelect = false;
			this.samples.Name = "samples";
			this.samples.Size = new System.Drawing.Size(448, 104);
			this.samples.TabIndex = 13;
			this.samples.View = System.Windows.Forms.View.Details;
			// 
			// performanceObjectLabel
			// 
			this.performanceObjectLabel.Location = new System.Drawing.Point(8, 88);
			this.performanceObjectLabel.Name = "performanceObjectLabel";
			this.performanceObjectLabel.Size = new System.Drawing.Size(216, 16);
			this.performanceObjectLabel.TabIndex = 3;
			this.performanceObjectLabel.Text = "Kategoria";
			// 
			// instanceListLabel
			// 
			this.instanceListLabel.Location = new System.Drawing.Point(240, 144);
			this.instanceListLabel.Name = "instanceListLabel";
			this.instanceListLabel.Size = new System.Drawing.Size(208, 16);
			this.instanceListLabel.TabIndex = 8;
			this.instanceListLabel.Text = "Lista egzemplarzy";
			// 
			// timer
			// 
			this.timer.Interval = 1000;
			this.timer.SynchronizingObject = this;
			this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
			// 
			// computerList
			// 
			this.computerList.DropDownWidth = 216;
			this.computerList.Location = new System.Drawing.Point(8, 56);
			this.computerList.Name = "computerList";
			this.computerList.Size = new System.Drawing.Size(216, 21);
			this.computerList.TabIndex = 2;
			this.computerList.Leave += new System.EventHandler(this.OnComputerListLeave);
			// 
			// localRadioButton
			// 
			this.localRadioButton.Location = new System.Drawing.Point(8, 8);
			this.localRadioButton.Name = "localRadioButton";
			this.localRadioButton.Size = new System.Drawing.Size(216, 24);
			this.localRadioButton.TabIndex = 0;
			this.localRadioButton.Text = "Użyj lokalnych liczników komputera";
			// 
			// counter
			// 
			this.counter.Text = "Licznik";
			this.counter.Width = 122;
			// 
			// PerformanceMonitorForm
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(464, 453);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.samples,
																		  this.helpLabel,
																		  this.counterHelp,
																		  this.instanceListLabel,
																		  this.instanceList,
																		  this.counterList,
																		  this.counterLabel,
																		  this.categoryList,
																		  this.performanceObjectLabel,
																		  this.computerList,
																		  this.remoteRadioButton,
																		  this.localRadioButton});
			this.Name = "PerformanceMonitorForm";
			this.Text = "Monitor wydajności";
			((System.ComponentModel.ISupportInitialize)(this.timer)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// Główny punkt wejścia dla aplikacji.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new PerformanceMonitorForm());
		}

		private void OnCategoryChanged(object sender, System.EventArgs e)
		{
			ComboBox cb = sender as ComboBox;
			timer.Enabled = false;
			samples.Items.Clear();
			currentPerformanceCounter = null;
			counterList.Items.Clear();
			instanceList.Items.Clear();
			counterHelp.Text = "";
			PerformanceCounterCategory pcc;
			if(computerList.Enabled)
				pcc = new PerformanceCounterCategory((string)cb.SelectedItem, (string)computerList.SelectedItem);
			else
				pcc = new PerformanceCounterCategory((string)cb.SelectedItem);
			string [] instanceNames = pcc.GetInstanceNames();
			foreach(string s in instanceNames)
			{
				instanceList.Items.Add(s);
			}
			if(instanceNames.Length > 0)
			{
				// Uzyskanie liczników dla ostatniego egzemplarza (powinny być identyczne)
				PerformanceCounter [] pca = pcc.GetCounters(instanceNames[0]);
				foreach(PerformanceCounter pc in pca)
				{
					counterList.Items.Add(pc.CounterName);
				}
			}
			else
			{
				PerformanceCounter [] pca = pcc.GetCounters();
				foreach(PerformanceCounter pc in pca)
				{
					counterList.Items.Add(pc.CounterName);
				}
			}
		}

		private void OnCounterSelect(object sender, System.EventArgs e)
		{
			ListBox lb = sender as ListBox;
			currentPerformanceCounter = null;
			timer.Enabled = false;
			samples.Items.Clear();
			PerformanceCounterCategory pcc = new PerformanceCounterCategory((string)categoryList.SelectedItem);
			PerformanceCounter pc;
			if(instanceList.SelectedIndex == -1 &&
				instanceList.Items.Count > 0)
			{
				instanceList.SelectedIndex = 0;
			}
			if(computerList.Enabled)
				pc = new PerformanceCounter(pcc.CategoryName, (string)lb.SelectedItem, (string)instanceList.SelectedItem, (string)computerList.SelectedItem);
			else
				pc = new PerformanceCounter(pcc.CategoryName, (string)lb.SelectedItem, (string)instanceList.SelectedItem);
			counterHelp.Text = pc.CounterHelp;
			currentPerformanceCounter = pc;
			timer.Enabled = true;
		}

		private void OnInstanceSelect(object sender, System.EventArgs e)
		{
			ListBox lb = sender as ListBox;
			currentPerformanceCounter = null;
			timer.Enabled = false;
			samples.Items.Clear();
			PerformanceCounterCategory pcc = new PerformanceCounterCategory((string)categoryList.SelectedItem);
			PerformanceCounter pc;
			if(counterList.SelectedIndex == -1 &&
				counterList.Items.Count > 0)
			{
				counterList.SelectedIndex = 0;
			}
			if(computerList.Enabled)
				pc = new PerformanceCounter(pcc.CategoryName, (string)counterList.SelectedItem, (string)lb.SelectedItem, (string)computerList.SelectedItem);
			else
				pc = new PerformanceCounter(pcc.CategoryName, (string)counterList.SelectedItem, (string)lb.SelectedItem);
			counterHelp.Text = pc.CounterHelp;
			currentPerformanceCounter = pc;
			timer.Enabled = true;
		}
		private void OnRemoteCheckedChanged(object sender, System.EventArgs e)
		{
			RadioButton rb = sender as RadioButton;
			timer.Enabled = false;
			currentPerformanceCounter = null;
			samples.Items.Clear();
			if(rb.Checked)
			{
				computerList.Enabled = true;
			}
			else
			{
				computerList.Enabled = false;
				computerList.SelectedItem = SystemInformation.ComputerName;
				counterList.Items.Clear();
				instanceList.Items.Clear();
				categoryList.Items.Clear();
				try
				{
					PerformanceCounterCategory [] pcca  = PerformanceCounterCategory.GetCategories();
					foreach(PerformanceCounterCategory p in pcca)
					{
						categoryList.Items.Add(p.CategoryName);
					}
					categoryList.SelectedIndex = 0;
					PerformanceCounterCategory pcc = new PerformanceCounterCategory((string)categoryList.SelectedItem);
					string [] instanceNames = pcc.GetInstanceNames();
					foreach(string s in instanceNames)
					{
						instanceList.Items.Add(s);
					}
					if(instanceNames.Length > 0)
					{
						instanceList.SelectedIndex = 0;
						// Uzyskanie liczników dla ostatniego egzemplarza (powinny być identyczne)
						PerformanceCounter [] pca = pcc.GetCounters(instanceNames[0]);
						foreach(PerformanceCounter pc in pca)
						{
							counterList.Items.Add(pc.CounterName);
						}
					}
					else
					{
						PerformanceCounter [] pca = pcc.GetCounters();
						foreach(PerformanceCounter pc in pca)
						{
							counterList.Items.Add(pc.CounterName);
						}
					}
				}
				catch(Exception exception)
				{
					Debug.WriteLine(exception);
				}
			}
		}

		private void OnComputerListLeave(object sender, System.EventArgs e)
		{
			ComboBox cb = sender as ComboBox;
			timer.Enabled = false;
			currentPerformanceCounter = null;
			samples.Items.Clear();
			counterList.Items.Clear();
			instanceList.Items.Clear();
			categoryList.Items.Clear();
			try
			{
				PerformanceCounterCategory [] pcc  = PerformanceCounterCategory.GetCategories(cb.Text);
				foreach(PerformanceCounterCategory p in pcc)
				{
					categoryList.Items.Add(p.CategoryName);
				}
				cb.Items.Add(cb.Text);
				cb.SelectedItem = cb.Text;
			}
			catch(Exception exception)
			{
				Debug.WriteLine(exception);
			}
		}

		private void OnTimer(object sender, System.Timers.ElapsedEventArgs e)
		{
			ListViewItem item = new ListViewItem(currentPerformanceCounter.CounterName);
			CounterSample sample = currentPerformanceCounter.NextSample();
			item.SubItems.Add(Convert.ToString(currentPerformanceCounter.CounterType));
			item.SubItems.Add(Convert.ToString(sample.TimeStamp));
			item.SubItems.Add(Convert.ToString(sample.RawValue));
			samples.Items.Add(item);
		}
	}
}