Laden...

CustomSection in App.config definieren?

Erstellt von #coder# vor 13 Jahren Letzter Beitrag vor 12 Jahren 9.108 Views
#coder# Themenstarter:in
395 Beiträge seit 2008
vor 13 Jahren
CustomSection in App.config definieren?

Hallo Leute,

ich möchte in in der App.config ein neue Section Aliase hinzufügen, welche mehrere Alias Items beinhaltet. Nun hab ich es geschaft ein Alias zu definieren und mit einem Handler die Daten auszulesen:


<configuration>
	<configSections>

		<section name="Alias" type="CustomSectionsTest.MyHandler, CustomSectionsTest"/>
	</configSections>

		<Alias Key="Key" Value="Value" />	
		
</configuration>

public class MyHandler : ConfigurationSection
    {
        [ConfigurationProperty("Key")]
        public string Key
        {
            get { return (string) this["Key"]; }
            set { this["Key"] = value; }
        }

        [ConfigurationProperty("Value")]
        public string Value
        {
            get { return (string) this["Value"]; }
            set { this["Value"] = value; }
        }
    }

So wird es aufgerufen:

MyHandler settings = (MyHandler) ConfigurationManager.GetSection("Alias");
            Console.WriteLine(settings.Key);
            Console.WriteLine(settings.Value);

Nun möchte ich aber eine Collection von Aliase definieren:

<Aliase>

<Alias Key="bla" Value="bla" />
<Alias Key="12" Value="34" />
...
</Aliase>

Nun würde ich gern es so aufrufen List<Alias> ... Wie würde dann im Handler das Property aussehen?

6.911 Beiträge seit 2009
vor 13 Jahren

Hallo,

ich will das an einem Beispiel erklären.

Die Konfigurationsdatei:


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<configSections>
		<section name="AliasMappingSection"
				 type="gfoidl.Configuration.AliasMappingSection, ConsoleApplication1" />
	</configSections>
	<AliasMappingSection>
		<mappings>
			<clear />
			<add key="a" value="A" />
			<add key="b" value="B" />
			<add key="c" value="C" />
		</mappings>
	</AliasMappingSection>
</configuration>

Das Demoprogramm:


using System;
using gfoidl.Configuration;

namespace ConsoleApplication1
{
	class Program
	{
		static void Main(string[] args)
		{
			AliasMappingSection config = AliasMappingSection.GetConfig();
			Mappings mappings = config.Mappings;
			Mapping mapping = mappings["a"];

			foreach (Mapping m in mappings)
				Console.WriteLine("{0} -> {1}", m.Key, m.Value);

			Console.ReadKey();
		}
	}
}

Damit ein eigener Konfigurationsabschnitt verwendet werden kann muss dieser definiert werden.

Zuerst definieren wir das Konfigurationselement:


using System.Configuration;

namespace gfoidl.Configuration
{
	public class Mapping : ConfigurationElement
	{
		[ConfigurationProperty("key", IsRequired = true)]
		[StringValidator(
			InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\",
			MinLength = 0,
			MaxLength = 60)]
		public string Key
		{
			get { return this["key"] as string; }
		}
		//---------------------------------------------------------------------
		[ConfigurationProperty("value", IsRequired=true)]
		[StringValidator(
			InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\",
			MinLength = 0,
			MaxLength = 60)]
		public string Value
		{
			get { return this["value"] as string; }
		}
	}
}

Dieses Konfigurationselement soll in einer Auflistung verwendet werden -> daher diese definieren:


using System.Configuration;

namespace gfoidl.Configuration
{
	public class Mappings : ConfigurationElementCollection
	{
		public Mapping this[int index]
		{
			get { return this.BaseGet(index) as Mapping; }
		}
		//---------------------------------------------------------------------
		public new Mapping this[string key]
		{
			get { return this.BaseGet(key) as Mapping; }
		}
		//---------------------------------------------------------------------
		protected override ConfigurationElement CreateNewElement()
		{
			return new Mapping();
		}
		//---------------------------------------------------------------------
		protected override object GetElementKey(ConfigurationElement element)
		{
			return (element as Mapping).Key;
		}
	}
}

Und nun der Konfigurationsabschnitt:


using System.Configuration;

namespace gfoidl.Configuration
{
	public class AliasMappingSection : ConfigurationSection
	{
		public static AliasMappingSection GetConfig()
		{
			return
				ConfigurationManager
				.GetSection("AliasMappingSection") as AliasMappingSection ??
				new AliasMappingSection();
		}
		//---------------------------------------------------------------------
		[ConfigurationProperty("mappings")]
		public Mappings Mappings
		{
			get
			{
				return
					this["mappings"] as Mappings ??
					new Mappings();
			}
		}
	}
}

Angehängt das Demo-Projekt.

mfG Gü

Speedski, Config, Customconfig, Konfiguration, Configuration

Stellt fachliche Fragen bitte im Forum, damit von den Antworten alle profitieren. Daher beantworte ich solche Fragen nicht per PM.

"Alle sagten, das geht nicht! Dann kam einer, der wusste das nicht - und hat's gemacht!"

153 Beiträge seit 2007
vor 12 Jahren

Sehr guter Beitrag, sollte imo in die FAQ verschoben werden 👍

Hinweis von winSharp93 vor 12 Jahren

Ich habe ihn mal unter [Tutorial] Konfigurationsmodell im .NET Framework verlinkt.

Grüße,
Chris

"Wenn Architekten genauso bauen würden, wie Programmierer programmieren, dann würde der erste Specht, der vorbeikommt, die Zivilisation zerstören." (Steven Weinberg)

6.911 Beiträge seit 2009
vor 12 Jahren

Hallo zusammen,

interessant in diesem Zusammenhang ist auch Configuration Section Designer. Ich hab den zwar nicht probiert, aber es schaut nützlich aus.

mfG Gü

Stellt fachliche Fragen bitte im Forum, damit von den Antworten alle profitieren. Daher beantworte ich solche Fragen nicht per PM.

"Alle sagten, das geht nicht! Dann kam einer, der wusste das nicht - und hat's gemacht!"

B
108 Beiträge seit 2006
vor 12 Jahren

Hallo zusammen,

ich habe ein ändliches Problem.

In der App.config wurde bisher die Connections auf eine DB in den app.settings eingetragen. Dies Umfasste ca. 10 einträge. Nun bin ich die Applikation am umschreiben, so dass mehrere Server erfasst werden könnten. Dabei soll folgendes Konstrukt möglich sein.

<Databases>
  <Database1>
     <add key = "a" value = "Hallo">
     <add key = "b" value = "value 2">
     <add key = "c" value = "value 3">
     <add key = "d" value = "value 4">
  </Database1> 
  <Database2>
     <add key = "a" value = "Hallo">
     <add key = "b" value = "value 2">
     <add key = "c" value = "value 3">
     <add key = "d" value = "value 4">
  </Database2> 
</Databases>

dies müsste ich von den appSettings in die CustomSettings wechseln. Doch leider weiss ich jetzt nicht, wie ich die Klasse aussehen muss, damit ich ein solches Konstrukt erstellen und Verwalten kann.

Könnte mir da jemand helfen? müsste ich dazu eine 4. klasse erstellen?

Besten Dank für eure Hilfe

B
108 Beiträge seit 2006
vor 12 Jahren

Hallo zusammen,

Ich habe mich heute den ganzen Tag mit meinem Problem beschäftigt. Die Struktur habe ich nun mal abgeändert um dem codeBeispiel von gfoidl abgeglichen:


<AliasMappingSection>
    <mappingsColl>
		  <mappings name="test">
			  <add key="a" value="A" />
			  <add key="b" value="B" />
			  <add key="c" value="C" />
		  </mappings>
      <mappings name="tezttu">
        <add key="d" value="D" />
        <add key="e" value="E" />
        <add key="f" value="F" />
      </mappings>
    </mappingsColl>
	</AliasMappingSection>

Wie ihr seht habe ich die mappingsColl dazwischen geschoben (was wohl nicht nötig ist, jedoch für mich übersichtlicher war). Der Code für die mappingsColl ist wie folgt:


public class MappingsColl : ConfigurationElementCollection
	{

        protected override ConfigurationElement CreateNewElement()
        {
            return new MappingsColl();
        }
        //---------------------------------------------------------------------
        protected override object GetElementKey(ConfigurationElement element)
        {
            return (element as Mapping).Key;
        }
        [ConfigurationProperty("mappings")]
        public Mappings this[object key]
        {
            get
            {
                return
                    base.BaseGet(key) as Mappings ??
                    new Mappings();
            }
        }
	}

Doch leider bekomme ich nun immer die Fehlermeldung, dass das Element mappings nur einmal vorkommen darf. Jedoch weiss ich nicht, wie ich das anpassen muss. Wenn ich den abschnitt [ConfigurationProperty("mappings")] weglasse, dann kommt der Fehler, Unbekanntes Element "mappings".

Ich glaube etwas Grundlegendes noch nicht verstanden zu haben. Könnte mir da jemand weiter helfen?

EDIT: habe gemerkt, dass die Funktion GetElementKey(ConfigurationElement element) ein bisschen blöde ist, da ich ja kein Element sonder eine ConfigurationElementCollection drin ist. muss mal schauen wie ich dies Ändern kann. Wäre aber trotzdem froh um jeden input.

Grüsse