/// <summary> /// Copies the value within the setting property onto the option property. /// </summary> /// <param name="settingsClass">The class instance for the settings property.</param> /// <param name="optionClass">The class instance for the option property.</param> public void CopySettingToOption(Settings settingsClass, object optionClass) { var settingValue = SettingProperty.GetValue(settingsClass); // Special case handling for MemberTypeSetting as operator casts for generics don't work as expected. if (typeof(TS) == typeof(string) && typeof(TO) == typeof(MemberTypeSetting)) { var optionValue = (MemberTypeSetting)(string)settingValue; // Note: No need to do an equality comparison before assignment as all options already have that through the Bindable base class. OptionProperty.SetValue(optionClass, optionValue); } else { var optionValue = (TO)settingValue; // Note: No need to do an equality comparison before assignment as all options already have that through the Bindable base class. OptionProperty.SetValue(optionClass, optionValue); } }
private static void CheckIsValid(SettingProperty prop) { if (!prop.Property.CanRead) { throw new Exception($"Property {prop.Property.Name} in {prop.SettingsInstance.GetType().FullName} must have a getter."); } if (!prop.Property.CanWrite) { throw new Exception($"Property {prop.Property.Name} in {prop.SettingsInstance.GetType().FullName} must have a setter."); } if (prop.SettingType == SettingType.Int || prop.SettingType == SettingType.Float) { if (prop.MinValue == prop.MaxValue) { throw new Exception($"Property {prop.Property.Name} in {prop.SettingsInstance.GetType().FullName} is a numeric type but the MinValue and MaxValue are the same."); } if (prop.GroupAttribute != null && prop.GroupAttribute.IsMainToggle) { throw new Exception($"Property {prop.Property.Name} in {prop.SettingsInstance.GetType().FullName} is marked as the main toggle for the group but is a numeric type. The main toggle must be a boolean type."); } } }
private SettingPropertyGroup GetGroupFor(SettingProperty sp, ICollection <SettingPropertyGroup> groupsList) { //If the setting somehow doesn't have a group attribute, throw an error. if (sp.GroupAttribute == null) { throw new Exception($"SettingProperty {sp.Name} has null GroupAttribute"); } SettingPropertyGroup group; //Check if the intended group is a sub group if (sp.GroupAttribute.GroupName.Contains(SubGroupDelimiter)) { //Intended group is a sub group. Must find it. First get the top group. string truncatedGroupName; string topGroupName = GetTopGroupName(sp.GroupAttribute.GroupName, out truncatedGroupName); SettingPropertyGroup topGroup = groupsList.GetGroup(topGroupName); if (topGroup == null) { topGroup = new SettingPropertyGroup(sp.GroupAttribute, topGroupName); groupsList.Add(topGroup); } //Find the sub group group = GetGroupForRecursive(truncatedGroupName, topGroup.SettingPropertyGroups, sp); } else { //Group is not a subgroup, can find it in the main list of groups. group = groupsList.GetGroup(sp.GroupAttribute.GroupName); if (group == null) { group = new SettingPropertyGroup(sp.GroupAttribute); groupsList.Add(group); } } return(group); }
/// <summary> /// Copies the value within the option property onto the setting property. /// </summary> /// <param name="settingsClass">The class instance for the settings property.</param> /// <param name="optionClass">The class instance for the option property.</param> public void CopyOptionToSetting(Settings settingsClass, object optionClass) { // Special case handling for MemberTypeSetting as operator casts for generics don't work as expected. if (typeof(TS) == typeof(string) && typeof(TO) == typeof(MemberTypeSetting)) { var optionValue = (string)(MemberTypeSetting)OptionProperty.GetValue(optionClass); var settingValue = (string)SettingProperty.GetValue(settingsClass); if (!EqualityComparer <string> .Default.Equals(optionValue, settingValue)) { SettingProperty.SetValue(settingsClass, optionValue); } } else { var optionValue = (TS)OptionProperty.GetValue(optionClass); var settingValue = (TS)SettingProperty.GetValue(settingsClass); if (!EqualityComparer <TS> .Default.Equals(optionValue, settingValue)) { SettingProperty.SetValue(settingsClass, optionValue); } } }
public static string GetSettingProperty(SettingProperty property) { SQLiteConnection connection = new SQLiteConnection(ConnectionString); try { connection.Open(); SQLiteCommand cmd = new SQLiteCommand( string.Format("select {0} from Setting where ID=@id", getStringFromEnum(property)), connection); cmd.Parameters.Add(new SQLiteParameter("id", 1)); object o = cmd.ExecuteScalar(); return o!=null ? o.ToString() : null; } catch (Exception exc) { MessageWindows.Show("GetSettingProperty:Exception", exc.Message); return null; } finally { if (connection.State == ConnectionState.Open) { connection.Close(); } } }
public static void UpdateSettingProperty(SettingProperty property, string value) { ExecuteNonQuery(string.Format("update Setting set {0}=@value", getStringFromEnum(property)), new List<SQLiteParameter> { new SQLiteParameter("value", value) }); }
public TValue GetSetting <TValue>(SettingProperty <TValue> property) { return(LocalSettings.Settings.TryGetValue(property, out TValue result) ? result : GetDefaultSetting(property)); }
public bool TryGetAutoSaveValue <TValue>(SettingProperty <TValue> property, out TValue value) => AutoSave.CurrentSettings.TryGetValue(property, out value);
private Session(SingleInstanceMainForm singleInstanceMainForm, ISettingsProvider settingsProvider, Localizer defaultLocalizer, Dictionary <LocalizedStringKey, string> defaultLocalizerDictionary, Icon applicationIcon) { if (settingsProvider == null) { throw new ArgumentNullException(nameof(settingsProvider)); } if (singleInstanceMainForm == null) { throw new ArgumentNullException(nameof(singleInstanceMainForm)); } if (!singleInstanceMainForm.IsHandleCreated || singleInstanceMainForm.Disposing || singleInstanceMainForm.IsDisposed) { throw new InvalidOperationException($"{nameof(singleInstanceMainForm)} should have its handle created."); } // May be null. this.defaultLocalizerDictionary = defaultLocalizerDictionary; ApplicationIcon = applicationIcon; // This depends on ExecutableFileName. DeveloperMode = new SettingProperty <bool>( new SettingKey(SettingKey.ToSnakeCase(nameof(DeveloperMode))), PType.CLR.Boolean, new SettingComment($"Enables tools which assist with {ExecutableFileNameWithoutExtension} development and debugging.")); // Attempt to load default settings. DefaultSettings = SettingsFile.Create( Path.Combine(ExecutableFolder, DefaultSettingsFileName), settingsProvider.CreateBuiltIn(this)); // Save name of LOCALAPPDATA subfolder for persistent files. AppDataSubFolder = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), GetDefaultSetting(SharedSettings.AppDataSubFolderName)); #if DEBUG // In debug mode, generate default json configuration files from hard coded settings. DeployRuntimeConfigurationFiles(); #endif // Scan Languages subdirectory to load localizers. var langFolderName = GetDefaultSetting(SharedSettings.LangFolderName); registeredLocalizers = Localizers.ScanLocalizers(this, Path.Combine(ExecutableFolder, langFolderName)); LangSetting = new SettingProperty <FileLocalizer>( new SettingKey(LangSettingKey), new PType.KeyedSet <FileLocalizer>(registeredLocalizers)); // Now attempt to get exclusive write access to the .lock file so it becomes a safe mutex. string lockFileName = Path.Combine(AppDataSubFolder, LockFileName); FileStreamPair autoSaveFiles = null; // Retry a maximum number of times. int remainingRetryAttempts = MaxRetryAttemptsForLockFile; while (remainingRetryAttempts >= 0) { try { // Create the folder on startup. Directory.CreateDirectory(AppDataSubFolder); // If this call doesn't throw, exclusive access to the mutex file is obtained. // Then this process is the first instance. // Use a buffer size of 24 rather than the default 4096. lockFile = new FileStream( lockFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read, WindowHandleLengthInBytes + MagicLengthInBytes); try { // Immediately empty the file. lockFile.SetLength(0); // Write the window handle to the lock file. // Use BitConverter to convert to and from byte[]. byte[] buffer = BitConverter.GetBytes(singleInstanceMainForm.Handle.ToInt64()); lockFile.Write(buffer, 0, WindowHandleLengthInBytes); // Generate a magic GUID for this instance. // The byte array has a length of 16. TodaysMagic = Guid.NewGuid().ToByteArray(); lockFile.Write(TodaysMagic, 0, MagicLengthInBytes); lockFile.Flush(); autoSaveFiles = OpenAutoSaveFileStreamPair(new AutoSaveFileNamePair(AutoSaveFileName1, AutoSaveFileName2)); // Loop exit point 1: successful write to lockFile. Can auto-save. break; } catch { ReleaseLockFile(lockFile); lockFile = null; } } catch { // Not the first instance. // Then try opening the lock file as read-only. try { // If opening as read-only succeeds, read the contents as bytes. FileStream existingLockFile = new FileStream( lockFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, WindowHandleLengthInBytes + MagicLengthInBytes); using (existingLockFile) { byte[] lockFileBytes = new byte[WindowHandleLengthInBytes + MagicLengthInBytes]; int totalBytesRead = 0; int remainingBytes = WindowHandleLengthInBytes + MagicLengthInBytes; while (remainingBytes > 0) { int bytesRead = existingLockFile.Read(lockFileBytes, totalBytesRead, remainingBytes); if (bytesRead == 0) { break; // Unexpected EOF? } totalBytesRead += bytesRead; remainingBytes -= bytesRead; } // For checking that EOF has been reached, evaluate ReadByte() == -1. if (remainingBytes == 0 && existingLockFile.ReadByte() == -1) { // Parse out the remote window handle and the magic bytes it is expecting. long longValue = BitConverter.ToInt64(lockFileBytes, 0); HandleRef remoteWindowHandle = new HandleRef(null, new IntPtr(longValue)); byte[] remoteExpectedMagic = new byte[MagicLengthInBytes]; Array.Copy(lockFileBytes, 8, remoteExpectedMagic, 0, MagicLengthInBytes); // Tell the singleInstanceMainForm that another instance is active. // Not a clean design to have callbacks going back and forth. // Hard to refactor since we're inside a loop. singleInstanceMainForm.NotifyExistingInstance(remoteWindowHandle, remoteExpectedMagic); // Reference remoteWindowHandle here so it won't be GC'ed until method returns. GC.KeepAlive(remoteWindowHandle); // Loop exit point 2: successful read of the lock file owned by an existing instance. return; } } } catch { } } // If any of the above steps fail, this might be caused by the other instance // shutting down for example, or still being in its startup phase. // In this case, sleep for 100 ms and retry the whole process. Thread.Sleep(PauseTimeBeforeLockRetry); remainingRetryAttempts--; // Loop exit point 3: proceed without auto-saving settings if even after 2 seconds the lock file couldn't be accessed. // This can happen for example if the first instance is running as Administrator and this instance is not. } try { AutoSave = new SettingsAutoSave(settingsProvider.CreateAutoSaveSchema(this), autoSaveFiles); // After creating the auto-save file, look for a local preferences file. // Create a working copy with correct schema first. SettingCopy localSettingsCopy = new SettingCopy(settingsProvider.CreateLocalSettingsSchema(this)); // And then create the local settings file which can overwrite values in default settings. LocalSettings = SettingsFile.Create( Path.Combine(AppDataSubFolder, GetDefaultSetting(SharedSettings.LocalPreferencesFileName)), localSettingsCopy); if (TryGetAutoSaveValue(LangSetting, out FileLocalizer localizer)) { currentLocalizer = localizer; } else { // Select best fit. currentLocalizer = Localizers.BestFit(registeredLocalizers); } // Fall back onto defaults if still null. currentLocalizer = currentLocalizer ?? defaultLocalizer ?? Localizer.Default; } catch { // Must dispose here, because Dispose() is never called if an exception is thrown in a constructor. ReleaseLockFile(lockFile); throw; } }
public TValue GetDefaultSetting <TValue>(SettingProperty <TValue> property) => DefaultSettings.Settings.GetValue(property);
public void SetConfiguration(SettingProperty settingProperty) { this.PropertyName = settingProperty.PropertyInfo.Name; //Behaviors.AddRange(settingProperty.Behaviors.Select(x => x.AssemblyQualifiedName).ToList()); }
set => SetValue(SettingProperty, value);
private static string getStringFromEnum(SettingProperty property) { switch (property) { case SettingProperty.CurrentUser: return "[CurrentUser]"; case SettingProperty.StartupDirectory: return "[StartupDirectory]"; case SettingProperty.SmtpServer: return "[SmtpServer]"; case SettingProperty.SmtpPort: return "[SmtpPort]"; case SettingProperty.PopServer: return "[PopServer]"; case SettingProperty.PopPort: return "[PopPort]"; case SettingProperty.EmailUser: return "[EmailUser]"; case SettingProperty.EmailPass: return "[EmailPass]"; } return string.Empty; }
private SettingPropertyGroup GetGroupForRecursive(string groupName, ICollection <SettingPropertyGroup> groupsList, SettingProperty sp) { if (groupName.Contains(SubGroupDelimiter)) { //Need to go deeper string topGroupName = GetTopGroupName(groupName, out string truncatedGroupName); SettingPropertyGroup topGroup = GetGroupFor(topGroupName, groupsList); if (topGroup == null) { topGroup = new SettingPropertyGroup(sp.GroupAttribute, topGroupName); groupsList.Add(topGroup); } return(GetGroupForRecursive(truncatedGroupName, topGroup.SettingPropertyGroups, sp)); } else { //Reached the bottom level, can return the final group. SettingPropertyGroup group = groupsList.GetGroup(groupName); if (group == null) { group = new SettingPropertyGroup(sp.GroupAttribute, groupName); groupsList.Add(group); } return(group); } }
public IReadOnlyCollection <WarpCoreEntity> GetDataRelationshipEntities(IRequiresDataSource requiresDataSource, SettingProperty settingProperty) { var info = settingProperty.PropertyInfo; var repo = RepositoryActivator.ActivateRepository(requiresDataSource.RepositoryApiId); List <WarpCoreEntity> allItems = null; if (repo is IUnversionedContentRepository unversionedRepo) { allItems = unversionedRepo.FindContent(BooleanExpression.None) .Cast <WarpCoreEntity>() .ToList(); } if (repo is IVersionedContentRepository versionedRepo) { allItems = versionedRepo.FindContentVersions(BooleanExpression.None) .Cast <WarpCoreEntity>() .ToList(); } if (allItems == null) { throw new Exception(); } return(allItems); }
public void SaveBoolSetting(SettingProperty property, bool value) { SaveSetting(property.ToString(), value.ToString()); }
public void SaveSetting(SettingProperty property, string value) { SaveSetting(property.ToString(), value); }
public bool GetBoolSetting(SettingProperty property) { string value = GetSetting(property.ToString()); return(bool.Parse(value)); }
public string GetSetting(SettingProperty property) { return(GetSetting(property.ToString())); }
/// <inheritdoc /> public void Execute(GeneratorExecutionContext context) { var settingClass = context.Compilation.GetTypeByMetadataName("Microsoft.Azure.PowerShell.Tools.AzPredictor.Settings"); if (settingClass is null) { throw new InvalidOperationException("Is the class Settings renamed?"); } var generatedSource = new StringBuilder($@" // ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the ""License""); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace {settingClass.ContainingNamespace} {{ // This file is generated from the source generator. DO NOT edit this file. sealed partial class {settingClass.Name} {{ "); var settingsFilePath = context.AdditionalFiles.Single((file) => file.Path.EndsWith("AzPredictorSettings.json", StringComparison.Ordinal)).Path; var fileContent = File.ReadAllText(settingsFilePath, Encoding.UTF8); var jsonDocument = JsonDocument.Parse(fileContent); var jsonRoot = jsonDocument.RootElement; var settingProperties = new List <SettingProperty>(); // Parse the json file and gather the property information, including name, type, and value. foreach (var element in jsonRoot.EnumerateObject()) { var newProperty = new SettingProperty() { Name = element.Name.Substring(0, 1).ToUpperInvariant() + element.Name.Substring(1), }; // There are only four types used in the json file: bool, int, string, and double (double isn't used in the json file yet). // So we only need to handle those right now. Expand to other types when we need to. switch (element.Value.ValueKind) { case JsonValueKind.String: newProperty.Type = SettingsSourceGenerator._StringType; newProperty.Value = $"\"{element.Value.GetString()}\""; break; case JsonValueKind.Number: if (element.Value.TryGetInt32(out var intValue)) { newProperty.Value = intValue.ToString(CultureInfo.InvariantCulture); newProperty.Type = SettingsSourceGenerator._IntType; } else if (element.Value.TryGetDouble(out var doubleValue)) { newProperty.Value = doubleValue.ToString(CultureInfo.InvariantCulture); newProperty.Type = SettingsSourceGenerator._DoubleType; } break; case JsonValueKind.True: goto case JsonValueKind.False; case JsonValueKind.False: newProperty.Type = SettingsSourceGenerator._BoolType; newProperty.Value = element.Value.ValueKind == JsonValueKind.True ? "true" : "false"; break; default: throw new InvalidOperationException($"The type {element.Value.ValueKind.ToString()} isn't supported yet."); } settingProperties.Add(newProperty); } // Generate the properties in the class Settings. foreach (var p in settingProperties) { _ = generatedSource.Append($@" public {p.Type} {p.Name} {{ get; set; }} = {p.Value}; "); } // Generate the method to override the properties values from user's profile settings. _ = generatedSource.Append($@" private void OverrideSettingsFrom(Settings otherSettings) {{ "); foreach (var p in settingProperties) { if (string.Equals(p.Type, SettingsSourceGenerator._IntType, StringComparison.Ordinal) || string.Equals(p.Type, SettingsSourceGenerator._DoubleType, StringComparison.Ordinal)) { _ = generatedSource.Append($@" if (otherSettings.{p.Name}.HasValue && otherSettings.{p.Name}.Value > 0) {{ {p.Name} = otherSettings.{p.Name}.Value; }} "); } else if (string.Equals(p.Type, SettingsSourceGenerator._StringType, StringComparison.Ordinal)) { _ = generatedSource.Append($@" if (!string.IsNullOrWhiteSpace(otherSettings.{p.Name})) {{ {p.Name} = otherSettings.{p.Name}; }} "); } else { _ = generatedSource.Append($@" if (otherSettings.{p.Name} != null) {{ {p.Name} = otherSettings.{p.Name}.Value; }} "); } } _ = generatedSource.Append(@" } "); _ = generatedSource.Append(@" } }"); context.AddSource("Settings.generated.cs", generatedSource.ToString()); }
private static Editor GetEditorForSettingProperty(SettingProperty property) { Editor?bestGuess = property.Editor; if (bestGuess == null) { var requiresCompositedConfiguration = property.PropertyInfo.PropertyType.GetCustomAttributes <CompositeConfiguratorTypeAttribute>().Any(); if (requiresCompositedConfiguration) { return(Editor.SubForm); } var isBoolean = property.PropertyInfo.PropertyType == typeof(bool); if (isBoolean) { bestGuess = Editor.CheckBox; } var isString = property.PropertyInfo.PropertyType == typeof(string); if (isString) { bestGuess = Editor.Text; } var isInt = property.PropertyInfo.PropertyType == typeof(int) || property.PropertyInfo.PropertyType == typeof(int?); if (isInt) { bestGuess = Editor.Text; } var isDecimal = property.PropertyInfo.PropertyType == typeof(decimal) || property.PropertyInfo.PropertyType == typeof(decimal?); if (isDecimal) { bestGuess = Editor.Text; } var isUri = property.PropertyInfo.PropertyType == typeof(Uri); if (isUri) { bestGuess = Editor.Url; } var hasDataRelation = property.PropertyInfo.GetCustomAttributes <DataRelationAttribute>().Any(); if (hasDataRelation) { bestGuess = Editor.OptionList; } var hasListControlSource = property.PropertyInfo.GetCustomAttributes().OfType <IListControlSource>().Any(); if (hasListControlSource) { bestGuess = Editor.OptionList; } var isSlug = property.PropertyInfo.PropertyType == typeof(Slug); if (isSlug) { bestGuess = Editor.Slug; } } return(bestGuess ?? Editor.SubForm); }
public EditValueGauntletScreen(SettingProperty settingProperty) { this.settingProperty = settingProperty; }
public WinServiceClient(SettingProperty <string> ipAddressSetting) { IPAddressSetting = ipAddressSetting; IPAddressSetting.Changed += IpAddressSetting_Changed; ListenTask = ListenAsync(); }