I want a configuration section that looks like this:
<MailMessage>
<from value="me#you.com" />
<subject value ="Subject goes here" />
<body value="Hello. You've got mail!" />
</MailMessage>
And I have implemented the classes like in the second answer of this link:
How to implement a ConfigurationSection with a ConfigurationElementCollection
Now for me the elements of MailMessage section are not a collection but this should not be a problem but I receive the error when I try to access the property:
Unrecognized element 'from'
I get the section with the code:
private static MailMessageSection emailSection = ConfigurationManager.GetSection("MailMessage") as MailMessageSection;
Here is the implementation of the elements:
public class MailMessageSection : ConfigurationSection
{
[ConfigurationProperty("from")]
public FromElement From
{
get { return base["from"] as FromElement; }
}
[ConfigurationProperty("subject")]
public SubjectElement Subject
{
get { return base["subject"] as SubjectElement; }
}
[ConfigurationProperty("body")]
public BodyElement Body
{
get { return base["body"] as BodyElement; }
}
}
public class FromElement : ConfigurationElement
{
[ConfigurationProperty("value")]
public string From
{
get { return base["value"] as string; }
}
}
public class SubjectElement : ConfigurationElement
{
[ConfigurationProperty("value")]
public string Subject
{
get { return base["value"] as string; }
}
}
public class BodyElement : ConfigurationElement
{
[ConfigurationProperty("value")]
public string Body
{
get { return base["value"] as string; }
}
}
Any ideas what could be wrong? Thanks for your time!
Looking for error is serializable classes can be frustrating. I suggest you to use the auto generate functionalities in VisualStudio. Here is how you do it (very simple):
1. Copy the XML example (to the clipboard)
2. Create new class for the XML ("MailMessageSection" in your case)
3. In VS go to Edit > Paste Special > Paste XML As Classes
I know this is not exactly the reason why the from is not working, but using auto generated code is much better practice then write it on your own.
Hope it helps...
id didnt find anything on Stackoverflow or on the internet, im sorry if this question was already posted (or if its simply impossible).
Is there a way to change the default value of a *.settigs-property, for example if i have the setting "USER"
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("TESTUSER")]
public string SQLServer {
get {
return ((string)(this["USER"]));
}
set {
this["USER"] = value;
}
}
would there be a way to change (at runtime) the DefaultSettingValueAttribute ("TESTUSER") to another value (i.e: "John Doe").
Thanks in advance
You can override the Properties property of the ApplicationSettingsBase class:
public override SettingsPropertyCollection Properties
{
get
{
var properties = base.Properties;
properties["SQLServer"].DefaultValue =
String.Format("John Doe {0}", DateTime.Now);
return properties;
}
}
Consider the following configuration group in a .NET .config file.
<MySettingsGroup enabled="true">
<MySettingsSection enabled="true">
</MySettingsSection>
</MySettingsGroup>
The supporting classes are:
public class MySettingsConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("enabled", DefaultValue = true, IsRequired = false)]
public bool Enabled
{
get
{
// works fine
return Convert.ToBoolean(this["enabled"]);
}
}
public class MySettingsConfigurationGroup : ConfigurationSectionGroup
{
[ConfigurationProperty("enabled", DefaultValue = true, IsRequired = false)]
public bool Enabled
{
get
{
// the way to retrieve attributes in sections is not supported by groups
// return Convert.ToBoolean(this["enabled"]);
return true;
}
}
How can the Enabled property on the MySettingsConfigurationGroup be implemented?
I don't think section groups were designed to be customized in the way you're attempting. A better solution would be to simply define your own configuration section that itself contains other configurations and omit the use of a section group altogether. Then, you'd get the full flexibility that configuration sections offer.
I have an application which i have some configuration files for cache, queue, and database.
public class ServerConfiguration: ConfigurationSection
{
[ ConfigurationProperty( FOO, DefaultValue = "", IsRequired = false ) ]
public string FOO
{
get { return (string)this[FOO]; }
set { this[FOO] = value; }
}
}
this is what i do for config files and I also have some inheritance hierarchy.
What do you use to handle configurations and what are some best practices for this purpose?
I love and use the Microsoft configuration library extensively but I try to make sure that my applications are not dependent on it. This usually involves having my configuration section implement an interface, so your example would look like:
public class ServerConfiguration : ConfigurationSection, IServerConfiguration
{
[ ConfigurationProperty( FOO, DefaultValue = "", IsRequired = false ) ]
public string FOO
{
get { return (string)this[FOO]; }
set { this[FOO] = value; }
}
}
public interface IServerConfiguration
{
public string FOO { get; } //Unless I am updating the config in code I don't use set on the interface
}
Now where ever you use your configuration in your code you only need to worry about IServerConfiguration and you can change your implementation without having to change the usages. Sometimes I just start of with a hard coded class during development and only change it to a configuration section when I actually need to have different values in different environments.
If you are using a configuration section you are also dependent on the ConfigurationManager. I have hidden this from my code by using an IConfigurationProvider[T] where T would be IServerConfiguration, you can see an example of this on my blog under configuration ignorance.
http://bronumski.blogspot.com/search/label/Configuration
Helo
Can anybody explain me how to get configuration element from .config file.
I know how to handle attributes but not elements. As example, I want to parse following:
<MySection enabled="true">
<header><![CDATA[ <div> .... </div> ]]></header>
<title> .... </title>
</MySection>
My c# code looks like this so far:
public class MyConfiguration : ConfigurationSection
{
[ConfigurationProperty("enabled", DefaultValue = "true")]
public bool Enabled
{
get { return this["enabled"].ToString().ToLower() == "true" ? true : false; }
}
[ConfigurationProperty("header")]
public string header
{
???
}
}
It works with attributes, how do I do with elements (header property in above code) ?
There is another approach for doing the same thing.
We could create an element by overriding DeserializeElement method to get string value:
public class EmailTextElement : ConfigurationElement {
public string Value { get; private set; }
protected override void DeserializeElement(XmlReader reader, bool s) {
Value = reader.ReadElementContentAs(typeof(string), null) as string;
}
}
Here's a pretty good custom config section designer tool you can use (and it's free):
Configuration Section Designer
EDIT:
I was looking into MSDN and it seems that custom config sections can't do what you want, ie. getting the config value from an element. Custom config elements can contain other config elements, but the config values always come from attributes.
Maybe you can put your html snippets into other files and refer to them from the config, like this.
<MySection enabled="true">
<header filename="myheader.txt" />
<title filename="mytitle.txt" />
</MySection>
Inherit the ConfigurationElement class and override its deserialize method. Use the new class to represent elements with text content.
http://www.codeproject.com/KB/XML/ConfigurationTextElement.aspx
Working with your example, you are going to override the Deserialization of "header" in the ConfigurationElement to get the CDATA value.
<MySection enabled="true">
<header name="foo"><![CDATA[ <div> .... </div> ]]></header>
<title> .... </title>
</MySection>
public sealed class HeaderSection: ConfigurationElement {
private string __Name, __CDATA;
[ConfigurationProperty("name", IsRequired = true)]
public string Name {
get {
return this.__Name;
}
set {
this.__Name = value;
}
}
[ConfigurationProperty("value", IsRequired = true)]
public string Value {
get {
return this.__CDATA;
}
set {
this.__CDATA = value;
}
}
protected override void DeserializeElement(System.Xml.XmlReader reader, bool s) {
this.Name = reader.GetAttribute("name").Trim();
string cdata = reader.ReadElementContentAs(typeof(string), null) as string;
this.Value = cdata.Trim();
}
}
You can use the ConfigurationManager.GetSection("SectionName") method for getting the configuration section in the config files.
I finally found one way to do it.
There is IConfigurationSectionHandler interface that allows for things I want. It requires the one to write the method
public object Create(object parent, object configContext, XmlNode section)
After it, u parse section on your own so I was able to fetch XmlElement's without a problem:
header = s["header"] != null ? s["header"].InnerText : String.Empty;
title = s["title"] != null ? s["title"].InnerText : String.Empty;
The down side of this is that interface is outdated but MSDN states that it will not be removed from future versions of the frameworks as it is used internally.
You can create a class that inherits from System.Configuration.ConfigurationElement that represents an element in your configuration section.
There's a simple example in the MSDN documentation for ConfigurationElement.
According to MSDN, in .NET 4 there's a new CurrentConfiguration property which gives you a reference to the top-level Configuration instance that represents the configuration hierarchy that the current ConfigurationElement instance belongs to.