". Net deep Breathing" Write your own application settings class

Source: Internet
Author: User

Before the beginning of the loading, the old week first to explain one thing. Some people say that the old week's writing is too simple, can write a bit more complicated. This is the question, what is to be written to be called "complex"? The most important thing is that the writing is too complicated, on the one hand many friends can not understand, on the other hand, even the old weeks themselves do not know how to express.

Moreover, the old week can not be in the K company, Z Company and T company in the project of the things written out, in fact, the work of the programming nothing to write, just select, INSERT, delete, update, just connect the database, disconnect, sync data, Turn data into XML or JSON and send it to another terminal. Just read your network card CPU hard drive serial number, compose an east and then encrypt, calculate the authorization code, or generate a fake certificate to grant the user authorization. Don't just write a few APIs and give someone a few notes. Let the brain cell death rate increase, is to dynamically generate a formula to calculate wages, this, then, the old week is the use of code DOM to generate this thing, the old weeks ago wrote a number of blog posts, I believe that the big friends have seen.

So, you see, the work used in fact very one-sided very single, covering the face is not as good as the old week usually idle time to write the small program. So, or write something simple harmony point, you know I understand he also understand, not very good, people alive why old with himself, Yu Heng elder brother once sang:

    • No matter how much pain and confusion we face tomorrow
    • Once in the faint secretly repeatedly cross-examine
    • Just know the light leisurely is the most true

Plain is a blessing, simple is music, who said otherwise?

Well, the above story is over, let's start talking.

As we all know, the VS development environment automatically generates a settings class for the project, the Help class for accessing the application settings, and the data is stored in the config file with the application, such as the historically Famous app. config file.

By the way, the VS auto-generated app settings class has one feature: application-scoped settings are read- only, and user-scoped settings items are readable and writable. Can't you read it? Okay, you can flirt with this settings class.

Under the Properties node, you should be able to see a Settings file and then open it.

Here you can add the settings yourself, and note the "Scope" column, which has two options, either based on the application scope or based on the user scope. OK, let's add a set item for each range.

Then we save it (must, save it to generate the code), and then open the code to see the Settings class generated by the designer.

Code excerpt.

[Global:: System.Configuration.UserScopedSettingAttribute ()] [Global:: System.Diagnostics.DebuggerNonUserCodeAttribute ()] [Global:: System.Configuration.DefaultSettingValueAttribute ("0")]         Public byteTestV1 {Get {                return((byte)( This["TestV1"])); }            Set {                 This["TestV1"] =value; }        }                [Global:: System.Configuration.ApplicationScopedSettingAttribute ()] [Global:: System.Diagnostics.DebuggerNonUserCodeAttribute ()] [Global:: System.Configuration.DefaultSettingValueAttribute ("0")]         Public intTestV2 {Get {                return((int)( This["TestV2"])); }        }

Applying ApplicationScopedSettingAttribute on a property indicates that the setting item is application-scoped, and we see that only get in the property has no set, which means it is read-only. The attribute that applied the UserScopedSettingAttribute represents a user-scoped set item, and when you see the property has both get and set, you can read and write.

Why the application-scoped settings item-related property generates a read-only property is understood by MSDN later, because the application-scoped settings do not work when the associated method is called to save the settings, but no error is given. That is, to write your own settings that can be saved directly, you can only define the attribute as user-scoped .

If you feel that the generated settings class is not fun, we can write it ourselves.

Writing this class is really simple, we just derive from the ApplicationSettingsBase class, which is in the System.Configuration namespace, which is an abstract class. When writing custom app settings classes, we can expose properties like normal classes, so it's easy to read and write settings, and you can use them directly for data binding.

When wrapping a property, it accesses the content by invoking the indexer of the base class, which is a dictionary model, key is a string type, and value is the object type, so you can set values of various types.

OK, let's write one for the show.

    Internal classAppsettings:applicationsettingsbase {#regionConstantConst stringApp_title ="AppTitle"; Const stringApp_usage ="Appusage"; Const stringUser_name ="UserName"; Const stringUse_years ="Useyears"; #endregion[userscopedsetting] [Defaultsettingvalue ("my App")]         Public stringAppTitle {Set            {                 This[App_title] =value; }            Get{return(string) This[App_title];} } [userscopedsetting] [Defaultsettingvalue ("for mounting x")]         Public stringAppusage {Get{return(string) This[App_usage];} Set{ This[App_usage] =value;} } [userscopedsetting] [Defaultsettingvalue ("Big Silly Winter")]         Public stringUserName {Get{return(string) This[user_name];} Set{ This[USER_NAME] =value;} } [userscopedsetting] [Defaultsettingvalue ("3")]         Public intUseyears {Get{return(int) This[Use_years];} Set{ This[Use_years] =value;} }    }

Because the key used in the property implementation is of a string type, a set of string constants can usually be pre-declared in order to prevent an error from entering multiple times.

        Const stringApp_title ="AppTitle"; Const stringApp_usage ="Appusage"; Const stringUser_name ="UserName"; Const stringUse_years ="Useyears";

In addition to applying a user-scoped identity attribute on a property exposed by a class, the Defaultsettingvalue attribute is applied to set the default value of the item, which is represented as a string.

This demonstration set-up class wraps four settings, so how to play it. It's easy to play, just like playing with monkeys. First, you want to new a class instance, and then you can read and write the set item through the four properties that we just wrapped, and finally, call the Save method to save the modified data to the configuration file.

The simplest and most convenient way to make the settings class interact with the user interface is to use bindings, such as this.

<textbox grid.column="1"text="{Binding path=apptitle, Mode=twoway, updatesourcetrigger=propertychanged}"/> <textbox grid.column="1"grid.row="1"text="{Binding path=appusage,mode=twoway,updatesourcetrigger=propertychanged}"/> <textbox grid.column="1"grid.row="2"text="{Binding path=username,mode=twoway,updatesourcetrigger=propertychanged}"/> <textbox grid.column="1"grid.row="3"text="{Binding path=useyears,mode=twoway,updatesourcetrigger=propertychanged}"/>

This setting class can be bound in two directions, because the base class ApplicationSettingsBase implements the INotifyPropertyChanged interface. Usually we can save the configuration when the window is closed.

        protected Override void onclosing (CancelEventArgs e)        {            base. OnClosing (e);            settings. Save ();        }

Before we develop the program, are accustomed to put a save button on the interface, when the user click on the save, but now seems to be popular, because the user after modifying the set up a button to save, the operation is a bit complicated, so that the window is closed automatically save settings, appear more friendly.

So where does this broken file go, and not in the configuration file in the directory where the app resides. Application-level settings in the application directory where the configuration file is stored, the user-level configuration should be related to the current user's private directory.

Open the File Manager, enter in the Address bar:%userprofile%\appdata\local, and then enter, will go to the current User folder under the AppData Local subdirectory, and then, in this directory, you will see a folder named after your application, Then you continue into the subdirectory until you see a file named User.config. Yes, it is, do not believe you open to see.

<Configuration>    <configsections>        <sectiongroupname= "UserSettings"type= "System.Configuration.UserSettingsGroup, System, version=4.0.0.0, Culture=neutral, publickeytoken= b77a5c561934e089 " >            < Sectionname= "Demoapp.appsettings"type= "System.Configuration.ClientSettingsSection, System, version=4.0.0.0, Culture=neutral, publickeytoken= b77a5c561934e089 "allowexedefinition= "Machinetolocaluser"requirepermission= "false" />        </sectiongroup>    </configsections>    <usersettings>        <demoapp.appsettings>            <settingname= "Useyears"SerializeAs= "String">                <value>2</value>            </setting>            <settingname= "UserName"SerializeAs= "String">                <value>Short melon</value>            </setting>            <settingname= "Appusage"SerializeAs= "String">                <value>Used for the flicker of minors</value>            </setting>            <settingname= "AppTitle"SerializeAs= "String">                <value>The first fake in heaven</value>            </setting>        </demoapp.appsettings>    </usersettings></Configuration>

In addition, the ApplicationSettingsBase class has several events that are useful and can be used if necessary. The Settingsloaded event occurs when the set number is loaded, and the purpose is known from the name, and the Settingchanging event occurs before the setting item is modified propertychanged Event (implements the INotifyPropertyChanged interface), the Settingssaving event is raised before the Save method is called, and the event arguments contain a Cancel property, which you can set to true if you want to cancel the save.

Sample source code: Click here?

". Net deep Breathing" Write your own application settings class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.