/// <summary> /// The initializer for this ShellComponent. /// </summary> /// <param name="lifetime"> /// The lifetime for this object. /// </param> public void Init(JetBrains.DataFlow.Lifetime lifetime) { RegistryUtils registryUtils = new RegistryUtils(); object oneTimeInitializationRequiredRegistryKey = registryUtils.CUGetValue("LastInitializationDate"); DateTime initializationDate = Convert.ToDateTime(oneTimeInitializationRequiredRegistryKey); string todayAsString = DateTime.Today.ToString("yyyy-MM-dd"); string value = registryUtils.LMGetValue("InstallDate") as string; DateTime lastInstalledDate; try { lastInstalledDate = Convert.ToDateTime(value); // If the installer stored a date that has now been read back in and seems to be in the future // then use the LocalUserInstallDate value. if (lastInstalledDate > DateTime.Today) { lastInstalledDate = GetInstallDateFromLocalUserRegistry(registryUtils, todayAsString); } } catch (FormatException ex) { // In some locales the installer saves the date in a format we can't parse back out. // Use today as the installed date and store it in the HKCU key. lastInstalledDate = GetInstallDateFromLocalUserRegistry(registryUtils, todayAsString); } if (oneTimeInitializationRequiredRegistryKey == null || initializationDate < lastInstalledDate) { SettingsStore settingsStore = Shell.Instance.GetComponent<SettingsStore>(); IContextBoundSettingsStoreLive settings = settingsStore.BindToContextLive(lifetime, ContextRange.ApplicationWide); bool checkReSharperCodeStyleOptionsAtStartUp = settings.GetValue((StyleCopOptionsSettingsKey key) => key.CheckReSharperCodeStyleOptionsAtStartUp); if (checkReSharperCodeStyleOptionsAtStartUp) { if (!StyleCopOptionsPage.CodeStyleOptionsValid(settings)) { DialogResult result = MessageBox.Show( @"Your ReSharper code style settings are not completely compatible with StyleCop. Would you like to reset them now?", @"StyleCop", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { StyleCopOptionsPage.CodeStyleOptionsReset(settings); } } } } registryUtils.CUSetValue("LastInitializationDate", todayAsString); }
/// <summary> /// Initializes our ShellComponent. /// </summary> public void Init() { StyleCopReferenceHelper.EnsureStyleCopIsLoaded(); RegistryUtils registryUtils = new RegistryUtils(); object oneTimeInitializationRequiredRegistryKey = registryUtils.CUGetValue("LastInitializationDate"); DateTime initializationDate = Convert.ToDateTime(oneTimeInitializationRequiredRegistryKey); string todayAsString = DateTime.Today.ToString("yyyy-MM-dd"); string value = registryUtils.LMGetValue("InstallDate") as string; DateTime lastInstalledDate; try { lastInstalledDate = Convert.ToDateTime(value); // If the installer stored a date that has now been read back in and seems to be in the future // then use the LocalUserInstallDate value. if (lastInstalledDate > DateTime.Today) { lastInstalledDate = GetInstallDateFromLocalUserRegistry(registryUtils, todayAsString); } } catch (FormatException ex) { // In some locales the installer saves the date in a format we can't parse back out. // Use today as the installed date and store it in the HKCU key. lastInstalledDate = GetInstallDateFromLocalUserRegistry(registryUtils, todayAsString); } if (oneTimeInitializationRequiredRegistryKey == null || initializationDate < lastInstalledDate) { if (!StyleCopOptionsPage.CodeStyleOptionsValid(null)) { DialogResult result = MessageBox.Show( @"Your ReSharper code style settings are not completely compatible with StyleCop. Would you like to reset them now?", @"StyleCop", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { StyleCopOptionsPage.ResetCodeStyleOptions(null); } } registryUtils.CUSetValue("LastInitializationDate", todayAsString); } }
/// <summary> /// Loads the InstallDate registry key value. /// </summary> /// <param name="registryUtils"> /// A <see cref="RegistryUtils"/> instance to access the registry. /// </param> /// <param name="defaultDateAsString"> /// The date to set the install date to if its value is not found in the registry. /// </param> /// <returns> /// The DateTime of the InstallDate LOCALUSER registry key. /// </returns> private static DateTime GetInstallDateFromLocalUserRegistry(RegistryUtils registryUtils, string defaultDateAsString) { string installDateRegistryKey = registryUtils.CUGetValue("InstallDate") as string; if (installDateRegistryKey != null) { return Convert.ToDateTime(installDateRegistryKey); } registryUtils.CUSetValue("InstallDate", defaultDateAsString); return Convert.ToDateTime(defaultDateAsString); }
private static string ConfigureAdminWAPCommandlineArguments() { StringBuilder arguments = new StringBuilder(); // Check to see if this is an uninstall if (PropertyBagDictionary.Instance.PropertyExists(PropertyBagConstants.Uninstall)) { arguments.Append("REMOVE=AdminSiteFeature "); } else { arguments.Append("ADDLOCAL=AdminSiteFeature "); } System.IO.DirectoryInfo inetpubDirectory = System.IO.Directory.GetParent(RegistryUtils.ReadRegistryValue(@"SOFTWARE\Microsoft\InetStp", @"PathWWWRoot", @"%SYSTEMDRIVE%\inetpub", true) as string); string adminSitePath = System.IO.Path.Combine(inetpubDirectory.FullName, SetupConstants.AdminSiteFolderName); arguments.Append(String.Format("PATHADMINSITE={0} ", adminSitePath)); return(arguments.ToString()); }
static void Main(string[] args) { RegistryUtils.registerPath(); if (args.Length == 0) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //configuration initialization ConfigurationManager.getInstance().initializeConfig(); Application.Run(new SplashScreen()); //start home Application.Run(new Home()); } else { thread = new Thread(new ThreadStart(service)); thread.Start(); } }
/// <summary> /// Returns the start menu programs folder path, optionally appending a category. /// </summary> /// <param name="category">The name of the category/directory below the programs folder; can be <c>null</c>.</param> /// <param name="machineWide"><c>true</c> to use the machine-wide start menu; <c>false</c> for the per-user variant.</param> /// <exception cref="IOException"><paramref name="category"/> contains invalid characters.</exception> private static string GetStartMenuCategoryPath(string?category, bool machineWide) { string menuDir = machineWide ? RegistryUtils.GetString(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", "Common Programs") : Environment.GetFolderPath(Environment.SpecialFolder.Programs); if (string.IsNullOrEmpty(category)) { return(menuDir); } else { string categoryDir = FileUtils.UnifySlashes(category); if (categoryDir.IndexOfAny(Path.GetInvalidPathChars()) != -1 || FileUtils.IsBreakoutPath(categoryDir)) { throw new IOException(string.Format(Resources.NameInvalidChars, category)); } return(Path.Combine(menuDir, categoryDir)); } }
private void SaveValue() { try { RegistryValueKind kind = this.Presenter.SelectedValueKind; // Value's kind object value = this.Presenter.CurrentData; // Value's Data RegistryKey currentKey = RegistryUtils.OpenKeyFromPath(this.CurrentKeyPath, true); if (this.IsEditing) // Removing the old value. { currentKey.DeleteValue(this.LastEditedValueName); } currentKey.SetValue(txtName.Text, value, kind); currentKey.Flush(); currentKey.Close(); } catch (Exception e) { MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1); } }
private byte[] GetRegistryInfo() { // add clsid strings byte[] buffer = new byte[0]; const string subkey = "CLSID"; RegistryUtils rtl = new RegistryUtils(); if (!rtl.AccessTest(RegistryUtils.RootKey.HKEY_CLASSES_ROOT, subkey)) { return(new byte[0]); } if (rtl.KeyExists(RegistryUtils.RootKey.HKEY_CLASSES_ROOT, subkey)) { string[] data = (string[])rtl.EnumKeys(RegistryUtils.RootKey.HKEY_CLASSES_ROOT, subkey).ToArray(typeof(string)); int len = 0; for (int i = 0; i < data.Length; ++i) { len += data[i].Length; } buffer = new byte[len]; for (int i = 0, j = 0; i < data.Length; ++i) { Guid res = Guid.Empty; if (Guid.TryParse((string)data[i], out res)) { if (!res.Equals(Guid.Empty)) { byte[] gb = res.ToByteArray(); Buffer.BlockCopy(gb, 0, buffer, j, gb.Length); j += gb.Length; } } } } return(Filter(buffer)); }
/// <summary> /// Stops the Zero Install Store Service if it is running. /// </summary> private void ServiceStop() { // Determine whether the service is installed and running var service = GetServiceController(); if (service?.Status != ServiceControllerStatus.Running) { return; } // Determine whether the service is installed in the target directory we are updating string imagePath = RegistryUtils.GetString(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\" + ServiceName, "ImagePath").Trim('"'); if (!imagePath.StartsWith(TargetDir)) { return; } Handler.RunTask(new SimpleTask(Resources.StopService, () => { try { service.Stop(); } #region Error handling catch (InvalidOperationException ex) { // Wrap exception since only certain exception types are allowed throw new IOException("Failed to stop service.", ex); } catch (Win32Exception ex) { // Wrap exception since only certain exception types are allowed throw new IOException("Failed to stop service.", ex); } #endregion Thread.Sleep(2000); })); }
private static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Bind(); // check legal acceptance status // if user hasn't accepted license term yet, force user to land on legal page first. bool userPreviouslyAcceptedLegalTerm = false; RegistryKey key = RegistryUtils.FindKey(ApplicationResource.RegistryEntryPoint); if (key != null) { // check acceptance status string value = RegistryUtils.GetKeyValue(key, ApplicationResource.RegistryKey); bool.TryParse(value, out userPreviouslyAcceptedLegalTerm); } if (userPreviouslyAcceptedLegalTerm) { IMainView appView = new MainView(); IMainModel appModel = new MainModel(); IMainPresenter presenter = SimpleResolver.Instance.Get <IMainPresenter>( new object[] { appModel, appView } ); Application.Run(appView as MainView); } else { // show legal view ILegalView legalView = new LegalView(); ILegalModel legalModel = new LegalModel(); ILegalPresenter presenter = SimpleResolver.Instance.Get <ILegalPresenter>( new object[] { legalModel, legalView } ); Application.Run(legalView as LegalView); } Unbind(); }
private ProcessStartInfo GetExistingInstance() { if (!WindowsUtils.IsWindows) { return(null); } string existingInstall = RegistryUtils.GetSoftwareString("Zero Install", "InstallLocation"); if (!string.IsNullOrEmpty(existingInstall)) { string launchAssembly = _gui ? "0install-win" //(WindowsUtils.IsWindows ? "0install-win" : "0install-gtk") : "0install"; if (File.Exists(Path.Combine(existingInstall, launchAssembly + ".exe"))) { return(ProcessUtils.Assembly(Path.Combine(existingInstall, launchAssembly), _targetArgs.ToArray())); } } return(null); }
private async Task ExecuteProcs(IEnumerable <Process> procs) { foreach (Process proc in procs) { procsExecuted++; string hiveShort = proc.StartInfo.Arguments.Split('"')[1]; string hive = cbxRemoteSearch.Checked ? RegistryUtils.GetRemoteHiveFullName(hiveShort) : RegistryUtils.GetHiveFullName(hiveShort); string message = $"Searching in {hive}...Patient :)"; Text = $"Find | {message}"; OnProgressChanged(this, new ProgressChangedArgs(message, hive)); await Task.Run(() => ExecuteProc(proc)); if (cancelToken.IsCancellationRequested) { break; } } }
internal static void CheckAndRunPortableInstaller() { try { if (!Oem.Instance.IsPortableInstaller) { return; } string registryValue = (string)RegistryUtils.GetRegistryValue(Strings.RegistryBaseKeyPath, "Version", (object)"", RegistryKeyKind.HKEY_LOCAL_MACHINE); string fullName = Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory.Trim('\\')).FullName; Logger.InitLogAtPath(Path.Combine(fullName, "Logs\\PortableInstaller.log"), nameof(PortableInstaller), true); if (!string.IsNullOrEmpty(registryValue) && !((string)RegistryUtils.GetRegistryValue(Strings.RegistryBaseKeyPath, "InstallDir", (object)"", RegistryKeyKind.HKEY_LOCAL_MACHINE) != Path.Combine(fullName, "BlueStacksPF")) && !Opt.Instance.isForceInstall) { return; } PortableInstaller.InstallPortableBlueStacks(AppDomain.CurrentDomain.BaseDirectory); } catch (Exception ex) { Logger.Info("Error in CheckAndRunPortableInstaller" + ex?.ToString()); } }
private void Uninstaller_Load(object sender, EventArgs e) { fileLocationLabel.Text = ""; try { _installPath = RegistryUtils.GetRegistryEntry(); installLocationLabel.Text = _installPath; } catch (Exception ex) { MessageBox.Show(ex.Message); } var removeFactory = new RemoveFactory(); var removeService = new RemoveService(removeFactory); var clientRemove = removeService.Create(FileType.Client, _installPath); var documentsRemove = removeService.Create(FileType.Documents, BotDirectories.baseDir); _commandList.Add(clientRemove); _commandList.Add(documentsRemove); }
public virtual void TestLsParent() { ServiceRecord written = PutExampleServiceEntry(EntryPath, 0); RegistryPathStatus stat = operations.Stat(EntryPath); IList <string> children = operations.List(ParentPath); NUnit.Framework.Assert.AreEqual(1, children.Count); NUnit.Framework.Assert.AreEqual(Name, children[0]); IDictionary <string, RegistryPathStatus> childStats = RegistryUtils.StatChildren(operations , ParentPath); NUnit.Framework.Assert.AreEqual(1, childStats.Count); NUnit.Framework.Assert.AreEqual(stat, childStats[Name]); IDictionary <string, ServiceRecord> records = RegistryUtils.ExtractServiceRecords( operations, ParentPath, childStats.Values); NUnit.Framework.Assert.AreEqual(1, records.Count); ServiceRecord record = records[EntryPath]; RegistryTypeUtils.ValidateServiceRecord(EntryPath, record); AssertMatches(written, record); }
// Uses detection logic described here: http://msdn.microsoft.com/library/hh925568 private IEnumerable <ExternalImplementation> FindNetFx(ImplementationVersion version, string clrVersion, string registryVersion, int releaseNumber = 0) { // Check for system native architecture (may be 32-bit or 64-bit) int install = RegistryUtils.GetDword(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\" + registryVersion, "Install"); int release = RegistryUtils.GetDword(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\" + registryVersion, "Release"); if (install == 1 && release >= releaseNumber) { yield return(new ExternalImplementation(DistributionName, "netfx", version, Architecture.CurrentSystem.Cpu) { // .NET executables do not need a runner on Windows Commands = { new Command { Name = Command.NameRun, Path = "" } }, IsInstalled = true, QuickTestFile = Path.Combine(WindowsUtils.GetNetFxDirectory(clrVersion), "mscorlib.dll") }); } // Check for 32-bit on a 64-bit system if (WindowsUtils.Is64BitProcess) { install = RegistryUtils.GetDword(@"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\NET Framework Setup\NDP\" + registryVersion, "Install"); release = RegistryUtils.GetDword(@"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\NET Framework Setup\NDP\" + registryVersion, "Release"); if (install == 1 && release >= releaseNumber) { yield return(new ExternalImplementation(DistributionName, "netfx", version, Cpu.I486) { // .NET executables do not need a runner on Windows Commands = { new Command { Name = Command.NameRun, Path = "" } }, IsInstalled = true, QuickTestFile = Path.Combine(WindowsUtils.GetNetFxDirectory(clrVersion), "mscorlib.dll") }); } } }
//--------------------// #region Service /// <summary> /// Stops the Zero Install Store Service if it is running. /// </summary> /// <returns><see langword="true"/> if the service was running; <see langword="false"/> otherwise.</returns> /// <exception cref="UnauthorizedAccessException">Administrator rights are missing.</exception> public bool ServiceStop() { // Do not touch the service in portable mode if (IsPortable) { return(false); } // Determine whether the service is installed and running var service = ServiceController.GetServices().FirstOrDefault(x => x.ServiceName == "0store-service"); if (service == null) { return(false); } if (service.Status == ServiceControllerStatus.Stopped) { return(false); } // Determine whether the service is installed in the target directory we are updating string imagePath = RegistryUtils.GetString(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\0store-service", "ImagePath").Trim('"'); if (!imagePath.StartsWith(Target)) { return(false); } if (!WindowsUtils.IsAdministrator) { throw new UnauthorizedAccessException(); } // Stop the service service.Stop(); Thread.Sleep(2000); return(true); }
internal MpDrawings() { if (double.TryParse(RegistryUtils.GetValue("DrawingsWinTop"), out var top)) { Top = top; } else { Top = 180; } if (double.TryParse(RegistryUtils.GetValue("DrawingsWinLeft"), out var left)) { Left = left; } else { Left = 60; } InitializeComponent(); ModPlusAPI.Windows.Helpers.WindowHelpers.ChangeStyleForResourceDictionary(Resources); ModPlusAPI.Language.SetLanguageProviderForResourceDictionary(Resources); MouseEnter += Window_MouseEnter; MouseLeave += Window_MouseLeave; MouseLeftButtonDown += Window_MouseLeftButtonDown; // Подключение обработчиков событий для создания и закрытия чертежей AcApp.DocumentManager.DocumentCreated += DocumentManager_DocumentCreated; AcApp.DocumentManager.DocumentDestroyed += DocumentManager_DocumentDestroyed; AcApp.DocumentManager.DocumentActivated += DocumentManager_DocumentActivated; GetDocuments(); // Обрабатываем событие покидания мышкой окна OnMouseLeaving(); }
private void PrepareLocalData(TreeNode editedNode) { this.CurrentKeyPath = editedNode.FullPath; RegistryKey currentKey = RegistryUtils.OpenKeyFromPath(this.CurrentKeyPath, false); this.SubKeyNames = new List <string>(currentKey.GetSubKeyNames()); currentKey.Close(); if (editedNode.Parent != null) { this.ParentKeyPath = editedNode.Parent.FullPath; RegistryKey parentKey = RegistryUtils.OpenKeyFromPath(this.ParentKeyPath, false); this.SameLevelKeyNames = new List <string>(parentKey.GetSubKeyNames()); parentKey.Close(); } else { this.SameLevelKeyNames = new List <string>(); } this.CurrentNode = editedNode; this.txtPath.Text = frmMain.Instance.txtPath.Text; }
private void DesktopIntegrationApply(long size) { Handler.RunTask(new SimpleTask(Resources.DesktopIntegrationApply, () => { UninstallEntry.Register( UninstallID, new[] { Path.Combine(TargetDir, "0install-win.exe"), Self.Name, Self.Remove.Name }, "Zero Install", new("https://0install.net/"), iconPath: Path.Combine(TargetDir, "ZeroInstall.exe"), AppInfo.Current.Version, size, MachineWide); RegistryUtils.SetSoftwareString(@"Microsoft\PackageManagement", "ZeroInstall", Path.Combine(TargetDir, "ZeroInstall.OneGet.dll"), MachineWide); PathEnv.AddDir(TargetDir, MachineWide); Shortcut.Create( path: Shortcut.GetStartMenuPath("", "Zero Install", MachineWide), targetPath: Path.Combine(TargetDir, "ZeroInstall.exe"), appId: "ZeroInstall"); }));
private void btnLogin_Click(object sender, EventArgs e) { this.btnLogin.Enabled = false; string serviceUrl = this.tbServiceUrl.Text; string userName = this.tbUsername.Text; string password = this.tbPassword.Text; SessionUtils.Session = SessionUtils.CreateSession(serviceUrl, userName, password); if (SessionUtils.Session != null) { this.setTextAlfLogout(AlfDefs.TEXT_LOGOUT); this.Close(); RegistryUtils.SetValue(AlfDefs.KEY_NAME_SERVICE_URL, serviceUrl); RegistryUtils.SetValue(AlfDefs.KEY_NAME_USERNAME, userName); RegistryUtils.SetValue(AlfDefs.KEY_NAME_PASSWORD, password); MessageBox.Show("Login Success", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Wrong username or password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } this.btnLogin.Enabled = true; }
/// <summary> /// Collects data about well-known URL protocol handlers. /// </summary> /// <param name="commandMapper">Provides best-match command-line to <see cref="Command"/> mapping.</param> /// <param name="capabilities">The capability list to add the collected data to.</param> /// <exception cref="IOException">There was an error accessing the registry.</exception> /// <exception cref="UnauthorizedAccessException">Read access to the registry was not permitted.</exception> public void CollectProtocolAssocs(CommandMapper commandMapper, CapabilityList capabilities) { #region Sanity checks if (capabilities == null) { throw new ArgumentNullException(nameof(capabilities)); } if (commandMapper == null) { throw new ArgumentNullException(nameof(commandMapper)); } #endregion foreach ((string protocol, _) in ProtocolAssocs) { using var protocolKey = Registry.ClassesRoot.OpenSubKey(protocol); if (protocolKey == null) { throw new IOException(protocol + " not found"); } capabilities.Entries.Add(new UrlProtocol { ID = protocol, Descriptions = { RegistryUtils.GetString(@"HKEY_CLASSES_ROOT\" + protocol, valueName: null, defaultValue: protocol) },
private void LicenseActivation(string license) { if (ValidateLincese(license)) { RegistryUtils.StoreLicenseKey(license); MessageBox.Show("Activated with success :), thanks for buying our product!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); DialogResult = DialogResult.OK; Close(); } else { DialogResult diagResult = MessageBox.Show("Invalid license, please contact us in www.big-technologies.com!", "Failed!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Hand); switch (diagResult) { case DialogResult.None: case DialogResult.Abort: case DialogResult.Ignore: case DialogResult.Cancel: DialogResult = DialogResult.Cancel; Close(); break; case DialogResult.Retry: maskedTextBox1.Focus(); maskedTextBox1.SelectAll(); return; default: DialogResult = DialogResult.OK; Close(); break; } } }
private void ToggleInstallLocationNeededButtons() { if (string.IsNullOrWhiteSpace(WoTDirectory)) { Logging.Info("WoTDirectory is empty, add default from registry search"); WoTDirectory = RegistryUtils.AutoFindWoTDirectoryFirst(); if (!string.IsNullOrWhiteSpace(WoTDirectory)) { WoTDirectory = Path.GetDirectoryName(WoTDirectory); } //if it's still empty, then mark is as not happening if (string.IsNullOrWhiteSpace(WoTDirectory)) { CollectLogInfoButton.IsEnabled = false; CleanupModFilesButton.IsEnabled = false; SelectedInstallation.Text = string.Format("{0}\n{1}", Translations.GetTranslatedString("SelectedInstallation"), Translations.GetTranslatedString("SelectedInstallationNone")); } } CollectLogInfoButton.IsEnabled = true; CleanupModFilesButton.IsEnabled = true; SelectedInstallation.Text = string.Format("{0}\n{1}", Translations.GetTranslatedString("SelectedInstallation"), WoTDirectory); }
public virtual int Purge(string path, RegistryAdminService.NodeSelector selector, RegistryAdminService.PurgePolicy purgePolicy, BackgroundCallback callback) { bool toDelete = false; // look at self to see if it has a service record IDictionary <string, RegistryPathStatus> childEntries; ICollection <RegistryPathStatus> entries; try { // list this path's children childEntries = RegistryUtils.StatChildren(this, path); entries = childEntries.Values; } catch (PathNotFoundException) { // there's no record here, it may have been deleted already. // exit return(0); } try { RegistryPathStatus registryPathStatus = Stat(path); ServiceRecord serviceRecord = Resolve(path); // there is now an entry here. toDelete = selector.ShouldSelect(path, registryPathStatus, serviceRecord); } catch (EOFException) { } catch (InvalidRecordException) { } catch (NoRecordException) { } catch (PathNotFoundException) { // ignore // ignore // ignore // there's no record here, it may have been deleted already. // exit return(0); } if (toDelete && !entries.IsEmpty()) { if (Log.IsDebugEnabled()) { Log.Debug("Match on record @ {} with children ", path); } switch (purgePolicy) { case RegistryAdminService.PurgePolicy.SkipOnChildren: { // there's children // don't do the deletion... continue to next record if (Log.IsDebugEnabled()) { Log.Debug("Skipping deletion"); } toDelete = false; break; } case RegistryAdminService.PurgePolicy.PurgeAll: { // mark for deletion if (Log.IsDebugEnabled()) { Log.Debug("Scheduling for deletion with children"); } toDelete = true; entries = new AList <RegistryPathStatus>(0); break; } case RegistryAdminService.PurgePolicy.FailOnChildren: { if (Log.IsDebugEnabled()) { Log.Debug("Failing deletion operation"); } throw new PathIsNotEmptyDirectoryException(path); } } } int deleteOps = 0; if (toDelete) { try { ZkDelete(path, true, callback); } catch (PathNotFoundException) { // sign that the path was deleted during the operation. // this is a no-op, and all children can be skipped return(deleteOps); } deleteOps++; } // now go through the children foreach (RegistryPathStatus status in entries) { string childname = status.path; string childpath = RegistryPathUtils.Join(path, childname); deleteOps += Purge(childpath, selector, purgePolicy, callback); } return(deleteOps); }
/// <summary>Get the path to a user's home dir</summary> /// <param name="username">username</param> /// <returns>a path for services underneath</returns> protected internal virtual string HomeDir(string username) { return(RegistryUtils.HomePathForUser(username)); }
/// <summary> /// Updates registry entry for recently used settings files /// </summary> private void SaveRecentSettingsList() { RegistryUtils.SetValue("", "RecentList", string.Join("|", RecentList.ToArray())); }
private static RegistryKey RegistryGetWritableKey(int keyNameSuffix) { return(RegistryUtils.GetWritableKey(ProfileRegistryString + keyNameSuffix)); }
private static void RegistrySetValue(int keyNameSuffix, string valueName, string value) { RegistryUtils.SetValue(ProfileRegistryString + keyNameSuffix, valueName, value); }
// Wrapper around RegistryUtils private static string RegistryGetValue(string suffix, object defaultValue) { return(RegistryUtils.GetValue(ProfileRegistryString + suffix, defaultValue)); }
/// <summary> /// Deletes a specific profile from the registry /// </summary> /// <param name="id"></param> public static void DeleteProfile(int id) { try { RegistryUtils.DeleteSubKey(ProfileRegistryString + id); } catch { } }
public override StatusResult CheckStatus() { //no need to check load and unload commands //these have to always run anyway if (Command == RegistryCommand.Load || Command == RegistryCommand.Unload) { return(StatusResult.Unavailable); } //The question this method is answering is: Would the state of the value(type, value) after execution be //the same as it is now. string keyName = RegistryUtils.NormalizeHive(Params[PARAM_NAME_KEY]); if (Command == RegistryCommand.Add) { //ADD command --------------------------------------------------------------- //if there is only key defined //-- check that key exists //if the value AND data is defined(no type is will be treated as SZ) //-- then check that the key has the value with that type and that data value //-- and no type is effectively the same as REG_SZ using (RegistryKey theKey = RegistryUtils.GetRegistryKey(keyName, RegistryView.Registry64)) { if (theKey == null) { return(StatusResult.Mismatch); } if (Params.TryGetValue(PARAM_NAME_VALUE, out string valueName) && Params.TryGetValue(PARAM_NAME_DATA, out string data)) { //there is value and data available //see if type is also provided, otherwise it is effectively an SZ Params.TryGetValue(PARAM_NAME_TYPE, out string type); if (type == null) { type = "REG_SZ"; } var valueKind = RegistryUtils.String2RegistryValueKind(type); //now fetch the actual value and type and compare with // the template parameters var valueDataCurr = theKey.GetValue(valueName); if (valueDataCurr != null) { //this value exists //now check the type var valueKindCurr = theKey.GetValueKind(valueName); if (valueKindCurr == valueKind) { //finally check the actual value string valueStrCurr = RegistryUtils.RegValue2String(valueDataCurr, valueKindCurr); if (data.ToLower().Equals(valueStrCurr.ToLower())) { return(StatusResult.Match); } } } } else { //at this point the key has been found //but no other params are there to check //so it is a match return(StatusResult.Match); } } } else { using (RegistryKey theKey = RegistryUtils.GetRegistryKey(keyName, RegistryView.Registry64)) { if (theKey == null) { //if the key does not exist then there is no need to delete it (or its values) return(StatusResult.Match); } else if (Command == RegistryCommand.DeleteValue) { //check if the value exists Params.TryGetValue(PARAM_NAME_VALUE, out string valueName); var valueDataCurr = theKey.GetValue(valueName); if (valueDataCurr == null) { //the specified value does not currently exist > match return(StatusResult.Match); } else { //the specified value does currently exist > mismatch return(StatusResult.Mismatch); } } else { //the key exists and the commnad is DeleteKey so it is a mismatch return(StatusResult.Mismatch); } } } //data+"!" makes sure that out dummy deafult will never accidentially //equal to the template value //var value = Registry.GetValue(keyName, valueName, data + "!"); return(StatusResult.Mismatch); }
public UserCredential() { UserName = RegistryUtils.LoadRememberedUserName(); }