In Groovy ConfigSlurper is a utility class that is used for reading configuration files written in form of Groovy scripts.Let’s consider the following properties file.
We will use a Groovy script to read from this properties file as shown in the snippet below:
package com.test import java.util.Properties class Start { static main(args) { def p = new Properties() new File("test.properties").withInputStream { stream -> p.load(stream) } println "gfv3.admin.url=" + p["gfv3.admin.url"] } }
This is a very simple piece of code which makes use of the java.util.Properties class and load the properties file using java.io.File and it’s associated InputStream class.Here the properties are accessed as a map of name/value pairs. This code can be tweaked bit using the ConfigSlurper class and the values can be accessed as object properties as shown below:
package com.test import java.util.Properties class Start { static main(args) { def p = new Properties() new File("test.properties").withInputStream { stream -> p.load(stream) } def cfg = new ConfigSlurper().parse(p) println "gfv3.admin.url=" + cfg.gfv3.admin.url } }
We can write a similar ConfigSlurper in C# using the System.Dynamic.ExpandoObject which allows us to add and remove properties to this object at runtime.ExpandoObject implement a IDictionary and IDynamicMetaObjectProvider interfaces as shown in the definition below:
public sealed class ExpandoObject : IDynamicMetaObjectProvider,IDictionary<string, Object>, ICollection<KeyValuePair<string, Object>>, IEnumerable<KeyValuePair<string, Object>>, IEnumerable, INotifyPropertyChanged
We can use the IDictionary implementation to attach properties at runtime as shown below in the ConfigSlurper class.
public static class ConfigSlurper { public static ExpandoObject Parse(System.Collections.Specialized.NameValueCollection settings) { var config = new ExpandoObject(); var dictConfig = (config as IDictionary<String, object>); foreach (var k in settings.AllKeys) { dictConfig[k] = settings[k]; } return config; } }
The config settings are defined as shown below:
<appSettings> <add key="gfv3AdminUrl" value="http\://localhost\:4848"/> <add key="gfv3Root" value="D\:\\Program Files\\glassfish-3.0.1\\glassfish"/> <add key="gfv3Port" value="4848"/> <add key="gfv3Host" value="localhost"/> <add key="gfv3Username" value="admin"/> <add key="gfv3Url" value="http\://localhost\:8080"/> </appSettings>
This config can be read using the ConfigSlurper class as:
static void Main(string[] args) { dynamic config = ConfigSlurper.Parse(ConfigurationManager.AppSettings); Console.WriteLine(config.gfv3AdminUrl); Console.Read(); }