How to read custom object list from app.config - c#

I've defined custom settings in app.config but I am getting an error when reading the section. It works with simple structure like reading only one profile but as soon as I have a list of profiles it fails with an error: "Unknown element "profile"". Can anyone tell me what am I doing wrong?
Here`s part of my app.config:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="DTester.Properties.ProfileSection" type="DTester.Settings.ProfileSection, DTester"/>
</configSections>
<DTester.Properties.ProfileSection>
<profiles>
<profile site="test1" urlscheme="http" urldomain="localhost">
<dataSource dataSource="test2" databaseName="test1" dbUserName="test1" dbUserPassword="test1" />
<user userName="test" password="test" TOHSoftwareVersion="8" iOSVersion="3" deviceUDID="12312"/>
</profile>
<profile site="test2" urlscheme="http" urldomain="localhost" >
<dataSource dataSource="test2" databaseName="test2" dbUserName="test2" dbUserPassword="test2" />
<user userName="test" password="test" TOHSoftwareVersion="3" iOSVersion="8" deviceUDID="123122"/>
</profile>
</profiles>
</DTester.Properties.ProfileSection>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
and here are my classes
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
namespace DTester.Settings
{
public class Profile : ConfigurationElement
{
[ConfigurationProperty("profile")]
public ProfileElem profile
{
get
{
return this["profile"] as ProfileElem;
}
set
{
this["profile"] = value;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
namespace DTester.Settings
{
[ConfigurationCollection(typeof(ProfileSection))]
public class ProfileCollection : ConfigurationElementCollection
{
public Profile this[int index]
{
get
{
return base.BaseGet(index) as Profile;
}
}
protected override ConfigurationElement CreateNewElement()
{
return new Profile();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((Profile)(element)).profile.site;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
namespace DTester.Settings
{
public class ProfileElem : ConfigurationElement
{
[ConfigurationProperty("site", IsRequired = true)]
public string site
{
get
{
return this["site"] as string;
}
set
{
this["site"] = value;
}
}
[ConfigurationProperty("urlscheme", IsRequired = true)]
public string urlscheme
{
get
{
return this["urlscheme"] as string;
}
set
{
this["urlscheme"] = value;
}
}
[ConfigurationProperty("urldomain", IsRequired = true)]
public string urldomain
{
get
{
return this["urldomain"] as string;
}
set
{
this["urldomain"] = value;
}
}
[ConfigurationProperty("dataSource", IsRequired = true)]
public DataSource dataSource
{
get
{
return this["dataSource"] as DataSource;
}
set
{
this["dataSource"] = value;
}
}
[ConfigurationProperty("user", IsRequired = true)]
public UserConfig user
{
get
{
return this["user"] as UserConfig;
}
set
{
this["user"] = value;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
namespace DTester.Settings
{
public class DataSource : ConfigurationElement
{
[ConfigurationProperty("dataSource", IsRequired = true)]
public string dataSource
{
get
{
return this["dataSource"] as string;
}
set
{
this["dataSource"] = value;
}
}
[ConfigurationProperty("databaseName", IsRequired = true)]
public string databaseName
{
get
{
return this["databaseName"] as string;
}
set
{
this["databaseName"] = value;
}
}
[ConfigurationProperty("dbUserName", IsRequired = true)]
public string dbUserName
{
get
{
return this["dbUserName"] as string;
}
set
{
this["dbUserName"] = value;
}
}
[ConfigurationProperty("dbUserPassword", IsRequired = true)]
public string dbUserPassword
{
get
{
return this["dbUserPassword"] as string;
}
set
{
this["dbUserPassword"] = value;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
namespace DTester.Settings
{
public class UserConfig : ConfigurationElement
{
[ConfigurationProperty("userName", IsRequired = true)]
public string userName
{
get
{
return this["userName"] as string;
}
set
{
this["userName"] = value;
}
}
[ConfigurationProperty("password", IsRequired = true)]
public string password
{
get
{
return this["password"] as string;
}
set
{
this["password"] = value;
}
}
[ConfigurationProperty("TOHSoftwareVersion", IsRequired = true)]
public string TOHSoftwareVersion
{
get
{
return this["TOHSoftwareVersion"] as string;
}
set
{
this["TOHSoftwareVersion"] = value;
}
}
[ConfigurationProperty("iOSVersion", IsRequired = true)]
public string iOSVersion
{
get
{
return this["iOSVersion"] as string;
}
set
{
this["iOSVersion"] = value;
}
}
[ConfigurationProperty("deviceUDID", IsRequired = true)]
public string deviceUDID
{
get
{
return this["deviceUDID"] as string;
}
set
{
this["deviceUDID"] = value;
}
}
}
}

I used the this tool to get the respose https://nconfiggen.codeplex.com/wikipage?title=Example2&referringTitle=Home
Here`s the modified configuration section:
<DTesterConfiguration>
<option cmpResWithOacis="true" valRecentRosterPat="false" maxPatCount="1" maxResCount="3" maxDetCount="3" />
<profiles defaultProfile="test1">
<profile site="test1" urlscheme="http" urldomain="localhost">
<dataSource dataSource="test2" databaseName="test1" dbUserName="test1" dbUserPassword="test1" />
<user userName="test" password="test" TOHSoftwareVersion="dfdf" iOSVersion="dfdf" deviceUDID="dfdf"/>
</profile>
<profile site="test2" urlscheme="http" urldomain="localhost" >
<dataSource dataSource="test2" databaseName="test2" dbUserName="test2" dbUserPassword="test2" />
<user userName="test" password="test" TOHSoftwareVersion="dfdf" iOSVersion="dfdf" deviceUDID="dfdfdf"/>
</profile>
</profiles>
</DTesterConfiguration>
and here is the code:
public sealed class DTesterConfiguration
{
private static DTesterConfigurationSection _config;
static DTesterConfiguration()
{
_config = ((DTesterConfigurationSection)(global::System.Configuration.ConfigurationManager.GetSection("DTesterConfiguration")));
}
private DTesterConfiguration()
{
}
public static DTesterConfigurationSection Config
{
get
{
return _config;
}
}
}
public sealed partial class DTesterConfigurationSection : System.Configuration.ConfigurationSection
{
[System.Configuration.ConfigurationPropertyAttribute("profiles")]
[System.Configuration.ConfigurationCollectionAttribute(typeof(ProfilesElementCollection.ProfileElement), AddItemName = "profile")]
public ProfilesElementCollection Profiles
{
get
{
return ((ProfilesElementCollection)(this["profiles"]));
}
}
[System.Configuration.ConfigurationPropertyAttribute("option")]
//[System.Configuration.ConfigurationCollectionAttribute(typeof(OptionElement), AddItemName = "option")]
public OptionElement Option
{
get
{
return ((OptionElement)(this["option"]));
}
}
//<option cmpResWithOacis="true" valRecentRosterPat="false" maxPatCount="10" maxResCount="3" maxDetCount="3" />
public sealed partial class OptionElement : System.Configuration.ConfigurationElement
{
[System.Configuration.ConfigurationPropertyAttribute("cmpResWithOacis", IsRequired = true)]
public bool CmpResWithOacis
{
get
{
return ((bool)(this["cmpResWithOacis"]));
}
set
{
this["cmpResWithOacis"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("valRecentRosterPat", IsRequired = true)]
public bool ValRecentRosterPat
{
get
{
return ((bool)(this["valRecentRosterPat"]));
}
set
{
this["valRecentRosterPat"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("maxPatCount", IsRequired = true)]
public long MaxPatCount
{
get
{
return ((long)(this["maxPatCount"]));
}
set
{
this["maxPatCount"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("maxResCount", IsRequired = true)]
public long MaxResCount
{
get
{
return ((long)(this["maxResCount"]));
}
set
{
this["maxResCount"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("maxDetCount", IsRequired = true)]
public long MaxDetCount
{
get
{
return ((long)(this["maxDetCount"]));
}
set
{
this["maxDetCount"] = value;
}
}
}
public sealed partial class ProfilesElementCollection : System.Configuration.ConfigurationElementCollection
{
[System.Configuration.ConfigurationPropertyAttribute("defaultProfile", IsRequired = true)]
public string DefaultProfile
{
get
{
return ((string)(this["defaultProfile"]));
}
set
{
this["defaultProfile"] = value;
}
}
public ProfileElement this[int i]
{
get
{
return ((ProfileElement)(this.BaseGet(i)));
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new ProfileElement();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((ProfileElement)(element)).Site;
}
public sealed partial class ProfileElement : System.Configuration.ConfigurationElement
{
[System.Configuration.ConfigurationPropertyAttribute("site", IsRequired = true)]
public string Site
{
get
{
return ((string)(this["site"]));
}
set
{
this["site"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("urlscheme", IsRequired = true)]
public string Urlscheme
{
get
{
return ((string)(this["urlscheme"]));
}
set
{
this["urlscheme"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("urldomain", IsRequired = true)]
public string Urldomain
{
get
{
return ((string)(this["urldomain"]));
}
set
{
this["urldomain"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("dataSource")]
public DataSourceElement DataSource
{
get
{
return ((DataSourceElement)(this["dataSource"]));
}
}
[System.Configuration.ConfigurationPropertyAttribute("user")]
public UserElement User
{
get
{
return ((UserElement)(this["user"]));
}
}
public sealed partial class DataSourceElement : System.Configuration.ConfigurationElement
{
[System.Configuration.ConfigurationPropertyAttribute("dataSource", IsRequired = true)]
public string DataSource
{
get
{
return ((string)(this["dataSource"]));
}
set
{
this["dataSource"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("databaseName", IsRequired = true)]
public string DatabaseName
{
get
{
return ((string)(this["databaseName"]));
}
set
{
this["databaseName"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("dbUserName", IsRequired = true)]
public string DbUserName
{
get
{
return ((string)(this["dbUserName"]));
}
set
{
this["dbUserName"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("dbUserPassword", IsRequired = true)]
public string DbUserPassword
{
get
{
return ((string)(this["dbUserPassword"]));
}
set
{
this["dbUserPassword"] = value;
}
}
}
public sealed partial class UserElement : System.Configuration.ConfigurationElement
{
[System.Configuration.ConfigurationPropertyAttribute("userName", IsRequired = true)]
public string UserName
{
get
{
return ((string)(this["userName"]));
}
set
{
this["userName"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("password", IsRequired = true)]
public string Password
{
get
{
return ((string)(this["password"]));
}
set
{
this["password"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("TOHSoftwareVersion", IsRequired = true)]
public string TOHSoftwareVersion
{
get
{
return ((string)(this["TOHSoftwareVersion"]));
}
set
{
this["TOHSoftwareVersion"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("iOSVersion", IsRequired = true)]
public string IOSVersion
{
get
{
return ((string)(this["iOSVersion"]));
}
set
{
this["iOSVersion"] = value;
}
}
[System.Configuration.ConfigurationPropertyAttribute("deviceUDID", IsRequired = true)]
public string DeviceUDID
{
get
{
return ((string)(this["deviceUDID"]));
}
set
{
this["deviceUDID"] = value;
}
}
}
}
}
}

Related

Custom configuration section in app.config -> Unrecognized element 'add'

So, I'm trying to make a custom configuration section for my app.config that will process the following pattern:
<domainSolutionSection>
<domainSolutionGroups>
<Group groupname="Legacy">
<add name="Old App #1"/>
<add name="Old App #2" />
</Group>
<Group groupname="Modern">
<add name="New App #1" />
<add name="New App #2" />
<add name="New App #3" />
</Group>
</domainSolutionGroups>
</domainSolutionSection>
I've spent all day trying to get this to work.
Right now, I'm getting an error:
System.Configuration.ConfigurationErrorsException: Unrecognized element 'add'.
Here are the classes in my DomainSolutionSection library:
public class DomainSolutionSection : ConfigurationSection
{
[ConfigurationProperty("domainSolutionGroups")]
public DomainSolutionGroupCollection DomainSolutionGroups
{
get
{
return (DomainSolutionGroupCollection) this["domainSolutionGroups"];
}
set
{
this["domainSolutionGroups"] = value;
}
}
}
[ConfigurationCollection(typeof(GroupConfigElement))]
public class DomainSolutionGroupCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new GroupConfigElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((GroupConfigElement)element).GroupName;
}
protected override string ElementName
{
get { return "Group"; }
}
protected override bool IsElementName(string elementName)
{
return !String.IsNullOrEmpty(elementName) && elementName == "Group";
}
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMap;
}
}
public GroupConfigElement this[int index]
{
get
{
return base.BaseGet(index) as GroupConfigElement;
}
}
public new GroupConfigElement this[string key]
{
get
{
return base.BaseGet(key) as GroupConfigElement;
}
}
}
public class GroupConfigElement : ConfigurationElement
{
[ConfigurationProperty("groupname", IsRequired = true, IsKey = true)]
public string GroupName
{
get { return (string)this["groupname"]; }
set { this["groupname"] = value; }
}
public PhraseCollection Phrases
{
get { return (PhraseCollection) base["Groups"]; }
}
}
[ConfigurationCollection(typeof(PhraseConfigElement), AddItemName = "add", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class PhraseCollection: ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new PhraseConfigElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((PhraseConfigElement)element).Name;
}
}
public class PhraseConfigElement: ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
}
Not finding any examples out there where "add" properties are used at this level of nesting, so obviously, I haven't "wired-up" the "Group" properly. Can anybody offer any guidance?
Thanks!
Apologies that this is not a direct answer to your question. I don't have the time to break down what you have done, but here is a similar example of something that I have done in the past, and which works. Perhaps there's something in here to help.
myconfig.config:
<?xml version="1.0"?>
<myconfig>
<moduleIPAccessRules>
<allowRules>
<add module="ModuleA" subnetIP="172.16.0.0" subnetMask="255.255.0.0" name="ModuleA intranet users" />
<add module="ModuleA" subnetIP="127.0.0.0" subnetMask="255.255.0.0" name="ModuleA local box" />
<add module="ModuleB" subnetIP="172.16.0.0" subnetMask="255.255.0.0" name="ModuleB intranet users" />
<add module="ModuleB" subnetIP="127.0.0.0" subnetMask="255.255.0.0" name="ModuleB local box" />
<add module="ModuleB" subnetIP="123.45.67.89" subnetMask="255.255.255.255" name="some remote machine" />
</allowRules>
</moduleIPAccessRules>
</myconfig>
Backing class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
namespace Myproject.Configuration
{
public class IPAccessSection : ConfigurationSection
{
public static IPAccessSection GetConfig()
{
return ConfigurationManager.GetSection("myconfig/moduleIPAccessRules") as IPAccessSection;
}
[ConfigurationProperty("allowRules")]
public AllowRuleCollection AllowRules
{
get { return this["allowRules"] as AllowRuleCollection; }
}
}
public class AllowRuleCollection : ConfigurationElementCollection
{
public AllowRule this[int index]
{
get
{
return base.BaseGet(index) as AllowRule;
}
set
{
if (base.BaseGet(index) != null)
base.BaseRemoveAt(index);
this.BaseAdd(index, value);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new AllowRule();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((AllowRule)element).Name;
}
}
public class AllowRule : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get { return this["name"] as string; }
}
[ConfigurationProperty("module", IsRequired = true)]
public string Module
{
get { return this["module"] as string; }
}
[ConfigurationProperty("subnetIP", IsRequired = true)]
public string SubnetIP
{
get { return this["subnetIP"] as string; }
}
[ConfigurationProperty("subnetMask", IsRequired = true)]
public string SubnetMask
{
get { return this["subnetMask"] as string; }
}
}
}
Actually, I just figured out the answer about 10 minutes ago. And it's basically that I hadn't really "hooked up" the PhraseCollection to the GroupConfigElement properly... nor had I fully fleshed-out the PhraseCollection.:
public class GroupConfigElement : ConfigurationElement
{
[ConfigurationProperty("groupname", IsRequired = true, IsKey = true)]
public string GroupName
{
get { return (string)this["groupname"]; }
set { this["groupname"] = value; }
}
[ConfigurationProperty("", IsDefaultCollection = true, IsRequired = true)]
public PhraseCollection Phrases
{
get { return (PhraseCollection) base[""]; }
}
}
[ConfigurationCollection(typeof(PhraseConfigElement))]
public class PhraseCollection: ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new PhraseConfigElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((PhraseConfigElement)element).Name;
}
public PhraseConfigElement this[int index]
{
get
{
return base.BaseGet(index) as PhraseConfigElement;
}
}
public new PhraseConfigElement this[string key]
{
get
{
return base.BaseGet(key) as PhraseConfigElement;
}
}
}
public class PhraseConfigElement: ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
}
}
The key fixes were to the "Phrases" definition... and then I had to add those two public methods to the "PhraseCollection" definition.
Thanks!

Entry has already been added error even though IsKey is false

I am getting Entry has already been added error when trying to use same title for SubModule. It is happening even though IsKey = false but still it is not allowing to enter duplicate Upload as Title
How can I fix this issue?
Here's my web.config
<SiteModules>
<Modules>
<MainModule title="MyUpload">
<SubModule title="Upload" page="/script/upload1" groups="group1" display="true" type="maker"></SubModule>
<SubModule title="Upload" page="/script/upload2" groups="group2" display="true" type="checker"></SubModule>
<SubModule title="SomeTitle1" page="/script/upload3" groups="group1" display="false"></SubModule>
</MainModule>
</Modules>
</SiteModules>
Here's my class
namespace MyClasses
{
public class SiteModules : ConfigurationSection
{
[ConfigurationProperty("Modules", IsDefaultCollection = false)]
public Modules Modules
{
get
{
Modules modulesConfigElement = (Modules)base["Modules"];
return modulesConfigElement;
}
}
}
public class Modules : ConfigurationElementCollection
{
public Modules()
{
AddElementName = "MainModule";
}
protected override ConfigurationElement CreateNewElement()
{
return new MainModule();
}
protected override Object GetElementKey(ConfigurationElement element)
{
return ((MainModule)element).Title;
}
}
public class MainModule : ConfigurationElementCollection
{
public MainModule()
{
AddElementName = "SubModule";
}
[ConfigurationProperty("title", IsRequired = true, IsKey = false)]
public string Title
{
get
{
return (string)this["title"];
}
set
{
this["title"] = value;
}
}
protected override ConfigurationElement CreateNewElement()
{
return new SubModule();
}
protected override Object GetElementKey(ConfigurationElement element)
{
return ((SubModule)element).Title;
}
}
public class SubModule : ConfigurationElement
{
[ConfigurationProperty("title", IsRequired = true, IsKey = false)]
public string Title
{
get
{
return (string)this["title"];
}
set
{
this["title"] = value;
}
}
[ConfigurationProperty("page", IsRequired = true)]
public string Page
{
get
{
return (string)this["page"];
}
set
{
this["page"] = value;
}
}
[ConfigurationProperty("groups", IsRequired = true)]
public string Groups
{
get
{
return (string)this["groups"];
}
set
{
this["groups"] = value;
}
}
[ConfigurationProperty("display", IsRequired = true)]
public string Display
{
get
{
return (string)this["display"];
}
set
{
this["display"] = value;
}
}
[ConfigurationProperty("type", IsRequired = false)]
public string Type
{
get
{
return (string)this["type"];
}
set
{
this["type"] = value;
}
}
}
}
The code which is throwing error is this:
SiteModules siteModules = (SiteModules)ConfigurationManager.GetSection("SiteModules");
Exception not related to IsKey attribute. Look on overrided method GetelementKey. In given case it return Title.. which is not unique.
protected override Object GetElementKey(ConfigurationElement element)
{
return ((MainModule)element).Title;
}

Custom web.config section not saving

I have implemented custom section in web.config and want to save data there, in runtime debug when you check it contains all values that you put there and save without any exception. But web.config file didn't get updated at all.
I have following custom section in web.config
public class PrintersSection : ConfigurationSection
{
[ConfigurationProperty("PrintForm", Options = ConfigurationPropertyOptions.IsRequired)]
public PrintFormElement PrintForm
{
get
{
return (PrintFormElement)this["PrintForm"];
}
set { this["PrintForm"] = value; }
}
[ConfigurationProperty("Printers", Options = ConfigurationPropertyOptions.IsRequired)]
public PrintersCollection Printers
{
get
{
return (PrintersCollection)this["Printers"];
}
set { this["Printers"] = value; }
}
public override bool IsReadOnly()
{
return false;
}
}
public class PrintFormElement : ConfigurationElement
{
[ConfigurationProperty("xmlPath")]
public string XmlPath
{
get
{
return (string)base["xmlPath"];
}
set { base["xmlPath"] = value; }
}
[ConfigurationProperty("formName")]
public string FormName
{
get
{
return (string)base["formName"];
}
set { base["formName"] = value; }
}
[ConfigurationProperty("sdateFormat")]
public string SDateFormat
{
get
{
return (string)base["sdateFormat"];
}
set { base["sdateFormat"] = value; }
}
[ConfigurationProperty("createOnTechpadMarkAsComplete")]
public bool CreateOnTechpadMarkAsComplete
{
get
{
return (bool)base["createOnTechpadMarkAsComplete"];
}
set { base["createOnTechpadMarkAsComplete"] = value; }
}
[ConfigurationProperty("createOnSurveySubmit")]
public bool CreateOnSurveySubmit
{
get
{
return (bool)base["createOnSurveySubmit"];
}
set { base["createOnSurveySubmit"] = value; }
}
public override bool IsReadOnly()
{
return false;
}
}
[ConfigurationCollection(typeof(PrinterElement), AddItemName = "printer", CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)]
public class PrintersCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new PrinterElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
if (element == null)
throw new ArgumentNullException("element");
return ((PrinterElement)element).Location;
}
[ConfigurationProperty("default", IsRequired = false)]
public string Default
{
get
{
return (string)base["default"];
}
set { base["default"] = value; }
}
public new PrinterElement this[string location]
{
get { return base.BaseGet(location) as PrinterElement; }
}
public void Add(PrinterElement element)
{
base.BaseAdd(element);
}
public void Clear()
{
base.BaseClear();
}
public override bool IsReadOnly()
{
return false;
}
}
public class PrinterElement : ConfigurationElement
{
[ConfigurationProperty("location", IsRequired = true, IsKey = true)]
public string Location
{
get
{
return (string)base["location"];
}
set { base["location"] = value; }
}
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return (string)base["name"];
}
set { base["name"] = value; }
}
public override bool IsReadOnly()
{
return false;
}
}
Here how it looks in web.config:
<printers>
<PrintForm xmlPath="H:\Temp\print3.txt" formName="test-form"
sdateFormat="MM-dd-yyyy" createOnTechpadMarkAsComplete="true"
createOnSurveySubmit="true" />
<Printers default="PrinterA">
<clear />
<printer location="1" name="PrinterA" />
<printer location="2" name="PrinterB" />
</Printers>
</printers>
This is how I editing it:
webConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
var printXmlConfig = (PrintersSection)ConfigurationManager.GetSection("printers");
printXmlConfig.PrintForm.XmlPath = model.PrintXMLPath;
printXmlConfig.PrintForm.FormName = model.PrintXMLFormName;
printXmlConfig.Printers.Default = model.PrintXMLPrinterName;
printXmlConfig.PrintForm.SDateFormat = model.PrintXMLSDateFormat;
printXmlConfig.PrintForm.CreateOnTechpadMarkAsComplete = model.PrintXMLCreateOnTechpadMarkAsComplete;
printXmlConfig.PrintForm.CreateOnSurveySubmit = model.PrintXMLCreateOnSurveySubmit;
printXmlConfig.Printers.Clear();
model.PrinterPerLocation.ForEach(p => printXmlConfig.Printers.Add(new PrinterElement { Location = p.Key, Name = p.Value}));
webConfig.Save();
But nothing updates in web.config, what I am doing wrong here?
Try
printXmlConfig.SectionInformation.ForceSave = true;
or
webConfig.SectionInformation.ForceSave = true;
before
webConfig.Save(ConfigurationSaveMode.Full);

Cannot define more than one section in web.config

I want to have multiple sections in sectiongroup like this
**<CredentialsGroup>
<Credentials>
<company name="Carolina" userid="abc" password="dd"></company>
<file name="dfbf0f94-767e-4c71-b4ee-2dc05fb76e3c.csv"
url="https://e.brightree.net/Home/file.csv"></file>
<company name="Asbury" userid="abc" password="dde"></company>
<file name="dfbf0f94-767e-4c71-b4ee-2dc05fb76e3c.csv"
url="https://e.brightree.net/Home/file.csv"></file>
</Credentials>
</CredentialsGroup>**
and this is my customconfig File
**public class CredentialsSection: ConfigurationSection
{
[ConfigurationProperty("company",IsRequired=true)]
public CompanyElement Company
{
get {
return (CompanyElement)this["company"];
}
set
{
this["company"] = value;
}
}
[ConfigurationProperty("file",IsRequired=true)]
public FileElement File
{
get
{
return (FileElement)this["file"];
}
set
{
this["file"] = value;
}
}
}
public class CompanyElement : ConfigurationElement
{
[ConfigurationProperty("name",IsRequired=true)]
public string Name
{
get {
return (string)this["name"];
}
set
{
this["name"] = value;
}
}
[ConfigurationProperty("userid", IsRequired = true)]
public string UserId
{
get
{
return (string)this["userid"];
}
set
{
this["userid"] = value;
}
}
[ConfigurationProperty("password", IsRequired = true)]
public string Password
{
get
{
return (string)this["password"];
}
set
{
this["password"] = value;
}
}
}
public class FileElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return (string)this["name"];
}
set
{
this["name"] = value;
}
}
[ConfigurationProperty("url",IsRequired=true)]
public string Url
{
get
{
return (string)this["url"];
}
set {
this["url"] = value;
}
}
}**
Company and File node shoukd be siblings and their selection will be conditional based on company name like this
ConfigurationManager.GetSection("CredentialsGroup/Credentials/company['name']=" + companyName);
Please Help

How to get some elements from app.config in C#?

Based on my app.config I would like to be able to get the elements of columns as shown in the example below in lines 3-5. How should I write the code in order to achieve this. If I'll need to change my app.config - I'll do it.
1. var bounceProviders = ConfigurationManager.GetSection("BounceProviders") as BounceProvidersSection;
2. var providerColumns = bounceProviders.Providers[0].Columns;
3. var emailColumn = providerColumns.Email;
4. var dateColumn = providerColumns.Date;
5. var messageColumn = providerColumns.Message;
app.config
<BounceProviders>
<Providers>
<Provider Name="p1">
<Columns>
<Email Name="My Email" />
<Date Name="My Date" />
<Message Name="My Message" />
</Columns>
</Provider>
<Provider Name="p2">
<Columns />
</Provider>
</Providers>
</BounceProviders>
ConfigurationSection
public class BounceProvidersSection : ConfigurationSection
{
[ConfigurationCollection(typeof(ConfigCollection<BounceProviderConfig>), AddItemName = "Provider")]
[ConfigurationProperty("Providers", IsRequired = true)]
public ConfigCollection<BounceProviderConfig> Providers
{
get { return (ConfigCollection<BounceProviderConfig>)this["Providers"]; }
set { this["Providers"] = value; }
}
}
public class BounceProviderConfig : ConfigurationElement
{
[ConfigurationProperty("Name", IsRequired = true)]
public string Name
{
get { return (string)this["Name"]; }
set { this["Name"] = value; }
}
}
ConfigCollection
public class ConfigCollection<T> : ConfigurationElementCollection
where T : ConfigurationElement, new()
{
protected override ConfigurationElement CreateNewElement()
{
return new T();
}
protected override object GetElementKey( ConfigurationElement element )
{
return element.GetHashCode();
}
public T this[int index]
{
get
{
return ( T )BaseGet( index );
}
set
{
if ( BaseGet( index ) != null )
{
BaseRemoveAt( index );
}
BaseAdd( index, value );
}
}
new public T this[string Name]
{
get
{
return ( T )BaseGet( Name );
}
}
}
sdf
I figured it out
public class BounceProvidersSection : ConfigurationSection
{
[ConfigurationCollection(typeof(ConfigCollection<BounceProviderConfig>), AddItemName = "Provider")]
[ConfigurationProperty("Providers", IsRequired = true)]
public ConfigCollection<BounceProviderConfig> Providers
{
get { return (ConfigCollection<BounceProviderConfig>)this["Providers"]; }
set { this["Providers"] = value; }
}
}
public class BounceProviderConfig : ConfigurationElement
{
[ConfigurationProperty("Id", IsRequired = true)]
public int Id
{
get { return (int)this["Id"]; }
set { this["Id"] = value; }
}
[ConfigurationProperty("Columns", IsRequired = false)]
public BounceProviderColumns Columns
{
get { return (BounceProviderColumns)this["Columns"]; }
set { this["Columns"] = value; }
}
public static BounceProviderConfig GetByProviderId(int providerId)
{
var section = ConfigUtils.GetConfigurationSection<BounceProvidersSection>("BounceProviders");
foreach (BounceProviderConfig provider in section.Providers)
{
if (provider.Id == providerId)
return provider;
}
return null;
}
}
public class BounceProviderColumns : ConfigurationElement
{
[ConfigurationProperty("Email", IsRequired = true)]
public ColumnConfig Email
{
get { return (ColumnConfig)this["Email"]; }
set { this["Email"] = value; }
}
[ConfigurationProperty("Date", IsRequired = true)]
public DateColumnConfig Date
{
get { return (DateColumnConfig)this["Date"]; }
set { this["Date"] = value; }
}
[ConfigurationProperty("Message", IsRequired = true)]
public ColumnConfig Message
{
get { return (ColumnConfig)this["Message"]; }
set { this["Message"] = value; }
}
}
public class ColumnConfig : ConfigurationElement
{
[ConfigurationProperty("Name", IsRequired = true)]
public string Name
{
get { return (string)this["Name"]; }
set { this["Name"] = value; }
}
}

Categories