Accendo / Publikované

Zlyhanie pretypovania custom ConfigurationSection

 

Autor: Libor Bešenyi

Dátum: 17.12.2009

 

            Niektorí ľudia na Internete – vrátane mňa majú problém s pretypovaním vlastnej ConfigurationSection na svoj typ, napriek tomu, že v app.configu majú zadefinovaný správny typ. Systém vždy vráti inštanciu odvodeného typu, čím sa znemožní načítanie dát (ak sa pretypuje cez AS tak je to samozrejme NULL / NIL).

 

            Problém nastal v mojom prípade vtedy, keď som zadefinoval do configu aj connections stringy (preto to niekomu chodí, pretože asi to neurobil). Dôležité je poradie. Môj príklad nechodil, tak som si stiahol príklad z netu a tiež nechodil s konfiguráciou takou:

 

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

      <connectionStrings>

            <add

                  name="Members"

                  connectionString="packet size=4096; user id=sa;data source=192.168.168.81;initial catalog=x_EES;password=password"

                  providerName="System.Data.SqlClient" />

            <add

                  name="SEPC2"

                  connectionString="packet size=4096; user id=sa;data source=192.168.168.81;initial catalog=x_S-EPC_2;password=password"

                  providerName="System.Data.SqlClient" />

      </connectionStrings>

 

      <configSections>

            <section name="StartupFolders" type="WindowsFormsApplication1.StartupFoldersConfigSection, WindowsFormsApplication1"/>

      </configSections>

     

      <StartupFolders>

            <Folders>

                  <add folderType="A" path="c:\foo" />

                  <add folderType="B" path="C:\foo1" />

            </Folders>

      </StartupFolders>

</configuration>

 

Napriek tomu, že config obsahuje (boldom označená časť) typ, na ktorú inštanciu sa ma StartupFolder pretypovať, vždy sa vrátim (pri krokovaní) ConfigurationSection inštancia predka. Akonáhle prehodíme connection string sekciu na koniec, začne to chodiť.

 

Príklad z netu:

using System.Configuration;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Xml.Serialization;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Windows.Forms;

 

namespace WindowsFormsApplication1

{

      [ConfigurationCollection(typeof(FolderElement))]

      public class FoldersCollection : ConfigurationElementCollection

      {

            protected override ConfigurationElement CreateNewElement()

            {

                  return new FolderElement();

            }

 

            protected override object GetElementKey(ConfigurationElement element)

            {

                  return ((FolderElement)(element)).FolderType;

            }

 

            public FolderElement this[int idx]

            {

                  get

                  {

                        return (FolderElement)BaseGet(idx);

                  }

            }

      }

 

      public class StartupFoldersConfigSection : ConfigurationSection

      {

            [ConfigurationProperty("Folders")]

            public FoldersCollection FolderItems

            {

                  get { return ((FoldersCollection)(base["Folders"])); }

            }

 

      }

 

      public class FolderElement : ConfigurationElement

      {

            [ConfigurationProperty("folderType", DefaultValue = "", IsKey = true, IsRequired = true)]

            public string FolderType

            {

                  get

                  {

                        return ((string)(base["folderType"]));

                  }

 

                  set

                  {

                        base["folderType"] = value;

                  }

            }

 

            [ConfigurationProperty("path", DefaultValue = "", IsKey = false, IsRequired = false)]

            public string Path

            {

                  get

                  {

 

                        return ((string)(base["path"]));

                  }

 

                  set

                  {

                        base["path"] = value;

                  }

            }

      }

     

      public partial class Form1 : Form

      {

            public Form1()

            {

                  InitializeComponent();

            }

 

            private void Form1_Load(object sender, EventArgs e)

            {

                  Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                  StartupFoldersConfigSection productSection = (config.GetSection("StartupFolders") as StartupFoldersConfigSection);

 

                  MessageBox.Show("Works = " + (productSection != null).ToString());

            }

      }

}

 

http://mrgeesbigcircus.posterous.com/i-love-net-custom-webconfig-sections-with-a-w