Exemple #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");
        }
Exemple #2
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);
        }
Exemple #3
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);
        }
        /// <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)));
        }
        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);
        }
        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;
        }
        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);
            }
        }
        /// <summary>
        /// Saves the active changes to the current theme.
        ///
        /// This is needed to be performed before enabling high-contrast because when high-contrast is de-activated it
        /// loads the settings (such as the wallpaper) from the last used .theme file, rather than the applied settings.
        ///
        /// These means, any unsaved theme customisations will be lost.
        ///
        /// Theme files are described in https://docs.microsoft.com/en-us/windows/desktop/controls/themesfileformat-overview
        /// </summary>
        /// <param name="currentThemeFile">
        /// The current theme file used by the OS. This will be used as a base to create a new theme file, and currently
        /// applied settings will be added to it.</param>
        /// <param name="saveAs">The file to write the saved theme to.</param>
        private async Task SaveCurrentTheme(string currentThemeFile, string saveAs)
        {
            this.logger.LogInformation($"Saving current theme, using {currentThemeFile}.");

            bool isValid = false;
            Dictionary <string, string>?themeData = null;

            try
            {
                // Read the .theme file that's currently being used.
                Ini themeReader = new();
                await themeReader.ReadFile(currentThemeFile);

                themeData = themeReader.ReadData();
                isValid   = themeData.ContainsKey("MasterThemeSelector.MTSM");
            }
            catch (IOException e)
            {
                this.logger.LogInformation(e, $"Unable to read {currentThemeFile}.");
            }

            if (!isValid || themeData is null)
            {
                string defaultTheme = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows),
                                                   "resources\\Themes\\aero.theme");
                if (currentThemeFile != defaultTheme)
                {
                    // OBSERVATION: this code is re-entrant; also note that if the aero.theme file is corrupt...this might reenter infinitely until the stack was full
                    await this.SaveCurrentTheme(defaultTheme, saveAs);
                }
                return;
            }
            else if (themeData.ContainsKey("VisualStyles.HighContrast"))
            {
                // Only save the current theme if it is not high-contrast.
                return;
            }

            using IRegistryKey hKeyCurrentUser =
                      this.registry.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default);

            // Wallpaper
            using IRegistryKey desktopKey = hKeyCurrentUser.OpenSubKey(@"Control Panel\Desktop", false);

            themeData["Theme.DisplayName"] = "morphic";

            themeData["Control Panel\\Desktop.Wallpaper"] =
                desktopKey.GetValue("WallPaper")?.ToString() ?? string.Empty;
            themeData["Control Panel\\Desktop.TileWallpaper"] =
                desktopKey.GetValue("TileWallPaper")?.ToString() ?? string.Empty;
            themeData["Control Panel\\Desktop.WallpaperStyle"] =
                desktopKey.GetValue("WallPaperStyle")?.ToString() ?? string.Empty;

            using IRegistryKey wallpapersKey =
                      hKeyCurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\Wallpapers");
            string?backgroundType = wallpapersKey.GetValue("backgroundType")?.ToString();

            if (backgroundType != "2")
            {
                // It's not a slide-show, remove the entire section.
                themeData.Keys.Where(k => k.StartsWith("Slideshow"))
                .ToList()
                .ForEach(k => themeData.Remove(k));
            }

            // Colours
            using IRegistryKey colorsKey = hKeyCurrentUser.OpenSubKey(@"Control Panel\Colors");
            foreach (string valueName in colorsKey.GetValueNames())
            {
                if (colorsKey.GetValue(valueName, null) is string value)
                {
                    themeData[$"Control Panel\\Colors.{valueName}"] = value;
                }
            }

            // if the directory for the saveAs file doesn't exist, create it now
            var saveAsPath = Path.GetDirectoryName(saveAs);

            if (Directory.Exists(saveAsPath) == false)
            {
                Directory.CreateDirectory(saveAsPath);
            }

            Ini writer = new();
            await writer.ReadFile(currentThemeFile);

            writer.WriteData(themeData !);
            await writer.WriteFile(saveAs);

            // Make windows use this theme file when restoring high-contrast.
            using IRegistryKey highContrastKey =
                      hKeyCurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\HighContrast");
            highContrastKey.SetValue("Pre-High Contrast Scheme", saveAs);
        }