Sunday, June 30, 2013

MultiValues User Settings creation and use.

I've never implemented ApplicationSettingsBase myself, I just knew of it. So built a test app to try it out. When you implement ApplicationSettingsBase, that is what your app will use for all of its Settings. So instead of using the designer to add Settings, you do it with code in the class you write.


I have put the project up on my sky drive, it is the CustomObjectSettings.zip file:


https://skydrive.live.com/redir?resid=E11159446BDBA3B3!2002&authkey=!AAib_vCsZ-bF5aA


If you don't have VS2012, then at least you should be able to open the files and read the code.


Files:


MyUserSettings.cs - This is the class that implements ApplicationSettingsBase. You will see three properties. One is a custom class I call "TheCustomObject". This just demonstrates how you can really use any class you want as a Settings property. Like the other two properties, it is decorated with [UserScopedSetting()] attribute. This is telling it that the user can modify the value. A user will only see their own changes, and it will persist between application invocations. It is also decorated with [SettingsSerializeAs(System.Configuration.SettingsSerializeAs.Xml)]. This is needed so that the custom objects properties can be persisted and read back by the application. There are two other properties, only included to demonstrate that you can add typical properties like strings and ints. They are also scoped by User and I also demonstrate how to give them default values. Lastly, in the construction I new up a TheCustomObject if it is null. The first time a user runs the app, this will be null and trying to get or set any of its properties will fail. Once Save has been called for the first time, the application will reload TheCustomObject from the serialized xml and it won't have to create a new one.


CustomObject.cs - this is the complex object definition that I'm storing in Settings. It just demonstrates that you can store any class you want as a settings property.


Form1.* - this is the form with labels and textboxes to identify and modify the application's settings. There is a Load method that reads values from the Settings and sets them into the textboxes, and there is a Save method that takes the values from the textboxes and updates the Settings. You can shut down the app, restart, and the last settings you saved will come back. You will see that I manually set and retrieve the settings but you could set databindings on the controls to save some work. I just think it is a better learning example to see it done manually.






Bob - www.crowcoder.com


No comments:

Post a Comment