Example #1
0
        public void ReadAsStreamAsync_ClosedInput()
        {
            var stream  = new MemoryStream(new byte[] { 1 });
            var content = new StreamContent(stream);

            Assert.IsTrue(content.LoadIntoBufferAsync().Wait(3000), "#1");
            stream.Close();

            var stream_read = content.ReadAsStreamAsync().Result;

            Assert.IsTrue(stream_read.CanSeek, "#2");
            Assert.AreEqual(0, stream_read.Position, "#3");
            Assert.AreEqual(1, stream_read.Length, "#4");
        }
Example #2
0
        public void LoadIntoBuffer_BufferOverflow()
        {
            var ms = new MemoryStream();

            ms.Write(new byte[10000], 0, 10000);
            ms.Seek(0, SeekOrigin.Begin);

            var sc = new StreamContent(ms);

            try {
                Assert.IsTrue(sc.LoadIntoBufferAsync(50).Wait(200));
                Assert.Fail("#1");
            } catch (AggregateException e) {
                Assert.IsTrue(e.InnerException is HttpRequestException, "#2");
            }
        }
Example #3
0
        /// <summary>
        /// Post a file as an atachment to storage.
        /// </summary>
        /// <returns>The HttpResponseMessage</returns>
        public async Task <HttpResponseMessage> PostFileAsAttachment(Instance instance, string dataType, string fileName, string contentType)
        {
            string requestUri = $"{versionPrefix}/instances/{instance.Id}/data?dataType={dataType}";

            Stream input = File.OpenRead($"data/{fileName}");

            HttpContent fileStreamContent = new StreamContent(input);

            fileStreamContent.Headers.ContentType = MediaTypeHeaderValue.Parse($"{contentType}");
            fileStreamContent.Headers.Add("Content-Disposition", $"attachment; filename={fileName}");

            await fileStreamContent.LoadIntoBufferAsync();

            HttpResponseMessage response = await client.PostAsync(requestUri, fileStreamContent);

            return(response);
        }
        public async Task <HttpContent> GetHttpContentAsync()
        {
            if (Data == null)
            {
                return(null);
            }

            using (var stream = new MemoryStream(Data))
            {
                var httpContent = new StreamContent(stream);
                await httpContent.LoadIntoBufferAsync();

                foreach (var key in ContentHeaders.AllKeys)
                {
                    httpContent.Headers.Add(key, ContentHeaders[key]);
                }
                return(httpContent);
            }
        }
Example #5
0
        public async Task CopyToAsync_CallMultipleTimesWithStreamNotSupportingSeekingButBufferedStream_ContentSerializedOnceToBuffer()
        {
            var source  = new MockStream(new byte[10], false, true); // doesn't support seeking.
            var content = new StreamContent(source);

            // After loading the content into a buffer, we should be able to copy the content to a destination stream
            // multiple times, even though the stream doesn't support seeking.
            await content.LoadIntoBufferAsync();

            var destination1 = new MemoryStream();
            await content.CopyToAsync(destination1);

            // Use hardcoded expected length, since source.Length would throw (source stream gets disposed if non-seekable)
            Assert.Equal(10, destination1.Length);

            var destination2 = new MemoryStream();
            await content.CopyToAsync(destination2);

            Assert.Equal(10, destination2.Length);
        }
Example #6
0
        public async Task CopyToAsync_CallMultipleTimesWithStreamNotSupportingSeekingButBufferedStreamPartiallyConsumed_ContentSerializedOnceToBuffer()
        {
            int consumed = 4;
            var source = new MockStream(new byte[10], false, true); // doesn't support seeking.
            source.Read(new byte[consumed], 0, consumed);
            var content = new StreamContent(source);

            // After loading the content into a buffer, we should be able to copy the content to a destination stream
            // multiple times, even though the stream doesn't support seeking.
            await content.LoadIntoBufferAsync();

            var destination1 = new MemoryStream();
            await content.CopyToAsync(destination1);
            // Use hardcoded expected length, since source.Length would throw (source stream gets disposed if non-seekable).
            Assert.Equal(10 - consumed, destination1.Length);

            var destination2 = new MemoryStream();
            await content.CopyToAsync(destination2);
            Assert.Equal(10 - consumed, destination2.Length);
        }
Example #7
0
        public async Task <HttpResponseMessage> Import()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "Định dạng không được server hỗ trợ");
            }

            var root = HttpContext.Current.Server.MapPath("~/UploadedFiles/Excels");

            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }

            var          provider   = new MultipartFormDataStreamProvider(root);
            Stream       reqStream  = Request.Content.ReadAsStreamAsync().Result;
            MemoryStream tempStream = new MemoryStream();

            reqStream.CopyTo(tempStream);

            tempStream.Seek(0, SeekOrigin.End);
            StreamWriter writer = new StreamWriter(tempStream);

            writer.WriteLine();
            writer.Flush();
            tempStream.Position = 0;

            StreamContent streamContent = new StreamContent(tempStream);

            foreach (var header in Request.Content.Headers)
            {
                streamContent.Headers.Add(header.Key, header.Value);
            }
            try
            {
                // Read the form data.
                streamContent.LoadIntoBufferAsync().Wait();
                //This is where it bugs out
                var result = await streamContent.ReadAsMultipartAsync(provider);

                //Upload files
                int addedCount = 0;
                foreach (MultipartFileData fileData in result.FileData)
                {
                    if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Yêu cầu không đúng định dạng"));
                    }
                    string fileName = fileData.Headers.ContentDisposition.FileName;
                    if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                    {
                        fileName = fileName.Trim('"');
                    }
                    if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                    {
                        fileName = Path.GetFileName(fileName);
                    }

                    var fullPath = Path.Combine(root, fileName);
                    File.Copy(fileData.LocalFileName, fullPath, true);

                    //insert to DB
                    //var
                    List <Period> listPeriod = new List <Period>();
                    listPeriod = this.ReadPeriodListFromExcel(fullPath);
                    if (listPeriod.Count > 0)
                    {
                        foreach (var period in listPeriod)
                        {
                            _periodService.Add(period);
                            addedCount++;
                        }
                        _periodService.Save();
                    }
                }
                return(Request.CreateResponse(HttpStatusCode.OK, "Đã nhập thành công " + addedCount + " sản phẩm thành công."));
            }
            catch (Exception e)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
            }
        }
Example #8
0
        public async Task <HttpResponseMessage> Import()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "Định dạng không được server hỗ trợ");
            }

            var root = HttpContext.Current.Server.MapPath("~/UploadedFiles/Excels");

            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }

            var          provider   = new MultipartFormDataStreamProvider(root);
            Stream       reqStream  = Request.Content.ReadAsStreamAsync().Result;
            MemoryStream tempStream = new MemoryStream();

            reqStream.CopyTo(tempStream);

            tempStream.Seek(0, SeekOrigin.End);
            StreamWriter writer = new StreamWriter(tempStream);

            writer.WriteLine();
            writer.Flush();
            tempStream.Position = 0;

            StreamContent streamContent = new StreamContent(tempStream);

            foreach (var header in Request.Content.Headers)
            {
                streamContent.Headers.Add(header.Key, header.Value);
            }
            try
            {
                // Read the form data.
                streamContent.LoadIntoBufferAsync().Wait();
                //This is where it bugs out
                var result = await streamContent.ReadAsMultipartAsync(provider);

                //Upload files
                int addedCount = 0;
                foreach (MultipartFileData fileData in result.FileData)
                {
                    if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Yêu cầu không đúng định dạng"));
                    }
                    string fileName = fileData.Headers.ContentDisposition.FileName;
                    if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                    {
                        fileName = fileName.Trim('"');
                    }
                    if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                    {
                        fileName = Path.GetFileName(fileName);
                    }

                    var fullPath = Path.Combine(root, fileName);
                    File.Copy(fileData.LocalFileName, fullPath, true);

                    //insert to DB
                    //var
                    List <TKBDHistory> listItem = new List <TKBDHistory>();
                    listItem = this.ReadTKBDFromExcel(fullPath);
                    if (listItem.Count > 0)
                    {
                        foreach (var product in listItem)
                        {
                            var _savingTypeId   = product.ServiceId.Substring(0, 2);
                            var _periodId       = product.ServiceId.Substring(2, 2);
                            var _interestTypeId = product.ServiceId.Substring(4, 2);
                            if (_savingTypeId == "V0")
                            {
                                product.Rate = (decimal)0.01;
                            }
                            else
                            {
                                if (_savingTypeId == "VT")
                                {
                                    var       money = product.Money;
                                    const int S1    = 100000000;
                                    const int S2    = 300000000;
                                    const int S3    = 500000000;
                                    const int S4    = 1000000000;
                                    const int S5    = 2000000000;
                                    if (S1 <= money && money < S2)
                                    {
                                        _savingTypeId = _savingTypeId + "1";
                                        product.Rate  = _interestRateService.GetByCondition(_savingTypeId, _periodId, _interestTypeId).Percent;
                                    }
                                    else
                                    {
                                        if (S2 <= money && money < S3)
                                        {
                                            _savingTypeId = _savingTypeId + "2";
                                            product.Rate  = _interestRateService.GetByCondition(_savingTypeId, _periodId, _interestTypeId).Percent;
                                        }
                                        else
                                        {
                                            if (S3 <= money && money < S4)
                                            {
                                                _savingTypeId = _savingTypeId + "3";
                                                product.Rate  = _interestRateService.GetByCondition(_savingTypeId, _periodId, _interestTypeId).Percent;
                                            }
                                            else
                                            {
                                                if (S4 <= money && money < S5)
                                                {
                                                    _savingTypeId = _savingTypeId + "4";
                                                    product.Rate  = _interestRateService.GetByCondition(_savingTypeId, _periodId, _interestTypeId).Percent;
                                                }
                                                else
                                                {
                                                    if (S5 <= money)
                                                    {
                                                        _savingTypeId = _savingTypeId + "5";
                                                        product.Rate  = _interestRateService.GetByCondition(_savingTypeId, _periodId, _interestTypeId).Percent;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    //InterestRate t = _interestRateService.GetByCondition(_savingTypeId, _periodId, _interestTypeId);

                                    product.Rate = _interestRateService.GetByCondition(_savingTypeId, _periodId, _interestTypeId).Percent;
                                }
                            }
                            _tkbdHistoryService.Add(product);
                            addedCount++;
                        }
                        _tkbdHistoryService.Save();
                    }
                }
                return(Request.CreateResponse(HttpStatusCode.OK, "Đã nhập thành công " + addedCount + " sản phẩm thành công."));
            }
            catch (Exception e)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
            }
        }