- Архитектура параметров приложения Application Settings Architecture
- Определение параметров Defining Settings
- Сохраняемость параметров Settings Persistence
- Привязки параметров Settings Bindings
- Сериализация параметров Settings Serialization
- Расположение файлов параметров Settings File Locations
- Параметры приложения и безопасность Application Settings and Security
- Поставщики пользовательских настроек Custom Settings Providers
Архитектура параметров приложения Application Settings Architecture
В этом разделе описываются принципы работы архитектуры параметров приложения и рассматриваются дополнительные возможности архитектуры, такие как сгруппированные параметры и ключи параметров. This topic describes how the Application Settings architecture works, and explores advanced features of the architecture, such as grouped settings and settings keys.
Архитектура параметров приложений позволяет определять строго типизированные параметры с областью приложения или пользователя и сохраняет параметры в сеансах приложения. The application settings architecture supports defining strongly typed settings with either application or user scope, and persisting the settings between application sessions. Архитектура предоставляет механизм сохраняемости по умолчанию для сохранения параметров и их загрузки из локальной файловой системы. The architecture provides a default persistence engine for saving settings to and loading them from the local file system. Она также определяет интерфейсы для предоставления пользовательских механизмов сохраняемости. The architecture also defines interfaces for supplying a custom persistence engine.
Эти интерфейсы позволяют пользовательским компонентам сохранять свои параметры, когда они размещаются в приложении. Interfaces are provided that enable custom components to persist their own settings when they are hosted in an application. Благодаря ключам параметров компоненты могут раздельно хранить параметры для нескольких экземпляров компонента. By using settings keys, components can keep settings for multiple instances of the component separate.
Определение параметров Defining Settings
Архитектура параметров приложения используется как в ASP.NET, так и в Windows Forms и содержит ряд базовых классов, совместно используемых в обеих средах. The application settings architecture is used within both ASP.NET and Windows Forms, and it contains a number of base classes that are shared across both environments. Наиболее важным является SettingsBase , который предоставляет доступ к параметрам через коллекцию и предоставляет низкоуровневые методы для загрузки и сохранения параметров. The most important is SettingsBase, which provides access to settings through a collection, and provides low-level methods for loading and saving settings. Каждая среда реализует собственный класс, производный от SettingsBase , чтобы предоставить дополнительные параметры для этой среды. Each environment implements its own class derived from SettingsBase to provide additional settings functionality for that environment. В приложении на основе Windows Forms все параметры приложения должны быть определены в классе, производном от ApplicationSettingsBase класса, который добавляет следующие функциональные возможности в базовый класс: In a Windows Forms-based application, all application settings must be defined on a class derived from the ApplicationSettingsBase class, which adds the following functionality to the base class:
Операции загрузки и сохранения более высокого уровня Higher-level loading and saving operations
Поддержка параметров области пользователя Support for user-scoped settings
Возврат для параметров пользователя предопределенных значений по умолчанию Reverting a user’s settings to the predefined defaults
Обновление параметров из предыдущей версии приложения Upgrading settings from a previous application version
Проверка параметров, либо до их изменения, либо до их сохранения Validating settings, either before they are changed or before they are saved
Параметры можно описать с помощью нескольких атрибутов, определенных в System.Configuration пространстве имен. они описаны в разделе атрибуты параметров приложения. The settings can be described using a number of attributes defined within the System.Configuration namespace; these are described in Application Settings Attributes. При определении параметра необходимо применить его с помощью ApplicationScopedSettingAttribute или UserScopedSettingAttribute , который описывает, применяется ли параметр ко всему приложению или только к текущему пользователю. When you define a setting, you must apply it with either ApplicationScopedSettingAttribute or UserScopedSettingAttribute, which describes whether the setting applies to the entire application or just to the current user.
В следующем примере кода определяется пользовательский класс параметров с одним параметром BackgroundColor . The following code example defines a custom settings class with a single setting, BackgroundColor .
Сохраняемость параметров Settings Persistence
ApplicationSettingsBaseСам класс не сохраняет и не загружает параметры. это задание принадлежит поставщику параметров, классу, производному от SettingsProvider . The ApplicationSettingsBase class does not itself persist or load settings; this job falls to the settings provider, a class that derives from SettingsProvider. Если в производном классе ApplicationSettingsBase не указан поставщик параметров через SettingsProviderAttribute , то используется поставщик по умолчанию, LocalFileSettingsProvider . If a derived class of ApplicationSettingsBase does not specify a settings provider through the SettingsProviderAttribute, then the default provider, LocalFileSettingsProvider, is used.
Система конфигурации, изначально выпущенная с .NET Framework, поддерживает предоставление статических данных конфигурации приложения с помощью файла machine.config локального компьютера или в app. exe.config файле, развертываемом с приложением. The configuration system that was originally released with the .NET Framework supports providing static application configuration data through either the local computer’s machine.config file or within an app. exe.config file that you deploy with your application. LocalFileSettingsProviderКласс расширяет эту встроенную поддержку следующими способами. The LocalFileSettingsProvider class expands this native support in the following ways:
Параметры области приложения могут храниться в файле machine.config или app. exe.config. Application-scoped settings can be stored in either the machine.config or app. exe.config files. Файл machine.config всегда предназначен только для чтения, тогда как app .exe.config для большинства приложений рекомендуется использовать только для чтения с точки зрения безопасности. Machine.config is always read-only, while app .exe.config is restricted by security considerations to read-only for most applications.
Параметры области пользователя могут храниться в файлах app .exe.config. В этом случае они обрабатываются как статические значения по умолчанию. User-scoped settings can be stored in app .exe.config files, in which case they are treated as static defaults.
Параметры области пользователя не по умолчанию хранятся в новом файле — пользователь.config, где пользователь — имя пользователя, который в данный момент выполняет приложение. Non-default user-scoped settings are stored in a new file, user.config, where user is the user name of the person currently executing the application. Можно указать значение по умолчанию для параметра с областью действия пользователя с помощью DefaultSettingValueAttribute . You can specify a default for a user-scoped setting with DefaultSettingValueAttribute. Так как во время выполнения приложения параметры области пользователя часто изменяются, файл user .config всегда доступен для чтения и записи. Because user-scoped settings often change during application execution, user .config is always read/write.
Определение элементов в разделе параметров приложения файла конфигурации см. в разделе Схема параметров приложения. For a definition of the elements within the application settings section of a configuration file, see Application Settings Schema.
Привязки параметров Settings Bindings
Параметры приложения используют архитектуру привязки данных Windows Forms для обеспечения двустороннего обмена обновлениями параметров между объектом параметров и компонентами. Application settings uses the Windows Forms data binding architecture to provide two-way communication of settings updates between the settings object and components. Если для создания параметров приложения и их назначения свойствам компонентов используется Visual Studio, эти привязки создаются автоматически. If you use Visual Studio to create application settings and assign them to component properties, these bindings are generated automatically.
Параметр приложения можно привязать только к компоненту, который поддерживает IBindableComponent интерфейс. You can only bind an application setting to a component that supports the IBindableComponent interface. Кроме того, компонент должен реализовать событие изменения для определенного привязанного свойства или уведомлять параметры приложения об изменении свойства через INotifyPropertyChanged интерфейс. Also, the component must implement a change event for a specific bound property, or notify application settings that the property has changed through the INotifyPropertyChanged interface. Если компонент не реализует IBindableComponent и привязка выполняется с помощью Visual Studio, привязанные свойства будут установлены в первый раз, но не будут обновлены. If the component does not implement IBindableComponent and you are binding through Visual Studio, the bound properties will be set the first time, but will not update. Если компонент реализует IBindableComponent , но не поддерживает уведомления об изменении свойств, привязка не будет обновляться в файле параметров при изменении свойства. If the component implements IBindableComponent but does not support property change notifications, the binding will not update in the settings file when the property is changed.
Некоторые Windows Forms компоненты, такие как ToolStripItem , не поддерживают привязки параметров. Some Windows Forms components, such as ToolStripItem, do not support settings bindings.
Сериализация параметров Settings Serialization
Когда LocalFileSettingsProvider параметр должен сохранять параметры на диске, он выполняет следующие действия: When LocalFileSettingsProvider must save settings to disk, it performs the following actions:
Использует отражение для проверки всех свойств, определенных в ApplicationSettingsBase производном классе, путем поиска тех, которые применяются с ApplicationScopedSettingAttribute или UserScopedSettingAttribute . Uses reflection to examine all of the properties defined on your ApplicationSettingsBase derived class, finding those that are applied with either ApplicationScopedSettingAttribute or UserScopedSettingAttribute.
Сериализует свойство на диск. Serializes the property to disk. Сначала он пытается вызвать метод ConvertToString или ConvertFromString для связанного типа TypeConverter . It first attempts to call the ConvertToString or ConvertFromString on the type’s associated TypeConverter. Если это не удается, использует XML-сериализацию. If this does not succeed, it uses XML serialization instead.
Распределяет параметры по файлам на основе атрибута параметра. Determines which settings go in which files, based on the setting’s attribute.
При реализации собственного класса параметров можно использовать, SettingsSerializeAsAttribute чтобы пометить параметр для двоичной или настраиваемой сериализации с помощью SettingsSerializeAs перечисления. If you implement your own settings class, you can use the SettingsSerializeAsAttribute to mark a setting for either binary or custom serialization using the SettingsSerializeAs enumeration. Дополнительные сведения о создании собственных классов параметров в коде см. в разделе Практическое руководство. Создание параметров приложения. For more information on creating your own settings class in code, see How to: Create Application Settings.
Расположение файлов параметров Settings File Locations
Расположение файлов app .exe.config и user.config зависит от способа установки приложения. The location of the app .exe.config and user.config files will differ based on how the application is installed. Для приложения на основе Windows Forms, скопированного на локальный компьютер, app .exe.config будет находиться в том же каталоге, что и базовый каталог главного исполняемого файла приложения, а файл User. config будет находиться в расположении, указанном Application.LocalUserAppDataPath свойством. For a Windows Forms-based application copied onto the local computer, app .exe.config will reside in the same directory as the base directory of the application’s main executable file, and user.config will reside in the location specified by the Application.LocalUserAppDataPath property. Для приложения, установленного с помощью ClickOnce, оба этих файла будут находиться в каталоге данных ClickOnce под%InstallRoot%\Documents и параметры \ username\Local Settings. For an application installed by means of ClickOnce, both of these files will reside in the ClickOnce Data Directory underneath %InstallRoot%\Documents and Settings\username\Local Settings.
Место хранения этих файлов немного отличается, если пользователь включил перемещаемые профили, что позволяет пользователю определять различные параметры Windows и приложения, если они используют другие компьютеры в домене. The storage location of these files is slightly different if a user has enabled roaming profiles, which enables a user to define different Windows and application settings when they are using other computers within a domain. В этом случае приложения ClickOnce и приложения, не относящиеся к ClickOnce, будут иметь свои app .exe.config и файлы User. config, хранящиеся в разделе%InstallRoot%\Documents and Settings \ username\Application Data. In that case, both ClickOnce applications and non-ClickOnce applications will have their app .exe.config and user.config files stored under %InstallRoot%\Documents and Settings\username\Application Data.
Дополнительные сведения о том, как параметры приложения работают с новой технологией развертывания, см. в разделе ClickOnce и параметры приложения. For more information about how the Application Settings feature works with the new deployment technology, see ClickOnce and Application Settings. Дополнительные сведения о каталоге данных ClickOnce см. в разделе доступ к локальным и удаленным данным в приложениях ClickOnce. For more information about the ClickOnce Data Directory, see Accessing Local and Remote Data in ClickOnce Applications.
Параметры приложения и безопасность Application Settings and Security
Параметры приложения предназначены для работы в режиме частичного доверия, то есть в среде с ограниченным доступом, которая используется по умолчанию для приложений Windows Forms, размещенных в Интернете или интрасети. Application settings are designed to work in partial trust, a restricted environment that is the default for Windows Forms applications hosted over the Internet or an intranet. Для использования параметров приложения с поставщиком параметров по умолчанию специальные разрешения, выходящие за рамки частичного доверия, не нужны. No special permissions beyond partial trust are needed to use application settings with the default settings provider.
Если параметры приложения используются в приложении ClickOnce, user файл config хранится в каталоге данных ClickOnce. When application settings are used in a ClickOnce application, the user .config file is stored in the ClickOnce data directory. Размер user файла конфигурации приложения не может превышать квоту каталога данных, установленную ClickOnce. The size of the application’s user .config file cannot exceed the data directory quota set by ClickOnce. Дополнительные сведения см. в разделе ClickOnce и параметры приложения. For more information, see ClickOnce and Application Settings.
Поставщики пользовательских настроек Custom Settings Providers
В архитектуре параметров приложения существует слабая связь между классом-оболочкой параметров приложения, производной от ApplicationSettingsBase , а также поставщиком и поставщиками связанных параметров, производными от SettingsProvider . In the Application Settings architecture, there is a loose coupling between the applications settings wrapper class, derived from ApplicationSettingsBase, and the associated settings provider or providers, derived from SettingsProvider. Эта ассоциация определяется только компонентом, SettingsProviderAttribute примененным к классу-оболочке или его отдельным свойствам. This association is defined only by the SettingsProviderAttribute applied to the wrapper class or its individual properties. Если поставщик параметров не указан явно, используется поставщик по умолчанию LocalFileSettingsProvider . If a settings provider is not explicitly specified, the default provider, LocalFileSettingsProvider, is used. В результате такая архитектура позволяет создавать и использовать поставщиков настраиваемых параметров. As a result, this architecture supports creating and using custom settings providers.
Предположим, что требуется разработать и использовать SqlSettingsProvider , то есть поставщика, который будет хранить все данные параметров в базе данных Microsoft SQL Server. For example, suppose that you want to develop and use SqlSettingsProvider , a provider that will store all settings data in a Microsoft SQL Server database. SettingsProviderКласс, производный от класса, получит эти сведения в своем Initialize методе как параметр типа System.Collections.Specialized.NameValueCollection . Your SettingsProvider-derived class would receive this information in its Initialize method as a parameter of type System.Collections.Specialized.NameValueCollection. Затем необходимо реализовать GetPropertyValues метод для получения параметров из хранилища данных и SetPropertyValues их сохранения. You would then implement the GetPropertyValues method to retrieve your settings from the data store, and SetPropertyValues to save them. Поставщик может использовать переданный объект SettingsPropertyCollection для GetPropertyValues определения имени свойства, типа и области, а также всех других атрибутов параметров, определенных для этого свойства. Your provider can use the SettingsPropertyCollection supplied to GetPropertyValues to determine the property’s name, type, and scope, as well as any other settings attributes defined for that property.
Вашему поставщику будет необходимо реализовать одно свойство и один метод, реализация которых может оказаться сложной. Your provider will need to implement one property and one method whose implementations may not be obvious. ApplicationNameСвойство является абстрактным свойством SettingsProvider ; необходимо запрограммировать его, чтобы он возвращал следующее: The ApplicationName property is an abstract property of SettingsProvider; you should program it to return the following:
Ваш производный класс также должен реализовать метод Initialize , который не принимает аргументы и не возвращает значения. Your derived class must also implement an Initialize method that takes no arguments and returns no value. Этот метод не определен в SettingsProvider . This method is not defined by SettingsProvider.
Наконец, вы реализуете IApplicationSettingsProvider поставщик, чтобы обеспечить поддержку обновления параметров, возврат параметров к значениям по умолчанию и обновление параметров из одной версии приложения в другую. Finally, you implement IApplicationSettingsProvider on your provider to provide support for refreshing settings, reverting settings to their defaults, and upgrading settings from one application version to another.
После реализации и компиляции поставщика необходимо указать, что класс параметров должен использовать этого поставщика вместо значения по умолчанию. Once you have implemented and compiled your provider, you need to instruct your settings class to use this provider instead of the default. Это можно сделать с помощью SettingsProviderAttribute . You accomplish this through the SettingsProviderAttribute. Если применяется ко всему классу параметров, поставщик используется для каждого параметра, определяемого классом. При применении к отдельным параметрам архитектура параметров приложения использует этот поставщик только для этих параметров и использует LocalFileSettingsProvider для остальных. If applied to an entire settings class, the provider is used for each setting that the class defines; if applied to individual settings, Application Settings architecture uses that provider for those settings only, and uses LocalFileSettingsProvider for the rest. В следующем примере кода показано, как указать классу параметров, что необходимо использовать пользовательского поставщика. The following code example shows how to instruct the settings class to use your custom provider.
Поставщик можно вызывать одновременно из нескольких потоков, но он всегда будет выполнять запись данных в одно место хранения. Таким образом, архитектура параметров приложения будет всегда создавать только один экземпляр класса поставщика. A provider may be called from multiple threads simultaneously, but it will always write to the same storage location; therefore, the Application Settings architecture will only ever instantiate a single instance of your provider class.
Следует убедиться, что поставщик является потокобезопасным и позволяет выполнять запись в файлы конфигурации только одному потоку за раз. You should ensure that your provider is thread-safe, and only allows one thread at a time to write to the configuration files.