Esempio n. 1
0
        public void Refresh()
        {
            try
            {
                var data = _category.ReadCategory();

                // ReSharper disable AssignNullToNotNullAttribute

                Counters = data.Values.Cast <InstanceDataCollection>()
                           .Select(t => t.CounterName)
                           .OrderBy(t => t, StringComparer.InvariantCultureIgnoreCase)
                           .ToArray();

                Instances = Counters.Count > 0
                                ? data.Values.Cast <InstanceDataCollection>().First()
                            .Values.Cast <InstanceData>()
                            .Select(t => t.InstanceName)
                            .OrderBy(t => t, StringComparer.InvariantCultureIgnoreCase)
                            .ToArray()
                                : new string[0];

                // ReSharper restore AssignNullToNotNullAttribute
            }
            catch (Exception)
            {
            }
        }
        public PerfCounterCategoryViewModel(PerformanceCounterCategory cat, IObservable <long> interval, MainViewModel parent)
        {
            Name.Value   = cat.CategoryName;
            Values.Value = new PerfCounterViewModel[1];



            Expanded.Observable.CombineLatest(interval, (p, i) => p).Where(p => p).Subscribe(e =>
            {
                var vals     = cat.ReadCategory();
                bool changed = false;

                foreach (var v in vals.Values.OfType <InstanceDataCollection>().OrderBy(v => v.CounterName))
                {
                    if (!valueDictionary.ContainsKey(v.CounterName))
                    {
                        changed            = true;
                        var processors     = parent.Processors.Where(x => Regex.IsMatch(cat.CategoryName, x.property.Category)).Select(x => (IPerfcounterProcessor)Activator.CreateInstance(x.type));
                        var processor      = processors.FirstOrDefault() ?? new DefaultperfcounterProcessor();
                        processor.Category = cat.CategoryName;
                        processor.Counter  = v.CounterName;
                        valueDictionary.Add(v.CounterName, new PerfCounterViewModel(parent, processor));
                    }
                    valueDictionary[v.CounterName].Update(v);
                }

                if (changed)
                {
                    Values.Value = valueDictionary.Values.ToList();
                }
            });
        }
Esempio n. 3
0
        public static void PerformanceCounterCategory_ReadCategory()
        {
            PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory("Processor"));

            InstanceDataCollectionCollection idColCol = pcc.ReadCategory();

            Assert.NotNull(idColCol);
        }
Esempio n. 4
0
        public static InstanceDataCollectionCollection GetInstanceDataCollectionCollection()
        {
            PerformanceCounterCategory pcc = new PerformanceCounterCategory("Processor");

            return(Helpers.RetryOnAllPlatformsWithClosingResources(() =>
            {
                var idcc = pcc.ReadCategory();
                Assert.InRange(idcc.Values.Count, 1, int.MaxValue);
                return idcc;
            }));
        }
Esempio n. 5
0
        /// <summary>
        /// Find the process counter name
        /// </summary>
        /// <returns></returns>
        public static string GetProcessCounterName()
        {
            Process process = Process.GetCurrentProcess();
            int     id      = process.Id;
            PerformanceCounterCategory perfCounterCat = new PerformanceCounterCategory("Process");

            foreach (DictionaryEntry entry in perfCounterCat.ReadCategory()["id process"])
            {
                string processCounterName = (string)entry.Key;
                if (((InstanceData)entry.Value).RawValue == id)
                {
                    return(processCounterName);
                }
            }
            return("");
        }
        public Dictionary <int, string> ObtainInstanceNames()
        {
            var category = new PerformanceCounterCategory(this.categoryName);

            var dataCollectionByCounters = category.ReadCategory();
            var dataCollection           = dataCollectionByCounters[counterName];
            var map = new Dictionary <int, string>(dataCollection.Count);

            foreach (DictionaryEntry kvp in dataCollection)
            {
                var instanceId = (string)kvp.Key;
                var value      = (InstanceData)kvp.Value;
                var pid        = (int)value.RawValue;
                map[pid] = instanceId;
            }

            return(map);
        }
Esempio n. 7
0
        /// <summary>
        /// Harvest a performance category.
        /// </summary>
        /// <param name="category">The name of the performance category.</param>
        /// <returns>A harvested file.</returns>
        public Util.PerformanceCategory HarvestPerformanceCategory(string category)
        {
            if (null == category)
            {
                throw new ArgumentNullException("category");
            }

            if (PerformanceCounterCategory.Exists(category))
            {
                Util.PerformanceCategory perfCategory = new Util.PerformanceCategory();

                // Get the performance counter category and set the appropriate WiX attributes
                PerformanceCounterCategory pcc = new PerformanceCounterCategory(category);
                perfCategory.Id   = CompilerCore.GetIdentifierFromName(pcc.CategoryName);
                perfCategory.Name = pcc.CategoryName;
                perfCategory.Help = pcc.CategoryHelp;
                if (PerformanceCounterCategoryType.MultiInstance == pcc.CategoryType)
                {
                    perfCategory.MultiInstance = Util.YesNoType.yes;
                }

                foreach (InstanceDataCollection counter in pcc.ReadCategory().Values)
                {
                    Util.PerformanceCounter perfCounter = new Util.PerformanceCounter();

                    // Get the performance counter and set the appropriate WiX attributes
                    PerformanceCounter pc = new PerformanceCounter(pcc.CategoryName, counter.CounterName);
                    perfCounter.Name = pc.CounterName;
                    perfCounter.Type = CounterTypeToWix(pc.CounterType);
                    perfCounter.Help = pc.CounterHelp;

                    perfCategory.AddChild(perfCounter);
                }

                return(perfCategory);
            }
            else
            {
                throw new WixException(UtilErrors.PerformanceCategoryNotFound(category));
            }
        }
        public static InstanceDataCollectionCollection GetInstanceDataCollectionCollection()
        {
            PerformanceCounterCategory pcc = Helpers.RetryOnAllPlatforms(() => new PerformanceCounterCategory("Processor"));

            return(Helpers.RetryOnAllPlatforms(() => pcc.ReadCategory()));
        }
Esempio n. 9
0
    //</snippet7>

    public static void Main()
    {
        string catNumStr;
        int    categoryNum;

        PerformanceCounterCategory[] categories = PerformanceCounterCategory.GetCategories();

        // Create and sort an array of category names.
        string[] categoryNames = new string[categories.Length];
        int      catX;

        for (catX = 0; catX < categories.Length; catX++)
        {
            categoryNames[catX] = categories[catX].CategoryName;
        }
        Array.Sort(categoryNames);

        Console.WriteLine("These categories are registered on this computer:");

        for (catX = 0; catX < categories.Length; catX++)
        {
            Console.WriteLine("{0,4} - {1}", catX + 1, categoryNames[catX]);
        }

        // Ask the user to choose a category.
        Console.Write("Enter the category number from the above list: ");
        catNumStr = Console.ReadLine();

        // Validate the entered category number.
        try
        {
            categoryNum = int.Parse(catNumStr);
            if (categoryNum < 1 || categoryNum > categories.Length)
            {
                throw new Exception(String.Format("The category number must be in the " +
                                                  "range 1..{0}.", categories.Length));
            }
            categoryName = categoryNames[(categoryNum - 1)];
        }
        catch (Exception ex)
        {
            Console.WriteLine("\"{0}\" is not a valid category number." +
                              "\r\n{1}", catNumStr, ex.Message);
            return;
        }
        //<snippet5>
        //<snippet6>

        // Process the InstanceDataCollectionCollection for this category.
        PerformanceCounterCategory       pcc      = new PerformanceCounterCategory(categoryName);
        InstanceDataCollectionCollection idColCol = pcc.ReadCategory();

        InstanceDataCollection[] idColArray = new InstanceDataCollection[idColCol.Count];

        Console.WriteLine("InstanceDataCollectionCollection for \"{0}\" " +
                          "has {1} elements.", categoryName, idColCol.Count);
        //</snippet6>

        // Copy and process the InstanceDataCollection array.
        idColCol.CopyTo(idColArray, 0);

        foreach (InstanceDataCollection idCol in idColArray)
        {
            ProcessInstanceDataCollection(idCol);
        }
        //</snippet5>
    }
Esempio n. 10
0
    public static void Main()
    {
        string catNumStr;
        int    categoryNum;

        PerformanceCounterCategory[] categories = PerformanceCounterCategory.GetCategories();

        Console.WriteLine("These categories are registered on this computer:");

        int catX;

        for (catX = 0; catX < categories.Length; catX++)
        {
            Console.WriteLine("{0,4} - {1}", catX + 1, categories[catX].CategoryName);
        }

        // Ask the user to choose a category.
        Console.Write("Enter the category number from the above list: ");
        catNumStr = Console.ReadLine();

        // Validate the entered category number.
        try
        {
            categoryNum = int.Parse(catNumStr);
            if (categoryNum < 1 || categoryNum > categories.Length)
            {
                throw new Exception(String.Format("The category number must be in the " +
                                                  "range 1..{0}.", categories.Length));
            }
            categoryName = categories[(categoryNum - 1)].CategoryName;
        }
        catch (Exception ex)
        {
            Console.WriteLine("\"{0}\" is not a valid category number." +
                              "\r\n{1}", catNumStr, ex.Message);
            return;
        }

        // Process the InstanceDataCollectionCollection for this category.
        PerformanceCounterCategory       pcc      = new PerformanceCounterCategory(categoryName);
        InstanceDataCollectionCollection idColCol = pcc.ReadCategory();

        ICollection idColColKeys = idColCol.Keys;

        string[] idCCKeysArray = new string[idColColKeys.Count];
        idColColKeys.CopyTo(idCCKeysArray, 0);

        ICollection idColColValues = idColCol.Values;

        InstanceDataCollection[] idCCValuesArray = new InstanceDataCollection[idColColValues.Count];
        idColColValues.CopyTo(idCCValuesArray, 0);

        Console.WriteLine("InstanceDataCollectionCollection for \"{0}\" " +
                          "has {1} elements.", categoryName, idColCol.Count);

        // Display the InstanceDataCollectionCollection Keys and Values.
        // The Keys and Values collections have the same number of elements.
        int index;

        for (index = 0; index < idCCKeysArray.Length; index++)
        {
            Console.WriteLine("  Next InstanceDataCollectionCollection " +
                              "Key is \"{0}\"", idCCKeysArray[index]);
            ProcessInstanceDataCollection(idCCValuesArray[index]);
        }
    }
Esempio n. 11
0
        public static void PerformanceCounterCategory_ReadCategory_Invalid()
        {
            PerformanceCounterCategory pcc = new PerformanceCounterCategory();

            Assert.Throws <InvalidOperationException>(() => pcc.ReadCategory());
        }
Esempio n. 12
0
    //<snippet2>
    public static void Main(string[] args)
    {
        // These values can be used as arguments.
        string categoryName = "Process";
        string counterName  = "Private Bytes";
        string instanceName = "Explorer";

        InstanceDataCollection idCol;
        const string           SINGLE_INSTANCE_NAME = "systemdiagnosticsperfcounterlibsingleinstance";

        // Copy the supplied arguments into the local variables.
        try
        {
            categoryName = args[0];
            counterName  = args[1];
            instanceName = args[2];
        }
        catch
        {
            // Ignore the exception from non-supplied arguments.
        }

        try
        {
            // Get the InstanceDataCollectionCollection for this category.
            PerformanceCounterCategory       pcc      = new PerformanceCounterCategory(categoryName);
            InstanceDataCollectionCollection idColCol = pcc.ReadCategory();

            // Get the InstanceDataCollection for this counter.
            idCol = idColCol[counterName];
            if (idCol == null)
            {
                throw new Exception("Counter does not exist.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred getting the InstanceDataCollection for " +
                              "category \"{0}\", counter \"{1}\"." + "\n" + ex.Message, categoryName, counterName);
            return;
        }

        // If the instance name is empty, use the single-instance name.
        if (instanceName.Length == 0)
        {
            instanceName = SINGLE_INSTANCE_NAME;
        }

        //<snippet3>
        // Check if this instance name exists using the Contains
        // method of the InstanceDataCollection.
        if (!idCol.Contains(instanceName))
        //</snippet3>
        {
            Console.WriteLine("Instance \"{0}\" does not exist in counter \"{1}\", " +
                              "category \"{2}\".", instanceName, counterName, categoryName);
            return;
        }
        else
        {
            //<snippet4>
            // The instance name exists, now get its InstanceData object
            // using the indexer (Item property) for the InstanceDataCollection.
            InstanceData instData = idCol[instanceName];
            //</snippet4>

            Console.WriteLine("CategoryName: {0}", categoryName);
            Console.WriteLine("CounterName:  {0}", counterName);
            Console.WriteLine("InstanceName: {0}", instData.InstanceName);
            Console.WriteLine("RawValue:     {0}", instData.RawValue);
        }
    }
    //<snippet2>
    public static void Main(string[] args)
    {
        // The following values can be used as arguments.
        string categoryName = "Process";
        string counterName  = "Private Bytes";

        InstanceDataCollectionCollection idColCol;

        // Copy the supplied arguments into the local variables.
        try
        {
            categoryName = args[0];
            counterName  = args[1];
        }
        catch
        {
            // Ignore the exception from non-supplied arguments.
        }

        try
        {
            // Get the InstanceDataCollectionCollection for this category.
            PerformanceCounterCategory pcc = new PerformanceCounterCategory(categoryName);
            idColCol = pcc.ReadCategory();
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred getting the InstanceDataCollection for " +
                              "category \"{0}\"." + "\n" + ex.Message, categoryName);
            return;
        }

        //<snippet3>
        // Check if this counter name exists using the Contains
        // method of the InstanceDataCollectionCollection.
        if (!idColCol.Contains(counterName))
        //</snippet3>
        {
            Console.WriteLine("Counter \"{0}\" does not exist in category \"{1}\".", counterName, categoryName);
            return;
        }
        else
        {
            //<snippet4>
            // Now get the counter's InstanceDataCollection object using the
            // indexer (Item property) for the InstanceDataCollectionCollection.
            InstanceDataCollection countData = idColCol[counterName];
            //</snippet4>

            ICollection idColKeys      = countData.Keys;
            string[]    idColKeysArray = new string[idColKeys.Count];
            idColKeys.CopyTo(idColKeysArray, 0);

            Console.WriteLine("Counter \"{0}\" of category \"{1}\" " +
                              "has {2} instances.", counterName, categoryName, idColKeys.Count);

            // Display the instance names for this counter.
            int index;
            for (index = 0; index < idColKeysArray.Length; index++)
            {
                Console.WriteLine("{0,4} -- {1}", index + 1, idColKeysArray[index]);
            }
        }
    }
Esempio n. 14
0
        public void Update()
        {
            foreach (string categoryName in subscribers.Select(kvp => kvp.Key.Item1).Distinct())
            {
                PerformanceCounterCategory pcc = new PerformanceCounterCategory(categoryName);

                #if DEBUG
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                #endif

                InstanceDataCollectionCollection idcc = pcc.ReadCategory();

                #if DEBUG
                stopwatch.Stop();
                Console.WriteLine("{0:f4} ms\t{1}", stopwatch.Elapsed.TotalMilliseconds, categoryName);
                #endif

                foreach (InstanceDataCollection idc in idcc.Values)
                {
                    string counterName           = idc.CounterName;
                    Tuple <string, string> tuple = Tuple.Create(categoryName, counterName);

                    List <IPerfmonCallback> list;
                    if (subscribers.TryGetValue(tuple, out list))
                    {
                        List <Instance> instances = new List <Instance>();
                        DateTime?       timestamp = null;

                        foreach (InstanceData id in idc.Values)
                        {
                            string instanceName = (pcc.CategoryType == PerformanceCounterCategoryType.MultiInstance ? id.InstanceName : "*");
                            string path         = string.Format(@"\{0}({1})\{2}", categoryName, instanceName, counterName);

                            CounterSample sample = id.Sample;

                            if (timestamp == null)
                            {
                                timestamp = DateTime.FromFileTime(sample.TimeStamp100nSec);
                            }

                            CounterSample prevSample;
                            if (prevSamples.TryGetValue(path, out prevSample))
                            {
                                float value = CounterSample.Calculate(prevSample, sample);
                                instances.Add(new Instance()
                                {
                                    Name = instanceName, Value = value
                                });
                            }
                            prevSamples[path] = sample;
                        }

                        // If there are instances available but we don't have a previous sample
                        // to calculate their value, then don't send anything to the client yet
                        if (idc.Count > 0 && instances.Count == 0)
                        {
                            continue;
                        }

                        // Otherwise let the client know that there are no instances by sending
                        // an empty list with the current time
                        if (timestamp == null)
                        {
                            timestamp = DateTime.Now;
                        }

                        Counter counter = new Counter()
                        {
                            Name = counterName, Instances = instances
                        };
                        Category category = new Category()
                        {
                            Name = categoryName, Counters = new List <Counter>()
                            {
                                counter
                            }
                        };
                        EventData e = new EventData()
                        {
                            Category = category, Timestamp = timestamp.Value
                        };

                        ThreadPool.QueueUserWorkItem(_ =>
                        {
                            Parallel.ForEach(list, subscriber =>
                            {
                                try
                                {
                                    subscriber.OnNext(e);
                                }
                                catch (CommunicationException) { }
                            });
                        });
                    }
                }
            }
        }