Exemplo n.º 1
0
        public static ConfigObject FromExpando(ExpandoObject e, bool isDefault = false)
        {
            var edict = e as IDictionary <string, object>;
            var c     = new ConfigObject();
            var cdict = c._members;

            // this is not complete. It will, however work for JsonFX ExpandoObjects
            // which consits only of primitive types, ExpandoObject or ExpandoObject []
            // but won't work for generic ExpandoObjects which might include collections etc.
            foreach (var kvp in edict)
            {
                // recursively convert and add ExpandoObjects
                if (kvp.Value is ExpandoObject)
                {
                    cdict.TryAdd(kvp.Key, FromExpando((ExpandoObject)kvp.Value, isDefault));
                }
                else if (kvp.Value is ExpandoObject[])
                {
                    var configObjects = new List <ConfigObject>();
                    foreach (var ex in ((ExpandoObject[])kvp.Value))
                    {
                        configObjects.Add(FromExpando(ex, isDefault));
                    }
                    cdict.TryAdd(kvp.Key, configObjects.ToArray());
                }
                else
                {
                    cdict.TryAdd(kvp.Key, new ConfigObjectMember(isDefault, kvp.Value));
                }
            }
            return(c);
        }
Exemplo n.º 2
0
        public static ConfigObject FromExpando(ExpandoObject e)
        {
            var edict = e as IDictionary <string, object>;
            var c     = new ConfigObject();
            var cdict = (IDictionary <string, object>)c;

            // this is not complete. It will, however work for JsonFX ExpandoObjects
            // which consists only of primitive types, ExpandoObject or ExpandoObject []
            // but won't work for generic ExpandoObjects which might include collections etc.
            foreach (var kvp in edict) // recursively convert and add ExpandoObjects
            {
                switch (kvp.Value)
                {
                case ExpandoObject o:
                    cdict.Add(kvp.Key, FromExpando(o));
                    break;

                case ExpandoObject[] _:
                    cdict.Add(kvp.Key, (from ex in (ExpandoObject[])kvp.Value select FromExpando(ex)).ToArray());
                    break;

                default:
                    cdict.Add(kvp.Key, kvp.Value);
                    break;
                }
            }
            return(c);
        }
Exemplo n.º 3
0
        public static ConfigObject ApplyJsonFromFileInfo(FileInfo file, ConfigObject config = null)
        {
            var     overlayJson   = File.ReadAllText(file.FullName);
            dynamic overlayConfig = ParseJson(overlayJson);

            return(Merger.Merge(overlayConfig, config));
        }
Exemplo n.º 4
0
        public void ApplyJson(string json)
        {
            ConfigObject result = Config.ApplyJson(json, this);

            // replace myself's members with the new ones
            this.members = result.members;
        }
Exemplo n.º 5
0
        // seeks a folder for .conf files
        public static ConfigObject ApplyFromDirectory(string path, ConfigObject config = null, bool recursive = false)
        {
            if (!Directory.Exists(path))
            {
                throw new Exception("no folder found in the given path");
            }

            if (config == null)
            {
                config = new ConfigObject();
            }

            var info = new DirectoryInfo(path);

            if (recursive)
            {
                foreach (var dir in info.GetDirectories())
                {
                    Console.WriteLine("reading in folder {0}", dir);
                    config = ApplyFromDirectoryInfo(dir, config, true);
                }
            }

            // find all files
            var files = info.GetFiles();

            foreach (var file in files)
            {
                Console.WriteLine("reading in file {0}", file);
                config = ApplyJsonFromFileInfo(file, config);
            }
            return(config);
        }
Exemplo n.º 6
0
        public static ConfigObject FromJobject(JObject source)
        {
            var sourceDictionary = source.ToObject <Dictionary <string, object> >();
            var configObject     = new ConfigObject();
            var configDictionary = (IDictionary <string, object>)configObject;

            var JObjectKeys = new List <string>();
            var JArrayKeys  = new List <string>();

            foreach (var r in sourceDictionary)
            {
                string key   = r.Key;
                object value = r.Value;
                if (value.GetType() == typeof(JObject))
                {
                    JObjectKeys.Add(key);
                }
                else if (value.GetType() == typeof(JArray))
                {
                    JArrayKeys.Add(key);
                }
                else
                {
                    configDictionary[key] = value;
                }
            }

            foreach (var key in JArrayKeys)
            {
                var  childType  = ((JArray)sourceDictionary[key]).Values().FirstOrDefault();
                bool isProperty = false;
                if (childType != null)
                {
                    isProperty = childType.GetType() == typeof(JProperty);
                }
                if (isProperty)
                {
                    var propertyList     = ((JArray)sourceDictionary[key]).ToObject <List <JObject> >();
                    var configObjectList = new Collection <ConfigObject>();
                    foreach (var property in propertyList)
                    {
                        configObjectList.Add(FromJobject(property));
                    }
                    configDictionary[key] = configObjectList.ToArray();
                }
                else
                {
                    configDictionary[key] = ((JArray)sourceDictionary[key]).Values().Select(x => ((JValue)x).Value).ToArray();
                }
            }
            JObjectKeys.ForEach(key => configDictionary[key] = FromJobject(sourceDictionary[key] as JObject));


            return(configObject);
        }
Exemplo n.º 7
0
 public static void SetUserConfig(ConfigObject config)
 {
     User = config;
     // disable the watcher
     if (userConfigWatcher != null)
     {
         userConfigWatcher.EnableRaisingEvents = false;
         userConfigWatcher.Dispose();
         userConfigWatcher = null;
     }
 }
Exemplo n.º 8
0
        public static ConfigObject ApplyJson(string json, ConfigObject config = null)
        {
            if (config == null)
            {
                config = new ConfigObject();
            }

            dynamic parsed = ParseJson(json);

            return(Merger.Merge(parsed, config));
        }
Exemplo n.º 9
0
 //// overrides any default config specified in default.conf
 //public void SetDefaultConfig(dynamic config)
 //{
 //    _user = config;
 //}
 public void SetUserConfig(ConfigObject config)
 {
     _readerWriterLockSlim.EnterWriteLock();
     try
     {
         _user = _default + config;
     }
     finally
     {
         _readerWriterLockSlim.ExitWriteLock();
     }
 }
Exemplo n.º 10
0
        public static void SetUserConfig(ConfigObject config)
        {
            User = config;
            // disable the watcher
            if (userConfigWatcher != null)
            {
                userConfigWatcher.EnableRaisingEvents = false;
                userConfigWatcher.Dispose();
                userConfigWatcher = null;
            }

            // invalidate the Global config, forcing a re-merge next time its accessed
            global_config = null;
        }
Exemplo n.º 11
0
        public static ConfigObject ParseJson(string json)
        {
            var lines = json.Split(new char[] { '\n' });
            // remove lines that start with a dash # character
            var filtered = from l in lines
                           where !(Regex.IsMatch(l, @"^\s*#(.*)"))
                           select l;

            var filtered_json = string.Join("\n", filtered);

            var parsed = JsonConvert.DeserializeObject <JObject>(filtered_json);

            // convert the ExpandoObject to ConfigObject before returning
            return(ConfigObject.FromJobject(parsed));
        }
Exemplo n.º 12
0
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            object member;

            if (_members.TryGetValue(binder.Name, out member))
            {
                result = (member is ConfigObjectMember) ? ((ConfigObjectMember)member).Value : member;
            }
            else
            {
                result = new ConfigObject();
                _members[binder.Name] = result;
            }
            return(true);
        }
Exemplo n.º 13
0
        public static ConfigObject ParseJson(string json)
        {
            var lines = json.Split(new char[] { '\n' });
            // remove lines that start with a dash # character
            var filtered = from l in lines
                           where !(Regex.IsMatch(l, @"^\s*#(.*)"))
                           select l;

            var filtered_json = string.Join("\n", filtered);

            //var json_reader = new JsonReader ();
            dynamic parsed = JsonFx.Json.JsonReader.Deserialize(filtered_json);

            // convert the ExpandoObject to ConfigObject before returning
            return(ConfigObject.FromExpando(parsed));
        }
Exemplo n.º 14
0
        public static ConfigObject ParseJson(string json, bool isDefault = false)
        {
            var lines = json.Split('\n');
            // remove lines that start with a dash # character
            var filtered = from l in lines
                           where !(Regex.IsMatch(l, @"^\s*#(.*)"))
                           select l;

            var filteredJson = string.Join("\n", filtered);

            var     jsonReader = new JsonReader();
            dynamic parsed     = jsonReader.Read(filteredJson);

            // convert the ExpandoObject to ConfigObject before returning
            return(ConfigObject.FromExpando(parsed, isDefault));
        }
Exemplo n.º 15
0
        public static ConfigObject ParseJson(string json)
        {
            #region 去除带#的注释
            var lines = json.Split(new char[] { '\n' });
            // remove lines that start with a dash # character
            var filtered = from l in lines
                           where !(Regex.IsMatch(l, @"^\s*#(.*)"))
                           select l;

            var filtered_json = string.Join("\n", filtered);
            #endregion

            ExpandoObject parsed = Newtonsoft.Json.JsonConvert.DeserializeObject <ExpandoObject>(filtered_json);
            // convert the ExpandoObject to ConfigObject before returning
            var result = ConfigObject.FromExpando(parsed);
            return(result);
        }
Exemplo n.º 16
0
        public static ConfigObject FromExpando(ExpandoObject e)
        {
            var edict = e as IDictionary <string, object>;
            var c     = new ConfigObject();
            var cdict = (IDictionary <string, object>)c;

            // this is not complete. It will, however work for JsonFX ExpandoObjects
            // which consits only of primitive types, ExpandoObject or ExpandoObject []
            // but won't work for generic ExpandoObjects which might include collections etc.
            foreach (var kvp in edict)
            {
                // recursively convert and add ExpandoObjects
                if (kvp.Value is ExpandoObject)
                {
                    cdict.Add(kvp.Key, FromExpando((ExpandoObject)kvp.Value));
                }
                #region 对于数组里面的ExpandoObject,转换为ConfigObject没有意义,因为配置后面的覆盖逻辑只会针对数组本身,不会细到数组中的每一项
                //else if (kvp.Value is ExpandoObject[])
                //{
                //    var config_objects = new List<ConfigObject>();
                //    foreach (var ex in ((ExpandoObject[])kvp.Value))
                //    {
                //        config_objects.Add(FromExpando(ex));
                //    }
                //    cdict.Add(kvp.Key, config_objects.ToArray());
                //}
                //else if (kvp.Value is List<Object>)
                //{
                //    var config_objects = new List<ConfigObject>();
                //    foreach (var ex in ((List<Object>)kvp.Value))
                //    {
                //        config_objects.Add(FromExpando((ExpandoObject)ex));
                //    }
                //    cdict.Add(kvp.Key, config_objects.ToArray());
                //}
                #endregion
                else
                {
                    cdict.Add(kvp.Key, kvp.Value);
                }
            }
            return(c);
        }
Exemplo n.º 17
0
        public static ConfigObject ParseJson(string json)
        {
            var lines = json.Split(new char[] { '\n' });
            // remove lines that start with a dash # character
            var filtered = from l in lines
                           where !(Regex.IsMatch(l, @"^\s*#(.*)"))
                           select l;

            var filtered_json = string.Join("\n", filtered);

            var parsed = JsonConvert.DeserializeObject <ExpandoObject> (filtered_json, new ExpandoObjectConverter());

            // transform the ExpandoObject to the format expected by ConfigObject
            parsed = JsonNetAdapter.Transform(parsed);

            // convert the ExpandoObject to ConfigObject before returning
            var result = ConfigObject.FromExpando(parsed);

            return(result);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Merge the specified obj2 and obj1, where obj1 has precendence and
        /// overrules obj2 if necessary.
        /// </summary>
        /// <exception cref='TypeMissmatchException'>
        /// Is thrown when the type missmatch exception.
        /// </exception>
        public static dynamic Merge(dynamic mObj1, dynamic mObj2)
        {
            dynamic obj1 = mObj1;
            dynamic obj2 = mObj2;

            // make sure we only deal with ConfigObject but not ExpandoObject as currently
            // return from JsonFX
            if (obj1 is ExpandoObject)
            {
                obj1 = ConfigObject.FromExpando(obj1);
            }
            if (obj2 is ExpandoObject)
            {
                obj2 = ConfigObject.FromExpando(obj2);
            }

            // if both objects are NullExceptionPreventer, return a ConfigObject so the
            // user gets an "Empty" ConfigObject
            if (obj1 is NullExceptionPreventer && obj2 is NullExceptionPreventer)
            {
                return(new ConfigObject());
            }

            // if any object is of NullExceptionPreventer, the other object gets precedence / overruling
            if (obj1 is NullExceptionPreventer && obj2 is ConfigObject)
            {
                return(obj2);
            }
            if (obj2 is NullExceptionPreventer && obj1 is ConfigObject)
            {
                return(obj1);
            }

            // handle what happens if one of the args is null
            if (obj1 == null && obj2 == null)
            {
                return(new ConfigObject());
            }

            if (obj2 == null)
            {
                return(obj1);
            }
            if (obj1 == null)
            {
                return(obj2);
            }

            if (obj1.GetType() != obj2.GetType())
            {
                throw new TypeMissmatchException();
            }

            // changes in the dictionary WILL REFLECT back to the object
            var dict1 = (IDictionary <string, object>)(obj1);
            var dict2 = (IDictionary <string, object>)(obj2);

            dynamic result = new ConfigObject();
            var     rdict  = (IDictionary <string, object>)result;

            // first, copy all non colliding keys over
            foreach (var kvp in dict1)
            {
                if (!dict2.Keys.Contains(kvp.Key))
                {
                    rdict.Add(kvp.Key, kvp.Value);
                }
            }
            foreach (var kvp in dict2)
            {
                if (!dict1.Keys.Contains(kvp.Key))
                {
                    rdict.Add(kvp.Key, kvp.Value);
                }
            }

            // now handle the colliding keys
            foreach (var kvp1 in dict1)
            {
                // skip already copied over keys
                if (!dict2.Keys.Contains(kvp1.Key) || dict2[kvp1.Key] == null)
                {
                    continue;
                }

                var kvp2 = new KeyValuePair <string, object>(kvp1.Key, dict2[kvp1.Key]);

                // some shortcut variables to make code more readable
                var key    = kvp1.Key;
                var value1 = kvp1.Value;
                var value2 = kvp2.Value;
                var type1  = value1.GetType();
                var type2  = value1.GetType();

                // check if both are same type
                if (type1 != type2)
                {
                    throw new TypeMissmatchException();
                }

                if (value1 is ConfigObject[])
                {
                    rdict[key] = CollectionMerge(value1, value2);

                    /*var d1 = val1 as IDictionary<string, object>;
                     *                  var d2 = val2 as IDictionary<string, object>;
                     *                  rdict[key] = CollectionMerge (val1, val2); */
                }
                else if (value1 is ConfigObject)
                {
                    rdict[key] = Merge(value1, value2);
                }
                else if (value1 is string)
                {
                    rdict[key] = value1;
                }
                else if (value1 is IEnumerable)
                {
                    rdict[key] = CollectionMerge(value1, value2);
                }
                else
                {
                    rdict[key] = value1;
                }

                //else if (kvp.Value.GetType ().IsByRef) {
                // recursively merge it
                //}
            }
            return(result);
        }
Exemplo n.º 19
0
        /// <summary>
        ///     Merge the specified obj2 and obj1, where obj1 has precendence and
        ///     overrules obj2 if necessary.
        /// </summary>
        /// <exception cref='TypeMissmatchException'>
        ///     Is thrown when the type missmatch exception.
        /// </exception>
        public static dynamic Merge(dynamic m_obj1, dynamic m_obj2)
        {
            dynamic obj1 = m_obj1;
            dynamic obj2 = m_obj2;

            // make sure we only deal with ConfigObject but not ExpandoObject as currently
            // return from JsonFX
            if (obj1 is ExpandoObject)
            {
                obj1 = ConfigObject.FromExpando(obj1);
            }
            if (obj2 is ExpandoObject)
            {
                obj2 = ConfigObject.FromExpando(obj2);
            }

            var isObj1Default = ((obj1 is ConfigObjectMember) && ((ConfigObjectMember)obj1).IsDefault);

            var isObj1EmptyConfigObject = obj1 is ConfigObject && ((ConfigObject)obj1).Count == 0;
            var isObj2EmptyConfigObject = obj2 is ConfigObject && ((ConfigObject)obj2).Count == 0;

            // if both objects are empty ConfigObject, return a ConfigObject so the
            // user gets an "Empty" ConfigObject
            if (isObj1EmptyConfigObject && isObj2EmptyConfigObject)
            {
                return(new ConfigObject(/*isObj1Default*/));
            }

            // if any object is of NullExceptionPreventer, the other object gets precedence / overruling
            //if (isObj1EmptyConfigObject && obj2 is ConfigObject)
            //{
            //    if (isObj1Default == isObj2Default)
            //    {
            //        return obj2;
            //    }
            //}
            if (isObj2EmptyConfigObject && obj1 is ConfigObject)
            {
                return(obj1);
            }

            // handle what happens if one of the args is null
            if (obj1 == null && obj2 == null)
            {
                return(new ConfigObject());
            }

            if (obj2 == null)
            {
                return(obj1);
            }
            if (obj1 == null)
            {
                return(obj2);
            }

            if (obj1.GetType() != obj2.GetType())
            {
                throw new TypeMissmatchException();
            }

            // changes in the dictionary WILL REFLECT back to the object
            var dict1 = (IDictionary <string, object>)(obj1);
            var dict2 = (IDictionary <string, object>)(obj2);


            var result = new ConfigObject();

            //var rdict = (IDictionary<string, object>) result;

            // first, copy all non colliding keys over
            foreach (var kvp in dict1)
            {
                if (!dict2.Keys.Contains(kvp.Key))
                {
                    bool isDefault = false;
                    if (obj1 is ConfigObject)
                    {
                        object member;
                        if (((ConfigObject)obj1)._members.TryGetValue(kvp.Key, out member) && member is ConfigObjectMember && ((ConfigObjectMember)member).IsDefault)
                        {
                            isDefault = true;
                        }
                    }
                    result.Set(kvp.Key, kvp.Value, isDefault);
                }
            }
            foreach (var kvp in dict2)
            {
                if (!dict1.Keys.Contains(kvp.Key))
                {
                    bool isDefault = false;
                    if (obj2 is ConfigObject)
                    {
                        object member;
                        if (((ConfigObject)obj2)._members.TryGetValue(kvp.Key, out member) && member is ConfigObjectMember && ((ConfigObjectMember)member).IsDefault)
                        {
                            isDefault = true;
                        }
                    }
                    result.Set(kvp.Key, kvp.Value, isDefault);
                }
            }

            // now handle the colliding keys
            foreach (var kvp1 in dict1)
            {
                // skip already copied over keys
                if (!dict2.Keys.Contains(kvp1.Key) || dict2[kvp1.Key] == null)
                {
                    continue;
                }

                var kvp2 = new KeyValuePair <string, object>(kvp1.Key, dict2[kvp1.Key]);

                // some shortcut variables to make code more readable
                object valueToAdd = null;
                var    key        = kvp1.Key;
                var    value1     = kvp1.Value;
                var    value2     = kvp2.Value;
                if (ReferenceEquals(null, value1))
                {
                    valueToAdd = value2;
                }
                else if (ReferenceEquals(null, value2))
                {
                    valueToAdd = value1;
                }
                else
                {
                    var type1 = value1.GetType();
                    var type2 = value2.GetType();
                    if (type1.IsArray && ((Array)value1).Length == 0)
                    {
                        valueToAdd = value2;
                    }
                    else if (type2.IsArray && ((Array)value2).Length == 0)
                    {
                        valueToAdd = value1;
                    }
                    else
                    {
                        // check if both are same type
                        if (type1 != type2)
                        {
                            throw new TypeMissmatchException();
                        }


                        if (value1 is ConfigObject[])
                        {
                            valueToAdd = CollectionMerge(value1, value2);
                        }
                        else if (value1 is ConfigObject)
                        {
                            valueToAdd = Merge(value1, value2);
                        }
                        else if (value1 is string)
                        {
                            valueToAdd = value1;
                        }
                        else if (value1 is IEnumerable)
                        {
                            valueToAdd = CollectionMerge(value1, value2);
                        }
                        else
                        {
                            valueToAdd = value1;
                        }
                    }
                }
                if (ReferenceEquals(null, valueToAdd))
                {
                    valueToAdd = new ConfigObject();
                }

                bool isDefault = false;
                if (obj1 is ConfigObject)
                {
                    object member;
                    if (((ConfigObject)obj1)._members.TryGetValue(key, out member) && member is ConfigObjectMember && ((ConfigObjectMember)member).IsDefault)
                    {
                        isDefault = true;
                    }
                }
                result.Set(key, valueToAdd, isDefault);
            }
            return(result);
        }
Exemplo n.º 20
0
 public static ConfigObject ApplyFromDirectoryInfo(DirectoryInfo info, ConfigObject config = null,
                                                   bool recursive = false)
 {
     return(ApplyFromDirectory(info.FullName, config, recursive));
 }
Exemplo n.º 21
0
 public static ConfigObject ApplyJsonFromPath(string path, ConfigObject config = null)
 {
     return(ApplyJsonFromFileInfo(new FileInfo(path), config));
 }