Microsoft.Win32.RegistryKey.OpenSubKey(string)

Here are the examples of the csharp api Microsoft.Win32.RegistryKey.OpenSubKey(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1105 Examples 7

19 Source : Exploit.cs
with GNU General Public License v3.0
from 0x00-0x00

public static int GetCortana()
        {

            string KeyName = @"SOFTWARE\Policies\Microsoft\Windows\Windows Search";
            string ValueName = "AllowCortana";

            using (var key = Registry.LocalMachine.OpenSubKey(KeyName))
            {
                return (int)(key?.GetValue(ValueName) ?? -1);
            }
        }

19 Source : Form1.cs
with MIT License
from 200Tigersbloxed

private void button1_Click(object sender, EventArgs e)
        {
            // Find the Steam folder
            RegistryKey rk1s = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
            if (rk1s != null)
            {
                RegistryKey rk2 = rk1s.OpenSubKey("Software");
                if (rk2 != null)
                {
                    RegistryKey rk3 = rk2.OpenSubKey("Valve");
                    if (rk3 != null)
                    {
                        RegistryKey rk4 = rk3.OpenSubKey("Steam");
                        if (rk4 != null)
                        {
                            userownssteam = true;
                            string phrase = rk4.GetValue("SteamPath").ToString();
                            steaminstallpath = phrase;
                        }
                    }
                }
            }

            if(userownssteam == false)
            {
                MessageBox.Show("Uh Oh!", "Steam Could not be found!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else{
                bsl = steaminstallpath + @"/steamapps/common/Beat Saber";
                if(Directory.Exists(bsl))
                {
                    if(File.Exists(bsl + @"\Beat Saber.exe"))
                    {
                        if(File.Exists(bsl + @"\IPA.exe"))
                        {
                            textBox1.Text = bsl;
                            pictureBox1.Image = BSMulti_Installer2.Properties.Resources.tick;
                            button4.BackColor = SystemColors.MenuHighlight;
                            allownext = true;
                            runVerifyCheck();
                            findMultiplayerVersion();
                        }
                        else
                        {
                            MessageBox.Show("IPA.exe Could not be found! Is Beat Saber Modded?", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Beat Saber.exe Could not be found! Is Beat Saber Installed?", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Beat Saber Could not be found! Is Beat Saber Installed under Steam?", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    bsl = "";
                }
            }
        }

19 Source : Form1.cs
with MIT License
from 200Tigersbloxed

private void button2_Click(object sender, EventArgs e)
        {
            //Find the Oculus Folder
            RegistryKey rk1s = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
            if (rk1s != null)
            {
                RegistryKey rk2 = rk1s.OpenSubKey("Software");
                if (rk2 != null)
                {
                    RegistryKey rk3 = rk2.OpenSubKey("WOW6432Node");
                    if (rk3 != null)
                    {
                        RegistryKey rk4 = rk3.OpenSubKey("Oculus VR, LLC");
                        if (rk4 != null)
                        {
                            RegistryKey rk5 = rk4.OpenSubKey("Oculus");
                            if(rk5 != null)
                            {
                                RegistryKey rk6 = rk5.OpenSubKey("Config");
                                if(rk6 != null)
                                {
                                    userownsoculus = true;
                                    string phrase = rk6.GetValue("InitialAppLibrary").ToString();
                                    oculusinstallpath = phrase;
                                }
                            }
                        }
                    }
                }
            }

            if (userownsoculus == false)
            {
                MessageBox.Show("Oculus Could not be found!", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                bsl = oculusinstallpath + @"/Software/Software/hyperbolic-magnetism-beat-saber";
                if (Directory.Exists(bsl))
                {
                    if (File.Exists(bsl + @"\Beat Saber.exe"))
                    {
                        if (File.Exists(bsl + @"\IPA.exe"))
                        {
                            textBox1.Text = bsl;
                            pictureBox1.Image = BSMulti_Installer2.Properties.Resources.tick;
                            button4.BackColor = SystemColors.MenuHighlight;
                            allownext = true;
                            runVerifyCheck();
                            findMultiplayerVersion();
                        }
                        else
                        {
                            MessageBox.Show("IPA.exe Could not be found! Is Beat Saber Modded?", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Beat Saber.exe Could not be found! Is Beat Saber Installed?", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Beat Saber Could not be found! Is Beat Saber Installed under Oculus?", "Uh Oh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    bsl = "";
                }
            }
        }

19 Source : dlgSettings.cs
with MIT License
from 86Box

private bool CheckForChanges()
        {
            RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\86Box");

            try
            {
                btnApply.Enabled = (
                    txtEXEdir.Text != regkey.GetValue("EXEdir").ToString() ||
                    txtCFGdir.Text != regkey.GetValue("CFGdir").ToString() ||
                    txtLogPath.Text != regkey.GetValue("LogPath").ToString() ||
                    txtLaunchTimeout.Text != regkey.GetValue("LaunchTimeout").ToString() ||
                    cbxMinimize.Checked != Convert.ToBoolean(regkey.GetValue("MinimizeOnVMStart")) ||
                    cbxShowConsole.Checked != Convert.ToBoolean(regkey.GetValue("ShowConsole")) ||
                    cbxMinimizeTray.Checked != Convert.ToBoolean(regkey.GetValue("MinimizeToTray")) ||
                    cbxCloseTray.Checked != Convert.ToBoolean(regkey.GetValue("CloseToTray")) || 
                    cbxLogging.Checked != Convert.ToBoolean(regkey.GetValue("EnableLogging")) ||
                    cbxGrid.Checked != Convert.ToBoolean(regkey.GetValue("EnableGridLines")));

                return btnApply.Enabled;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
                return true; //For now let's just return true if anything goes wrong
            }
            finally
            {
                regkey.Close();
            }
        }

19 Source : ExportExampleHelper.cs
with MIT License
from ABTSoftware

public static string GetreplacedemblyPathFromRegistry()
        {
            using (var registryKey = Registry.CurrentUser.OpenSubKey(RegistryKeyString))
            {
                if (registryKey != null)
                {
                    var replacedemblyPathFromRegistry = string.Format("{0}{1}", registryKey.GetValue("Path"), @"Lib\net40\");
                    return replacedemblyPathFromRegistry;
                }
            }

            return null;
        }

19 Source : SystemInfo.cs
with MIT License
from Accelerider

private static DotNetFramework Get45PlusFromRegistry()
        {
            const string subKey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";

            using (RegistryKey ndpKey = RegistryKey
                .OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)
                .OpenSubKey(subKey))
            {
                return ndpKey?.GetValue("Release") != null
                    ? CheckFor45PlusVersion((int)ndpKey.GetValue("Release"))
                    : DotNetFramework.Unknown;
            }
        }

19 Source : RegistryHandler.cs
with MIT License
from adrianmteo

public static WindowsTheme GetAppTheme()
        {
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(KeyPath))
            {
                object registryValueObject = key?.GetValue("AppsUseLightTheme");

                if (registryValueObject == null)
                {
                    return WindowsTheme.Light;
                }

                int registryValue = (int)registryValueObject;

                return registryValue > 0 ? WindowsTheme.Light : WindowsTheme.Dark;
            }
        }

19 Source : Model.cs
with MIT License
from advancedmonitoring

private static int CalcKeyCount(RegistryKey key)
        {
            if (_ww.AbortEvent.WaitOne(0))
                return 0;
            string[] keys;
            try
            {
                keys = key.GetSubKeyNames();
            }
            catch
            {
                return 1;
            }
            var c = 1;
            if (_isRecursing)
                foreach (var k in keys)
                    try
                    {
                        c += CalcKeyCount(key.OpenSubKey(k));
                    }
                    catch
                    {
                        c++;
                    }
            return c;
        }

19 Source : Model.cs
with MIT License
from advancedmonitoring

private static void UpdateRegKey(RegistryKey key)
        {
            var localSb = new StringBuilder();
            localSb.AppendLine(key.Name);
            _currentFiles++;
            var sddlString = "Unable obtain SDDL";
            try
            {
                sddlString = key.GetAccessControl().GetSecurityDescriptorSddlForm(AccessControlSections.All);
            }
            catch
            {
                // ignore
            }
            localSb.AppendLine(sddlString);
            _sb.AppendLine(localSb.ToString());
            if (key.SubKeyCount != 0)
                foreach (var sub in key.GetSubKeyNames())
                {
                    try
                    {
                        var oKey = key.OpenSubKey(sub);
                        if (oKey != null)
                            if (_isRecursing)
                                UpdateRegKey(oKey);
                            else
                            {
                                localSb.Clear();
                                localSb.AppendLine(oKey.Name);
                                _currentFiles++;
                                localSb.AppendLine(
                                    oKey.GetAccessControl().GetSecurityDescriptorSddlForm(AccessControlSections.All));
                                _sb.AppendLine(localSb.ToString());
                            }
                    }
                    catch
                    {
                        // ignored
                    }
                    _ww.Percentage = (int) ((_currentFiles + 0.0) * 100.0 / (_maxFiles + 0.0));
                    if (_ww.AbortEvent.WaitOne(0))
                        return;
                }
        }

19 Source : FolderRegPickerWindow.xaml.cs
with MIT License
from advancedmonitoring

private void keyreg_OnExpanded(object sender, RoutedEventArgs e)
        {
            var item = (TreeViewItem)sender;
            try
            {
                if (item.Items.Count == 1 && (item.Items[0] is TreeViewItem) && (string.IsNullOrWhiteSpace((string)((TreeViewItem)item.Items[0]).Header)))
                {
                    EdtPath.Text = item.Tag.ToString().Trim();
                    item.Items.Clear();
                    try
                    {
                        RegistryKey rk = GetKeyFromString(item.Tag.ToString());
                        foreach (string s in rk.GetSubKeyNames())
                        {
                            TreeViewItem subitem = new TreeViewItem
                            {
                                Header = s,
                                Tag = item.Tag + "\\" + s
                            };
                            try
                            {
                                var oSubKey = rk.OpenSubKey(s);
                                if (oSubKey != null && oSubKey.SubKeyCount != 0)
                                    subitem.Items.Add(new TreeViewItem { Header = "" });
                            }
                            catch { /* ignore */ }
                            subitem.Expanded += keyreg_OnExpanded;
                            subitem.Selected += element_OnSelected;
                            item.Items.Add(subitem);
                        }
                    }
                    catch { /* ignore */ }
                }
            }
            catch { /* ignore */ }
        }

19 Source : FolderRegPickerWindow.xaml.cs
with MIT License
from advancedmonitoring

public static RegistryKey GetKeyFromString(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
                return null;
            path = path.Trim();
            if (path[path.Length - 1] == '\\')
                path = path.Substring(0, path.Length - 1);
            var index = path.IndexOf('\\');
            var start = (index == -1) ? path : path.Substring(0, index);
            RegistryKey rv;
            switch (start.ToUpperInvariant())
            {
                case "HKEY_CLreplacedES_ROOT":
                case "HKCR":
                    rv = Registry.ClreplacedesRoot;
                    break;

                case "HKEY_CURRENT_USER":
                case "HKCU":
                    rv = Registry.CurrentUser;
                    break;

                case "HKEY_LOCAL_MACHINE":
                case "HKLM":
                    rv = Registry.LocalMachine;
                    break;

                case "HKEY_USERS":
                case "HKU":
                    rv = Registry.Users;
                    break;

                case "HKEY_CURRENT_CONFIG":
                    rv = Registry.CurrentConfig;
                    break;

                default:
                    return null;
            }
            if (index == -1)
            {
                return rv;
            }
            try
            {
                path = path.Substring(index + 1);
                return rv.OpenSubKey(path);
            }
            catch
            {
                return null;
            }
        }

19 Source : SystemInformation.cs
with MIT License
from afxw

private static string GetProductName()
        {
            var key = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
            return Registry.LocalMachine.OpenSubKey(key).GetValue("ProductName").ToString();
        }

19 Source : RegistryHelper.cs
with Mozilla Public License 2.0
from agebullhu

public static RegistryKey GetQFErpRootKey()
        {
            using (var root = RegistryKey.OpenBaseKey(RegistryHive.CurrentConfig, RegistryView.Default))
            {
                var r = root.OpenSubKey("上海秦奋网络科技有限公司") ?? root.CreateSubKey("上海秦奋网络科技有限公司");
                if (r != null)
                {
                    return r.OpenSubKey("清风企业智能管理系统") ?? root.CreateSubKey("清风企业智能管理系统");
                }
            }
            return null;
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

void IsGameInstalled()
        {
            string lePath = Path.Combine(ProgramFilesx86(), @"Steam\" + gameMode.GetValue("c_exeDirectory") + @"\" + gameMode.GetValue("c_exe") + ".exe");
            TryPath(lePath);
            if (!gameFound)
            {
                RegistryKey steamSubKey = Registry.CurrentUser.OpenSubKey(@"Software\Valve\Steam\Apps\" + gameMode.GetValue("c_gameID"));
                if (steamSubKey != null)
                {
                    object installed = steamSubKey.GetValue("Installed");
                    if (installed != null && Convert.ToInt32(installed) > 0)
                    {
                        gameFound = true;
                    }
                }
            }
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

void IsGameInstalled()
        {
            string lePath = Path.Combine(ProgramFilesx86(), @"Steam\" + gameMode.GetValue("c_exeDirectory") + @"\" + gameMode.GetValue("c_exe") + ".exe");
            TryPath(lePath);
            if (!gameFound)
            {
                RegistryKey steamSubKey = Registry.CurrentUser.OpenSubKey(@"Software\Valve\Steam");
                if (steamSubKey != null)
                {
                    object steamPath = steamSubKey.GetValue("SteamPath");
                    if (steamPath != null && !String.IsNullOrEmpty(steamPath.ToString()))
                    {
                        lePath = Path.Combine(steamPath.ToString(), gameMode.GetValue("c_exeDirectory") + @"\" + gameMode.GetValue("c_exe") + ".exe");
                        TryPath(lePath);
                    }
                }
            }
        }

19 Source : DataProtectionBuilderExtentions.cs
with Apache License 2.0
from Aguafrommars

public static IDataProtectionBuilder ConfigureDataProtection(this IDataProtectionBuilder builder, IConfiguration configuration)
        {
            var dataProtectionsOptions = configuration.Get<Aguacongas.TheIdServer.Models.DataProtectionOptions>();
            if (dataProtectionsOptions == null)
            {
                return builder;
            }
            builder.AddKeyManagementOptions(options => configuration.GetSection(nameof(KeyManagementOptions))?.Bind(options));
            ConfigureEncryptionAlgorithm(builder, configuration);
            switch (dataProtectionsOptions.StorageKind)
            {
                case StorageKind.AzureStorage:
                    builder.PersistKeysToAzureBlobStorage(blobSasUri: new Uri(dataProtectionsOptions.StorageConnectionString));
                    break;
                case StorageKind.EnreplacedyFramework:
                    builder.PersistKeysToDbContext<OperationalDbContext>();
                    break;
                case StorageKind.RavenDb:
                    builder.PersistKeysToRavenDb();
                    break;
                case StorageKind.MongoDb:
                    builder.PersistKeysToMongoDb();
                    break;
                case StorageKind.FileSystem:
                    builder.PersistKeysToFileSystem(new DirectoryInfo(dataProtectionsOptions.StorageConnectionString));
                    break;
                case StorageKind.Redis:
                    var redis = ConnectionMultiplexer.Connect(dataProtectionsOptions.StorageConnectionString);
                    if (string.IsNullOrEmpty(dataProtectionsOptions.RedisKey))
                    {
                        builder.PersistKeysToStackExchangeRedis(redis);
                        break;
                    }
                    builder.PersistKeysToStackExchangeRedis(redis, dataProtectionsOptions.RedisKey);
                    break;
                case StorageKind.Registry:
#pragma warning disable CA1416 // Validate platform compatibility
                    builder.PersistKeysToRegistry(Registry.CurrentUser.OpenSubKey(dataProtectionsOptions.StorageConnectionString));
#pragma warning restore CA1416 // Validate platform compatibility
                    break;
            }
            var protectOptions = dataProtectionsOptions.KeyProtectionOptions;
            if (protectOptions != null)
            {
                switch (protectOptions.KeyProtectionKind)
                {
                    case KeyProtectionKind.AzureKeyVault:
                        builder.ProtectKeysWithAzureKeyVault(new Uri(protectOptions.AzureKeyVaultKeyId), new DefaultAzureCredential());
                        break;
                    case KeyProtectionKind.WindowsDpApi:
                        builder.ProtectKeysWithDpapi(protectOptions.WindowsDPAPILocalMachine);
                        break;
                    case KeyProtectionKind.WindowsDpApiNg:
                        ConfigureWindowsDpApiNg(builder, protectOptions);
                        break;
                    case KeyProtectionKind.X509:
                        if (!string.IsNullOrEmpty(protectOptions.X509CertificatePath))
                        {
                            var certificate = SigningKeysLoader.LoadFromFile(protectOptions.X509CertificatePath, protectOptions.X509CertificatePreplacedword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserKeySet);
                            builder.ProtectKeysWithCertificate(certificate);
                            break;
                        }
                        builder.ProtectKeysWithCertificate(protectOptions.X509CertificateThumbprint);
                        break;
                }
            }

            return builder;
        }

19 Source : ExternalEditor.cs
with GNU General Public License v3.0
from ahmed605

public bool SupportsExtension(string extension)
        {
            try
            {
                var key = Registry.ClreplacedesRoot.OpenSubKey("." + extension);
                
                if (key == null) 
                {
                    return false;
                }
                
                var defaultValue = key.GetValue("").ToString();
                
                if (defaultValue == null)
                {
                    return false;
                }

                var shellOpenKey = Registry.ClreplacedesRoot.OpenSubKey(defaultValue + @"\shell\open");

                return shellOpenKey != null;
            }
            catch
            {
                return false;
            }
        }

19 Source : KeyUtil.cs
with GNU General Public License v3.0
from ahmed605

public string FindGameDirectory()
        {

            if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), ExecutableName)))
            {
                dir = Directory.GetCurrentDirectory();
            }
            else
            {
                if (ExecutableName == "GTAIV.exe" && File.Exists(@"path.iv") && !StringExtensions.IsNullOrWhiteSpace(File.ReadAllText(@"path.iv")) && File.Exists(Path.Combine(File.ReadAllText(@"path.iv"), ExecutableName)))
                {
                    dir = File.ReadAllText(@"path.iv");
                }
                else
                {
                    if (ExecutableName == "EFLC.exe" && File.Exists(@"path.eflc") && !StringExtensions.IsNullOrWhiteSpace(File.ReadAllText(@"path.eflc")) && File.Exists(Path.Combine(File.ReadAllText(@"path.eflc"), ExecutableName)))
                    {
                        dir = File.ReadAllText(@"path.eflc");
                    }
                    else
                    {
                        var keys = PathRegistryKeys;
                        foreach (var s in keys)
                        {
                            RegistryKey key;
                            if ((key = Registry.LocalMachine.OpenSubKey(s)) != null)
                            {
                                if (key.GetValue("InstallFolder") != null && File.Exists(Path.Combine(key.GetValue("InstallFolder").ToString(), ExecutableName)))
                                {
                                    dir = key.GetValue("InstallFolder").ToString();
                                    key.Close();
                                    break;
                                }
                                else
                                {
                                    var fbd = new VistaFolderBrowserDialog();
                                    fbd.Description = "Select game folder";
                                    //DialogResult result = fbd.ShowDialog();
                                    if (fbd.ShowDialog() == DialogResult.OK && !StringExtensions.IsNullOrWhiteSpace(fbd.SelectedPath))
                                    {
                                        dir = fbd.SelectedPath;
                                        break;
                                    }
                                    else
                                    {
                                        MessageBox.Show("Please select game folder.");
                                        Application.Exit();
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return dir;
        }

19 Source : MainWindow.xaml.cs
with GNU Affero General Public License v3.0
from aianlinb

private async void OnLoaded(object sender, RoutedEventArgs e) {
            if (SteamMode)
                replacedle += " (SteamMode)";
            if (BundleMode)
                replacedle += " (SteamMode)";
            // Version Check
            try {
                var http = new HttpClient {
                    Timeout = TimeSpan.FromSeconds(2)
                };
                http.DefaultRequestHeaders.Add("User-Agent", "VisualGGPK2");
                var json = await http.GetStringAsync("https://api.github.com/repos/aianlinb/LibGGPK2/releases");
                var match = Regex.Match(json, "(?<=\"tag_name\":\"v).*?(?=\")");
                var currentVersion = replacedembly.GetEntryreplacedembly().GetName().Version;
                var versionText = $"{currentVersion.Major}.{currentVersion.Minor}.{currentVersion.Build}";
                if (match.Success && match.Value != versionText && MessageBox.Show(this, $"Found a new update on GitHub!\n\nCurrent Version: {versionText}\nLatest Version: {match.Value}\n\nDownload now?", "VisualGGPK2", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) {
                    Process.Start(new ProcessStartInfo("https://github.com/aianlinb/LibGGPK2/releases") { UseShellExecute = true });
                    Close();
                    return;
                }
                http.Dispose();
            } catch { }

            // GGPK Selection
            if (FilePath == null) {
                var ofd = new OpenFileDialog {
                    DefaultExt = "ggpk",
                    FileName = SteamMode ? "_.index.bin" : "Content.ggpk",
                    Filter = SteamMode ? "Index Bundle File|*.index.bin" : "GGPK File|*.ggpk"
                };

                var setting = Properties.Settings.Default;
                if (setting.GGPKPath == "") {
                    setting.Upgrade();
                    setting.Save();
                }
                if (setting.GGPKPath == "") {
                    string path;
                    path = Registry.CurrentUser.OpenSubKey(@"Software\GrindingGearGames\Path of Exile")?.GetValue("InstallLocation") as string;
                    if (path != null && File.Exists(path + @"\Content.ggpk")) // Get POE path
                        ofd.InitialDirectory = path.TrimEnd('\\');
                } else
                    ofd.InitialDirectory = setting.GGPKPath;

                if (ofd.ShowDialog() == true) {
                    setting.GGPKPath = Directory.GetParent(FilePath = ofd.FileName).FullName;
                    setting.Save();
                } else {
                    Close();
                    return;
                }
            }

            // Initial GGPK
            await Task.Run(() => ggpkContainer = new GGPKContainer(FilePath, BundleMode, SteamMode));
            
            // Initial ContextMenu
            var mi = new MenuItem { Header = "Export" };
            mi.Click += OnExportClicked;
            TreeMenu.Items.Add(mi);
            mi = new MenuItem { Header = "Replace" };
            mi.Click += OnReplaceClicked;
            TreeMenu.Items.Add(mi);
            mi = new MenuItem { Header = "Recovery" };
            mi.Click += OnRecoveryClicked;
            TreeMenu.Items.Add(mi);
            mi = new MenuItem { Header = "Convert dds to png" };
            mi.Click += OnSavePngClicked;
            TreeMenu.Items.Add(mi);

            var imageMenu = new ContextMenu();
            mi = new MenuItem { Header = "Save as png" };
            mi.Click += OnSavePngClicked;
            imageMenu.Items.Add(mi);
            ImageView.ContextMenu = imageMenu;

            var root = CreateNode(ggpkContainer.rootDirectory);
            Tree.Items.Add(root); // Initial TreeView
            root.IsExpanded = true;

            FilterButton.IsEnabled = true;
            if (!SteamMode)
                AllowGameOpen.IsEnabled = true;

            // Mark the free spaces in data section of dat files
            DatReferenceDataTable.CellStyle = new Style(typeof(DataGridCell));
            DatReferenceDataTable.CellStyle.Setters.Add(new EventSetter(LoadedEvent, new RoutedEventHandler(OnCellLoaded)));

            // Make changes to DatContainer after editing DatTable
            DatTable.CellEditEnding += OnDatTableCellEdit;
            // Make changes to DatContainer after editing DatReferenceDataTable
            DatReferenceDataTable.CellEditEnding += OnDatReferenceDataTableCellEdit;

            TextView.AppendText("\r\n\r\nDone!\r\n");
        }

19 Source : ScriptAssetOpener.cs
with MIT License
from akof1314

private static string LuaExecutablePath()
        {
            using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.lua\\UserChoice"))
            {
                if (registryKey != null)
                {
                    string val = registryKey.GetValue("Progid") as string;
                    if (!string.IsNullOrEmpty(val))
                    {
                        val = "Software\\Clreplacedes\\" + val + "\\shell\\open\\command";
                        using (RegistryKey registryKey2 = Registry.CurrentUser.OpenSubKey(val))
                        {
                            string val3 = LuaExecutablePathInter(registryKey2);
                            if (!string.IsNullOrEmpty(val3))
                            {
                                return val3;
                            }
                        }
                    }
                }
            }

            using (RegistryKey registryKey = Registry.ClreplacedesRoot.OpenSubKey(".lua"))
            {
                if (registryKey != null)
                {
                    string val = registryKey.GetValue(null) as string;
                    if (val != null)
                    {
                        val += "\\shell\\open\\command";
                        using (RegistryKey registryKey2 = Registry.ClreplacedesRoot.OpenSubKey(val))
                        {
                            string val3 = LuaExecutablePathInter(registryKey2);
                            if (!string.IsNullOrEmpty(val3))
                            {
                                return val3;
                            }
                        }
                    }
                }
            }
            return String.Empty;
        }

19 Source : ActionMods.cs
with MIT License
from AlbertMN

private static string GetPythonPath(string requiredVersion = "", string maxVersion = "") {
            string[] possiblePythonLocations = new string[3] {
                @"HKLM\SOFTWARE\Python\PythonCore\",
                @"HKCU\SOFTWARE\Python\PythonCore\",
                @"HKLM\SOFTWARE\Wow6432Node\Python\PythonCore\"
            };
            //Version number, install path
            Dictionary<string, string> pythonLocations = new Dictionary<string, string>();

            foreach (string possibleLocation in possiblePythonLocations) {
                string regKey = possibleLocation.Substring(0, 4), actualPath = possibleLocation.Substring(5);
                RegistryKey theKey = (regKey == "HKLM" ? Registry.LocalMachine : Registry.CurrentUser);
                RegistryKey theValue = theKey.OpenSubKey(actualPath);

                foreach (var v in theValue.GetSubKeyNames()) {
                    RegistryKey productKey = theValue.OpenSubKey(v);
                    if (productKey != null) {
                        try {
                            string pythonExePath = productKey.OpenSubKey("InstallPath").GetValue("ExecutablePath").ToString();
                            if (pythonExePath != null && pythonExePath != "") {
                                //Console.WriteLine("Got python version; " + v + " at path; " + pythonExePath);
                                pythonLocations.Add(v.ToString(), pythonExePath);
                            }
                        } catch {
                            //Install path doesn't exist
                        }
                    }
                }
            }

            if (pythonLocations.Count > 0) {
                System.Version desiredVersion = new System.Version(requiredVersion == "" ? "0.0.1" : requiredVersion),
                    maxPVersion = new System.Version(maxVersion == "" ? "999.999.999" : maxVersion);

                string highestVersion = "", highestVersionPath = "";

                foreach (KeyValuePair<string, string> pVersion in pythonLocations) {
                    //TODO; if on 64-bit machine, prefer the 64 bit version over 32 and vice versa
                    int index = pVersion.Key.IndexOf("-"); //For x-32 and x-64 in version numbers
                    string formattedVersion = index > 0 ? pVersion.Key.Substring(0, index) : pVersion.Key;

                    System.Version thisVersion = new System.Version(formattedVersion);
                    int comparison = desiredVersion.CompareTo(thisVersion),
                        maxComparison = maxPVersion.CompareTo(thisVersion);

                    if (comparison <= 0) {
                        //Version is greater or equal
                        if (maxComparison >= 0) {
                            desiredVersion = thisVersion;

                            highestVersion = pVersion.Key;
                            highestVersionPath = pVersion.Value;
                        } else {
                            //Console.WriteLine("Version is too high; " + maxComparison.ToString());
                        }
                    } else {
                        //Console.WriteLine("Version (" + pVersion.Key + ") is not within the spectrum.");
                    }
                }

                return highestVersionPath;
            }

            return "";
        }

19 Source : CloudServiceFunctions.cs
with MIT License
from AlbertMN

public static string GetGoogleDriveFolder() {
            //New Google Drive check first
            string registryKey = @"Software\Google\DriveFS";
            RegistryKey key = Registry.CurrentUser.OpenSubKey(registryKey);

            if (key != null || Directory.Exists(Environment.ExpandEnvironmentVariables("%programfiles%") + @"\Google\Drive File Stream")) {
                //New google Drive seems to be installed
                DriveInfo[] allDrives = DriveInfo.GetDrives();

                //Check if it's a virual drive
                foreach (DriveInfo d in allDrives) {
                    if (d.VolumeLabel == "Google Drive") {
                        string check = Path.Combine(d.Name, "My Drive");
                        if (Directory.Exists(check)) {
                            return check;
                        }
                    }
                }

                //Not a virtual drive, check the user's folder
                string userDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                if (Directory.Exists(userDir)) {
                    foreach (string dir in Directory.GetDirectories(userDir)) {
                        if (dir.Contains("My Drive")) {
                            //Pretty sure it's Google Drive... But bad practice maybe...?
                            return dir;
                        }
                    }
                }


                return "partial";
            }

            //No? Check the old one
            registryKey = @"Software\Google\Drive";
            key = Registry.CurrentUser.OpenSubKey(registryKey);
            if (key != null) {
                string installed = key.GetValue("Installed").ToString();
                key.Close();
                if (installed != null) {
                    if (installed == "True") {
                        string checkPath = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Google Drive");
                        if (Directory.Exists(checkPath)) {
                            return checkPath;
                        }
                        return "partial";
                    }
                }
            }
            return "";
        }

19 Source : MainProgram.cs
with MIT License
from AlbertMN

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args) {
            Exception e = (Exception)args.ExceptionObject;
            string errorLogLoc = Path.Combine(dataFolderLocation, "error_log.txt");

            string subKey = @"SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion";
            RegistryKey thekey = Registry.LocalMachine;
            RegistryKey skey = thekey.OpenSubKey(subKey);

            string windowsVersionName = skey.GetValue("ProductName").ToString();
            string rawWindowsVersion = Environment.OSVersion.ToString();

            int totalExecutions = 0;
            foreach (int action in Properties.Settings.Default.TotalActionsExecuted) {
                totalExecutions += action;
            }
            if (File.Exists(errorLogLoc))
                try {
                    File.Delete(errorLogLoc);
                } catch {
                    DoDebug("Failed to delete error log");
                }

            if (!File.Exists(errorLogLoc)) {
                try {
                    using (var tw = new StreamWriter(errorLogLoc, true)) {
                        tw.WriteLine("OS;");
                        tw.WriteLine("- " + windowsVersionName);
                        tw.WriteLine("- " + rawWindowsVersion);
                        tw.WriteLine();
                        tw.WriteLine("ACC info;");
                        tw.WriteLine("- Version; " + softwareVersion + ", " + releaseDate);
                        tw.WriteLine("- UID; " + Properties.Settings.Default.UID);
                        tw.WriteLine("- Running from; " + currentLocationFull);
                        tw.WriteLine("- Start with Windows; " + (ACCStartsWithWindows() ? "[Yes]" : "[No]"));
                        tw.WriteLine("- Check for updates; " + (Properties.Settings.Default.CheckForUpdates ? "[Yes]" : "[No]"));
                        tw.WriteLine("- In beta program; " + (Properties.Settings.Default.BetaProgram ? "[Yes]" : "[No]"));
                        tw.WriteLine("- Has completed setup guide; " + (Properties.Settings.Default.HasCompletedTutorial ? "[Yes]" : "[No]"));
                        tw.WriteLine("- Check path; " + CheckPath());
                        tw.WriteLine("- Check extension; " + Properties.Settings.Default.ActionFileExtension);
                        tw.WriteLine("- Actions executed; " + totalExecutions);
                        tw.WriteLine("- replacedistant type; " + "[Google replacedistant: " + Properties.Settings.Default.replacedistantType[0] + "] [Alexa: " + Properties.Settings.Default.replacedistantType[1] + "] [Unknown: " + Properties.Settings.Default.replacedistantType[1] + "]");
                        tw.WriteLine();

                        tw.WriteLine(e);
                        tw.Close();
                    }
                } catch {
                    //Caught exception when trying to log exception... *sigh*
                }
            }

            File.AppendAllText(errorLogLoc, DateTime.Now.ToString() + ": " + e + Environment.NewLine);
            if (debug) {
                Console.WriteLine(e);
            }
            MessageBox.Show("A critical error occurred. The developer has been notified and will resolve this issue ASAP! Try and start ACC again, and avoid whatever just made it crash (for now) :)", "ACC | Error");
        }

19 Source : MainProgram.cs
with MIT License
from AlbertMN

public static bool ApplicationInstalled(string c_name) {
            string displayName;

            string registryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey);
            if (key != null) {
                foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName))) {
                    displayName = subkey.GetValue("DisplayName") as string;
                    if (displayName != null && displayName.Contains(c_name)) {
                        return true;
                    }
                }
                key.Close();
            }

            registryKey = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
            key = Registry.LocalMachine.OpenSubKey(registryKey);
            if (key != null) {
                foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName))) {
                    displayName = subkey.GetValue("DisplayName") as string;
                    if (displayName != null && displayName.Contains(c_name)) {
                        return true;
                    }
                }
                key.Close();
            }
            return false;
        }

19 Source : SystemUtils.cs
with MIT License
from AlexanderPro

public static string GetDefaultBrowserModuleName()
        {
            var browserName = "iexplore.exe";
            using (var userChoiceKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\Shell\\replacedociations\\Urlreplacedociations\\http\\UserChoice"))
            {
                if (userChoiceKey == null)
                {
                    return browserName;
                }

                var progIdValue = userChoiceKey.GetValue("Progid");
                if (progIdValue == null)
                {
                    return browserName;
                }

                var progId = progIdValue.ToString();
                var path = progId + "\\shell\\open\\command";
                using (var pathKey = Registry.ClreplacedesRoot.OpenSubKey(path))
                {
                    if (pathKey == null)
                    {
                        return browserName;
                    }

                    try
                    {
                        path = pathKey.GetValue(null).ToString().ToLower().Replace("\"", "");
                        const string exeSuffix = ".exe";
                        if (!path.EndsWith(exeSuffix))
                        {
                            path = path.Substring(0, path.LastIndexOf(exeSuffix, StringComparison.Ordinal) + exeSuffix.Length);
                        }
                        return path;
                    }
                    catch
                    {
                        return browserName;
                    }
                }
            }
        }

19 Source : AutoStarter.cs
with MIT License
from AlexanderPro

public static bool IsAutoStartByRegisterEnabled(string keyName, string replacedemblyLocation)
        {
            using (var key = Registry.CurrentUser.OpenSubKey(RUN_LOCATION))
            {
                if (key == null) return false;
                var value = (string)key.GetValue(keyName);
                if (string.IsNullOrEmpty(value)) return false;
                var result = (value == replacedemblyLocation);
                return result;
            }
        }

19 Source : HeatmasterGroup.cs
with MIT License
from AlexGyver

private static string[] GetRegistryPortNames() {
      List<string> result = new List<string>();
      string[] paths = { "", "&MI_00" };
      try {
        foreach (string path in paths) {
          RegistryKey key = Registry.LocalMachine.OpenSubKey(
            @"SYSTEM\CurrentControlSet\Enum\USB\VID_10C4&PID_EA60" + path);
          if (key != null) {
            foreach (string subKeyName in key.GetSubKeyNames()) {
              RegistryKey subKey =
                key.OpenSubKey(subKeyName + "\\" + "Device Parameters");
              if (subKey != null) {
                string name = subKey.GetValue("PortName") as string;
                if (name != null && !result.Contains(name))
                  result.Add(name);
              }
            }
          }
        }
      } catch (SecurityException) { }
      return result.ToArray();
    }

19 Source : MainWindow.xaml.cs
with Apache License 2.0
from AlexWan

private bool CheckDotNetVersion()
        {
            using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
            {
                if (ndpKey == null)
                {
                    return false;
                }
                int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release"));

                if (releaseKey >= 393295)
                {
                    //"4.6 or later";
                    return true;
                }
                if ((releaseKey >= 379893))
                {
                    //"4.5.2 or later";
                    return true;
                }
                if ((releaseKey >= 378675))
                {
                    //"4.5.1 or later";
                    return true;
                }
                if ((releaseKey >= 378389))
                {
                    MessageBox.Show(OsLocalization.MainWindow.Message4);
                    return false;
                }

                MessageBox.Show(OsLocalization.MainWindow.Message4);

                return false;
            }
        }

19 Source : PulseLogPrivesc.cs
with Apache License 2.0
from AlmondOffSec

public static string GetPulseCommandLineFromRegistry(string regKey, string value)
        {
            try
            {
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(regKey))
                {
                    if (key != null)
                    {
                        Object o = key.GetValue(value);
                        if (o != null) {
                            string v = o as String;
                            return v.Remove(v.IndexOf(PulseRunArg)).Trim();
                        }
                    }
                }
            }
            catch {}
            return null;
        }

19 Source : RegistryConfig.cs
with GNU General Public License v3.0
from aloopkin

public bool isThereConfigParam(string startsWith)
        {
            foreach (string key in Registry.LocalMachine.OpenSubKey(_subKey).GetValueNames())
            {
                if (key.StartsWith(startsWith))
                    return true;
            }
            return false;
        }

19 Source : RegistryConfig.cs
with GNU General Public License v3.0
from aloopkin

public void DeleteAllParameters()
        {
            if (Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("WinCertes").OpenSubKey("extra") != null)
            {
                Registry.LocalMachine.OpenSubKey(_subKey, true).DeleteSubKeyTree("extra");
            }
            for (int i = 2; i < 10; i++)
            {
                if (Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("WinCertes").OpenSubKey("extra" + i) != null)
                    Registry.LocalMachine.OpenSubKey(_subKey, true).DeleteSubKeyTree("extra" + i);
            }
            foreach (string key in Registry.LocalMachine.OpenSubKey(_subKey).GetValueNames())
            {
                DeleteParameter(key);
            }
        }

19 Source : EpicGameFinder.cs
with MIT License
from amazingalek

public override string FindGamePath()
		{
			var key = Registry.LocalMachine.OpenSubKey(RegistryPath);
			var appDataPath = (string)key?.GetValue(RegistryName);
			if (string.IsNullOrEmpty(appDataPath))
			{
				Writer.WriteLine("EGS not found in Registry.");
				return null;
			}

			var manifestsPath = $"{appDataPath}{ManifestsFolder}";
			if (!Directory.Exists(manifestsPath))
			{
				Writer.WriteLine($"EGS manifests folder not found: {manifestsPath}");
				return null;
			}

			var manifestPaths = Directory.GetFiles(manifestsPath, ManifestPattern, SearchOption.TopDirectoryOnly);
			foreach (var manifestPath in manifestPaths)
			{
				var json = File.ReadAllText(manifestPath);
				var epicManifest = JsonConvert.DeserializeObject<EpicManifest>(json);
				if (epicManifest.InstallLocation.Contains(ManifestGameName) && IsValidGamePath(epicManifest.InstallLocation))
				{
					return epicManifest.InstallLocation;
				}
			}

			Writer.WriteLine("Game not found in EGS.");
			return null;
		}

19 Source : HTTPController.cs
with MIT License
from AmazingDM

private void RecordPrevious()
        {
            try
            {
                var registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings");
                if (registry == null)
                    throw new Exception();

                prevPAC = registry.GetValue("AutoConfigURL")?.ToString() ?? "";
                prevHTTP = registry.GetValue("ProxyServer")?.ToString() ?? "";
                prevBypreplaced = registry.GetValue("ProxyOverride")?.ToString() ?? "";
                prevEnabled = registry.GetValue("ProxyEnable")?.Equals(1) ?? false; // HTTP Proxy Enabled

                if (prevHTTP == $"127.0.0.1:{Global.Settings.HTTPLocalPort}")
                {
                    prevEnabled = false;
                    prevHTTP = "";
                }

                if (prevPAC != "")
                    prevEnabled = true;
            }
            catch
            {
                prevEnabled = false;
                prevPAC = prevHTTP = prevBypreplaced = "";
            }
        }

19 Source : TUNTAP.cs
with MIT License
from AmazingDM

public static string GetComponentID()
        {
            try
            {
                var adaptersRegistry = Registry.LocalMachine.OpenSubKey(ADAPTER_KEY);

                foreach (var adapterRegistryName in adaptersRegistry.GetSubKeyNames())
                {
                    if (adapterRegistryName != "Configuration" && adapterRegistryName != "Properties")
                    {
                        var adapterRegistry = adaptersRegistry.OpenSubKey(adapterRegistryName);

                        var adapterComponentId = adapterRegistry.GetValue("ComponentId", "").ToString();
                        if (adapterComponentId == TUNTAP_COMPONENT_ID_0901 || adapterComponentId == TUNTAP_COMPONENT_ID_0801)
                        {
                            return adapterRegistry.GetValue("NetCfgInstanceId", "").ToString();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logging.Warning(e.ToString());
            }

            return "";
        }

19 Source : SteamGameFinder.cs
with MIT License
from amazingalek

public override string FindGamePath()
		{
			var key = Registry.CurrentUser.OpenSubKey(RegistryPath);
			var steamPath = (string)key?.GetValue(RegistryName);
			if (string.IsNullOrEmpty(steamPath))
			{
				Writer.WriteLine("Steam not found in Registry.");
				return null;
			}

			var defaultLocation = $"{steamPath}/{GameLocation}";
			if (IsValidGamePath(defaultLocation))
			{
				return defaultLocation;
			}

			var libraryFoldersFile = $"{steamPath}/{LibraryFoldersPath}";
			if (!File.Exists(libraryFoldersFile))
			{
				Writer.WriteLine($"Steam library folders file not found: {libraryFoldersFile}");
				return null;
			}

			var libraryFoldersContent = File.ReadAllText(libraryFoldersFile);
			var libraryFoldersVdf = VdfConvert.Deserialize(libraryFoldersContent);
			for (var i = 0; i < MaxLibraryCount; i++)
			{
				var libraryName = i.ToString();

				var libraryBlock = libraryFoldersVdf.Value[libraryName];

				if (libraryBlock is null)
				{
					continue;
				}

				var token = libraryBlock.Children().First().ToString();
				var libraryPath = token.Substring(8, token.Length - 9);
				if (string.IsNullOrEmpty(libraryPath))
				{
					continue;
				}

				var gamePath = $"{libraryPath}/{GameLocation}";
				if (IsValidGamePath(gamePath))
				{
					return gamePath;
				}
			}

			Writer.WriteLine("Game not found in Steam.");
			return null;
		}

19 Source : TUNTAP.cs
with MIT License
from AmazingDM

public static string GetName(string componentId)
        {
            var registry = Registry.LocalMachine.OpenSubKey($"{NETWORK_KEY}\\{componentId}\\Connection");

            return registry.GetValue("Name", "").ToString();
        }

19 Source : SelfUpdatePromptPage.cs
with GNU General Public License v3.0
from Amebis

public void CheckForUpdates()
        {
            try
            {
                Parallel.ForEach(new List<Action>()
                    {
                        () =>
                        {
                            // Get self-update.
                            var res = Properties.SettingsEx.Default.SelfUpdateDiscovery;
                            Trace.TraceInformation("Downloading self-update JSON discovery from {0}...", res.Uri.AbsoluteUri);
                            var obj = Properties.Settings.Default.ResponseCache.GetSeq(res, Window.Abort.Token);

                            var repoVersion = new Version((string)obj["version"]);
                            Trace.TraceInformation("Online version: {0}", repoVersion.ToString());
                            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
                                AvailableVersion = repoVersion;
                                Changelog = eduJSON.Parser.GetValue(obj, "changelog_uri", out string changelogUri) ? new Uri(changelogUri) : null;
                                Wizard.SelfUpdateProgressPage.DownloadUris = new List<Uri>(((List<object>)obj["uri"]).Select(uri => new Uri(res.Uri, (string)uri)));
                                Wizard.SelfUpdateProgressPage.Hash = ((string)obj["hash-sha256"]).FromHexToBin();
                                Wizard.SelfUpdateProgressPage.Arguments = eduJSON.Parser.GetValue(obj, "arguments", out string installerArguments) ? installerArguments : null;
                            }));
                        },

                        () =>
                        {
                            // Evaluate installed products.
                            Version productVersion = null;
                            var productId = Properties.Settings.Default.SelfUpdateBundleId.ToUpperInvariant();
                            Trace.TraceInformation("Evaluating installed products...");
                            using (var hklmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
                            using (var uninstallKey = hklmKey.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", false))
                            {
                                foreach (var productKeyName in uninstallKey.GetSubKeyNames())
                                {
                                    Window.Abort.Token.ThrowIfCancellationRequested();
                                    using (var productKey = uninstallKey.OpenSubKey(productKeyName))
                                    {
                                        var bundleUpgradeCode = productKey.GetValue("BundleUpgradeCode");
                                        if ((bundleUpgradeCode is string   bundleUpgradeCodeString && bundleUpgradeCodeString.ToUpperInvariant() == productId ||
                                                bundleUpgradeCode is string[] bundleUpgradeCodeArray  && bundleUpgradeCodeArray.FirstOrDefault(code => code.ToUpperInvariant() == productId) != null) &&
                                            productKey.GetValue("BundleVersion") is string bundleVersionString)
                                        {
                                            // Our product entry found.
                                            productVersion = new Version(productKey.GetValue("DisplayVersion") is string displayVersionString ? displayVersionString : bundleVersionString);
                                            Trace.TraceInformation("Installed version: {0}", productVersion.ToString());
                                            break;
                                        }
                                    }
                                }
                            }
                            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { InstalledVersion = productVersion; }));
                        },
                    },
                    action =>
                    {
                        Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
                        try { action(); }
                        finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--)); }
                    });
            }
            catch (AggregateException ex)
            {
                var nonCancelledException = ex.InnerExceptions.Where(innerException => !(innerException is OperationCanceledException));
                if (nonCancelledException.Any())
                    throw new AggregateException(Resources.Strings.ErrorSelfUpdateDetection, nonCancelledException.ToArray());
                throw new OperationCanceledException();
            }

            //// Mock the values for testing.
            //InstalledVersion = new Version(1, 0);
            //Properties.Settings.Default.SelfUpdateLastReminder = DateTime.MinValue;

            try
            {
                if (new Version(Properties.Settings.Default.SelfUpdateLastVersion) == AvailableVersion &&
                    (Properties.Settings.Default.SelfUpdateLastReminder == DateTime.MaxValue ||
                    (DateTime.UtcNow - Properties.Settings.Default.SelfUpdateLastReminder).TotalDays < 3))
                {
                    // We already prompted user for this version.
                    // Either user opted not to be reminded of this version update again,
                    // or it has been less than three days since the last prompt.
                    Trace.TraceInformation("Update deferred by user choice.");
                    return;
                }
            }
            catch { }

            if (InstalledVersion == null)
            {
                // Nothing to update.
                Trace.TraceInformation("Product not installed or version could not be determined.");
                return; // Quit self-updating.
            }

            if (AvailableVersion <= InstalledVersion)
            {
                // Product already up-to-date.
                Trace.TraceInformation("Update not required.");
                return;
            }

            // We're in the background thread - raise the prompt event via dispatcher.
            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
            {
                if (Wizard.NavigateTo.CanExecute(this))
                {
                    Properties.Settings.Default.SelfUpdateLastVersion = AvailableVersion.ToString();
                    Properties.Settings.Default.SelfUpdateLastReminder = DateTime.UtcNow;
                    Wizard.NavigateTo.Execute(this);
                }
            }));
        }

19 Source : CheckForUpdates.cs
with Apache License 2.0
from AmpScm

public override void OnExecute(CommandEventArgs e)
        {
            if (e.Argument != null)
            {
                ShowUpdate(e);
                return;
            }

            int interval = 24 * 6; // 6 days
            IAnkhConfigurationService config = e.GetService<IAnkhConfigurationService>();

            if (config.Instance.DisableUpdateCheck)
                return;

            using (RegistryKey rk = config.OpenUserInstanceKey("UpdateCheck"))
            {
                object value = rk.GetValue("Interval");

                if (value is int)
                {
                    interval = (int)value;

                    if (interval <= 0)
                        return;
                }
            }

            Version version = GetCurrentVersion(e.Context);
            Version osVersion = Environment.OSVersion.Version;

            StringBuilder sb = new StringBuilder();
            sb.Append("http://svc.ankhsvn.net/svc/");
            if (IsDevVersion())
                sb.Append("dev/");
            sb.Append("update-info/");
            sb.Append(version.ToString(2));
            sb.Append(".xml");
            sb.Append("?av=");
            sb.Append(version);
            sb.Append("&vs=");
            sb.Append(VSVersion.FullVersion);
            sb.Append("&os=");
            sb.Append(osVersion);

            if (IsDevVersion())
                sb.Append("&dev=1");

            sb.AppendFormat(CultureInfo.InvariantCulture, "&iv={0}", interval);
            int x = 0;
            // Create some hashcode that is probably constant and unique for all users
            // using the same IP address, but not translatable to a single user
            try
            {
                foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
                {
                    string type = ni.NetworkInterfaceType.ToString();

                    if (type.Contains("Ethernet") || type.Contains("Wireless"))
                        x ^= ni.GetPhysicalAddress().GetHashCode();
                }
            }
            catch { }

            sb.AppendFormat(CultureInfo.InvariantCulture, "&xx={0}&pc={1}", x, Environment.ProcessorCount);

            try
            {
                using (RegistryKey rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP"))
                {
                    if (rk != null)
                    {
                        sb.Append("&dn=");
                        Regex re = new Regex("^[vV]([0-9]+\\.[0-9]+)(\\.[0-9]+)*", RegexOptions.Singleline);
                        bool first = true;
                        HybridCollection<string> vers = new HybridCollection<string>();

                        foreach (string s in rk.GetSubKeyNames())
                        {
                            Match m = re.Match(s);

                            if (m.Success)
                            {
                                string v = m.Groups[1].Value;

                                if (vers.Contains(v))
                                    continue;

                                vers.Add(v);

                                if (first)
                                    first = false;
                                else
                                    sb.Append(',');

                                sb.Append(v);
                            }
                        }
                    }
                }
            }
            catch
            { }

            WebRequest wr;
            try
            {
                wr = WebRequest.Create(new Uri(sb.ToString()));
            }
            catch (System.Configuration.ConfigurationException)
            {
                // The global .Net or Visual Studio configuration probably contains an invalid (proxy) configuration
                return; // Not our problem
            }

            HttpWebRequest hwr = wr as HttpWebRequest;

            if (hwr != null)
            {
                hwr.AllowAutoRedirect = true;
                hwr.AllowWriteStreamBuffering = true;
                hwr.UserAgent = string.Format("AnkhSVN/{0} VisualStudio/{1} Windows/{2}", version, VSVersion.FullVersion, osVersion);
            }

            try
            {
                wr.BeginGetResponse(OnResponse, wr);
            }
            catch (NotSupportedException)
            { /* Raised when an invalid proxy server setting is set */ }
        }

19 Source : AnkhIssueService.cs
with Apache License 2.0
from AmpScm

private void ReadConnectorRegistry()
        {
            IAnkhPackage ankhPackage = GetService<IAnkhPackage>();
            if (ankhPackage != null)
            {
                using (RegistryKey key = ankhPackage.ApplicationRegistryRoot)
                {
                    using (RegistryKey aKey = key.OpenSubKey("IssueRepositoryConnectors"))
                    {
                        if (aKey == null)
                            return;

                        string[] connectorKeys = aKey.GetSubKeyNames();
                        foreach (string connectorKey in connectorKeys)
                            using (RegistryKey connector = aKey.OpenSubKey(connectorKey))
                            {
                                string serviceName = (string)connector.GetValue("");
                                IssueRepositoryConnector descriptor = new IssueRepositoryConnectorProxy(this, serviceName, connectorKey);
                                _nameConnectorMap.Add(serviceName, descriptor);
                            }
                    }
                }
            }
        }

19 Source : AnkhRepositoryProviderService.cs
with Apache License 2.0
from AmpScm

private void ReadProviderRegistry()
        {
            IAnkhPackage ankhPackage = GetService<IAnkhPackage>();
            if (ankhPackage != null)
            {
                using (RegistryKey key = ankhPackage.ApplicationRegistryRoot)
                {
                    using (RegistryKey aKey = key.OpenSubKey("ScmRepositoryProviders"))
                    {
                        if (aKey == null)
                            return;

                        string[] providerKeys = aKey.GetSubKeyNames();
                        foreach (string providerKey in providerKeys)
                        {
                            using (RegistryKey provider = aKey.OpenSubKey(providerKey))
                            {
                                string serviceName = (string)provider.GetValue("");
                                RepositoryType rt = GetRepositoryType(provider.GetValue("ScmType") as string);
                                ScmRepositoryProvider descriptor = new ScmRepositoryProviderProxy(this, providerKey, serviceName, rt);
                                if (!_nameProviderMap.ContainsKey(providerKey))
                                {
                                    _nameProviderMap.Add(providerKey, descriptor);
                                }
                            }
                        }
                    }
                }
            }
        }

19 Source : ConfigService.cs
with Apache License 2.0
from AmpScm

void SetSettingsFromRegistry(AnkhConfig config)
        {
            using (RegistryKey reg = OpenHKCUKey("Configuration"))
            {
                if (reg == null)
                    return;

                foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(config))
                {
                    string value = reg.GetValue(pd.Name, null) as string;

                    if (pd.Name == "DiffExePaths")
                    {
                        RegistryKey diffRegKey = OpenHKCUKey("Configuration");
                        diffRegKey = diffRegKey.OpenSubKey(pd.Name);

                        if (diffRegKey != null)
                        {
                            config.DiffExePaths.Clear();

                            foreach (string regKeyName in diffRegKey.GetValueNames())
                            {
                                string regValue = diffRegKey.GetValue(regKeyName) as string;

                                try
                                {
                                    ExtToolDefinition extToolDef = new ExtToolDefinition();
                                    extToolDef.extension = regKeyName;
                                    extToolDef.exePath = regValue;

                                    config.DiffExePaths.Add(extToolDef);
                                }
                                catch
                                {

                                }
                            }
                        }
                    }
                    else if (pd.Name == "MergeExePaths")
                    {
                        RegistryKey mergeRegKey = OpenHKCUKey("Configuration");
                        mergeRegKey = mergeRegKey.OpenSubKey(pd.Name);

                        if (mergeRegKey != null)
                        {
                            config.MergeExePaths.Clear();

                            foreach (string regKeyName in mergeRegKey.GetValueNames())
                            {
                                string regValue = mergeRegKey.GetValue(regKeyName) as string;

                                try
                                {
                                    ExtToolDefinition extToolDef = new ExtToolDefinition();
                                    extToolDef.extension = regKeyName;
                                    extToolDef.exePath = regValue;

                                    config.MergeExePaths.Add(extToolDef);
                                }
                                catch
                                {

                                }
                            }
                        }
                    }


                    else if (value != null)
                        try
                        {
                            pd.SetValue(config, pd.Converter.ConvertFromInvariantString(value));
                        }
                        catch { }
                }
            }
        }

19 Source : ConfigService.cs
with Apache License 2.0
from AmpScm

RegistryKey OpenHKLMKey(string subKey)
        {
            if (string.IsNullOrEmpty(subKey))
                throw new ArgumentNullException("subKey");

            // Opens the specified key or returns null
            return Registry.LocalMachine.OpenSubKey("SOFTWARE\\AnkhSVN\\AnkhSVN\\" + Settings.RegistryHiveSuffix + "\\" + subKey, RegistryKeyPermissionCheck.ReadSubTree);
        }

19 Source : ConfigService.cs
with Apache License 2.0
from AmpScm

public RegistryKey OpenVSInstanceKey(string name)
        {
            RegistryKey rootKey = null;

            ILocalRegistry4 lr4 = GetService<ILocalRegistry4>(typeof(SLocalRegistry));

            if (lr4 == null)
                return null;

            uint type;
            const uint VsLocalRegistryRootHandle_CURRENT_USER = unchecked((uint)-2147483647);
            string root;
            if (!VSErr.Succeeded(lr4.GetLocalRegistryRootEx(2 /* _VsLocalRegistryType.Configuration */, out type, out root)))
                return null;

            rootKey = ((type == VsLocalRegistryRootHandle_CURRENT_USER) ? Registry.CurrentUser : Registry.LocalMachine).OpenSubKey(root);

            if (rootKey == null)
                return null;
            else if (string.IsNullOrEmpty(name))
                return rootKey;

            using (rootKey)
            {
                return rootKey.OpenSubKey(name);
            }
        }

19 Source : ConfigService.cs
with Apache License 2.0
from AmpScm

public RegistryKey OpenVSUserKey(string name)
        {
            RegistryKey rootKey = null;

            ILocalRegistry4 lr4 = GetService<ILocalRegistry4>(typeof(SLocalRegistry));

            if (lr4 == null)
                return null;

            uint type;
            const uint VsLocalRegistryRootHandle_CURRENT_USER = unchecked((uint)-2147483647);
            string root;
            if (!VSErr.Succeeded(lr4.GetLocalRegistryRootEx(1 /* _VsLocalRegistryType.UserSettings */, out type, out root)))
                return null;

            rootKey = ((type == VsLocalRegistryRootHandle_CURRENT_USER) ? Registry.CurrentUser : Registry.LocalMachine).OpenSubKey(root);

            if (rootKey == null)
                return null;
            else if (string.IsNullOrEmpty(name))
                return rootKey;

            using (rootKey)
            {
                return rootKey.OpenSubKey(name);
            }
        }

19 Source : SccProjectData.cs
with Apache License 2.0
from AmpScm

void LoadProjectFlagMap()
        {
            _projectFlagMapLoaded = true;

            IAnkhConfigurationService configService = GetService<IAnkhConfigurationService>();

            if (configService == null)
                return;

            using (RegistryKey projectHandlingKey = configService.OpenVSInstanceKey("Extensions\\AnkhSVN\\ProjectHandling"))
            {
                if (projectHandlingKey == null)
                    return;

                foreach (string typeValue in projectHandlingKey.GetSubKeyNames())
                {
                    if (typeValue.Length != 38) // No proper guid
                        continue;

                    try
                    {
                        using (RegistryKey projectTypeKey = projectHandlingKey.OpenSubKey(typeValue))
                        {
                            object v = projectTypeKey.GetValue("flags");

                            if (!(v is int))
                                continue;

                            Guid projectType = new Guid(typeValue);
                            SccProjectFlags flags = (SccProjectFlags)(int)v;
                            _projectFlagMap.Add(projectType, flags);
                        }
                    }
                    catch
                    { /* Parse Error */ }
                }
            }
        }

19 Source : AnkhDiff.Tools.cs
with Apache License 2.0
from AmpScm

private void LoadRegistryTools(DiffToolMode diffToolMode, List<AnkhDiffTool> tools)
        {
            using (RegistryKey rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\AnkhSVN\\AnkhSVN\\CurrentVersion\\Tools\\" + diffToolMode.ToString(), false))
            {
                if (rk == null)
                    return;

                foreach (string name in rk.GetSubKeyNames())
                {
                    using(RegistryKey sk = rk.OpenSubKey(name, false))
                    {
                        string replacedle = sk.GetValue("") as string ?? name;
                        string program = sk.GetValue("Program") as string;
                        string arguments = sk.GetValue("Arguments") as string;

                        if (!string.IsNullOrEmpty(replacedle) && !string.IsNullOrEmpty(program) && !string.IsNullOrEmpty(arguments))
                        {
                            bool found = false;
                            foreach (AnkhDiffTool dt in tools)
                            {
                                if (dt.Name == name)
                                {
                                    found = true;
                                    break;
                                }
                            }

                            if (!found)
                                tools.Add(new DiffTool(Context, name, replacedle, program, arguments));
                        }
                    }
                }
            }
        }

19 Source : BuildDeployTools.cs
with MIT License
from anderm

public static string CalcMSBuildPath(string msBuildVersion)
        {
            if (msBuildVersion.Equals("14.0"))
            {
                using (Microsoft.Win32.RegistryKey key =
                    Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
                        string.Format(@"Software\Microsoft\MSBuild\ToolsVersions\{0}", msBuildVersion)))
                {
                    if (key == null)
                    {
                        return null;
                    }

                    var msBuildBinFolder = (string)key.GetValue("MSBuildToolsPath");
                    return Path.Combine(msBuildBinFolder, "msbuild.exe");
                }
            }

            // For MSBuild 15+ we should to use vswhere to give us the correct instance
            string output = @"/C cd ""%ProgramFiles(x86)%\Microsoft Visual Studio\Installer"" && vswhere -version " + msBuildVersion + " -products * -requires Microsoft.Component.MSBuild -property installationPath";

            var vswherePInfo = new System.Diagnostics.ProcessStartInfo
            {
                FileName = "cmd.exe",
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                Arguments = output
            };

            using (var vswhereP = new System.Diagnostics.Process())
            {
                vswhereP.StartInfo = vswherePInfo;
                vswhereP.Start();
                output = vswhereP.StandardOutput.ReadToEnd();
                vswhereP.WaitForExit();
                vswhereP.Close();
                vswhereP.Dispose();
            }

            output = output + @"\MSBuild\" + msBuildVersion + @"\Bin\MSBuild.exe";
            output = output.Replace(Environment.NewLine, "");
            return output;
        }

19 Source : RegistryExtensions.cs
with GNU General Public License v3.0
from AndreiFedarets

public static RegistryKey OpenSubKey(string fullName, RegistryView view)
        {
            RegistryHive hive = GetRegistryHive(fullName);
            string path = GetRegistryName(fullName);
            RegistryKey key = RegistryKey.OpenBaseKey(hive, view);
            if (!string.IsNullOrEmpty(path))
            {
                key = key.OpenSubKey(path);
            }
            return key;
        }

19 Source : BuilderLocator.cs
with GNU General Public License v3.0
from AndreiFedarets

public static string GetLatestBuilder()
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\MSBuild\ToolsVersions");
            string latestVersionPath = ""; //default
            Version latestVersion = new Version();
            foreach (string subKeyName in key.GetSubKeyNames())
            {
                Version version;
                if (Version.TryParse(subKeyName, out version) && version > latestVersion)
                {
                    RegistryKey tempkey = key.OpenSubKey(subKeyName);
                    string path = (string)tempkey.GetValue("MSBuildToolsPath");
                    if (!string.IsNullOrEmpty(path))
                    {
                        latestVersion = version;
                        latestVersionPath = Path.Combine(path, "msbuild.exe");
                    }
                }
            }
            return latestVersionPath;
        }

19 Source : RegistryKey.cs
with GNU General Public License v3.0
from AndreiFedarets

internal void Import(VariableCollection variables)
        {
            if (!string.IsNullOrEmpty(Name))
            {
                Microsoft.Win32.RegistryKey rootKey = Microsoft.Win32.RegistryKey.OpenBaseKey(RegistryHive, RegistryView);
                Microsoft.Win32.RegistryKey key = rootKey.OpenSubKey(Name);
                if (key == null)
                {
                    rootKey.CreateSubKey(Name);
                }
            }
            Keys.Import(variables);
            Values.Import(variables);
        }

See More Examples