Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing boolean from configuration section in web.config

Tags:

c#

nullable

I have a custom configuration section in my web.config.

One of my classes is grabbing from this:

<myConfigSection LabelVisible="" TitleVisible="true"/>

I have things working for parsing if I have true or false, however if the attribute is blank I am getting errors. When the config section tries to map the class to the configuration section I get an error of "not a valid value for bool" on the 'LabelVisible' part.

How can I parse "" as false in my myConfigSection class?

I have tried this:

    [ConfigurationProperty("labelsVisible", DefaultValue = true, IsRequired = false)]
    public bool? LabelsVisible
    {
        get
        {

            return (bool?)this["labelsVisible"];

        }

But when I try and use what is returned like so:

graph.Label.Visible = myConfigSection.LabelsVisible;

I get an error of:

'Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)  
like image 279
Bloopy Avatar asked Nov 04 '09 17:11

Bloopy


2 Answers

Your problem is that graph.Label.Visible is of type bool but myConfigSection.LabelsVisible is of type bool?. There is no implicit conversion from bool? to bool because this a narrowing conversion. There are several ways to solve this:

1: Cast myConfigSection.LabelsVisible to a bool:

graph.Label.Visible = (bool)myConfigSection.LabelsVisible;

2: Extract the underlying bool value from myConfigSection.LabelsVisible:

graph.Label.Visible = myConfigSection.LabelsVisible.Value;

3: Add logic to capture when myConfigSection.LabelsVisible represents the null value:

graph.Label.Visible = myConfigSection.LabelsVisible.HasValue ?
                          myConfigSection.LabelsVisible.Value : true;

4: Interalize this logic to myConfigSection.LabelsVisible:

[ConfigurationProperty("labelsVisible", DefaultValue = true, IsRequired = false)]
public bool LabelsVisible {
    get {
        bool? b= (bool?)this["labelsVisible"];
        return b.HasValue ? b.Value : true;
    }
}

It is one of the latter two approaches that is best to avoid some exceptions that would occur if you use the other solutions when myConfigSection.LabelsVisible represents the null value. And the best solution is to internalize this logic into the myConfigSection.LabelsVisible property getter.

like image 58
jason Avatar answered Nov 09 '22 13:11

jason


This is a little dangerous, but technically works: (you'll get an InvalidOperationException if the value of the nullable is indeed null):

graph.Label.Visible = (bool)myConfigSection.LabelsVisible;

You should verify the nullable to see if it's been set:

bool defaultValue = true;
graph.Label.Visible = myConfigSection.LabelsVisible ?? defaultValue;
like image 36
Rex M Avatar answered Nov 09 '22 15:11

Rex M