Пример #1
0
        public void TestMockWindowsRegistry()
        {
            var          w     = new WindowsRegistry();
            IRegistryKey rCore = w.LocalMachine.OpenSubKey(@"SOFTWARE\R-core");

            string localMachineTestReg = @"
[HKEY_LOCAL_MACHINE\SOFTWARE\R-core]

[HKEY_LOCAL_MACHINE\SOFTWARE\R-core\R]
'InstallPath'='C:\Program Files\R\R-3.3.3'
'Current Version'='3.3.3'
";
            var    reg = new MockRegistry(localMachineTestReg);
            var    lm  = reg.LocalMachine;

            //var sk = lm.GetSubKeyNames();
            rCore = lm.OpenSubKey(@"SOFTWARE\R-core");
            var valNames = rCore.GetValueNames();

            Assert.AreEqual(valNames.Length, 0);

            Assert.AreEqual(rCore.GetSubKeyNames().Length, 1);
            Assert.AreEqual(rCore.GetSubKeyNames()[0], "R");
            var R = rCore.OpenSubKey(@"R");

            Assert.AreEqual(R.GetSubKeyNames().Length, 0);
            Assert.AreEqual(R.GetValueNames().Length, 2);
            Assert.AreEqual(R.GetValue("InstallPath"), "C:\\Program Files\\R\\R-3.3.3");
            Assert.AreEqual(R.GetValue("Current Version"), "3.3.3");

            localMachineTestReg = @"
[HKEY_LOCAL_MACHINE\SOFTWARE\R-core\R\R64]
'InstallPath'='C:\Program Files\Microsoft\R Client\R_SERVER\'
'Current Version'='3.2.2.803'

[HKEY_LOCAL_MACHINE\SOFTWARE\R-core\R\R64\3.2.2.803]
'InstallPath'='C:\Program Files\Microsoft\R Client\R_SERVER\'
";

            reg   = new MockRegistry(localMachineTestReg);
            lm    = reg.LocalMachine;
            rCore = lm.OpenSubKey(@"SOFTWARE\R-core");
            Assert.AreEqual(rCore.GetValueNames().Length, 0);

            Assert.AreEqual(rCore.GetSubKeyNames().Length, 1);
            Assert.AreEqual(rCore.GetSubKeyNames()[0], "R");
            R = rCore.OpenSubKey(@"R");
            Assert.AreEqual(R.GetSubKeyNames().Length, 1);

            var R64 = lm.OpenSubKey(@"SOFTWARE\R-core\R\R64");

            Assert.AreEqual(R64.GetSubKeyNames().Length, 1);
            Assert.AreEqual(R64.GetValueNames().Length, 2);

            Assert.AreEqual(R64.GetValue("InstallPath"), @"C:\Program Files\Microsoft\R Client\R_SERVER\");
            Assert.AreEqual(R64.GetValue("Current Version"), "3.2.2.803");
        }
Пример #2
0
        public static IRInterpreterInfo GetMicrosoftRClientInfo(IRegistry registry = null, IFileSystem fileSystem = null)
        {
            registry   = registry ?? new RegistryImpl();
            fileSystem = fileSystem ?? new FileSystem();

            // If yes, check 32-bit registry for R engine installed by the R Server.
            // TODO: remove this when MRS starts writing 64-bit keys.
            if (IsMRCInstalledInSql(registry))
            {
                using (IRegistryKey hklm = registry.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) {
                    try {
                        using (var key = hklm.OpenSubKey(@"SOFTWARE\R-core\R64")) {
                            foreach (var keyName in key.GetSubKeyNames())
                            {
                                using (var rsKey = key.OpenSubKey(keyName)) {
                                    try {
                                        var path = (string)rsKey?.GetValue("InstallPath");
                                        if (!string.IsNullOrEmpty(path) && path.Contains(_rServer))
                                        {
                                            var info = new RInterpreterInfo(string.Empty, path);
                                            if (info.VerifyInstallation(new SupportedRVersionRange(), fileSystem))
                                            {
                                                return(new RInterpreterInfo(Invariant($"Microsoft R Client (SQL) {info.Version.Major}.{info.Version.Minor}.{info.Version.Build}"), info.InstallPath));
                                            }
                                        }
                                    } catch (Exception) { }
                                }
                            }
                        }
                    } catch (Exception) { }
                }
            }

            return(null);
        }
Пример #3
0
        private IRegistryKey GetRCoreRegistryKeyWin32(StringBuilder logger)
        {
            CheckPlatformWin32();
            IRegistryKey rCore = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\R-core");

            if (rCore == null)
            {
                doLogSetEnvVarInfo(@"Local machine SOFTWARE\R-core not found - trying current user", logger);
                rCore = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\R-core");
                if (rCore == null)
                {
                    throw new ApplicationException("Windows Registry key 'SOFTWARE\\R-core' not found in HKEY_LOCAL_MACHINE nor HKEY_CURRENT_USER");
                }
            }
            doFoundWinRegKey(rCore, logger);
            bool is64Bit = Environment.Is64BitProcess;
            var  subKey  = is64Bit ? "R64" : "R";
            var  r       = rCore.OpenSubKey(subKey);

            if (r == null)
            {
                throw new ApplicationException(string.Format(
                                                   "Windows Registry sub-key '{0}' of key '{1}' was not found", subKey, rCore.ToString()));
            }
            doFoundWinRegKey(rCore, logger);
            return(r);
        }
Пример #4
0
        /// <summary>
        /// Unsets the icon handler default icon sharp shell value, restoring the backed up value.
        /// </summary>
        /// <param name="classesKey">The classes key.</param>
        /// <param name="className">Name of the class.</param>
        private static void UnsetIconHandlerDefaultIcon(IRegistryKey classesKey, string className)
        {
            //  Open the class.
            using (var classKey = classesKey.OpenSubKey(className))
            {
                //  Check we have the class.
                if (classKey == null)
                {
                    throw new InvalidOperationException("Cannot open class " + className);
                }

                //  Open the default icon.
                using (var defaultIconKey = classKey.OpenSubKey(KeyName_DefaultIcon, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ReadKey | RegistryRights.WriteKey))
                {
                    //  Check we have the key.
                    if (defaultIconKey == null)
                    {
                        throw new InvalidOperationException("Cannot open default icon key for class " + className);
                    }

                    //  Do we have a backup default icon to restore?
                    if (defaultIconKey.GetValueNames().Any(vm => vm == ValueName_DefaultIconBackup))
                    {
                        //  Get the backup default icon.
                        var backupDefaultIcon = defaultIconKey.GetValue(ValueName_DefaultIconBackup, string.Empty).ToString();

                        //  Save the default icon, delete the backup.
                        defaultIconKey.SetValue(null, backupDefaultIcon);
                        defaultIconKey.DeleteValue(ValueName_DefaultIconBackup);
                    }
                }
            }
        }
Пример #5
0
        /// <summary>
        /// Sets the icon handler default icon, enabling an icon handler extension.
        /// </summary>
        /// <param name="classesKey">The classes key.</param>
        /// <param name="className">Name of the class.</param>
        private static void SetIconHandlerDefaultIcon(IRegistryKey classesKey, string className)
        {
            //  Open the class.
            using (var classKey = classesKey.OpenSubKey(className))
            {
                //  Check we have the class.
                if (classKey == null)
                {
                    throw new InvalidOperationException("Cannot open class " + className);
                }

                //  Open the default icon.
                using (var defaultIconKey = classKey.OpenSubKey(KeyName_DefaultIcon, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ReadKey | RegistryRights.WriteKey))
                {
                    //  Check we have the key.
                    if (defaultIconKey == null)
                    {
                        // if not, we create the key.
                        var tempDefaultIconKey = classesKey.CreateSubKey(className + @"\" + KeyName_DefaultIcon, RegistryKeyPermissionCheck.ReadWriteSubTree);
                        tempDefaultIconKey.SetValue(null, "%1");
                    }
                    else
                    {
                        //  Get the default icon.
                        var defaultIcon = defaultIconKey.GetValue(null, string.Empty).ToString();

                        //  Save the default icon.
                        defaultIconKey.SetValue(ValueName_DefaultIconBackup, defaultIcon);
                        defaultIconKey.SetValue(null, "%1");
                    }
                }
            }
        }
        private static bool TryGetDockerFromRegistryInstall(IFileSystem fs, IRegistryKey hklm, out LocalDocker docker)
        {
            using (var dockerRegKey = hklm.OpenSubKey(DockerRegistryPath)) {
                if (dockerRegKey != null)
                {
                    string[] subkeys = dockerRegKey.GetSubKeyNames();
                    foreach (var subKey in subkeys)
                    {
                        using (var key = dockerRegKey.OpenSubKey(subKey)) {
                            var isInstallKey = key.GetValueNames().Count(v => v.Equals("BinPath") || v.Equals("Version")) == 2;
                            if (isInstallKey)
                            {
                                var binPath     = ((string)key.GetValue("BinPath")).Trim('\"');
                                var commandPath = Path.Combine(binPath, DockerCommand);
                                if (fs.FileExists(commandPath))
                                {
                                    docker = new LocalDocker(binPath, commandPath);
                                    return(true);
                                }
                            }
                        }
                    }
                }
            }

            docker = null;
            return(false);
        }
Пример #7
0
        /// <summary>
        /// Gets the phone format from registry.
        /// </summary>
        /// <param name="countryCode">The country code.</param>
        /// <param name="distanceRule">The distance rule.</param>
        /// <returns>The string representation of the country's selected phone number format or <value>String.Empty</value>, if an error occured.</returns>
        public string GetPhoneFormat(int countryCode, DISTANCE_RULE distanceRule)
        {
            if (distanceRule == DISTANCE_RULE.CANONICAL)
            {
                return(PhoneNumberConstants.CANONICAL_FORMAT);
            }

            IRegistryKey hklmCountry = _registryProxy.LocalMachine.OpenSubKey(PhoneNumberConstants.REGISTRY_COUNTRYLIST_LEGACY);

            if (hklmCountry == null)
            {
                hklmCountry = _registryProxy.LocalMachine.OpenSubKey(PhoneNumberConstants.REGISTRY_COUNTRYLIST_MODERN);
            }

            try
            {
                hklmCountry = hklmCountry.OpenSubKey(countryCode.ToString());
                object curFormat = hklmCountry.GetValue(distanceRule.ToString());
                if (curFormat != null)
                {
                    return(curFormat.ToString());
                }
            }
            catch { }

            return(String.Empty);
        }
Пример #8
0
        /// <summary>
        /// Retrieves information on installed R versions in registry.
        /// </summary>
        private IEnumerable <IRInterpreterInfo> GetInstalledEnginesFromRegistry()
        {
            List <IRInterpreterInfo> engines = new List <IRInterpreterInfo>();

            // HKEY_LOCAL_MACHINE\SOFTWARE\R-core
            // HKEY_LOCAL_MACHINE\SOFTWARE\R-core\R64\3.3.0 Pre-release
            using (IRegistryKey hklm = _registry.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) {
                try {
                    using (var rKey = hklm.OpenSubKey(@"SOFTWARE\R-core\R64")) {
                        foreach (var name in rKey.GetSubKeyNames())
                        {
                            using (var subKey = rKey.OpenSubKey(name)) {
                                var path = subKey?.GetValue("InstallPath") as string;
                                if (!string.IsNullOrEmpty(path))
                                {
                                    // Convert '3.2.2.803 Microsoft R Client' to Microsoft R Client (version)
                                    // Convert '3.3.1' to 'R 3.3.1' for consistency
                                    engines.Add(new RInterpreterInfo(NameFromKey(name), path, _fileSystem));
                                }
                            }
                        }
                    }
                } catch (Exception) { }
            }
            return(engines);
        }
Пример #9
0
        /// <summary>
        /// Utility method that loads sub keys at the machine and user level.
        /// </summary>
        /// <param name="subKeyName">The name of the required sub key.</param>
        /// <param name="machineKey">The parent key at the machine level, or <see langword="null"/>
        /// if there is no registry key.</param>
        /// <param name="userKey">The parent key at the user level, or <see langword="null"/>
        /// if there is no registry key.</param>
        /// <param name="machineSubKey">When this method returns, contains a reference to the sub key of
        /// <paramref name="machineKey"/> named <paramref name="subKeyName"/>, or <see langword="null"/>
        /// if either machineKey is <see langword="null"/> or it does not have a sub key with
        /// the requested name.</param>
        /// <param name="userSubKey">When this method returns, contains a reference to the sub key of
        /// <paramref name="userKey"/> named <paramref name="subKeyName"/>, or <see langword="null"/>
        /// if either userKey is <see langword="null"/> or it does not have a sub key with
        /// the requested name.</param>
        protected static void LoadRegistrySubKeys(String subKeyName,
                                                  IRegistryKey machineKey, IRegistryKey userKey,
                                                  out IRegistryKey machineSubKey, out IRegistryKey userSubKey)
        {
            machineSubKey = machineKey != null?machineKey.OpenSubKey(subKeyName) : null;

            userSubKey = userKey != null?userKey.OpenSubKey(subKeyName) : null;
        }
        private IRegistryKey?OpenKey(string rootName, string keyPath, bool writing = false)
        {
            IRegistryKey root = GetRootKey(rootName, this.registry);

            return(writing
                ? root.CreateSubKey(keyPath)
                : root.OpenSubKey(keyPath));
        }
Пример #11
0
        private bool OverrideWithGroupPoliciesAndGenerateWmiObjectsForTraceSource(TraceSourceData traceSourceData,
                                                                                  bool readGroupPolicies, IRegistryKey machineKey, IRegistryKey userKey,
                                                                                  bool generateWmiObjects, ICollection <ConfigurationSetting> wmiSettings,
                                                                                  String sourceKind)
        {
            if (readGroupPolicies)
            {
                IRegistryKey policyKey = machineKey != null ? machineKey : userKey;
                if (policyKey != null)
                {
                    if (policyKey.IsPolicyKey && !policyKey.GetBoolValue(PolicyValueName).Value)
                    {
                        return(false);
                    }
                    try
                    {
                        SourceLevels?defaultLevelOverride = policyKey.GetEnumValue <SourceLevels>(SourceDefaultLevelPropertyName);

                        // the key where the values for the source listeners are stored
                        // might not exist if no listener is selected
                        traceSourceData.TraceListeners.Clear();
                        using (IRegistryKey listenersOverrideKey = policyKey.OpenSubKey(SourceTraceListenersPropertyName))
                        {
                            if (listenersOverrideKey != null)
                            {
                                foreach (String valueName in listenersOverrideKey.GetValueNames())
                                {
                                    traceSourceData.TraceListeners.Add(new TraceListenerReferenceData(valueName));
                                }
                            }
                        }
                        traceSourceData.DefaultLevel = defaultLevelOverride.Value;
                    }
                    catch (RegistryAccessException ex)
                    {
                        LogExceptionWhileOverriding(ex);
                    }
                }
            }
            if (generateWmiObjects)
            {
                String[] referencedTraceListeners = new String[traceSourceData.TraceListeners.Count];
                for (int i = 0; i < traceSourceData.TraceListeners.Count; i++)
                {
                    referencedTraceListeners[i]
                        = traceSourceData.TraceListeners.Get(i).Name;
                }

                wmiSettings.Add(
                    new TraceSourceSetting(
                        traceSourceData.Name,
                        traceSourceData.DefaultLevel.ToString(),
                        referencedTraceListeners,
                        sourceKind));
            }

            return(true);
        }
Пример #12
0
        /// <summary>
        /// Gets the class of the given file extension, optionally creating it if it does not exist.
        /// </summary>
        /// <param name="classesKey">The classes key (HKEY_CLASSES_ROOT).</param>
        /// <param name="fileExtension">The file extension, with a leading dot.</param>
        /// <param name="createIfMissing">if set to <c>true</c> then if no class exists, one will be created.</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException">Thrown if the extension is invalid.</exception>
        public static string Get(IRegistryKey classesKey, string fileExtension, bool createIfMissing)
        {
            //  Make sure that we have a file extension, a string which starts with a dot and
            //  has at least one character following it.
            if (string.IsNullOrEmpty(fileExtension) ||
                fileExtension.StartsWith(".") == false ||
                fileExtension.Length < 2)
            {
                throw new InvalidOperationException($@"'{fileExtension}' does not appear to be a valid file extension class.");
            }

            //  We will need the extension with no leading dot later.
            var extension = fileExtension.Substring(1);

            //  Open or create the file extension key.
            using (var fileExtensionClassKey =
                       classesKey.CreateSubKey(fileExtension, RegistryKeyPermissionCheck.ReadWriteSubTree))
            {
                //  Get the class, which is the 'default' value. If we've got a value, we're done.
                var fileExtensionClassName = fileExtensionClassKey.GetValue(null) as string;
                if (!string.IsNullOrEmpty(fileExtensionClassName))
                {
                    return(fileExtensionClassName);
                }

                //  We don't have a class for the extension. If we are *not* creating missing ones, we're done.
                if (!createIfMissing)
                {
                    return(null);
                }

                //  There is no file extension class name, so we'll have to create one. Set the desired class name.
                fileExtensionClassName = $"{extension}.1"; // e.g. 'dllfile', 'mytypefile'

                //  If the desired class name exists, we're going to have to bail out (we could try and find another
                //  name, but that starts to get difficult for users to reason about).
                using (var fileExtensionClassNameKey = classesKey.OpenSubKey(fileExtensionClassName))
                {
                    if (fileExtensionClassNameKey != null)
                    {
                        var applicationName = fileExtensionClassNameKey.GetValue(null) as string;
                        throw new InvalidOperationException(
                                  $@"Unable to create a new class '{fileExtensionClassName}' for extension '{fileExtension}'. That class is already in use by application '{applicationName}'.");
                    }
                }

                //  Create the file extension class name key, point the file extension to it, set a sensible name for the application and we're done.
                using (var fileExtensionClassNameKey = classesKey.CreateSubKey(fileExtensionClassName, RegistryKeyPermissionCheck.ReadWriteSubTree))
                {
                    fileExtensionClassKey.SetValue(null, fileExtensionClassName);
                    fileExtensionClassNameKey.SetValue(null, $"{extension} Application");
                    return(fileExtensionClassName);
                }
            }
        }
Пример #13
0
        private static string TryFindInstallationPath(string msiDisplayName, string applicationExeName, IRegistry registry, IFile file)
        {
            foreach (string key in SoftwareKeys)
            {
                using (IRegistryKey rk = registry.LocalMachine.OpenSubKey(key))
                {
                    if (rk == null)
                    {
                        continue;
                    }

                    //Let's go through the registry keys and get the info we need:
                    foreach (string skName in rk.GetSubKeyNames())
                    {
                        using (IRegistryKey sk = rk.OpenSubKey(skName))
                        {
                            if (sk == null)
                            {
                                continue;
                            }

                            try
                            {
                                //first look for PDF Architect 3
                                //If the key has value, continue, if not, skip it:
                                string displayName = sk.GetValue("DisplayName").ToString();
                                if ((displayName.StartsWith(msiDisplayName, StringComparison.OrdinalIgnoreCase)) &&
                                    !displayName.Contains("Enterprise") &&
                                    (sk.GetValue("Publisher").ToString().Contains("pdfforge")) &&
                                    (sk.GetValue("InstallLocation") != null))
                                {
                                    var installLocation = sk.GetValue("InstallLocation").ToString();
                                    var exePath         = Path.Combine(installLocation, applicationExeName);

                                    if (file.Exists(exePath))
                                    {
                                        return(exePath);
                                    }

                                    // if the exe does not exist, this is the wrong path
                                    return(null);
                                }
                            }
                            catch (Exception)
                            {
                                // ignored
                            }
                        }
                    }
                }
            }
            return(null);
        }
        /// <summary>
        /// Opens the exporer subkey.
        /// </summary>
        /// <param name="hiveKey">The hive key.</param>
        /// <param name="permissionCheck">The permission check.</param>
        /// <returns>
        /// The explorer subkey.
        /// </returns>
        private static IRegistryKey OpenExporerSubkey(IRegistryKey hiveKey, RegistryKeyPermissionCheck permissionCheck)
        {
            //  Open the explorer key with the desired permissions.
            var explorerKey = hiveKey.OpenSubKey(KeyName_Explorer, permissionCheck);
            
            //  If we don't have it, we've got a critical error.
            if (explorerKey == null)
                throw new InvalidOperationException("Unable to open the Explorer key.");

            //  Return the key.
            return explorerKey;
        }
Пример #15
0
        /// <summary>
        ///     Copy a registry key.  The parentKey must be writeable.
        /// </summary>
        /// <param name="parentKey"></param>
        /// <param name="keyNameToCopy"></param>
        /// <param name="newKeyName"></param>
        /// <returns></returns>
        public bool CopyKey(IRegistryKey parentKey, string keyNameToCopy, string newKeyName)
        {
            //Create new key
            var destinationKey = parentKey.CreateSubKey(newKeyName);

            //Open the sourceKey we are copying from
            var sourceKey = parentKey.OpenSubKey(keyNameToCopy);

            RecurseCopyKey(sourceKey, destinationKey);

            return(true);
        }
Пример #16
0
 private static string GetRVersionInstallPathFromRegistry(string version)
 {
     // HKEY_LOCAL_MACHINE\SOFTWARE\R-core
     using (IRegistryKey hklm = Registry.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) {
         try {
             using (var rKey = hklm.OpenSubKey(@"SOFTWARE\R-core\R\" + version)) {
                 if (rKey != null)
                 {
                     return(rKey.GetValue("InstallPath") as string);
                 }
             }
         } catch (Exception) { }
     }
     return(String.Empty);
 }
Пример #17
0
 private string RecurseFirstSubkey(IRegistryKey rCoreKey, StringBuilder logger)
 {
     string[] subKeyNames = rCoreKey.GetSubKeyNames();
     if (subKeyNames.Length > 0)
     {
         var versionNum      = subKeyNames.First();
         var rVersionCoreKey = rCoreKey.OpenSubKey(versionNum);
         doLogSetEnvVarInfo("As a last resort, trying to recurse into " + rVersionCoreKey, logger);
         return(GetRInstallPathFromRCoreKegKey(rVersionCoreKey, logger));
     }
     else
     {
         doLogSetEnvVarWarn("No sub-key found under " + rCoreKey, logger);
         return(null);
     }
 }
Пример #18
0
        private string GetRInstallPathFromRCoreKegKey(IRegistryKey rCoreKey, StringBuilder logger)
        {
            string installPath = null;

            string[] subKeyNames = rCoreKey.GetSubKeyNames();
            string[] valueNames  = rCoreKey.GetValueNames();
            if (valueNames.Length == 0)
            {
                doLogSetEnvVarWarn("Did not find any value names under " + rCoreKey, logger);
                return(RecurseFirstSubkey(rCoreKey, logger));
            }
            else
            {
                const string installPathKey = "InstallPath";
                if (valueNames.Contains(installPathKey))
                {
                    doLogSetEnvVarInfo("Found sub-key InstallPath under " + rCoreKey, logger);
                    installPath = (string)rCoreKey.GetValue(installPathKey);
                }
                else
                {
                    doLogSetEnvVarInfo("Did not find sub-key InstallPath under " + rCoreKey, logger);
                    if (valueNames.Contains("Current Version"))
                    {
                        doLogSetEnvVarInfo("Found sub-key Current Version under " + rCoreKey, logger);
                        string currentVersion = GetRCurrentVersionStringFromRegistry(rCoreKey);
                        if (subKeyNames.Contains(currentVersion))
                        {
                            IRegistryKey rVersionCoreKey = rCoreKey.OpenSubKey(currentVersion);
                            return(GetRInstallPathFromRCoreKegKey(rVersionCoreKey, logger));
                        }
                        else
                        {
                            doLogSetEnvVarWarn("Sub key " + currentVersion + " not found in " + rCoreKey, logger);
                        }
                    }
                    else
                    {
                        doLogSetEnvVarInfo("Did not find sub-key Current Version under " + rCoreKey, logger);
                        return(RecurseFirstSubkey(rCoreKey, logger));
                    }
                }
            }
            doLogSetEnvVarInfo(string.Format("InstallPath value of key " + rCoreKey.ToString() + ": {0}",
                                             installPath == null ? "null" : installPath), logger);
            return(installPath);
        }
Пример #19
0
        private bool TryFindInRegistry(string exeName, out string fullPath)
        {
            fullPath = null;

            const string keyBase     = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths";
            string       expectedKey = string.Format(@"{0}\{1}", keyBase, exeName);

            IRegistryKey hklm    = _registry.LocalMachine;
            IRegistryKey fileKey = hklm.OpenSubKey(expectedKey);

            if (fileKey == null)
            {
                return(false);
            }

            object result;

            try
            {
                result = fileKey.GetValue(string.Empty);
            }
            finally
            {
                fileKey.Close();
            }

            if (result == null)
            {
                return(false);
            }

            string suggestedPath = result.ToString();
            bool   exists        = _fileSystem.File.Exists(suggestedPath);

            if (!exists)
            {
                _log.Debug(
                    "{0} was specified in registry to be located at {1}, but it wasn't found there.",
                    exeName,
                    suggestedPath);
                return(false);
            }

            _log.Debug("Found {0} at {1} (via registry).", exeName, suggestedPath);
            fullPath = suggestedPath;
            return(true);
        }
        protected override void OverrideWithGroupPolicies(CategoryFilterData configurationObject, IRegistryKey policyKey)
        {
            CategoryFilterMode?categoryFilterModelOverride = policyKey.GetEnumValue <CategoryFilterMode>(CategoryFilterModePropertyName);

            configurationObject.CategoryFilters.Clear();
            using (IRegistryKey categoryFiltersOverrideKey = policyKey.OpenSubKey(CategoryFiltersKeyName))
            {
                if (categoryFiltersOverrideKey != null)
                {
                    foreach (String valueName in categoryFiltersOverrideKey.GetValueNames())
                    {
                        configurationObject.CategoryFilters.Add(new CategoryFilterEntry(valueName));
                    }
                }
            }
            configurationObject.CategoryFilterMode = categoryFilterModelOverride.Value;
        }
Пример #21
0
        /// <summary>
        /// Prints a registry key with the given depth.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="depth">The depth.</param>
        /// <returns>The key, printed at the given depth.</returns>
        private static string PrintKey(IRegistryKey key, int depth)
        {
            var indent = new string(' ', depth *3);

            //  Get the value strings.
            var values = key.GetValueNames()
                         .Select(v => $"{indent}{(string.IsNullOrEmpty(v) ? "(Default)" : v)} = {key.GetValue(v)}")
                         .OrderBy(s => s);

            //  Get the subkey strings.
            var subKeys = key.GetSubKeyNames()
                          .OrderBy(sk => sk)
                          .Select(sk =>
                                  $"{indent}{sk}{Environment.NewLine}{PrintKey(key.OpenSubKey(sk), depth + 1)}");

            return(string.Join(Environment.NewLine, values.Concat(subKeys)));
        }
Пример #22
0
        public static bool ValueExistsAtSubKey(this IRegistryKey key, string subkey, string value)
        {
            if (subkey.Length == 0)
            {
                throw new ArgumentException("The 'subkey' should not be empty", "subkey");
            }

            using (var k = key.OpenSubKey(subkey))
            {
                if (k == null)
                {
                    return(false);
                }
                // Gets the unnamed value.
                return((string)k.GetValue(string.Empty) == value);
            }
        }
        private bool OverrideWithGroupPoliciesForTraceSource(
            TraceSourceData traceSourceData,
            bool readGroupPolicies,
            IRegistryKey machineKey,
            IRegistryKey userKey,
            String sourceKind)
        {
            if (readGroupPolicies)
            {
                IRegistryKey policyKey = machineKey != null ? machineKey : userKey;
                if (policyKey != null)
                {
                    if (policyKey.IsPolicyKey && !policyKey.GetBoolValue(PolicyValueName).Value)
                    {
                        return(false);
                    }
                    try
                    {
                        SourceLevels?defaultLevelOverride = policyKey.GetEnumValue <SourceLevels>(SourceDefaultLevelPropertyName);
                        bool?        autoFlushOverride    = policyKey.GetBoolValue(SourceAutoFlushPropertyName);

                        // the key where the values for the source listeners are stored
                        // might not exist if no listener is selected
                        traceSourceData.TraceListeners.Clear();
                        using (IRegistryKey listenersOverrideKey = policyKey.OpenSubKey(SourceTraceListenersPropertyName))
                        {
                            if (listenersOverrideKey != null)
                            {
                                foreach (String valueName in listenersOverrideKey.GetValueNames())
                                {
                                    traceSourceData.TraceListeners.Add(new TraceListenerReferenceData(valueName));
                                }
                            }
                        }
                        traceSourceData.DefaultLevel = defaultLevelOverride.Value;
                        traceSourceData.AutoFlush    = autoFlushOverride.Value;
                    }
                    catch (RegistryAccessException ex)
                    {
                        LogExceptionWhileOverriding(ex);
                    }
                }
            }

            return(true);
        }
Пример #24
0
        /// <summary>
        /// Retrieves installed R versions. Returns array of strings
        /// that typically look like 'R-3.2.1' (but development versions
        /// may also look like '3.3.0 Pre-release' and typically are
        /// subfolders of 'Program Files\R'
        /// </summary>
        public static string[] GetInstalledEngineVersionsFromRegistry()
        {
            List <string> enginePaths = new List <string>();

            // HKEY_LOCAL_MACHINE\SOFTWARE\R-core
            // HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\R-core
            // HKEY_LOCAL_MACHINE\SOFTWARE\R-core\R64\3.3.0 Pre-release
            using (IRegistryKey hklm = Registry.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) {
                try {
                    using (var rKey = hklm.OpenSubKey(@"SOFTWARE\R-core\R")) {
                        return(rKey.GetSubKeyNames());
                    }
                } catch (Exception) { }
            }

            return(new string[0]);
        }
Пример #25
0
        public MareRegHandlerTests()
        {
            RegKeyFake = A.Fake <IRegistryKey>();
            A.CallTo(() => RegKeyFake.GetSubKeyNames()).Returns(new string[] { "1" });
            A.CallTo(() => RegKeyFake.GetValue("KMD_EnableInternalLargePage", null)).Returns(0);
            A.CallTo(() => RegKeyFake.GetValue("EnableCrossFireAutoLink", null)).Returns(0);
            A.CallTo(() => RegKeyFake.GetValue("EnableUlps", null)).Returns(0);
            A.CallTo(() => RegKeyFake.GetValue("DriverDesc", null)).Returns("FAKE_GPU");
            A.CallTo(() => RegKeyFake.SetValue(A <string> .Ignored, A <object> .Ignored, A <RegistryValueKind> .Ignored)).DoesNothing();
            A.CallTo(() => RegKeyFake.OpenSubKey(A <string> .Ignored, A <bool> .Ignored)).Returns(RegKeyFake);

            RegFake = A.Fake <IRegistry>();
            A.CallTo(() => RegFake.OpenSubKey(A <string> .Ignored)).Returns(RegKeyFake);

            MsgBoxFake = A.Fake <IMessageBox>();
            A.CallTo(() => MsgBoxFake.Show(A <string> .Ignored)).DoesNothing();
        }
Пример #26
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TEnum"></typeparam>
        /// <param name="policyKey"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        protected TEnum?GetFlagsEnumOverride <TEnum>(IRegistryKey policyKey, string propertyName)
            where TEnum : struct
        {
            string[] allValueNames = new string[0];

            using (var propertyKey = policyKey.OpenSubKey(propertyName))
            {
                if (propertyKey != null)
                {
                    allValueNames = propertyKey.GetValueNames();
                }
            }

            var convertedValues = allValueNames.Select(vn => Convert.ToUInt64(Enum.Parse(typeof(TEnum), vn)));
            var mergedValues    = convertedValues.Aggregate <ulong, ulong>(0, (acc, v) => acc | v);

            return((TEnum)Enum.ToObject(typeof(TEnum), mergedValues));
        }
Пример #27
0
        private static string GetRPathFromMRS()
        {
            // First check that MRS is present on the machine.
            bool mrsInstalled = false;

            try {
                using (var hklm = Registry.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) {
                    using (var key = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\130\sql_shared_mr")) {
                        var path = (string)key.GetValue("Path");
                        if (!string.IsNullOrEmpty(path) && path.Contains(rServer))
                        {
                            mrsInstalled = true;
                        }
                    }
                }
            } catch (Exception) { }

            // If yes, check 32-bit registry for R engine installed by the R Server.
            // TODO: remove this when MRS starts writing 64-bit keys.
            if (mrsInstalled)
            {
                using (IRegistryKey hklm = Registry.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) {
                    try {
                        using (var key = hklm.OpenSubKey(@"SOFTWARE\R-core\R64")) {
                            foreach (var keyName in key.GetSubKeyNames())
                            {
                                using (var rsKey = key.OpenSubKey(keyName)) {
                                    try {
                                        var path = (string)rsKey.GetValue("InstallPath");
                                        if (!string.IsNullOrEmpty(path) && path.Contains(rServer))
                                        {
                                            return(path);
                                        }
                                    } catch (Exception) { }
                                }
                            }
                        }
                    } catch (Exception) { }
                }
            }

            return(null);
        }
Пример #28
0
        private void RecurseCopyKey(IRegistryKey sourceKey, IRegistryKey destinationKey)
        {
            //copy all the values
            foreach (var valueName in sourceKey.GetValueNames())
            {
                var objValue = sourceKey.GetValue(valueName);
                var valKind  = sourceKey.GetValueKind(valueName);
                destinationKey.SetValue(valueName, objValue, valKind);
            }

            //For Each subKey
            //Create a new subKey in destinationKey
            //Call myself
            foreach (var sourceSubKeyName in sourceKey.GetSubKeyNames())
            {
                var sourceSubKey = sourceKey.OpenSubKey(sourceSubKeyName);
                var destSubKey   = destinationKey.CreateSubKey(sourceSubKeyName);
                RecurseCopyKey(sourceSubKey, destSubKey);
            }
        }
Пример #29
0
        public IRegistryKey OpenKey(string keyPath, RegistryKeyPermissionCheck permissionCheck = default, RegistryRights rights = default)
        {
            IRegistryKey cleanUpKey = null;

            try
            {
                IRegistryKey root        = GetCorrespondingRoot(keyPath);
                string       openKeyName = keyPath.MustEndWith(RegistryPathDelimiter).Remove(root.Name.MustEndWith(RegistryPathDelimiter));
                if (openKeyName.IsNullOrWhitespace())
                {
                    return(root);
                }
                cleanUpKey = root;
                IRegistryKey key = root.OpenSubKey(openKeyName, permissionCheck, rights);
                return(key);
            }
            finally
            {
                cleanUpKey?.Dispose();
            }
        }
Пример #30
0
        /// <summary>
        /// Gets the user's area code from the Registry.
        /// </summary>
        /// <returns>A string containing the user's area code or <value>String.Empty</value>, if an error occured.</returns>
        public string GetUserAreaCode()
        {
            IRegistryKey hklmLocations = _registryProxy.LocalMachine.OpenSubKey(PhoneNumberConstants.REGISTRY_LOCATIONS);

            try
            {
                object currentID = hklmLocations.GetValue("CurrentID");
                if (currentID == null)
                {
                    return(String.Empty);
                }
                IRegistryKey currentLocation = hklmLocations.OpenSubKey("Location" + currentID);
                object       areaCode        = currentLocation.GetValue("AreaCode");
                if (areaCode == null)
                {
                    return(String.Empty);
                }

                return(areaCode.ToString());
            }
            catch { return(String.Empty); }
        }