/// <summary> /// Creates CPU counter /// </summary> public static SimpleCounter CreateCPUCounter() { // Créer un compteur par CPU System.Diagnostics.PerformanceCounterCategory category = new System.Diagnostics.PerformanceCounterCategory("Processor"); SimpleCounter mainCounter = null; List <SimpleCounter> counters = new List <SimpleCounter>(); foreach (string instance in category.GetInstanceNames().OrderBy(s => s)) { System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", instance, true); SimpleCounter counter = new KnownMaxPerformanceCounter(new PerformanceCounter(pc), new StaticPerformanceCounter(100)); if (instance == "_Total") { mainCounter = counter; } else { counters.Add(counter); } } return(new SubPerformanceCounter(mainCounter, counters)); }
/// <summary> /// Creates counters for each physical disk connected /// </summary> /// <returns>enumeration of counters</returns> public static IEnumerable<SimpleCounter> CreatePhysicalDiskCounters() { List<SimpleCounter> list = new List<SimpleCounter>(); System.Diagnostics.PerformanceCounterCategory category = new System.Diagnostics.PerformanceCounterCategory("PhysicalDisk"); foreach (string instance in category.GetInstanceNames().OrderBy(s => s)) { if (instance == "_Total") { continue; } List<SimpleCounter> subCounterslist = new List<SimpleCounter>(); System.Diagnostics.PerformanceCounterCategory subCounterCategory = new System.Diagnostics.PerformanceCounterCategory("LogicalDisk"); foreach (string subCounterInstance in subCounterCategory .GetInstanceNames().OrderBy(s => s)) { if (subCounterInstance == "_Total") { continue; } if (!instance.Contains(subCounterInstance)) { continue; } System.Diagnostics.PerformanceCounter subPc = new System.Diagnostics.PerformanceCounter("LogicalDisk", "% Idle Time", subCounterInstance , true); subCounterslist.Add(new ReversePerformanceCounter(new PerformanceCounter(subPc), new StaticPerformanceCounter(100))); } System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("PhysicalDisk", "% Idle Time", instance, true); // list.Add(new ReversePerformanceCounter(new PerformanceCounter(pc), new StaticPerformanceCounter(100))); list.Add( new SubPerformanceCounter( new ReversePerformanceCounter( new PerformanceCounter(pc), new StaticPerformanceCounter(100)), subCounterslist)); } return list; }
private int GetCounters(string[] hosts) { dtSent.Clear(); dtReceived.Clear(); int error = 0; QueryAnalyzer_ADOTrafficMonitor.ThreadTools <string> .Parallel( new Action <string>( delegate(string slave) { if (string.Compare(slave, "localhost", true) == 0) { slave = System.Net.Dns.GetHostName(); } List <System.Diagnostics.PerformanceCounter> received = new List <System.Diagnostics.PerformanceCounter>(); List <System.Diagnostics.PerformanceCounter> sent = new List <System.Diagnostics.PerformanceCounter>(); try { System.Diagnostics.PerformanceCounterCategory cat = new System.Diagnostics.PerformanceCounterCategory("Network Interface", slave); string[] instances = cat.GetInstanceNames(); foreach (string s in instances) { if (s.ToLower().IndexOf("loopback") == -1) { received.Add(new System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Received/sec", s, slave)); sent.Add(new System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Sent/sec", s, slave)); } } //Initial reading. foreach (System.Diagnostics.PerformanceCounter pc in received) { pc.NextValue(); } foreach (System.Diagnostics.PerformanceCounter pc in sent) { pc.NextValue(); } lock (dtSent) { dtSent.Add(slave, sent); dtReceived.Add(slave, received); } } catch (Exception e) { AppendStatusText(txtStatus, "Text", "Error while getting counter from " + slave + ". Error: " + e.ToString()); System.Threading.Interlocked.Increment(ref error); } } ), hosts, hosts.Length); return(error); }
public static System.Collections.Generic.Dictionary <int, int> GetAllProcessParentPids() { var childPidToParentPid = new System.Collections.Generic.Dictionary <int, int>(); var processCounters = new System.Collections.Generic.SortedDictionary <string, System.Diagnostics.PerformanceCounter[]>(); var category = new System.Diagnostics.PerformanceCounterCategory("Process"); // As the base system always has more than one process running, // don't special case a single instance return. var instanceNames = category.GetInstanceNames(); foreach (string t in instanceNames) { try { processCounters[t] = category.GetCounters(t); } catch (System.InvalidOperationException) { // Transient processes may no longer exist between // GetInstanceNames and when the counters are queried. } } foreach (var kvp in processCounters) { int childPid = -1; int parentPid = -1; foreach (var counter in kvp.Value) { if ("ID Process".CompareTo(counter.CounterName) == 0) { childPid = (int)(counter.NextValue()); } else if ("Creating Process ID".CompareTo(counter.CounterName) == 0) { parentPid = (int)(counter.NextValue()); } } if (childPid != -1 && parentPid != -1) { childPidToParentPid[childPid] = parentPid; } } return(childPidToParentPid); } // End Function GetAllProcessParentPids
/// <summary> /// Creates network counter /// </summary> public static SimpleCounter CreateNetworkCounter() { // Créer les contrôles pour chaque interface réseau System.Diagnostics.PerformanceCounterCategory category = new System.Diagnostics.PerformanceCounterCategory("Network Interface"); List <SimpleCounter> counters = new List <SimpleCounter>(); foreach (string instance in category.GetInstanceNames().OrderBy(s => s)) { System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Total/sec", instance, true); PerformanceCounter counter = new PerformanceCounter(pc); counters.Add(new PerformanceCounter(pc)); } return(new SumPerformanceCounter(counters)); }
private void instanceCb_SelectedIndexChanged(object sender, EventArgs e) { nameCb.Items.Clear(); nameCb.Text = ""; nameCb.Enabled = true; var category = new System.Diagnostics.PerformanceCounterCategory(categoryCb.SelectedItem.ToString()); System.Collections.ArrayList counters = new System.Collections.ArrayList(); counters.AddRange(category.GetCounters(instanceCb.Text.ToString())); foreach (System.Diagnostics.PerformanceCounter counter in counters) { nameCb.Items.Add(counter.CounterName); } }
public static bool _Create_System_String_System_String_System_String_System_String( ) { //Parameters System.String categoryName = null; System.String categoryHelp = null; System.String counterName = null; System.String counterHelp = null; //ReturnType/Value System.Diagnostics.PerformanceCounterCategory returnVal_Real = null; System.Diagnostics.PerformanceCounterCategory returnVal_Intercepted = null; //Exception Exception exception_Real = null; Exception exception_Intercepted = null; InterceptionMaintenance.disableInterception( ); try { returnValue_Real = System.Diagnostics.PerformanceCounterCategory.Create(categoryName, categoryHelp, counterName, counterHelp); } catch (Exception e) { exception_Real = e; } InterceptionMaintenance.enableInterception( ); try { returnValue_Intercepted = System.Diagnostics.PerformanceCounterCategory.Create(categoryName, categoryHelp, counterName, counterHelp); } catch (Exception e) { exception_Intercepted = e; } Return((exception_Real.Messsage == exception_Intercepted.Message) && (returnValue_Real == returnValue_Intercepted)); }
/// <summary> /// Create counter list from string /// </summary> /// <param name="counterString">string which represents one or more counters: "\\<machineName>\<categoryName>(<instanceName>)\<counterName>" /// counterName and/or instanceName can have the special value "#ALL#", meaning we want to get all of them</param> /// <returns>list of counters</returns> public static IEnumerable <System.Diagnostics.PerformanceCounter> CreateCountersFromString(string counterString) { string machineName, categoryName, instanceName, counterName; ParseCounterString(counterString, out machineName, out categoryName, out instanceName, out counterName); System.Diagnostics.PerformanceCounterCategory category = new System.Diagnostics.PerformanceCounterCategory(categoryName, machineName); IEnumerable <System.Diagnostics.PerformanceCounter> counters = new System.Diagnostics.PerformanceCounter[] { }; if (counterName == "#ALL#" && instanceName == "#ALL#") { foreach (string instance in category.GetInstanceNames().OrderBy(s => s)) { counters = counters.Concat(category.GetCounters(instance)); } } else if (counterName == "#ALL#") { if (string.IsNullOrEmpty(instanceName)) { counters = category.GetCounters(); } else { counters = category.GetCounters(instanceName); } } else if (instanceName == "#ALL#") { foreach (string instance in category.GetInstanceNames().OrderBy(s => s)) { counters = counters.Concat(new System.Diagnostics.PerformanceCounter[] { new System.Diagnostics.PerformanceCounter(categoryName, counterName, instance, machineName) }); } } else { counters = new System.Diagnostics.PerformanceCounter[] { new System.Diagnostics.PerformanceCounter(categoryName, counterName, instanceName, machineName) }; } // Création des contrôles return(counters); }
/// <summary> /// Creates CPU percentage of max frequency counter /// </summary> public static SimpleCounter CreateCPUFrequencyCounter() { // Créer un compteur par CPU System.Diagnostics.PerformanceCounterCategory category = new System.Diagnostics.PerformanceCounterCategory("ProcessorPerformance"); SimpleCounter mainCounter = null; List <SimpleCounter> counters = new List <SimpleCounter>(); foreach (string instance in category.GetInstanceNames().OrderBy(s => s)) { System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("ProcessorPerformance", "percentage", instance, true); SimpleCounter counter = new KnownMaxPerformanceCounter(new PerformanceCounter(pc), new StaticPerformanceCounter(100)); counters.Add(counter); } mainCounter = new SumPerformanceCounter(counters); return(new SubPerformanceCounter(mainCounter, counters)); }
private void categoryCb_SelectedIndexChanged(object sender, EventArgs e) { string[] instanceNames; var category = new System.Diagnostics.PerformanceCounterCategory(categoryCb.SelectedItem.ToString()); instanceCb.Items.Clear(); nameCb.Items.Clear(); instanceCb.Text = ""; nameCb.Text = ""; instanceCb.Enabled = true; nameCb.Enabled = false; try { instanceNames = category.GetInstanceNames(); if (instanceNames.Length == 0) { instanceCb.Enabled = false; nameCb.Enabled = true; System.Collections.ArrayList counters = new System.Collections.ArrayList(); counters.AddRange(category.GetCounters()); foreach (System.Diagnostics.PerformanceCounter counter in counters) { nameCb.Items.Add(counter.CounterName); } } else { for (int i = 0; i < instanceNames.Length; i++) { instanceCb.Items.Add(instanceNames[i]); } } } catch (System.Exception ex) { MessageBox.Show("Unable to list the counters for this category:\n" + ex.Message); } }
/// <summary> /// Creates counters for each physical disk connected /// </summary> /// <returns>enumeration of counters</returns> public static IEnumerable <SimpleCounter> CreatePhysicalDiskCounters() { List <SimpleCounter> list = new List <SimpleCounter>(); System.Diagnostics.PerformanceCounterCategory category = new System.Diagnostics.PerformanceCounterCategory("PhysicalDisk"); foreach (string instance in category.GetInstanceNames().OrderBy(s => s)) { if (instance == "_Total") { continue; } List <SimpleCounter> subCounterslist = new List <SimpleCounter>(); System.Diagnostics.PerformanceCounterCategory subCounterCategory = new System.Diagnostics.PerformanceCounterCategory("LogicalDisk"); foreach (string subCounterInstance in subCounterCategory.GetInstanceNames().OrderBy(s => s)) { if (subCounterInstance == "_Total") { continue; } if (!instance.Contains(subCounterInstance)) { continue; } System.Diagnostics.PerformanceCounter subPc = new System.Diagnostics.PerformanceCounter("LogicalDisk", "% Idle Time", subCounterInstance, true); subCounterslist.Add(new ReversePerformanceCounter(new PerformanceCounter(subPc), new StaticPerformanceCounter(100))); } System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("PhysicalDisk", "% Idle Time", instance, true); // list.Add(new ReversePerformanceCounter(new PerformanceCounter(pc), new StaticPerformanceCounter(100))); list.Add( new SubPerformanceCounter( new ReversePerformanceCounter( new PerformanceCounter(pc), new StaticPerformanceCounter(100)), subCounterslist)); } return(list); }
private void button2_Click(object sender, EventArgs e) { System.Diagnostics.PerformanceCounterCategory selectedPerfCat = new System.Diagnostics.PerformanceCounterCategory(this.listBox1.SelectedItem.ToString()); string selectedInstance = this.listBox2.SelectedItem.ToString(); System.Collections.ArrayList selectedCounters = new System.Collections.ArrayList(); foreach(var counter in listBox3.SelectedItems) { selectedCounters.Add(counter); } if (selectedCounters.Count <= 1) { listBox4.Items.Add("\\"+ selectedPerfCat.CategoryName+"("+ selectedInstance+")\\"+selectedCounters[0]); } else { foreach(var selectedCounter in selectedCounters) { listBox4.Items.Add("\\" + selectedPerfCat.CategoryName + "(" + selectedInstance + ")\\" + selectedCounter); } } }
/// <summary> /// Creates CPU counter /// </summary> public static SimpleCounter CreateCPUCounter() { // Créer un compteur par CPU System.Diagnostics.PerformanceCounterCategory category = new System.Diagnostics.PerformanceCounterCategory("Processor"); SimpleCounter mainCounter = null; List<SimpleCounter> counters = new List<SimpleCounter>(); foreach (string instance in category.GetInstanceNames().OrderBy(s => s)) { System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", instance, true); SimpleCounter counter = new KnownMaxPerformanceCounter(new PerformanceCounter(pc), new StaticPerformanceCounter(100)); if (instance == "_Total") { mainCounter = counter; } else { counters.Add(counter); } } return new SubPerformanceCounter(mainCounter, counters); }
//</snippet14> static void Main(string[] args) { //<snippet1> var currentPerformanceCounterCategory = new System.Diagnostics. PerformanceCounterCategory(); //</snippet1> int val1 = 1; int val2 = 2; int val3 = 3; //<snippet2> if ((val1 > val2) && (val1 > val3)) { // Take appropriate action. } //</snippet2> //<snippet3> // The following declaration creates a query. It does not run // the query. //</snippet3> // Save snippet 4 and 5 for possible additions in program structure. Name[] nameList = { new Name { FirstName = "Anderson", LastName = "Redmond" }, new Name { FirstName = "Jones", LastName = "Seattle" }, new Name { FirstName = "Anderson", LastName = "Redmond" } }; int n = 0; //<snippet6> string displayName = $"{nameList[n].LastName}, {nameList[n].FirstName}"; //</snippet6> Console.WriteLine("{0}, {1}", nameList[n].LastName, nameList[n].FirstName); Console.WriteLine(nameList[n].LastName + ", " + nameList[n].FirstName); //<snippet7> var phrase = "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala"; var manyPhrases = new StringBuilder(); for (var i = 0; i < 10000; i++) { manyPhrases.Append(phrase); } //Console.WriteLine("tra" + manyPhrases); //</snippet7> //<snippet8> // When the type of a variable is clear from the context, use var // in the declaration. var var1 = "This is clearly a string."; var var2 = 27; var var3 = Convert.ToInt32(Console.ReadLine()); //</snippet8> //<snippet9> // When the type of a variable is not clear from the context, use an // explicit type. int var4 = ExampleClass.ResultSoFar(); //</snippet9> //<snippet10> // Naming the following variable inputInt is misleading. // It is a string. var inputInt = Console.ReadLine(); Console.WriteLine(inputInt); //</snippet10> //<snippet11> var syllable = "ha"; var laugh = ""; for (var i = 0; i < 10; i++) { laugh += syllable; Console.WriteLine(laugh); } //</snippet11> //<snippet12> foreach (var ch in laugh) { if (ch == 'h') { Console.Write("H"); } else { Console.Write(ch); } } Console.WriteLine(); //</snippet12> //<snippet13> // Preferred syntax. Note that you cannot use var here instead of string[]. string[] vowels1 = { "a", "e", "i", "o", "u" }; // If you use explicit instantiation, you can use var. var vowels2 = new string[] { "a", "e", "i", "o", "u" }; // If you specify an array size, you must initialize the elements one at a time. var vowels3 = new string[5]; vowels3[0] = "a"; vowels3[1] = "e"; // And so on. //</snippet13> //<snippet15> // In the Main method, create an instance of Del. // Preferred: Create an instance of Del by using condensed syntax. Del exampleDel2 = DelMethod; // The following declaration uses the full syntax. Del exampleDel1 = new Del(DelMethod); //</snippet15> exampleDel1("Hey"); exampleDel2(" hey"); // #16 is below Main. Console.WriteLine(GetValueFromArray(vowels1, 1)); // 17 requires System.Drawing //<snippet17> // This try-finally statement only calls Dispose in the finally block. Font font1 = new Font("Arial", 10.0f); try { byte charset = font1.GdiCharSet; } finally { if (font1 != null) { ((IDisposable)font1).Dispose(); } } // You can do the same thing with a using statement. using (Font font2 = new Font("Arial", 10.0f)) { byte charset = font2.GdiCharSet; } //</snippet17> //<snippet18> Console.Write("Enter a dividend: "); var dividend = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter a divisor: "); var divisor = Convert.ToInt32(Console.ReadLine()); // If the divisor is 0, the second clause in the following condition // causes a run-time error. The && operator short circuits when the // first expression is false. That is, it does not evaluate the // second expression. The & operator evaluates both, and causes // a run-time error when divisor is 0. if ((divisor != 0) && (dividend / divisor > 0)) { Console.WriteLine("Quotient: {0}", dividend / divisor); } else { Console.WriteLine("Attempted division by 0 ends up here."); } //</snippet18> //<snippet19> var instance1 = new ExampleClass(); //</snippet19> //<snippet20> ExampleClass instance2 = new ExampleClass(); //</snippet20> //<snippet21> // Object initializer. var instance3 = new ExampleClass { Name = "Desktop", ID = 37414, Location = "Redmond", Age = 2.3 }; // Default constructor and assignment statements. var instance4 = new ExampleClass(); instance4.Name = "Desktop"; instance4.ID = 37414; instance4.Location = "Redmond"; instance4.Age = 2.3; //</snippet21> // #22 and #23 are in Coding_Conventions_WF, below. // Save 24 in case we add an exxample to Static Members. ExampleClass.totalInstances = 1; var customers = new List <Customer> { new Customer { Name = "Jones", ID = 432, City = "Redmond" } }; // Check shop name to use this. var distributors = new List <Distributor> { new Distributor { Name = "ShopSmart", ID = 11302, City = "Redmond" } }; //<snippet25> //<snippet28> var seattleCustomers = from customer in customers //</snippet28> where customer.City == "Seattle" select customer.Name; //</snippet25> //<snippet26> var localDistributors = from customer in customers join distributor in distributors on customer.City equals distributor.City select new { Customer = customer, Distributor = distributor }; //</snippet26> //<snippet27> var localDistributors2 = from customer in customers join distributor in distributors on customer.City equals distributor.City select new { CustomerName = customer.Name, DistributorID = distributor.ID }; //</snippet27> //<snippet29> var seattleCustomers2 = from customer in customers where customer.City == "Seattle" orderby customer.Name select customer; //</snippet29> // #30 is in class CompoundFrom var customerDistributorNames = from customer in customers join distributor in distributors on customer.City equals distributor.City select new { CustomerName = customer.Name, DistributorID = distributor.ID }; var customerDistributorNames2 = from customer in customers from distributor in distributors where customer.City == distributor.City select new { CustomerName = customer.Name, DistributorID = distributor.ID }; foreach (var c in customerDistributorNames) { Console.WriteLine(c); } // Could use in Static Members. Console.WriteLine(BaseClass.IncrementTotal()); // Do not do access the static member of the base class through // a derived class. Console.WriteLine(DerivedClass.IncrementTotal()); //// Error //var instance = new ExampleClass(); //Console.WriteLine(instance.IncrementTotal()); }
/// <summary> /// Creates network counter /// </summary> public static SimpleCounter CreateNetworkCounter() { // Créer les contrôles pour chaque interface réseau System.Diagnostics.PerformanceCounterCategory category = new System.Diagnostics.PerformanceCounterCategory("Network Interface"); List<SimpleCounter> counters = new List<SimpleCounter>(); foreach (string instance in category.GetInstanceNames().OrderBy(s => s)) { System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Total/sec", instance, true); PerformanceCounter counter = new PerformanceCounter(pc); counters.Add(new PerformanceCounter(pc)); } return new SumPerformanceCounter(counters); }
/// <summary> /// Create counter list from string /// </summary> /// <param name="counterString">string which represents one or more counters: "\\<machineName>\<categoryName>(<instanceName>)\<counterName>" /// counterName and/or instanceName can have the special value "#ALL#", meaning we want to get all of them</param> /// <returns>list of counters</returns> public static IEnumerable<System.Diagnostics.PerformanceCounter> CreateCountersFromString(string counterString) { string machineName, categoryName, instanceName, counterName; ParseCounterString(counterString, out machineName, out categoryName, out instanceName, out counterName); System.Diagnostics.PerformanceCounterCategory category = new System.Diagnostics.PerformanceCounterCategory(categoryName, machineName); IEnumerable<System.Diagnostics.PerformanceCounter> counters = new System.Diagnostics.PerformanceCounter[] { }; if (counterName == "#ALL#" && instanceName == "#ALL#") { foreach (string instance in category.GetInstanceNames().OrderBy(s => s)) { counters = counters.Concat(category.GetCounters(instance)); } } else if (counterName == "#ALL#") { if (string.IsNullOrEmpty(instanceName)) { counters = category.GetCounters(); } else { counters = category.GetCounters(instanceName); } } else if (instanceName == "#ALL#") { foreach (string instance in category.GetInstanceNames().OrderBy(s => s)) { counters = counters.Concat(new System.Diagnostics.PerformanceCounter[] { new System.Diagnostics.PerformanceCounter(categoryName, counterName, instance, machineName) }); } } else { counters = new System.Diagnostics.PerformanceCounter[] { new System.Diagnostics.PerformanceCounter(categoryName, counterName, instanceName, machineName) }; } // Création des contrôles return counters; }
private void listBox2_SelectedIndexChanged(object sender, EventArgs e) { System.Collections.ArrayList counters = new System.Collections.ArrayList(); if (this.listBox2.SelectedIndex != -1) { System.Diagnostics.PerformanceCounterCategory selectedPerfCat = new System.Diagnostics.PerformanceCounterCategory(this.listBox1.SelectedItem.ToString()); string selectedInstance = this.listBox2.SelectedItem.ToString(); this.listBox3.Items.Clear(); try { counters.AddRange(selectedPerfCat.GetCounters(selectedInstance)); foreach (System.Diagnostics.PerformanceCounter counter in counters) { this.listBox3.Items.Add(counter.CounterName); } } catch (System.Exception ex) { MessageBox.Show("Unable to list the counters for this category:\n" + ex.Message); } } }
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { string[] objectNames; if (this.listBox1.SelectedIndex != -1) { System.Diagnostics.PerformanceCounterCategory selectedPerfCat = new System.Diagnostics.PerformanceCounterCategory(this.listBox1.SelectedItem.ToString()); this.listBox2.Items.Clear(); try { objectNames = selectedPerfCat.GetInstanceNames(); Array.Sort(objectNames); for (int i = 0; i < objectNames.Length; i++) { this.listBox2.Items.Add(objectNames[i]); } } catch (System.Exception ex) { MessageBox.Show("Unable to list the counters for this category:\n" + ex.Message); } } }
//</snippet14b> static void Main(string[] args) { //<snippet1> var currentPerformanceCounterCategory = new System.Diagnostics. PerformanceCounterCategory(); //</snippet1> int val1 = 1; int val2 = 2; int val3 = 3; //<snippet2> if ((val1 > val2) && (val1 > val3)) { // Take appropriate action. } //</snippet2> //<snippet3> // The following declaration creates a query. It does not run // the query. //</snippet3> // Save snippet 4 and 5 for possible additions in program structure. Name[] nameList = { new Name { FirstName = "Anderson", LastName = "Redmond" }, new Name { FirstName = "Jones", LastName = "Seattle" }, new Name { FirstName = "Anderson", LastName = "Redmond" } }; int n = 0; //<snippet6> string displayName = $"{nameList[n].LastName}, {nameList[n].FirstName}"; //</snippet6> Console.WriteLine("{0}, {1}", nameList[n].LastName, nameList[n].FirstName); Console.WriteLine(nameList[n].LastName + ", " + nameList[n].FirstName); //<snippet7> var phrase = "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala"; var manyPhrases = new StringBuilder(); for (var i = 0; i < 10000; i++) { manyPhrases.Append(phrase); } //Console.WriteLine("tra" + manyPhrases); //</snippet7> //<snippet8> var var1 = "This is clearly a string."; var var2 = 27; //</snippet8> //<snippet9> int var3 = Convert.ToInt32(Console.ReadLine()); int var4 = ExampleClass.ResultSoFar(); //</snippet9> //<snippet10> var inputInt = Console.ReadLine(); Console.WriteLine(inputInt); //</snippet10> //<snippet11> var syllable = "ha"; var laugh = ""; for (var i = 0; i < 10; i++) { laugh += syllable; Console.WriteLine(laugh); } //</snippet11> //<snippet12> foreach (char ch in laugh) { if (ch == 'h') { Console.Write("H"); } else { Console.Write(ch); } } Console.WriteLine(); //</snippet12> //<snippet13a> string[] vowels1 = { "a", "e", "i", "o", "u" }; //</snippet13a> //<snippet13b> var vowels2 = new string[] { "a", "e", "i", "o", "u" }; //</snippet13b> //<snippet13c> var vowels3 = new string[5]; vowels3[0] = "a"; vowels3[1] = "e"; // And so on. //</snippet13c> //<snippet15a> ActionExample1("string for x"); ActionExample2("string for x", "string for y"); Console.WriteLine($"The value is {FuncExample1("1")}"); Console.WriteLine($"The sum is {FuncExample2(1, 2)}"); //</snippet15a> //<snippet15b> Del exampleDel2 = DelMethod; exampleDel2("Hey"); //</snippet15b> //<snippet15c> Del exampleDel1 = new Del(DelMethod); exampleDel1("Hey"); //</snippet15c> // #16 is below Main. Console.WriteLine(GetValueFromArray(vowels1, 1)); // 17 requires System.Drawing //<snippet17a> Font font1 = new Font("Arial", 10.0f); try { byte charset = font1.GdiCharSet; } finally { if (font1 != null) { ((IDisposable)font1).Dispose(); } } //</snippet17a> //<snippet17b> using (Font font2 = new Font("Arial", 10.0f)) { byte charset2 = font2.GdiCharSet; } //</snippet17b> //<snippet17c> using Font font3 = new Font("Arial", 10.0f); byte charset3 = font3.GdiCharSet; //</snippet17c> //<snippet18> Console.Write("Enter a dividend: "); int dividend = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter a divisor: "); int divisor = Convert.ToInt32(Console.ReadLine()); if ((divisor != 0) && (dividend / divisor > 0)) { Console.WriteLine("Quotient: {0}", dividend / divisor); } else { Console.WriteLine("Attempted division by 0 ends up here."); } //</snippet18> //<snippet19> var instance1 = new ExampleClass(); //</snippet19> // Can't show `ExampleClass instance1 = new()` because this projet targets net48. //<snippet20> ExampleClass instance2 = new ExampleClass(); //</snippet20> //<snippet21a> var instance3 = new ExampleClass { Name = "Desktop", ID = 37414, Location = "Redmond", Age = 2.3 }; //</snippet21a> //<snippet21b> var instance4 = new ExampleClass(); instance4.Name = "Desktop"; instance4.ID = 37414; instance4.Location = "Redmond"; instance4.Age = 2.3; //</snippet21b> // #22 and #23 are in Coding_Conventions_WF, below. // Save 24 in case we add an example to Static Members. ExampleClass.totalInstances = 1; var customers = new List <Customer> { new Customer { Name = "Jones", ID = 432, City = "Redmond" } }; // Check shop name to use this. var distributors = new List <Distributor> { new Distributor { Name = "ShopSmart", ID = 11302, City = "Redmond" } }; //<snippet25> //<snippet28> var seattleCustomers = from customer in customers //</snippet28> where customer.City == "Seattle" select customer.Name; //</snippet25> //<snippet26> var localDistributors = from customer in customers join distributor in distributors on customer.City equals distributor.City select new { Customer = customer, Distributor = distributor }; //</snippet26> //<snippet27> var localDistributors2 = from customer in customers join distributor in distributors on customer.City equals distributor.City select new { CustomerName = customer.Name, DistributorID = distributor.ID }; //</snippet27> //<snippet29> var seattleCustomers2 = from customer in customers where customer.City == "Seattle" orderby customer.Name select customer; //</snippet29> // #30 is in class CompoundFrom var customerDistributorNames = from customer in customers join distributor in distributors on customer.City equals distributor.City select new { CustomerName = customer.Name, DistributorID = distributor.ID }; var customerDistributorNames2 = from customer in customers from distributor in distributors where customer.City == distributor.City select new { CustomerName = customer.Name, DistributorID = distributor.ID }; foreach (var c in customerDistributorNames) { Console.WriteLine(c); } // Could use in Static Members. Console.WriteLine(BaseClass.IncrementTotal()); // Do not do access the static member of the base class through // a derived class. Console.WriteLine(DerivedClass.IncrementTotal()); //// Error //var instance = new ExampleClass(); //Console.WriteLine(instance.IncrementTotal()); }
private List <IISAppPoolStateInfo> AppPoolStatesIIS7Plus(string hostName) { List <IISAppPoolStateInfo> appPools = new List <IISAppPoolStateInfo>(); try { if (UsePerfCounter && System.Diagnostics.PerformanceCounterCategory.Exists("APP_POOL_WAS", hostName)) { //Try performance counters System.Diagnostics.PerformanceCounterCategory pcCat = new System.Diagnostics.PerformanceCounterCategory("APP_POOL_WAS", hostName); //getting instance names string[] instances = pcCat.GetInstanceNames(); foreach (string instanceName in instances) { if (instanceName != "_Total") { System.Diagnostics.PerformanceCounter pc = (from pcCacheEntry in pcCatCache where pcCacheEntry.InstanceName == instanceName select pcCacheEntry).FirstOrDefault(); if (pc == null) { pc = new System.Diagnostics.PerformanceCounter("APP_POOL_WAS", "Current Application Pool State", instanceName, hostName); pcCatCache.Add(pc); } float value = pc.NextValue(); IISAppPoolStateInfo appPool = new IISAppPoolStateInfo() { DisplayName = instanceName }; appPool.Status = ReadAppPoolStateFromPCValue(value); appPools.Add(appPool); } } } else { using (WebAdmin.ServerManager serverManager = WebAdmin.ServerManager.OpenRemote(hostName)) { foreach (var pool in serverManager.ApplicationPools) { IISAppPoolStateInfo appPool = new IISAppPoolStateInfo() { DisplayName = pool.Name }; appPool.Status = (AppPoolStatus)pool.State; appPools.Add(appPool); } } } } //catch (UnauthorizedAccessException unauthEx) //{ // appPools = new List<IISAppPoolStateInfo>(); // //Try performance counters // System.Diagnostics.PerformanceCounterCategory pcCat = new System.Diagnostics.PerformanceCounterCategory("APP_POOL_WAS", hostName); // //getting instance names // string[] instances = pcCat.GetInstanceNames(); // foreach (string instanceName in instances) // { // System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("APP_POOL_WAS", "Current Application Pool State", instanceName, hostName); // float value = pc.NextValue(); // IISAppPoolStateInfo appPool = new IISAppPoolStateInfo() { DisplayName = instanceName }; // appPool.Status = ReadAppPoolStateFromPCValue(value); // appPools.Add(appPool); // } //} catch (Exception ex) { if (ex is UnauthorizedAccessException) { throw new Exception("Using ServiceManager class on local machine requires elevated rights. Please run this collector in a process that runs in 'Admin mode'"); } else if (ex.Message.Contains("80040154")) { throw new Exception(string.Format("ServiceManager class not supported on {0}", hostName)); } else if (ex.Message.Contains("800706ba")) { throw new Exception("Firewall blocking ServiceManager call. Please add OAB exception"); } else { throw; } } return(appPools); }
/// <summary> /// Creates CPU percentage of max frequency counter /// </summary> public static SimpleCounter CreateCPUFrequencyCounter() { // Créer un compteur par CPU System.Diagnostics.PerformanceCounterCategory category = new System.Diagnostics.PerformanceCounterCategory("ProcessorPerformance"); SimpleCounter mainCounter = null; List<SimpleCounter> counters = new List<SimpleCounter>(); foreach (string instance in category.GetInstanceNames().OrderBy(s => s)) { System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("ProcessorPerformance", "percentage", instance, true); SimpleCounter counter = new KnownMaxPerformanceCounter(new PerformanceCounter(pc), new StaticPerformanceCounter(100)); counters.Add(counter); } mainCounter = new SumPerformanceCounter(counters); return new SubPerformanceCounter(mainCounter, counters); }
private static void GetBytesSentReceivedCounters(string[] args, string[] hosts, int nThreads, int nReads, int sleep) { DateTime startTime = DateTime.Now; Dictionary <string, float> dtSent = new Dictionary <string, float>(); Dictionary <string, float> dtReceived = new Dictionary <string, float>(); MySpace.DataMining.Threading.ThreadTools <string> .Parallel( new Action <string>( delegate(string slave) { if (string.Compare(slave, "localhost", true) == 0) { slave = System.Net.Dns.GetHostName(); } List <System.Diagnostics.PerformanceCounter> received = new List <System.Diagnostics.PerformanceCounter>(); List <System.Diagnostics.PerformanceCounter> sent = new List <System.Diagnostics.PerformanceCounter>(); lock (dtSent) { Console.WriteLine(); Console.WriteLine("Waiting to connect: {0}", slave); } System.Diagnostics.PerformanceCounterCategory cat = new System.Diagnostics.PerformanceCounterCategory("Network Interface", slave); string[] instances = cat.GetInstanceNames(); try { foreach (string s in instances) { if (s.ToLower().IndexOf("loopback") == -1) { received.Add(new System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Received/sec", s, slave)); sent.Add(new System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Sent/sec", s, slave)); } } lock (dtSent) { Console.WriteLine(); Console.WriteLine("Connected: {0}", slave); } //Initial reading. foreach (System.Diagnostics.PerformanceCounter pc in received) { pc.NextValue(); } foreach (System.Diagnostics.PerformanceCounter pc in sent) { pc.NextValue(); } float br = 0; float bs = 0; for (int i = 0; i < nReads; i++) { System.Threading.Thread.Sleep(sleep); foreach (System.Diagnostics.PerformanceCounter pc in received) { br += pc.NextValue(); } foreach (System.Diagnostics.PerformanceCounter pc in sent) { bs += pc.NextValue(); } } if (nReads > 1) { br = br / (float)nReads; bs = bs / (float)nReads; } lock (dtSent) { Console.WriteLine(); Console.WriteLine("Received {0}: {1}/s", slave, AELight.GetFriendlyByteSize((long)br)); Console.WriteLine("Sent {0}: {1}/s", slave, AELight.GetFriendlyByteSize((long)bs)); dtSent.Add(slave, bs); } lock (dtReceived) { dtReceived.Add(slave, br); } } catch (Exception e) { lock (dtSent) { Console.Error.WriteLine("Error while reading counter: {0}: {1}", slave, e.Message); } } } ), hosts, nThreads); //Write out total sent, received. double totalSent = 0; double totalReceived = 0; foreach (float f in dtSent.Values) { totalSent += f; } foreach (float f in dtReceived.Values) { totalReceived += f; } Console.WriteLine(); Console.WriteLine("Total Received: {0}/s", AELight.GetFriendlyByteSize((long)totalReceived)); Console.WriteLine("Total Sent: {0}/s", AELight.GetFriendlyByteSize((long)totalSent)); //Sort List <KeyValuePair <string, float> > sSent = new List <KeyValuePair <string, float> >(dtSent); sSent.Sort(CompareFloat); List <KeyValuePair <string, float> > sReceived = new List <KeyValuePair <string, float> >(dtReceived); sReceived.Sort(CompareFloat); //Max, min Console.WriteLine(); Console.WriteLine("Min Received: {0} {1}/s", sReceived[0].Key, AELight.GetFriendlyByteSize((long)sReceived[0].Value)); Console.WriteLine("Min Sent: {0} {1}/s", sSent[0].Key, AELight.GetFriendlyByteSize((long)sSent[0].Value)); Console.WriteLine("Max Received: {0} {1}/s", sReceived[sReceived.Count - 1].Key, AELight.GetFriendlyByteSize((long)sReceived[sReceived.Count - 1].Value)); Console.WriteLine("Max Sent: {0} {1}/s", sSent[sSent.Count - 1].Key, AELight.GetFriendlyByteSize((long)sSent[sSent.Count - 1].Value)); //Avg double avgSent = totalSent / (double)sSent.Count; double avgReceived = totalReceived / (double)sReceived.Count; Console.WriteLine(); Console.WriteLine("Avg Received: {0}/s", AELight.GetFriendlyByteSize((long)avgReceived)); Console.WriteLine("Avg Sent: {0}/s", AELight.GetFriendlyByteSize((long)avgSent)); //Dt Console.WriteLine(); Console.WriteLine("Perfmon Request Time: {0}", startTime.ToString()); Console.WriteLine("Perfmon End Time: {0}", DateTime.Now.ToString()); }
private int GetCounters(string[] hosts) { dtSent.Clear(); dtReceived.Clear(); int error = 0; QueryAnalyzer_ADOTrafficMonitor.ThreadTools<string>.Parallel( new Action<string>( delegate(string slave) { if (string.Compare(slave, "localhost", true) == 0) { slave = System.Net.Dns.GetHostName(); } List<System.Diagnostics.PerformanceCounter> received = new List<System.Diagnostics.PerformanceCounter>(); List<System.Diagnostics.PerformanceCounter> sent = new List<System.Diagnostics.PerformanceCounter>(); try { System.Diagnostics.PerformanceCounterCategory cat = new System.Diagnostics.PerformanceCounterCategory("Network Interface", slave); string[] instances = cat.GetInstanceNames(); foreach (string s in instances) { if (s.ToLower().IndexOf("loopback") == -1) { received.Add(new System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Received/sec", s, slave)); sent.Add(new System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Sent/sec", s, slave)); } } //Initial reading. foreach (System.Diagnostics.PerformanceCounter pc in received) { pc.NextValue(); } foreach (System.Diagnostics.PerformanceCounter pc in sent) { pc.NextValue(); } lock (dtSent) { dtSent.Add(slave, sent); dtReceived.Add(slave, received); } } catch (Exception e) { AppendStatusText(txtStatus, "Text", "Error while getting counter from " + slave + ". Error: " + e.ToString()); System.Threading.Interlocked.Increment(ref error); } } ), hosts, hosts.Length); return error; }
private static void GetBytesSentReceivedCounters(string[] args, string[] hosts, int nThreads, int nReads, int sleep) { DateTime startTime = DateTime.Now; Dictionary<string, float> dtSent = new Dictionary<string, float>(); Dictionary<string, float> dtReceived = new Dictionary<string, float>(); MySpace.DataMining.Threading.ThreadTools<string>.Parallel( new Action<string>( delegate(string slave) { if (string.Compare(slave, "localhost", true) == 0) { slave = System.Net.Dns.GetHostName(); } List<System.Diagnostics.PerformanceCounter> received = new List<System.Diagnostics.PerformanceCounter>(); List<System.Diagnostics.PerformanceCounter> sent = new List<System.Diagnostics.PerformanceCounter>(); lock (dtSent) { Console.WriteLine(); Console.WriteLine("Waiting to connect: {0}", slave); } System.Diagnostics.PerformanceCounterCategory cat = new System.Diagnostics.PerformanceCounterCategory("Network Interface", slave); string[] instances = cat.GetInstanceNames(); try { foreach (string s in instances) { if (s.ToLower().IndexOf("loopback") == -1) { received.Add(new System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Received/sec", s, slave)); sent.Add(new System.Diagnostics.PerformanceCounter("Network Interface", "Bytes Sent/sec", s, slave)); } } lock (dtSent) { Console.WriteLine(); Console.WriteLine("Connected: {0}", slave); } //Initial reading. foreach (System.Diagnostics.PerformanceCounter pc in received) { pc.NextValue(); } foreach (System.Diagnostics.PerformanceCounter pc in sent) { pc.NextValue(); } float br = 0; float bs = 0; for (int i = 0; i < nReads; i++) { System.Threading.Thread.Sleep(sleep); foreach (System.Diagnostics.PerformanceCounter pc in received) { br += pc.NextValue(); } foreach (System.Diagnostics.PerformanceCounter pc in sent) { bs += pc.NextValue(); } } if (nReads > 1) { br = br / (float)nReads; bs = bs / (float)nReads; } lock (dtSent) { Console.WriteLine(); Console.WriteLine("Received {0}: {1}/s", slave, AELight.GetFriendlyByteSize((long)br)); Console.WriteLine("Sent {0}: {1}/s", slave, AELight.GetFriendlyByteSize((long)bs)); dtSent.Add(slave, bs); } lock (dtReceived) { dtReceived.Add(slave, br); } } catch (Exception e) { lock (dtSent) { Console.Error.WriteLine("Error while reading counter: {0}: {1}", slave, e.Message); } } } ), hosts, nThreads); //Write out total sent, received. double totalSent = 0; double totalReceived = 0; foreach (float f in dtSent.Values) { totalSent += f; } foreach (float f in dtReceived.Values) { totalReceived += f; } Console.WriteLine(); Console.WriteLine("Total Received: {0}/s", AELight.GetFriendlyByteSize((long)totalReceived)); Console.WriteLine("Total Sent: {0}/s", AELight.GetFriendlyByteSize((long)totalSent)); //Sort List<KeyValuePair<string, float>> sSent = new List<KeyValuePair<string, float>>(dtSent); sSent.Sort(CompareFloat); List<KeyValuePair<string, float>> sReceived = new List<KeyValuePair<string, float>>(dtReceived); sReceived.Sort(CompareFloat); //Max, min Console.WriteLine(); Console.WriteLine("Min Received: {0} {1}/s", sReceived[0].Key, AELight.GetFriendlyByteSize((long)sReceived[0].Value)); Console.WriteLine("Min Sent: {0} {1}/s", sSent[0].Key, AELight.GetFriendlyByteSize((long)sSent[0].Value)); Console.WriteLine("Max Received: {0} {1}/s", sReceived[sReceived.Count - 1].Key, AELight.GetFriendlyByteSize((long)sReceived[sReceived.Count - 1].Value)); Console.WriteLine("Max Sent: {0} {1}/s", sSent[sSent.Count - 1].Key, AELight.GetFriendlyByteSize((long)sSent[sSent.Count - 1].Value)); //Avg double avgSent = totalSent / (double)sSent.Count; double avgReceived = totalReceived / (double)sReceived.Count; Console.WriteLine(); Console.WriteLine("Avg Received: {0}/s", AELight.GetFriendlyByteSize((long)avgReceived)); Console.WriteLine("Avg Sent: {0}/s", AELight.GetFriendlyByteSize((long)avgSent)); //Dt Console.WriteLine(); Console.WriteLine("Perfmon Request Time: {0}", startTime.ToString()); Console.WriteLine("Perfmon End Time: {0}", DateTime.Now.ToString()); }