Exemple #1
0
        internal CounterSetInstanceCounterDataSet(CounterSetInstance thisInst)
        {
            _instance = thisInst;
            _counters = new Dictionary <int, CounterData>();

            unsafe
            {
                if (_instance._counterSet._provider == null)
                {
                    throw new ArgumentException(SR.Format(SR.Perflib_Argument_ProviderNotFound, _instance._counterSet._providerGuid), "ProviderGuid");
                }
                if (_instance._counterSet._provider._hProvider.IsInvalid)
                {
                    throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _instance._counterSet._providerGuid));
                }

                _dataBlock = (byte *)Marshal.AllocHGlobal(_instance._counterSet._idToCounter.Count * sizeof(long));
                if (_dataBlock == null)
                {
                    throw new InsufficientMemoryException(SR.Format(SR.Perflib_InsufficientMemory_InstanceCounterBlock, _instance._counterSet._counterSet, _instance._instName));
                }

                int CounterOffset = 0;

                foreach (KeyValuePair <int, CounterType> CounterDef in _instance._counterSet._idToCounter)
                {
                    CounterData thisCounterData = new CounterData((long *)(_dataBlock + CounterOffset * sizeof(long)));

                    _counters.Add(CounterDef.Key, thisCounterData);

                    // ArgumentNullException - CounterName is NULL
                    // ArgumentException - CounterName already exists.
                    uint Status = Interop.PerfCounter.PerfSetCounterRefValue(
                        _instance._counterSet._provider._hProvider,
                        _instance._nativeInst,
                        (uint)CounterDef.Key,
                        (void *)(_dataBlock + CounterOffset * sizeof(long)));
                    if (Status != (uint)Interop.Errors.ERROR_SUCCESS)
                    {
                        Dispose(true);

                        // ERROR_INVALID_PARAMETER or ERROR_NOT_FOUND
                        switch (Status)
                        {
                        case (uint)Interop.Errors.ERROR_NOT_FOUND:
                            throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_CounterRefValue, _instance._counterSet._counterSet, CounterDef.Key, _instance._instName));

                        default:
                            throw new Win32Exception((int)Status);
                        }
                    }
                    CounterOffset++;
                }
            }
        }
 internal EndpointPerformanceCountersV2(string service, string contract, string uri) : base(service, contract, uri)
 {
     EnsureCounterSet();
     this.endpointCounterSetInstance = CreateCounterSetInstance(this.InstanceName);
     this.counters = new CounterData[0x13];
     for (int i = 0; i < 0x13; i++)
     {
         this.counters[i] = this.endpointCounterSetInstance.Counters[i];
         this.counters[i].Value = 0L;
     }
 }
        internal CounterSetInstanceCounterDataSet(CounterSetInstance thisInst)
        {
            m_instance = thisInst;
            m_counters = new Dictionary <Int32, CounterData>();

            unsafe {
                if (m_instance.m_counterSet.m_provider == null)
                {
                    throw new ArgumentException(SR.GetString(SR.Perflib_Argument_ProviderNotFound, m_instance.m_counterSet.m_providerGuid), "ProviderGuid");
                }
                if (m_instance.m_counterSet.m_provider.m_hProvider.IsInvalid)
                {
                    throw new InvalidOperationException(SR.GetString(SR.Perflib_InvalidOperation_NoActiveProvider, m_instance.m_counterSet.m_providerGuid));
                }

                m_dataBlock = (byte *)Marshal.AllocHGlobal(m_instance.m_counterSet.m_idToCounter.Count * sizeof(Int64));
                if (m_dataBlock == null)
                {
                    throw new InsufficientMemoryException(SR.GetString(SR.Perflib_InsufficientMemory_InstanceCounterBlock, m_instance.m_counterSet.m_counterSet, m_instance.m_instName));
                }

                Int32 CounterOffset = 0;

                foreach (KeyValuePair <Int32, CounterType> CounterDef in m_instance.m_counterSet.m_idToCounter)
                {
                    CounterData thisCounterData = new CounterData((Int64 *)(m_dataBlock + CounterOffset * sizeof(Int64)));

                    m_counters.Add(CounterDef.Key, thisCounterData);
                    // ArgumentNullException - CounterName is NULL
                    // ArgumentException - CounterName already exists.

                    uint Status = UnsafeNativeMethods.PerfSetCounterRefValue(
                        m_instance.m_counterSet.m_provider.m_hProvider,
                        m_instance.m_nativeInst,
                        (uint)CounterDef.Key,
                        (void *)(m_dataBlock + CounterOffset * sizeof(Int64)));
                    if (Status != (uint)UnsafeNativeMethods.ERROR_SUCCESS)
                    {
                        Dispose(true);

                        // ERROR_INVALID_PARAMETER or ERROR_NOT_FOUND
                        switch (Status)
                        {
                        case (uint)UnsafeNativeMethods.ERROR_NOT_FOUND:
                            throw new InvalidOperationException(SR.GetString(SR.Perflib_InvalidOperation_CounterRefValue, m_instance.m_counterSet.m_counterSet, CounterDef.Key, m_instance.m_instName));

                        default:
                            throw new Win32Exception((int)Status);
                        }
                    }
                    CounterOffset++;
                }
            }
        }
 internal OperationPerformanceCountersV2(string service, string contract, string operationName, string uri) : base(service, contract, operationName, uri)
 {
     EnsureCounterSet();
     this.operationCounterSetInstance = CreateCounterSetInstance(this.InstanceName);
     this.counters = new CounterData[15];
     for (int i = 0; i < 15; i++)
     {
         this.counters[i] = this.operationCounterSetInstance.Counters[i];
         this.counters[i].Value = 0L;
     }
 }
Exemple #5
0
		public PerfCounters(Uri instanceName)
		{
			this.providerGuid = new Guid("{b0f9d01b-71f3-4d7d-b69e-5d1c5932b74d}");
			this.providerCounterSetGuid = new Guid("{e711142e-c6b7-41a9-ac1a-aa63c936cd55}");
			this.counterSet = new CounterSet(this.providerGuid, this.providerCounterSetGuid, CounterSetInstanceType.Multiple);
			this.counterSet.AddCounter(1, CounterType.RawData32);
			this.counterSet.AddCounter(2, CounterType.RawData32);
			this.counterSet.AddCounter(3, CounterType.RawData32);
			this.counterSet.AddCounter(4, CounterType.RateOfCountPerSecond32);
			this.counterSet.AddCounter(5, CounterType.RateOfCountPerSecond32);
			this.counterSetInstance = this.CreateInstance(instanceName);
		}
 internal EndpointPerformanceCountersV2(string service, string contract, string uri)
     : base(service, contract, uri)
 {
     EnsureCounterSet();
     // Create an instance of the counter set (contains the counter data).
     this.endpointCounterSetInstance = 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.endpointCounterSetInstance.Counters[i];
         this.counters[i].Value = 0;
     }
 }
 protected override void Dispose(bool disposing)
 {
     try
     {
         if ((disposing && PerformanceCounters.PerformanceCountersEnabled) && (this.operationCounterSetInstance != null))
         {
             this.operationCounterSetInstance.Dispose();
             this.operationCounterSetInstance = null;
         }
     }
     finally
     {
         base.Dispose(disposing);
     }
 }
 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);
 }
Exemple #9
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;
     }
 }
        internal unsafe CounterSetInstanceCounterDataSet(CounterSetInstance thisInst)
        {
            this.m_instance = thisInst;
            this.m_counters = new Dictionary <int, CounterData>();
            if (this.m_instance.m_counterSet.m_provider == null)
            {
                throw new ArgumentException(System.SR.GetString("Perflib_Argument_ProviderNotFound", new object[] { this.m_instance.m_counterSet.m_providerGuid }), "ProviderGuid");
            }
            if (this.m_instance.m_counterSet.m_provider.m_hProvider.IsInvalid)
            {
                throw new InvalidOperationException(System.SR.GetString("Perflib_InvalidOperation_NoActiveProvider", new object[] { this.m_instance.m_counterSet.m_providerGuid }));
            }
            this.m_dataBlock = (byte *)Marshal.AllocHGlobal((int)(this.m_instance.m_counterSet.m_idToCounter.Count * 8));
            if (this.m_dataBlock == null)
            {
                throw new InsufficientMemoryException(System.SR.GetString("Perflib_InsufficientMemory_InstanceCounterBlock", new object[] { this.m_instance.m_counterSet.m_counterSet, this.m_instance.m_instName }));
            }
            int num = 0;

            foreach (KeyValuePair <int, CounterType> pair in this.m_instance.m_counterSet.m_idToCounter)
            {
                CounterData data = new CounterData((long)(this.m_dataBlock + (num * 8)));
                this.m_counters.Add(pair.Key, data);
                int num2 = Microsoft.Win32.UnsafeNativeMethods.PerfSetCounterRefValue(this.m_instance.m_counterSet.m_provider.m_hProvider, this.m_instance.m_nativeInst, pair.Key, (void *)(this.m_dataBlock + (num * 8)));
                if (num2 != 0)
                {
                    this.Dispose(true);
                    switch (num2)
                    {
                    case 0x490:
                        throw new InvalidOperationException(System.SR.GetString("Perflib_InvalidOperation_CounterRefValue", new object[] { this.m_instance.m_counterSet.m_counterSet, pair.Key, this.m_instance.m_instName }));
                    }
                    throw new Win32Exception((int)num2);
                }
                num++;
            }
        }
 internal unsafe CounterSetInstanceCounterDataSet(CounterSetInstance thisInst)
 {
     this.m_instance = thisInst;
     this.m_counters = new Dictionary<int, CounterData>();
     if (this.m_instance.m_counterSet.m_provider == null)
     {
         throw new ArgumentException(System.SR.GetString("Perflib_Argument_ProviderNotFound", new object[] { this.m_instance.m_counterSet.m_providerGuid }), "ProviderGuid");
     }
     if (this.m_instance.m_counterSet.m_provider.m_hProvider.IsInvalid)
     {
         throw new InvalidOperationException(System.SR.GetString("Perflib_InvalidOperation_NoActiveProvider", new object[] { this.m_instance.m_counterSet.m_providerGuid }));
     }
     this.m_dataBlock = (byte*) Marshal.AllocHGlobal((int) (this.m_instance.m_counterSet.m_idToCounter.Count * 8));
     if (this.m_dataBlock == null)
     {
         throw new InsufficientMemoryException(System.SR.GetString("Perflib_InsufficientMemory_InstanceCounterBlock", new object[] { this.m_instance.m_counterSet.m_counterSet, this.m_instance.m_instName }));
     }
     int num = 0;
     foreach (KeyValuePair<int, CounterType> pair in this.m_instance.m_counterSet.m_idToCounter)
     {
         CounterData data = new CounterData((long)(this.m_dataBlock + (num * 8)));
         this.m_counters.Add(pair.Key, data);
         int num2 = Microsoft.Win32.UnsafeNativeMethods.PerfSetCounterRefValue(this.m_instance.m_counterSet.m_provider.m_hProvider, this.m_instance.m_nativeInst, pair.Key, (void*) (this.m_dataBlock + (num * 8)));
         if (num2 != 0)
         {
             this.Dispose(true);
             switch (num2)
             {
                 case 0x490:
                     throw new InvalidOperationException(System.SR.GetString("Perflib_InvalidOperation_CounterRefValue", new object[] { this.m_instance.m_counterSet.m_counterSet, pair.Key, this.m_instance.m_instName }));
             }
             throw new Win32Exception((int) num2);
         }
         num++;
     }
 }
        /// <summary>
        /// Helper function to generate the triangle wave and square wave for the counters.
        /// </summary>
        /// <param name="CsInstance"> CounterSetInstance object which needs the value update.</param>
        /// <param name="MinimalValue"> The minimal value for the counters.</param>
        /// <param name="Degree"> Generate the data according to this value.</param>
        static void UpdataGeometricWave(CounterSetInstance CsInstance, UInt32 MinimalValue, UInt32 Degree)
        {
            long High;
            UInt32 Increase;

            High = ((Degree % 180) > 90) ? ALTITUDE : -ALTITUDE;
            CsInstance.Counters[2].Value = MinimalValue + High; //"Square Wave"

            Increase = (Degree < 180) ? Degree : 360 - Degree;
            Increase = (UInt32)((double)ALTITUDE / 180 * Increase);
            CsInstance.Counters[1].Value = MinimalValue + Increase; //"Triangle Wave"
        }
        internal void InitializePerformanceCounters()
        {
            this.instanceName = CreateFriendlyInstanceName(this.serviceHost);

            if (PerformanceCounters.PerformanceCountersEnabled)
            {
                EnsureCounterSet();
                // Create an instance of the counter set (contains the counter data).
                this.workflowServiceHostCounterSetInstance = CreateCounterSetInstance(this.InstanceName);

                if (this.workflowServiceHostCounterSetInstance != null)
                {
                    this.counters = new CounterData[(int)PerfCounters.TotalCounters]; 
                    for (int i = 0; i < (int)PerfCounters.TotalCounters; i++)
                    {
                        this.counters[i] = this.workflowServiceHostCounterSetInstance.Counters[i];
                        this.counters[i].Value = 0;
                    }
                    // Enable perf counter only if CounterSetInstance is created without instance name conflict. 
                    this.isPerformanceCounterEnabled = PerformanceCounters.PerformanceCountersEnabled;
                }
            }
            this.initialized = true;
        }
        internal CounterSetInstanceCounterDataSet(CounterSetInstance thisInst) {
            m_instance = thisInst;
            m_counters = new Dictionary<Int32, CounterData>();

            unsafe {
                if (m_instance.m_counterSet.m_provider == null) {
                    throw new ArgumentException(SR.GetString(SR.Perflib_Argument_ProviderNotFound, m_instance.m_counterSet.m_providerGuid), "ProviderGuid");
                }
                if (m_instance.m_counterSet.m_provider.m_hProvider.IsInvalid) {
                    throw new InvalidOperationException(SR.GetString(SR.Perflib_InvalidOperation_NoActiveProvider, m_instance.m_counterSet.m_providerGuid));
                }

                m_dataBlock = (byte *) Marshal.AllocHGlobal(m_instance.m_counterSet.m_idToCounter.Count * sizeof(Int64));
                if (m_dataBlock == null) {
                    throw new InsufficientMemoryException(SR.GetString(SR.Perflib_InsufficientMemory_InstanceCounterBlock, m_instance.m_counterSet.m_counterSet, m_instance.m_instName));
                }

                Int32 CounterOffset = 0;

                foreach (KeyValuePair<Int32, CounterType> CounterDef in m_instance.m_counterSet.m_idToCounter) {
                    CounterData thisCounterData = new CounterData((Int64 *) (m_dataBlock + CounterOffset * sizeof(Int64)));

                    m_counters.Add(CounterDef.Key, thisCounterData);
                    // ArgumentNullException - CounterName is NULL
                    // ArgumentException - CounterName already exists.

                    uint Status = UnsafeNativeMethods.PerfSetCounterRefValue(
                                    m_instance.m_counterSet.m_provider.m_hProvider,
                                    m_instance.m_nativeInst,
                                    (uint) CounterDef.Key,
                                    (void *) (m_dataBlock + CounterOffset * sizeof(Int64)));
                    if (Status != (uint) UnsafeNativeMethods.ERROR_SUCCESS) {
                        Dispose(true);

                        // ERROR_INVALID_PARAMETER or ERROR_NOT_FOUND
                        switch (Status) {
                            case (uint) UnsafeNativeMethods.ERROR_NOT_FOUND:
                                throw new InvalidOperationException(SR.GetString(SR.Perflib_InvalidOperation_CounterRefValue, m_instance.m_counterSet.m_counterSet, CounterDef.Key, m_instance.m_instName));

                            default:
                                throw new Win32Exception((int) Status);
                        }
                    }
                    CounterOffset ++;
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Create instances of the CounterSet. Created CounterSetInstance identifies active identity and tracks raw counter data for that identity.
        /// </summary>
        /// <param name="instanceName">Friendly name identifies the instance. InstanceName would be shown in counter consumption applications like perfmon.</param>
        /// <returns>CounterSetInstance object</returns>
        public CounterSetInstance CreateCounterSetInstance(string instanceName)
        {
            if (instanceName == null)
            {
                throw new ArgumentNullException(nameof(instanceName));
            }
            if (instanceName.Length == 0)
            {
                throw new ArgumentException(SR.Format(SR.Perflib_Argument_EmptyInstanceName), nameof(instanceName));
            }
            if (_provider == null)
            {
                throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
            }
            if (!_instanceCreated)
            {
                lock (_lockObject)
                {
                    if (!_instanceCreated)
                    {
                        if (_provider == null)
                        {
                            throw new ArgumentException(SR.Format(SR.Perflib_Argument_ProviderNotFound, _providerGuid), "ProviderGuid");
                        }
                        if (_provider._hProvider.IsInvalid)
                        {
                            throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
                        }
                        if (_idToCounter.Count == 0)
                        {
                            throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_CounterSetContainsNoCounter, _counterSet));
                        }

                        uint Status = (uint)Interop.Errors.ERROR_SUCCESS;

                        unsafe
                        {
                            uint CounterSetInfoSize = (uint)sizeof(Interop.PerfCounter.PerfCounterSetInfoStruct)
                                                      + (uint)_idToCounter.Count * (uint)sizeof(Interop.PerfCounter.PerfCounterInfoStruct);
                            uint  CounterSetInfoUsed = 0;
                            byte *CounterSetBuffer   = stackalloc byte[(int)CounterSetInfoSize];

                            Debug.Assert(sizeof(Interop.PerfCounter.PerfCounterSetInfoStruct) == 40);
                            Debug.Assert(sizeof(Interop.PerfCounter.PerfCounterInfoStruct) == 32);

                            Interop.PerfCounter.PerfCounterSetInfoStruct *CounterSetInfo;
                            Interop.PerfCounter.PerfCounterInfoStruct *   CounterInfo;

                            uint CurrentCounter = 0;
                            uint CurrentOffset  = 0;

                            CounterSetInfo = (Interop.PerfCounter.PerfCounterSetInfoStruct *)CounterSetBuffer;
                            CounterSetInfo->CounterSetGuid = _counterSet;
                            CounterSetInfo->ProviderGuid   = _providerGuid;
                            CounterSetInfo->NumCounters    = (uint)_idToCounter.Count;
                            CounterSetInfo->InstanceType   = (uint)_instType;

                            foreach (KeyValuePair <int, CounterType> CounterDef in _idToCounter)
                            {
                                CounterSetInfoUsed = (uint)sizeof(Interop.PerfCounter.PerfCounterSetInfoStruct)
                                                     + (uint)CurrentCounter * (uint)sizeof(Interop.PerfCounter.PerfCounterInfoStruct);
                                if (CounterSetInfoUsed < CounterSetInfoSize)
                                {
                                    CounterInfo              = (Interop.PerfCounter.PerfCounterInfoStruct *)(CounterSetBuffer + CounterSetInfoUsed);
                                    CounterInfo->CounterId   = (uint)CounterDef.Key;
                                    CounterInfo->CounterType = (uint)CounterDef.Value;
                                    CounterInfo->Attrib      = 0x0000000000000001;   // PERF_ATTRIB_BY_REFERENCE
                                    CounterInfo->Size        = (uint)sizeof(void *); // always use pointer size
                                    CounterInfo->DetailLevel = 100;                  // PERF_DETAIL_NOVICE
                                    CounterInfo->Scale       = 0;                    // Default scale
                                    CounterInfo->Offset      = CurrentOffset;

                                    CurrentOffset += CounterInfo->Size;
                                }
                                CurrentCounter++;
                            }
                            Status = Interop.PerfCounter.PerfSetCounterSetInfo(_provider._hProvider, CounterSetInfo, CounterSetInfoSize);

                            // ERROR_INVALID_PARAMETER, ERROR_ALREADY_EXISTS, ERROR_NOT_ENOUGH_MEMORY, ERROR_OUTOFMEMORY
                            if (Status != (uint)Interop.Errors.ERROR_SUCCESS)
                            {
                                switch (Status)
                                {
                                case (uint)Interop.Errors.ERROR_ALREADY_EXISTS:
                                    throw new ArgumentException(SR.Format(SR.Perflib_Argument_CounterSetAlreadyRegister, _counterSet), "CounterSetGuid");

                                default:
                                    throw new Win32Exception((int)Status);
                                }
                            }

                            Interlocked.Increment(ref _provider._counterSet);
                        }

                        _instanceCreated = true;
                    }
                }
            }

            CounterSetInstance thisInst = new CounterSetInstance(this, instanceName);

            return(thisInst);
        }
Exemple #16
0
		protected virtual void Dispose(bool disposeManagedResources)
		{
			if (disposeManagedResources && !this.disposed)
			{
				if (this.counterSetInstance != null)
				{
					this.counterSetInstance.Dispose();
					this.counterSetInstance = null;
				}
				if (this.counterSet != null)
				{
					this.counterSet.Dispose();
					this.counterSet = null;
				}
				this.disposed = true;
			}
		}
Exemple #17
0
		public PerfCounter(CounterSetInstance counterSetInstance, int counterId)
		{
			this.counterId = counterId;
			this.counterSetInstance = counterSetInstance;
		}
 // Immediately disposes and nulls the CounterSetInstance. This differs from Dispose because Dispose is "lazy" in that
 // it holds weak references to the instances so we don't get corrupted state if the values are updated later. This
 // method is used in situations when we need to delete the instance immediately and know the values won't be updated.
 internal void DeleteInstance()
 {
     if (this.operationCounterSetInstance != null)
     {
         this.operationCounterSetInstance.Dispose();
         this.operationCounterSetInstance = null;
     }
 }
 // Immediately disposes and nulls the CounterSetInstance. This differs from Dispose because Dispose is "lazy" in that
 // it holds weak references to the instances so we don't get corrupted state if the values are updated later. This
 // method is used in situations when we need to delete the instance immediately and know the values won't be updated.
 internal void DeleteInstance()
 {
     if (this.serviceCounterSetInstance != null)
     {
         this.serviceCounterSetInstance.Dispose();
         this.serviceCounterSetInstance = null;
     }
 }
 protected override void Dispose(bool disposing)
 {
     try
     {
         if (disposing && this.workflowServiceHostCounterSetInstance != null)
         {
             this.workflowServiceHostCounterSetInstance.Dispose();
             this.workflowServiceHostCounterSetInstance = null;
             this.isPerformanceCounterEnabled = false;
         }
     }
     finally
     {
         base.Dispose(disposing);
     }
 }
        private void CreateCounterSetInstance()
        {
            _CounterSet =
                new CounterSet(
                    base._counterSetRegistrarBase.ProviderId,
                    base._counterSetRegistrarBase.CounterSetId,
                    base._counterSetRegistrarBase.CounterSetInstType);

            // Add the counters to the counter set definition.
            foreach (CounterInfo counterInfo in base._counterSetRegistrarBase.CounterInfoArray)
            {
                if (counterInfo.Name == null)
                {
                    _CounterSet.AddCounter(counterInfo.Id, counterInfo.Type);
                }
                else
                {
                    _CounterSet.AddCounter(counterInfo.Id, counterInfo.Type, counterInfo.Name);
                }
            }

            string instanceName = PSPerfCountersMgr.Instance.GetCounterSetInstanceName();
            // Create an instance of the counter set (contains the counter data).
            _CounterSetInstance = _CounterSet.CreateCounterSetInstance(instanceName);
        }
 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;
     }
 }
            /// <summary>
            /// Adds a CounterSetInstance to the cache, from where it will be garbage collected or re-used by another performance counter (whichever occurs first).
            /// </summary>
            internal void Add(string instanceName, CounterSetInstance instance)
            {
                Fx.Assert(instanceName != null, "Invalid argument.");
                Fx.Assert(instance != null, "Invalid argument.");

                lock (this.cache)
                {
                    this.cache[instanceName] = new WeakReference(instance);
                }
            }
        public CounterSetInstance CreateCounterSetInstance(String instanceName) {
            if (instanceName == null) {
                throw new ArgumentNullException("instanceName");
            }
            if (instanceName.Length == 0) {
                throw new ArgumentException(SR.GetString(SR.Perflib_Argument_EmptyInstanceName), "instanceName");
            }
            if (m_provider == null) {
                throw new InvalidOperationException(SR.GetString(SR.Perflib_InvalidOperation_NoActiveProvider, m_providerGuid));
            }
            if (! m_instanceCreated) {
                lock (m_lockObject) {
                    if (! m_instanceCreated) {
                        if (m_provider == null) {
                            throw new ArgumentException(SR.GetString(SR.Perflib_Argument_ProviderNotFound, m_providerGuid), "ProviderGuid");
                        }
                        if (m_provider.m_hProvider.IsInvalid) {
                            throw new InvalidOperationException(SR.GetString(SR.Perflib_InvalidOperation_NoActiveProvider, m_providerGuid));
                        }
                        if (m_idToCounter.Count == 0) {
                            throw new InvalidOperationException(SR.GetString(SR.Perflib_InvalidOperation_CounterSetContainsNoCounter, m_counterSet));
                        }

                        uint Status = (uint) UnsafeNativeMethods.ERROR_SUCCESS;
    
                        unsafe {
                            uint CounterSetInfoSize   = (uint) sizeof(UnsafeNativeMethods.PerfCounterSetInfoStruct)
                                            + (uint) m_idToCounter.Count * (uint) sizeof(UnsafeNativeMethods.PerfCounterInfoStruct);
                            uint   CounterSetInfoUsed = 0;
                            byte * CounterSetBuffer   = stackalloc byte[(int)CounterSetInfoSize];

                            if (CounterSetBuffer == null) {
                                throw new InsufficientMemoryException(SR.GetString(SR.Perflib_InsufficientMemory_CounterSetTemplate, m_counterSet, CounterSetInfoSize));
                            }

                            UnsafeNativeMethods.PerfCounterSetInfoStruct * CounterSetInfo;
                            UnsafeNativeMethods.PerfCounterInfoStruct    * CounterInfo;

                            uint CurrentCounter = 0;
                            uint CurrentOffset  = 0;

                            CounterSetInfo = (UnsafeNativeMethods.PerfCounterSetInfoStruct *) CounterSetBuffer;
                            CounterSetInfo->CounterSetGuid = m_counterSet;
                            CounterSetInfo->ProviderGuid   = m_providerGuid;
                            CounterSetInfo->NumCounters    = (uint) m_idToCounter.Count;
                            CounterSetInfo->InstanceType   = (uint) m_instType;

                            foreach (KeyValuePair<Int32, CounterType> CounterDef in m_idToCounter) {
                                CounterSetInfoUsed = (uint)sizeof(UnsafeNativeMethods.PerfCounterSetInfoStruct)
                                                + (uint)CurrentCounter * (uint)sizeof(UnsafeNativeMethods.PerfCounterInfoStruct);
                                if (CounterSetInfoUsed < CounterSetInfoSize) {
                                    CounterInfo = (UnsafeNativeMethods.PerfCounterInfoStruct *) (CounterSetBuffer + CounterSetInfoUsed);
                                    CounterInfo->CounterId   = (uint) CounterDef.Key;
                                    CounterInfo->CounterType = (uint) CounterDef.Value;
                                    CounterInfo->Attrib      = 0x0000000000000001;   // PERF_ATTRIB_BY_REFERENCE
                                    CounterInfo->Size        = (uint) sizeof(void*); // always use pointer size
                                    CounterInfo->DetailLevel = 100;                  // PERF_DETAIL_NOVICE
                                    CounterInfo->Scale       = 0;                    // Default scale
                                    CounterInfo->Offset      = CurrentOffset;

                                    CurrentOffset += CounterInfo->Size;
                                }
                                CurrentCounter++;
                            }
                            Status = UnsafeNativeMethods.PerfSetCounterSetInfo(m_provider.m_hProvider, CounterSetInfo, CounterSetInfoSize);
                            // ERROR_INVALID_PARAMETER, ERROR_ALREADY_EXISTS, ERROR_NOT_ENOUGH_MEMORY, ERROR_OUTOFMEMORY
                            if (Status != (uint) UnsafeNativeMethods.ERROR_SUCCESS) {
                                switch (Status) {
                                    case (uint) UnsafeNativeMethods.ERROR_ALREADY_EXISTS:
                                        throw new ArgumentException(SR.GetString(SR.Perflib_Argument_CounterSetAlreadyRegister, m_counterSet), "CounterSetGuid");

                                    default:
                                        throw new Win32Exception((int) Status);
                                }
                            }

                            Interlocked.Increment(ref m_provider.m_counterSet);
                        }

                        m_instanceCreated = true;
                    }
                }
            }

            CounterSetInstance thisInst = new CounterSetInstance(this, instanceName);
            return thisInst;
        }
        static CounterSetInstance CreateCounterSetInstance(string name)
        {
            CounterSetInstance workflowServiceHostCounterSetInstance = null;

            if (PartialTrustHelpers.AppDomainFullyTrusted)
            {
                try
                {
                    workflowServiceHostCounterSetInstance = workflowServiceHostCounterSet.CreateCounterSetInstance(name);
                }
                catch (Exception exception)
                {
                    if (Fx.IsFatal(exception))
                    {
                        throw;
                    }
                    // A conflicting instance name already exists and probably the unmanaged resource is not yet disposed. 
                    FxTrace.Exception.AsWarning(exception);
                    workflowServiceHostCounterSetInstance = null;
                }
            }

            return workflowServiceHostCounterSetInstance;
        }
 // Immediately disposes and nulls the CounterSetInstance. This differs from Dispose because Dispose is "lazy" in that
 // it holds weak references to the instances so we don't get corrupted state if the values are updated later. This
 // method is used in situations when we need to delete the instance immediately and know the values won't be updated.
 internal void DeleteInstance()
 {
     if (this.endpointCounterSetInstance != null)
     {
         this.endpointCounterSetInstance.Dispose();
         this.endpointCounterSetInstance = null;
     }
 }