예제 #1
0
        /// <summary>
        /// Converts a dictionary to a DataSource
        /// </summary>
        public static DataNode FromDictionary(this IDictionary dic, string name)
        {
            if (dic == null)
            {
                return(null);
            }

            var node = DataNode.CreateObject(name);

            foreach (var key in dic.Keys)
            {
                node.AddField(key.ToString().ToLower(), dic[key]);
            }
            return(node);
        }
예제 #2
0
        /// <summary>
        /// Converts an object to a DataSource
        /// </summary>
        public static DataNode ToDataNode(this object obj, string name = null, bool isArrayElement = false)
        {
            if (obj == null)
            {
                return(null);
            }

            Type type = obj.GetType();

            if (type.IsArray)
            {
                return(FromArray(obj));
            }
            else
            if (IsPrimitive(type))
            {
                throw new Exception("Can't convert primitive type to DataNode");
            }

            TypeInfo info   = null;
            var      fields = Enumerable.Empty <FieldInfo>();

            Type currentClass = type;

            do
            {
                var currentInfo = currentClass.GetTypeInfo();
                if (currentClass == type)
                {
                    info = currentInfo;
                }

                var temp = currentInfo.DeclaredFields.Where(f => f.IsPublic);

                var fieldArray = temp.ToArray();

                fields = temp.Concat(fields);

                currentClass = currentInfo.BaseType;
                if (currentClass == typeof(object))
                {
                    break;
                }
            } while (true);


            if (name == null && !isArrayElement)
            {
                name = type.Name.ToLower();
            }

            var result = DataNode.CreateObject(name);

            foreach (var field in fields)
            {
                var val = field.GetValue(obj);

                var fieldName     = field.Name.ToLower();
                var fieldTypeInfo = field.FieldType.GetTypeInfo();

                if (field.FieldType.IsPrimitive() || fieldTypeInfo.IsEnum)
                {
                    result.AddField(fieldName, val);
                }
                else
                if (fieldTypeInfo.IsArray)
                {
                    var arrayNode = FromArray(val, fieldName);
                    result.AddNode(arrayNode);
                }
                else
                if (val != null)
                {
                    var node = val.ToDataNode(fieldName);
                    result.AddNode(node);
                }
                else
                {
                    result.AddField(fieldName, null);
                }
            }

            return(result);
        }