//public async Task<string> PostAsync(string url, List<IFormFile> files)
        //{
        //    var client = _httpClientFactory.CreateClient();
        //    var httpContent = new MultipartFormDataContent();
        //    if (files != null && files.Count > 0)

        //    foreach (var file in files)
        //    {
        //        var byteArr = await file.GetBytesAsync();
        //        var imageContent = new ByteArrayContent(byteArr);
        //        imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
        //    }
        //    var response = await client.PostAsync(url, httpContent);
        //    if (response.StatusCode != HttpStatusCode.OK)
        //        return null;
        //    var resultStr = await response.Content.ReadAsStringAsync();
        //    return resultStr;
        //}

        public async Task <TOutResult> GetAsync <TOutResult>(string url, DeserializeType deserializeType = DeserializeType.JsonDeserialize) where TOutResult : class, new()
        {
            var client   = _httpClientFactory.CreateClient();
            var response = await client.GetAsync(url);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                return(null);
            }
            var resultStr = await response.Content.ReadAsStringAsync();

            TOutResult result = new TOutResult();

            switch (deserializeType)
            {
            case DeserializeType.JsonDeserialize:
                result = JsonConvert.DeserializeObject <TOutResult>(resultStr);
                break;

            case DeserializeType.XmlDeserialize:
                var xmlSerialize = new XmlSerialize();
                result = xmlSerialize.Deserialize <TOutResult>(resultStr);
                break;

            default:
                break;
            }
            return(result);
        }
Beispiel #2
0
        private static void DeserializeError <TObj, TEx>(string s, DeserializeType deserializeType, string expectedExceptionText = null, bool checkAgainstSkylineSchema = true, string expectedSkylineSchemaType = null)
            where TEx : Exception
            where TObj : class
        {
            s = XmlUtil.XML_DIRECTIVE + s;

            XmlSerializer ser = new XmlSerializer(typeof(TObj));

            using (TextReader reader = new StringReader(s))
            {
                String message = null;
                try
                {
                    TObj obj = (TObj)ser.Deserialize(reader);

                    if (deserializeType == DeserializeType.error)
                    {
                        // Fail if deserialization succeeds.
                        Assert.Fail("Expected error deserializing {0}:\r\n{1}", typeof(TObj).Name, s);
                    }

                    if (deserializeType == DeserializeType.roundtrip)
                    {
                        Serializable(obj, Cloned, checkAgainstSkylineSchema, expectedSkylineSchemaType);
                    }
                }
                catch (InvalidOperationException x)
                {
                    message = GetMessageStack(x, null);
                    if (deserializeType == DeserializeType.error)
                    {
                        // Make sure the XML parsing exception was thrown
                        // with the expected innerException type.
                        HasInnerExceptionType(x, typeof(TEx));
                    }
                    else
                    {
                        Assert.Fail("Unexpected exception {0} - {1}:\r\n{2}", typeof(TEx), message, x.StackTrace);
                    }
                }
                catch (TEx x)
                {
                    message = GetMessageStack(x, null);
                    if (deserializeType != DeserializeType.error)
                    {
                        Assert.Fail("Unexpected exception {0} - {1}:\r\n{2}", typeof(TEx), message, x.StackTrace);
                    }
                }
                if (expectedExceptionText != null)
                {
                    if ((message == null) || !message.Contains(expectedExceptionText))
                    {
                        Assert.Fail("Unexpected exception message for {0}: expected to contain\r\n{1}\r\nactual\r\n{2}", typeof(TEx), expectedExceptionText, message ?? "<none>");
                    }
                }
            }
        }
Beispiel #3
0
    /// <summary>
    /// Parses the i dictionary.
    /// </summary>
    /// <param name="value">The value.</param>
    /// <param name="dictType">Type of the dictionary.</param>
    /// <returns>IDictionary.</returns>
    public static IDictionary ParseIDictionary(ReadOnlySpan <char> value, Type dictType)
    {
        if (value.IsEmpty)
        {
            return(null);
        }

        var index = VerifyAndGetStartIndex(value, dictType);

        var valueParseMethod = Serializer.GetParseStringSpanFn(typeof(object));

        if (valueParseMethod == null)
        {
            return(null);
        }

        var to = (IDictionary)dictType.CreateInstance();

        if (Json.JsonTypeSerializer.IsEmptyMap(value, index))
        {
            return(to);
        }

        var valueLength = value.Length;

        while (index < valueLength)
        {
            var keyValue = Serializer.EatMapKey(value, ref index);
            Serializer.EatMapKeySeperator(value, ref index);
            var elementStartIndex = index;
            var elementValue      = Serializer.EatTypeValue(value, ref index);
            if (keyValue.IsEmpty)
            {
                continue;
            }

            var mapKey = valueParseMethod(keyValue);

            if (elementStartIndex < valueLength)
            {
                Serializer.EatWhitespace(value, ref elementStartIndex);
                to[mapKey] = DeserializeType <TSerializer> .ParsePrimitive(elementValue.Value(), value[elementStartIndex]);
            }
            else
            {
                to[mapKey] = valueParseMethod(elementValue);
            }

            Serializer.EatItemSeperatorOrMapEndChar(value, ref index);
        }

        return(to);
    }
Beispiel #4
0
    public static void InitAot <T>()
    {
        var hold = DeserializeBuiltin <T> .Parse;

        hold = DeserializeArray <T[], TSerializer> .Parse;
        DeserializeType <TSerializer> .ExtractType(default(ReadOnlySpan <char>));

        DeserializeArrayWithElements <T, TSerializer> .ParseGenericArray(default(ReadOnlySpan <char>), null);

        DeserializeCollection <TSerializer> .ParseCollection <T>(default(ReadOnlySpan <char>), null, null);

        DeserializeListWithElements <T, TSerializer> .ParseGenericList(default(ReadOnlySpan <char>), null, null);
    }
Beispiel #5
0
        public static IDynamicMetaObjectProvider ParseDynamic(StringSegment value)
        {
            var index = VerifyAndGetStartIndex(value, typeof(ExpandoObject));

            var result = new ExpandoObject();

            if (JsonTypeSerializer.IsEmptyMap(value))
            {
                return(result);
            }

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

            var tryToParsePrimitiveTypes = JsConfig.TryToParsePrimitiveTypeValues;

            var valueLength = value.Length;

            while (index < valueLength)
            {
                var keyValue = Serializer.EatMapKey(value, ref index);
                Serializer.EatMapKeySeperator(value, ref index);
                var elementValue = Serializer.EatValue(value, ref index);

                var mapKey = Serializer.UnescapeString(keyValue).Value;

                if (JsonUtils.IsJsObject(elementValue))
                {
                    container[mapKey] = ParseDynamic(elementValue);
                }
                else if (JsonUtils.IsJsArray(elementValue))
                {
                    container[mapKey] = DeserializeList <List <object>, TSerializer> .ParseStringSegment(elementValue);
                }
                else if (tryToParsePrimitiveTypes)
                {
                    container[mapKey] = DeserializeType <TSerializer> .ParsePrimitive(elementValue)
                                        ?? Serializer.UnescapeString(elementValue);
                }
                else
                {
                    container[mapKey] = Serializer.UnescapeString(elementValue);
                }

                Serializer.EatItemSeperatorOrMapEndChar(value, ref index);
            }

            return(result);
        }
Beispiel #6
0
 public static SetPropertyDelegate GetSetPropertyMethod(Type type, PropertyInfo propertyInfo)
 {
     return(DeserializeType <JsvTypeSerializer> .GetSetPropertyMethod(type, propertyInfo));
 }
Beispiel #7
0
    /// <summary>
    /// Gets the core parse string span function.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns>ParseStringSpanDelegate.</returns>
    private static ParseStringSpanDelegate GetCoreParseStringSpanFn <T>()
    {
        var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);

        if (JsConfig <T> .HasDeserializeFn)
        {
            return(value => JsConfig <T> .ParseFn(Serializer, value.Value()));
        }

        if (type.IsEnum)
        {
            return(x => ParseUtils.TryParseEnum(type, Serializer.UnescapeSafeString(x).Value()));
        }

        if (type == typeof(string))
        {
            return(Serializer.UnescapeStringAsObject);
        }

        if (type == typeof(object))
        {
            return(DeserializeType <TSerializer> .ObjectStringToType);
        }

        var specialParseFn = ParseUtils.GetSpecialParseMethod(type);

        if (specialParseFn != null)
        {
            return(v => specialParseFn(v.Value()));
        }

        if (type.IsArray)
        {
            return(DeserializeArray <T, TSerializer> .ParseStringSpan);
        }

        var builtInMethod = DeserializeBuiltin <T> .ParseStringSpan;

        if (builtInMethod != null)
        {
            return(value => builtInMethod(Serializer.UnescapeSafeString(value)));
        }

        if (type.HasGenericType())
        {
            if (type.IsOrHasGenericInterfaceTypeOf(typeof(IList <>)))
            {
                return(DeserializeList <T, TSerializer> .ParseStringSpan);
            }

            if (type.IsOrHasGenericInterfaceTypeOf(typeof(IDictionary <,>)))
            {
                return(DeserializeDictionary <TSerializer> .GetParseStringSpanMethod(type));
            }

            if (type.IsOrHasGenericInterfaceTypeOf(typeof(ICollection <>)))
            {
                return(DeserializeCollection <TSerializer> .GetParseStringSpanMethod(type));
            }

            if (type.HasAnyTypeDefinitionsOf(typeof(Queue <>)) ||
                type.HasAnyTypeDefinitionsOf(typeof(Stack <>)))
            {
                return(DeserializeSpecializedCollections <T, TSerializer> .ParseStringSpan);
            }

            if (type.IsOrHasGenericInterfaceTypeOf(typeof(KeyValuePair <,>)))
            {
                return(DeserializeKeyValuePair <TSerializer> .GetParseStringSpanMethod(type));
            }

            if (type.IsOrHasGenericInterfaceTypeOf(typeof(IEnumerable <>)))
            {
                return(DeserializeEnumerable <T, TSerializer> .ParseStringSpan);
            }

            var customFn = DeserializeCustomGenericType <TSerializer> .GetParseStringSpanMethod(type);

            if (customFn != null)
            {
                return(customFn);
            }
        }

        var pclParseFn = PclExport.Instance.GetJsReaderParseStringSpanMethod <TSerializer>(typeof(T));

        if (pclParseFn != null)
        {
            return(pclParseFn);
        }

        var isDictionary = typeof(T) != typeof(IEnumerable) && typeof(T) != typeof(ICollection) &&
                           (typeof(T).IsAssignableFrom(typeof(IDictionary)) || typeof(T).HasInterface(typeof(IDictionary)));

        if (isDictionary)
        {
            return(DeserializeDictionary <TSerializer> .GetParseStringSpanMethod(type));
        }

        var isEnumerable = typeof(T).IsAssignableFrom(typeof(IEnumerable)) ||
                           typeof(T).HasInterface(typeof(IEnumerable));

        if (isEnumerable)
        {
            var parseFn = DeserializeSpecializedCollections <T, TSerializer> .ParseStringSpan;
            if (parseFn != null)
            {
                return(parseFn);
            }
        }

        if (type.IsValueType)
        {
            //at first try to find more faster `ParseStringSpan` method
            var staticParseStringSpanMethod = StaticParseMethod <T> .ParseStringSpan;
            if (staticParseStringSpanMethod != null)
            {
                return(value => staticParseStringSpanMethod(Serializer.UnescapeSafeString(value)));
            }

            //then try to find `Parse` method
            var staticParseMethod = StaticParseMethod <T> .Parse;
            if (staticParseMethod != null)
            {
                return(value => staticParseMethod(Serializer.UnescapeSafeString(value).ToString()));
            }
        }
        else
        {
            var staticParseStringSpanMethod = StaticParseRefTypeMethod <TSerializer, T> .ParseStringSpan;
            if (staticParseStringSpanMethod != null)
            {
                return(value => staticParseStringSpanMethod(Serializer.UnescapeSafeString(value)));
            }

            var staticParseMethod = StaticParseRefTypeMethod <TSerializer, T> .Parse;
            if (staticParseMethod != null)
            {
                return(value => staticParseMethod(Serializer.UnescapeSafeString(value).ToString()));
            }
        }

        var typeConstructor = DeserializeType <TSerializer> .GetParseStringSpanMethod(TypeConfig <T> .GetState());

        if (typeConstructor != null)
        {
            return(typeConstructor);
        }

        var stringConstructor = DeserializeTypeUtils.GetParseStringSpanMethod(type);

        return(stringConstructor ?? DeserializeType <TSerializer> .ParseAbstractType <T>);
    }
        public async Task <TOutResult> PostAsync <TOutResult>(string url, string content, DeserializeType deserializeType = DeserializeType.JsonDeserialize, X509Certificate2 cert = null) where TOutResult : class, new()
        {
            var client = _httpClientFactory.CreateClient();

            //HttpResponseMessage sendCertResponse = new HttpResponseMessage();
            if (cert != null)
            {
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri(url),
                    Method     = HttpMethod.Get,
                };
                request.Headers.Add("X-ARR-ClientCert", cert.GetRawCertDataString());
                var sendCertResponse = await client.SendAsync(request);

                if (!sendCertResponse.IsSuccessStatusCode)
                {
                    throw new ASampleException("certificate is error");
                }
            }

            HttpContent httpContent = null;

            if (!string.IsNullOrEmpty(content))
            {
                httpContent = new StringContent(content);
            }

            var response = await client.PostAsync(url, httpContent);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                return(null);
            }
            var resultStr = await response.Content.ReadAsStringAsync();

            TOutResult result = new TOutResult();

            switch (deserializeType)
            {
            case DeserializeType.JsonDeserialize:
                result = JsonConvert.DeserializeObject <TOutResult>(resultStr);
                break;

            case DeserializeType.XmlDeserialize:
                var xmlSerialize = new XmlSerialize();
                result = xmlSerialize.Deserialize <TOutResult>(resultStr);
                break;

            default:
                break;
            }
            return(result);
        }
Beispiel #9
0
            internal static int Register <T, TSerializer>() where TSerializer : ITypeSerializer
            {
                var i = 0;

                if (JsonWriter <T> .WriteFn() != null)
                {
                    i++;
                }
                if (JsonWriter.Instance.GetWriteFn <T>() != null)
                {
                    i++;
                }
                if (JsonReader.Instance.GetParseFn <T>() != null)
                {
                    i++;
                }
                if (JsonReader <T> .Parse(null) != null)
                {
                    i++;
                }
                if (JsonReader <T> .GetParseFn() != null)
                {
                    i++;
                }
                //if (JsWriter.GetTypeSerializer<JsonTypeSerializer>().GetWriteFn<T>() != null) i++;
                if (new List <T>() != null)
                {
                    i++;
                }
                if (new T[0] != null)
                {
                    i++;
                }

                JsConfig <T> .ExcludeTypeInfo = false;

                if (JsConfig <T> .OnDeserializedFn != null)
                {
                    i++;
                }
                if (JsConfig <T> .HasDeserializeFn)
                {
                    i++;
                }
                if (JsConfig <T> .SerializeFn != null)
                {
                    i++;
                }
                if (JsConfig <T> .DeSerializeFn != null)
                {
                    i++;
                }
                //JsConfig<T>.SerializeFn = arg => "";
                //JsConfig<T>.DeSerializeFn = arg => default(T);
                if (TypeConfig <T> .Properties != null)
                {
                    i++;
                }



                // zhaojh
                //if (  WriteType<T, TSerializer>.testsAOT != null ) i++;

                // AOT for ServiceStack.Text.Common.ParseMethodUtilities+<GetParseFn>
                Func <string, T> t = x => default(T);

                DeserializeType <TSerializer> .ParseAbstractType <T> (null);



//*
                if (WriteType <T, TSerializer> .Write != null)
                {
                    i++;
                }
                if (WriteType <object, TSerializer> .Write != null)
                {
                    i++;
                }

                if (DeserializeBuiltin <T> .Parse != null)
                {
                    i++;
                }
                if (DeserializeArray <T[], TSerializer> .Parse != null)
                {
                    i++;
                }
                DeserializeType <TSerializer> .ExtractType(null);

                DeserializeArrayWithElements <T, TSerializer> .ParseGenericArray(null, null);

                DeserializeCollection <TSerializer> .ParseCollection <T>(null, null, null);

                DeserializeListWithElements <T, TSerializer> .ParseGenericList(null, null, null);

                SpecializedQueueElements <T> .ConvertToQueue(null);

                SpecializedQueueElements <T> .ConvertToStack(null);

//*/

                WriteListsOfElements <T, TSerializer> .WriteList(null, null);

                WriteListsOfElements <T, TSerializer> .WriteIList(null, null);

                WriteListsOfElements <T, TSerializer> .WriteEnumerable(null, null);

                WriteListsOfElements <T, TSerializer> .WriteListValueType(null, null);

                WriteListsOfElements <T, TSerializer> .WriteIListValueType(null, null);

                WriteListsOfElements <T, TSerializer> .WriteGenericArrayValueType(null, null);

                WriteListsOfElements <T, TSerializer> .WriteArray(null, null);

                TranslateListWithElements <T> .LateBoundTranslateToGenericICollection(null, null);

                TranslateListWithConvertibleElements <T, T> .LateBoundTranslateToGenericICollection(null, null);

                QueryStringWriter <T> .WriteObject(null, null);

                return(i);
            }