public bool CounterExists(string counterName)
 {
     if (counterName == null)
     {
         throw new ArgumentNullException("counterName");
     }
     if (this.categoryName == null)
     {
         throw new InvalidOperationException(SR.GetString("CategoryNameNotSet"));
     }
     return(PerformanceCounterLib.CounterExists(this.machineName, this.categoryName, counterName));
 }
 public bool InstanceExists(string instanceName)
 {
     if (instanceName == null)
     {
         throw new ArgumentNullException("instanceName");
     }
     if (this.categoryName == null)
     {
         throw new InvalidOperationException(SR.GetString("CategoryNameNotSet"));
     }
     return(PerformanceCounterLib.GetCategorySample(this.machineName, this.categoryName).InstanceNameTable.ContainsKey(instanceName));
 }
        /// <summary>
        ///     Reads all the counter and instance data of this performance category.  Note that reading the entire category
        ///     at once can be as efficient as reading a single counter because of the way the system provides the data.
        /// </summary>
        public InstanceDataCollectionCollection ReadCategory()
        {
            if (_categoryName == null)
            {
                throw new InvalidOperationException(SR.CategoryNameNotSet);
            }

            using (CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName))
            {
                return(categorySample.ReadCategory());
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        ///     Returns true if the counter is registered for this category
        /// </summary>
        public bool CounterExists(string counterName)
        {
            if (counterName == null)
            {
                throw new ArgumentNullException(nameof(counterName));
            }

            if (_categoryName == null)
            {
                throw new InvalidOperationException(SR.CategoryNameNotSet);
            }

            return(PerformanceCounterLib.CounterExists(_machineName, _categoryName, counterName));
        }
        /// <summary>
        ///     Returns true if the instance already exists for this category.
        /// </summary>
        public bool InstanceExists(string instanceName)
        {
            ArgumentNullException.ThrowIfNull(instanceName);

            if (_categoryName == null)
            {
                throw new InvalidOperationException(SR.CategoryNameNotSet);
            }

            using (CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName))
            {
                return(categorySample._instanceNameTable.ContainsKey(instanceName));
            }
        }
 public static PerformanceCounterCategory[] GetCategories(string machineName)
 {
     if (!SyntaxCheck.CheckMachineName(machineName))
     {
         throw new ArgumentException(SR.GetString("InvalidParameter", new object[] { "machineName", machineName }));
     }
     new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Browse, machineName, "*").Demand();
     string[] categories = PerformanceCounterLib.GetCategories(machineName);
     PerformanceCounterCategory[] categoryArray = new PerformanceCounterCategory[categories.Length];
     for (int i = 0; i < categoryArray.Length; i++)
     {
         categoryArray[i] = new PerformanceCounterCategory(categories[i], machineName);
     }
     return(categoryArray);
 }
Ejemplo n.º 7
0
        /// <include file='doc\PerformanceCounterCategory.uex' path='docs/doc[@for="PerformanceCounterCategory.ReadCategory"]/*' />
        /// <devdoc>
        ///     Reads all the counter and instance data of this performance category.  Note that reading the entire category
        ///     at once can be as efficient as reading a single counter because of the way the system provides the data.
        /// </devdoc>
        public InstanceDataCollectionCollection ReadCategory()
        {
            if (this.categoryName == null)
            {
                throw new InvalidOperationException(SR.GetString(SR.CategoryNameNotSet));
            }

            CategorySample categorySample = PerformanceCounterLib.GetCategorySample(this.machineName, this.categoryName);

            try {
                return(categorySample.ReadCategory());
            }
            finally {
                categorySample.Dispose();
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        ///     Returns an array of performance counter categories for a particular machine.
        /// </summary>
        public static PerformanceCounterCategory[] GetCategories(string machineName)
        {
            if (!SyntaxCheck.CheckMachineName(machineName))
            {
                throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName));
            }

            string[] categoryNames = PerformanceCounterLib.GetCategories(machineName);
            PerformanceCounterCategory[] categories = new PerformanceCounterCategory[categoryNames.Length];
            for (int index = 0; index < categories.Length; index++)
            {
                categories[index] = new PerformanceCounterCategory(categoryNames[index], machineName);
            }

            return(categories);
        }
Ejemplo n.º 9
0
        /// <summary>
        ///     Returns true if the instance already exists for this category.
        /// </summary>
        public bool InstanceExists(string instanceName)
        {
            if (instanceName == null)
            {
                throw new ArgumentNullException(nameof(instanceName));
            }

            if (_categoryName == null)
            {
                throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
            }

            CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName);

            return(categorySample._instanceNameTable.ContainsKey(instanceName));
        }
        public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData)
        {
            if (categoryType < PerformanceCounterCategoryType.Unknown || categoryType > PerformanceCounterCategoryType.MultiInstance)
            {
                throw new ArgumentOutOfRangeException("categoryType");
            }
            if (counterData == null)
            {
                throw new ArgumentNullException("counterData");
            }

            CheckValidCategory(categoryName);
            if (categoryHelp != null)
            {
                // null categoryHelp is a valid option - it gets set to "Help Not Available" later on.
                CheckValidHelp(categoryHelp);
            }
            string machineName = ".";

            PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Administer, machineName, categoryName);

            permission.Demand();

            SharedUtils.CheckNtEnvironment();

            Mutex mutex = null;

            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                SharedUtils.EnterMutex(perfMutexName, ref mutex);
                if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName) || PerformanceCounterLib.CategoryExists(machineName, categoryName))
                {
                    throw new InvalidOperationException(SR.GetString(SR.PerformanceCategoryExists, categoryName));
                }

                CheckValidCounterLayout(counterData);
                PerformanceCounterLib.RegisterCategory(categoryName, categoryType, categoryHelp, counterData);
                return(new PerformanceCounterCategory(categoryName, machineName));
            }
            finally {
                if (mutex != null)
                {
                    mutex.ReleaseMutex();
                    mutex.Close();
                }
            }
        }
 public static bool Exists(string categoryName, string machineName)
 {
     if (categoryName == null)
     {
         throw new ArgumentNullException("categoryName");
     }
     if (categoryName.Length == 0)
     {
         throw new ArgumentException(SR.GetString("InvalidParameter", new object[] { "categoryName", categoryName }));
     }
     if (!SyntaxCheck.CheckMachineName(machineName))
     {
         throw new ArgumentException(SR.GetString("InvalidParameter", new object[] { "machineName", machineName }));
     }
     new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Browse, machineName, categoryName).Demand();
     return(PerformanceCounterLib.IsCustomCategory(machineName, categoryName) || PerformanceCounterLib.CategoryExists(machineName, categoryName));
 }
        internal static string[] GetCounterInstances(string categoryName, string machineName)
        {
            new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Browse, machineName, categoryName).Demand();
            CategorySample categorySample = PerformanceCounterLib.GetCategorySample(machineName, categoryName);

            if (categorySample.InstanceNameTable.Count == 0)
            {
                return(new string[0]);
            }
            string[] array = new string[categorySample.InstanceNameTable.Count];
            categorySample.InstanceNameTable.Keys.CopyTo(array, 0);
            if ((array.Length == 1) && (array[0].CompareTo("systemdiagnosticsperfcounterlibsingleinstance") == 0))
            {
                return(new string[0]);
            }
            return(array);
        }
Ejemplo n.º 13
0
        /// <summary>
        ///     Returns true if the counter is registered for this category on a particular machine.
        /// </summary>
        public static bool CounterExists(string counterName, string categoryName, string machineName)
        {
            ArgumentNullException.ThrowIfNull(counterName);
            ArgumentNullException.ThrowIfNull(categoryName);

            if (categoryName.Length == 0)
            {
                throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName));
            }

            if (!SyntaxCheck.CheckMachineName(machineName))
            {
                throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName));
            }

            return(PerformanceCounterLib.CounterExists(machineName, categoryName, counterName));
        }
        public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData)
        {
            PerformanceCounterCategory category;

            if ((categoryType < PerformanceCounterCategoryType.Unknown) || (categoryType > PerformanceCounterCategoryType.MultiInstance))
            {
                throw new ArgumentOutOfRangeException("categoryType");
            }
            if (counterData == null)
            {
                throw new ArgumentNullException("counterData");
            }
            CheckValidCategory(categoryName);
            if (categoryHelp != null)
            {
                CheckValidHelp(categoryHelp);
            }
            string machineName = ".";

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

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                SharedUtils.EnterMutex("netfxperf.1.0", ref mutex);
                if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName) || PerformanceCounterLib.CategoryExists(machineName, categoryName))
                {
                    throw new InvalidOperationException(SR.GetString("PerformanceCategoryExists", new object[] { categoryName }));
                }
                CheckValidCounterLayout(counterData);
                PerformanceCounterLib.RegisterCategory(categoryName, categoryType, categoryHelp, counterData);
                category = new PerformanceCounterCategory(categoryName, machineName);
            }
            finally
            {
                if (mutex != null)
                {
                    mutex.ReleaseMutex();
                    mutex.Close();
                }
            }
            return(category);
        }
Ejemplo n.º 15
0
 public static ProcessInfo[] GetProcessInfos(string machineName, bool isRemoteMachine)
 {
     ProcessInfo[] processInfos;
     new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
     try
     {
         processInfos = GetProcessInfos(PerformanceCounterLib.GetPerformanceCounterLib(machineName, new CultureInfo(9)));
     }
     catch (Exception exception)
     {
         if (isRemoteMachine)
         {
             throw new InvalidOperationException(SR.GetString("CouldntConnectToRemoteMachine"), exception);
         }
         throw exception;
     }
     return(processInfos);
 }
Ejemplo n.º 16
0
        /// <summary>
        ///     Returns the instance names for a given category
        /// </summary>
        /// <internalonly/>
        internal static string[] GetCounterInstances(string categoryName, string machineName)
        {
            CategorySample categorySample = PerformanceCounterLib.GetCategorySample(machineName, categoryName);

            if (categorySample._instanceNameTable.Count == 0)
            {
                return(Array.Empty <string>());
            }

            string[] instanceNames = new string[categorySample._instanceNameTable.Count];
            categorySample._instanceNameTable.Keys.CopyTo(instanceNames, 0);
            if (instanceNames.Length == 1 && instanceNames[0] == PerformanceCounterLib.SingleInstanceName)
            {
                return(Array.Empty <string>());
            }

            return(instanceNames);
        }
Ejemplo n.º 17
0
        public static PerformanceCounterCategory Create(string categoryName, string categoryHelp, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection counterData)
        {
            if (categoryType < PerformanceCounterCategoryType.Unknown || categoryType > PerformanceCounterCategoryType.MultiInstance)
            {
                throw new ArgumentOutOfRangeException(nameof(categoryType));
            }
            if (counterData == null)
            {
                throw new ArgumentNullException(nameof(counterData));
            }

            CheckValidCategory(categoryName);
            if (categoryHelp != null)
            {
                // null categoryHelp is a valid option - it gets set to "Help Not Available" later on.
                CheckValidHelp(categoryHelp);
            }
            string machineName = ".";

            Mutex mutex = null;

            try
            {
                NetFrameworkUtils.EnterMutex(PerfMutexName, ref mutex);
                if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName) || PerformanceCounterLib.CategoryExists(machineName, categoryName))
                {
                    throw new InvalidOperationException(SR.Format(SR.PerformanceCategoryExists, categoryName));
                }

                CheckValidCounterLayout(counterData);
                PerformanceCounterLib.RegisterCategory(categoryName, categoryType, categoryHelp, counterData);
                return(new PerformanceCounterCategory(categoryName, machineName));
            }
            finally
            {
                if (mutex != null)
                {
                    mutex.ReleaseMutex();
                    mutex.Close();
                }
            }
        }
Ejemplo n.º 18
0
        /// <include file='doc\PerformanceCounterCategory.uex' path='docs/doc[@for="PerformanceCounterCategory.GetCounterInstances"]/*' />
        /// <devdoc>
        ///     Returns the instance names for a given category
        /// </devdoc>
        /// <internalonly/>
        internal static string[] GetCounterInstances(string categoryName, string machineName)
        {
            if (categoryName == null)
            {
                throw new ArgumentNullException("categoryName");
            }

            if (categoryName.Length == 0)
            {
                throw new ArgumentException(SR.GetString(SR.InvalidParameter, "categoryName", categoryName));
            }

            if (!SyntaxCheck.CheckMachineName(machineName))
            {
                throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName));
            }

            PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Browse, machineName, categoryName);

            permission.Demand();

            CategorySample categorySample = PerformanceCounterLib.GetCategorySample(machineName, categoryName);

            try {
                if (categorySample.InstanceNameTable.Count == 0)
                {
                    throw new InvalidOperationException(SR.GetString(SR.NoInstanceInformation, categoryName));
                }

                string[] instanceNames = new string[categorySample.InstanceNameTable.Count];
                categorySample.InstanceNameTable.Keys.CopyTo(instanceNames, 0);
                if (instanceNames.Length == 1 && instanceNames[0].CompareTo(PerformanceCounterLib.SingleInstanceName) == 0)
                {
                    return(new string[0]);
                }

                return(instanceNames);
            }
            finally {
                categorySample.Dispose();
            }
        }
        /// <devdoc>
        ///     Returns an array of performance counter categories for a particular machine.
        /// </devdoc>
        public static PerformanceCounterCategory[] GetCategories(string machineName)
        {
            if (!SyntaxCheck.CheckMachineName(machineName))
            {
                throw new ArgumentException(SR.GetString(SR.InvalidParameter, "machineName", machineName));
            }

            PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, "*");

            permission.Demand();

            string[] categoryNames = PerformanceCounterLib.GetCategories(machineName);
            PerformanceCounterCategory[] categories = new PerformanceCounterCategory[categoryNames.Length];
            for (int index = 0; index < categories.Length; index++)
            {
                categories[index] = new PerformanceCounterCategory(categoryNames[index], machineName);
            }

            return(categories);
        }
 public static ProcessInfo[] GetProcessInfos(string machineName, bool isRemoteMachine)
 {
     try
     {
         // We don't want to call library.Close() here because that would cause us to unload all of the perflibs.
         // On the next call to GetProcessInfos, we'd have to load them all up again, which is SLOW!
         PerformanceCounterLib library = PerformanceCounterLib.GetPerformanceCounterLib(machineName, new CultureInfo("en"));
         return(GetProcessInfos(library));
     }
     catch (Exception e)
     {
         if (isRemoteMachine)
         {
             throw new InvalidOperationException(SR.CouldntConnectToRemoteMachine, e);
         }
         else
         {
             throw;
         }
     }
 }
 public PerformanceCounter[] GetCounters(string instanceName)
 {
     if (instanceName == null)
     {
         throw new ArgumentNullException("instanceName");
     }
     if (this.categoryName == null)
     {
         throw new InvalidOperationException(SR.GetString("CategoryNameNotSet"));
     }
     if ((instanceName.Length != 0) && !this.InstanceExists(instanceName))
     {
         throw new InvalidOperationException(SR.GetString("MissingInstance", new object[] { instanceName, this.categoryName }));
     }
     string[]             counters     = PerformanceCounterLib.GetCounters(this.machineName, this.categoryName);
     PerformanceCounter[] counterArray = new PerformanceCounter[counters.Length];
     for (int i = 0; i < counterArray.Length; i++)
     {
         counterArray[i] = new PerformanceCounter(this.categoryName, counters[i], instanceName, this.machineName, true);
     }
     return(counterArray);
 }
Ejemplo n.º 22
0
 private static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library)
 {
     ProcessInfo[] infoArray = new ProcessInfo[0];
     byte[]        data      = null;
     for (int i = 5; (infoArray.Length == 0) && (i != 0); i--)
     {
         try
         {
             data      = library.GetPerformanceData("230 232");
             infoArray = GetProcessInfos(library, 230, 0xe8, data);
         }
         catch (Exception exception)
         {
             throw new InvalidOperationException(SR.GetString("CouldntGetProcessInfos"), exception);
         }
     }
     if (infoArray.Length == 0)
     {
         throw new InvalidOperationException(SR.GetString("ProcessDisabled"));
     }
     return(infoArray);
 }
Ejemplo n.º 23
0
        /// <include file='doc\PerformanceCounterCategory.uex' path='docs/doc[@for="PerformanceCounterCategory.InstanceExists"]/*' />
        /// <devdoc>
        ///     Returns true if the instance already exists for this category.
        /// </devdoc>
        public bool InstanceExists(string instanceName)
        {
            if (instanceName == null)
            {
                throw new ArgumentNullException("instanceName");
            }

            if (this.categoryName == null)
            {
                throw new InvalidOperationException(SR.GetString(SR.CategoryNameNotSet));
            }

            CategorySample categorySample = PerformanceCounterLib.GetCategorySample(machineName, categoryName);

            try {
                IEnumerator valueEnum = categorySample.CounterTable.Values.GetEnumerator();
                return(categorySample.InstanceNameTable.ContainsKey(instanceName));
            }
            finally {
                categorySample.Dispose();
            }
        }
        /// <devdoc>
        ///     Returns the instance names for a given category
        /// </devdoc>
        /// <internalonly/>
        internal static string[] GetCounterInstances(string categoryName, string machineName)
        {
            PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, machineName, categoryName);

            permission.Demand();

            CategorySample categorySample = PerformanceCounterLib.GetCategorySample(machineName, categoryName);

            if (categorySample.InstanceNameTable.Count == 0)
            {
                return(new string[0]);
            }

            string[] instanceNames = new string[categorySample.InstanceNameTable.Count];
            categorySample.InstanceNameTable.Keys.CopyTo(instanceNames, 0);
            if (instanceNames.Length == 1 && instanceNames[0].CompareTo(PerformanceCounterLib.SingleInstanceName) == 0)
            {
                return(new string[0]);
            }

            return(instanceNames);
        }
        internal static bool CounterExists(string machine, string category, string counter)
        {
            PerformanceCounterLib performanceCounterLib = GetPerformanceCounterLib(machine, new CultureInfo(9));
            bool categoryExists = false;
            bool flag2          = performanceCounterLib.CounterExists(category, counter, ref categoryExists);

            if (!categoryExists && (CultureInfo.CurrentCulture.Parent.LCID != 9))
            {
                for (CultureInfo info = CultureInfo.CurrentCulture; info != CultureInfo.InvariantCulture; info = info.Parent)
                {
                    flag2 = GetPerformanceCounterLib(machine, info).CounterExists(category, counter, ref categoryExists);
                    if (flag2)
                    {
                        break;
                    }
                }
            }
            if (!categoryExists)
            {
                throw new InvalidOperationException(SR.GetString("MissingCategory"));
            }
            return(flag2);
        }
Ejemplo n.º 26
0
        /// <summary>
        ///     Returns an array of counters in this category for the given instance.
        /// </summary>
        public PerformanceCounter[] GetCounters(string instanceName)
        {
            ArgumentNullException.ThrowIfNull(instanceName);

            if (_categoryName == null)
            {
                throw new InvalidOperationException(SR.CategoryNameNotSet);
            }

            if (instanceName.Length != 0 && !InstanceExists(instanceName))
            {
                throw new InvalidOperationException(SR.Format(SR.MissingInstance, instanceName, _categoryName));
            }

            string[]             counterNames = PerformanceCounterLib.GetCounters(_machineName, _categoryName);
            PerformanceCounter[] counters     = new PerformanceCounter[counterNames.Length];
            for (int index = 0; index < counters.Length; index++)
            {
                counters[index] = new PerformanceCounter(_categoryName, counterNames[index], instanceName, _machineName, true);
            }

            return(counters);
        }
        internal static string[] GetCounters(string machine, string category)
        {
            PerformanceCounterLib performanceCounterLib = GetPerformanceCounterLib(machine, new CultureInfo(9));
            bool categoryExists = false;

            string[] counters = performanceCounterLib.GetCounters(category, ref categoryExists);
            if (!categoryExists && (CultureInfo.CurrentCulture.Parent.LCID != 9))
            {
                for (CultureInfo info = CultureInfo.CurrentCulture; info != CultureInfo.InvariantCulture; info = info.Parent)
                {
                    counters = GetPerformanceCounterLib(machine, info).GetCounters(category, ref categoryExists);
                    if (categoryExists)
                    {
                        return(counters);
                    }
                }
            }
            if (!categoryExists)
            {
                throw new InvalidOperationException(SR.GetString("MissingCategory"));
            }
            return(counters);
        }
Ejemplo n.º 28
0
        internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture)
        {
            string lcidString = culture.Name.ToLowerInvariant();

            if (machineName.CompareTo(".") == 0)
            {
                machineName = ComputerName.ToLowerInvariant();
            }
            else
            {
                machineName = machineName.ToLowerInvariant();
            }

            if (PerformanceCounterLib.s_libraryTable == null)
            {
                lock (InternalSyncObject)
                {
                    if (PerformanceCounterLib.s_libraryTable == null)
                    {
                        PerformanceCounterLib.s_libraryTable = new Dictionary <string, PerformanceCounterLib>();
                    }
                }
            }

            string libraryKey = machineName + ":" + lcidString;

            if (PerformanceCounterLib.s_libraryTable.ContainsKey(libraryKey))
            {
                return((PerformanceCounterLib)PerformanceCounterLib.s_libraryTable[libraryKey]);
            }
            else
            {
                PerformanceCounterLib library = new PerformanceCounterLib(machineName, lcidString);
                PerformanceCounterLib.s_libraryTable[libraryKey] = library;
                return(library);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        ///     Returns true if the category is registered in the machine.
        /// </summary>
        public static bool Exists(string categoryName, string machineName)
        {
            if (categoryName == null)
            {
                throw new ArgumentNullException(nameof(categoryName));
            }

            if (categoryName.Length == 0)
            {
                throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(categoryName), categoryName), nameof(categoryName));
            }

            if (!SyntaxCheck.CheckMachineName(machineName))
            {
                throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName), nameof(machineName));
            }

            if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName))
            {
                return(true);
            }

            return(PerformanceCounterLib.CategoryExists(machineName, categoryName));
        }
        public static void Delete(string categoryName)
        {
            CheckValidCategory(categoryName);
            string machineName = ".";

            PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Administer, machineName, categoryName);

            permission.Demand();

            SharedUtils.CheckNtEnvironment();

            categoryName = categoryName.ToLower(CultureInfo.InvariantCulture);

            Mutex mutex = null;

            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                SharedUtils.EnterMutex(perfMutexName, ref mutex);
                if (!PerformanceCounterLib.IsCustomCategory(machineName, categoryName))
                {
                    throw new InvalidOperationException(SR.GetString(SR.CantDeleteCategory));
                }

                SharedPerformanceCounter.RemoveAllInstances(categoryName);

                PerformanceCounterLib.UnregisterCategory(categoryName);
                PerformanceCounterLib.CloseAllLibraries();
            }
            finally {
                if (mutex != null)
                {
                    mutex.ReleaseMutex();
                    mutex.Close();
                }
            }
        }
 private static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data)
 {
     Hashtable hashtable = new Hashtable();
     ArrayList list = new ArrayList();
     GCHandle handle = new GCHandle();
     try
     {
         handle = GCHandle.Alloc(data, GCHandleType.Pinned);
         IntPtr ptr = handle.AddrOfPinnedObject();
         Microsoft.Win32.NativeMethods.PERF_DATA_BLOCK structure = new Microsoft.Win32.NativeMethods.PERF_DATA_BLOCK();
         Marshal.PtrToStructure(ptr, structure);
         IntPtr ptr2 = (IntPtr) (((long) ptr) + structure.HeaderLength);
         Microsoft.Win32.NativeMethods.PERF_INSTANCE_DEFINITION perf_instance_definition = new Microsoft.Win32.NativeMethods.PERF_INSTANCE_DEFINITION();
         Microsoft.Win32.NativeMethods.PERF_COUNTER_BLOCK perf_counter_block = new Microsoft.Win32.NativeMethods.PERF_COUNTER_BLOCK();
         for (int j = 0; j < structure.NumObjectTypes; j++)
         {
             Microsoft.Win32.NativeMethods.PERF_OBJECT_TYPE perf_object_type = new Microsoft.Win32.NativeMethods.PERF_OBJECT_TYPE();
             Marshal.PtrToStructure(ptr2, perf_object_type);
             IntPtr ptr3 = (IntPtr) (((long) ptr2) + perf_object_type.DefinitionLength);
             IntPtr ptr4 = (IntPtr) (((long) ptr2) + perf_object_type.HeaderLength);
             ArrayList list2 = new ArrayList();
             for (int k = 0; k < perf_object_type.NumCounters; k++)
             {
                 Microsoft.Win32.NativeMethods.PERF_COUNTER_DEFINITION perf_counter_definition = new Microsoft.Win32.NativeMethods.PERF_COUNTER_DEFINITION();
                 Marshal.PtrToStructure(ptr4, perf_counter_definition);
                 string counterName = library.GetCounterName(perf_counter_definition.CounterNameTitleIndex);
                 if (perf_object_type.ObjectNameTitleIndex == processIndex)
                 {
                     perf_counter_definition.CounterNameTitlePtr = (int) GetValueId(counterName);
                 }
                 else if (perf_object_type.ObjectNameTitleIndex == threadIndex)
                 {
                     perf_counter_definition.CounterNameTitlePtr = (int) GetValueId(counterName);
                 }
                 list2.Add(perf_counter_definition);
                 ptr4 = (IntPtr) (((long) ptr4) + perf_counter_definition.ByteLength);
             }
             Microsoft.Win32.NativeMethods.PERF_COUNTER_DEFINITION[] perf_counter_definitionArray = new Microsoft.Win32.NativeMethods.PERF_COUNTER_DEFINITION[list2.Count];
             list2.CopyTo(perf_counter_definitionArray, 0);
             for (int m = 0; m < perf_object_type.NumInstances; m++)
             {
                 Marshal.PtrToStructure(ptr3, perf_instance_definition);
                 IntPtr ptr5 = (IntPtr) (((long) ptr3) + perf_instance_definition.NameOffset);
                 string strA = Marshal.PtrToStringUni(ptr5);
                 if (!strA.Equals("_Total"))
                 {
                     IntPtr ptr6 = (IntPtr) (((long) ptr3) + perf_instance_definition.ByteLength);
                     Marshal.PtrToStructure(ptr6, perf_counter_block);
                     if (perf_object_type.ObjectNameTitleIndex == processIndex)
                     {
                         ProcessInfo info = GetProcessInfo(perf_object_type, (IntPtr) (((long) ptr3) + perf_instance_definition.ByteLength), perf_counter_definitionArray);
                         if (((info.processId != 0) || (string.Compare(strA, "Idle", StringComparison.OrdinalIgnoreCase) == 0)) && (hashtable[info.processId] == null))
                         {
                             string str3 = strA;
                             if (str3.Length == 15)
                             {
                                 if (strA.EndsWith(".", StringComparison.Ordinal))
                                 {
                                     str3 = strA.Substring(0, 14);
                                 }
                                 else if (strA.EndsWith(".e", StringComparison.Ordinal))
                                 {
                                     str3 = strA.Substring(0, 13);
                                 }
                                 else if (strA.EndsWith(".ex", StringComparison.Ordinal))
                                 {
                                     str3 = strA.Substring(0, 12);
                                 }
                             }
                             info.processName = str3;
                             hashtable.Add(info.processId, info);
                         }
                     }
                     else if (perf_object_type.ObjectNameTitleIndex == threadIndex)
                     {
                         ThreadInfo info2 = GetThreadInfo(perf_object_type, (IntPtr) (((long) ptr3) + perf_instance_definition.ByteLength), perf_counter_definitionArray);
                         if (info2.threadId != 0)
                         {
                             list.Add(info2);
                         }
                     }
                     ptr3 = (IntPtr) ((((long) ptr3) + perf_instance_definition.ByteLength) + perf_counter_block.ByteLength);
                 }
             }
             ptr2 = (IntPtr) (((long) ptr2) + perf_object_type.TotalByteLength);
         }
     }
     finally
     {
         if (handle.IsAllocated)
         {
             handle.Free();
         }
     }
     for (int i = 0; i < list.Count; i++)
     {
         ThreadInfo info3 = (ThreadInfo) list[i];
         ProcessInfo info4 = (ProcessInfo) hashtable[info3.processId];
         if (info4 != null)
         {
             info4.threadInfoList.Add(info3);
         }
     }
     ProcessInfo[] array = new ProcessInfo[hashtable.Values.Count];
     hashtable.Values.CopyTo(array, 0);
     return array;
 }
        internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture) {
            SharedUtils.CheckEnvironment();

            string lcidString = culture.LCID.ToString("X3", CultureInfo.InvariantCulture);
            if (machineName.CompareTo(".") == 0)
                machineName = ComputerName.ToLower(CultureInfo.InvariantCulture);
            else
                machineName = machineName.ToLower(CultureInfo.InvariantCulture);

            if (PerformanceCounterLib.libraryTable == null) {
                lock (InternalSyncObject) {
                    if (PerformanceCounterLib.libraryTable == null)
                        PerformanceCounterLib.libraryTable = new Hashtable();
                }
            }

            string libraryKey = machineName + ":" + lcidString;
            if (PerformanceCounterLib.libraryTable.Contains(libraryKey))
                return (PerformanceCounterLib)PerformanceCounterLib.libraryTable[libraryKey];
            else {
                PerformanceCounterLib library = new PerformanceCounterLib(machineName, lcidString);
                PerformanceCounterLib.libraryTable[libraryKey] = library;
                return library;
            }
        }
        internal unsafe CategorySample(byte[] data, CategoryEntry entry, PerformanceCounterLib library) {
            this.entry = entry;
            this.library = library;
            int categoryIndex = entry.NameIndex;
            NativeMethods.PERF_DATA_BLOCK dataBlock = new NativeMethods.PERF_DATA_BLOCK();
            fixed (byte* dataPtr = data) {
                IntPtr dataRef = new IntPtr((void*) dataPtr);

                Marshal.PtrToStructure(dataRef, dataBlock);
                this.SystemFrequency = dataBlock.PerfFreq;
                this.TimeStamp = dataBlock.PerfTime;
                this.TimeStamp100nSec = dataBlock.PerfTime100nSec;
                dataRef = (IntPtr)((long)dataRef + dataBlock.HeaderLength);
                int numPerfObjects = dataBlock.NumObjectTypes;
                if (numPerfObjects == 0) {
                    this.CounterTable = new Hashtable();
                    this.InstanceNameTable = new Hashtable(StringComparer.OrdinalIgnoreCase);
                    return;
                }

                //Need to find the right category, GetPerformanceData might return
                //several of them.
                NativeMethods.PERF_OBJECT_TYPE perfObject = null;
                bool foundCategory = false;
                for (int index = 0; index < numPerfObjects; index++) {
                    perfObject = new NativeMethods.PERF_OBJECT_TYPE();
                    Marshal.PtrToStructure(dataRef, perfObject);

                   if (perfObject.ObjectNameTitleIndex == categoryIndex) {
                        foundCategory = true;
                        break;
                    }

                    dataRef = (IntPtr)((long)dataRef + perfObject.TotalByteLength);
                }

                if (!foundCategory)
                    throw new InvalidOperationException(SR.GetString(SR.CantReadCategoryIndex, categoryIndex.ToString(CultureInfo.CurrentCulture)));

                this.CounterFrequency = perfObject.PerfFreq;
                this.CounterTimeStamp = perfObject.PerfTime;
                int counterNumber = perfObject.NumCounters;
                int instanceNumber = perfObject.NumInstances;

                if (instanceNumber == -1)
                    IsMultiInstance = false;
                else
                    IsMultiInstance = true;
                
                // Move pointer forward to end of PERF_OBJECT_TYPE
                dataRef = (IntPtr)((long)dataRef + perfObject.HeaderLength);

                CounterDefinitionSample[] samples = new CounterDefinitionSample[counterNumber];
                this.CounterTable = new Hashtable(counterNumber);
                for (int index = 0; index < samples.Length; ++ index) {
                    NativeMethods.PERF_COUNTER_DEFINITION perfCounter = new NativeMethods.PERF_COUNTER_DEFINITION();
                    Marshal.PtrToStructure(dataRef, perfCounter);
                    samples[index] = new CounterDefinitionSample(perfCounter, this, instanceNumber);
                    dataRef = (IntPtr)((long)dataRef + perfCounter.ByteLength);

                    int currentSampleType = samples[index].CounterType;
                    if (!PerformanceCounterLib.IsBaseCounter(currentSampleType)) {
                        // We'll put only non-base counters in the table. 
                        if (currentSampleType != NativeMethods.PERF_COUNTER_NODATA)
                            this.CounterTable[samples[index].NameIndex] = samples[index];
                    }
                    else {
                        // it's a base counter, try to hook it up to the main counter. 
                        Debug.Assert(index > 0, "Index > 0 because base counters should never be at index 0");
                        if (index > 0)
                            samples[index-1].BaseCounterDefinitionSample = samples[index];
                    }
                }

                // now set up the InstanceNameTable.  
                if (!IsMultiInstance) {
                    this.InstanceNameTable = new Hashtable(1, StringComparer.OrdinalIgnoreCase);
                    this.InstanceNameTable[PerformanceCounterLib.SingleInstanceName] = 0;

                    for (int index = 0; index < samples.Length; ++ index)  {
                        samples[index].SetInstanceValue(0, dataRef);
                    }
                }
                else {
                    string[] parentInstanceNames = null;
                    this.InstanceNameTable = new Hashtable(instanceNumber, StringComparer.OrdinalIgnoreCase);
                    for (int i = 0; i < instanceNumber; i++) {
                        NativeMethods.PERF_INSTANCE_DEFINITION perfInstance = new NativeMethods.PERF_INSTANCE_DEFINITION();
                        Marshal.PtrToStructure(dataRef, perfInstance);
                        if (perfInstance.ParentObjectTitleIndex > 0 && parentInstanceNames == null)
                            parentInstanceNames = GetInstanceNamesFromIndex(perfInstance.ParentObjectTitleIndex);

                        string instanceName;
                        if (parentInstanceNames != null && perfInstance.ParentObjectInstance >= 0 && perfInstance.ParentObjectInstance < parentInstanceNames.Length - 1)
                            instanceName = parentInstanceNames[perfInstance.ParentObjectInstance] + "/" + Marshal.PtrToStringUni((IntPtr)((long)dataRef + perfInstance.NameOffset));
                        else
                            instanceName = Marshal.PtrToStringUni((IntPtr)((long)dataRef + perfInstance.NameOffset));

                        //In some cases instance names are not unique (Process), same as perfmon
                        //generate a unique name.
                        string newInstanceName = instanceName;
                        int newInstanceNumber = 1;
                        while (true) {
                            if (!this.InstanceNameTable.ContainsKey(newInstanceName)) {
                                this.InstanceNameTable[newInstanceName] = i;
                                break;
                            }
                            else {
                                newInstanceName =  instanceName + "#" + newInstanceNumber.ToString(CultureInfo.InvariantCulture);
                                ++  newInstanceNumber;
                            }
                        }


                        dataRef = (IntPtr)((long)dataRef + perfInstance.ByteLength);
                        for (int index = 0; index < samples.Length; ++ index)
                            samples[index].SetInstanceValue(i, dataRef);

                        dataRef = (IntPtr)((long)dataRef + Marshal.ReadInt32(dataRef));
                    }
                }
            }
        }
Ejemplo n.º 34
0
        static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data) {
            Debug.WriteLineIf(Process.processTracing.TraceVerbose, "GetProcessInfos()");
            Hashtable processInfos = new Hashtable();
            ArrayList threadInfos = new ArrayList();

            GCHandle dataHandle = new GCHandle();             
            try {
                dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
                IntPtr dataBlockPtr = dataHandle.AddrOfPinnedObject();
                NativeMethods.PERF_DATA_BLOCK dataBlock = new NativeMethods.PERF_DATA_BLOCK();
                Marshal.PtrToStructure(dataBlockPtr, dataBlock);
                IntPtr typePtr = (IntPtr)((long)dataBlockPtr + dataBlock.HeaderLength);
                NativeMethods.PERF_INSTANCE_DEFINITION instance = new NativeMethods.PERF_INSTANCE_DEFINITION();
                NativeMethods.PERF_COUNTER_BLOCK counterBlock = new NativeMethods.PERF_COUNTER_BLOCK();                        
                for (int i = 0; i < dataBlock.NumObjectTypes; i++) {
                    NativeMethods.PERF_OBJECT_TYPE type = new NativeMethods.PERF_OBJECT_TYPE();
                    Marshal.PtrToStructure(typePtr, type);
                    IntPtr instancePtr = (IntPtr)((long)typePtr + type.DefinitionLength);
                    IntPtr counterPtr = (IntPtr)((long)typePtr + type.HeaderLength);
                    ArrayList counterList = new ArrayList();
                    
                    for (int j = 0; j < type.NumCounters; j++) {                    
                        NativeMethods.PERF_COUNTER_DEFINITION counter = new NativeMethods.PERF_COUNTER_DEFINITION();
                        Marshal.PtrToStructure(counterPtr, counter);
                        string counterName = library.GetCounterName(counter.CounterNameTitleIndex);

                        if (type.ObjectNameTitleIndex == processIndex)
                            counter.CounterNameTitlePtr = (int)GetValueId(counterName);
                        else if (type.ObjectNameTitleIndex == threadIndex)
                            counter.CounterNameTitlePtr = (int)GetValueId(counterName);
                        counterList.Add(counter);
                        counterPtr = (IntPtr)((long)counterPtr + counter.ByteLength);
                    }
                    NativeMethods.PERF_COUNTER_DEFINITION[] counters = new NativeMethods.PERF_COUNTER_DEFINITION[counterList.Count];
                    counterList.CopyTo(counters, 0);
                    for (int j = 0; j < type.NumInstances; j++) {
                        Marshal.PtrToStructure(instancePtr, instance);
                        IntPtr namePtr = (IntPtr)((long)instancePtr + instance.NameOffset);
                        string instanceName = Marshal.PtrToStringUni(namePtr);            
                        if (instanceName.Equals("_Total")) continue;
                        IntPtr counterBlockPtr = (IntPtr)((long)instancePtr + instance.ByteLength);
                        Marshal.PtrToStructure(counterBlockPtr, counterBlock);
                        if (type.ObjectNameTitleIndex == processIndex) {
                            ProcessInfo processInfo = GetProcessInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters);
                            if (processInfo.processId == 0 && string.Compare(instanceName, "Idle", StringComparison.OrdinalIgnoreCase) != 0) {
                                // Sometimes we'll get a process structure that is not completely filled in.
                                // We can catch some of these by looking for non-"idle" processes that have id 0
                                // and ignoring those.
                                Debug.WriteLineIf(Process.processTracing.TraceVerbose, "GetProcessInfos() - found a non-idle process with id 0; ignoring.");
                            }
                            else {
                                if (processInfos[processInfo.processId] != null) {
                                    // We've found two entries in the perfcounters that claim to be the
                                    // same process.  We throw an exception.  Is this really going to be
                                    // helpfull to the user?  Should we just ignore?
                                    Debug.WriteLineIf(Process.processTracing.TraceVerbose, "GetProcessInfos() - found a duplicate process id");
                                }
                                else {
                                    // the performance counters keep a 15 character prefix of the exe name, and then delete the ".exe",
                                    // if it's in the first 15.  The problem is that sometimes that will leave us with part of ".exe"
                                    // at the end.  If instanceName ends in ".", ".e", or ".ex" we remove it.
                                    string processName = instanceName;
                                    if (processName.Length == 15) {
                                        if      (instanceName.EndsWith(".", StringComparison.Ordinal  )) processName = instanceName.Substring(0, 14);
                                        else if (instanceName.EndsWith(".e", StringComparison.Ordinal )) processName = instanceName.Substring(0, 13);
                                        else if (instanceName.EndsWith(".ex", StringComparison.Ordinal)) processName = instanceName.Substring(0, 12);
                                    }
                                    processInfo.processName = processName;
                                    processInfos.Add(processInfo.processId, processInfo);
                                }
                            }
                        }
                        else if (type.ObjectNameTitleIndex == threadIndex) {
                            ThreadInfo threadInfo = GetThreadInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters);
                            if (threadInfo.threadId != 0) threadInfos.Add(threadInfo);
                        }
                        instancePtr = (IntPtr)((long)instancePtr + instance.ByteLength + counterBlock.ByteLength);
                    }                                
                    
                    typePtr = (IntPtr)((long)typePtr + type.TotalByteLength);
                }
            }
            finally {
                if (dataHandle.IsAllocated) dataHandle.Free();
            }

            for (int i = 0; i < threadInfos.Count; i++) {
                ThreadInfo threadInfo = (ThreadInfo)threadInfos[i];
                ProcessInfo processInfo = (ProcessInfo)processInfos[threadInfo.processId];
                if (processInfo != null) {
                    processInfo.threadInfoList.Add(threadInfo);
                }
            }
                        
            ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
            processInfos.Values.CopyTo(temp, 0);
            return temp;
        }
Ejemplo n.º 35
0
 static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library) {
     ProcessInfo[] processInfos = new ProcessInfo[0] ;
     byte[] dataPtr = null;
     
     int retryCount = 5;
     while (processInfos.Length == 0 && retryCount != 0) {                    
         try {
             dataPtr = library.GetPerformanceData(PerfCounterQueryString);
             processInfos = GetProcessInfos(library, ProcessPerfCounterId, ThreadPerfCounterId, dataPtr);
         }
         catch (Exception e) {
             throw new InvalidOperationException(SR.GetString(SR.CouldntGetProcessInfos), e);
         }
                                 
         --retryCount;                        
     }                    
 
     if (processInfos.Length == 0)
         throw new InvalidOperationException(SR.GetString(SR.ProcessDisabled));    
         
     return processInfos;                    
                 
 }
 private static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library)
 {
     ProcessInfo[] infoArray = new ProcessInfo[0];
     byte[] data = null;
     for (int i = 5; (infoArray.Length == 0) && (i != 0); i--)
     {
         try
         {
             data = library.GetPerformanceData("230 232");
             infoArray = GetProcessInfos(library, 230, 0xe8, data);
         }
         catch (Exception exception)
         {
             throw new InvalidOperationException(SR.GetString("CouldntGetProcessInfos"), exception);
         }
     }
     if (infoArray.Length == 0)
     {
         throw new InvalidOperationException(SR.GetString("ProcessDisabled"));
     }
     return infoArray;
 }
 internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture)
 {
     SharedUtils.CheckEnvironment();
     string lcid = culture.LCID.ToString("X3", CultureInfo.InvariantCulture);
     if (machineName.CompareTo(".") == 0)
     {
         machineName = ComputerName.ToLower(CultureInfo.InvariantCulture);
     }
     else
     {
         machineName = machineName.ToLower(CultureInfo.InvariantCulture);
     }
     if (libraryTable == null)
     {
         lock (InternalSyncObject)
         {
             if (libraryTable == null)
             {
                 libraryTable = new Hashtable();
             }
         }
     }
     string key = machineName + ":" + lcid;
     if (libraryTable.Contains(key))
     {
         return (PerformanceCounterLib) libraryTable[key];
     }
     PerformanceCounterLib lib = new PerformanceCounterLib(machineName, lcid);
     libraryTable[key] = lib;
     return lib;
 }
 internal unsafe CategorySample(byte[] data, System.Diagnostics.CategoryEntry entry, PerformanceCounterLib library)
 {
     this.entry = entry;
     this.library = library;
     int nameIndex = entry.NameIndex;
     Microsoft.Win32.NativeMethods.PERF_DATA_BLOCK structure = new Microsoft.Win32.NativeMethods.PERF_DATA_BLOCK();
     fixed (byte* numRef = data)
     {
         IntPtr ptr = new IntPtr((void*) numRef);
         Marshal.PtrToStructure(ptr, structure);
         this.SystemFrequency = structure.PerfFreq;
         this.TimeStamp = structure.PerfTime;
         this.TimeStamp100nSec = structure.PerfTime100nSec;
         ptr = (IntPtr) (((long) ptr) + structure.HeaderLength);
         int numObjectTypes = structure.NumObjectTypes;
         if (numObjectTypes == 0)
         {
             this.CounterTable = new Hashtable();
             this.InstanceNameTable = new Hashtable(StringComparer.OrdinalIgnoreCase);
             return;
         }
         Microsoft.Win32.NativeMethods.PERF_OBJECT_TYPE perf_object_type = null;
         bool flag = false;
         for (int i = 0; i < numObjectTypes; i++)
         {
             perf_object_type = new Microsoft.Win32.NativeMethods.PERF_OBJECT_TYPE();
             Marshal.PtrToStructure(ptr, perf_object_type);
             if (perf_object_type.ObjectNameTitleIndex == nameIndex)
             {
                 flag = true;
                 break;
             }
             ptr = (IntPtr) (((long) ptr) + perf_object_type.TotalByteLength);
         }
         if (!flag)
         {
             throw new InvalidOperationException(SR.GetString("CantReadCategoryIndex", new object[] { nameIndex.ToString(CultureInfo.CurrentCulture) }));
         }
         this.CounterFrequency = perf_object_type.PerfFreq;
         this.CounterTimeStamp = perf_object_type.PerfTime;
         int numCounters = perf_object_type.NumCounters;
         int numInstances = perf_object_type.NumInstances;
         if (numInstances == -1)
         {
             this.IsMultiInstance = false;
         }
         else
         {
             this.IsMultiInstance = true;
         }
         ptr = (IntPtr) (((long) ptr) + perf_object_type.HeaderLength);
         CounterDefinitionSample[] sampleArray = new CounterDefinitionSample[numCounters];
         this.CounterTable = new Hashtable(numCounters);
         for (int j = 0; j < sampleArray.Length; j++)
         {
             Microsoft.Win32.NativeMethods.PERF_COUNTER_DEFINITION perf_counter_definition = new Microsoft.Win32.NativeMethods.PERF_COUNTER_DEFINITION();
             Marshal.PtrToStructure(ptr, perf_counter_definition);
             sampleArray[j] = new CounterDefinitionSample(perf_counter_definition, this, numInstances);
             ptr = (IntPtr) (((long) ptr) + perf_counter_definition.ByteLength);
             int counterType = sampleArray[j].CounterType;
             if (!PerformanceCounterLib.IsBaseCounter(counterType))
             {
                 if (counterType != 0x40000200)
                 {
                     this.CounterTable[sampleArray[j].NameIndex] = sampleArray[j];
                 }
             }
             else if (j > 0)
             {
                 sampleArray[j - 1].BaseCounterDefinitionSample = sampleArray[j];
             }
         }
         if (!this.IsMultiInstance)
         {
             this.InstanceNameTable = new Hashtable(1, StringComparer.OrdinalIgnoreCase);
             this.InstanceNameTable["systemdiagnosticsperfcounterlibsingleinstance"] = 0;
             for (int k = 0; k < sampleArray.Length; k++)
             {
                 sampleArray[k].SetInstanceValue(0, ptr);
             }
         }
         else
         {
             string[] instanceNamesFromIndex = null;
             this.InstanceNameTable = new Hashtable(numInstances, StringComparer.OrdinalIgnoreCase);
             for (int m = 0; m < numInstances; m++)
             {
                 string str;
                 Microsoft.Win32.NativeMethods.PERF_INSTANCE_DEFINITION perf_instance_definition = new Microsoft.Win32.NativeMethods.PERF_INSTANCE_DEFINITION();
                 Marshal.PtrToStructure(ptr, perf_instance_definition);
                 if ((perf_instance_definition.ParentObjectTitleIndex > 0) && (instanceNamesFromIndex == null))
                 {
                     instanceNamesFromIndex = this.GetInstanceNamesFromIndex(perf_instance_definition.ParentObjectTitleIndex);
                 }
                 if (((instanceNamesFromIndex != null) && (perf_instance_definition.ParentObjectInstance >= 0)) && (perf_instance_definition.ParentObjectInstance < (instanceNamesFromIndex.Length - 1)))
                 {
                     str = instanceNamesFromIndex[perf_instance_definition.ParentObjectInstance] + "/" + Marshal.PtrToStringUni((IntPtr) (((long) ptr) + perf_instance_definition.NameOffset));
                 }
                 else
                 {
                     str = Marshal.PtrToStringUni((IntPtr) (((long) ptr) + perf_instance_definition.NameOffset));
                 }
                 string key = str;
                 int num10 = 1;
                 while (true)
                 {
                     if (!this.InstanceNameTable.ContainsKey(key))
                     {
                         this.InstanceNameTable[key] = m;
                         break;
                     }
                     key = str + "#" + num10.ToString(CultureInfo.InvariantCulture);
                     num10++;
                 }
                 ptr = (IntPtr) (((long) ptr) + perf_instance_definition.ByteLength);
                 for (int n = 0; n < sampleArray.Length; n++)
                 {
                     sampleArray[n].SetInstanceValue(m, ptr);
                 }
                 ptr = (IntPtr) (((long) ptr) + Marshal.ReadInt32(ptr));
             }
         }
     }
 }
        internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture)
        {
            string lcidString = culture.Name.ToLowerInvariant();
            if (machineName.CompareTo(".") == 0)
                machineName = ComputerName.ToLowerInvariant();
            else
                machineName = machineName.ToLowerInvariant();

            if (PerformanceCounterLib.s_libraryTable == null)
            {
                lock (InternalSyncObject)
                {
                    if (PerformanceCounterLib.s_libraryTable == null)
                        PerformanceCounterLib.s_libraryTable = new Dictionary<string, PerformanceCounterLib>();
                }
            }

            string libraryKey = machineName + ":" + lcidString;
            if (PerformanceCounterLib.s_libraryTable.ContainsKey(libraryKey))
                return (PerformanceCounterLib)PerformanceCounterLib.s_libraryTable[libraryKey];
            else
            {
                PerformanceCounterLib library = new PerformanceCounterLib(machineName, lcidString);
                PerformanceCounterLib.s_libraryTable[libraryKey] = library;
                return library;
            }
        }