/// <summary> /// Return Download Speed in MBs /// </summary> /// <param name="lInstance">Network Interface ID</param> /// <param name="lDelay">Delay in seconds for more precision</param> /// <returns></returns> public static float GetDownloadSpeed(int lInstance = 1, int lDelay = 1) { PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface"); string networkInstance = performanceCounterCategory.GetInstanceNames()[lInstance]; PerformanceCounter performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", networkInstance); performanceCounterReceived.NextValue(); Thread.Sleep(lDelay * 1000); float downloadSpeed = performanceCounterReceived.NextValue() / (1024f * 1024f); return downloadSpeed; }
private void TryToInitializeCounters() { if (!countersInitialized) { PerformanceCounterCategory category = new PerformanceCounterCategory(".NET CLR Networking 4.0.0.0"); var instanceNames = category.GetInstanceNames().Where(i => i.Contains(string.Format("p{0}", pid))); if (instanceNames.Any()) { bytesSentPerformanceCounter = new PerformanceCounter(); bytesSentPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0"; bytesSentPerformanceCounter.CounterName = "Bytes Sent"; bytesSentPerformanceCounter.InstanceName = instanceNames.First(); bytesSentPerformanceCounter.ReadOnly = true; bytesReceivedPerformanceCounter = new PerformanceCounter(); bytesReceivedPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0"; bytesReceivedPerformanceCounter.CounterName = "Bytes Received"; bytesReceivedPerformanceCounter.InstanceName = instanceNames.First(); bytesReceivedPerformanceCounter.ReadOnly = true; countersInitialized = true; } } }
private static void EnumerateCountersFor(string category, string instance) { var sb = new StringBuilder(); var counterCategory = new PerformanceCounterCategory(category); foreach (var counter in counterCategory.GetCounters(instance)) { sb.AppendLine(string.Format("{0}:{1}:{2}", instance, category, counter.CounterName)); } Console.WriteLine(sb.ToString()); }
private void InitializePerfCounter() { string computername = "."; if (Computer != "" && Computer.ToLower() != "localhost") { computername = Computer; } if (InstanceValueAggregationStyle == AggregationStyle.None) { pc = new PerformanceCounter(Category, Counter, Instance, computername); pc.NextValue(); pcList.Add(pc); } else { PerformanceCounterCategory pcCat = new PerformanceCounterCategory(Category, computername); if (pcCat.CategoryType == PerformanceCounterCategoryType.MultiInstance) { string[] instances = pcCat.GetInstanceNames(); foreach (string instanceNameItem in (from string s in instances orderby s select s)) { PerformanceCounter pci = new PerformanceCounter(Category, Counter, instanceNameItem, computername); float tmpval = pci.NextValue(); pcList.Add(pci); } } else { pc = new PerformanceCounter(Category, Counter, Instance, computername); pc.NextValue(); pcList.Add(pc); } } }
/// <summary> /// /// </summary> private void CreatePerformanceCounters() { try { if (PerformanceCounterCategory.Exists(WebConfig.PerformanceCounterCategoryName)) { PerformanceCounterCategory.Delete(WebConfig.PerformanceCounterCategoryName); } CounterCreationDataCollection Counters = new CounterCreationDataCollection(); CounterCreationData CounterData = new CounterCreationData(); CounterData.CounterName = "Total SQL Statements"; CounterData.CounterHelp = ""; CounterData.CounterType = PerformanceCounterType.NumberOfItems64; Counters.Add(CounterData); CounterData = new CounterCreationData(); CounterData.CounterName = "Total Milliseconds"; CounterData.CounterHelp = ""; CounterData.CounterType = PerformanceCounterType.NumberOfItems64; Counters.Add(CounterData); PerformanceCounterCategory.Create(WebConfig.PerformanceCounterCategoryName, WebConfig.PerformanceCounterCategoryName, PerformanceCounterCategoryType.Unknown, Counters); counterTotalStatements = new PerformanceCounter(WebConfig.PerformanceCounterCategoryName, "Total SQL Statements", false); counterTotalTime = new PerformanceCounter(WebConfig.PerformanceCounterCategoryName, "Total Milliseconds", false); counterTotalStatements.RawValue = 0; counterTotalTime.RawValue = 0; } catch (Exception exp) { Logger.Error(ErrorMessageResID.DBServiceCreatePerformanceCountersFailed, exp); } }
private void InitializePerformanceCounters() { try { string instanceName = null; var category = new PerformanceCounterCategory("Process"); var names = category.GetInstanceNames(); foreach (var name in names) { using (var counter = new PerformanceCounter("Process", "ID Process", name, true)) { if (Pid == (int)counter.RawValue) { instanceName = name; break; } } } if (instanceName != null) { _committedBytesCounter = new PerformanceCounter( ".NET CLR Memory", "# Total committed Bytes", instanceName); _countersInitialized = true; } else { Logger.Warn("Unable to determine process instance name for committed CLR bytes performanc counter"); } } catch (Exception e) { Logger.Warn("Error initializing committed CLR bytes counter: " + e.Message); } }
private static bool SetupCategory() { if (!PerformanceCounterCategory.Exists("RateOfCountsPerSecond64SampleCategory")) { CounterCreationDataCollection CCDC = new CounterCreationDataCollection(); // Add the counter. CounterCreationData rateOfCounts64 = new CounterCreationData(); rateOfCounts64.CounterType = PerformanceCounterType.RateOfCountsPerSecond64; rateOfCounts64.CounterName = "RateOfCountsPerSecond64Sample"; CCDC.Add(rateOfCounts64); // Create the category. PerformanceCounterCategory.Create("RateOfCountsPerSecond64SampleCategory", "Demonstrates usage of the RateOfCountsPerSecond64 performance counter type.", PerformanceCounterCategoryType.SingleInstance, CCDC); return(true); } else { Console.WriteLine("Category exists - RateOfCountsPerSecond64SampleCategory"); return(false); } }
/// <summary> /// Gets the instance for a particular process /// </summary> /// <param name="processId">Process value</param> /// <returns></returns> public static string GetInstanceNameForProcessId(int processId) { var process = Process.GetProcessById(processId); var processName = Path.GetFileNameWithoutExtension(process.ProcessName); var cat = new PerformanceCounterCategory("Process"); var instances = cat.GetInstanceNames() .Where(inst => inst.StartsWith(processName)) .ToArray(); foreach (var instance in instances) { using (PerformanceCounter cnt = new PerformanceCounter("Process", "ID Process", instance, true)) { var val = (int)cnt.RawValue; if (val == processId) { return(instance); } } } return(null); }
private PerformanceCounter TryCreateCounter(string name) { if (!IsInitialized) { throw new InvalidOperationException("This PerfCounter instance has not been initialized"); } try { if (!PerformanceCounterCategory.Exists(CategoryName)) { // the category doesn't exist. This means that the counters were never installed, or previous errors have occurred. return(null); } if (!PerformanceCounterCategory.CounterExists(name, CategoryName)) { // the category exists, but the counter does not. return(null); } return(new PerformanceCounter(CategoryName, name, InstanceName, false)); } catch (InvalidOperationException ioex) { // Counter not installed. Log.DebugFormat( "PerfCounter {0} of {1} in {2} could not be initialized, and will not be available. {3}", name, InstanceName, CategoryName, ioex); } catch (UnauthorizedAccessException uae) { // if the account doesn't have privileges to use counters, this exception is thrown. The account has to be in the // Perfmormance Monitor Users group or be admin. Log.DebugFormat("The process does not have the privilege to initialze PerfCounter {0} of {1} in {2}. {3}", name, InstanceName, CategoryName, uae); } return(null); }
public bool IsPerformanceCounterReady() { try { PerformanceCounter PC = new PerformanceCounter(); string strCategoryName; strCategoryName = "Processor"; if (PerformanceCounterCategory.Exists(strCategoryName)) { return(true); } else { return(false); } } catch (Exception ex) { WSPEvent.WriteEvent("Performace category can't be read in this system. - " + ex.Message, "E", 1133); return(false); } }
public static void CreateCategory(IICPerformanceCountersAttribute categoryAttr, IEnumerable <IICPerformanceCounter> counters) { CounterCreationDataCollection ccdc = new CounterCreationDataCollection(); foreach (IICPerformanceCounter counter in counters) { CounterCreationData ccd = new CounterCreationData(); ccd.CounterType = counter._rawAttr.CounterType; ccd.CounterName = counter._rawAttr.CounterName; ccd.CounterHelp = counter._rawAttr.CounterHelp; ccdc.Add(ccd); if (counter._baseAttr != null) { CounterCreationData baseCcd = new CounterCreationData(); baseCcd.CounterType = counter._baseAttr.CounterType; baseCcd.CounterName = counter._baseAttr.CounterName; baseCcd.CounterHelp = counter._baseAttr.CounterHelp; ccdc.Add(baseCcd); } } PerformanceCounterCategory.Create(categoryAttr.CategoryName, categoryAttr.CategoryHelp, categoryAttr.CategoryType, ccdc); }
private static string GetPerformanceCounterInstanceName(int pid) { PerformanceCounterCategory cat = new PerformanceCounterCategory("Process"); string[] instances = cat.GetInstanceNames(); string name = null; foreach (string i in instances) { // Check if the current instance name correspond to the performance counter // of the wanted process using (PerformanceCounter cnt = new PerformanceCounter("Process", "ID Process", i, true)) { int rawValue = 0; try { rawValue = (int)cnt.RawValue; } catch (InvalidOperationException) { // A problem occured when trying to get read the value of the current // performance counter ... continue; } if (rawValue == pid) { name = i; break; } } } // If the instance name is null that means there no performance counter // instance name for current process. This is truly strange ... return(name); }
public void BenchmarkTest() { var process = Process.GetCurrentProcess(); NTStopwatch.Start(); // 这个太慢 PerformanceCounterCategory cat = new PerformanceCounterCategory("Process"); // 同一个程序如果运行多次,对应的多个进程名称是通过后缀#1、#2、#3...区分的 string[] instanceNames = cat.GetInstanceNames().Where(a => a.StartsWith(process.ProcessName)).ToArray(); var elapsedMilliseconds = NTStopwatch.Stop(); Console.WriteLine(elapsedMilliseconds); NTStopwatch.Start(); for (int i = 0; i < 100; i++) { cat = new PerformanceCounterCategory("Process"); // 同一个程序如果运行多次,对应的多个进程名称是通过后缀#1、#2、#3...区分的 instanceNames = cat.GetInstanceNames().Where(a => a.StartsWith(process.ProcessName)).ToArray(); } elapsedMilliseconds = NTStopwatch.Stop(); Console.WriteLine(elapsedMilliseconds); }
private void BDeleteClick(object sender, EventArgs e) { try { Cursor = Cursors.WaitCursor; lbExists.DataSource = null; PerformanceCounterCategory.Delete(tbGroupName.Text); bDelete.Enabled = false; bCreate.Enabled = true; gbExists.Enabled = false; gbAddNew.Enabled = false; } catch (Exception ex) { MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { Cursor = DefaultCursor; } }
public CpuLoad(int interval = 1000) { _performanceCounter = new PerformanceCounter("Processor Information", "% Processor Time"); var performanceCounterCategory = new PerformanceCounterCategory("Processor Information"); _instances = performanceCounterCategory.GetInstanceNames(); _counterSamples = new Dictionary <string, CounterSample>(); foreach (var s in _instances) { _performanceCounter.InstanceName = s; _counterSamples.Add(s, _performanceCounter.NextSample()); } _updateTimer = new Timer { AutoReset = true, Interval = interval }; _updateTimer.Elapsed += UpdateTimerOnElapsed; _updateTimer.Start(); }
//performan counters to check how the code are working static void Main3(string[] args) { if (PerformanceCounterCategory.Exists("Flowerhub Orders")) { Console.WriteLine("La categoria ya existe"); } else { CounterCreationDataCollection counter = new CounterCreationDataCollection(); CounterCreationData webOrders = new CounterCreationData(); webOrders.CounterHelp = "Total order numbers from the web form app"; webOrders.CounterName = "Web Orders"; webOrders.CounterType = PerformanceCounterType.NumberOfItems32; counter.Add(webOrders); CounterCreationData cloudOrders = new CounterCreationData(); cloudOrders.CounterHelp = "Total order numbers from the cloud web app"; cloudOrders.CounterName = "Cloud Orders"; cloudOrders.CounterType = PerformanceCounterType.NumberOfItems32; counter.Add(cloudOrders); PerformanceCounterCategory.Create("Flowerhub Orders", "Flowerhub orders counters", PerformanceCounterCategoryType.SingleInstance, counter); Console.WriteLine("La categoria fue creada"); } }
private void TrackContextSwitches() { #if !NETSTANDARD_TODO // TODO: this temporary exclusion should be resolved by #2147 PerformanceCounterCategory allThreadsWithPerformanceCounters = new PerformanceCounterCategory("Thread"); PerformanceCounter[] performanceCountersForThisThread = null; // Iterate over all "Thread" category performance counters on system (includes numerous processes) foreach (string threadName in allThreadsWithPerformanceCounters.GetInstanceNames()) { // Obtain those performance counters for the OrleansHost if (threadName.Contains("OrleansHost") && threadName.EndsWith("/" + Thread.CurrentThread.ManagedThreadId)) { performanceCountersForThisThread = allThreadsWithPerformanceCounters.GetCounters(threadName); break; } } // In the case that the performance was not obtained correctly (this condition is null), we simply will not have stats for context switches if (performanceCountersForThisThread == null) { return; } // Look at all performance counters for this thread foreach (PerformanceCounter performanceCounter in performanceCountersForThisThread) { // Find performance counter for context switches if (performanceCounter.CounterName == CONTEXT_SWTICH_COUNTER_NAME) { // Use raw value for logging, should show total context switches FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.THREADS_CONTEXT_SWITCHES, Name), () => (float)performanceCounter.RawValue, CounterStorage.LogOnly); } } #endif }
private static string GetPerformanceCounterInstanceName(Process process) { var processId = process.Id; var processCategory = new PerformanceCounterCategory("Process"); var runnedInstances = processCategory.GetInstanceNames(); foreach (string runnedInstance in runnedInstances) { if (!runnedInstance.StartsWith(process.ProcessName, StringComparison.OrdinalIgnoreCase)) { continue; } using (var performanceCounter = new PerformanceCounter("Process", "ID Process", runnedInstance, true)) { if ((int)performanceCounter.RawValue == processId) { return(runnedInstance); } } } return(process.ProcessName); }
public DiskActivity(int interval = 1000) { _performanceCounter = new PerformanceCounter("PhysicalDisk", "% Idle Time"); var performanceCounterCategory = new PerformanceCounterCategory("PhysicalDisk"); _instances = performanceCounterCategory.GetInstanceNames(); _counterSamples = new Dictionary <string, CounterSample>(); foreach (var s in _instances) { _performanceCounter.InstanceName = s; _counterSamples.Add(s, _performanceCounter.NextSample()); } _updateTimer = new Timer { AutoReset = true, Interval = interval }; _updateTimer.Elapsed += UpdateTimerOnElapsed; _updateTimer.Start(); }
/// <summary> /// Creates performance counter category and cache performance counters /// </summary> public static void CreateCounters(PerformanceCounterCategoryMetadata category) { try { if (!PerformanceCounterCategory.Exists(category.Name)) { CounterCreationDataCollection counterCollection = new CounterCreationDataCollection(); foreach (var description in category.Counters) { var counter = new CounterCreationData(); counter.CounterName = description.Name; counter.CounterHelp = description.Description; counter.CounterType = description.Type; counterCollection.Add(counter); } PerformanceCounterCategory.Create(category.Name, category.Description, PerformanceCounterCategoryType.SingleInstance, counterCollection); Log.Debug("{0} counter category Created", category.Name); } } catch (Exception ex) { Log.Warn("Instrumentation.CreateCounters failed, performance counters may not be initialised. Error: {0}", ex.FullMessage()); } }
public void Initialize(IFrozenContext frozenCtx) { if (!PerformanceCounterCategory.Exists(Category)) { initialized = false; Logging.Log.Warn("PerfCounters are not installed, execute 'sudo Zetbox.*.exe -installperfcounter'"); return; } try { foreach (var desc in _counterDescs.Concat(CounterDesciptors).Concat(_methodDescs.Concat(MethodCounterDesciptors).SelectMany(desc => desc.CreateDescriptors()))) { desc.Set(this); } initialized = true; } catch (Exception ex) { Logging.Log.Error("Unable to initialize PerfCounters", ex); initialized = false; } }
public static Boolean Create(Category cat) { try { //deshabilitar cuando esten bien definidos los nombres de los Performance Counters if (PerformanceCounterCategory.Exists(cat.CategoryName)) { PerformanceCounterCategory.Delete(cat.CategoryName); } if (!PerformanceCounterCategory.Exists(cat.CategoryName)) { PerformanceCounterCategory.Create(cat.CategoryName, String.Empty, PerformanceCounterCategoryType.SingleInstance, cat.Counters); } return(true); } catch (Exception e) { STrace.Exception(typeof(PerformanceCounterHelper).FullName, e); //Console.ReadLine(); return(false); } }
/// <summary> /// This method finds the process counter instance by process ID. /// </summary> /// <param name="processName"></param> /// <param name="processId"></param> /// <param name="remotehost"></param> /// <returns></returns> private string GetInstanceNameForProcessId(string processName, int processId, string remotehost) { string result = string.Empty; try { // Create the appropriate PerformanceCounterCategory object. PerformanceCounterCategory cat = new PerformanceCounterCategory("Process", remotehost); // Get the instances associated with this category. string[] instances = cat.GetInstanceNames() .Where(inst => inst.StartsWith(processName)) .ToArray(); foreach (string instance in instances) { // CategoryName, InstanceCounterName, instance, remotehost using (PerformanceCounter cnt = new PerformanceCounter("Process", "ID Process", instance, remotehost)) { int val = (int)cnt.RawValue; if (val == processId) { return(instance); } } } } catch (Exception e) { result = "Exception occured in an attempt to get the performce data of the instance for the " + processId + ": " + e.Message; } if (!string.IsNullOrEmpty(result)) { Log.Debug(result); } return(null); }
static Counters() { var enabled = false; var expensiveEnabled = false; #if NET45 || NET451 try { enabled = PerformanceCounterCategory.Exists(Counter.DiagnosticsCounterCategory); var perfCtrSwitch = new TraceSwitch("ConnectionPoolPerformanceCounterDetail", "level of detail to track with connection pool performance counters"); expensiveEnabled = enabled && perfCtrSwitch.Level == TraceLevel.Verbose; } catch (Exception e) { Log.Logger.LogDebug("Exception while checking for performance counter category (counters will be disabled)", e); } #endif try { HardConnectsPerSecond = new Counter(enabled, nameof(HardConnectsPerSecond)); HardDisconnectsPerSecond = new Counter(enabled, nameof(HardDisconnectsPerSecond)); NumberOfActiveConnectionPools = new Counter(enabled, nameof(NumberOfActiveConnectionPools)); NumberOfNonPooledConnections = new Counter(enabled, nameof(NumberOfNonPooledConnections)); NumberOfPooledConnections = new Counter(enabled, nameof(NumberOfPooledConnections)); SoftConnectsPerSecond = new Counter(expensiveEnabled, nameof(SoftConnectsPerSecond)); SoftDisconnectsPerSecond = new Counter(expensiveEnabled, nameof(SoftDisconnectsPerSecond)); NumberOfActiveConnections = new Counter(expensiveEnabled, nameof(NumberOfActiveConnections)); NumberOfFreeConnections = new Counter(expensiveEnabled, nameof(NumberOfFreeConnections)); } catch (Exception e) { Log.Logger.LogDebug("Exception while setting up performance counter (counters will be disabled)", e); } }
public static void CreateCounters() { if (!PerformanceCounterCategory.Exists("Contoso")) { var counters = new CounterCreationDataCollection(); var ccdCounter1 = new CounterCreationData { CounterName = "Counter1", CounterType = PerformanceCounterType.AverageTimer32 }; counters.Add(ccdCounter1); var ccdCounter2 = new CounterCreationData { CounterName = "Counter2", CounterType = PerformanceCounterType.AverageBase }; counters.Add(ccdCounter2); PerformanceCounterCategory.Create("Contoso", "Help string", PerformanceCounterCategoryType.MultiInstance, counters); } }
private void SetupPreformanceCounterName(string name) { //For databases that has a long name if (CountersNames.ContainsKey(name)) { return; } string result = name; //dealing with names who are very long (there is a limit of 80 chars for counter name) if (result.Length > 60) { result = name.Remove(59); int counter = 1; while (PerformanceCounterCategory.Exists("RavenDB 2.0: " + result + counter)) { counter++; } result = result + counter; } CountersNames.Add(name, result); }
private static bool CreatePerformanceCounters() { if (!PerformanceCounterCategory.Exists("MyCategory")) { CounterCreationDataCollection counters = new CounterCreationDataCollection { new CounterCreationData( "# operations executed", "Total number of operations executed", PerformanceCounterType.NumberOfItems32), new CounterCreationData( "# operations / sec", "Number of operations executed per second", PerformanceCounterType.RateOfCountsPerSecond32) }; PerformanceCounterCategory.Create( "MyCategory", "Sample category for Codeproject", PerformanceCounterCategoryType.SingleInstance, counters); return(true); } return(false); }
private static bool CreatePerformanceCounters() { if (!PerformanceCounterCategory.Exists("MyCategory")) { CounterCreationDataCollection counters = new CounterCreationDataCollection { new CounterCreationData( "#�operations�executed", "Total�number�of�operations�executed", PerformanceCounterType.NumberOfItems32), new CounterCreationData( "#�operations�/�sec", "Number�of�operations�executed�per�second", PerformanceCounterType.RateOfCountsPerSecond32) }; PerformanceCounterCategory.Create( "MyCategory", "Sample�category�for�Codeproject", counters); return(true); } return(false); }
public static void RefreshInstances() { _pidToInstance.Clear(); const string processCategory = "Process"; var cat = new PerformanceCounterCategory(processCategory); string[] instances = cat.GetInstanceNames(); foreach (string instance in instances) { try { using (var cnt = new PerformanceCounter(processCategory, "ID Process", instance, true)) { int val = (int)cnt.RawValue; if (!_pidToInstance.ContainsKey(val)) { _pidToInstance.Add(val, instance); } } } catch { } } }
/// <summary> /// Installs performance counters in the current assembly using PerfItFilterAttribute. /// </summary> /// <param name="installerAssembly"></param> /// <param name="categoryName">category name for the metrics. If not provided, it will use the assembly name</param> public static void Install(Assembly installerAssembly, string categoryName = null) { if (string.IsNullOrEmpty(categoryName)) { categoryName = installerAssembly.GetName().Name; } Uninstall(installerAssembly, categoryName); var httpActionDescriptors = FindAllHttpActionDescriptors(installerAssembly).Distinct().ToArray(); var httpActionDescriptorCounters = GetCounterCreationDataCollectionForHttpActionDescriptors(httpActionDescriptors); var httpActionDescriptorCategoryName = PerformanceCounterApmApiFilterAttribute.GetCategoryName(categoryName); PerformanceCounterCategory.Create(httpActionDescriptorCategoryName, "APM api filter category for " + categoryName, PerformanceCounterCategoryType.MultiInstance, httpActionDescriptorCounters); Trace.TraceInformation("Built category '{0}' with {1} items", httpActionDescriptorCategoryName, httpActionDescriptorCounters.Count); //Todo: Need to rather use ApmContext.GetDelegatingHandler and ApmContext.GetMethodHander var apmContextUsage = FindAllApmContextUsage(installerAssembly).Distinct().ToArray(); var apmContextUsageCounters = GetCounterCreationDataCollectionForApmContextUsage(apmContextUsage); var httpClientCategoryName = PerformanceCounterApmHttpClientDelegatingHandler.GetCategoryName(categoryName); PerformanceCounterCategory.Create(httpClientCategoryName, "APM http client category for " + categoryName, PerformanceCounterCategoryType.MultiInstance, apmContextUsageCounters); Trace.TraceInformation("Built category '{0}' with {1} items", httpClientCategoryName, apmContextUsageCounters.Count); }
private WMIDataStoreProviders() { Instrumentation.Publish(this); try { if (!PerformanceCounterCategory.Exists("GeneXusCounters")) { CounterCreationDataCollection CounterDatas = new CounterCreationDataCollection(); CounterCreationData statementCount = new CounterCreationData(); statementCount.CounterName = "StatementCount"; statementCount.CounterHelp = "SQL Statement Count"; statementCount.CounterType = PerformanceCounterType.NumberOfItems64; CounterDatas.Add(statementCount); PerformanceCounterCategory.Create("GeneXusCounters", "GeneXus Counters", CounterDatas); } } catch (Exception e) { GXLogging.Error(log, "WMI Performance countes error", e); } try{ statementCounter = new PerformanceCounter("GeneXusCounters", "StatementCount", "instance1", false); statementSelectCounter = new PerformanceCounter("GeneXusCounters", "StatementCount", "instance1", false); statementUpdateCounter = new PerformanceCounter("GeneXusCounters", "StatementUpdateCount", "instance1", false); statementDeleteCounter = new PerformanceCounter("GeneXusCounters", "StatementDeleteCount", "instance1", false); statementInsertCounter = new PerformanceCounter("GeneXusCounters", "StatementInsertCount", "instance1", false); statementCallCounter = new PerformanceCounter("GeneXusCounters", "StatementCallCount", "instance1", false); statementDirectSQLCounter = new PerformanceCounter("GeneXusCounters", "StatementDirectSQLCount", "instance1", false); } catch (Exception e) { GXLogging.Error(log, "WMI Performance countes error", e); } }
public override bool Refresh() { if (MetricRetrievers == null) { MetricRetrievers = new List <MetricRetriever>(); } if (CounterInstance != null && CounterInstance == "*") { var cat = new PerformanceCounterCategory(CounterCategory); string[] instances = cat.GetInstanceNames(); foreach (string instance in instances) { if (!ExistInstance(instance)) { MetricRetriever metricRetriver = GetMetricRetriever(CounterCategory, CounterName, instance); if (metricRetriver == null) { return(false); } // Replace collectd_plugin_instance with the Instance got from counter metricRetriver.Instance = instance; MetricRetrievers.Add(metricRetriver); } } } else if (MetricRetrievers.Count == 0) { MetricRetriever metricRetriver = GetMetricRetriever(CounterCategory, CounterName, CounterInstance); if (metricRetriver == null) { return(false); } MetricRetrievers.Add(metricRetriver); } return(true); }
/// <summary> /// In this method we instantiate the PerformanceCounter object and return it. /// </summary> /// <param name="categoryName">Category name</param> /// <param name="counterName">Counter name</param> /// <param name="instanceName">Counter instance name</param> /// <param name="instanceLifeTime">The life time of this instance</param> /// <param name="readOnly">Is counter for read only?</param> /// <returns>Performance counter</returns> public static PerformanceCounter getCounter( string categoryName, string counterName, string instanceName, PerformanceCounterInstanceLifetime instanceLifeTime, bool readOnly ) { PerformanceCounter counter = null; // Check if the category exists if (PerformanceCounterCategory.Exists(categoryName)) { counter = new PerformanceCounter( categoryName, counterName, instanceName, readOnly ); } return(counter); }
private static void EnumerateCounters() { var categories = PerformanceCounterCategory.GetCategories().Select(c => c.CategoryName).OrderBy(s => s).ToArray(); var sb = new StringBuilder(); foreach (var category in categories) { var counterCategory = new PerformanceCounterCategory(category); foreach (var counterInstance in counterCategory.GetInstanceNames()) { try { foreach (var counter in counterCategory.GetCounters(counterInstance)) { sb.AppendLine(string.Format("{0}:{1}:{2}", counterInstance, category, counter.CounterName)); } } catch { // Drop it on the floor } } } Console.WriteLine(sb.ToString()); }
private static void EnumerateCountersFor(string category) { var sb = new StringBuilder(); var counterCategory = new PerformanceCounterCategory(category); if(counterCategory.CategoryType == PerformanceCounterCategoryType.SingleInstance) { foreach (var counter in counterCategory.GetCounters()) { sb.AppendLine(string.Format("{0}:{1}", category, counter.CounterName)); } } else { foreach (var counterInstance in counterCategory.GetInstanceNames()) { foreach (var counter in counterCategory.GetCounters(counterInstance)) { sb.AppendLine(string.Format("{0}:{1}:{2}", counterInstance, category, counter.CounterName)); } } } Console.WriteLine(sb.ToString()); }
public static void mesure_init_2(List<String> names) { PlugwiseLib.BLL.BC.PlugwiseDeviceInfo calib; string fileName = @"C:\GreenCodeLab_Plugwyse\log.txt"; TextWriter writer; writer = new StreamWriter(fileName); string entete = ""; int num = 0; for (int i = 0; i < 9; i++) { if (Plug_act[i] == true) { calib = control.InitPlug(TimerMesure.Plug_mac[i],serialPort); if (calib != null) { Plug_Ok[i] = true; Plug_Calib[i] = calib; if (bufferisation == false) { entete = entete + names[i] + ";%CPU " + (i + 1).ToString() + ";Bytes/S " + (i + 1).ToString() + ";Disk Bytes/S " + (i + 1).ToString() + ";consommation " + (i + 1).ToString() + ";Impact consommation " + (i + 1).ToString(); } else { entete = entete + names[i] + ";"; } Array.Resize(ref Plug_num, num + 1); Plug_num[num] = i; num++; } else { Plug_Ok[i] = false; } } else { Plug_Ok[i] = false; } } writer.WriteLine(entete); writer.Close(); if (mesurecpu == true) { PerformanceCounterCategory networkCategory; string instanceName = null; PCounter = new PerformanceCounter(); PCounter.MachineName = Environment.MachineName; //Attribution de la propriété MachineName permettant de "dire" au Compteur de performance de compter sur la machine local PCounter.CategoryName = "Processor"; PCounter.CounterName = "% Processor Time"; PCounter.InstanceName = "_Total"; PCounter2 = new PerformanceCounter(); PCounter2.MachineName = Environment.MachineName; //Attribution de la propriété MachineName permettant de "dire" au Compteur de performance de compter sur la machine local PCounter2.CategoryName = "Network Interface"; PCounter2.CounterName = "Bytes Total/sec"; networkCategory = new PerformanceCounterCategory("Network Interface"); foreach (string instance in networkCategory.GetInstanceNames()) { Console.WriteLine(instance); if (instance == "Realtek PCIe FE Family Controller") { instanceName = instance; break; } } PCounter2.InstanceName = instanceName; PCounter3 = new PerformanceCounter(); PCounter3.MachineName = Environment.MachineName; //Attribution de la propriété MachineName permettant de "dire" au Compteur de performance de compter sur la machine local PCounter3.CategoryName = "PhysicalDisk"; PCounter3.CounterName = "% Disk Time"; PCounter3.InstanceName = "_Total"; } }