Windows Azure Cloud Storage ermöglicht es Ihnen bereits ab 0,10€ pro GB/Monat die Vorteile der Cloud zu nutzen.
Willkommen bei dotnet-snippets.de! Snippet hinzufügen Login Registrieren
Snippets in der Datenbank: 1551 | Anzahl registrierter User: 1841 | Besucher online: 3
Hauptmenü
Home
Top Ten
Zufälliger Snippet
FAQs
.NET Community
dotnet-forum.de
dotnet-kicks.de
Social

RSS Feeds
Rss Alle Snippets
Rss C#
Rss VB.NET
Rss C++
Rss ASP.NET
Partner
Member of Microsoft Community Leader/Insider Program (CLIP)

XML-Programmkonfiguration / -Steuerung


Autor: _ntr_
Sprache: C#
Bewertung:
6.41 (4 votes)
Anzahl der Aufrufe: 9742
  
Kick it on dotnet-kicks.de  

Beschreibung:

Mit Hilfe dieser Klasse lassen sich sehr einfach Objekte mit öffentlichen Eigenschaften per XML Datei setzen.
Dies geschieht über Reflection, und kann daher auf jedes Objekt angewandt werden.

Bisher können 4 verschiedene Arten von Eigenschaften gesetzt werden: Color, Font, Enum und String. Durch ein Switch-Case Modell und entsprechende String-Value Konvertierungsmethoden kann dies aber beliebig erweitert werden.

Highlights:
- Es können geschachtelte Properties mittels Punkt getrennt (so wie man es im Code auch verwenden würde) im XML Konfigurationsfile benutzt werden.
- Dies kann zur Runtime angewendet werden
- Es benötigt nur eine Zeile Code bei der Anwendung

Viel Spaß damit, ich freue mich auf Bewertungen,
_ntr_


Abgelegt unter: XML, Konfiguration, Reflection.



C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Drawing;
using System.Reflection;

namespace Snippets_Wettbewerb.XMLConfigReader
{
    /// <summary>
    /// This class reads xml configuration file and will try to translate all xml nodes
    /// into configuration strings. The configuration strings will be used to set public
    /// properties from specified object via runtime and reflection. There are several
    /// ways to define kind of property values (e.g. color-definition).
    /// </summary>
    /// <example>
    /// Following xml configuration:
    /// <?xml version="1.0" encoding="utf-8" ?>
    /// <Config>
    ///   <TestString>This is a string.</TestString>
    ///   <TestColor1 type="rgb">125, 125, 125</TestColor1>
    ///   <TestColor2 type="colorname">White</TestColor2>
    ///   <TestFont type="font">Microsoft Sans Sarif, 10, bold</TestFont>
    /// </Config>
    /// Can be used with objects containing "TestString", "TestColor1", "TestColor2" and "TestFont"
    /// properties with following instruction:
    /// <code>XMLConfigReader.XmlConfigReader.ReadAllConfig("config.xml", this);</code>
    /// </example>
    public class XmlConfigReader
    {
        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="T:BVXmlConfigReader"/> class.
        /// </summary>
        private XmlConfigReader()
        {
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Method which gets all property nodes in xml config file.
        /// </summary>
        /// <param name="p_sXmlFilenamePath">Name and path of xml config file.</param>
        /// <param name="p_sXmlRoot">Xml path root, from where to search properties.</param>
        /// <returns>XmlNodeList of all properties, or null if xml file/rootnode was not found.</returns>
        private static XmlNodeList GetXmlNodes(string p_sXmlFilenamePath, string p_sXmlRoot)
        {
            // check whether xml file exists
            if (System.IO.File.Exists(p_sXmlFilenamePath))
            {
                // local variable
                string sXmlPathRoot = String.Empty;

                // load xml file
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(p_sXmlFilenamePath);

                // create XPath expression
                sXmlPathRoot = CreateXPathExpression(p_sXmlRoot, "*");

                // return selected nodes
                return xmlDoc.SelectNodes(sXmlPathRoot);
            }

            return null;
        }

        /// <summary>
        /// Method which get single xml node from xml config file.
        /// </summary>
        /// <param name="p_sXmlFilenamePath">Name and path of xml config file.</param>
        /// <param name="p_sXmlRoot">Xml path root, from where to search properties.</param>
        /// <param name="p_sNodename">Xml node name which should be received.</param>
        /// <returns>XmlNode of requested property or null if node was not found.</returns>
        private static XmlNode GetSingleXmlNode(string p_sXmlFilenamePath, string p_sXmlRoot, string p_sNodename)
        {
            // check whether file exists
            if (System.IO.File.Exists(p_sXmlFilenamePath))
            {
                // load xml file
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(p_sXmlFilenamePath);

                // create XPath expression
                string sXmlPathRoot = CreateXPathExpression(p_sXmlRoot, p_sNodename);

                // return selected node
                return xmlDoc.DocumentElement.SelectSingleNode(sXmlPathRoot);
            }

            return null;
        }

        /// <summary>
        /// Method which creates xml path expression to find all nodes defined with specified
        /// root node (which don't have to be same like document element node).
        /// </summary>
        /// <param name="p_sXmlRoot">Name of inner root node. May be same like document element node.</param>
        /// <param name="p_sNodename">Define one specific node name where to search.</param>
        /// <returns>XPath Expression pointing to specific root/named node.</returns>
        private static string CreateXPathExpression(string p_sXmlRoot, string p_sNodename)
        {
            // local variable
            string sXmlPathRoot = String.Empty;

            // concat XmlRoot (to search) with XmlPathRoot
            if (p_sXmlRoot != String.Empty)
            {
                sXmlPathRoot = String.Concat(
                    p_sXmlRoot,
                    "/",
                    p_sNodename);
            }
            else
            {
                sXmlPathRoot = String.Concat(
                    "./*/",
                    p_sNodename);
            }
            return sXmlPathRoot;
        }

        /// <summary>
        /// Method which tries to set property from xml node.
        /// </summary>
        /// <param name="node">The xml node.</param>
        private static bool SetPropertyFromXmlNode(XmlNode node, object p_oConcreteInstance)
        {
            // local variables
            string sAttributeType = "default";

            // check if node or object is null
            if ((node == null) || (p_oConcreteInstance == null))
            {
                return false;
            }

            // check if property with sub property is given
            string[] sSubProperties = node.Name.Split('.');

            // detect if given property exists
            PropertyInfo propInfo = null;
            Type currPropertyType = p_oConcreteInstance.GetType();

            // go straight forward with nested types until last property should get
            for (int i = 0; i < sSubProperties.Length; i++)
            {
                // name of current property
                string sCurrentProperty = sSubProperties[i];

                // if last property detected, get it PropertyInfo object, otherwise get nested type
                if (i == sSubProperties.Length-1)
                {
                    propInfo = currPropertyType.GetProperty(sSubProperties[i]);
                }
                else
                {
                    PropertyInfo pi = currPropertyType.GetProperty(sSubProperties[i]);
                    currPropertyType = pi.GetValue(p_oConcreteInstance, null).GetType();

                    // create new instane of current property value
                    try
                    {
                        object obj = pi.GetValue(p_oConcreteInstance, null);
                        p_oConcreteInstance = obj;
                    }
                    catch
                    {
                        break;
                    }

                    // check if nested type was found, otherwise break
                    if (currPropertyType == null)
                    {
                        break;
                    }
                }
            }

            // check if property info was found
            if (propInfo == null)
            {
                return false;
            }
            if (!propInfo.CanWrite)
            {
                return false;
            }

            // check if node attribute "type" is specified
            XmlAttribute xmlAttr = (XmlAttribute)node.Attributes.GetNamedItem("type");
            if (xmlAttr != null)
            {
                sAttributeType = xmlAttr.Value.ToLower();
            }

            try
            {
                // switch for all different types
                switch (sAttributeType)
                {
                    case "rgb":
                        Color color = ConvertRGBString(node.InnerText);
                        if (color != Color.Empty)
                        {
                            propInfo.SetValue(p_oConcreteInstance, color, null);
                        }
                        break;
                    case "colorname":
                        color = Color.FromName(node.InnerText);
                        if (!color.Equals(Color.FromArgb(0)))
                        {
                            propInfo.SetValue(p_oConcreteInstance, color, null);
                        }
                        break;
                    case "bool":
                        string nodeVal = node.InnerText;
                        bool convertedVal = false;
                        if (nodeVal.ToLower() == "true")
                        {
                            convertedVal = true;
                        }
                        propInfo.SetValue(p_oConcreteInstance, convertedVal, null);
                        break;
                    case "font":
                        Font fontToSet = ConvertFontString(node.InnerText);
                        propInfo.SetValue(p_oConcreteInstance, fontToSet, null);
                        break;
                    case "enum":
                        object enumToSet = ConvertEnumString(node.InnerText,
                            propInfo.GetValue(p_oConcreteInstance, null));
                        propInfo.SetValue(p_oConcreteInstance, enumToSet, null);
                        break;
                    default:
                        propInfo.SetValue(p_oConcreteInstance, node.InnerText, null);
                        break;
                }
            }
            catch (Exception ex)
            {
                // TODO: Decide what is necessary: Exception or log entry...
                return false;
            }

            return true;
        }

        #endregion

        #region Converting routines

        /// <summary>
        /// Converts the enum string.
        /// </summary>
        /// <param name="p_sEnumString">The EnumString.</param>
        /// <param name="p_oCurrentEnumValue">The current enum value object to detect which enum is necessary.</param>
        /// <returns>Parsed enum value.</returns>
        private static object ConvertEnumString(string p_sEnumString, object p_oCurrentEnumValue)
        {
            object retValue = Enum.Parse(p_oCurrentEnumValue.GetType(), p_sEnumString);
            return retValue;
        }

        /// <summary>
        /// Converts the font string.
        /// </summary>
        /// <param name="p_sFontString">The Font string coming from xml file.</param>
        /// <returns>Converted Font object, or null if conversion fails.</returns>
        private static Font ConvertFontString(string p_sFontString)
        {
            // local variables
            float fFontSize = 0;
            FontStyle fontStyle;
            string[] fontParams = p_sFontString.Split(',');

            // check count of input parameters
            if (fontParams.Length < 3)
            {
                return null;
            }

            // try to parse font size
            if (!Single.TryParse(fontParams[1], out fFontSize))
            {
                fFontSize = 10f;
            }

            // try to parse font style
            try
            {
                fontStyle = (FontStyle)Enum.Parse(typeof(FontStyle), fontParams[2], true);
            }
            catch
            {
                fontStyle = FontStyle.Regular;
            }

            return new Font(fontParams[0], fFontSize, fontStyle);
        }

        /// <summary>
        /// Converts the RGB string to Color object.
        /// </summary>
        /// <param name="p">String contains comma seperated rgb values.</param>
        /// <returns>Color from RGB values.</returns>
        private static Color ConvertRGBString(string p_sRGBValues)
        {
            // local variables
            int iColorR = 300; // initial illegal range
            int iColorG = 300; // initial illegal range
            int iColorB = 300; // initial illegal range
            string[] rgbValues = p_sRGBValues.Split(',');

            // check if 3 rgb values exists
            if (rgbValues.Length != 3)
            {
                return Color.Empty;
            }

            // try to parse 3 rgb values to integer
            Int32.TryParse(rgbValues[0], out iColorR);
            Int32.TryParse(rgbValues[1], out iColorG);
            Int32.TryParse(rgbValues[2], out iColorB);

            // check rgb range
            if ((iColorR < 0) || (iColorR > 255))
            {
                return Color.Empty;
            }
            if ((iColorG < 0) || (iColorG > 255))
            {
                return Color.Empty;
            }
            if ((iColorB < 0) || (iColorB > 255))
            {
                return Color.Empty;
            }

            // return RGB color
            return Color.FromArgb(iColorR, iColorG, iColorB);
        }

        #endregion

        #region Public / Protected Methods

        /// <summary>
        /// This method reads from xml configuration file one property and tries to use it in concrete
        /// object instance.
        /// </summary>
        /// <param name="p_sXmlFilePath">Filepath to xml config file.</param>
        /// <param name="p_sProperty">Name of property (XmlNode name), which to read.</param>
        /// <param name="p_oConcreteInstance">Concrete instance for which property should be set.</param>
        /// <returns>
        /// True, if property setting was successfully, otherwise False.
        /// </returns>
        public static bool ReadConfig(string p_sXmlFilePath, string p_sProperty, object p_oConcreteInstance)
        {
            XmlNode node = GetSingleXmlNode(p_sXmlFilePath, String.Empty, p_sProperty);
            return SetPropertyFromXmlNode(node, p_oConcreteInstance);
        }

        /// <summary>
        /// This method reads from xml configuration file all properties and tries to use them in concrete
        /// object instance.
        /// </summary>
        /// <param name="p_sXmlFilePath">Filepath to xml config file.</param>
        /// <param name="p_oConcreteInstance">Concrete instance for which properties should be set.</param>
        /// <returns>
        /// True, if properties setting was successfully, otherwise False.
        /// </returns>
        public static bool ReadAllConfig(string p_sXmlFilePath, object p_oConcreteInstance)
        {
            // local variable
            bool retValue = true;

            XmlNodeList nodeList = GetXmlNodes(p_sXmlFilePath, String.Empty);

            if (nodeList == null)
            {
                return false;
            }

            foreach (XmlNode node in nodeList)
            {
                if(!SetPropertyFromXmlNode(node, p_oConcreteInstance))
                {
                    retValue = false;
                }
            }

            return retValue;
        }

        #endregion
    }
}

Sie haben Fragen zu diesem Snippet oder brauchen Hilfe bei der .NET Entwicklung?
Freundliche und kompetente Entwickler helfen Ihnen gern weiter im Forum für .NET Entwicklung.



Kommentare:
(Zum Schreiben von Kommentaren bitte anmelden.)

Thomas Westrupp schrieb am:  11.12.2006 15:51:19

Top Snippet, wenn auch ein wenig umfangreich, aber doch absolut simpel in der Einsetzung!
_ntr_ schrieb am:  11.12.2006 15:57:55

Vielen Dank,
auch wenn mir unerklärlich ist, wie man mit 1 Bewertung eine Kommazahl als Wertung erhält ;-)

Zieht man hier alle Kommentare ab, dann ist das Ganze gar nicht mehr so umfangreich ;-)
Jan Welker schrieb am:  11.12.2006 21:49:51

Wie sich die Bewertung zusammensetzt kann man hier <a href="http://dotnet-snippets.de/dns/TopTen.aspx">http://dotnet-snippets.de/dns/TopTen.aspx</a> (unten) nachlesen.
_ntr_ schrieb am:  13.12.2006 04:44:16

Hallo,
ich sehe, dass mein Snippet bewertet worden ist, aber ein Kommentar fehlt. Ich kann zwar nicht verlangen, dass ein Kommentar abgegeben wird, aber ich kann darum bitten. Kommentare sind mir deshalb wichtiger als eine Bewertung.
Also bitte bei Verwendung meines Snippets auch einen Kommentar abgeben, danke!
_ntr_


Diese Snippets könnten für Sie interessant sein:
[C#] Objekt in XML speichern (Serialisieren)
[C#] Treeview in XML schreiben
[ASP.net] XML - HTML Transformation
[C#] XML Encoding eines XmlDocument ändern
[C#] XMLDocument in XDocument konvertieren
[C#] Rss Feed in XMLDocument laden
[VB.NET] XML Datei in DataSet einlesen
[VB.NET] Objekt mit dem XmlSerializer serialisieren
[VB.NET] XML Datei mit dem XmlSerializer deserialisieren
[C#] Image zu Base64 konvertieren und zurück
[C#] Generische XML-Serialisierung
[C#] CSV und XML-Datei Datenbank-Import (incl. valid-check)
[C#] Währungskurse in Datenbank speichern
[VB.NET] Einfaches Erstellen einer XML Datei in .Net
[C#] XML in DataTable laden
[C#] Intellisense Unterstützung für XML Dateien für LINQ
[C#] user.config und generische Listen
[C#] Dataset verschlüsseln
[C#] Xml Datei entschlüsseln
[ASP.net] XML Daten über einen Internet Proxy abfragen
[C#] Formatieren von Sonderzeichen für XML
[C#] Binärdatei in XML File speichern
[C#] Binärdatei aus XML Datei auslesen und abspeichern
[C#] leere Knoten aus XML Document entfernen
[C#] XML Kommentare entfernen
[C#] Austauch von kritischen Zeichen in einem String...
[C#] Excel-Export ohne Excel (auch für Web)
[C#] Ini-Datei-Klasse
[C#] TreeView Export To Xml OR Import from XMl
[C#] Autom. Laden & Speichern von Position und Größe eines Forms
[VB.NET] Bild als XML Datei Speichern
[C#] Ein Object serialisieren
[C#] Ein Object deserialisieren
[C#] Konvertiert Code nach Example für XML-Kommentar
[C#] XMLIO - einfachstes (De)serialisieren von/zu XML-Dateien
[C#] Generisch XML De-/ Serialisieren
[C#] XML generieren mit Linq to XML
[C#] 3 arten der Serialisierung bzw Deserialisierung
[C#] Spracherkennung
[C#] Wunderground Wettervorhersage
[C#] Mit LINQtoXML XML Dateien erzeugen bzw. abfragen
[C#] ini Datei anlegen - mit Dictionary
[C#] Typen mit dem XmlSerializer (de-)serialisieren
[C#] user.config löschen
[C#] Liefert alle Assemblies aus dem Global Assembly Cache (GAC)
[C#] Kompilierung zur Laufzeit
[C#] Generische Liste per Reflection erzeugen
[C#] Generische Extension zum Auslesen eines Klassen-Attributes
[C#] Versionsnummer der Assembly ermitteln
[VB.NET] Funktion an Hand des Names ausführen
[C#] Ruft eine Methode in einer externen DLL anhand der Namen auf
[C#] Transactionen mit mehreren TableAdaptern
[C#] Reflektion und Generika
[C#] Dateiname des aktuellen Programms ermitteln
[C#] Generic Type Creator
[C#] Aktuelle Methode mit StackTrace ermitteln

schlecht sehr gut
1 2 3 4 5 6 7 8 9 10
Nur angemeldete User können Snippets bewerten.