Esempio n. 1
0
        private IEnumerable <object> ReadObjects <T>(StreamReader sr, IAvroSerializer <T> avroSerializer, Func <object, bool?> filterFunc = null)
        {
            while (true)
            {
                object obj = null;
                try
                {
                    obj = avroSerializer.Deserialize(sr.BaseStream);

                    if (IsDynamicType)
                    {
                        obj = new ChoDynamicObject(obj as Dictionary <string, object>);
                    }
                }
                catch (System.OverflowException)
                {
                    break;
                }
                catch (SerializationException sEx)
                {
                    if (sEx.Message.StartsWith("Invalid integer value in the input stream"))
                    {
                        break;
                    }
                    throw;
                }

                yield return(obj);
            }
        }
Esempio n. 2
0
        public static T ToObject <T>(this ChoDynamicObject obj)
            where T : class, new()
        {
            T ret = ((IDictionary <string, object>)obj).ToObject <T>();

            return(ret);
        }
Esempio n. 3
0
        private object ReadObject(JsonReader reader)
        {
            IDictionary <string, object> expandoObject = new ChoDynamicObject();

            while (reader.Read())
            {
                switch (reader.TokenType)
                {
                case JsonToken.PropertyName:
                    string propertyName = reader.Value.ToString();

                    if (!reader.Read())
                    {
                        throw new Exception("Unexpected end.");
                    }

                    object v = ReadValue(reader);

                    if (_ignoreFields == null || !_ignoreFields.Contains(propertyName))
                    {
                        expandoObject[propertyName] = v;
                    }
                    break;

                case JsonToken.Comment:
                    break;

                case JsonToken.EndObject:
                    return(expandoObject);
                }
            }

            throw new Exception("Unexpected end.");
        }
Esempio n. 4
0
        public static void SetNestedPropertyValue(this object target, string propName, object propValue,
                                                  bool createSubKeysIfNotExists = false, Func <object> factory = null)
        {
            object parent     = null;
            string memberName = null;

            if (GetNestedMember(target, propName, ref parent, ref memberName, createSubKeysIfNotExists, factory))
            {
                if (parent is IDictionary)
                {
                    IDictionary dict = parent as IDictionary;
                    if (dict.Contains(memberName))
                    {
                        dict[memberName] = propValue;
                    }
                    else if (createSubKeysIfNotExists)
                    {
                        dict.Add(memberName, propValue);
                        return;
                    }
                    else
                    {
                        return;
                    }
                }
                else if (parent is IDictionary <string, object> )
                {
                    IDictionary <string, object> dict = parent as IDictionary <string, object>;
                    if (dict.ContainsKey(memberName))
                    {
                        dict[memberName] = propValue;
                    }
                    else if (createSubKeysIfNotExists)
                    {
                        dict.Add(memberName, propValue);
                        return;
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    ChoType.SetPropertyValue(parent, memberName, propValue);
                }
            }
            else
            {
                var child = new ChoDynamicObject();
                return;
            }
        }
Esempio n. 5
0
        public static ChoDynamicObject From(IEnumerable <KeyValuePair <string, object> > kvps, string name = null)
        {
            ChoDynamicObject obj = new ChoDynamicObject(name);

            if (kvps != null)
            {
                foreach (var kvp in kvps)
                {
                    obj.AddOrUpdate(kvp.Key.ToNString(), kvp.Value);
                }
            }

            return(obj);
        }
Esempio n. 6
0
        //public int IndexOf(object item)
        //{
        //	return _list.IndexOf(item);
        //}

        //public void Insert(int index, object item)
        //{
        //	_list.Insert(index, item);
        //}

        //public void RemoveAt(int index)
        //{
        //	_list.RemoveAt(index);
        //}

        //public void Add(object item)
        //{
        //	_list.Add(item);
        //}

        //public bool Contains(object item)
        //{
        //	return _list.Contains(item);
        //}

        //public void CopyTo(object[] array, int arrayIndex)
        //{
        //	_list.CopyTo(array, arrayIndex);
        //}

        //public bool Remove(object item)
        //{
        //	return _list.Remove(item);
        //}
        //List<object> _list = new List<object>();
        //IEnumerator<object> IEnumerable<object>.GetEnumerator()
        //{
        //	return _list.GetEnumerator();
        //}

        //int IList.Add(object value)
        //{
        //	return ((IList)_list).Add(value);
        //}

        //void IList.Remove(object value)
        //{
        //	_list.Remove(value);
        //}

        //public void CopyTo(Array array, int index)
        //{
        //	_list.CopyTo(array.Cast<object>().ToArray(), index);
        //}
        //public int ListCount
        //{
        //	get { return _list.Count;  }
        //}
        //public object GetListItemAt(int index)
        //{
        //	return _list[index];
        //}

        public static ChoDynamicObject FromDictionary(IDictionary kvpDict)
        {
            ChoDynamicObject obj = new ChoDynamicObject();

            if (kvpDict != null)
            {
                foreach (var key in kvpDict.Keys)
                {
                    obj.AddOrUpdate(key.ToNString(), kvpDict[key]);
                }
            }

            return(obj);
        }
Esempio n. 7
0
        public static IEnumerable <dynamic> FlattenBy(this IDictionary <string, object> dict, params string[] fields)
        {
            if (dict == null || fields == null)
            {
                yield return(dict);
            }
            else
            {
                dynamic dest = new ChoDynamicObject();
                dest.Merge(dict);

                FlatternBy1(dict, dest, fields);

                yield return(dest);
            }
        }
        public static dynamic ConvertToNestedObject(this object @this, char separator = '/')
        {
            if (separator == ChoCharEx.NUL)
            {
                throw new ArgumentException("Invalid separator passed.");
            }

            if (@this == null || [email protected]().IsDynamicType())
            {
                return(@this);
            }

            IDictionary <string, object> expandoDic = null;

            expandoDic = @this is ExpandoObject || @this is ChoDynamicObject ? (IDictionary <string, object>)@this : ToExpandoObject(@this as DynamicObject);
            IDictionary <string, object> root = new ChoDynamicObject();

            foreach (var kvp in expandoDic)
            {
                if (kvp.Key.IndexOf(separator) >= 0)
                {
                    var tokens = kvp.Key.SplitNTrim(separator).Where(e => !e.IsNullOrWhiteSpace()).ToArray();
                    IDictionary <string, object> current = root;
                    foreach (var token in tokens.Take(tokens.Length - 1))
                    {
                        if (token.IsNullOrWhiteSpace())
                        {
                            continue;
                        }

                        if (!current.ContainsKey(token))
                        {
                            current.Add(token, new ChoDynamicObject());
                        }

                        current = current[token] as IDictionary <string, object>;
                    }
                    current.AddOrUpdate(tokens[tokens.Length - 1], kvp.Value);
                }
                else
                {
                    root.Add(kvp.Key, kvp.Value);
                }
            }

            return(root as ChoDynamicObject);
        }
Esempio n. 9
0
        public static void ConvertNSetMemberValue(this IDictionary <string, object> dict, string fn, ChoRecordFieldConfiguration fieldConfig, ref object fieldValue, CultureInfo culture)
        {
            ChoDynamicObject dDict = dict as ChoDynamicObject;

            if (fieldValue is ChoDynamicObject)
            {
                ((ChoDynamicObject)fieldValue).DynamicObjectName = fn;
            }

            if (fieldConfig.ValueConverter != null)
            {
                fieldValue = fieldConfig.ValueConverter(fieldValue);
            }
            else
            {
                object[] fcParams = fieldConfig.PropConverterParams;
                if (!fieldConfig.FormatText.IsNullOrWhiteSpace())
                {
                    fcParams = new object[] { new object[] { fieldConfig.FormatText } }
                }
                ;

                if (fieldConfig.Converters.IsNullOrEmpty())
                {
                    fieldValue = ChoConvert.ConvertFrom(fieldValue, fieldConfig.FieldType, null, fieldConfig.PropConverters, fcParams, culture);
                }
                else
                {
                    fieldValue = ChoConvert.ConvertFrom(fieldValue, fieldConfig.FieldType, null, fieldConfig.Converters.ToArray(), fcParams, culture);
                }
            }

            if (dDict != null)
            {
                dDict.AddToDictionary(fn, fieldValue);
            }
            else
            {
                dict.AddOrUpdate(fn, fieldValue);
            }

            if (dDict != null && fieldValue == null && fieldConfig.FieldType != null)
            {
                dDict.SetMemberType(fn, fieldConfig.FieldType);
            }
        }
Esempio n. 10
0
        private object ToDynamicObject(object rec)
        {
            if (!(rec is AvroRecord))
            {
                return(rec);
            }

            var output = new ChoDynamicObject();

            var avroRec = ((AvroRecord)rec);
            var schema  = avroRec.Schema;

            foreach (var f in schema.Fields)
            {
                output.Add(f.Name, ToDynamicObject(avroRec[f.Name]));
            }

            return(output);
        }
Esempio n. 11
0
        public static object ConvertTo(object value, Type targetType, object sourceObject, object[] converters, object[] parameters, CultureInfo culture,
                                       string propName = null)
        {
            Type origType = targetType;

            targetType = targetType.IsNullableType() ? targetType.GetUnderlyingType() : targetType;
            object obj1 = value;

            if (targetType == (Type)null)
            {
                return(value);
            }
            //if (targetType == typeof(object))
            //    return value;
            if (culture == null)
            {
                culture = ChoConvert.DefaultCulture;
            }
            Type type = value == null ? typeof(object) : value.GetType().GetUnderlyingType();

            try
            {
                if (sourceObject is IChoConvertible && !propName.IsNullOrWhiteSpace())
                {
                    var    convObject    = sourceObject as IChoConvertible;
                    object convPropValue = null;
                    if (convObject.ConvertBack(propName, value, targetType, culture, out convPropValue))
                    {
                        return(convPropValue);
                    }
                }

                object objArray = null;
                if (converters.IsNullOrEmpty())
                {
                    converters = ChoTypeDescriptor.GetTypeConvertersForType(type);
                }

                if (converters != null && converters.Length > 0)
                {
                    for (int index = 0; index < converters.Length; ++index)
                    {
                        object conv = converters[index];
                        if (parameters != null && parameters.Length > 0)
                        {
                            objArray = parameters[index];
                        }


                        if (value is IList && !typeof(IChoCollectionConverter).IsAssignableFrom(conv.GetType()))
                        {
                            List <object> retValue = new List <object>();
                            object        lVal     = null;
                            foreach (var item in (IList)value)
                            {
                                if (conv is TypeConverter)
                                {
                                    TypeConverter typeConverter = conv as TypeConverter;
                                    if (typeConverter.CanConvertFrom(type))
                                    {
                                        lVal = typeConverter.ConvertTo((ITypeDescriptorContext)null, culture, item, targetType.GetItemType());
                                    }
                                }
#if !NETSTANDARD2_0
                                else if (conv is IValueConverter)
                                {
                                    lVal = ((IValueConverter)conv).ConvertBack(item, targetType, (object)objArray, culture);
                                }
#endif
                                else if (conv is IChoValueConverter)
                                {
                                    lVal = ((IChoValueConverter)conv).ConvertBack(item, targetType, (object)objArray, culture);
                                }

                                retValue.Add(lVal);
                            }

                            value = retValue.ToArray();
                        }
                        else
                        {
                            if (conv is TypeConverter)
                            {
                                TypeConverter typeConverter = conv as TypeConverter;
                                if (typeConverter.CanConvertFrom(type))
                                {
                                    value = typeConverter.ConvertTo((ITypeDescriptorContext)null, culture, value, targetType);
                                }
                            }
#if !NETSTANDARD2_0
                            else if (conv is IValueConverter)
                            {
                                value = ((IValueConverter)conv).ConvertBack(value, targetType, (object)objArray, culture);
                            }
#endif
                            else if (conv is IChoValueConverter)
                            {
                                value = ((IChoValueConverter)conv).ConvertBack(value, targetType, (object)objArray, culture);
                            }
                        }
                    }
                    if (obj1 != value)
                    {
                        return(value);
                    }
                }
                if (value == null)
                {
                    return(origType.Default());
                }
                if (type == origType)
                {
                    return(value);
                }
                if (targetType.IsAssignableFrom(value.GetType()) || targetType == value.GetType())
                {
                    return(value);
                }

                var srcType = value.GetType();
                var conv1   = TypeDescriptor.GetConverter(targetType);
                if (conv1 != null)
                {
                    try
                    {
                        if (conv1.CanConvertFrom(srcType))
                        {
                            return(conv1.ConvertFrom(value));
                        }
                    }
                    catch { }
                }

                if (value is IConvertible)
                {
                    try
                    {
                        value = Convert.ChangeType(value, targetType, (IFormatProvider)culture);
                        if (obj1 != value)
                        {
                            return(value);
                        }
                    }
                    catch
                    {
                    }
                }
                if (ChoConvert.TryConvertXPlicit(value, targetType, "op_Explicit", ref value) ||
                    ChoConvert.TryConvertXPlicit(value, targetType, "op_Implicit", ref value))
                {
                    //|| (!origType.IsNullableType() && ChoConvert.TryConvertToSpecialValues(value, targetType, culture, out value)))
                    //  || ChoConvert.TryConvertToSpecialValues(value, targetType, culture, out value))
                    return(value);
                }

                if (targetType == typeof(
                        ChoDynamicObject))
                {
                    dynamic ret = new ChoDynamicObject();
                    ret.Value = value;
                    return(ret);
                }

                object result = null;
                if (origType.IsNullableType())
                {
                    return(null);
                }
                else if (ChoConvert.TryConvertToSpecialValues(value, targetType, culture, out result))
                {
                    return(result);
                }

                throw new ApplicationException("Object conversion failed.");
            }
            catch (Exception ex)
            {
                if (type.IsSimple())
                {
                    throw new ApplicationException(string.Format("Can't convert '{2}' value from '{0}' type to '{1}' type.", (object)type, (object)targetType, value), ex);
                }
                throw new ApplicationException(string.Format("Can't convert object from '{0}' type to '{1}' type.", (object)type, (object)targetType), ex);
            }
        }
Esempio n. 12
0
        public static dynamic ToDynamic(this XElement element)
        {
            // loop through child elements
            // define an Expando Dynamic
            dynamic obj = new ChoDynamicObject(element.Name.LocalName);

            // cater for attributes as properties
            if (element.HasAttributes)
            {
                foreach (var attribute in element.Attributes())
                {
                    ((IDictionary <string, object>)obj).Add("@{0}".FormatString(attribute.Name.LocalName), attribute.Value);
                }
            }

            // cater for child nodes as properties, or child objects
            if (element.HasElements)
            {
                foreach (var kvp in element.Elements().GroupBy(e => e.Name.LocalName).Select(g => new { Name = g.Key, Value = g.ToArray() }))
                {
                    if (kvp.Value.Length == 1)
                    {
                        XElement subElement = kvp.Value.First();
                        // if sub element has child elements
                        if (subElement.HasElements)
                        {
                            List <dynamic> subDynamic = new List <dynamic>();
                            foreach (XElement subsubElement in subElement.Elements())
                            {
                                subDynamic.Add(ToDynamic(subsubElement));
                            }
                            // using a bit of recursion lets us cater for an unknown chain of child elements
                            ((IDictionary <string, object>)obj).Add(subElement.Name.LocalName, subDynamic.ToArray());
                        }
                        else
                        {
                            ChoDynamicObject x = new ChoDynamicObject(subElement.Name.LocalName);
                            ((IDictionary <string, object>)x).Add("@@Value", subElement.Value);
                            ((IDictionary <string, object>)obj).Add(subElement.Name.LocalName, x);
                        }
                    }
                    else
                    {
                        int counter = 0;
                        List <ChoDynamicObject> list = new List <ChoDynamicObject>();
                        string keyName = null;
                        foreach (var subElement in kvp.Value)
                        {
                            keyName = subElement.Name.LocalName;

                            // if sub element has child elements
                            if (subElement.HasElements)
                            {
                                List <ChoDynamicObject> subDynamic = new List <ChoDynamicObject>();
                                foreach (XElement subsubElement in subElement.Elements())
                                {
                                    subDynamic.Add(ToDynamic(subsubElement));
                                }
                                // using a bit of recursion lets us cater for an unknown chain of child elements
                                //((IDictionary<string, object>)obj).Add(subElement.Name.LocalName, subDynamic.ToArray());
                                list.AddRange(subDynamic.ToArray());
                            }
                            else
                            {
                                ChoDynamicObject x = new ChoDynamicObject(subElement.Name.LocalName);
                                ((IDictionary <string, object>)x).Add("@@Value", subElement.Value);
                                //((IDictionary<string, object>)obj).Add(subElement.Name.LocalName, x);
                                list.Add(x);
                            }
                        }
                        ((IDictionary <string, object>)obj).Add(keyName, list.ToArray());
                    }
                }
            }
            else
            {
                ((IDictionary <string, object>)obj).Add("@@Value", element.Value);
            }

            return(obj);
        }
Esempio n. 13
0
 public ChoAutoConverter(object value, ChoDynamicObject dynamicObject = null)
 {
     Value          = value;
     _dynamicObject = dynamicObject;
 }