Create a .config file
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10

Thread: Create a .config file

  1. #1
    Join Date
    Jan 2011
    Posts
    16

    Create a .config file

    Hello
    This is the part of my C# code that i need some help with.
    Code:
    if(deviceName.Equals("RelayController1"))
                {
                    // Turn off
                    if(deviceActionId == 1)
                    {
                        string args = "C11";
                        rippedFromIsaksson.SendCMD(args);
                        intercepted = true;
                        System.Threading.Thread.Sleep(135); 
                       
                    }
                    // Turn on
                    else if(deviceActionId== 2)
                    {
                        string args = "S11";
                        rippedFromIsaksson.SendCMD(args);
                        intercepted = true;
                        System.Threading.Thread.Sleep(135);
                    }
                }
    Everything works just fine with this code, what it does is that it sends a command with rs232 to a relayboard (This is a plugin to a program) In the main program i set up a device with name RelayController1 and when i activate that device in main program than this script takes action becourse of if(deviceName.Equals("RelayController1"))

    But what i need help with is that i wanna add a .config file that i could add new devices in.
    I will need something like this.

    Code:
    <devices>
    	<add deviceName="RelayController1"
               	StringArgs="C11"
               	intercept="true"
                    Sleep="135" />
    	<add deviceName="RelayController2"
               	StringArgs="C21"
               	intercept="true"
                    Sleep="135" />
            <add deviceName="RelayController3"
               	StringArgs="C31"
               	intercept="true"
                    Sleep="135" />
    </devices>
    So that i dont need to hardcode every new device, so for every new device that i add in the .config file then it has to add this to the code

    Code:
    if(deviceName.Equals("From devicename in config"))
                {
                    // Turn off
                    if(deviceActionId == 1)
                    {
                        string args = "From StringArgs in config";
                        rippedFromIsaksson.SendCMD(args);
                        intercepted = From intercept in config;
                        System.Threading.Thread.Sleep(From Sleep in config); 
                       
                    }
                    // Turn on
                    else if(deviceActionId== 2)
                    {
                        string args = "From StringArgs in config";
                        rippedFromIsaksson.SendCMD(args);
                        intercepted = From intercept in config;
                        System.Threading.Thread.Sleep(From Sleep in config);
                    }
                }
    So the config has to add a new if-statment.

    So what do you thing about this, is this something that you could help me get started with?

  2. #2
    Join Date
    Jan 2011
    Posts
    16

    Re: Create a .config file

    This is what i have come up with so far.

    App.config

    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <appSettings>
        <add DeviceName="RelayController1"
                  StringArgs="C11"
                  intercept="true"
                  Sleep="135" />
        <add DeviceName="RelayController2"
                  StringArgs="C21"
                  intercept="true"
                  Sleep="135" />
        <add DeviceName="RelayController3"
                  StringArgs="C31"
                  intercept="true"
                  Sleep="135" />
        
      </appSettings>
    </configuration>
    what do you thing about that start?

  3. #3
    Join Date
    Jan 2011
    Posts
    16

    Wink Re: Create a .config file

    Quote Originally Posted by Isaksson View Post
    This is what i have come up with so far.

    App.config

    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <appSettings>
        <add DeviceName="RelayController1"
                  StringArgs="C11"
                  intercept="true"
                  Sleep="135" />
        <add DeviceName="RelayController2"
                  StringArgs="C21"
                  intercept="true"
                  Sleep="135" />
        <add DeviceName="RelayController3"
                  StringArgs="C31"
                  intercept="true"
                  Sleep="135" />
        
      </appSettings>
    </configuration>
    what do you thing about that start?
    That code will ofcourse not work, back to the drawingboard

  4. #4
    Join Date
    Jan 2011
    Posts
    16

    Re: Create a .config file

    Here is what i have been working on, i hope someone could tell me if iam way out on this or if iam getting closer.

    app.config
    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    
      <configSections>
        <section name="Plugins" type="RelayControllerPlugin.PluginConfigSection, RelayControllerPlugin" />
      </configSections>    
      <Plugins>
        <Plugin>
          <add deviceName="RelayController1"
               stringArgs="C11"
               sleep ="135"
               intercept ="true"/>
    
          <add deviceName="RelayController2"
               stringArgs="C21"
               sleep ="135"
               intercept ="true"/>
          
          <add deviceName="RelayController3"
               stringArgs="C31"
               sleep ="135"
               intercept ="true"/>
        </Plugin>
      </Plugins>
      
    </configuration>
    and here is
    PluginConfigSection
    Code:
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Text;
    
    
    namespace RelayControllerPlugin
    {
        public class PluginConfigSection : ConfigurationSection
        {
            [ConfigurationProperty("Plugin")]
            public PluginsCollection PluginItems
            {
                get { return ((PluginsCollection)(base["Plugin"])); }
            }
    
        }
    
        [ConfigurationCollection(typeof(PluginElement))]
        public class PluginsCollection : ConfigurationElementCollection
        {
            public PluginElement this[int idx]
            {
                get { return (PluginElement)BaseGet(idx); }
            }
    
            protected override ConfigurationElement CreateNewElement()
            {
                return new PluginElement();
            }
    
            protected override object GetElementKey(ConfigurationElement element)
            {
                return ((PluginElement)(element)).DeviceName;
            }
        }
        public class PluginElement : ConfigurationElement
        {
            [ConfigurationProperty("deviceName", DefaultValue = "", IsKey = false, IsRequired = true)]
            public string DeviceName
            {
                get { return ((string)(base["deviceName"])); }
    
                set { base["deviceName"] = value; }
            }
    
            [ConfigurationProperty("stringArgs", DefaultValue = "", IsKey = false, IsRequired = true)]
            public string StringArgs
            {
                get { return ((string)(base["stringArgs"])); }
    
                set { base["stringArgs"] = value; }
            }
    
            [ConfigurationProperty("sleep", DefaultValue = "", IsKey = false, IsRequired = true)]
            public string Sleep
            {
                get { return ((string)(base["sleep"])); }
    
                set { base["sleep"] = value; }
            }
    
            [ConfigurationProperty("intercept", DefaultValue = "", IsKey = false, IsRequired = true)]
            public string Intercept
            {
                get { return ((string)(base["intercept"])); }
    
                set { base["intercept"] = value; }
            }
        }
    
    }
    Is this something to continue to work with could this code help me to solve my problem?

    I wanna grabb the info from .config and add that in a If-statment (or maybe some other way)
    And make this happen.
    Code:
    if(deviceName.Equals("From deviceName in app.config"))
                {
                    // Turn off
                    if(deviceActionId == 1)
                    {
                        string args = "From stringArgs in app.config";
                        rippedFromIsaksson.SendCMD(args);
                        intercepted = From intercept in app.config;
                        System.Threading.Thread.Sleep(From sleep in app.config); 
                       
                    }
                    // Turn on
                    else if(deviceActionId== 2)
                    {
                        string args = "From stringArgs in app. config";
                        rippedFromIsaksson.SendCMD(args);
                        intercepted = From intercept in app.config;
                        System.Threading.Thread.Sleep(From sleep in app.config);
                    }
                }
    For every
    Code:
     <add deviceName="RelayController1"
               stringArgs="C11"
               sleep ="135"
               intercept ="true"/>
    in my app.config file.

    Thanks.

  5. #5
    Join Date
    Jan 2011
    Posts
    16

    Re: Create a .config file

    This is a sample code that i have
    Code:
    var section = (PluginConfigSection)ConfigurationManager.GetSection("Plugins");
    
                if (section != null)
                {
                    foreach (PluginElement pluginItem in section.PluginItems)
                    {
                        Debug.WriteLine(pluginItem.DeviceName);
                        Debug.WriteLine(pluginItem.StringArgs);
                        Debug.WriteLine(pluginItem.Sleep);
                    }
                }
    How could i rewrite this so that i can loop and grabb info from all my "add devicename" in my app.config

  6. #6
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    11,201

    Re: Create a .config file

    Personally I prefer to use the XmlSerializer class to read custom sections out of the config file. I find the ConfigurationSection approach too much work for too little gain.

    So below is how I would approach the problem. I've taken the liberty to flatten some of the xml structure and removed some of the plugin layers. If you only have one plugin, these extra layers are unnecessary. If you are planning more plugings, the put the layers back in (and modify the serialization classes).

    First, changes to the App.Config file
    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="relayDevices" type=" CG.ConfigXmlSerialization, RelayDevices" />
      </configSections>
      <relayDevices>
        <device name="RelayController1"
          args="C11"
          sleep="135"
          intercept="true"/>
        <device name="RelayController2"
          args="C21 D23"
          sleep="145"
          intercept="true"/>
        <device name="RelayController3"
          args="C33"
          sleep="157"
          intercept="false"/>
      </relayDevices>
    </configuration>
    Next, the classes that read the relayDevices section of the App.Config
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml.Serialization;
    using System.Xml;
    using System.Reflection;
    
    namespace CG.ConfigXmlSerialization
    {
    
        [XmlRoot( "configuration", Namespace = "", IsNullable = false )]
        public class RelayDevices
        {        
            public static RelayDevices Load()
            {
                var serializer = new XmlSerializer( typeof( RelayDevices ) );
    
                using( var reader = XmlReader.Create( Assembly.GetEntryAssembly( ).Location + ".config" ) )
                {
                    return ( RelayDevices ) serializer.Deserialize( reader );                
                }
            }
    
            [XmlArray( "relayDevices" )]
            [XmlArrayItem( "device" )]
            public Device[] Devices
            {
                get
                {
                    if ( _deviceDictionary == null ) { _deviceDictionary = new Dictionary<string, Device>( ); }
    
                    return _deviceDictionary.Values.ToArray( );
                }
    
                set
                {
                    if( _deviceDictionary == null ) { _deviceDictionary = new Dictionary< string, Device >( ); }
    
                    if( value != null )
                    {
                        foreach( var device in value )
                        {
                            _deviceDictionary.Add( device.Name, device );
                        }
                    }
    
                }
    
            }
    
            /// <summary>
            /// Override the this operator.  Allow access of device by name
            /// </summary>
            public Device this[string name]
            {
                get { return _deviceDictionary[name]; }
            }
    
            private Dictionary< string, Device > _deviceDictionary = new Dictionary< string, Device >( );
        }
    
        [Serializable]
        public class Device
        {
            [XmlAttribute( "name" )]
            public string Name { get; set; }
    
            [XmlAttribute("args")]
            public string[] Args
            {
                get 
                {
                    if ( _argList == null ) { _argList = new List< string >( ); }
    
                    return _argList.ToArray( );
                }
    
                set
                {
                    if ( _argList == null ) { _argList = new List<string>( ); }
    
                    if ( value != null )
                    {
                        _argList.AddRange( value );
                    }
                }
            }
    
            [XmlAttribute("sleep")]
            public int Sleep { get; set; }
    
            [XmlAttribute("intercept")]
            public bool Intercept { get; set; }
    
            public List<string> _argList = new List<string>( );
        }
    }
    Notice there are two classes defined: The first I call RelayDevices. This class contains the list of Devices (which is defined in another class.

    There are a couple of interesting things going on here so let's take a look at each.

    1) The XmlRoot attribute specifies the root class that reads xml. Notice here that I have specified "configuration" as it's element name rather than "relayDevices". This let's the xml serializer know that the first node in the file is called "configuration" (which is what the root node is in an App.Config file).
    Code:
    [XmlRoot( "configuration", Namespace = "", IsNullable = false )]
    public class RelayDevices
    2) Next is the Devices property. The XmlArray( "relayDevices" ) and XmlArrayItem( "device" ) attributes tell the serializer that there is a "relayDevices" node that contains an array of device nodes.
    Code:
    [XmlArray( "relayDevices" )]
    [XmlArrayItem( "device" )]
    public Device[] Devices { ... }
    3) Notice I've used a collection to 'back' the array object. Typically you can use an auto property to return an array of Devices (e.g. public Device[] Devices { get; set; }. The problem with this approach is that users of the class must check the Devices property for null before using it. This is because if no device nodes are found in the config file, this property will be null. I hate checking for null in any of my class properties, so I use a List<> or a Dictionary<> to 'back' my property. This always ensures that the Devices node will never be null (that way I can call foreach( var device in relayDevices.Devices) without fear). Btw, the next section will explain why I'm opted for a Dictionary< > instead of a List<>.
    Code:
    public Device[] Devices
    {
      get
      {
        if ( _deviceDictionary == null ) { _deviceDictionary = new Dictionary<string, Device>( ); }
    
        return _deviceDictionary.Values.ToArray( );
      }
      ...
    }
    4) Sometimes it's useful to be able to do a lookup for a particular device by name. So we override the '[]' operator (and that's why we've used the dictionary in step 3) to back the Devices property.
    Code:
    public Device this[string name]
    {
      get { return _deviceDictionary[name]; }
    }
    5) Not much interesting in the Device class except I've used the List<> collection to back the string[] Args property. Also I've alluded to this previously, but you can change the element names in the Xml related attributes. E.g. consider
    Code:
    [XmlAttribute("args")]
    public string[] Args { ... }
    This allows the xml to appear as 'args', but the C# property to be Args - in terms of naming conventions, everybody's happy.

    6) Notice the static Load method in the RelayDevices class.
    Code:
    public static RelayDevices Load()
    {
      var serializer = new XmlSerializer( typeof( RelayDevices ) );
    
      using( var reader = XmlReader.Create( Assembly.GetEntryAssembly( ).Location + ".config" ) )
      {
        return ( RelayDevices ) serializer.Deserialize( reader );                
      }
    }
    This method, reads the App.Config file, uses the XmlSerializer class to deserialize the app config into a RelayDevices class instance and returns the object. The using( ) block insures that the XmlReader instance is closed and destroyed when we are done using it.

    Finally let's look at the calling code.
    Code:
    namespace CG.ConfigXmlSerialization
    {
        class Program
        {
            static void Main(string[] args)
            {
                var relayDevices = RelayDevices.Load( );
    
                foreach (var device in relayDevices.Devices)
                {
    
                }
    
                var device2 = relayDevices[ "RelayController2" ];
            }
        }
    }
    To use, we just create an instance of the RelayDevices class by calling the static Load method. Then we can enumerate the devices by using a foreach loop on the Devices property. Since we used a Dictionary<> to back the Devices property, we can be assurred it will never be null so we can safely use the foreach loop. The second example shows how the overloaded [] operator allows us to perform a device lookup.

  7. #7
    Join Date
    Jan 2011
    Posts
    16

    Re: Create a .config file

    Thanks for the reply.
    this will help me alote.

    I will get back in this post when i have tryed this.

    Thanks again Arjay

  8. #8
    Join Date
    Jan 2011
    Posts
    16

    Re: Create a .config file

    I have tryed this now and it works great.
    Thanks again for the help.
    It was a very good approch.

  9. #9
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    11,201

    Re: Create a .config file

    Your welcome. XmlSerialization is really cool.

  10. #10
    Join Date
    Jan 2011
    Posts
    16

    Re: Create a .config file

    Quote Originally Posted by Arjay View Post
    Your welcome. XmlSerialization is really cool.
    thumbs up on that one.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center