/// <summary> Gets a list of all available serial port names this controller provides. </summary> /// <returns> list of all available serial port names this controller provides. </returns> public List<string> GetPortNames() { RegistryKey baseKey = null; RegistryKey serialKey = null; var portNames = new List<string>(); var regperm = new RegistryPermission( RegistryPermissionAccess.Read, @"HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM"); regperm.Assert(); try { baseKey = Registry.LocalMachine; serialKey = baseKey.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM", false); if (serialKey != null) { var deviceNames = serialKey.GetValueNames(); portNames.AddRange(deviceNames.Select(devname => (string) serialKey.GetValue(devname))); } } finally { baseKey?.Dispose(); serialKey?.Dispose(); CodeAccessPermission.RevertAssert(); } return portNames; }
private static Uri GetRegistryPassportCertificationUrl() { // This Function Will return null, if the registry entry is missing // Acquire permissions to read the one key we care about from the registry RegistryPermission permission = new RegistryPermission( RegistryPermissionAccess.Read, System.Security.AccessControl.AccessControlActions.View, _passportActivationRegistryFullKeyName); permission.Assert(); try { RegistryKey key = Registry.LocalMachine.OpenSubKey(_passportActivationRegistryKeyName); if (key == null) { return null; } else { object keyValue = key.GetValue(null); // this should get the default value string stringValue = keyValue as string; if (stringValue != null) { return new Uri(stringValue); } else { return null; } } } finally { RegistryPermission.RevertAssert(); } }
private static void DeleteRegistryEntry(string categoryName) { RegistryKey serviceKey = null; //SECREVIEW: Whoever is able to call this function, must already // have demmanded PerformanceCounterPermission // we can therefore assert the RegistryPermission. RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted); registryPermission.Assert(); try { serviceKey = Registry.LocalMachine.OpenSubKey(ServicePath, true); bool deleteCategoryKey = false; using (RegistryKey categoryKey = serviceKey.OpenSubKey(categoryName, true)) { if (categoryKey != null) { if (categoryKey.GetValueNames().Length == 0) { deleteCategoryKey = true; } else { categoryKey.DeleteSubKeyTree("Linkage"); categoryKey.DeleteSubKeyTree("Performance"); } } } if (deleteCategoryKey) serviceKey.DeleteSubKeyTree(categoryName); } finally { if (serviceKey != null) serviceKey.Close(); RegistryPermission.RevertAssert(); } }
private static void CreateRegistryEntry(string categoryName, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection creationData, ref bool iniRegistered) { RegistryKey serviceParentKey = null; RegistryKey serviceKey = null; RegistryKey linkageKey = null; //SECREVIEW: Whoever is able to call this function, must already // have demmanded PerformanceCounterPermission // we can therefore assert the RegistryPermission. RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted); registryPermission.Assert(); try { serviceParentKey = Registry.LocalMachine.OpenSubKey(ServicePath, true); serviceKey = serviceParentKey.OpenSubKey(categoryName + "\\Performance", true); if (serviceKey == null) serviceKey = serviceParentKey.CreateSubKey(categoryName + "\\Performance"); serviceKey.SetValue("Open","OpenPerformanceData"); serviceKey.SetValue("Collect", "CollectPerformanceData"); serviceKey.SetValue("Close","ClosePerformanceData"); serviceKey.SetValue("Library", DllName); serviceKey.SetValue("IsMultiInstance", (int) categoryType, RegistryValueKind.DWord); serviceKey.SetValue("CategoryOptions", 0x3, RegistryValueKind.DWord); string [] counters = new string[creationData.Count]; string [] counterTypes = new string[creationData.Count]; for (int i = 0; i < creationData.Count; i++) { counters[i] = creationData[i].CounterName; counterTypes[i] = ((int) creationData[i].CounterType).ToString(CultureInfo.InvariantCulture); } linkageKey = serviceParentKey.OpenSubKey(categoryName + "\\Linkage" , true); if (linkageKey == null) linkageKey = serviceParentKey.CreateSubKey(categoryName + "\\Linkage" ); linkageKey.SetValue("Export", new string[]{categoryName}); serviceKey.SetValue("Counter Types", (object) counterTypes); serviceKey.SetValue("Counter Names", (object) counters); object firstID = serviceKey.GetValue("First Counter"); if (firstID != null) iniRegistered = true; else iniRegistered = false; } finally { if (serviceKey != null) serviceKey.Close(); if (linkageKey != null) linkageKey.Close(); if (serviceParentKey != null) serviceParentKey.Close(); RegistryPermission.RevertAssert(); } }
// What if an app is locked back? Why would we use this? internal static string GetLatestBuildDllDirectory(string machineName) { string dllDir = ""; RegistryKey baseKey = null; RegistryKey complusReg = null; //This property is retrieved only when creationg a new category, // the calling code already demanded PerformanceCounterPermission. // Therefore the assert below is safe. //This property is retrieved only when creationg a new log, // the calling code already demanded EventLogPermission. // Therefore the assert below is safe. RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted); registryPermission.Assert(); try { if (machineName.Equals(".")) { return GetLocalBuildDirectory(); } else { baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName); } if (baseKey == null) throw new InvalidOperationException(SR.GetString(SR.RegKeyMissingShort, "HKEY_LOCAL_MACHINE", machineName)); complusReg = baseKey.OpenSubKey("SOFTWARE\\Microsoft\\.NETFramework"); if (complusReg != null) { string installRoot = (string)complusReg.GetValue("InstallRoot"); if (installRoot != null && installRoot != String.Empty) { // the "policy" subkey contains a v{major}.{minor} subkey for each version installed. There are also // some extra subkeys like "standards" and "upgrades" we want to ignore. // first we figure out what version we are... string versionPrefix = "v" + Environment.Version.Major + "." + Environment.Version.Minor; RegistryKey policyKey = complusReg.OpenSubKey("policy"); // This is the full version string of the install on the remote machine we want to use (for example "v2.0.50727") string version = null; if (policyKey != null) { try { // First check to see if there is a version of the runtime with the same minor and major number: RegistryKey bestKey = policyKey.OpenSubKey(versionPrefix); if (bestKey != null) { try { version = versionPrefix + "." + GetLargestBuildNumberFromKey(bestKey); } finally { bestKey.Close(); } } else { // There isn't an exact match for our version, so we will look for the largest version // installed. string[] majorVersions = policyKey.GetSubKeyNames(); int[] largestVersion = new int[] { -1, -1, -1 }; for (int i = 0; i < majorVersions.Length; i++) { string majorVersion = majorVersions[i]; // If this looks like a key of the form v{something}.{something}, we should see if it's a usable build. if (majorVersion.Length > 1 && majorVersion[0] == 'v' && majorVersion.Contains(".")) { int[] currentVersion = new int[] { -1, -1, -1 }; string[] splitVersion = majorVersion.Substring(1).Split('.'); if(splitVersion.Length != 2) { continue; } if (!Int32.TryParse(splitVersion[0], out currentVersion[0]) || !Int32.TryParse(splitVersion[1], out currentVersion[1])) { continue; } RegistryKey k = policyKey.OpenSubKey(majorVersion); if (k == null) { // We may be able to use another subkey continue; } try { currentVersion[2] = GetLargestBuildNumberFromKey(k); if (currentVersion[0] > largestVersion[0] || ((currentVersion[0] == largestVersion[0]) && (currentVersion[1] > largestVersion[1]))) { largestVersion = currentVersion; } } finally { k.Close(); } } } version = "v" + largestVersion[0] + "." + largestVersion[1] + "." + largestVersion[2]; } } finally { policyKey.Close(); } if (version != null && version != String.Empty) { StringBuilder installBuilder = new StringBuilder(); installBuilder.Append(installRoot); if (!installRoot.EndsWith("\\", StringComparison.Ordinal)) installBuilder.Append("\\"); installBuilder.Append(version); dllDir = installBuilder.ToString(); } } } } } catch { // ignore } finally { if (complusReg != null) complusReg.Close(); if (baseKey != null) baseKey.Close(); RegistryPermission.RevertAssert(); } return dllDir; }
private unsafe CategoryData GetCategoryData() { CategoryData data = (CategoryData) categoryDataTable[categoryName]; if (data == null) { lock(categoryDataTable) { data = (CategoryData) categoryDataTable[categoryName]; if (data == null) { data = new CategoryData(); data.FileMappingName = DefaultFileMappingName; data.MutexName = categoryName; RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted); registryPermission.Assert(); RegistryKey categoryKey = null; try { categoryKey = Registry.LocalMachine.OpenSubKey(PerformanceCounterLib.ServicePath + "\\" + categoryName + "\\Performance"); // first read the options Object optionsObject = categoryKey.GetValue("CategoryOptions"); if (optionsObject != null) { int options = (int) optionsObject; data.EnableReuse = (((PerformanceCounterCategoryOptions) options & PerformanceCounterCategoryOptions.EnableReuse) != 0); if (((PerformanceCounterCategoryOptions) options & PerformanceCounterCategoryOptions.UseUniqueSharedMemory) != 0) { data.UseUniqueSharedMemory = true; InitialOffset = 8; data.FileMappingName = DefaultFileMappingName + categoryName; } } int fileMappingSize; object fileMappingSizeObject = categoryKey.GetValue("FileMappingSize"); if (fileMappingSizeObject != null && data.UseUniqueSharedMemory) { // we only use this reg value in the unique shared memory case. fileMappingSize = (int) fileMappingSizeObject; if (fileMappingSize < MinCountersFileMappingSize) fileMappingSize = MinCountersFileMappingSize; if (fileMappingSize > MaxCountersFileMappingSize) fileMappingSize = MaxCountersFileMappingSize; } else { fileMappingSize = GetFileMappingSizeFromConfig(); if (data.UseUniqueSharedMemory) fileMappingSize = fileMappingSize >> 2; // if we have a custom filemapping, only make it 25% as large. } // now read the counter names object counterNamesObject = categoryKey.GetValue("Counter Names"); byte[] counterNamesBytes = counterNamesObject as byte[]; if (counterNamesBytes != null) { ArrayList names = new ArrayList(); fixed (byte* counterNamesPtr = counterNamesBytes) { int start = 0; for (int i=0; i<counterNamesBytes.Length-1; i+=2) { if (counterNamesBytes[i] == 0 && counterNamesBytes[i+1] == 0 && start != i) { string counter = new String((sbyte*)counterNamesPtr, start, i-start, Encoding.Unicode); names.Add(counter.ToLowerInvariant()); start = i+2; } } } data.CounterNames = names; } else { string[] counterNames = (string[]) counterNamesObject; for (int i=0; i<counterNames.Length; i++) counterNames[i] = counterNames[i].ToLowerInvariant(); data.CounterNames = new ArrayList(counterNames); } // figure out the shared memory name if (SharedUtils.CurrentEnvironment == SharedUtils.W2kEnvironment) { data.FileMappingName = "Global\\" + data.FileMappingName; data.MutexName = "Global\\" + categoryName; } data.FileMapping = new FileMapping(data.FileMappingName, fileMappingSize, InitialOffset); categoryDataTable[categoryName] = data; } finally { if (categoryKey != null) categoryKey.Close(); RegistryPermission.RevertAssert(); } } } } baseAddress = (long) data.FileMapping.FileViewAddress; if (data.UseUniqueSharedMemory) InitialOffset = 8; return data; }
public static string[] GetPortNames() { if (Environment.OSVersion.Platform == PlatformID.Win32Windows) throw new PlatformNotSupportedException(SR.GetString(SR.NotSupportedOS)); // Get all the registered serial device names RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted); registryPermission.Assert(); RegistryKey baseKey = null; RegistryKey serialKey = null; Hashtable portNames = new Hashtable(10); try { baseKey = Registry.LocalMachine; serialKey = baseKey.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM", true); if (serialKey != null) { string[] devices = serialKey.GetValueNames(); for (int j=0; j<devices.Length; j++) { portNames.Add(devices[j], null); } } } finally { if (baseKey != null) baseKey.Close(); if (serialKey != null) serialKey.Close(); RegistryPermission.RevertAssert(); } // Get all the MS-DOS names on the local machine //(sending null for lpctstrName gets all the names) int dataSize; char[] buffer = CallQueryDosDevice(null, out dataSize); // From QueryDosDevice, we get back a long string where the names are delimited by \0 and the end // of the string is indicated by two \0s ArrayList names = new ArrayList(); ArrayList deviceNames = new ArrayList(); int i=0; while (i < dataSize) { // Walk through the buffer building a name until we hit the delimiter \0 int start = i; while (buffer[i] != '\0') { i++; } if (i != start) { // We now have an MS-DOS name (the common name). We call QueryDosDevice again with // this name to get the underlying system name mapped to the MS-DOS name. string currentName = (new String(buffer, start, i-start)).Trim(); int nameSize; char[] nameBuffer = CallQueryDosDevice(currentName, out nameSize); // If we got a system name, see if it's a serial port name. If it is, add the common name // to our list if (nameSize > 0) { // internalName will include the trailing null chars as well as any additional // names that may get returned. This is ok, since we are only interested in the // first name and we can use StartsWith. string internalName = new string(nameBuffer, 0, nameSize-2).Trim(); if (internalName.StartsWith(SERIAL_NAME) || portNames.ContainsKey(internalName)) { names.Add(currentName); deviceNames.Add(internalName); } } } i++; } string[] namesArray = new String[names.Count]; names.CopyTo(namesArray); string[] deviceNamesArray = new String[deviceNames.Count]; deviceNames.CopyTo(deviceNamesArray); // sort the common names according to their actual device ordering Array.Sort(deviceNamesArray, namesArray, Comparer.DefaultInvariant); return namesArray; }
internal static string GetLatestBuildDllDirectory(string machineName) { string result = ""; RegistryKey registryKey = null; RegistryKey registryKey2 = null; RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted); registryPermission.Assert(); try { if (machineName.Equals(".")) { return SharedUtils.GetLocalBuildDirectory(); } registryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName); if (registryKey == null) { throw new InvalidOperationException("RegKeyMissingShort"); } registryKey2 = registryKey.OpenSubKey("SOFTWARE\\Microsoft\\.NETFramework"); if (registryKey2 != null) { string text = (string)registryKey2.GetValue("InstallRoot"); if (text != null && text != string.Empty) { string text2 = string.Concat(new object[] { "v", Environment.Version.Major, ".", Environment.Version.Minor }); RegistryKey registryKey3 = registryKey2.OpenSubKey("policy"); string text3 = null; if (registryKey3 != null) { try { RegistryKey registryKey4 = registryKey3.OpenSubKey(text2); if (registryKey4 != null) { try { text3 = text2 + "." + SharedUtils.GetLargestBuildNumberFromKey(registryKey4); goto IL_29A; } finally { registryKey4.Close(); } } string[] subKeyNames = registryKey3.GetSubKeyNames(); int[] array = new int[] { -1, -1, -1 }; for (int i = 0; i < subKeyNames.Length; i++) { string text4 = subKeyNames[i]; if (text4.Length > 1 && text4[0] == 'v' && text4.Contains(".")) { int[] array2 = new int[] { -1, -1, -1 }; string[] array3 = text4.Substring(1).Split(new char[] { '.' }); if (array3.Length == 2 && int.TryParse(array3[0], out array2[0]) && int.TryParse(array3[1], out array2[1])) { RegistryKey registryKey5 = registryKey3.OpenSubKey(text4); if (registryKey5 != null) { try { array2[2] = SharedUtils.GetLargestBuildNumberFromKey(registryKey5); if (array2[0] > array[0] || (array2[0] == array[0] && array2[1] > array[1])) { array = array2; } } finally { registryKey5.Close(); } } } } } text3 = string.Concat(new object[] { "v", array[0], ".", array[1], ".", array[2] }); IL_29A: ; } finally { registryKey3.Close(); } if (text3 != null && text3 != string.Empty) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(text); if (!text.EndsWith("\\", StringComparison.Ordinal)) { stringBuilder.Append("\\"); } stringBuilder.Append(text3); result = stringBuilder.ToString(); } } } } } catch { } finally { if (registryKey2 != null) { registryKey2.Close(); } if (registryKey != null) { registryKey.Close(); } CodeAccessPermission.RevertAssert(); } return result; }
public static string[] GetPortNames() { RegistryKey baseKey = null; RegistryKey serialKey = null; String[] portNames = null; RegistryPermission registryPermission = new RegistryPermission(RegistryPermissionAccess.Read, @"HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM"); registryPermission.Assert(); try { baseKey = Registry.LocalMachine; serialKey = baseKey.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM", false); if (serialKey != null) { string[] deviceNames = serialKey.GetValueNames(); portNames = new String[deviceNames.Length]; for (int i=0; i<deviceNames.Length; i++) portNames[i] = (string)serialKey.GetValue(deviceNames[i]); } } finally { if (baseKey != null) baseKey.Close(); if (serialKey != null) serialKey.Close(); RegistryPermission.RevertAssert(); } // If serialKey didn't exist for some reason if (portNames == null) portNames = new String[0]; return portNames; }
private static void ReadAnimationSmoothingSetting() { #if PRERELEASE // Acquire permissions to read the one key we care about from the registry RegistryPermission permission = new RegistryPermission( RegistryPermissionAccess.Read, System.Security.AccessControl.AccessControlActions.View, @"HKEY_LOCAL_MACHINE\Software\Microsoft\Avalon.Graphics"); permission.Assert(); try { RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Avalon.Graphics"); if (key != null) { object keyValue = key.GetValue("AnimationSmoothing"); // The Regkey now turns off AnimationSmoothing s_animationSmoothing = !(keyValue is int && ((int)keyValue) == 0); } } finally { RegistryPermission.RevertAssert(); } #endif }
static internal CultureInfo GetCultureInfoByIetfLanguageTag(string languageTag) { CultureInfo culture = null; RegistryPermission regPerm = new RegistryPermission(RegistryPermissionAccess.Read, RegistryKeys.HKLM_IetfLanguage);//BlessedAssert regPerm.Assert();//BlessedAssert try { culture = CultureInfo.GetCultureInfoByIetfLanguageTag(languageTag); } finally { RegistryPermission.RevertAssert(); } return culture; }
internal static bool IsFeatureDisabled(KeyToRead key) { string regValue = null; bool fResult = false; switch (key) { case KeyToRead.WebBrowserDisable: regValue = RegistryKeys.value_WebBrowserDisallow; break; case KeyToRead.MediaAudioDisable: regValue = RegistryKeys.value_MediaAudioDisallow; break; case KeyToRead.MediaVideoDisable: regValue = RegistryKeys.value_MediaVideoDisallow; break; case KeyToRead.MediaImageDisable: regValue = RegistryKeys.value_MediaImageDisallow; break; case KeyToRead.MediaAudioOrVideoDisable: regValue = RegistryKeys.value_MediaAudioDisallow; break; case KeyToRead.ScriptInteropDisable: regValue = RegistryKeys.value_ScriptInteropDisallow; break; default:// throw exception for invalid key throw(new System.ArgumentException(key.ToString())); } RegistryKey featureKey; //Assert for read access to HKLM\Software\Microsoft\Windows\Avalon RegistryPermission regPerm = new RegistryPermission(RegistryPermissionAccess.Read,"HKEY_LOCAL_MACHINE\\"+RegistryKeys.WPF_Features);//BlessedAssert regPerm.Assert();//BlessedAssert try { object obj = null; bool keyValue = false; // open the key and read the value featureKey = Registry.LocalMachine.OpenSubKey(RegistryKeys.WPF_Features); if (featureKey != null) { // If key exists and value is 1 return true else false obj = featureKey.GetValue(regValue); keyValue = obj is int && ((int)obj == 1); if (keyValue) { fResult = true; } // special case for audio and video since they can be orred // this is in the condition that audio is enabled since that is // the path that MediaAudioVideoDisable defaults to // This is purely to optimize perf on the number of calls to assert // in the media or audio scenario. if ((fResult == false) && (key == KeyToRead.MediaAudioOrVideoDisable)) { regValue = RegistryKeys.value_MediaVideoDisallow; // If key exists and value is 1 return true else false obj = featureKey.GetValue(regValue); keyValue = obj is int && ((int)obj == 1); if (keyValue) { fResult = true; } } } } finally { RegistryPermission.RevertAssert(); } return fResult; }
internal void ClassicRegistration(Assembly asm) { RegistryPermission permission = new RegistryPermission(PermissionState.Unrestricted); permission.Demand(); permission.Assert(); try { new RegistrationServices().RegisterAssembly(asm, AssemblyRegistrationFlags.SetCodeBase); } catch (Exception exception) { if ((exception is NullReferenceException) || (exception is SEHException)) { throw; } throw new RegistrationException(Resource.FormatString("Reg_AssemblyRegErr", asm), exception); } }