Click here to Skip to main content
Licence CPOL
First Posted 17 Oct 2007
Views 55,136
Downloads 1,581
Bookmarked 50 times

Creating a Custom Settings Provider

By | 17 Oct 2007 | Article
Demonstration of how to write custom settings providers.

Introduction

This article demonstrates how to write a custom Settings Provider to allow you to persist your My.Settings to your own storage system. The example given creates an XML file in the application folder which is ideal for portable applications. It also includes brief details of how to implement storage onto a U3 compliant USB device.

Background

The My.Settings functionality introduced with .NET 2.0 saves a lot of time and repeated effort for developers by providing a common, easy to use, and well thought out method of loading/saving settings. For a standard WinForms application, this works great, separating local and roaming settings automatically and storing them in the Documents and Settings\User\Local Settings\Application Data and Documents and Settings\User\Application Data folder hierarchies, respectively. But, what happens if you haven't got a typical scenario, say you want settings to be stored on a network drive, or you want them to be portable with the application so they can run off a USB device? As with most things in the .NET framework, you can override this default behaviour thankfully. In this case, it's by writing your own Settings Provider. This sounds daunting, but is actually relatively trivial. All you have to do is create a new class that inherits from SettingsProvider and provide the must override ApplicationName property which I just default to the Product Name.

Using the Code

Using a custom settings provider is simple; just include the class within your application, and when viewing the My Project/Settings page, just set the Provider property (defaults to blank) to your provider class name. Note that the Provider property is set for each setting individually; that way, you could keep some items under the default .NET provider model but override a few critical ones to travel with you using this portable provider.

The screenshot below shows exactly where to change this:

Screenshot - CustomSettingsProvider1.jpg

By default, the roaming property is set to false, which for the portable settings provider will mean that the setting is machine specific. For settings like window size/location, this is desired, but for settings you want to be used regardless of machine (in this example, the UserWord), you should set this to true.

Other than that, handle the settings exactly as you would normally do. In the example app, we just get and set them on our Form Load and Closing events.

When you run the application, it tries to load the settings from an XML file named applicationtitle.settings. Since this does not exist to start with, it uses the default values. Upon exiting the application, the settings file is created. If you have a look at it (in the project's bin/debug folder), you'll see it has the following format;

<?xml version="1.0" encoding="utf-8"?>
<Settings>
  <WorkPC>
    <WindowSize>300, 100</WindowSize>
    <WindowLocation>100, 100</WindowLocation>
  </WorkPC>
  <HomePC>
    <WindowSize>300, 200</WindowSize>
    <WindowLocation>300, 300</WindowLocation>
  </HomePC>
  <UserWord>Test</UserWord>
</Settings>

Notice how the settings that have a roaming value of false are enclosed within an element for the current PC name, whilst the roaming setting of UserWord is at the Settings node level, meaning it is used regardless of the PC you are using.

Also included is a U3 specific settings provider. This inherits from PortableSettingsProvider, overriding the GetAppSettingsPath function which, in this case, tries to retrieve a path from an environment variable. If you're happy with the storing of settings within an XML file but just want to change the location (perhaps a common network mapping), then you can use this inheritance technique as well.

Points of Interest

The real guts of the Settings Provider happen in the GetPropertyValues and SetPropertyValues functions. These pass in a collection object of all properties required to be got/set for this provider, which we just iterate round, loading or saving them to our XML document. I have implemented a SettingsXML property which either loads or creates a new XML document with the required root node.

The final point of interest is the IsRoaming function. This looks through the attributes collection of the objects on the property for a type of SettingsManageabilityAttribute. This attribute being present indicates that the IsRoaming property is set to true.

History

  • 18 October 2007 - Initial article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

CodeChimp

Web Developer

United Kingdom United Kingdom

Member

A general purpose analyst programmer working in a small development team for a company in the city.
 
VB has always been my passion and I code both Win forms and web based systems for both work and fun.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralRe: Writing Settings file to a different location PinmemberSSDiver21126:07 3 Jul '10  
GeneralRe: Writing Settings file to a different location Pinmembervbjay.net6:31 3 Jul '10  
GeneralRe: Writing Settings file to a different location PinmemberSSDiver21128:05 3 Jul '10  
GeneralRe: Writing Settings file to a different location PinmemberSSDiver211210:40 6 Jul '10  
QuestionWin Form Designer breaking with custom SettingsProvider PinmemberTom Faller2:48 20 Jun '08  
AnswerRe: Win Form Designer breaking with custom SettingsProvider [modified] PinmemberGeoffHacker15:16 20 Jul '08  
GeneralRe: Win Form Designer breaking with custom SettingsProvider PinmemberStewart McGuire10:22 10 Dec '08  
I was having trouble getting the custom settings provider to save my settings. After finding the source code for the SettingsBase class and looked at how it was saving the settings, I realized that the code in the previous post was missing something:
 
Imports System.Configuration    
 
Namespace My
 
    Partial Friend NotInheritable Class MySettings
        Private _csp As PortableSettingsProvider = New PortableSettingsProvider
 
        Public Sub New()
            Me.Providers().Add(_csp)         ' Added this line to add the custom provider to the Providers collection
            For Each sp As SettingsProperty In Me.Properties
                sp.Provider = _csp
            Next
        End Sub
 
    End Class
 
End Namespace
I added the Providers().Add() call to add the custom provider to the Providers collection. Otherwise, the settings would never get saved because the Save() method loops over the Providers collection, then compares all the settings to the provider and only saves those settings that match the current provider. If the provider is not in the Providers() collection then it will never save the settings for the custom provider.
 
I also had to add an additional property to the custom provider class:
 
Public Overrides ReadOnly Property Name() As String
        Get
            Return "PortableSettingsProvider"
        End Get
    End Property
This property overrides the Name property in the ProviderBase class that returns only a blank name. You can not add the provider to the Providers() collection unless it has a non-empty name.
GeneralRe: Win Form Designer breaking with custom SettingsProvider Pinmemberpiles3:03 5 May '09  
GeneralRe: Win Form Designer breaking with custom SettingsProvider PinmemberMatteo Rossi5:17 4 Jun '09  
GeneralRe: Win Form Designer breaking with custom SettingsProvider Pinmemberjuan32119:05 19 Oct '09  
GeneralRe: Win Form Designer breaking with custom SettingsProvider Pinmembersimonlynen3:56 26 Nov '09  
GeneralRe: Win Form Designer breaking with custom SettingsProvider PinmemberMLLong6:38 1 Feb '10  
AnswerRe: Win Form Designer breaking with custom SettingsProvider PinmemberSpock11:21 11 Aug '10  
AnswerRe: Win Form Designer breaking with custom SettingsProvider Pinmemberbwknight8776:32 7 Oct '11  
AnswerRe: Win Form Designer breaking with custom SettingsProvider PinmemberMember 904782514:55 30 May '12  
QuestionDoes it support .net 3.5 Pinmembersachintana20:35 21 Jan '08  
GeneralError using the project resources PinmemberSnakeskinner2:58 6 Nov '07  
GeneralRe: Error using the project resources PinmemberCodeChimp22:57 7 Nov '07  
GeneralRe: Error using the project resources PinmemberSnakeskinner0:50 9 Nov '07  
AnswerRe: Error using the project resources Pinmemberhikariuk23:33 7 Apr '08  
QuestionRe: Error using the project resources PinmemberMatteo Rossi5:16 4 Jun '09  
AnswerRe: Error using the project resources Pinmemberdreamgarden7:43 28 Jul '10  
GeneralRe: Error using the project resources Pinmemberper781:08 9 Oct '11  
GeneralRe: Error using the project resources PinmemberMember 904782518:09 30 May '12  
GeneralCreating a Custom Settigs Provider Pinmemberrctaubert3:54 23 Oct '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120604.1 | Last Updated 18 Oct 2007
Article Copyright 2007 by CodeChimp
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid