/// <devdoc>
        ///     Frees all the resources allocated for all performance
        ///     counters, frees File Mapping used by extensible counters,
        ///     unloads dll's used to read counters.
        /// </devdoc>
        public static void CloseSharedResources()
        {
            PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, ".", "*");

            permission.Demand();
            PerformanceCounterLib.CloseAllLibraries();
        }
Example #2
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)
        {
            if (counterName == null)
            {
                throw new ArgumentNullException(nameof(counterName));
            }

            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));
            }

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

            permission.Demand();

            return(PerformanceCounterLib.CounterExists(machineName, categoryName, counterName));
        }
Example #3
0
        private static void DeleteCategory(string categoryName, string machineName)
        {
            CheckValidCategory(categoryName);

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

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

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

            permission.Demand();

            SharedUtils.CheckNtEnvironment();

            Mutex mutex = SharedUtils.EnterMutex(perfMutexName);

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

                PerformanceCounterLib.UnregisterCategory(machineName, categoryName);
            }
            finally {
                mutex.ReleaseMutex();
                mutex.Close();
            }
        }
        // Will cause an update, raw value
        /// <devdoc>
        ///     Obtains a counter sample and returns the raw value for it.
        /// </devdoc>
        public CounterSample NextSample()
        {
            string currentCategoryName = categoryName;
            string currentMachineName  = machineName;

            PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName);

            permission.Demand();

            Initialize();
            CategorySample          categorySample = PerformanceCounterLib.GetCategorySample(currentMachineName, currentCategoryName);
            CounterDefinitionSample counterSample  = categorySample.GetCounterDefinitionSample(this.counterName);

            this.counterType = counterSample.CounterType;
            if (!categorySample.IsMultiInstance)
            {
                if (instanceName != null && instanceName.Length != 0)
                {
                    throw new InvalidOperationException(SR.GetString(SR.InstanceNameProhibited, this.instanceName));
                }

                return(counterSample.GetSingleValue());
            }
            else
            {
                if (instanceName == null || instanceName.Length == 0)
                {
                    throw new InvalidOperationException(SR.GetString(SR.InstanceNameRequired));
                }

                return(counterSample.GetInstanceValue(this.instanceName));
            }
        }
        /// <devdoc>
        ///     Returns true if the category is registered in the machine.
        /// </devdoc>
        public static bool Exists(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.Read, machineName, categoryName);

            permission.Demand();

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

            return(PerformanceCounterLib.CategoryExists(machineName, categoryName));
        }
 /// <include file='doc\PerformanceCounterPermissionEntryCollection.uex' path='docs/doc[@for="PerformanceCounterPermissionEntryCollection.PerformanceCounterPermissionEntryCollection"]/*' />
 ///<internalonly/>
 internal PerformanceCounterPermissionEntryCollection(PerformanceCounterPermission owner, ResourcePermissionBaseEntry[] entries)
 {
     this.owner = owner;
     for (int index = 0; index < entries.Length; ++index)
     {
         this.InnerList.Add(new PerformanceCounterPermissionEntry(entries[index]));
     }
 }
 internal PerformanceCounterPermissionEntryCollection(PerformanceCounterPermission owner, ResourcePermissionBaseEntry[] entries)
 {
     this.owner = owner;
     for (int i = 0; i < entries.Length; i++)
     {
         base.InnerList.Add(new PerformanceCounterPermissionEntry(entries[i]));
     }
 }
Example #8
0
        protected virtual bool UserHasAccessRights(string catagory)
        {
            PerformanceCounterPermission permissions = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Write, ".", catagory);
            permissions.Demand();

            if (!PerformanceCounterCategory.Exists(catagory, "."))
                return false;
            
            return true;
        }
Example #9
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;
                        }
                    }
                }
            }
        }
		internal PerformanceCounterPermissionEntryCollection (PerformanceCounterPermission owner)
		{
			this.owner = owner;
			ResourcePermissionBaseEntry[] entries = owner.GetEntries ();
			if (entries.Length > 0) {
				foreach (ResourcePermissionBaseEntry entry in entries) {
					PerformanceCounterPermissionAccess elpa = (PerformanceCounterPermissionAccess) entry.PermissionAccess;
					string machine = entry.PermissionAccessPath [0];
					string category = entry.PermissionAccessPath [1];
					PerformanceCounterPermissionEntry elpe = new PerformanceCounterPermissionEntry (elpa, machine, category);
					// we don't want to add them (again) to the base class
					InnerList.Add (elpe);
				}
			}
		}
        /// <devdoc>
        ///     Creates a PerformanceCounterCategory object for given category.
        ///     Uses the given machine name.
        /// </devdoc>
        public PerformanceCounterCategory(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.Read, machineName, categoryName);
            permission.Demand();

            this.categoryName = categoryName;
            this.machineName = machineName;
         }
        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();
                }
            }
        }
Example #13
0
 internal PerformanceCounterPermissionEntryCollection(PerformanceCounterPermission owner)
 {
     this.owner = owner;
     ResourcePermissionBaseEntry[] entries = owner.GetEntries();
     if (entries.Length > 0)
     {
         foreach (ResourcePermissionBaseEntry entry in entries)
         {
             PerformanceCounterPermissionAccess elpa = (PerformanceCounterPermissionAccess)entry.PermissionAccess;
             string machine  = entry.PermissionAccessPath [0];
             string category = entry.PermissionAccessPath [1];
             PerformanceCounterPermissionEntry elpe = new PerformanceCounterPermissionEntry(elpa, machine, category);
             // we don't want to add them (again) to the base class
             InnerList.Add(elpe);
         }
     }
 }
		public void PermissionState_Unrestricted ()
		{
			PermissionState ps = PermissionState.Unrestricted;
			PerformanceCounterPermission pcp = new PerformanceCounterPermission (ps);
			Assert.AreEqual (0, pcp.PermissionEntries.Count, "PermissionEntries");
			Assert.IsTrue (pcp.IsUnrestricted (), "IsUnrestricted");

			SecurityElement se = pcp.ToXml ();
			// only class and version are present
			Assert.AreEqual ("true", se.Attribute ("Unrestricted"), "Xml-Unrestricted");
			Assert.IsNull (se.Children, "Xml-Children");

			PerformanceCounterPermission copy = (PerformanceCounterPermission)pcp.Copy ();
			Assert.IsFalse (Object.ReferenceEquals (pcp, copy), "ReferenceEquals");
			Assert.AreEqual (pcp.PermissionEntries.Count, copy.PermissionEntries.Count, "copy-PermissionEntries");
			Assert.AreEqual (pcp.IsUnrestricted (), copy.IsUnrestricted (), "copy-IsUnrestricted ()");
		}
Example #15
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);
        }
        /// <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);
        }
        /// <devdoc>
        ///     Creates a PerformanceCounterCategory object for given category.
        ///     Uses the given machine name.
        /// </devdoc>
        public PerformanceCounterCategory(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.Read, machineName, categoryName);

            permission.Demand();

            this.categoryName = categoryName;
            this.machineName  = machineName;
        }
        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();
                }
            }
        }
Example #20
0
        /// <summary>
        ///     Creates a PerformanceCounterCategory object for given category.
        ///     Uses the given machine name.
        /// </summary>
        public PerformanceCounterCategory(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));
            }

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

            permission.Demand();

            _categoryName = categoryName;
            _machineName  = machineName;
        }
 ///<internalonly/>   
 internal PerformanceCounterPermissionEntryCollection(PerformanceCounterPermission owner, ResourcePermissionBaseEntry[] entries) {
     this.owner = owner;
     for (int index = 0; index < entries.Length; ++index)
         this.InnerList.Add(new PerformanceCounterPermissionEntry(entries[index]));
 }                                                                                                              
		public void Intersect_None ()
		{
			PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.None);
			PerformanceCounterPermission pcp2 = new PerformanceCounterPermission (PermissionState.None);
			// 1. None N None
			PerformanceCounterPermission result = (PerformanceCounterPermission)pcp1.Intersect (pcp2);
			Assert.IsNull (result, "Empty N Empty");
			// 2. None N Entry
			pcp2.PermissionEntries.Add (new PerformanceCounterPermissionEntry (PerformanceCounterPermissionAccess.None, "localhost", String.Empty));
			result = (PerformanceCounterPermission)pcp1.Intersect (pcp2);
			Assert.IsNull (result, "Empty N Entry");
			// 3. Entry N None
			result = (PerformanceCounterPermission)pcp2.Intersect (pcp1);
			Assert.IsNull (result, "Entry N Empty");
		}
        /// <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);
                }
            }
        }
		public void Intersect_Unrestricted ()
		{
			// Intersection with unrestricted == Copy
			// a. source (this) is unrestricted
			PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.Unrestricted);
			PerformanceCounterPermission pcp2 = new PerformanceCounterPermission (PermissionState.None);

			// 1. Unrestricted N None
			PerformanceCounterPermission result = (PerformanceCounterPermission)pcp1.Intersect (pcp2);
			Assert.IsFalse (result.IsUnrestricted (), "(Unrestricted N None).IsUnrestricted");
			Assert.AreEqual (0, result.PermissionEntries.Count, "(Unrestricted N None).Count");

			// 2. None N Unrestricted
			result = (PerformanceCounterPermission)pcp2.Intersect (pcp1);
			Assert.IsFalse (result.IsUnrestricted (), "(None N Unrestricted).IsUnrestricted");
			Assert.AreEqual (0, result.PermissionEntries.Count, "(None N Unrestricted).Count");

			// 3. Unrestricted N Unrestricted
			result = (PerformanceCounterPermission)pcp1.Intersect (pcp1);
			Assert.IsTrue (result.IsUnrestricted (), "(Unrestricted N Unrestricted).IsUnrestricted");
			Assert.AreEqual (0, result.PermissionEntries.Count, "(Unrestricted N Unrestricted).Count");

			// 4. Unrestricted N Entry
			pcp2.PermissionEntries.Add (new PerformanceCounterPermissionEntry (PerformanceCounterPermissionAccess.None, "localhost", String.Empty));
			result = (PerformanceCounterPermission)pcp1.Intersect (pcp2);
			Assert.IsFalse (result.IsUnrestricted (), "(Unrestricted N Entry).IsUnrestricted");
			Assert.AreEqual (1, result.PermissionEntries.Count, "(Unrestricted N Entry).Count");

			// 5. Entry N Unrestricted
			result = (PerformanceCounterPermission)pcp2.Intersect (pcp1);
			Assert.IsFalse (result.IsUnrestricted (), "(Entry N Unrestricted).IsUnrestricted");
			Assert.AreEqual (1, result.PermissionEntries.Count, "(Entry N Unrestricted).Count");

			// 6. Unrestricted N Unrestricted
			pcp1.PermissionEntries.Add (new PerformanceCounterPermissionEntry (PerformanceCounterPermissionAccess.None, "localhost", String.Empty));
			result = (PerformanceCounterPermission)pcp1.Intersect (pcp1);
			Assert.IsTrue (result.IsUnrestricted (), "(Unrestricted N Unrestricted).IsUnrestricted");
			Assert.AreEqual (1, result.PermissionEntries.Count, "(Unrestricted N Unrestricted).Count");
		}
		public void FromXml_WrongTagCase ()
		{
			PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
			SecurityElement se = pcp.ToXml ();
			se.Tag = "IPERMISSION"; // instead of IPermission
			pcp.FromXml (se);
			// note: normally IPermission classes (in corlib) DO care about the
			// IPermission tag
		}
		public void Copy ()
		{
			foreach (PerformanceCounterPermissionAccess pcpa in AllAccess) {
				PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
				PerformanceCounterPermissionEntry pcpe = new PerformanceCounterPermissionEntry (pcpa, pcpa.ToString (), String.Empty);
				pcp.PermissionEntries.Add (pcpe);
				PerformanceCounterPermission copy = (PerformanceCounterPermission)pcp.Copy ();
				Assert.AreEqual (1, copy.PermissionEntries.Count, "Count==1");
				Assert.AreEqual (pcpa, pcp.PermissionEntries [0].PermissionAccess, pcpa.ToString ());
			}
		}
		public void Union_BadPermission ()
		{
			PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.Unrestricted);
			pcp1.Union (new SecurityPermission (SecurityPermissionFlag.Assertion));
		}
Example #28
0
        internal static PerformanceCounterCategory Create(string categoryName, string categoryHelp, CounterCreationDataCollection counterData, string machineName, string localizedIniFilePath)
        {
            CheckValidCategory(categoryName);

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

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

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

            permission.Demand();

            SharedUtils.CheckNtEnvironment();

            Mutex mutex = SharedUtils.EnterMutex(perfMutexName);

            try {
                if (PerformanceCounterLib.IsCustomCategory(machineName, categoryName) || PerformanceCounterLib.CategoryExists(machineName, categoryName))
                {
                    throw new InvalidOperationException(SR.GetString(SR.PerformanceCategoryExists));
                }

                // Ensure that there are no duplicate counter names being created
                Hashtable h = new Hashtable();
                for (int i = 0; i < counterData.Count; i++)
                {
                    // Ensure that all counter help strings aren't null or empty
                    if (counterData[i].CounterName == null || counterData[i].CounterName.Length == 0)
                    {
                        throw new ArgumentException(SR.GetString(SR.InvalidCounterName));
                    }

                    int currentSampleType = (int)counterData[i].CounterType;
                    if ((currentSampleType == NativeMethods.PERF_AVERAGE_BULK) ||
                        (currentSampleType == NativeMethods.PERF_COUNTER_QUEUELEN_TYPE) ||
                        (currentSampleType == NativeMethods.PERF_COUNTER_LARGE_QUEUELEN_TYPE) ||
                        (currentSampleType == NativeMethods.PERF_100NSEC_MULTI_TIMER) ||
                        (currentSampleType == NativeMethods.PERF_100NSEC_MULTI_TIMER_INV) ||
                        (currentSampleType == NativeMethods.PERF_COUNTER_MULTI_TIMER) ||
                        (currentSampleType == NativeMethods.PERF_COUNTER_MULTI_TIMER_INV) ||
                        (currentSampleType == NativeMethods.PERF_RAW_FRACTION) ||
                        (currentSampleType == NativeMethods.PERF_SAMPLE_FRACTION) ||
                        (currentSampleType == NativeMethods.PERF_SAMPLE_COUNTER) ||
                        (currentSampleType == NativeMethods.PERF_AVERAGE_TIMER))
                    {
                        if (counterData.Count <= (i + 1))
                        {
                            throw new InvalidOperationException(SR.GetString(SR.CounterLayout));
                        }
                        else
                        {
                            currentSampleType = (int)counterData[i + 1].CounterType;


                            if (currentSampleType != NativeMethods.PERF_AVERAGE_BASE &&
                                currentSampleType != NativeMethods.PERF_COUNTER_MULTI_BASE &&
                                currentSampleType != NativeMethods.PERF_RAW_BASE &&
                                currentSampleType != NativeMethods.PERF_SAMPLE_BASE)
                            {
                                throw new InvalidOperationException(SR.GetString(SR.CounterLayout));
                            }
                        }
                    }
                    else if (currentSampleType == NativeMethods.PERF_AVERAGE_BASE ||
                             currentSampleType == NativeMethods.PERF_COUNTER_MULTI_BASE ||
                             currentSampleType == NativeMethods.PERF_RAW_BASE ||
                             currentSampleType == NativeMethods.PERF_SAMPLE_BASE)
                    {
                        if (i == 0)
                        {
                            throw new InvalidOperationException(SR.GetString(SR.CounterLayout));
                        }
                        else
                        {
                            currentSampleType = (int)counterData[i - 1].CounterType;

                            if (
                                (currentSampleType != NativeMethods.PERF_AVERAGE_BULK) &&
                                (currentSampleType != NativeMethods.PERF_COUNTER_QUEUELEN_TYPE) &&
                                (currentSampleType != NativeMethods.PERF_COUNTER_LARGE_QUEUELEN_TYPE) &&
                                (currentSampleType != NativeMethods.PERF_100NSEC_MULTI_TIMER) &&
                                (currentSampleType != NativeMethods.PERF_100NSEC_MULTI_TIMER_INV) &&
                                (currentSampleType != NativeMethods.PERF_COUNTER_MULTI_TIMER) &&
                                (currentSampleType != NativeMethods.PERF_COUNTER_MULTI_TIMER_INV) &&
                                (currentSampleType != NativeMethods.PERF_RAW_FRACTION) &&
                                (currentSampleType != NativeMethods.PERF_SAMPLE_FRACTION) &&
                                (currentSampleType != NativeMethods.PERF_SAMPLE_COUNTER) &&
                                (currentSampleType != NativeMethods.PERF_AVERAGE_TIMER))
                            {
                                throw new InvalidOperationException(SR.GetString(SR.CounterLayout));
                            }
                        }
                    }

                    if (h.ContainsKey(counterData[i].CounterName))
                    {
                        throw new ArgumentException(SR.GetString(SR.DuplicateCounterName, counterData[i].CounterName));
                    }
                    else
                    {
                        h.Add(counterData[i].CounterName, String.Empty);

                        // Ensure that all counter help strings aren't null or empty
                        if (counterData[i].CounterHelp == null || counterData[i].CounterHelp.Length == 0)
                        {
                            counterData[i].CounterHelp = counterData[i].CounterName + " help";
                        }
                    }
                }

                if (localizedIniFilePath == null)
                {
                    PerformanceCounterLib.RegisterCategory(machineName, categoryName, categoryHelp, counterData);
                }
                else
                {
                    PerformanceCounterLib.RegisterCategory(machineName, categoryName, categoryHelp, counterData, localizedIniFilePath);
                }

                return(new PerformanceCounterCategory(categoryName, machineName));
            }
            finally {
                mutex.ReleaseMutex();
                mutex.Close();
            }
        }
		public void IsSubset_Unrestricted ()
		{
			// IsSubset with unrestricted
			// a. source (this) is unrestricted -> target is never a subset
			// b. destination (target) is unrestricted -> source is always a subset
			PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.Unrestricted);
			foreach (PerformanceCounterPermissionAccess pcpa in AllAccess) {
				PerformanceCounterPermission pcp2 = new PerformanceCounterPermission (PermissionState.None);
				pcp2.PermissionEntries.Add (new PerformanceCounterPermissionEntry (pcpa, pcpa.ToString (), String.Empty));
				Assert.IsFalse (pcp1.IsSubsetOf (pcp2), "target " + pcpa.ToString ());
				Assert.IsTrue (pcp2.IsSubsetOf (pcp1), "source " + pcpa.ToString ());
			}
			Assert.IsTrue (pcp1.IsSubsetOf (pcp1), "Unrestricted.IsSubsetOf(Unrestricted)");
		}
        /// <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;
        }
        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();
                }
            }

        }
// "special" behavior inherited from ResourceBasePermission
//		[ExpectedException (typeof (ArgumentException))]
		public void IsSubsetOf_BadPermission ()
		{
			PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.Unrestricted);
			Assert.IsFalse (pcp1.IsSubsetOf (new SecurityPermission (SecurityPermissionFlag.Assertion)));
		}
		public void Intersect_Null ()
		{
			PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
			// No intersection with null
			Assert.IsNull (pcp.Intersect (null), "None N null");
		}
		public void Union_Unrestricted ()
		{
			// Union with unrestricted is unrestricted
			PerformanceCounterPermission pcp1 = new PerformanceCounterPermission (PermissionState.Unrestricted);
			foreach (PerformanceCounterPermissionAccess pcpa in AllAccess) {
				PerformanceCounterPermission pcp2 = new PerformanceCounterPermission (PermissionState.None);
				pcp2.PermissionEntries.Add (new PerformanceCounterPermissionEntry (pcpa, pcpa.ToString (), String.Empty));
				PerformanceCounterPermission union = (PerformanceCounterPermission)pcp1.Union (pcp2);
				Assert.IsTrue (union.IsUnrestricted (), "target.IsUnrestricted " + pcpa.ToString ());
				Assert.AreEqual (0, union.PermissionEntries.Count, "target.Count " + pcpa.ToString ());

				union = (PerformanceCounterPermission)pcp2.Union (pcp1);
				Assert.IsTrue (union.IsUnrestricted (), "source.IsUnrestricted " + pcpa.ToString ());
				Assert.AreEqual (0, union.PermissionEntries.Count, "source.Count " + pcpa.ToString ());
			}
		}
		public void Union_Self ()
		{
			foreach (PerformanceCounterPermissionAccess pcpa in AllAccess) {
				PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
				pcp.PermissionEntries.Add (new PerformanceCounterPermissionEntry (pcpa, pcpa.ToString (), String.Empty));
				PerformanceCounterPermission union = (PerformanceCounterPermission)pcp.Union (pcp);
				Assert.IsFalse (union.IsUnrestricted (), "IsUnrestricted " + pcpa.ToString ());
				Assert.AreEqual (1, union.PermissionEntries.Count, "Count " + pcpa.ToString ());
			}
		}
		public void PermissionState_Bad ()
		{
			PermissionState ps = (PermissionState)77;
			PerformanceCounterPermission pcp = new PerformanceCounterPermission (ps);
			Assert.IsFalse (pcp.IsUnrestricted (), "IsUnrestricted");
		}
		public void FromXml_Null ()
		{
			PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
			pcp.FromXml (null);
		}
		public void IsSubset_Self ()
		{
			foreach (PerformanceCounterPermissionAccess pcpa in AllAccess) {
				PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
				pcp.PermissionEntries.Add (new PerformanceCounterPermissionEntry (pcpa, pcpa.ToString (), String.Empty));
				Assert.IsTrue (pcp.IsSubsetOf (pcp), pcpa.ToString ());
			}
		}
		public void IsSubset_Null ()
		{
			PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
#if NET_2_0
			Assert.IsTrue (pcp.IsSubsetOf (null), "null");
#else
			Assert.IsFalse (pcp.IsSubsetOf (null), "null");
#endif
		}
		public void FromXml_WrongClass ()
		{
			PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
			SecurityElement se = pcp.ToXml ();

			SecurityElement w = new SecurityElement (se.Tag);
			w.AddAttribute ("class", "Wrong" + se.Attribute ("class"));
			w.AddAttribute ("version", se.Attribute ("version"));
			pcp.FromXml (w);
			// doesn't care of the class name at that stage
			// anyway the class has already be created so...
		}
		public void Union_Null ()
		{
			PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
			pcp.PermissionEntries.Add (new PerformanceCounterPermissionEntry (PerformanceCounterPermissionAccess.None, "localhost", String.Empty));
			// Union with null is a simple copy
			PerformanceCounterPermission union = (PerformanceCounterPermission)pcp.Union (null);
			Assert.IsNotNull (pcp.PermissionEntries.Count, "Count");
		}
        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 void FromXml_NoClass ()
		{
			PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
			SecurityElement se = pcp.ToXml ();

			SecurityElement w = new SecurityElement (se.Tag);
			w.AddAttribute ("version", se.Attribute ("version"));
			pcp.FromXml (w);
			// doesn't even care of the class attribute presence
		}
        /// <devdoc>
        ///     Returns true if the category is registered in the machine.
        /// </devdoc>
        public static bool Exists(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.Read,  machineName, categoryName);
            permission.Demand();

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

            return PerformanceCounterLib.CategoryExists(machineName , categoryName);
        }
		public void FromXml_WrongVersion ()
		{
			PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
			SecurityElement se = pcp.ToXml ();
			se.Attributes.Remove ("version");
			se.Attributes.Add ("version", "2");
			pcp.FromXml (se);
		}
        /// <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 void FromXml_NoVersion ()
		{
			PerformanceCounterPermission pcp = new PerformanceCounterPermission (PermissionState.None);
			SecurityElement se = pcp.ToXml ();

			SecurityElement w = new SecurityElement (se.Tag);
			w.AddAttribute ("class", se.Attribute ("class"));
			pcp.FromXml (w);
		}
	// Constructor.
	internal PerformanceCounterPermissionEntryCollection
				(PerformanceCounterPermission perm)
			{
				this.perm = perm;
			}
Example #49
0
 // Constructor.
 internal PerformanceCounterPermissionEntryCollection
     (PerformanceCounterPermission perm)
 {
     this.perm = perm;
 }