示例#1
0
        private void RefreshRecentList(ToolStripMenuItem menuItem, RegistrySetting setting)
        {
            string[] fileNames = (string[])RegistryAccess.GetValueOrDefault(setting, new string[] { "" }, Microsoft.Win32.RegistryValueKind.MultiString);

            if (fileNames.Length == 1 && fileNames[0] == "")
            {
                return;
            }

            if (menuItem.HasDropDownItems)
            {
                menuItem.DropDownItems.Clear();
            }

            for (int i = 0; i < fileNames.Length; ++i)
            {
                menuItem.DropDownItems.Add((i + 1) + "  " + RegistryAccess.MakeShorter(fileNames[i]), null, new EventHandler(recentFile_click));
                menuItem.DropDownItems[i].Tag = fileNames[i];
            }

            if (menuItem.HasDropDownItems)
            {
                menuItem.Enabled = true;
            }
            else
            {
                menuItem.Enabled = false;
            }
        }
        public static ObservableCollection <string> GetObservable()
        {
            var observableCollection = new ObservableCollection <string>();

            foreach (var keyString in Settings.Default.Keys)
            {
                var key = new RegistrySetting(keyString);
                observableCollection.Add(key.Application);
            }
            return(observableCollection);
        }
示例#3
0
        public static void SetValue(RegistrySetting setting, object value, RegistryValueKind kind = RegistryValueKind.DWord)
        {
            VerifyAccess();

            object ret = key.GetValue(setting.ToString());

            if (ret != null && key.GetValueKind(setting.ToString()) != kind)
            {
                throw new Exception("setting parameter doesn't match kind parameter");
            }

            key.SetValue(setting.ToString(), value, kind);
        }
        public async Task BasicRegistrySettingsCRUD()
        {
            using (var session = await StartSession())
            {
                var client = await session.GetClient();

                //create
                var regSetting = new RegistrySetting
                {
                    Name        = "testSetting",
                    Value       = "testVal",
                    IsEncrypted = false,
                    IsReadOnly  = false
                };

                var res = await client.CreateRegistrySetting(regSetting);

                Assert.NotNull(res);

                //retrieve
                var getRes = await client.GetRegistrySetting(regSetting.Name);

                Assert.NotNull(getRes);
                Assert.Equal(res.Value, getRes.Value);
                Assert.Equal(res.IsEncrypted, getRes.IsEncrypted);

                //update
                var updatedSetting = new RegistrySetting
                {
                    Name        = "testSetting",
                    Value       = "testValUpdated",
                    IsEncrypted = false,
                    IsReadOnly  = false
                };
                var updated = await client.UpdateRegistrySetting(updatedSetting);

                Assert.True(updated);

                //check update
                getRes = await client.GetRegistrySetting(updatedSetting.Name);

                Assert.NotNull(getRes);
                Assert.Equal(updatedSetting.Value, getRes.Value);
                Assert.NotEqual(regSetting.Value, getRes.Value);

                //delete
                var delRes = await client.DeleteRegistrySetting(updatedSetting.Name);

                Assert.True(delRes);
            }
        }
 public static void Remove(string application)
 {
     foreach (var keyString in Settings.Default.Keys)
     {
         var key = new RegistrySetting(keyString);
         if (key.Application != application)
         {
             continue;
         }
         Settings.Default.Keys.Remove(keyString);
         Settings.Default.Save();
         return;
     }
     new ExceptionWindow("Error finding " + application + " in settings");
 }
示例#6
0
        public Task <int> Execute()
        {
            RegistrySetting setting = null;

            if (key == null)
            {
                foreach (var k in GlobalSettings.AllKeys)
                {
                    Console.WriteLine($"{k.Value.Name} = \"{ k.Value.GetStringValue().ToString()}\"");
                }

                return(Task.FromResult(0));
            }

            GlobalSettings.AllKeys.TryGetValue(key, out setting);

            if (setting == null)
            {
                Console.WriteLine($"Invalid Setting '{key}'.", LogLevel.Error);
                return(Task.FromResult(Constants.GSUDO_ERROR_EXITCODE));
            }

            if (value != null && value.Any())
            {
                if (value.FirstOrDefault().In("--reset"))
                {
                    setting.Reset(); // reset to default value
                }
                else if (value.Count() == 1)
                {
                    setting.Save(ArgumentsHelper.UnQuote(value.FirstOrDefault()).Replace("\\%", "%"));
                }
                else
                {
                    setting.Save(string.Join(" ", value.ToArray()));
                }
            }

            // READ
            Console.WriteLine($"{setting.Name} = \"{ setting.GetStringValue().ToString()}\"");
            return(Task.FromResult(0));
        }
示例#7
0
        public static object GetValueOrDefault(RegistrySetting setting, object defaultValue, RegistryValueKind kind = RegistryValueKind.DWord)
        {
            VerifyAccess();

            object ret = key.GetValue(setting.ToString());

            if (ret == null)
            {
                key.SetValue(setting.ToString(), defaultValue);
                return(defaultValue);
            }
            else if (key.GetValueKind(setting.ToString()) != kind)
            {
                throw new Exception("setting parameter doesn't match kind parameter");
            }
            else
            {
                return(ret);
            }
        }
示例#8
0
        public static void AddRecentFile(string filename, RegistrySetting setting)
        {
            if (setting.ToString().Substring(0, 6) != "Recent")
            {
                return;
            }

            VerifyAccess();

            string[] recentList = (string[])GetValueOrDefault(setting, new string[] { "" }, RegistryValueKind.MultiString);
            if (recentList == null)
            {
                recentList = new string[0];
            }

            int positionInRecentFiles = -1;

            for (int i = 0; i < recentList.Length; i++)
            {
                if (recentList[i] == filename)
                {
                    positionInRecentFiles = i;
                    break;
                }
            }

            if (recentList.Length < EditorConst.MAXIMUM_RECENT_FILES && recentList[0] != "" && positionInRecentFiles == -1)
            {
                Array.Resize <string>(ref recentList, recentList.Length + 1);
            }

            for (int i = positionInRecentFiles != -1 ? positionInRecentFiles : recentList.Length - 1; i > 0; i--)
            {
                recentList[i] = recentList[i - 1];
            }

            recentList[0] = filename;

            SetValue(setting, recentList, RegistryValueKind.MultiString);
        }
        private void LoadInitialSettings()
        {
            RegistrySetting oRegistrySetting = new RegistrySetting();

            try
            {
                servicetimer = new System.Timers.Timer((HourlyDailyEntity.HourlyReadInterval != 0) ?
                                                       CheckInterval(HourlyDailyEntity.HourlyReadInterval) : 1000);
                servicetimer.Elapsed += new System.Timers.ElapsedEventHandler(servicetimer_Elapsed);
                DBConnect.InitialSettings();
                HourlyDailyEntity.HasReadRunWithHourly    = false; // Fix for Read run twice for a day
                HourlyDailyEntity.ShouldReadRunWithHourly = HourlyDailyEntity.DailyAutoReadTime.Split(':')[1].ToString() == "00" ? true : false;
                oRegistrySetting.ReadRegistrySettings(HourlyDailyEntity.sRegistryPath);
                LogManager.WriteLog("HourlyReadHour from Registry: " + HourlyDailyEntity.HourlyReadHour.ToString() + " Date format from Registry: " + HourlyDailyEntity.LastAutoRead.ToString() + " Regional setting date format: " + System.Globalization.CultureInfo.CurrentCulture.DisplayName + " Service started", LogManager.enumLogLevel.Info);
                //HourlyDailyEventLog.WriteToEventLog(HourlyDailyEntity.EventLogName,"LoadInitialSettings: ", "Hourly Daily Service initiated", EventLogEntryType.Information);
            }
            catch (Exception ex)
            {
                //HourlyDailyEventLog.WriteToEventLog(HourlyDailyEntity.EventLogName, "LoadInitialSettings: ", "Message: " + ex.Message + "Source: " + ex.Source, EventLogEntryType.Error);
                ExceptionManager.Publish(ex);
            }
        }
 public Task <bool> UpdateRegistrySetting(RegistrySetting setting)
 {
     return(PutVoid($"/registry/{setting.Name}", setting, SOC));
 }
 public Task <RegistrySetting> CreateRegistrySetting(RegistrySetting setting)
 {
     return(PostAsync <RegistrySetting>("/registry", setting, SOC));
 }
示例#12
0
        /// <summary>
        /// Add a script installer deployment type to an application, using registry key in HKLM
        /// </summary>
        public static void AddScriptInstaller(string applicationName, string installName, string hklmKey, bool is64bit, string valueName, string valueNameValue, string dataType, string expressionOperator, string installCommand, string uninstallCommand, int postInstallBehaviour, int userInteractMode, int maxExecTime, int estimateExecTime, int execContext, string server)
        {
            Application     app       = CMApplication.GetApplicationByName(applicationName, server);
            ScriptInstaller installer = ReturnStandardScriptInstaller(installCommand, uninstallCommand, postInstallBehaviour, userInteractMode, maxExecTime, estimateExecTime, execContext);

            installer.DetectionMethod = DetectionMethod.Enhanced;
            EnhancedDetectionMethod enhancedDetectionMethod = new EnhancedDetectionMethod();

            ConstantValue   expectedValue   = null;
            RegistrySetting registrySetting = new RegistrySetting(null);

            registrySetting.RootKey           = RegistryRootKey.LocalMachine;
            registrySetting.Key               = hklmKey;
            registrySetting.Is64Bit           = is64bit;
            registrySetting.ValueName         = valueName;
            registrySetting.CreateMissingPath = false;

            switch (dataType)
            {
            case "Version":
                registrySetting.SettingDataType = DataType.Version;
                expectedValue = new ConstantValue(valueNameValue, DataType.Version);
                break;

            default:
                break;
            }

            enhancedDetectionMethod.Settings.Add(registrySetting);

            SettingReference settingReference = new SettingReference(app.Scope, app.Name, app.Version.GetValueOrDefault(), registrySetting.LogicalName, registrySetting.SettingDataType, registrySetting.SourceType, false);

            settingReference.MethodType = ConfigurationItemSettingMethodType.Value;

            CustomCollection <ExpressionBase> operands = new CustomCollection <ExpressionBase>();

            operands.Add(settingReference);
            operands.Add(expectedValue);

            Expression expression = null;

            switch (expressionOperator)
            {
            case "IsEquals":
                expression = new Expression(ExpressionOperator.IsEquals, operands);
                break;

            case "LessEquals":
                expression = new Expression(ExpressionOperator.LessEquals, operands);
                break;

            default:
                break;
            }

            Rule rule = new Rule(Guid.NewGuid().ToString("N"), NoncomplianceSeverity.None, null, expression);

            enhancedDetectionMethod.Rule = rule;

            installer.EnhancedDetectionMethod = enhancedDetectionMethod;

            DeploymentType deploymentType = new DeploymentType(installer, ScriptInstaller.TechnologyId, NativeHostingTechnology.TechnologyId);

            deploymentType.Title = installName;
            app.DeploymentTypes.Add(deploymentType);

            CMApplication.Save(app, server);
        }
示例#13
0
        public Task <int> Execute()
        {
            RegistrySetting setting = null;

            if (key == null)
            {
                // print all configs
                foreach (var k in Settings.AllKeys)
                {
                    Console.WriteLine($"{k.Value.Name} = \"{ k.Value.GetStringValue().ToString()}\"".PadRight(50) + (k.Value.HasGlobalValue() ? "(global)" : (k.Value.HasLocalValue() ? "(user)" : string.Empty)));
                }

                return(Task.FromResult(0));
            }

            Settings.AllKeys.TryGetValue(key, out setting);

            if (setting == null)
            {
                Logger.Instance.Log($"Invalid Setting '{key}'.", LogLevel.Error);
                return(Task.FromResult(Constants.GSUDO_ERROR_EXITCODE));
            }

            if (value != null && value.Any())
            {
                if (value.Any(v => v.In("--global")))
                {
                    InputArguments.Global = true;
                    value = value.Where(v => !v.In("--global"));
                }

                bool reset = value.Any(v => v.In("--reset"));
                value = value.Where(v => !v.In("--reset"));

                string unescapedValue =
                    (value.Count() == 1)
                    ? ArgumentsHelper.UnQuote(value.FirstOrDefault()).Replace("\\%", "%")
                    : string.Join(" ", value.ToArray());

                if (!reset)
                {
                    _ = setting.Parse(unescapedValue);
                }

                if (!InputArguments.Global && setting.Scope == RegistrySettingScope.GlobalOnly)
                {
                    Logger.Instance.Log($"Config Setting for '{setting.Name}' will be set as global system setting.", LogLevel.Info);
                    InputArguments.Global = true;
                }

                if (InputArguments.Global && !ProcessHelper.IsAdministrator())
                {
                    Logger.Instance.Log($"Global system settings requires elevation. Elevating...", LogLevel.Info);
                    return(new RunCommand()
                    {
                        CommandToRun = new string[]
                        { $"\"{ProcessHelper.GetOwnExeName()}\"", "--global", "config", key, reset ? "--reset" : $"\"{unescapedValue}\"" }
                    }.Execute());
                }

                if (reset)
                {
                    setting.Reset(InputArguments.Global); // reset to default value
                }
                else
                {
                    setting.Save(unescapedValue, InputArguments.Global);
                }

                if (setting.Name == Settings.CacheDuration.Name)
                {
                    new KillCacheCommand().Execute();
                }
            }

            // READ
            setting.ClearRunningValue();
            Console.WriteLine($"{setting.Name} = \"{ setting.GetStringValue().ToString()}\" {(setting.HasGlobalValue() ? "(global)" : (setting.HasLocalValue() ? "(user)" : "(default)"))}");
            return(Task.FromResult(0));
        }
示例#14
0
 public static object GetValue(RegistrySetting setting, RegistryValueKind kind = RegistryValueKind.DWord)
 {
     return(GetValueOrDefault(setting, (int)setting, kind));
 }
示例#15
0
        /// <summary>
        /// Add a script installer deployment type to an application, using registry key in HKLM
        /// </summary>
        public static void AddScriptInstaller(string applicationName, string installName, string hklmKey, bool is64bit, string valueName, string valueNameValue, string dataType, string expressionOperator, string installCommand, string uninstallCommand, int postInstallBehaviour, int userInteractMode, int maxExecTime, int estimateExecTime, int execContext, string server)
        {
            Application app = CMApplication.GetApplicationByName(applicationName, server);
            ScriptInstaller installer = ReturnStandardScriptInstaller(installCommand, uninstallCommand, postInstallBehaviour, userInteractMode, maxExecTime, estimateExecTime, execContext);

            installer.DetectionMethod = DetectionMethod.Enhanced;
            EnhancedDetectionMethod enhancedDetectionMethod = new EnhancedDetectionMethod();

            ConstantValue expectedValue = null;
            RegistrySetting registrySetting = new RegistrySetting(null);
            registrySetting.RootKey = RegistryRootKey.LocalMachine;
            registrySetting.Key = hklmKey;
            registrySetting.Is64Bit = is64bit;
            registrySetting.ValueName = valueName;
            registrySetting.CreateMissingPath = false;

            switch (dataType)
            {
                case "Version":
                    registrySetting.SettingDataType = DataType.Version;
                    expectedValue = new ConstantValue(valueNameValue, DataType.Version);
                    break;
                default:
                    break;
            }

            enhancedDetectionMethod.Settings.Add(registrySetting);

            SettingReference settingReference = new SettingReference(app.Scope, app.Name, app.Version.GetValueOrDefault(), registrySetting.LogicalName, registrySetting.SettingDataType, registrySetting.SourceType, false);
            settingReference.MethodType = ConfigurationItemSettingMethodType.Value;

            CustomCollection<ExpressionBase> operands = new CustomCollection<ExpressionBase>();
            operands.Add(settingReference);
            operands.Add(expectedValue);

            Expression expression = null;

            switch (expressionOperator)
            {
                case "IsEquals":
                    expression = new Expression(ExpressionOperator.IsEquals, operands);
                    break;
                case "LessEquals":
                    expression = new Expression(ExpressionOperator.LessEquals, operands);
                    break;
                default:
                    break;
            }

            Rule rule = new Rule(Guid.NewGuid().ToString("N"), NoncomplianceSeverity.None, null, expression);
            enhancedDetectionMethod.Rule = rule;

            installer.EnhancedDetectionMethod = enhancedDetectionMethod;

            DeploymentType deploymentType = new DeploymentType(installer, ScriptInstaller.TechnologyId, NativeHostingTechnology.TechnologyId);
            deploymentType.Title = installName;
            app.DeploymentTypes.Add(deploymentType);

            CMApplication.Save(app, server);
        }
示例#16
0
        public Form1()
        {
            InitializeComponent();
            ////connect to sccm
            this.sccmConnection.Connect(Environment.MachineName);
            ////retrieve the current applications and add them to the supersedence/dependency drop downs
            string wmiQuery = "SELECT * FROM SMS_Application WHERE SMS_APPLICATION.IsLatest = 1";
            WqlQueryResultsObject applicationResults = this.sccmConnection.QueryProcessor.ExecuteQuery(wmiQuery) as WqlQueryResultsObject;

            foreach (WqlResultObject appReference in applicationResults)
            {
                this.cmbSuperseded.Items.Add(appReference["LocalizedDisplayName"].StringValue);
                this.cmbDependency.Items.Add(appReference["LocalizedDisplayName"].StringValue);
            }

            ////get the global conditions and them to the global conditions drop down
            string condtionQuery = string.Format("SELECT * FROM SMS_GlobalCondition");
            WqlQueryResultsObject queryResults = this.sccmConnection.QueryProcessor.ExecuteQuery(condtionQuery) as WqlQueryResultsObject;

            foreach (IResultObject condition in queryResults)
            {
                ////retireve the lazy properties from the global condition
                condition.Get();
                ////load into wrapper objects so we can read out the properties in more detail
                DcmObjectWrapper wraper            = DcmObjectWrapper.WrapExistingConfigurationItem(condition) as DcmObjectWrapper;
                ComplexSetting   conditionSettings = wraper.InnerConfigurationItem.Settings;
                if (conditionSettings.ChildSimpleSettings.Any())
                {
                    ////if the condition contains simplechild settings assume this is a registry setting
                    RegistrySetting registrySetting = conditionSettings.ChildSimpleSettings[0] as RegistrySetting;
                    if (registrySetting != null)
                    {
                        ScalarDataType type = registrySetting.SettingDataType as ScalarDataType;
                        ////only add string based registry conditions
                        if (type == ScalarDataType.String)
                        {
                            this.cmbConditions.Items.Add(registrySetting.Name);
                        }
                    }
                }
            }

            ////get the available distribution point groups and add them to the drop down
            string dpgQuery            = "Select * From SMS_DistributionPointGroup";
            WqlQueryResultsObject dpgs = this.sccmConnection.QueryProcessor.ExecuteQuery(dpgQuery) as WqlQueryResultsObject;

            foreach (WqlResultObject dpg in dpgs)
            {
                this.cmbDPGNames.Items.Add(dpg["Name"].StringValue);
            }

            ////get a list of the avialable collections
            string collectionQuery            = "SELECT * FROM SMS_Collection";
            WqlQueryResultsObject collections = this.sccmConnection.QueryProcessor.ExecuteQuery(collectionQuery) as WqlQueryResultsObject;

            foreach (WqlResultObject collection in collections)
            {
                this.cmbCollection.Items.Add(collection.PropertyList["Name"]);
            }

            if (this.cmbSuperseded.Items.Count > 0)
            {
                this.cmbSuperseded.SelectedIndex = 0;
                this.cmbDependency.SelectedIndex = 0;
            }

            if (this.cmbConditions.Items.Count > 0)
            {
                this.cmbConditions.SelectedIndex = 0;
            }

            if (this.cmbDPGNames.Items.Count > 0)
            {
                this.cmbDPGNames.SelectedIndex = 0;
            }

            if (this.cmbCollection.Items.Count > 0)
            {
                this.cmbCollection.SelectedIndex = 0;
            }
        }
        public void RunService()
        {
            //Dictionary<string, string> dictServiceentries = new Dictionary<string, string>();
            RegistrySetting oRegistrySetting = new RegistrySetting();

            try
            {
#if (DEBUG)
                {
                    if (IsRunning == false)
                    {
                        IsRunning            = true;
                        servicetimer.Enabled = true;
                        TimerCount           = TimerCount + 1;
                        oRegistrySetting.ReadRegistrySettings(HourlyDailyEntity.sRegistryPath);
                        if (DateTime.Now.Hour != HourlyDailyEntity.HourlyReadHour)
                        {
                            //LogManager.WriteLog("The Hour: " + HourlyDailyEntity.HourlyReadHour.ToString(), LogManager.enumLogLevel.Debug);
                            if (DBConnect.CheckSqlConnectionExists())
                            {
                                DBConnect.InitialSettings();
                                oHourlyServiceHandle.DoWork();
                                HourlyDailyEntity.HourlyReadHour = DateTime.Now.Hour;
                                dictServiceentries.Add(HourlyDailyEntity.sRegistryPath + "\\\\HourlyReadHour", HourlyDailyEntity.HourlyReadHour.ToString());
                                oRegistrySetting.SetRegistryEntries(dictServiceentries, HourlyDailyEntity.sRegistryPath);
                            }
                        }
                        if (TimerCount == 10)
                        {
                            oRegistrySetting.ReadRegistrySettings(HourlyDailyEntity.sRegistryPath);
                            oDailyReadServiceHandle.DoWork();
                            TimerCount = 0;
                        }
                        IsRunning = false;
                    }
                }
#else
                {
                    if (IsRunning == false)
                    {
                        IsRunning            = true;
                        servicetimer.Enabled = true;
                        TimerCount           = TimerCount + 1;
                        oRegistrySetting.ReadRegistrySettings(HourlyDailyEntity.sRegistryPath);
                        if (DateTime.Now.Hour != HourlyDailyEntity.HourlyReadHour)
                        {
                            //LogManager.WriteLog("The Hour: " + HourlyDailyEntity.HourlyReadHour.ToString(), LogManager.enumLogLevel.Debug);
                            if (DBConnect.CheckSqlConnectionExists())
                            {
                                DBConnect.InitialSettings();
                                oHourlyServiceHandle.DoWork();
                                HourlyDailyEntity.HourlyReadHour = DateTime.Now.Hour;
                                BMCRegistryHelper.SetRegKeyValue(HourlyDailyEntity.sRegistryPath, "HourlyReadHour", Microsoft.Win32.RegistryValueKind.String, HourlyDailyEntity.HourlyReadHour.ToString());
                            }
                        }
                        if (TimerCount == 10)
                        {
                            oRegistrySetting.ReadRegistrySettings(HourlyDailyEntity.sRegistryPath);
                            oDailyReadServiceHandle.DoWork();
                            TimerCount = 0;
                        }
                        IsRunning = false;
                    }
                }
#endif
            }

            catch (Exception ex)
            {
                IsRunning = false;
                //HourlyDailyEventLog.WriteToEventLog(HourlyDailyEntity.EventLogName, "RunService: ", "Message: " + ex.Message + "Source: " + ex.Source, EventLogEntryType.Error);
                ExceptionManager.Publish(ex);
            }
        }