How to set a default value for a new profile property for existing users in ASP.NET?

749 Views Asked by At

I added a new boolean property to my profile class.

I can't seem to find a way however to have it's value be true by default.

Profile.ShowDocumentsNotApplicable

returns false when not explicitly set to true...

web.config contents:

<!-- snip -->
<profile inherits="Company.Product.CustomerProfile">
  <providers>
    <clear />
    <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/" />
  </providers>
</profile>
<!-- snap -->

CustomerProfile:

public class CustomerProfile: ProfileBase
{
    private bool _showDocumentsNotApplicable = true;

    public bool ShowDocumentsNotApplicable
    {
        get { return Return("ShowDocumentsNotApplicable", _showDocumentsNotApplicable); }
        set { Set("ShowDocumentsNotApplicable", value, () => _showDocumentsNotApplicable = value); }
    }

    private T Return<T>(string propertyName, T defaultValue)
    {
        try
        {
            return (T)base[propertyName];
        }
        catch (SettingsPropertyNotFoundException)
        {
            return defaultValue;
        }
    }

    private void Set<T>(string propertyName, T setValue, System.Action defaultAction)
    {
        try
        {
            base[propertyName] = setValue;
        }
        catch (SettingsPropertyNotFoundException)
        {
            defaultAction();
        }
    }
}
1

There are 1 best solutions below

0
anaximander On

With boolean properties, you'll often find they can be expressed either way round. I consider it best practice to have them whichever way makes "false" the default. So, if by default you want Profile.ShowDocumentsNotApplicable to be true, then I'd call it Profile.HideDocumentsNotApplicable, for which the default is false. The reasoning behind this is that the compiler sets uninitialised bools to false; it makes sense to have your logic's defaults matching the compiler's defaults.

If the reverse is less suited (for example, you're always using !Profile.HideDocumentsNotApplicable and you find this reduces readability) then you could do the following:

public class CustomerProfile: ProfileBase
{
    private bool _hideDocumentsNotApplicable;
    public bool ShowDocumentsNotApplicable
    {
        get { return !_hideDocumentsNotApplicable); }
        set { _hideDocumentsNotApplicable = !value); }
    }

    //other stuff...
}