예제 #1
0
        private static bool SetSpecialTypes <TResponse>(string mimeType, byte[] bytes, IMemoryStreamFactory memoryStreamFactory, out TResponse cs)
            where TResponse : class, IElasticsearchResponse, new()
        {
            cs = null;
            var responseType = typeof(TResponse);

            if (!SpecialTypes.Contains(responseType))
            {
                return(false);
            }

            if (responseType == typeof(StringResponse))
            {
                cs = new StringResponse(bytes.Utf8String()) as TResponse;
            }
            else if (responseType == typeof(BytesResponse))
            {
                cs = new BytesResponse(bytes) as TResponse;
            }
            else if (responseType == typeof(VoidResponse))
            {
                cs = new VoidResponse() as TResponse;
            }
            else if (responseType == typeof(DynamicResponse))
            {
                //if not json store the result under "body"
                if (mimeType != RequestData.MimeType)
                {
                    var dictionary = new DynamicDictionary();
                    dictionary["body"] = new DynamicValue(bytes.Utf8String());
                    cs = new DynamicResponse(dictionary) as TResponse;
                }
                else
                {
                    using (var ms = memoryStreamFactory.Create(bytes))
                    {
                        var body = LowLevelRequestResponseSerializer.Instance.Deserialize <DynamicDictionary>(ms);
                        cs = new DynamicResponse(body) as TResponse;
                    }
                }
            }
            return(cs != null);
        }
예제 #2
0
        /// <summary>
        /// Returns the value as a dictionary if the current value represents an object.
        /// Otherwise returns null.
        /// </summary>
        public IDictionary <string, DynamicValue> ToDictionary()
        {
            if (_value is IDictionary <string, object> dict)
            {
                return(DynamicDictionary.Create(dict));
            }
            else if (_value is JsonElement e && e.ValueKind == JsonValueKind.Object)
            {
                var d = e.EnumerateObject()
                        .Aggregate(new Dictionary <string, object>(), (dictionary, je) =>
                {
                    dictionary.Add(je.Name, je.Value);
                    return(dictionary);
                });
                return(DynamicDictionary.Create(d));
            }

            return(null);
        }
예제 #3
0
        public static object ConsumeJsonElement(Type targetReturnType, JsonElement e)
        {
            // ReSharper disable once HeapView.BoxingAllocation
            object ParseNumber(JsonElement el)
            {
                if (el.TryGetInt64(out var l))
                {
                    return(l);
                }

                return(el.GetDouble());
            }

            return(targetReturnType switch
            {
                _ when targetReturnType == typeof(bool) => e.GetBoolean(),
                _ when targetReturnType == typeof(byte) => e.GetByte(),
                _ when targetReturnType == typeof(decimal) => e.GetDecimal(),
                _ when targetReturnType == typeof(double) => e.GetDouble(),
                _ when targetReturnType == typeof(Guid) => e.GetGuid(),
                _ when targetReturnType == typeof(short) => e.GetInt16(),
                _ when targetReturnType == typeof(int) => e.GetInt32(),
                _ when targetReturnType == typeof(long) => e.GetInt64(),
                _ when targetReturnType == typeof(float) => e.GetSingle(),
                _ when targetReturnType == typeof(string) => e.GetString(),
                _ when targetReturnType == typeof(DateTime) => e.GetDateTime(),
                _ when targetReturnType == typeof(DateTimeOffset) => e.GetDateTimeOffset(),
                _ when targetReturnType == typeof(ushort) => e.GetUInt16(),
                _ when targetReturnType == typeof(uint) => e.GetUInt32(),
                _ when targetReturnType == typeof(ulong) => e.GetUInt64(),
                _ when targetReturnType == typeof(sbyte) => e.GetSByte(),
                _ when targetReturnType == typeof(DynamicDictionary) => DynamicDictionary.Create(e),
                _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.Array =>
                e.EnumerateArray().Select(je => ConsumeJsonElement(targetReturnType, je)).ToArray(),
                _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.Object => e.ToDictionary(),
                _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.True => true,
                _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.False => false,
                _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.Null => null,
                _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.String => e.GetString(),
                _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.Number => ParseNumber(e),
                _ => null
            });
예제 #4
0
        internal bool TryParse(object defaultValue, Type targetReturnType, object value, out object newObject)
        {
            newObject = defaultValue;
            if (value == null)
            {
                return(false);
            }

            if (targetReturnType.IsGenericType && targetReturnType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                targetReturnType = targetReturnType.GenericTypeArguments[0];
            }

            try
            {
                var valueType = value.GetType();
                if (targetReturnType.IsArray && value is DynamicValue v)
                {
                    value     = v.Value;
                    valueType = value.GetType();
                }
                if (targetReturnType.IsArray)
                {
                    if (!valueType.IsArray)
                    {
                        return(false);
                    }
                    var ar          = (object[])value;
                    var t           = targetReturnType.GetElementType();
                    var objectArray = ar
                                      .Select(a => TryParse(defaultValue, t, a, out var o) ? o : null)
                                      .Where(a => a != null)
                                      .ToArray();

                    var arr = Array.CreateInstance(t, objectArray.Length);
                    Array.Copy(objectArray, arr, objectArray.Length);
                    newObject = arr;
                    return(true);
                }

                if (valueType.IsAssignableFrom(targetReturnType))
                {
                    newObject = value;
                    return(true);
                }

                var stringValue = value as string;

                if (targetReturnType == typeof(DateTime) &&
                    DateTime.TryParse(stringValue, CultureInfo.InvariantCulture, DateTimeStyles.None, out var result))
                {
                    newObject = result;
                    return(true);
                }
                if (stringValue != null)
                {
                    if (targetReturnType == typeof(object))
                    {
                        newObject = Convert.ChangeType(value, targetReturnType);
                        return(true);
                    }

                    var converter = TypeDescriptor.GetConverter(targetReturnType);
                    if (converter.IsValid(stringValue))
                    {
                        newObject = converter.ConvertFromInvariantString(stringValue);
                        return(true);
                    }
                }
                else if (value is DynamicValue dv)
                {
                    return(dv.TryParse(defaultValue, targetReturnType, dv.Value, out newObject));
                }
                else if (targetReturnType == typeof(string))
                {
                    newObject = Convert.ChangeType(value, TypeCode.String, CultureInfo.InvariantCulture);
                    return(true);
                }
                else if (valueType.IsValueType)
                {
                    newObject = Convert.ChangeType(_value, targetReturnType);
                    return(true);
                }
                else if (targetReturnType == typeof(DynamicDictionary) && valueType == typeof(Dictionary <string, object>))
                {
                    newObject = DynamicDictionary.Create(value as Dictionary <string, object>);
                    return(true);
                }

                else if (targetReturnType == typeof(object))
                {
                    newObject = value;
                    return(true);
                }
            }
            catch
            {
                return(false);
            }
            return(false);
        }
예제 #5
0
 private static ElasticsearchResponse <DynamicDictionary> ToDynamicResponse(ElasticsearchResponse <Dictionary <string, object> > response)
 {
     return(CloneFrom(response, response.Response != null ? DynamicDictionary.Create(response.Response) : null));
 }
예제 #6
0
 public DynamicResponse(DynamicDictionary dictionary)
 {
     Body       = dictionary;
     Dictionary = dictionary;
 }
예제 #7
0
        /// <summary>
        /// Attempts to convert the value to type of T, failing to do so will return the defaultValue.
        /// </summary>
        /// <typeparam name="T">When no default value is supplied, required to supply the default type</typeparam>
        /// <param name="defaultValue">Optional parameter for default value, if not given it returns default of type T</param>
        /// <returns>If value is not null, value is returned, else default value is returned</returns>
        public T TryParse <T>(T defaultValue = default(T))
        {
            var type = typeof(T);

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                type = type.GenericTypeArguments[0];
            }

            if (HasValue)
            {
                try
                {
                    var valueType = _value.GetType();
                    if (valueType.IsAssignableFrom(typeof(T)))
                    {
                        return((T)_value);
                    }

                    var stringValue = _value as string;

                    if (type == typeof(DateTime))
                    {
                        if (DateTime.TryParse(stringValue, CultureInfo.InvariantCulture, DateTimeStyles.None, out var result))
                        {
                            return((T)(object)result);
                        }
                    }
                    else if (stringValue != null)
                    {
                        if (type == typeof(object))
                        {
                            return((T)Convert.ChangeType(_value, type));
                        }

                        var converter = TypeDescriptor.GetConverter(type);
                        if (converter.IsValid(stringValue))
                        {
                            return((T)converter.ConvertFromInvariantString(stringValue));
                        }
                    }
                    else if (type == typeof(string))
                    {
                        return((T)Convert.ChangeType(_value, TypeCode.String, CultureInfo.InvariantCulture));
                    }
                    else if (valueType.IsValueType)
                    {
                        return((T)Convert.ChangeType(_value, type));
                    }
                    else if (type == typeof(DynamicDictionary) && valueType == typeof(Dictionary <string, object>))
                    {
                        return((T)(object)DynamicDictionary.Create(_value as Dictionary <string, object>));
                    }
                    else if (type == typeof(object))
                    {
                        return((T)_value);
                    }
                }
                catch
                {
                    return(defaultValue);
                }
            }

            return(defaultValue);
        }