Пример #1
0
        /// <inheritdoc />
        public async Task <Result <CounterSet> > GetStatsAsync(OperationContext context)
        {
            var counterSet = new CounterSet();

            foreach (var(name, store) in StoresByName)
            {
                var stats = await GetStatsAsync(store, context);

                if (!stats)
                {
                    return(Result.FromError <CounterSet>(stats));
                }

                counterSet.Merge(stats.CounterSet, $"{name}.");
            }

            return(counterSet);
        }
Пример #2
0
        private void CreateCounterSetInstance()
        {
            this._CounterSet = new CounterSet(base._counterSetRegistrarBase.ProviderId, base._counterSetRegistrarBase.CounterSetId, base._counterSetRegistrarBase.CounterSetInstType);
            foreach (CounterInfo info in base._counterSetRegistrarBase.CounterInfoArray)
            {
                if (info.Name == null)
                {
                    this._CounterSet.AddCounter(info.Id, info.Type);
                }
                else
                {
                    this._CounterSet.AddCounter(info.Id, info.Type, info.Name);
                }
            }
            string counterSetInstanceName = PSPerfCountersMgr.Instance.GetCounterSetInstanceName();

            this._CounterSetInstance = this._CounterSet.CreateCounterSetInstance(counterSetInstanceName);
        }
Пример #3
0
        public virtual CounterSet GetCounters()
        {
            var counterSet = new CounterSet();

            foreach (var counter in Counters)
            {
                counterSet.Add(counter.Name, counter.Value);
            }

            var callsCounterSet = new CounterSet();

            foreach (var callCounter in CallCounters)
            {
                callCounter.AppendTo(callsCounterSet);
            }

            return(callsCounterSet.Merge(counterSet));
        }
Пример #4
0
        /// <inheritdoc />
        async Task <Result <CounterSet> > ISessionHandler <TSession> .GetStatsAsync(OperationContext context)
        {
            var counterSet = new CounterSet();

            foreach (var store in StoresByName.Values)
            {
                var stats = await GetStatsAsync(store, context);

                if (!stats)
                {
                    return(Result.FromError <CounterSet>(stats));
                }

                counterSet.Merge(stats.CounterSet);
            }

            return(counterSet);
        }
Пример #5
0
        /// <summary>
        ///     Run the call.
        /// </summary>
        public static async Task <GetStatsResult> RunAsync(TTracer tracer, OperationContext context, Func <Task <GetStatsResult> > funcAsync)
        {
            using (var call = new GetStatsCall <TTracer>(tracer, context))
            {
                var result = await call.RunAsync(funcAsync);

                if (result)
                {
                    var stats = new CounterSet();

                    stats.Add("CriticalErrors", tracer.NumberOfCriticalErrors);
                    stats.Add("RecoverableErrors", tracer.NumberOfRecoverableErrors);
                    result.CounterSet.Merge(stats, $"{tracer.GetType().Name}.{tracer.Name}.ErrorStats.");
                }

                return(result);
            }
        }
Пример #6
0
        public CounterSet CreateCounterSet(string groupID, string name, string description = null)
        {
            if (GetCounterSet(groupID, name) != null)
            {
                throw new CounterSetAlreadyExistException();
            }
            CounterSet cs = new CounterSet();

            cs.Group          = groupID;
            cs.Name           = name;
            cs.Description    = description;
            cs.RecordCount    = 0;
            cs.LastUpdateTime = DateTime.UtcNow;
            CounterSetEntity entity          = cs;
            TableOperation   insertOperation = TableOperation.Insert(entity);

            _counterSet.Execute(insertOperation);
            return(entity);
        }
Пример #7
0
        public void CounterSet_Functionbased()
        {
            var counterSet = new CounterSet();
            var counter1   = new Counter(2);
            var counter2   = new Counter(() => { return(OneHigherThanValue(counter1)); });

            counterSet.AddCounter(counter1);
            counterSet.AddCounter(counter2);

            int           i     = 0;
            List <String> perms = GetAllPermutations(counterSet);

            Assert.AreEqual("1:1", perms[0]);
            Assert.AreEqual("1:2", perms[1]);
            Assert.AreEqual("2:1", perms[2]);
            Assert.AreEqual("2:2", perms[3]);
            Assert.AreEqual("2:3", perms[4]);
            Assert.AreEqual(5, perms.Count);
        }
Пример #8
0
        public void GenerateCounterListTestManyProvidersWithFilter()
        {
            CounterMonitor monitor  = new CounterMonitor();
            CounterSet     counters = monitor.ParseProviderList("MySource1[mycounter1,mycounter2], MySource2[mycounter1], System.Runtime[cpu-usage,working-set]");

            Assert.Equal(3, counters.Providers.Count());

            Assert.Equal("MySource1", counters.Providers.ElementAt(0));
            Assert.False(counters.IncludesAllCounters("MySource1"));
            Assert.True(Enumerable.SequenceEqual(counters.GetCounters("MySource1"), new string[] { "mycounter1", "mycounter2" }));

            Assert.Equal("MySource2", counters.Providers.ElementAt(1));
            Assert.False(counters.IncludesAllCounters("MySource2"));
            Assert.True(Enumerable.SequenceEqual(counters.GetCounters("MySource2"), new string[] { "mycounter1" }));

            Assert.Equal("System.Runtime", counters.Providers.ElementAt(2));
            Assert.False(counters.IncludesAllCounters("System.Runtime"));
            Assert.True(Enumerable.SequenceEqual(counters.GetCounters("System.Runtime"), new string[] { "cpu-usage", "working-set" }));
        }
Пример #9
0
        public void Stats(CounterSet snapshot)
        {
            if (IsEnabled())
            {
                var  oldActivity   = Guid.Empty;
                var  buildActivity = Environment.GetEnvironmentVariable("_MS_ENGSYS_ACTIVITY_ID");
                Guid activity;
                if (buildActivity != null && Guid.TryParse(buildActivity, out activity))
                {
                    SetCurrentThreadActivityId(activity, out oldActivity);
                }

                WriteEvent((int)StatsEventId.Stats, snapshot.ToDictionaryIntegral());

                if (oldActivity != Guid.Empty)
                {
                    SetCurrentThreadActivityId(oldActivity);
                }
            }
        }
Пример #10
0
    protected virtual void OnAddSet(object sender, System.EventArgs e)
    {
        AddSet cdialog = new AddSet(cfg);
        int    res     = cdialog.Run();

        if (res == (int)ResponseType.Ok)
        {
            CounterSet    cset         = cfg [cdialog.CounterSet];
            string        instance     = cdialog.Instance;
            List <string> csetcounters = cset.Counters;
            for (int i = 0; i < csetcounters.Count; i += 2)
            {
                AddCounter(csetcounters [i], csetcounters [i + 1], instance);
            }
        }
        else
        {
        }
        cdialog.Destroy();
    }
        /// <inheritdoc />
        public Task <GetStatsResult> GetStatsAsync(Context context)
        {
            return(GetStatsCall <ContentStoreTracer> .RunAsync(
                       StoreTracer,
                       new OperationContext(context),
                       async() =>
            {
                CounterSet aggregatedCounters = new CounterSet();
                foreach (var kvp in DrivesWithContentStore)
                {
                    var stats = await kvp.Value.GetStatsAsync(context);
                    if (stats.Succeeded)
                    {
                        aggregatedCounters.Merge(stats.CounterSet, $"{kvp.Value.GetType().Name}.{kvp.Key}.");
                    }
                }

                return new GetStatsResult(aggregatedCounters);
            }));
        }
Пример #12
0
        /// <nodoc />
        public static CounterSet ToCounterSet <TEnum>(this CounterCollection <TEnum> counters)
            where TEnum : struct
        {
            CounterSet counterSet = new CounterSet();

            foreach (var counterEnum in EnumTraits <TEnum> .EnumerateValues())
            {
                var counter     = counters[counterEnum];
                var counterName = counterEnum.ToString();

                counterSet.Add($"{counterName}.Count", (long)counter.Value, counter.Name);

                if (counter.IsStopwatch)
                {
                    counterSet.Add($"{counterName}.AverageMs", counter.Value != 0 ? (long)counter.Duration.TotalMilliseconds / counter.Value : 0);
                    counterSet.Add($"{counterName}.DurationMs", (long)counter.Duration.TotalMilliseconds);
                }
            }

            return(counterSet);
        }
Пример #13
0
        /// <summary>
        /// Gets the statistics from the remote.
        /// </summary>
        public async Task <GetStatsResult> GetStatsAsync(Context context)
        {
            CounterSet counters = new CounterSet();

            // Get stats iff compatible with service and client
            if ((_serviceCapabilities & Capabilities.GetStats) != 0 &&
                (_clientCapabilities & Capabilities.GetStats) != 0)
            {
                var response = await SendGrpcRequestAsync(context, async() => await GetStatsAsync(new GetStatsRequest()));

                if (response.Success)
                {
                    foreach (var entry in response.Statistics)
                    {
                        counters.Add(entry.Key, entry.Value);
                    }
                }
            }

            return(new GetStatsResult(counters));
        }
Пример #14
0
        internal static void EnsureCounterSet()
        {
            if (workflowServiceHostCounterSet == null)
            {
                lock (syncRoot)
                {
                    if (workflowServiceHostCounterSet == null)
                    {
                        CounterSet localCounterSet = CreateCounterSet();

                        // Add the counters to the counter set definition.
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsCreated, CounterType.RawData32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsCreatedPerSecond, CounterType.RateOfCountPerSecond32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsExecuting, CounterType.RawData32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsCompleted, CounterType.RawData32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsCompletedPerSecond, CounterType.RateOfCountPerSecond32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsAborted, CounterType.RawData32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsAbortedPerSecond, CounterType.RateOfCountPerSecond32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsInMemory, CounterType.RawData32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsPersisted, CounterType.RawData32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsPersistedPerSecond, CounterType.RateOfCountPerSecond32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsTerminated, CounterType.RawData32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsTerminatedPerSecond, CounterType.RateOfCountPerSecond32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsLoaded, CounterType.RawData32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsLoadedPerSecond, CounterType.RateOfCountPerSecond32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsUnloaded, CounterType.RawData32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsUnloadedPerSecond, CounterType.RateOfCountPerSecond32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsSuspended, CounterType.RawData32, perfCounterNames[(int)PerfCounters.WorkflowsSuspended]);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsSuspendedPerSecond, CounterType.RateOfCountPerSecond32);
                        localCounterSet.AddCounter((int)PerfCounters.WorkflowsIdlePerSecond, CounterType.RateOfCountPerSecond32);
                        localCounterSet.AddCounter((int)PerfCounters.AverageWorkflowLoadTime, CounterType.AverageTimer32);
                        localCounterSet.AddCounter((int)PerfCounters.AverageWorkflowLoadTimeBase, CounterType.AverageBase);
                        localCounterSet.AddCounter((int)PerfCounters.AverageWorkflowPersistTime, CounterType.AverageTimer32);
                        localCounterSet.AddCounter((int)PerfCounters.AverageWorkflowPersistTimeBase, CounterType.AverageBase);

                        workflowServiceHostCounterSet = localCounterSet;
                    }
                }
            }
        }
Пример #15
0
        public DisplayCounterChart GetCounterChart(string path, string name, string group = null)
        {
            string me = whoami();

            if (string.IsNullOrEmpty(group))
            {
                group = MembershipHelper.DefaultGroup(me);
            }
            else
            {
                MembershipHelper.CheckMembership(group, me);
            }

            CounterSet cs = _counterManager.GetCounterSet(group, name);

            if (cs == null)
            {
                throw new CounterSetNotFoundException();
            }

            CounterRecord record = _counterManager.GetSingleCounterRecord(group, name, cs.RecordCount - 1);

            CounterRecord.ComplexValue cv = CounterRecordHelper.Get(record, path);
            if (cv == null)
            {
                return(null);
            }

            DisplayCounterChart dcc = new DisplayCounterChart();

            dcc.Title          = cv.Name;
            dcc.MainCounter    = new DisplayCounter(path, cv.Type);
            dcc.RelatedCounter = new List <DisplayCounter>();
            foreach (var value in cv.RelatedValues)
            {
                dcc.RelatedCounter.Add(new DisplayCounter(string.Format("{0}.{1}", path, value.Name), value.Type));
            }

            return(dcc);
        }
Пример #16
0
 protected override void OnInitialize()
 {
     lock (MessagingPerformanceCounters.staticSyncRoot)
     {
         if (MessagingPerformanceCounters.counterSet == null)
         {
             CounterSet counterSet = MessagingPerformanceCounters.CreateCounterSet();
             foreach (KeyValuePair <MessagingPerformanceCounters.MessagingPerfCounterKeys, MessagingPerformanceCounters.CounterMetadata> perfCounterDictionary in MessagingPerformanceCounters.PerfCounterDictionary)
             {
                 counterSet.AddCounter(perfCounterDictionary.Value.Id, perfCounterDictionary.Value.Type, perfCounterDictionary.Value.Name);
             }
             MessagingPerformanceCounters.counterSet = counterSet;
         }
     }
     this.counterSetInstance = MessagingPerformanceCounters.CreateCounterSetInstance(this.InstanceName);
     this.counters           = new CounterData[43];
     for (int i = 0; i < (int)this.counters.Length; i++)
     {
         this.counters[i]       = this.counterSetInstance.Counters[i];
         this.counters[i].Value = (long)0;
     }
 }
Пример #17
0
        /// <summary>
        /// Gets the counters collected by this tracer instance.
        /// </summary>
        public CounterSet GetCounters()
        {
            var aggregatedCounters = new CounterSet();

            aggregatedCounters.Merge(ContentSessionTracer.GetCounters());
            var countersStored = aggregatedCounters.ToDictionaryIntegral();

            foreach (var counter in MemoizationStoreTracer.GetCounters().ToDictionaryIntegral())
            {
                if (!countersStored.ContainsKey(counter.Key))
                {
                    aggregatedCounters.Add(counter.Key, counter.Value);
                }
            }

            foreach (Counter counter in _counters)
            {
                aggregatedCounters.Add(counter.Name, counter.Value);
            }

            return(aggregatedCounters);
        }
Пример #18
0
        /// <inheritdoc />
        public Task <GetStatsResult> GetStatsAsync(Context context)
        {
            return(GetStatsCall <ContentStoreTracer> .RunAsync(
                       ExecutionTracer,
                       OperationContext(context),
                       async() =>
            {
                CounterSet aggregatedCounters = new CounterSet();
                aggregatedCounters.Merge(SessionTracer.GetCounters(), $"{nameof(ServiceClientContentSession)}.");
                // Getting the stats from the remote as well.
                if (_grpcClient != null)
                {
                    var getStats = await _grpcClient.GetStatsAsync(context);
                    if (getStats.Succeeded)
                    {
                        aggregatedCounters.Merge(getStats.CounterSet, "ContentServer.");
                    }
                }

                return new GetStatsResult(aggregatedCounters);
            }));
        }
Пример #19
0
        static void Main(string[] args)
        {
            var schemaPath = RegisterCounters();
            PerformanceCounter pc = new PerformanceCounter("Typing", "Words Typed In Interval");
            typingCounterSet = new CounterSet(providerId, typingCounterSetId, CounterSetInstanceType.Single);
            try
            {
                typingCounterSet.AddCounter(1, CounterType.Delta32, "Words Typed In Interval");
                typingCsInstance = typingCounterSet.CreateCounterSetInstance("Typing Instance");
                typingCsInstance.Counters[1].Value = 0;

                System.Diagnostics.Debug.Assert(pc.RawValue == 0);
                typingCsInstance.Counters["Words Typed In Interval"].Increment();
                System.Diagnostics.Debug.Assert(pc.RawValue == 1);
            }
            finally
            {
                typingCounterSet.Dispose();
                UnregisterCounters(schemaPath);
                Directory.Delete(Path.GetDirectoryName(schemaPath), true);
            }
        }
Пример #20
0
        private async Task <GetStatsResult> StatsAsync(Context context)
        {
            var counters = new CounterSet();

            var statsResult = await ContentStore.GetStatsAsync(context).ConfigureAwait(false);

            if (!statsResult.Succeeded)
            {
                return(statsResult);
            }

            counters.Merge(statsResult.CounterSet);

            statsResult = await MemoizationStore.GetStatsAsync(context).ConfigureAwait(false);

            if (!statsResult.Succeeded)
            {
                return(statsResult);
            }

            counters.Merge(statsResult.CounterSet);

            return(new GetStatsResult(counters));
        }
Пример #21
0
        //
        // ProcessListSetPerMachine() helper lists counter sets on a machine.
        // NOTE: machine argument should be NULL for the local machine
        //
        private void ProcessListSetPerMachine(string machine)
        {
            StringCollection counterSets = new StringCollection();
            uint             res         = _pdhHelper.EnumObjects(machine, ref counterSets);

            if (res != 0)
            {
                // add an error message
                string    msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoCounterSetsOnComputer"), machine, res);
                Exception exc = new Exception(msg);
                WriteError(new ErrorRecord(exc, "NoCounterSetsOnComputer", ErrorCategory.InvalidResult, machine));
                return;
            }

            CultureInfo culture = GetCurrentCulture();
            List <Tuple <char, char> > characterReplacementList = null;
            StringCollection           validPaths = new StringCollection();

            _cultureAndSpecialCharacterMap.TryGetValue(culture.Name, out characterReplacementList);

            foreach (string pattern in _listSet)
            {
                bool   bMatched          = false;
                string normalizedPattern = pattern;

                if (characterReplacementList != null)
                {
                    foreach (Tuple <char, char> pair in characterReplacementList)
                    {
                        normalizedPattern = normalizedPattern.Replace(pair.Item1, pair.Item2);
                    }
                }

                WildcardPattern wildLogPattern = new WildcardPattern(normalizedPattern, WildcardOptions.IgnoreCase);

                foreach (string counterSet in counterSets)
                {
                    if (!wildLogPattern.IsMatch(counterSet))
                    {
                        continue;
                    }

                    StringCollection counterSetCounters  = new StringCollection();
                    StringCollection counterSetInstances = new StringCollection();

                    res = _pdhHelper.EnumObjectItems(machine, counterSet, ref counterSetCounters, ref counterSetInstances);
                    if (res == PdhResults.PDH_ACCESS_DENIED)
                    {
                        string    msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterSetEnumAccessDenied"), counterSet);
                        Exception exc = new Exception(msg);
                        WriteError(new ErrorRecord(exc, "CounterSetEnumAccessDenied", ErrorCategory.InvalidResult, null));
                        continue;
                    }
                    else if (res != 0)
                    {
                        ReportPdhError(res, false);
                        continue;
                    }

                    string[] instanceArray = new string[counterSetInstances.Count];
                    int      i             = 0;
                    foreach (string instance in counterSetInstances)
                    {
                        instanceArray[i++] = instance;
                    }

                    //
                    // Special case: no instances present: change to * to create a valid paths
                    //
                    if (instanceArray.Length == 1 &&
                        instanceArray[0].Length == 0)
                    {
                        instanceArray[0] = "*";
                    }

                    Dictionary <string, string[]> counterInstanceMapping = new Dictionary <string, string[]>();
                    foreach (string counter in counterSetCounters)
                    {
                        if (!counterInstanceMapping.ContainsKey(counter))
                        {
                            counterInstanceMapping.Add(counter, instanceArray);
                        }
                    }

                    PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown;
                    if (counterSetInstances.Count > 1)
                    {
                        categoryType = PerformanceCounterCategoryType.MultiInstance;
                    }
                    else // if (counterSetInstances.Count == 1) //???
                    {
                        categoryType = PerformanceCounterCategoryType.SingleInstance;
                    }

                    string setHelp = _pdhHelper.GetCounterSetHelp(machine, counterSet);

                    CounterSet setObj = new CounterSet(counterSet, machine, categoryType, setHelp, ref counterInstanceMapping);
                    WriteObject(setObj);
                    bMatched = true;
                }

                if (!bMatched)
                {
                    string    msg = _resourceMgr.GetString("NoMatchingCounterSetsFound");
                    Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg,
                                                                machine ?? "localhost", normalizedPattern));
                    WriteError(new ErrorRecord(exc, "NoMatchingCounterSetsFound", ErrorCategory.ObjectNotFound, null));
                }
            }
        }
Пример #22
0
        //
        // ProcessListSet().
        // Does the work to process ListSet parameter set.
        //
        private void ProcessListSet()
        {
            uint res = _pdhHelper.ConnectToDataSource(_resolvedPaths);

            if (res != 0)
            {
                ReportPdhError(res, true);
                return;
            }

            StringCollection machineNames = new StringCollection();

            res = _pdhHelper.EnumBlgFilesMachines(ref machineNames);
            if (res != 0)
            {
                ReportPdhError(res, true);
                return;
            }

            foreach (string machine in machineNames)
            {
                StringCollection counterSets = new StringCollection();
                res = _pdhHelper.EnumObjects(machine, ref counterSets);
                if (res != 0)
                {
                    return;
                }

                StringCollection validPaths = new StringCollection();

                foreach (string pattern in _listSet)
                {
                    bool bMatched = false;

                    WildcardPattern wildLogPattern = new WildcardPattern(pattern, WildcardOptions.IgnoreCase);

                    foreach (string counterSet in counterSets)
                    {
                        if (!wildLogPattern.IsMatch(counterSet))
                        {
                            continue;
                        }

                        StringCollection counterSetCounters  = new StringCollection();
                        StringCollection counterSetInstances = new StringCollection();

                        res = _pdhHelper.EnumObjectItems(machine, counterSet, ref counterSetCounters, ref counterSetInstances);
                        if (res != 0)
                        {
                            ReportPdhError(res, false);
                            continue;
                        }

                        string[] instanceArray = new string[counterSetInstances.Count];
                        int      i             = 0;
                        foreach (string instance in counterSetInstances)
                        {
                            instanceArray[i++] = instance;
                        }

                        Dictionary <string, string[]> counterInstanceMapping = new Dictionary <string, string[]>();
                        foreach (string counter in counterSetCounters)
                        {
                            counterInstanceMapping.Add(counter, instanceArray);
                        }

                        PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown;
                        if (counterSetInstances.Count > 1)
                        {
                            categoryType = PerformanceCounterCategoryType.MultiInstance;
                        }
                        else //if (counterSetInstances.Count == 1) //???
                        {
                            categoryType = PerformanceCounterCategoryType.SingleInstance;
                        }

                        string setHelp = _pdhHelper.GetCounterSetHelp(machine, counterSet);

                        CounterSet setObj = new CounterSet(counterSet, machine, categoryType, setHelp, ref counterInstanceMapping);
                        WriteObject(setObj);
                        bMatched = true;
                    }
                    if (!bMatched)
                    {
                        string    msg = _resourceMgr.GetString("NoMatchingCounterSetsInFile");
                        Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg,
                                                                    CommonUtilities.StringArrayToString(_resolvedPaths),
                                                                    pattern));
                        WriteError(new ErrorRecord(exc, "NoMatchingCounterSetsInFile", ErrorCategory.ObjectNotFound, null));
                    }
                }
            }
        }
Пример #23
0
        private void ProcessListSet()
        {
            long res = this._pdhHelper.ConnectToDataSource(this._resolvedPaths);

            if (res != 0)
            {
                this.ReportPdhError(res, true);
            }
            else
            {
                StringCollection machineNames = new StringCollection();
                res = this._pdhHelper.EnumBlgFilesMachines(ref machineNames);
                if (res != 0)
                {
                    this.ReportPdhError(res, true);
                }
                else
                {
                    foreach (string str in machineNames)
                    {
                        StringCollection objectNames = new StringCollection();
                        if (this._pdhHelper.EnumObjects(str, ref objectNames) != 0)
                        {
                            break;
                        }
                        new StringCollection();
                        foreach (string str2 in this._listSet)
                        {
                            bool            flag    = false;
                            WildcardPattern pattern = new WildcardPattern(str2, WildcardOptions.IgnoreCase);
                            foreach (string str3 in objectNames)
                            {
                                if (pattern.IsMatch(str3))
                                {
                                    StringCollection counterNames  = new StringCollection();
                                    StringCollection instanceNames = new StringCollection();
                                    res = this._pdhHelper.EnumObjectItems(str, str3, ref counterNames, ref instanceNames);
                                    if (res != 0)
                                    {
                                        this.ReportPdhError(res, false);
                                    }
                                    else
                                    {
                                        string[] strArray = new string[instanceNames.Count];
                                        int      num2     = 0;
                                        foreach (string str4 in instanceNames)
                                        {
                                            strArray[num2++] = str4;
                                        }
                                        Dictionary <string, string[]> counterInstanceMapping = new Dictionary <string, string[]>();
                                        foreach (string str5 in counterNames)
                                        {
                                            counterInstanceMapping.Add(str5, strArray);
                                        }
                                        PerformanceCounterCategoryType unknown = PerformanceCounterCategoryType.Unknown;
                                        if (instanceNames.Count > 1)
                                        {
                                            unknown = PerformanceCounterCategoryType.MultiInstance;
                                        }
                                        else
                                        {
                                            unknown = PerformanceCounterCategoryType.SingleInstance;
                                        }
                                        string     counterSetHelp = this._pdhHelper.GetCounterSetHelp(str, str3);
                                        CounterSet sendToPipeline = new CounterSet(str3, str, unknown, counterSetHelp, ref counterInstanceMapping);
                                        base.WriteObject(sendToPipeline);
                                        flag = true;
                                    }
                                }
                            }
                            if (!flag)
                            {
                                string    format    = this._resourceMgr.GetString("NoMatchingCounterSetsInFile");
                                Exception exception = new Exception(string.Format(CultureInfo.InvariantCulture, format, new object[] { CommonUtilities.StringArrayToString(this._resolvedPaths), str2 }));
                                base.WriteError(new ErrorRecord(exception, "NoMatchingCounterSetsInFile", ErrorCategory.ObjectNotFound, null));
                            }
                        }
                    }
                }
            }
        }
        public void PerformanceCounter_PerformanceData()
        {
            // We run test in isolated process to avoid interferences on internal performance counter shared state with other tests.
            // These interferences could lead to fail also after retries
            RemoteExecutor.Invoke((string providerId, string typingCounterSetId) =>
            {
                // Create the 'Typing' counter set.
                using (CounterSet typingCounterSet = new CounterSet(Guid.Parse(providerId), Guid.Parse(typingCounterSetId), CounterSetInstanceType.Single))
                {
                    // Add the counters to the counter set definition.
                    typingCounterSet.AddCounter(1, CounterType.RawData32, "Total Words Typed");
                    typingCounterSet.AddCounter(2, CounterType.Delta32, "Words Typed In Interval");
                    typingCounterSet.AddCounter(3, CounterType.RawData32, "Letter A Pressed");
                    typingCounterSet.AddCounter(4, CounterType.RawData32, "Words Containing A");
                    typingCounterSet.AddCounter(5, CounterType.SampleFraction, "Percent of Words Containing A");
                    typingCounterSet.AddCounter(6, CounterType.SampleBase, "Percent Base");
                    typingCounterSet.AddCounter(7, CounterType.SampleBase);

                    // Create an instance of the counter set (contains the counter data).
                    using (CounterSetInstance typingCsInstance = typingCounterSet.CreateCounterSetInstance("Typing Instance"))
                    {
                        typingCsInstance.Counters[1].Value = 0;
                        typingCsInstance.Counters[2].Value = 0;
                        typingCsInstance.Counters[3].Value = 0;
                        typingCsInstance.Counters[4].Value = 0;
                        typingCsInstance.Counters[5].Value = 0;
                        typingCsInstance.Counters[6].Value = 0;

                        // Instance counters readers
                        using (PerformanceCounter totalWordsTyped = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter("Typing", "Total Words Typed")),
                               wordsTypedInInterval = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter("Typing", "Words Typed In Interval")),
                               aKeyPressed = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter("Typing", "Letter A Pressed")),
                               wordsContainingA = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter("Typing", "Words Containing A")),
                               percentofWordsContaingA = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter("Typing", "Percent of Words Containing A")))
                        {
                            typingCsInstance.Counters[1].Increment();
                            Assert.Equal(1, typingCsInstance.Counters[1].Value);
                            Assert.Equal(1, typingCsInstance.Counters[1].RawValue);
                            Assert.Equal(1, typingCsInstance.Counters["Total Words Typed"].RawValue);
                            Assert.Equal(1, totalWordsTyped.RawValue);


                            typingCsInstance.Counters[1].Increment();
                            Assert.Equal(2, typingCsInstance.Counters[1].Value);
                            Assert.Equal(2, typingCsInstance.Counters[1].RawValue);
                            Assert.Equal(2, typingCsInstance.Counters["Total Words Typed"].RawValue);
                            Assert.Equal(2, totalWordsTyped.RawValue);

                            typingCsInstance.Counters[2].IncrementBy(3);
                            Assert.Equal(3, typingCsInstance.Counters[2].Value);
                            Assert.Equal(3, typingCsInstance.Counters[2].RawValue);
                            Assert.Equal(3, typingCsInstance.Counters["Words Typed In Interval"].RawValue);
                            Assert.Equal(3, wordsTypedInInterval.RawValue);

                            typingCsInstance.Counters[3].RawValue = 4;
                            Assert.Equal(4, typingCsInstance.Counters[3].Value);
                            Assert.Equal(4, typingCsInstance.Counters[3].RawValue);
                            Assert.Equal(4, typingCsInstance.Counters["Letter A Pressed"].RawValue);
                            Assert.Equal(4, aKeyPressed.RawValue);

                            typingCsInstance.Counters[4].Value = 5;
                            Assert.Equal(5, typingCsInstance.Counters[4].Value);
                            Assert.Equal(5, typingCsInstance.Counters[4].RawValue);
                            Assert.Equal(5, typingCsInstance.Counters["Words Containing A"].RawValue);
                            Assert.Equal(5, wordsContainingA.RawValue);

                            typingCsInstance.Counters[4].Decrement();
                            Assert.Equal(4, typingCsInstance.Counters[4].Value);
                            Assert.Equal(4, typingCsInstance.Counters[4].RawValue);
                            Assert.Equal(4, typingCsInstance.Counters["Words Containing A"].RawValue);
                            Assert.Equal(4, wordsContainingA.RawValue);
                        }
                    }
                }
            }, _fixture._providerId.ToString(), _fixture._typingCounterSetId.ToString()).Dispose();
        }
Пример #25
0
        private void ProcessListSetPerMachine(string machine)
        {
            StringCollection objectNames = new StringCollection();
            long             res         = this._pdhHelper.EnumObjects(machine, ref objectNames);

            if (res != 0)
            {
                Exception exception = new Exception(string.Format(CultureInfo.InvariantCulture, this._resourceMgr.GetString("NoCounterSetsOnComputer"), new object[] { machine, res }));
                base.WriteError(new ErrorRecord(exception, "NoCounterSetsOnComputer", ErrorCategory.InvalidResult, machine));
            }
            else
            {
                new StringCollection();
                foreach (string str2 in this._listSet)
                {
                    bool            flag    = false;
                    WildcardPattern pattern = new WildcardPattern(str2, WildcardOptions.IgnoreCase);
                    foreach (string str3 in objectNames)
                    {
                        if (pattern.IsMatch(str3))
                        {
                            StringCollection counterNames  = new StringCollection();
                            StringCollection instanceNames = new StringCollection();
                            res = this._pdhHelper.EnumObjectItems(machine, str3, ref counterNames, ref instanceNames);
                            if (res == 0xc0000bdbL)
                            {
                                Exception exception2 = new Exception(string.Format(CultureInfo.InvariantCulture, this._resourceMgr.GetString("CounterSetEnumAccessDenied"), new object[] { str3 }));
                                base.WriteError(new ErrorRecord(exception2, "CounterSetEnumAccessDenied", ErrorCategory.InvalidResult, null));
                            }
                            else if (res != 0)
                            {
                                this.ReportPdhError(res, false);
                            }
                            else
                            {
                                string[] strArray = new string[instanceNames.Count];
                                int      num2     = 0;
                                foreach (string str5 in instanceNames)
                                {
                                    strArray[num2++] = str5;
                                }
                                if ((strArray.Length == 1) && (strArray[0].Length == 0))
                                {
                                    strArray[0] = "*";
                                }
                                Dictionary <string, string[]> counterInstanceMapping = new Dictionary <string, string[]>();
                                foreach (string str6 in counterNames)
                                {
                                    if (!counterInstanceMapping.ContainsKey(str6))
                                    {
                                        counterInstanceMapping.Add(str6, strArray);
                                    }
                                }
                                PerformanceCounterCategoryType unknown = PerformanceCounterCategoryType.Unknown;
                                if (instanceNames.Count > 1)
                                {
                                    unknown = PerformanceCounterCategoryType.MultiInstance;
                                }
                                else
                                {
                                    unknown = PerformanceCounterCategoryType.SingleInstance;
                                }
                                string     counterSetHelp = this._pdhHelper.GetCounterSetHelp(machine, str3);
                                CounterSet sendToPipeline = new CounterSet(str3, machine, unknown, counterSetHelp, ref counterInstanceMapping);
                                base.WriteObject(sendToPipeline);
                                flag = true;
                            }
                        }
                    }
                    if (!flag)
                    {
                        string    format     = this._resourceMgr.GetString("NoMatchingCounterSetsFound");
                        Exception exception3 = new Exception(string.Format(CultureInfo.InvariantCulture, format, new object[] { (machine == null) ? "localhost" : machine, str2 }));
                        base.WriteError(new ErrorRecord(exception3, "NoMatchingCounterSetsFound", ErrorCategory.ObjectNotFound, null));
                    }
                }
            }
        }
Пример #26
0
 internal ServicePerformanceCountersV2(ServiceHostBase serviceHost)
     : base(serviceHost)
 {
     if (serviceCounterSet == null)
     {
         lock (syncRoot)
         {
             if (serviceCounterSet == null)
             {
                 CounterSet localCounterSet = CreateCounterSet();
                 // Add the counters to the counter set definition.
                 localCounterSet.AddCounter((int)PerfCounters.Calls, CounterType.RawData32, perfCounterNames[(int)PerfCounters.Calls]);
                 localCounterSet.AddCounter((int)PerfCounters.CallsPerSecond, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.CallsPerSecond]);
                 localCounterSet.AddCounter((int)PerfCounters.CallsOutstanding, CounterType.RawData32, perfCounterNames[(int)PerfCounters.CallsOutstanding]);
                 localCounterSet.AddCounter((int)PerfCounters.CallsFailed, CounterType.RawData32, perfCounterNames[(int)PerfCounters.CallsFailed]);
                 localCounterSet.AddCounter((int)PerfCounters.CallsFailedPerSecond, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.CallsFailedPerSecond]);
                 localCounterSet.AddCounter((int)PerfCounters.CallsFaulted, CounterType.RawData32, perfCounterNames[(int)PerfCounters.CallsFaulted]);
                 localCounterSet.AddCounter((int)PerfCounters.CallsFaultedPerSecond, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.CallsFaultedPerSecond]);
                 localCounterSet.AddCounter((int)PerfCounters.CallDurationBase, CounterType.AverageBase, perfCounterNames[(int)PerfCounters.CallDurationBase]);
                 localCounterSet.AddCounter((int)PerfCounters.CallDuration, CounterType.AverageTimer32, perfCounterNames[(int)PerfCounters.CallDuration]);
                 localCounterSet.AddCounter((int)PerfCounters.SecurityValidationAuthenticationFailures, CounterType.RawData32, perfCounterNames[(int)PerfCounters.SecurityValidationAuthenticationFailures]);
                 localCounterSet.AddCounter((int)PerfCounters.SecurityValidationAuthenticationFailuresPerSecond, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.SecurityValidationAuthenticationFailuresPerSecond]);
                 localCounterSet.AddCounter((int)PerfCounters.CallsNotAuthorized, CounterType.RawData32, perfCounterNames[(int)PerfCounters.CallsNotAuthorized]);
                 localCounterSet.AddCounter((int)PerfCounters.CallsNotAuthorizedPerSecond, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.CallsNotAuthorizedPerSecond]);
                 localCounterSet.AddCounter((int)PerfCounters.Instances, CounterType.RawData32, perfCounterNames[(int)PerfCounters.Instances]);
                 localCounterSet.AddCounter((int)PerfCounters.InstancesRate, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.InstancesRate]);
                 localCounterSet.AddCounter((int)PerfCounters.RMSessionsFaulted, CounterType.RawData32, perfCounterNames[(int)PerfCounters.RMSessionsFaulted]);
                 localCounterSet.AddCounter((int)PerfCounters.RMSessionsFaultedPerSecond, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.RMSessionsFaultedPerSecond]);
                 localCounterSet.AddCounter((int)PerfCounters.RMMessagesDropped, CounterType.RawData32, perfCounterNames[(int)PerfCounters.RMMessagesDropped]);
                 localCounterSet.AddCounter((int)PerfCounters.RMMessagesDroppedPerSecond, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.RMMessagesDroppedPerSecond]);
                 localCounterSet.AddCounter((int)PerfCounters.TxFlowed, CounterType.RawData32, perfCounterNames[(int)PerfCounters.TxFlowed]);
                 localCounterSet.AddCounter((int)PerfCounters.TxFlowedPerSecond, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.TxFlowedPerSecond]);
                 localCounterSet.AddCounter((int)PerfCounters.TxCommitted, CounterType.RawData32, perfCounterNames[(int)PerfCounters.TxCommitted]);
                 localCounterSet.AddCounter((int)PerfCounters.TxCommittedPerSecond, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.TxCommittedPerSecond]);
                 localCounterSet.AddCounter((int)PerfCounters.TxAborted, CounterType.RawData32, perfCounterNames[(int)PerfCounters.TxAborted]);
                 localCounterSet.AddCounter((int)PerfCounters.TxAbortedPerSecond, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.TxAbortedPerSecond]);
                 localCounterSet.AddCounter((int)PerfCounters.TxInDoubt, CounterType.RawData32, perfCounterNames[(int)PerfCounters.TxInDoubt]);
                 localCounterSet.AddCounter((int)PerfCounters.TxInDoubtPerSecond, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.TxInDoubtPerSecond]);
                 localCounterSet.AddCounter((int)PerfCounters.MsmqPoisonMessages, CounterType.RawData32, perfCounterNames[(int)PerfCounters.MsmqPoisonMessages]);
                 localCounterSet.AddCounter((int)PerfCounters.MsmqPoisonMessagesPerSecond, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.MsmqPoisonMessagesPerSecond]);
                 localCounterSet.AddCounter((int)PerfCounters.MsmqRejectedMessages, CounterType.RawData32, perfCounterNames[(int)PerfCounters.MsmqRejectedMessages]);
                 localCounterSet.AddCounter((int)PerfCounters.MsmqRejectedMessagesPerSecond, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.MsmqRejectedMessagesPerSecond]);
                 localCounterSet.AddCounter((int)PerfCounters.MsmqDroppedMessages, CounterType.RawData32, perfCounterNames[(int)PerfCounters.MsmqDroppedMessages]);
                 localCounterSet.AddCounter((int)PerfCounters.MsmqDroppedMessagesPerSecond, CounterType.RateOfCountPerSecond32, perfCounterNames[(int)PerfCounters.MsmqDroppedMessagesPerSecond]);
                 localCounterSet.AddCounter((int)PerfCounters.CallsPercentMaxCalls, CounterType.RawFraction32, perfCounterNames[(int)PerfCounters.CallsPercentMaxCalls]);
                 localCounterSet.AddCounter((int)PerfCounters.CallsPercentMaxCallsBase, CounterType.RawBase32, perfCounterNames[(int)PerfCounters.CallsPercentMaxCallsBase]);
                 localCounterSet.AddCounter((int)PerfCounters.InstancesPercentMaxInstances, CounterType.RawFraction32, perfCounterNames[(int)PerfCounters.InstancesPercentMaxInstances]);
                 localCounterSet.AddCounter((int)PerfCounters.InstancesPercentMaxInstancesBase, CounterType.RawBase32, perfCounterNames[(int)PerfCounters.InstancesPercentMaxInstancesBase]);
                 localCounterSet.AddCounter((int)PerfCounters.SessionsPercentMaxSessions, CounterType.RawFraction32, perfCounterNames[(int)PerfCounters.SessionsPercentMaxSessions]);
                 localCounterSet.AddCounter((int)PerfCounters.SessionsPercentMaxSessionsBase, CounterType.RawBase32, perfCounterNames[(int)PerfCounters.SessionsPercentMaxSessionsBase]);
                 serviceCounterSet = localCounterSet;
             }
         }
     }
     // Create an instance of the counter set (contains the counter data).
     this.serviceCounterSetInstance = CreateCounterSetInstance(this.InstanceName);
     this.counters = new CounterData[(int)PerfCounters.TotalCounters]; // Cache to dodge dictionary lookups in ServiceModelInstance
     for (int i = 0; i < (int)PerfCounters.TotalCounters; i++)
     {
         this.counters[i]       = this.serviceCounterSetInstance.Counters[i];
         this.counters[i].Value = 0;
     }
 }
 internal CounterSetInstance(CounterSet counterSetDefined, string instanceName)
 {
 }
Пример #28
0
        static void Main(string[] args)
        {
            // Initialize the provider and counters

            Guid providerId = new Guid("{5AE84FD4-BF72-49c4-936E-A7473237C338}");

            Guid       geometricWavesCounterSetId = new Guid("{F7DC6E2D-9A3F-4239-AC8D-28DCE96CCA98}");
            CounterSet geometricWavesCounterSet   = new CounterSet(providerId, geometricWavesCounterSetId, CounterSetInstanceType.MultipleAggregate);

            geometricWavesCounterSet.AddCounter(1, CounterType.RawData32); //"Triangle Wave"
            geometricWavesCounterSet.AddCounter(2, CounterType.RawData32); //"Square Wave"
            CounterSetInstance geomCsInstance1 = geometricWavesCounterSet.CreateCounterSetInstance("Instance_1");
            CounterSetInstance geomCsInstance2 = geometricWavesCounterSet.CreateCounterSetInstance("Instance_2");
            CounterSetInstance geomCsInstance3 = geometricWavesCounterSet.CreateCounterSetInstance("Instance_3");

            Guid       trigWavesCounterSetId = new Guid("{F89A016D-A5D1-4ce2-8489-D5612FDD2C6F}");
            CounterSet trigWavesCounterSet   = new CounterSet(providerId, trigWavesCounterSetId, CounterSetInstanceType.Single);

            trigWavesCounterSet.AddCounter(1, CounterType.RawData32);     //"Sine Wave"
            trigWavesCounterSet.AddCounter(2, CounterType.RawData32);     //"Cosine Wave"
            trigWavesCounterSet.AddCounter(3, CounterType.RawData32);     //"Constant Value"
            trigWavesCounterSet.AddCounter(4, CounterType.RawBase32);     //"Constant Number"
            trigWavesCounterSet.AddCounter(5, CounterType.RawFraction32); //"Raw Fraction"
            CounterSetInstance trigCsInstance = trigWavesCounterSet.CreateCounterSetInstance("_Default");

            // Initialize variables used in counter calculations.
            UInt32 Degree         = 0;
            UInt32 Base           = BASE;
            UInt32 NaturalNumbers = 1;
            double Angle          = 0;
            UInt32 Sine           = 0;
            UInt32 Cosine         = 0;

            // Set the constant counter value.
            trigCsInstance.Counters[4].Value = BASE;

            Console.WriteLine("\tPress any key to quit");
            while (!Console.KeyAvailable)
            {
                // Increment the Degree value to between 0 - 360.
                Degree = (Degree + 10) % 360;

                // Increment the Natural Number counter. Set it to 1 if we reach 100.
                NaturalNumbers = ++NaturalNumbers % 100;

                Angle  = (((double)Degree) * M_PI) / (180.00);
                Sine   = Base + (UInt32)(AMPLITUDE * Math.Sin(Angle));
                Cosine = Base + (UInt32)(AMPLITUDE * Math.Cos(Angle));

                // Set raw counter data for SingleInstanceCounterSet.
                UpdataGeometricWave(geomCsInstance1, 30, Degree);
                UpdataGeometricWave(geomCsInstance2, 50, Degree);
                UpdataGeometricWave(geomCsInstance3, 80, Degree);

                //Update TrigonometricWave counters
                trigCsInstance.Counters[1].Value = Sine;
                trigCsInstance.Counters[2].Value = Cosine;
                trigCsInstance.Counters[3].Value = Base;
                trigCsInstance.Counters[5].Value = NaturalNumbers;

                //Sleep for 1 second before iterating once again to change the counter values.
                Thread.Sleep(TIME_INTERVAL);
            }
        }