Beispiel #1
0
        /// <summary>
        ///     Removes the counter (category) from the system
        /// </summary>
        public static void Delete(string categoryName)
        {
            CheckValidCategory(categoryName);
            string machineName = ".";

            categoryName = categoryName.ToLowerInvariant();

            Mutex mutex = null;

            try
            {
                NetFrameworkUtils.EnterMutex(PerfMutexName, ref mutex);
                if (!PerformanceCounterLib.IsCustomCategory(machineName, categoryName))
                {
                    throw new InvalidOperationException(SR.CantDeleteCategory);
                }

                SharedPerformanceCounter.RemoveAllInstances(categoryName);

                PerformanceCounterLib.UnregisterCategory(categoryName);
                PerformanceCounterLib.CloseAllLibraries();
            }
            finally
            {
                if (mutex != null)
                {
                    mutex.ReleaseMutex();
                    mutex.Close();
                }
            }
        }
        public static void Delete(string categoryName)
        {
            CheckValidCategory(categoryName);
            string machineName = ".";

            new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Administer, machineName, categoryName).Demand();
            SharedUtils.CheckNtEnvironment();
            categoryName = categoryName.ToLower(CultureInfo.InvariantCulture);
            Mutex mutex = null;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                SharedUtils.EnterMutex("netfxperf.1.0", ref mutex);
                if (!PerformanceCounterLib.IsCustomCategory(machineName, categoryName))
                {
                    throw new InvalidOperationException(SR.GetString("CantDeleteCategory"));
                }
                SharedPerformanceCounter.RemoveAllInstances(categoryName);
                PerformanceCounterLib.UnregisterCategory(categoryName);
                PerformanceCounterLib.CloseAllLibraries();
            }
            finally
            {
                if (mutex != null)
                {
                    mutex.ReleaseMutex();
                    mutex.Close();
                }
            }
        }
Beispiel #3
0
 /// <include file='doc\PerformanceCounter.uex' path='docs/doc[@for="PerformanceCounter.Close"]/*' />
 /// <devdoc>
 ///     Frees all the resources allocated by this counter
 /// </devdoc>
 public void Close()
 {
     this.helpMsg       = null;
     this.oldSample     = CounterSample.Empty;
     this.sharedCounter = null;
     this.initialized   = false;
 }
 /// <summary>
 ///     Frees all the resources allocated by this counter
 /// </summary>
 public void Close()
 {
     _helpMsg       = null;
     _oldSample     = CounterSample.Empty;
     _sharedCounter = null;
     _initialized   = false;
     _counterType   = -1;
 }
Beispiel #5
0
        /// <include file='doc\PerformanceCounter.uex' path='docs/doc[@for="PerformanceCounter.RemoveInstance"]/*' />
        /// <devdoc>
        ///     Removes this counter instance from the shared memory
        /// </devdoc>
        public void RemoveInstance()
        {
            if (ReadOnly)
            {
                throw new InvalidOperationException(SR.GetString(SR.ReadOnlyRemoveInstance));
            }

            Initialize();
            SharedPerformanceCounter.RemoveInstance(this.categoryName.ToLower(CultureInfo.InvariantCulture), this.instanceName.ToLower(CultureInfo.InvariantCulture));
        }
Beispiel #6
0
        /// <include file='doc\PerformanceCounter.uex' path='docs/doc[@for="PerformanceCounter.Initialize"]/*' />
        /// <devdoc>
        ///     Intializes required resources
        /// </devdoc>
        private void Initialize()
        {
            if (!initialized && !DesignMode)
            {
                lock (this) {
                    if (!initialized)
                    {
                        if (this.categoryName == String.Empty)
                        {
                            throw new InvalidOperationException(SR.GetString(SR.CategoryNameMissing));
                        }
                        if (this.counterName == String.Empty)
                        {
                            throw new InvalidOperationException(SR.GetString(SR.CounterNameMissing));
                        }

                        if (this.ReadOnly)
                        {
                            PerformanceCounterPermission permission = new PerformanceCounterPermission(
                                PerformanceCounterPermissionAccess.Browse, this.machineName, this.categoryName);

                            permission.Demand();

                            if (!PerformanceCounterLib.CounterExists(machineName, categoryName, counterName))
                            {
                                throw new InvalidOperationException(SR.GetString(SR.CounterExists, categoryName, counterName));
                            }

                            this.initialized = true;
                        }
                        else
                        {
                            PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Instrument, this.machineName, this.categoryName);
                            permission.Demand();

                            if (this.machineName != "." && String.Compare(this.machineName, PerformanceCounterLib.ComputerName, true, CultureInfo.InvariantCulture) != 0)
                            {
                                throw new InvalidOperationException(SR.GetString(SR.RemoteWriting));
                            }

                            SharedUtils.CheckNtEnvironment();

                            if (!PerformanceCounterLib.IsCustomCategory(machineName, categoryName))
                            {
                                throw new InvalidOperationException(SR.GetString(SR.NotCustomCounter));
                            }

                            this.sharedCounter = new SharedPerformanceCounter(categoryName.ToLower(CultureInfo.InvariantCulture), counterName.ToLower(CultureInfo.InvariantCulture), instanceName.ToLower(CultureInfo.InvariantCulture));
                            this.initialized   = true;
                        }
                    }
                }
            }
        }
Beispiel #7
0
        /// <include file='doc\PerformanceCounterManager.uex' path='docs/doc[@for="PerformanceCounterManager.InitCounterData"]/*' />
        /// <devdoc>
        ///     Initializes the PERF_OBJECT_TYPE structure
        /// </devdoc>
        /// <internalonly/>
        private static IntPtr InitCounterData(IntPtr ptr, int instanceNameHashCode, string instanceName, ObjectData data)
        {
            NativeMethods.PERF_COUNTER_BLOCK counterBlock = new NativeMethods.PERF_COUNTER_BLOCK();
            IntPtr startPtr = ptr;

            ptr = (IntPtr)((long)ptr + Marshal.SizeOf(typeof(NativeMethods.PERF_COUNTER_BLOCK)));
            for (int index = 0; index < data.CounterNameHashCodes.Length; ++index)
            {
                long counterValue = SharedPerformanceCounter.GetCounterValue(data.CategoryNameHashCode, data.CategoryName,
                                                                             data.CounterNameHashCodes[index], data.CounterNames[index],
                                                                             instanceNameHashCode, instanceName);
                if (((data.CounterTypes[index] & NativeMethods.PERF_SIZE_LARGE) != 0) || (data.CounterTypes[index] == NativeMethods.PERF_AVERAGE_TIMER))
                {
                    LARGE_COUNTER_DATA counterData = new LARGE_COUNTER_DATA();
                    counterData.value = counterValue;
                    Marshal.StructureToPtr(counterData, ptr, false);
                    ptr = (IntPtr)((long)ptr + Marshal.SizeOf(typeof(LARGE_COUNTER_DATA)));
                }
                else   // Must be DWORD size
                {
                    DWORD_COUNTER_DATA counterData = new DWORD_COUNTER_DATA();
                    counterData.value = (int)counterValue;
                    Marshal.StructureToPtr(counterData, ptr, false);
                    ptr = (IntPtr)((long)ptr + Marshal.SizeOf(typeof(DWORD_COUNTER_DATA)));
                }
            }

            // Make sure our data block is 8-byte aligned.
            int diff = ((int)((long)ptr - (long)startPtr) % 8);

            // Null out block (because our data is either 32 or 64 bits, at most we'll need to zero out 4 bytes).
            if (diff != 0)
            {
                Marshal.WriteInt32(ptr, 0);
                ptr = (IntPtr)((long)ptr + 4);
            }

            counterBlock.ByteLength = (int)((long)ptr - (long)startPtr);
            Marshal.StructureToPtr(counterBlock, startPtr, false);
            return(ptr);
        }
Beispiel #8
0
        /// <include file='doc\PerformanceCounterManager.uex' path='docs/doc[@for="PerformanceCounterManager.CreateDataForObject"]/*' />
        /// <devdoc>
        ///     Prepares data for a single performance object (category)
        /// </devdoc>
        /// <internalonly/>
        private IntPtr CreateDataForObject(int objId, IntPtr ptr)
        {
            IntPtr startPtr     = ptr;
            int    numInstances = NativeMethods.PERF_NO_INSTANCES;

            ObjectData data = (ObjectData)perfObjects[objId];

            // Init the PerfObjectType later, just skip over it for now.
            ptr = (IntPtr)((long)ptr + Marshal.SizeOf(typeof(NativeMethods.PERF_OBJECT_TYPE)));

            // Start the counter offset at 4 to skip over the counter block size
            int nextCounterOffset = 4;

            for (int i = 0; i < data.CounterNameHashCodes.Length; i++)
            {
                nextCounterOffset += InitCounterDefinition(ptr, i, data, nextCounterOffset);
                ptr = (IntPtr)((long)ptr + Marshal.SizeOf(typeof(NativeMethods.PERF_COUNTER_DEFINITION)));
            }
            // now ptr points at the begining of the instances block or counter block (for global counter)
            string[] instanceNames = SharedPerformanceCounter.GetInstanceNames(data.CategoryNameHashCode, data.CategoryName);
            if (instanceNames.Length == 0)
            {
                ptr = InitCounterData(ptr, SharedPerformanceCounter.SingleInstanceHashCode, SharedPerformanceCounter.SingleInstanceName, data);
            }
            else
            {
                for (int index = 0; index < instanceNames.Length; ++index)
                {
                    ptr = InitInstanceDefinition(ptr, 0, 0, NativeMethods.PERF_NO_UNIQUE_ID, instanceNames[index]);
                    string instanceName = instanceNames[index].ToLower(CultureInfo.InvariantCulture);
                    ptr = InitCounterData(ptr, instanceName.GetHashCode(), instanceName, data);
                }

                // update instance count
                numInstances = instanceNames.Length;
            }
            // update arguments for return
            InitPerfObjectType(startPtr, data, numInstances, (int)((long)ptr - (long)startPtr));

            return(ptr);
        }
Beispiel #9
0
        /// <include file='doc\PerformanceCounterManager.uex' path='docs/doc[@for="PerformanceCounterManager.SpaceRequired"]/*' />
        /// <devdoc>
        ///     Returns a size in bytes of the space required to pass all requested
        ///     performance data
        /// </devdoc>
        /// <internalonly/>
        private int GetSpaceRequired(int objectId)
        {
            int        totalSize         = 0;
            ObjectData data              = (ObjectData)perfObjects[objectId];
            int        numberOfInstances = SharedPerformanceCounter.GetNumberOfInstances(data.CategoryNameHashCode, data.CategoryName);

            totalSize += Marshal.SizeOf(typeof(NativeMethods.PERF_OBJECT_TYPE));
            totalSize += (data.CounterNameHashCodes.Length * Marshal.SizeOf(typeof(NativeMethods.PERF_COUNTER_DEFINITION)));
            if (numberOfInstances == 0)
            {
                totalSize += (data.CounterNameHashCodes.Length * NativeMethods.LARGE_INTEGER_SIZE) + NativeMethods.DWORD_SIZE;
            }
            else
            {
                int instanceSize = Marshal.SizeOf(typeof(NativeMethods.PERF_INSTANCE_DEFINITION)) + 2 * (MAX_SIZEOF_INSTANCE_NAME + 1)
                                   + (data.CounterNameHashCodes.Length * NativeMethods.LARGE_INTEGER_SIZE) + NativeMethods.DWORD_SIZE;

                totalSize += numberOfInstances * instanceSize;
            }

            return(totalSize);
        }
Beispiel #10
0
        private void InitializeImpl()
        {
            bool lockTaken = false;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                Monitor.Enter(this.InstanceLockObject, ref lockTaken);
                if (!this.initialized)
                {
                    string categoryName = this.categoryName;
                    string machineName  = this.machineName;
                    if (categoryName == string.Empty)
                    {
                        throw new InvalidOperationException(SR.GetString("CategoryNameMissing"));
                    }
                    if (this.counterName == string.Empty)
                    {
                        throw new InvalidOperationException(SR.GetString("CounterNameMissing"));
                    }
                    if (this.ReadOnly)
                    {
                        new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Browse, machineName, categoryName).Demand();
                        if (!PerformanceCounterLib.CounterExists(machineName, categoryName, this.counterName))
                        {
                            throw new InvalidOperationException(SR.GetString("CounterExists", new object[] { categoryName, this.counterName }));
                        }
                        PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(machineName, categoryName);
                        if (categoryType == PerformanceCounterCategoryType.MultiInstance)
                        {
                            if (string.IsNullOrEmpty(this.instanceName))
                            {
                                throw new InvalidOperationException(SR.GetString("MultiInstanceOnly", new object[] { categoryName }));
                            }
                        }
                        else if ((categoryType == PerformanceCounterCategoryType.SingleInstance) && !string.IsNullOrEmpty(this.instanceName))
                        {
                            throw new InvalidOperationException(SR.GetString("SingleInstanceOnly", new object[] { categoryName }));
                        }
                        if (this.instanceLifetime != PerformanceCounterInstanceLifetime.Global)
                        {
                            throw new InvalidOperationException(SR.GetString("InstanceLifetimeProcessonReadOnly"));
                        }
                        this.initialized = true;
                    }
                    else
                    {
                        new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Write, machineName, categoryName).Demand();
                        if ((machineName != ".") && (string.Compare(machineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase) != 0))
                        {
                            throw new InvalidOperationException(SR.GetString("RemoteWriting"));
                        }
                        SharedUtils.CheckNtEnvironment();
                        if (!PerformanceCounterLib.IsCustomCategory(machineName, categoryName))
                        {
                            throw new InvalidOperationException(SR.GetString("NotCustomCounter"));
                        }
                        PerformanceCounterCategoryType type2 = PerformanceCounterLib.GetCategoryType(machineName, categoryName);
                        if (type2 == PerformanceCounterCategoryType.MultiInstance)
                        {
                            if (string.IsNullOrEmpty(this.instanceName))
                            {
                                throw new InvalidOperationException(SR.GetString("MultiInstanceOnly", new object[] { categoryName }));
                            }
                        }
                        else if ((type2 == PerformanceCounterCategoryType.SingleInstance) && !string.IsNullOrEmpty(this.instanceName))
                        {
                            throw new InvalidOperationException(SR.GetString("SingleInstanceOnly", new object[] { categoryName }));
                        }
                        if (string.IsNullOrEmpty(this.instanceName) && (this.InstanceLifetime == PerformanceCounterInstanceLifetime.Process))
                        {
                            throw new InvalidOperationException(SR.GetString("InstanceLifetimeProcessforSingleInstance"));
                        }
                        this.sharedCounter = new SharedPerformanceCounter(categoryName.ToLower(CultureInfo.InvariantCulture), this.counterName.ToLower(CultureInfo.InvariantCulture), this.instanceName.ToLower(CultureInfo.InvariantCulture), this.instanceLifetime);
                        this.initialized   = true;
                    }
                }
            }
            finally
            {
                if (lockTaken)
                {
                    Monitor.Exit(this.InstanceLockObject);
                }
            }
        }
Beispiel #11
0
        /// <summary>
        ///     Intializes required resources
        /// </summary>
        private void InitializeImpl()
        {
            bool tookLock = false;

            try
            {
                Monitor.Enter(InstanceLockObject, ref tookLock);

                if (!_initialized)
                {
                    string currentCategoryName = _categoryName;
                    string currentMachineName  = _machineName;

                    if (currentCategoryName.Length == 0)
                    {
                        throw new InvalidOperationException(SR.CategoryNameMissing);
                    }
                    if (_counterName.Length == 0)
                    {
                        throw new InvalidOperationException(SR.CounterNameMissing);
                    }

                    if (ReadOnly)
                    {
                        if (!PerformanceCounterLib.CounterExists(currentMachineName, currentCategoryName, _counterName))
                        {
                            throw new InvalidOperationException(SR.Format(SR.CounterExists, currentCategoryName, _counterName));
                        }

                        PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName);
                        if (categoryType == PerformanceCounterCategoryType.MultiInstance)
                        {
                            if (string.IsNullOrEmpty(_instanceName))
                            {
                                throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, currentCategoryName));
                            }
                        }
                        else if (categoryType == PerformanceCounterCategoryType.SingleInstance)
                        {
                            if (!string.IsNullOrEmpty(_instanceName))
                            {
                                throw new InvalidOperationException(SR.Format(SR.SingleInstanceOnly, currentCategoryName));
                            }
                        }

                        if (_instanceLifetime != PerformanceCounterInstanceLifetime.Global)
                        {
                            throw new InvalidOperationException(SR.InstanceLifetimeProcessonReadOnly);
                        }

                        _initialized = true;
                    }
                    else
                    {
                        if (currentMachineName != "." && !string.Equals(currentMachineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase))
                        {
                            throw new InvalidOperationException(SR.RemoteWriting);
                        }

                        if (!PerformanceCounterLib.IsCustomCategory(currentMachineName, currentCategoryName))
                        {
                            throw new InvalidOperationException(SR.NotCustomCounter);
                        }

                        // check category type
                        PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName);
                        if (categoryType == PerformanceCounterCategoryType.MultiInstance)
                        {
                            if (string.IsNullOrEmpty(_instanceName))
                            {
                                throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, currentCategoryName));
                            }
                        }
                        else if (categoryType == PerformanceCounterCategoryType.SingleInstance)
                        {
                            if (!string.IsNullOrEmpty(_instanceName))
                            {
                                throw new InvalidOperationException(SR.Format(SR.SingleInstanceOnly, currentCategoryName));
                            }
                        }

                        if (string.IsNullOrEmpty(_instanceName) && InstanceLifetime == PerformanceCounterInstanceLifetime.Process)
                        {
                            throw new InvalidOperationException(SR.InstanceLifetimeProcessforSingleInstance);
                        }

                        _sharedCounter = new SharedPerformanceCounter(currentCategoryName.ToLowerInvariant(), _counterName.ToLowerInvariant(), _instanceName.ToLowerInvariant(), _instanceLifetime);
                        _initialized   = true;
                    }
                }
            }
            finally
            {
                if (tookLock)
                {
                    Monitor.Exit(InstanceLockObject);
                }
            }
        }
 public void Close()
 {
     this.helpMsg = null;
     this.oldSample = CounterSample.Empty;
     this.sharedCounter = null;
     this.initialized = false;
     this.counterType = -1;
 }
 private void InitializeImpl()
 {
     bool lockTaken = false;
     RuntimeHelpers.PrepareConstrainedRegions();
     try
     {
         Monitor.Enter(this.InstanceLockObject, ref lockTaken);
         if (!this.initialized)
         {
             string categoryName = this.categoryName;
             string machineName = this.machineName;
             if (categoryName == string.Empty)
             {
                 throw new InvalidOperationException(SR.GetString("CategoryNameMissing"));
             }
             if (this.counterName == string.Empty)
             {
                 throw new InvalidOperationException(SR.GetString("CounterNameMissing"));
             }
             if (this.ReadOnly)
             {
                 new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Browse, machineName, categoryName).Demand();
                 if (!PerformanceCounterLib.CounterExists(machineName, categoryName, this.counterName))
                 {
                     throw new InvalidOperationException(SR.GetString("CounterExists", new object[] { categoryName, this.counterName }));
                 }
                 PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(machineName, categoryName);
                 if (categoryType == PerformanceCounterCategoryType.MultiInstance)
                 {
                     if (string.IsNullOrEmpty(this.instanceName))
                     {
                         throw new InvalidOperationException(SR.GetString("MultiInstanceOnly", new object[] { categoryName }));
                     }
                 }
                 else if ((categoryType == PerformanceCounterCategoryType.SingleInstance) && !string.IsNullOrEmpty(this.instanceName))
                 {
                     throw new InvalidOperationException(SR.GetString("SingleInstanceOnly", new object[] { categoryName }));
                 }
                 if (this.instanceLifetime != PerformanceCounterInstanceLifetime.Global)
                 {
                     throw new InvalidOperationException(SR.GetString("InstanceLifetimeProcessonReadOnly"));
                 }
                 this.initialized = true;
             }
             else
             {
                 new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Write, machineName, categoryName).Demand();
                 if ((machineName != ".") && (string.Compare(machineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase) != 0))
                 {
                     throw new InvalidOperationException(SR.GetString("RemoteWriting"));
                 }
                 SharedUtils.CheckNtEnvironment();
                 if (!PerformanceCounterLib.IsCustomCategory(machineName, categoryName))
                 {
                     throw new InvalidOperationException(SR.GetString("NotCustomCounter"));
                 }
                 PerformanceCounterCategoryType type2 = PerformanceCounterLib.GetCategoryType(machineName, categoryName);
                 if (type2 == PerformanceCounterCategoryType.MultiInstance)
                 {
                     if (string.IsNullOrEmpty(this.instanceName))
                     {
                         throw new InvalidOperationException(SR.GetString("MultiInstanceOnly", new object[] { categoryName }));
                     }
                 }
                 else if ((type2 == PerformanceCounterCategoryType.SingleInstance) && !string.IsNullOrEmpty(this.instanceName))
                 {
                     throw new InvalidOperationException(SR.GetString("SingleInstanceOnly", new object[] { categoryName }));
                 }
                 if (string.IsNullOrEmpty(this.instanceName) && (this.InstanceLifetime == PerformanceCounterInstanceLifetime.Process))
                 {
                     throw new InvalidOperationException(SR.GetString("InstanceLifetimeProcessforSingleInstance"));
                 }
                 this.sharedCounter = new SharedPerformanceCounter(categoryName.ToLower(CultureInfo.InvariantCulture), this.counterName.ToLower(CultureInfo.InvariantCulture), this.instanceName.ToLower(CultureInfo.InvariantCulture), this.instanceLifetime);
                 this.initialized = true;
             }
         }
     }
     finally
     {
         if (lockTaken)
         {
             Monitor.Exit(this.InstanceLockObject);
         }
     }
 }
        /// <devdoc>
        ///     Intializes required resources
        /// </devdoc>
        //[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        private void InitializeImpl()
        {
            bool tookLock = false;

            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                Monitor.Enter(InstanceLockObject, ref tookLock);

                if (!initialized)
                {
                    string currentCategoryName = categoryName;
                    string currentMachineName  = machineName;

                    if (currentCategoryName == String.Empty)
                    {
                        throw new InvalidOperationException(SR.GetString(SR.CategoryNameMissing));
                    }
                    if (this.counterName == String.Empty)
                    {
                        throw new InvalidOperationException(SR.GetString(SR.CounterNameMissing));
                    }

                    if (this.ReadOnly)
                    {
                        PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName);

                        permission.Demand();

                        if (!PerformanceCounterLib.CounterExists(currentMachineName, currentCategoryName, counterName))
                        {
                            throw new InvalidOperationException(SR.GetString(SR.CounterExists, currentCategoryName, counterName));
                        }

                        PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName);
                        if (categoryType == PerformanceCounterCategoryType.MultiInstance)
                        {
                            if (String.IsNullOrEmpty(instanceName))
                            {
                                throw new InvalidOperationException(SR.GetString(SR.MultiInstanceOnly, currentCategoryName));
                            }
                        }
                        else if (categoryType == PerformanceCounterCategoryType.SingleInstance)
                        {
                            if (!String.IsNullOrEmpty(instanceName))
                            {
                                throw new InvalidOperationException(SR.GetString(SR.SingleInstanceOnly, currentCategoryName));
                            }
                        }

                        if (instanceLifetime != PerformanceCounterInstanceLifetime.Global)
                        {
                            throw new InvalidOperationException(SR.GetString(SR.InstanceLifetimeProcessonReadOnly));
                        }

                        this.initialized = true;
                    }
                    else
                    {
                        PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Write, currentMachineName, currentCategoryName);
                        permission.Demand();

                        if (currentMachineName != "." && String.Compare(currentMachineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase) != 0)
                        {
                            throw new InvalidOperationException(SR.GetString(SR.RemoteWriting));
                        }

                        SharedUtils.CheckNtEnvironment();

                        if (!PerformanceCounterLib.IsCustomCategory(currentMachineName, currentCategoryName))
                        {
                            throw new InvalidOperationException(SR.GetString(SR.NotCustomCounter));
                        }

                        // check category type
                        PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName);
                        if (categoryType == PerformanceCounterCategoryType.MultiInstance)
                        {
                            if (String.IsNullOrEmpty(instanceName))
                            {
                                throw new InvalidOperationException(SR.GetString(SR.MultiInstanceOnly, currentCategoryName));
                            }
                        }
                        else if (categoryType == PerformanceCounterCategoryType.SingleInstance)
                        {
                            if (!String.IsNullOrEmpty(instanceName))
                            {
                                throw new InvalidOperationException(SR.GetString(SR.SingleInstanceOnly, currentCategoryName));
                            }
                        }

                        if (String.IsNullOrEmpty(instanceName) && InstanceLifetime == PerformanceCounterInstanceLifetime.Process)
                        {
                            throw new InvalidOperationException(SR.GetString(SR.InstanceLifetimeProcessforSingleInstance));
                        }

                        this.sharedCounter = new SharedPerformanceCounter(currentCategoryName.ToLower(CultureInfo.InvariantCulture), counterName.ToLower(CultureInfo.InvariantCulture), instanceName.ToLower(CultureInfo.InvariantCulture), instanceLifetime);
                        this.initialized   = true;
                    }
                }
            } finally {
                if (tookLock)
                {
                    Monitor.Exit(InstanceLockObject);
                }
            }
        }
 internal unsafe static void RemoveAllInstances(string categoryName) {
     SharedPerformanceCounter spc = new SharedPerformanceCounter(categoryName, null, null);
     spc.RemoveAllInstances();
     RemoveCategoryData(categoryName);
 }
        /// <devdoc>
        ///     Intializes required resources
        /// </devdoc>
        //[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        private void InitializeImpl() {
            bool tookLock = false;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                Monitor.Enter(InstanceLockObject, ref tookLock);

                if (!initialized) {
                    string currentCategoryName = categoryName;
                    string currentMachineName = machineName;

                    if (currentCategoryName == String.Empty)
                        throw new InvalidOperationException(SR.GetString(SR.CategoryNameMissing));
                    if (this.counterName == String.Empty)
                        throw new InvalidOperationException(SR.GetString(SR.CounterNameMissing));

                    if (this.ReadOnly) {
                        PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName);

                        permission.Demand();

                        if (!PerformanceCounterLib.CounterExists(currentMachineName, currentCategoryName, counterName))
                            throw new InvalidOperationException(SR.GetString(SR.CounterExists, currentCategoryName, counterName));

                        PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName);
                        if (categoryType == PerformanceCounterCategoryType.MultiInstance) {
                            if (String.IsNullOrEmpty(instanceName))
                                throw new InvalidOperationException(SR.GetString(SR.MultiInstanceOnly, currentCategoryName));
                        } else if (categoryType == PerformanceCounterCategoryType.SingleInstance) {
                            if (!String.IsNullOrEmpty(instanceName))
                                throw new InvalidOperationException(SR.GetString(SR.SingleInstanceOnly, currentCategoryName));
                        }

                        if (instanceLifetime != PerformanceCounterInstanceLifetime.Global)
                            throw new InvalidOperationException(SR.GetString(SR.InstanceLifetimeProcessonReadOnly));

                        this.initialized = true;
                    } else {
                        PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Write, currentMachineName, currentCategoryName);
                        permission.Demand();

                        if (currentMachineName != "." && String.Compare(currentMachineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase) != 0)
                            throw new InvalidOperationException(SR.GetString(SR.RemoteWriting));

                        SharedUtils.CheckNtEnvironment();

                        if (!PerformanceCounterLib.IsCustomCategory(currentMachineName, currentCategoryName))
                            throw new InvalidOperationException(SR.GetString(SR.NotCustomCounter));

                        // check category type
                        PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName);
                        if (categoryType == PerformanceCounterCategoryType.MultiInstance) {
                            if (String.IsNullOrEmpty(instanceName))
                                throw new InvalidOperationException(SR.GetString(SR.MultiInstanceOnly, currentCategoryName));
                        } else if (categoryType == PerformanceCounterCategoryType.SingleInstance) {
                            if (!String.IsNullOrEmpty(instanceName))
                                throw new InvalidOperationException(SR.GetString(SR.SingleInstanceOnly, currentCategoryName));
                        }

                        if (String.IsNullOrEmpty(instanceName) && InstanceLifetime == PerformanceCounterInstanceLifetime.Process)
                            throw new InvalidOperationException(SR.GetString(SR.InstanceLifetimeProcessforSingleInstance));

                        this.sharedCounter = new SharedPerformanceCounter(currentCategoryName.ToLower(CultureInfo.InvariantCulture), counterName.ToLower(CultureInfo.InvariantCulture), instanceName.ToLower(CultureInfo.InvariantCulture), instanceLifetime);
                        this.initialized = true;
                    }
                }
            } finally {
                if (tookLock)
                    Monitor.Exit(InstanceLockObject);
            }

        }