예제 #1
1
        public async override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {

            if (!content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var Parts = await content.ReadAsMultipartAsync();
            var FileContent = Parts.Contents.First(x =>
                SupportedMediaTypes.Contains(x.Headers.ContentType));

            var DataString = "";
            foreach (var Part in Parts.Contents.Where(x => x.Headers.ContentDisposition.DispositionType == "form-data"
                                                        && x.Headers.ContentDisposition.Name == "\"data\""))
            {
                var Data = await Part.ReadAsStringAsync();
                DataString = Data;
            }

            string FileName = FileContent.Headers.ContentDisposition.FileName;
            string MediaType = FileContent.Headers.ContentType.MediaType;

            using (var Imgstream = await FileContent.ReadAsStreamAsync())
            {
                return new GenericContent { ContentType = MediaType, Body = ReadToEnd(Imgstream) };
            }
        }
 public override object ReadFromStream(Type type, Stream stream, HttpContent content,
                                       IFormatterLogger formatterLogger) {
     Encoding selectedEncoding = SelectCharacterEncoding(content.Headers);
     using (var reader = new StreamReader(stream, selectedEncoding)) {
         return reader.ReadToEnd();
     }
 }
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
        {
            var taskCompletionSource = new TaskCompletionSource<object>();

            try
            {
                BsonReader reader = new BsonReader(readStream);
                if (typeof(IEnumerable).IsAssignableFrom(type)) reader.ReadRootValueAsArray = true;

                using (reader)
                {
                    var jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings);
                    var output = jsonSerializer.Deserialize(reader, type);
                    if (formatterLogger != null)
                    {
                        jsonSerializer.Error += (sender, e) =>
                        {
                            Exception exception = e.ErrorContext.Error;
                            formatterLogger.LogError(e.ErrorContext.Path, exception.Message);
                            e.ErrorContext.Handled = true;
                        };
                    }
                    taskCompletionSource.SetResult(output);
                }
            }
            catch (Exception ex)
            {
                if (formatterLogger == null) throw;
                formatterLogger.LogError(String.Empty, ex.Message);
                taskCompletionSource.SetResult(GetDefaultValueForType(type));
            }

            return taskCompletionSource.Task;
        }
예제 #4
0
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return Task.Factory.StartNew<object>( () => 
            {
                try
                {
                    var body = base.ReadBodyFromStream(readStream, content);

                    if (type == typeof(Bundle))
                    {
                        if (XmlSignatureHelper.IsSigned(body))
                        {
                            if (!XmlSignatureHelper.VerifySignature(body))
                                throw Error.BadRequest("Digital signature in body failed verification");
                        }
                    }

                    if (typeof(Resource).IsAssignableFrom(type))
                    {
                        Resource resource = FhirParser.ParseResourceFromXml(body);
                        return resource;
                    }
                    else
                        throw Error.Internal("The type {0} expected by the controller can not be deserialized", type.Name);
                }
                catch (FormatException exc)
                {
                    throw Error.BadRequest("Body parsing failed: " + exc.Message);
                }
            });
        }
예제 #5
0
        private object DeSerialize(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
        {
            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;

            // If content length is 0 then return default value for this type
            if (contentHeaders != null && contentHeaders.ContentLength == 0)
            {
                return GetDefaultValueForType(type);
            }

            // Get the character encoding for the content
            Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders);

            try
            {
                using (var reader = new StreamReader(readStream, effectiveEncoding, false, 512, true))
                {
                    var deserialize = TypedDeserializers.GetTyped(type);
                    return deserialize(reader, _jilOptions);
                }
            }
            catch (Exception e)
            {
                if (formatterLogger == null)
                {
                    throw;
                }
                formatterLogger.LogError(String.Empty, e);
                return GetDefaultValueForType(type);
            }
        }
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
        {
            var task = Task<object>.Factory.StartNew(() =>
            {
                var ser = JsonNetExtensions.GetJsonSerializer();

                using (var sr = new StreamReader(readStream))
                {
                    using (var jreader = new JsonTextReader(sr))
                    {
                        ser.Converters.Add(new IsoDateTimeConverter());
                        return ser.Deserialize(jreader, type);
                    }
                }
                /*
                var sr = new StreamReader(stream);
                var jreader = new JsonTextReader(sr);

                var ser = new JsonSerializer();
                ser.Converters.Add(new IsoDateTimeConverter());

                object val = ser.Deserialize(jreader, type);
                return val;*/
            });

            return task;
        }
예제 #7
0
 public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
 {
     var reader = new StreamReader(readStream);
     var deserialize = TypedDeserializers.GetTyped(type);
     var result = deserialize(reader, options);
     return Task.FromResult(result);
 }
예제 #8
0
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return Task.Factory.StartNew(() =>
            {
                MemoryStream stream = new MemoryStream();
                readStream.CopyTo(stream);

                IEnumerable<string> xContentHeader;
                var success = content.Headers.TryGetValues("X-Content-Type", out xContentHeader);

                if (!success)
                {
                    throw Error.BadRequest("POST to binary must provide a Content-Type header");
                }

                string contentType = xContentHeader.FirstOrDefault();

                Binary binary = new Binary();
                binary.Content = stream.ToArray();
                binary.ContentType = contentType;

                //ResourceEntry entry = ResourceEntry.Create(binary);
                //entry.Tags = content.Headers.GetFhirTags();
                return (object)binary;
            });
        }
예제 #9
0
        //public JsonFormatter()
        //{
        //  SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json"));
        //  SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
        //}
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var task = new TaskCompletionSource<object>();

              using (var ms = new MemoryStream())
              {
            readStream.CopyTo(ms);
            //ms.Seek(0, SeekOrigin.Begin);

            //var result = JsonSchemaValidator.Instance().Validate(ms, type);

            //if (!string.IsNullOrWhiteSpace(result))
            //  task.SetResult(result);
            //else
            {
              ms.Seek(0, SeekOrigin.Begin);
              using (var reader = new JsonTextReader(new StreamReader(ms)))
              {
            var serializer = new JsonSerializer();
            task.SetResult(serializer.Deserialize(reader, type));
              }
            }
              }
              return task.Task;
        }
        /// <inheritdoc />
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            if (readStream == null)
            {
                throw Error.ArgumentNull("readStream");
            }

            if (type == typeof(DBNull) && content != null && content.Headers != null && content.Headers.ContentLength == 0)
            {
                // Lower-level Json.Net deserialization can convert null to DBNull.Value. However this formatter treats
                // DBNull.Value like null and serializes no content. Json.Net code won't be invoked at all (for read or
                // write). Override BaseJsonMediaTypeFormatter.ReadFromStream()'s call to GetDefaultValueForType()
                // (which would return null in this case) and instead return expected DBNull.Value. Special case exists
                // primarily for parity with JsonMediaTypeFormatter.
                return Task.FromResult((object)DBNull.Value);
            }
            else
            {
                return base.ReadFromStreamAsync(type, readStream, content, formatterLogger);
            }
        }
예제 #11
0
        public override async Task<object> ReadFromStreamAsync(Type type, Stream stream,
                                                        HttpContent httpContent,
                                                        IFormatterLogger iFormatterLogger)
        {
            MultipartStreamProvider parts = await httpContent.ReadAsMultipartAsync();
            IEnumerable<HttpContent> contents = parts.Contents;

            HttpContent content = contents.FirstOrDefault();
            foreach (HttpContent c in contents ) {
                if (SupportedMediaTypes.Contains(c.Headers.ContentType)) {
                    content = c;
                    break;
                }
            }

            using (var msgStream = await content.ReadAsStreamAsync())
            {
                DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(TenMsg));
                TenMsg msg = (TenMsg)js.ReadObject(msgStream);
                Debug.WriteLine("msgString: " + msgStream.ToString());

                int sender = msg.Sender;
                int receiver = msg.Receiver;
                byte phoneType = msg.PhoneType;
                bool isLocked = msg.IsLocked;
                DateTime msgTime = msg.MsgTime;
                string msgContent = msg.MsgContent;
                Debug.WriteLine("Msg Content: " + msg.MsgContent);
                
                return new TenMsg(sender, receiver, phoneType, isLocked, msgTime, msgContent);
            }
        }
예제 #12
0
 public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
 {
     return Task.Factory.StartNew(() =>
     {
         return (object)null;
     });
 }
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var tcs = new TaskCompletionSource<object>();
            if (content != null && content.Headers.ContentLength == 0) return null;

            try
            {
                var reader = new BsonReader(readStream);

                if (typeof(IEnumerable).IsAssignableFrom(type)) reader.ReadRootValueAsArray = true;

                using (reader)
                {
                    var jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings);
                    var output = jsonSerializer.Deserialize(reader, type);
                    tcs.SetResult(output);
                }
            }
            catch (Exception)
            {
                tcs.SetResult(GetDefaultValueForType(type));
            }

            return tcs.Task;
        }
예제 #14
0
 public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
 {
     MultipartMemoryStreamProvider multipartMemoryStreamProvider = await content.ReadAsMultipartAsync();
     Collection<HttpContent> contents = multipartMemoryStreamProvider.Contents;
     ImageSet imageSet = await contents.FirstOrDefault<HttpContent>((HttpContent c) => c.Headers.ContentDisposition.Name.NormalizeName() == "imageset").ReadAsAsync<ImageSet>();
     ImageSet images = imageSet;
     Collection<HttpContent> httpContents = multipartMemoryStreamProvider.Contents;
     List<HttpContent> list = (
         from c in httpContents
         where c.Headers.ContentDisposition.Name.NormalizeName().Matches("image\\d+")
         select c).ToList<HttpContent>();
     images.Images = new List<Image>();
     foreach (HttpContent httpContent in list)
     {
         List<Image> images1 = images.Images;
         Image image = new Image();
         Image image1 = image;
         image1.ImageData = await httpContent.ReadAsByteArrayAsync();
         image.MimeType = httpContent.Headers.ContentType.MediaType;
         image.FileName = httpContent.Headers.ContentDisposition.FileName.NormalizeName();
         images1.Add(image);
         images1 = null;
         image1 = null;
         image = null;
     }
     return images;
 }
예제 #15
0
        private async Task<object> Deserialize(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {


            var headers = (content == null) ? null : content.Headers;
            if (headers != null && headers.ContentLength == 0L)
            {
                return MediaTypeFormatter.GetDefaultValueForType(type);
            }

            object result = null;
            try
            {

                result = DeserializeByJsonSerializer(type, readStream, headers);

            }
            catch (Exception exception)
            {
                if (formatterLogger != null)
                {
                    formatterLogger.LogError(string.Empty, exception);
                }

                result = MediaTypeFormatter.GetDefaultValueForType(type);
            }

            return result;
        }
예제 #16
0
        public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var tcs = new TaskCompletionSource<object>();
            if (content.Headers != null && content.Headers.ContentLength == 0) return null;
            try
            {
                var serializer = MessagePackSerializer.Get(type, sContext);
                object result;

                using (var unpacker = Unpacker.Create(stream))
                {
                    unpacker.Read();
                    result = serializer.UnpackFrom(unpacker);
                }
                tcs.SetResult(result);
            }
            catch (Exception e)
            {
                if (formatterLogger == null) throw;
                formatterLogger.LogError(String.Empty, e.Message);
                tcs.SetResult(GetDefaultValueForType(type));
            }

            return tcs.Task;
        }
예제 #17
0
        public async override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var imageSet = new ImageSet();

            var provider = await content.ReadAsMultipartAsync();

            //extract model
            var modelContent = provider.Contents.FirstOrDefault(c => c.Headers.ContentDisposition.Name.NormalizeName() == "imageset");
            if (modelContent != null)
            {
                imageSet = await modelContent.ReadAsAsync<ImageSet>();
            }

            if (!imageSet.Images.Any())
            {
                //try extract from image content
                var fileContents = provider.Contents.Where(c => c.Headers.ContentDisposition.Name.NormalizeName().Matches(@"image\d+")).ToList();
                foreach (var fileContent in fileContents)
                {
                    imageSet.Images.Add(new Image
                    {
                        FileName = fileContent.Headers.ContentDisposition.FileName.NormalizeName(),
                        MimeType = fileContent.Headers.ContentType.MediaType,
                        Side = GetSide(fileContent),
                        ImageData = await fileContent.ReadAsByteArrayAsync()
                    });
                }
            }

            return imageSet;
        }
        private object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var root = GetRootFieldName(type);
            var contentHeaders = content == null ? null : content.Headers;

            // If content length is 0 then return default value for this type
            if (contentHeaders != null && contentHeaders.ContentLength == 0)
                return GetDefaultValueForType(type);

            // Get the character encoding for the content
            var effectiveEncoding = SelectCharacterEncoding(contentHeaders);

            try
            {
                using (var reader = (new StreamReader(readStream, effectiveEncoding)))
                {
                    var json = reader.ReadToEnd();
                    var serializer = new EmberJsonSerializer();
                    var deserialized = serializer.Deserialize(json, root);
                    return deserialized.ToObject(type);
                }
            }
            catch (Exception e)
            {
                if (formatterLogger == null)
                {
                    throw;
                }
                formatterLogger.LogError(String.Empty, e);
                return GetDefaultValueForType(type);
            }
        }
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (readStream == null)
            {
                throw new ArgumentNullException("readStream");
            }

            var completion = new TaskCompletionSource<object>();

            if (cancellationToken.IsCancellationRequested)
            {
                completion.SetCanceled();
            }
            else
            {
                try
                {
                    var value = ReadValue(type, readStream, content, formatterLogger);
                    completion.SetResult(value);
                }
                catch (Exception ex)
                {
                    completion.SetException(ex);
                }
            }

            return completion.Task;
        }
예제 #20
0
        public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
        {
            Task<IEnumerable<HttpContent>> readAsMultipartAsync = _httpRequestMessage.Content.ReadAsMultipartAsync();

            IEnumerable<HttpContent> httpContents = readAsMultipartAsync.Result;

            HttpContent content = httpContents.First(x => SupportedMediaTypes.Contains(x.Headers.ContentType));

            string fileName = content.Headers.ContentDisposition.FileName;
            string mediaType = content.Headers.ContentType.MediaType;

            Task<Stream> readAsStreamAsync = content.ReadAsStreamAsync();

            byte[] readFully = readAsStreamAsync.Result.ReadFully();

            var taskCompletionSource = new TaskCompletionSource<object>();

            taskCompletionSource.SetResult(new ImageMedia(fileName, mediaType, readFully));

            return taskCompletionSource.Task;

            //            var taskCompletionSource = new TaskCompletionSource<object>();
            //            try
            //            {
            //                var memoryStream = new MemoryStream();
            //                stream.CopyTo(memoryStream);
            //                var s = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
            //                taskCompletionSource.SetResult(s);
            //            }
            //            catch (Exception e)
            //            {
            //                taskCompletionSource.SetException(e);
            //            }
            //            return taskCompletionSource.Task;
        }
        public override object ReadFromStream(Type type, Stream stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
        {
            BufferedMediaTypeFormatter innerFormatter = InnerBufferedFormatter;
            MediaTypeHeaderValue contentType = contentHeaders == null ? null : contentHeaders.ContentType;
            object value = null;

            _innerTracer.TraceWriter.TraceBeginEnd(
                _innerTracer.Request,
                TraceCategories.FormattingCategory,
                TraceLevel.Info,
                _innerTracer.InnerFormatter.GetType().Name,
                OnReadFromStreamMethodName,
                beginTrace: (tr) =>
                {
                    tr.Message = Error.Format(
                            SRResources.TraceReadFromStreamMessage,
                            type.Name,
                            contentType == null ? SRResources.TraceNoneObjectMessage : contentType.ToString());
                },
                execute: () =>
                {
                    value = innerFormatter.ReadFromStream(type, stream, contentHeaders, formatterLogger);
                },
                endTrace: (tr) =>
                {
                    tr.Message = Error.Format(
                                SRResources.TraceReadFromStreamValueMessage,
                                FormattingUtilities.ValueToString(value, CultureInfo.CurrentCulture));
                },
                errorTrace: null);

            return value;
        }
예제 #22
0
 public override System.Threading.Tasks.Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
 {
     return new TaskFactory<object>().StartNew(() =>
                                                   {
                                                       return new StreamReader(stream).ReadToEnd();
                                                   });
 }
예제 #23
0
 public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
 {
     using (var streamReader = new StreamReader(readStream))
     {
         return await streamReader.ReadToEndAsync();
     }
 }
        public override object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) {

            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;

            // If content length is 0 then return default value for this type
            if (contentHeaders != null && contentHeaders.ContentLength == null) {

                return GetDefaultValueForType(type);
            }

            try {
                using (readStream) {
                    using (var reader = XmlReader.Create(readStream)) {

                        var formatter = new Atom10ItemFormatter();
                        formatter.ReadFrom(reader);

                        var command = Activator.CreateInstance(type);
                        ((IPublicationCommand)command).ReadSyndicationItem(formatter.Item);

                        return command;
                    }
                }
            }
            catch (Exception e) {

                if (formatterLogger == null) {
                    throw;
                }
                formatterLogger.LogError(String.Empty, e);
                return GetDefaultValueForType(type);
            }
        }
예제 #25
0
    //private readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    //public XmlFormatter()
    //{
    //  SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
    //  SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
    //}

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
    {
      var task = new TaskCompletionSource<object>();
      var serializer = new XmlSerializer(type);

      using (var ms = new MemoryStream())
      {
        readStream.CopyTo(ms);

        //ms.Seek(0, SeekOrigin.Begin);

        //Log.IfDebugFormat("Content Length: {0}", ms.Length);
        //Log.IfDebugFormat("Content: {0}", new StreamReader(ms).ReadToEnd());

        //var result = XmlSchemaValidator.Instance().Validate(ms, type);

        //if (!string.IsNullOrWhiteSpace(result))
        //task.SetResult(result);
        //else
        {
          ms.Seek(0, SeekOrigin.Begin);
          var obj = serializer.Deserialize(ms);
          task.SetResult(obj);
        }
      }
      return task.Task;
    }
 public ReadFromStreamArgs(Type type, Stream stream, HttpContent content, IFormatterLogger logger)
 {
     Type = type;
     Stream = stream;
     Content = content;
     Logger = logger;
 }
예제 #27
0
        public override Task<object> ReadFromStreamAsync(Type type, System.IO.Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return Task<object>.Factory.StartNew(() =>
            {
                var reader = new StreamReader(readStream);
                var text = reader.ReadToEnd();

                var regex = new Regex("<wav>[a-zA-Z0-9]*.wav</wav>");
                var wavLink = regex.Match(text).Value.Replace("<wav>", "").Replace("</wav>", "");
                if(string.IsNullOrEmpty(wavLink))
                {
                    wavLink  = "{wav}";
                }

                //<dt>:
                regex = new Regex("<dt>:[a-zA-Z0-9 '.s\"\\(\\):]*<");
                var def = regex.Match(text).Value.Replace("<dt>:", "").Replace("<", "");
                if(string.IsNullOrEmpty(def))
                {
                    def = "{def}";
                }

                return wavLink + ";" +def;
            });
        }
예제 #28
0
        public async override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
        {
            try
            {
                if (!content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                var provider = await content.ReadAsMultipartAsync();

                var mediacontent = provider.Contents.First(x =>
                    SupportedMediaTypes.Contains(x.Headers.ContentType));

                string fileName = mediacontent.Headers.ContentDisposition.FileName;

                string mediaType = mediacontent.Headers.ContentType.MediaType;

                var imagebuffer = await mediacontent.ReadAsByteArrayAsync();

                return new ImageMediaModels(fileName, mediaType, imagebuffer);
            }
            catch (Exception Ex)
            {
                string Err = "Unable to upload the image ";
                Log.LogError("{0}, Error: {1}", Err, Ex.Message);
                throw;
            }
                   
        }
예제 #29
0
 public override Task<object> ReadFromStreamAsync(Type type, Stream input, HttpContent content, IFormatterLogger formatterLogger)
 {
     var reader = new StreamReader(input);
     Func<TextReader, Options, object> deserialize = TypedDeserializers.GetTyped(type);
     object result = deserialize(reader, _options);
     return Task.FromResult(result);
 }
예제 #30
0
        public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger logger)
        {
            var trades = new Trades();
            var symbol = _symbol;

            using (var reader = new StreamReader(stream))
            {
                var line = reader.ReadLine();
                var seperator = ",".ToCharArray();

                while (null != (line = reader.ReadLine()))
                {
                    if (!line.Contains("502 Bad Gateway"))
                    {
                        var parts = line.Split(seperator);

                        var unixtime = parts[0].Parse();
                        var price = decimal.Parse(parts[1], CultureInfo.InvariantCulture);
                        var quantity = decimal.Parse(parts[2], CultureInfo.InvariantCulture);

                        var datetime = Epoch.AddSeconds(unixtime);

                        trades.Add(symbol, datetime, price, quantity);
                    }
                    else throw new Exception("Bad Gateway");
                }
            }

            var tcs = new TaskCompletionSource<object>();
            tcs.SetResult(trades);
            return tcs.Task;
        }
예제 #31
0
        // Perf-sensitive - keeping the async method as small as possible
        private async Task ExecuteBindingAsyncCore(ModelMetadataProvider metadataProvider, HttpActionContext actionContext,
                                                   HttpParameterDescriptor paramFromBody, Type type, HttpRequestMessage request, IFormatterLogger formatterLogger,
                                                   CancellationToken cancellationToken)
        {
            var model = await ReadContentAsync(request, type, Formatters, formatterLogger, cancellationToken);

            if (model == null)
            {
                model = System.Activator.CreateInstance(type);
            }
            ;
            var routeParams = actionContext.ControllerContext.RouteData.Values;

            foreach (var key in routeParams.Keys.Where(k => k != "controller"))
            {
                var prop = type.GetProperty(key, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);
                if (prop == null)
                {
                    continue;
                }
                var descriptor = TypeDescriptor.GetConverter(prop.PropertyType);
                if (descriptor.CanConvertFrom(typeof(string)))
                {
                    prop.SetValue(model, descriptor.ConvertFromString(routeParams[key] as string));
                }
            }

            var queryParams = actionContext.Request.GetQueryNameValuePairs();

            foreach (var queryParam in queryParams)
            {
                var prop = type.GetProperty(queryParam.Key, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);
                if (prop == null)
                {
                    continue;
                }
                var descriptor = TypeDescriptor.GetConverter(prop.PropertyType);
                if (descriptor.CanConvertFrom(typeof(string)))
                {
                    prop.SetValue(model, descriptor.ConvertFromString(queryParam.Value));
                }
            }

            // Set the merged model in the context
            SetValue(actionContext, model);

            if (BodyModelValidator != null)
            {
                BodyModelValidator.Validate(model, type, metadataProvider, actionContext, paramFromBody.ParameterName);
            }
        }
예제 #32
0
        public override object ReadFromStream(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (!typeof(Representation).IsAssignableFrom(type))
            {
                return(null);
            }

            var xml = XElement.Load(stream);

            return(ReadHalResource(type, xml));
        }
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var task = Task.Factory.StartNew(() =>
            {
                using (var rdr = new StreamReader(readStream))
                {
                    var json = rdr.ReadToEnd();

                    JavaScriptSerializer ser = new JavaScriptSerializer();

                    object result = ser.Deserialize(json, type);

                    return(result);
                }
            });

            return(task);
        }
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (readStream == null)
            {
                throw new ArgumentNullException("readStream");
            }

            // For simple types, defer to base class
            if (base.CanReadType(type))
            {
                return(base.ReadFromStreamAsync(type, readStream, content, formatterLogger));
            }

            return(base.ReadFromStreamAsync(typeof(FormDataCollection), readStream, content, formatterLogger).Then(
                       (obj) =>
            {
                FormDataCollection fd = (FormDataCollection)obj;

                try
                {
                    return fd.ReadAs(type, String.Empty, RequiredMemberSelector, formatterLogger);
                }
                catch (Exception e)
                {
                    if (formatterLogger == null)
                    {
                        throw;
                    }
                    formatterLogger.LogError(String.Empty, e);
                    return GetDefaultValueForType(type);
                }
            }));
        }
예제 #35
0
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var taskSource = new TaskCompletionSource <object>();

            try
            {
                var obj = new XmlSerializer(type).Deserialize(readStream);
                taskSource.SetResult(obj);
            }
            catch (Exception e)
            {
                taskSource.SetException(e);
            }
            return(taskSource.Task);
        }
        private object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;

            // If content length is 0 then return default value for this type
            if (contentHeaders != null && contentHeaders.ContentLength == 0)
            {
                return(GetDefaultValueForType(type));
            }

            // Get the character encoding for the content
            Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders);

            try
            {
                using (JsonTextReader jsonTextReader = new JsonTextReader(new StreamReader(readStream, effectiveEncoding))
                {
                    CloseInput = false, MaxDepth = _maxDepth
                })
                {
                    JsonSerializer jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings);
                    if (formatterLogger != null)
                    {
                        // Error must always be marked as handled
                        // Failure to do so can cause the exception to be rethrown at every recursive level and overflow the stack for x64 CLR processes
                        jsonSerializer.Error += (sender, e) =>
                        {
                            Exception exception = e.ErrorContext.Error;
                            formatterLogger.LogError(e.ErrorContext.Path, exception);
                            e.ErrorContext.Handled = true;
                        };
                    }
                    return(jsonSerializer.Deserialize(jsonTextReader, type));
                }
            }
            catch (Exception e)
            {
                if (formatterLogger == null)
                {
                    throw;
                }
                formatterLogger.LogError(String.Empty, e);
                return(GetDefaultValueForType(type));
            }
        }
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (readStream == null)
            {
                throw new ArgumentNullException("readStream");
            }

            try
            {
                return(TaskHelpers.FromResult(ReadFromStream(type, readStream, content, formatterLogger)));
            }
            catch (Exception e)
            {
                return(TaskHelpers.FromError <object>(e));
            }
        }
예제 #38
0
        private object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            object result;

            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;

            // If content length is 0 then return default value for this type
            if (contentHeaders == null || contentHeaders.ContentLength == 0)
            {
                result = GetDefaultValueForType(type);
            }
            else
            {
                IEdmModel model = Request.ODataProperties().Model;
                if (model == null)
                {
                    throw Error.InvalidOperation(SRResources.RequestMustHaveModel);
                }

                IEdmTypeReference expectedPayloadType;
                ODataDeserializer deserializer = GetDeserializer(type, Request.ODataProperties().Path, model, _deserializerProvider, out expectedPayloadType);
                if (deserializer == null)
                {
                    throw Error.Argument("type", SRResources.FormatterReadIsNotSupportedForType, type.FullName, GetType().FullName);
                }

                try
                {
                    ODataMessageReaderSettings oDataReaderSettings = new ODataMessageReaderSettings(MessageReaderSettings);
                    oDataReaderSettings.BaseUri = GetBaseAddressInternal(Request);

                    IODataRequestMessage oDataRequestMessage = new ODataMessageWrapper(readStream, contentHeaders, Request.GetODataContentIdMapping());
                    ODataMessageReader   oDataMessageReader  = new ODataMessageReader(oDataRequestMessage, oDataReaderSettings, model);

                    Request.RegisterForDispose(oDataMessageReader);
                    ODataPath path = Request.ODataProperties().Path;
                    ODataDeserializerContext readContext = new ODataDeserializerContext
                    {
                        Path            = path,
                        Model           = model,
                        Request         = Request,
                        ResourceType    = type,
                        ResourceEdmType = expectedPayloadType,
                        RequestContext  = Request.GetRequestContext(),
                    };

                    result = deserializer.Read(oDataMessageReader, type, readContext);
                }
                catch (Exception e)
                {
                    if (formatterLogger == null)
                    {
                        throw;
                    }

                    formatterLogger.LogError(String.Empty, e);
                    result = GetDefaultValueForType(type);
                }
            }

            return(result);
        }
예제 #39
0
 protected virtual Task <object> ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable <MediaTypeFormatter> formatters, IFormatterLogger formatterLogger)
 {
     return(request.Content.ReadAsAsync(type, formatters, formatterLogger));
 }
예제 #40
0
        public override Task <object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
        {
            string value;

            using (var reader = new StreamReader(stream))
            {
                value = reader.ReadToEnd();
            }

            var tcs = new TaskCompletionSource <object>();

            tcs.SetResult(value);
            return(tcs.Task);
        }
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            try
            {
                var body = base.ReadBodyFromStream(readStream, content);

                if (type == typeof(Bundle))
                {
                    if (XmlSignatureHelper.IsSigned(body))
                    {
                        if (!XmlSignatureHelper.VerifySignature(body))
                        {
                            //throw Error.BadRequest("Digital signature in body failed verification");
                            throw new InterneuronBusinessException((short)HttpStatusCode.BadRequest, "Digital signature in body failed verification");
                        }
                    }
                }

                if (typeof(Resource).IsAssignableFrom(type))
                {
                    Resource resource = _parser.Parse <Resource>(body);
                    return(System.Threading.Tasks.Task.FromResult <object>(resource));
                }
                else
                {
                    //throw Error.Internal("The type {0} expected by the controller can not be deserialized", type.Name);
                    throw new InterneuronBusinessException((short)HttpStatusCode.InternalServerError, $"The type {type.Name} expected by the controller can not be deserialized");
                }
            }
            catch (FormatException exc)
            {
                //throw Error.BadRequest("Body parsing failed: " + exc.Message);
                throw new InterneuronBusinessException(exc, (short)HttpStatusCode.BadRequest, "Body parsing failed: " + exc.Message);
            }
        }
예제 #42
0
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            if (readStream == null)
            {
                throw Error.ArgumentNull("readStream");
            }

            if (Request == null)
            {
                throw Error.InvalidOperation(SRResources.ReadFromStreamAsyncMustHaveRequest);
            }

            try
            {
                return(Task.FromResult(ReadFromStream(type, readStream, content, formatterLogger)));
            }
            catch (Exception ex)
            {
                return(TaskHelpers.FromError <object>(ex));
            }
        }
        private Task <object> ReadFromStreamAsyncCore(
            Type type,
            Stream readStream,
            HttpContent content,
            IFormatterLogger formatterLogger,
            CancellationToken?cancellationToken
            )
        {
            HttpContentHeaders   contentHeaders = content == null ? null : content.Headers;
            MediaTypeHeaderValue contentType    =
                contentHeaders == null ? null : contentHeaders.ContentType;

            IFormatterLogger formatterLoggerTraceWrapper =
                (formatterLogger == null)
                    ? null
                    : new FormatterLoggerTraceWrapper(
                    formatterLogger,
                    TraceWriter,
                    Request,
                    InnerFormatter.GetType().Name,
                    ReadFromStreamAsyncMethodName
                    );

            return(TraceWriter.TraceBeginEndAsync <object>(
                       Request,
                       TraceCategories.FormattingCategory,
                       TraceLevel.Info,
                       InnerFormatter.GetType().Name,
                       ReadFromStreamAsyncMethodName,
                       beginTrace: (tr) =>
            {
                tr.Message = Error.Format(
                    SRResources.TraceReadFromStreamMessage,
                    type.Name,
                    contentType == null
                          ? SRResources.TraceNoneObjectMessage
                          : contentType.ToString()
                    );
            },
                       execute: () =>
            {
                if (cancellationToken.HasValue)
                {
                    return InnerFormatter.ReadFromStreamAsync(
                        type,
                        readStream,
                        content,
                        formatterLoggerTraceWrapper,
                        cancellationToken.Value
                        );
                }
                else
                {
                    return InnerFormatter.ReadFromStreamAsync(
                        type,
                        readStream,
                        content,
                        formatterLoggerTraceWrapper
                        );
                }
            },
                       endTrace: (tr, value) =>
            {
                tr.Message = Error.Format(
                    SRResources.TraceReadFromStreamValueMessage,
                    FormattingUtilities.ValueToString(value, CultureInfo.CurrentCulture)
                    );
            },
                       errorTrace: null
                       ));
        }
        internal static Task <object> DeserializeAsync(string json, Type type, MediaTypeFormatter formatter = null, IFormatterLogger formatterLogger = null)
        {
            formatter = formatter ?? new JsonMediaTypeFormatter();
            MemoryStream ms = new MemoryStream();

            byte[] bytes = Encoding.Default.GetBytes(json);
            ms.Write(bytes, 0, bytes.Length);
            ms.Flush();
            ms.Position = 0;

            return(formatter.ReadFromStreamAsync(type, ms, content: null, formatterLogger: formatterLogger));
        }
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
        {
            Task <object> resultTask = base.ReadFromStreamAsync(type, readStream, content, formatterLogger, cancellationToken);

            var propertiesFlaggedForSanitization = type.GetProperties().Where(e => e.GetCustomAttribute <SanitizeAttribute>() != null).ToList();

            if (propertiesFlaggedForSanitization.Any())
            {
                var result = resultTask.Result;
                foreach (var propertyInfo in propertiesFlaggedForSanitization)
                {
                    var raw = (string)propertyInfo.GetValue(result);
                    if (!string.IsNullOrEmpty(raw))
                    {
                        propertyInfo.SetValue(result, AntiXssEncoder.HtmlEncode(raw, true));
                    }
                }
            }

            return(resultTask);
        }
예제 #46
0
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var taskCompletionSource = new TaskCompletionSource <object>();

            try
            {
                var memoryStream = new MemoryStream();
                readStream.CopyTo(memoryStream);
                var s = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
                taskCompletionSource.SetResult(s);
            }
            catch (Exception e)
            {
                taskCompletionSource.SetException(e);
            }
            return(taskCompletionSource.Task);
        }
예제 #47
0
 public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
 {
     return(Task.Factory.StartNew(
                () =>
     {
         using (var streamReader = new StreamReader(readStream, Encoding.UTF8))
         {
             var root = XElement.Load(streamReader);
             object result = null;
             if (content.Headers.ContentType.MediaType == "application/vnd.netmx.attr+xml")
             {
                 result = new MBeanAttributeResource
                 {
                     Value = DeserializeValue(root.Element("Value"))
                 };
             }
             return result;
         }
     }));
 }
        /// <summary>
        /// Called during deserialization to read an object of the specified <paramref name="type"/>
        /// from the specified <paramref name="readStream"/>.
        /// </summary>
        /// <remarks>
        /// Public for delegating wrappers of this class.  Expected to be called only from
        /// <see cref="ReadFromStreamAsync"/>.
        /// </remarks>
        /// <param name="type">The <see cref="Type"/> of object to read.</param>
        /// <param name="readStream">The <see cref="Stream"/> from which to read.</param>
        /// <param name="effectiveEncoding">The <see cref="Encoding"/> to use when reading.</param>
        /// <param name="formatterLogger">The <see cref="IFormatterLogger"/> to log events to.</param>
        /// <returns>The <see cref="object"/> instance that has been read.</returns>
        public virtual object ReadFromStream(
            Type type,
            Stream readStream,
            Encoding effectiveEncoding,
            IFormatterLogger formatterLogger
            )
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            if (readStream == null)
            {
                throw Error.ArgumentNull("readStream");
            }

            if (effectiveEncoding == null)
            {
                throw Error.ArgumentNull("effectiveEncoding");
            }

            using (
                JsonReader jsonReader = CreateJsonReaderInternal(
                    type,
                    readStream,
                    effectiveEncoding
                    )
                )
            {
                jsonReader.CloseInput = false;
                jsonReader.MaxDepth   = _maxDepth;

                JsonSerializer jsonSerializer = CreateJsonSerializerInternal();

                EventHandler <Newtonsoft.Json.Serialization.ErrorEventArgs> errorHandler = null;
                if (formatterLogger != null)
                {
                    // Error must always be marked as handled
                    // Failure to do so can cause the exception to be rethrown at every recursive level and overflow the stack for x64 CLR processes
                    errorHandler = (sender, e) =>
                    {
                        Exception exception = e.ErrorContext.Error;
                        formatterLogger.LogError(e.ErrorContext.Path, exception);
                        e.ErrorContext.Handled = true;
                    };
                    jsonSerializer.Error += errorHandler;
                }

                try
                {
                    return(jsonSerializer.Deserialize(jsonReader, type));
                }
                finally
                {
                    if (errorHandler != null)
                    {
                        // Clean up the error handler in case CreateJsonSerializer() reuses a serializer
                        jsonSerializer.Error -= errorHandler;
                    }
                }
            }
        }
예제 #49
0
 public async Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
 {
     using (var streamReader = new StreamReader(readStream))
     {
         return(await streamReader.ReadToEndAsync());
     }
 }
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            if (readStream == null)
            {
                throw Error.ArgumentNull("readStream");
            }

            if (Request == null)
            {
                throw Error.InvalidOperation(SRResources.ReadFromStreamAsyncMustHaveRequest);
            }

            object defaultValue = GetDefaultValueForType(type);

            // If content length is 0 then return default value for this type
            HttpContentHeaders contentHeaders = (content == null) ? null : content.Headers;

            if (contentHeaders == null || contentHeaders.ContentLength == 0)
            {
                return(Task.FromResult(defaultValue));
            }

            try
            {
                Func <ODataDeserializerContext> getODataDeserializerContext = () =>
                {
                    return(new ODataDeserializerContext
                    {
                        Request = Request,
                    });
                };

                Action <Exception> logErrorAction = (ex) =>
                {
                    if (formatterLogger == null)
                    {
                        throw ex;
                    }

                    formatterLogger.LogError(String.Empty, ex);
                };

                ODataDeserializerProvider deserializerProvider = Request.GetRequestContainer()
                                                                 .GetRequiredService <ODataDeserializerProvider>();

                return(Task.FromResult(ODataInputFormatterHelper.ReadFromStream(
                                           type,
                                           defaultValue,
                                           Request.GetModel(),
                                           GetBaseAddressInternal(Request),
                                           new WebApiRequestMessage(Request),
                                           () => ODataMessageWrapperHelper.Create(readStream, contentHeaders, Request.GetODataContentIdMapping(), Request.GetRequestContainer()),
                                           (objectType) => deserializerProvider.GetEdmTypeDeserializer(objectType),
                                           (objectType) => deserializerProvider.GetODataDeserializer(objectType, Request),
                                           getODataDeserializerContext,
                                           (disposable) => Request.RegisterForDispose(disposable),
                                           logErrorAction)));
            }
            catch (Exception ex)
            {
                return(TaskHelpers.FromError <object>(ex));
            }
        }
        internal static object Deserialize(string json, Type type, MediaTypeFormatter formatter = null, IFormatterLogger formatterLogger = null)
        {
            formatter = formatter ?? new JsonMediaTypeFormatter();
            MemoryStream ms = new MemoryStream();

            byte[] bytes = Encoding.Default.GetBytes(json);
            ms.Write(bytes, 0, bytes.Length);
            ms.Flush();
            ms.Position = 0;
            Task <object> readTask = formatter.ReadFromStreamAsync(type, ms, content: null, formatterLogger: formatterLogger);

            readTask.WaitUntilCompleted();
            if (readTask.IsFaulted)
            {
                throw readTask.Exception.GetBaseException();
            }
            return(readTask.Result);
        }
예제 #52
0
 public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,
                                                   IFormatterLogger formatterLogger, CancellationToken cancellationToken)
 {
     return(ReadFromStreamAsyncCore(type, readStream, content, formatterLogger, cancellationToken));
 }
 public override System.Threading.Tasks.Task <Object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
 {
     //Do date formatting here
 }
예제 #54
0
        // This method reads bytes from an input stream (i.e. an "upload")
        public override object ReadFromStream(Type type, System.IO.Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
        {
            // Create an in-memory buffer
            var ms = new MemoryStream();

            // Copy the request message body content to the in-memory buffer
            readStream.CopyTo(ms);
            // Deliver a byte array to the controller
            return(ms.ToArray());
        }
예제 #55
0
        public override Task <object> ReadFromStreamAsync(Type type, Stream input, HttpContent content, IFormatterLogger formatterLogger)
        {
            var reader = new StreamReader(input);
            Func <TextReader, Options, object> deserialize = TypedDeserializers.GetTyped(type);
            object result = deserialize(reader, _options);

            return(Task.FromResult(result));
        }
예제 #56
0
        /// <summary>Deserialize an object from the stream.</summary>
        /// <param name="type">The type of object to read.</param>
        /// <param name="stream">The stream from which to read.</param>
        /// <param name="content">The HTTP content being read.</param>
        /// <param name="formatterLogger">The trace message logger.</param>
        /// <returns>Returns a deserialized object.</returns>
        public override object Deserialize(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
        {
            JsonSerializer serializer = new JsonSerializer();
            BsonReader     reader     = new BsonReader(stream);

            return(serializer.Deserialize(reader, type));
        }
예제 #57
0
        private Task <object> ReadContentAsync(HttpRequestMessage request, Type type,
                                               IEnumerable <MediaTypeFormatter> formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
        {
            var content = request.Content;

            if (content == null)
            {
                var defaultValue = MediaTypeFormatter.GetDefaultValueForType(type);
                return(defaultValue == null?Task.FromResult <object>(null) : Task.FromResult(defaultValue));
            }

            return(content.ReadAsAsync(type, formatters, formatterLogger, cancellationToken));
        }
예제 #58
0
    public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        var serializer = JsonSerializer.Create(JsonSerializerSettings);

        return(Task.Factory.StartNew(() =>
        {
            using (var streamReader = new StreamReader(readStream, _encoding))
            {
                using (var jsonTextReader = new JsonTextReader(streamReader))
                {
                    return serializer.Deserialize(jsonTextReader, type);
                }
            }
        }));
    }
        /// <summary>
        ///     Read data from incoming stream.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="stream"></param>
        /// <param name="content"></param>
        /// <param name="formatterLogger"></param>
        /// <returns></returns>
        public override async Task <object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content,
                                                                IFormatterLogger formatterLogger)
        {
            // Type is invalid.
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            // Stream is invalid.
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            // Find dependency resolver.
            var dependencyResolver = GlobalConfiguration.Configuration.DependencyResolver;

            if (dependencyResolver == null)
            {
                throw new ArgumentException("Dependency resolver is required.");
            }

            using (var dependencyScope = dependencyResolver.BeginScope())
            {
                try
                {
                    // load multipart data into memory
                    var multipartProvider = await content.ReadAsMultipartAsync();

                    var httpContents = multipartProvider.Contents;

                    // Create an instance from specific type.
                    var instance = Activator.CreateInstance(type);

                    foreach (var httpContent in httpContents)
                    {
                        // Find parameter from content deposition.
                        var contentParameter = httpContent.Headers.ContentDisposition.Name.Trim('"');
                        var parameterParts   = FindContentDispositionParameters(contentParameter);

                        // Content is a parameter, not a file.
                        if (string.IsNullOrEmpty(httpContent.Headers.ContentDisposition.FileName))
                        {
                            var value = await httpContent.ReadAsStringAsync();
                            await BuildRequestModelAsync(instance, parameterParts, value, dependencyScope);

                            continue;
                        }

                        // Content is a file.
                        // File retrieved from client-side.

                        HttpFileBase file = null;

                        // set null if no content was submitted to have support for [Required]
                        if (httpContent.Headers.ContentLength.GetValueOrDefault() > 0)
                        {
                            if (IsStreamingRequested(instance, contentParameter))
                            {
                                file = new StreamedHttpFile(
                                    httpContent.Headers.ContentDisposition.FileName.Trim('"'),
                                    httpContent.Headers.ContentType.MediaType,
                                    await httpContent.ReadAsStreamAsync());
                            }
                            else
                            {
                                file = new HttpFile(
                                    httpContent.Headers.ContentDisposition.FileName.Trim('"'),
                                    httpContent.Headers.ContentType.MediaType,
                                    await httpContent.ReadAsByteArrayAsync());
                            }
                        }

                        await BuildRequestModelAsync(instance, parameterParts, file, dependencyScope);
                    }

                    return(instance);
                }
                catch (Exception e)
                {
                    if (formatterLogger == null)
                    {
                        throw;
                    }
                    formatterLogger.LogError(string.Empty, e);
                    return(GetDefaultValueForType(type));
                }
            }
        }
예제 #60
0
 public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
 {
     return(Task.FromResult(this.DeserializeFromStream(type, readStream)));
 }