예제 #1
1
        public Task<HttpResponseMessage> PostNotification (BlackberryNotification notification)
        {
            var c = new MultipartContent ("related", Configuration.Boundary);
            c.Headers.Remove("Content-Type");
            c.Headers.TryAddWithoutValidation("Content-Type", "multipart/related; boundary=" + Configuration.Boundary + "; type=application/xml");

            var xml = notification.ToPapXml ();


            c.Add (new StringContent (xml, Encoding.UTF8, "application/xml"));

            var bc = new ByteArrayContent(notification.Content.Content);
            bc.Headers.Add("Content-Type", notification.Content.ContentType);

            foreach (var header in notification.Content.Headers)
                bc.Headers.Add(header.Key, header.Value);

            c.Add(bc);

            return PostAsync (Configuration.SendUrl, c);
        }
예제 #2
0
        static void Main(string[] args)
        {
            var client = new HttpClient();
            var batchRequest = new HttpRequestMessage(
                HttpMethod.Post,
                "http://fsatnav:8080/api/batch"
            );

            var batchContent = new MultipartContent("mixed");
            batchRequest.Content = batchContent;

            batchContent.Add(
                new HttpMessageContent(
                    new HttpRequestMessage(
                        HttpMethod.Get,
                        "http://localhost:8080/api/products"
                    )
                )
            );

            batchContent.Add(
                new HttpMessageContent(
                    new HttpRequestMessage(
                        HttpMethod.Put,
                        "http://localhost:8080/api/products"
                    )
                    {
                        Content = new StringContent("{\"Name\":\"Product X\",\"StockQuantity\":300}", Encoding.UTF8, "application/json")
                    }
                )
            );

            using (Stream stdout = Console.OpenStandardOutput())
            {
                Console.WriteLine("<<< REQUEST >>>");
                Console.WriteLine();
                Console.WriteLine(batchRequest);
                Console.WriteLine();
                batchContent.CopyToAsync(stdout).Wait();
                Console.WriteLine();

                var batchResponse = client.SendAsync(batchRequest).Result;

                Console.WriteLine("<<< RESPONSE >>>");
                Console.WriteLine();
                Console.WriteLine(batchResponse);
                Console.WriteLine();
                batchResponse.Content.CopyToAsync(stdout).Wait();
                Console.WriteLine();
                Console.WriteLine();
            }

            Console.ReadLine();
        }
예제 #3
0
        static void Main(string[] args)
        {
            var client = new HttpClient();
            var batchRequest = new HttpRequestMessage(
                HttpMethod.Post,
                "http://localhost:52857/api/$batch"
            );

            var batchContent = new MultipartContent("mixed");
            batchRequest.Content = batchContent;

            batchContent.Add(
                new HttpMessageContent(
                    new HttpRequestMessage(
                        HttpMethod.Get,
                        "http://localhost:52857/api/TestClassOne"
                    )
                )
            );

            batchContent.Add(
                new HttpMessageContent(
                    new HttpRequestMessage(
                        HttpMethod.Get,
                        "http://localhost:52857/api/TestClassTwo"
                    )
                )
            );

            using (Stream stdout = Console.OpenStandardOutput())
            {
                Console.WriteLine("<<< REQUEST >>>");
                Console.WriteLine();
                Console.WriteLine(batchRequest);
                Console.WriteLine();
                batchContent.CopyToAsync(stdout).Wait();
                Console.WriteLine();

                var batchResponse = client.SendAsync(batchRequest).Result;

                Console.WriteLine("<<< RESPONSE >>>");
                Console.WriteLine();
                Console.WriteLine(batchResponse);
                Console.WriteLine();
                batchResponse.Content.CopyToAsync(stdout).Wait();
                Console.WriteLine();
                Console.WriteLine();
            }

            Console.ReadLine();
        }
        public void Add_2()
        {
            var m = new MultipartContent ("a", "X");

            var other = new MultipartContent ("2", "2a");
            m.Add (other);
            var other2 = new MultipartContent ("3", "3a");
            other2.Headers.Add ("9", "9n");
            m.Add (other2);

            Assert.AreEqual ("multipart/a", m.Headers.ContentType.MediaType, "#1");
            Assert.AreEqual (148, m.Headers.ContentLength, "#2");
            Assert.AreEqual ("--X\r\nContent-Type: multipart/2; boundary=\"2a\"\r\n\r\n--2a\r\n\r\n--2a--\r\n\r\n--X\r\nContent-Type: multipart/3; boundary=\"3a\"\r\n9: 9n\r\n\r\n--3a\r\n\r\n--3a--\r\n\r\n--X--\r\n",
                m.ReadAsStringAsync ().Result, "#3");
            Assert.AreEqual (other, m.First (), "#4");
        }
        public void ReadFromStreamAsyncShouldReturnUploadImageDataTest()
        {
            ImageMultipartMediaFormatter target = new ImageMultipartMediaFormatter();
            Type type = typeof(UploadImageData);
            Stream readStream = null;
            MultipartContent content = new MultipartContent("form-data");
            byte[] content_bytes=new byte[] { 10, 11, 12 };
            StreamContent content_part = new StreamContent(new MemoryStream(content_bytes));
            content_part.Headers.Add("Content-Disposition", @"form-data; name=fieldName; filename=image.jpg");
            content_part.Headers.Add("Content-Type", "image/jpeg");
            content.Add(content_part);
            IFormatterLogger formatterLogger = null;

            var actual = target.ReadFromStreamAsync(type, readStream, content, formatterLogger);
            var actualResult = actual.Result;

            Assert.IsInstanceOfType(actualResult,typeof(UploadImageData));
            Assert.AreEqual(3, (actualResult as UploadImageData).ImageBuffer.Length);
            for (int ind = 0; ind < 3; ind++)
            {
                Assert.AreEqual(content_bytes[ind], (actualResult as UploadImageData).ImageBuffer[ind]);
            }
            Assert.AreEqual("image.jpg", (actualResult as UploadImageData).FileName);
            Assert.AreEqual("image/jpeg", (actualResult as UploadImageData).ImageType);
        }
        public async Task ExecuteAsync(string accessToken, string ebookId, int partCount, Func<Stream, Task> streamHandler)
        {
            var message = new HttpRequestMessage(HttpMethod.Post, new Uri("http://localhost:20394/api/batch"));
            var content = new MultipartContent("mixed");
            message.Content = content;
            for (int i = 0; i < partCount; ++i)
            {
                content.Add(new HttpMessageContent(
                    new HttpRequestMessage(HttpMethod.Get, new Uri(string.Format("http://localhost:20394/api/ebooks/ebook/{0}/part/{1}", ebookId, i)))));
            }

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                var response = await client.SendAsync(message);

                var streamProvider = await response.Content.ReadAsMultipartAsync();
                foreach (var partialContent in streamProvider.Contents)
                {
                    var part = await partialContent.ReadAsHttpResponseMessageAsync();
                    var partStream = await part.Content.ReadAsStreamAsync();
                    await streamHandler(partStream);
                }
            }
        }
        public void Add()
        {
            var m = new MultipartContent ("a", "b");

            var other = new MultipartContent ("2", "44");
            other.Headers.Expires = new DateTimeOffset (2020, 11, 30, 19, 55, 22, TimeSpan.Zero);
            m.Add (other);

            Assert.AreEqual ("multipart/a", m.Headers.ContentType.MediaType, "#1");
            Assert.AreEqual (114, m.Headers.ContentLength, "#2");
            Assert.AreEqual ("--b\r\nContent-Type: multipart/2; boundary=\"44\"\r\nExpires: Mon, 30 Nov 2020 19:55:22 GMT\r\n\r\n--44\r\n\r\n--44--\r\n\r\n--b--\r\n", m.ReadAsStringAsync ().Result, "#3");
            Assert.AreEqual (other, m.First (), "#4");
        }
        public void BeginBatch()
        {
            _batchId = Guid.NewGuid().ToString();
            _changesetId = Guid.NewGuid().ToString();

            this.Request = CreateRequest(CreateRequestUrl(FluentCommand.BatchLiteral));
            this.Request.Method = RestVerbs.POST;
            var batchContent = new MultipartContent("mixed", "batch_" + _batchId);
            this.Request.Content = batchContent;
            this.Request.ContentType = "application/http";
            var changesetContent = new MultipartContent("mixed", "changeset_" + _changesetId);
            batchContent.Add(changesetContent);
            _content = changesetContent;
        }
예제 #9
0
        public void PostConvertFile_ConvertToKml_ShouldReturnByteArray()
        {
            var multipartContent = new MultipartContent();
            var streamContent = new StreamContent(new MemoryStream(new byte[1] { 1 }));
            streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "\"files\"",
                FileName = "\"SomeFile.twl\""
            };
            streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/kml");
            multipartContent.Add(streamContent);
            _controller.Request = new HttpRequestMessage();
            _controller.Request.Content = multipartContent;
            _gpsBabelGateway.ConvertFileFromat(Arg.Any<byte[]>(), "naviguide", "kml").Returns(Task.FromResult(new byte[2] { 1, 1 }));

            var response = _controller.PostConvertFile("kml").Result as OkNegotiatedContentResult<byte[]>;

            Assert.AreEqual(2, response.Content.Length);
        }
예제 #10
0
        private static HttpRequestMessage CreateBatchedRequest(Uri batchEndPoint, IEnumerable <HttpRequestMessage> requestsToBatch)
        {
            MultipartContent multipartContent = new MultipartContent("mixed", "batch_" + Guid.NewGuid().ToString());

            foreach (var request in requestsToBatch)
            {
                var httpMessageContent = new HttpMessageContent(request);
                httpMessageContent.Headers.Remove("Content-Type");
                httpMessageContent.Headers.Add("Content-Type", "application/http");
                httpMessageContent.Headers.Add("Content-Transfer-Encoding", "binary");

                multipartContent.Add(httpMessageContent);
            }

            return(new HttpRequestMessage(HttpMethod.Post, batchEndPoint)
            {
                Content = multipartContent
            });
        }
예제 #11
0
        private static HttpResponseMessage GetMultipartResponse(IEnumerable <IWadoRsResponse> wadoResponses, string mimeType)
        {
            HttpResponseMessage response     = new HttpResponseMessage( );
            MultipartContent    multiContent = new MultipartContent("related", "DICOM DATA BOUNDARY");

            multiContent.Headers.ContentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("type", "\"" + mimeType + "\""));

            response.Content = multiContent;

            foreach (var wadoResponse in wadoResponses)
            {
                StreamContent sContent = new StreamContent(wadoResponse.Content);
                sContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(wadoResponse.MimeType);

                multiContent.Add(sContent);
            }

            return(response);
        }
예제 #12
0
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="url">上传地址</param>
        /// <param name="stream">数据流</param>
        private string HttpUpLoad(string url, Stream stream, int ServiceId, string FileName)
        {
            HttpClient c           = new HttpClient();
            var        bytes       = StreamToBytes(stream);
            var        fileContent = new ByteArrayContent(bytes);

            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("name")
            {
                FileName = FileName
            };
            MultipartContent content = new MultipartContent();

            content.Add(fileContent);
            var    response     = c.PostAsync(url, content);
            string responseBody = response.Result.Content.ReadAsStringAsync().Result;
            var    apiResult    = JsonConvert.DeserializeObject <BaseWebApiResponse <string> >(responseBody);

            return(apiResult.Result);
        }
예제 #13
0
        private async Task <DicomWebResponse <DicomDataset> > PostAsync(
            IEnumerable <byte[]> postContent,
            string studyInstanceUid,
            CancellationToken cancellationToken)
        {
            MultipartContent multiContent = GetMultipartContent(MediaTypeApplicationDicom.MediaType);

            foreach (byte[] content in postContent)
            {
                var byteContent = new ByteArrayContent(content);
                byteContent.Headers.ContentType = MediaTypeApplicationDicom;
                multiContent.Add(byteContent);
            }

            return(await PostMultipartContentAsync(
                       multiContent,
                       string.Format(DicomWebConstants.BasStudyUriFormat, studyInstanceUid),
                       cancellationToken));
        }
예제 #14
0
        internal static async Task <bool> DeleteCustomer(string customerId, string caseId)
        {
            Customer customer = new Customer();

            customer.CustomerId = Convert.ToInt32(customerId);
            customer.CaseId     = caseId;
            var json       = JsonConvert.SerializeObject(customer);
            var strContent = new StringContent(json, Encoding.UTF8, "application/json");
            var content    = new MultipartContent();

            content.Add(strContent);

            HttpResponseMessage response = await SendApiRequest("api/Upload/DeleteCustomer", content);

            if (response.IsSuccessStatusCode)
            {
                return(true);
            }
            return(false);
        }
예제 #15
0
        public static async Task <Customer> GetCustomerWithCustomerId(string customerId)
        {
            // Customer customer = null;
            Customer customer = new Customer();

            customer.CustomerId = Convert.ToInt32(customerId);
            var json       = JsonConvert.SerializeObject(customer);
            var strcontent = new StringContent(json, Encoding.UTF8, "application/json");
            var content    = new MultipartContent();

            content.Add(strcontent);

            HttpResponseMessage response = await SendApiRequest("api/Upload/GetCustomerWithCustomerId", content);

            if (response.IsSuccessStatusCode)
            {
                customer = await response.Content.ReadAsAsync <Customer>();
            }
            return(customer);
        }
예제 #16
0
 internal HttpContent CreateHttpContent()
 {
     if (Contents != null)
     {
         if (Contents.Count == 1)
         {
             return(Contents[0]);
         }
         else if (Contents.Count > 0)
         {
             var content = new MultipartContent();
             foreach (var item in Contents)
             {
                 content.Add(item);
             }
             return(content);
         }
     }
     return(null);
 }
예제 #17
0
 public HttpContent Build(string boundary)
 {
     if (boundary == null)
     {
         throw new ArgumentNullException("boundary");
     }
     if (string.IsNullOrWhiteSpace(boundary))
     {
         throw new ArgumentException("The provided boundary value is invalid", "boundary");
     }
     MultipartContent content = new MultipartContent("mixed", boundary);
     foreach (var request in Requests)
     {
         HttpMessageContent messageContent = new HttpMessageContent(request);
         messageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/http");
         messageContent.Headers.Add("Content-Transfer-Encoding", "binary");
         content.Add(messageContent);
     }
     return content;
 }
예제 #18
0
        public async Task <bool> CreatePost(string messageUserId, string post,
                                            UserAccountEntity userAccountEntity)
        {
            try
            {
                var          user = userAccountEntity.GetUserEntity();
                var          authenticationManager = new AuthenticationManager();
                const string boundary      = "abcdefghijklmnopqrstuvwxyz";
                var          theAuthClient = new HttpClient();
                var          request       = new HttpRequestMessage(HttpMethod.Post, string.Format("https://{0}-gmsg.np.community.playstation.net/groupMessaging/v1/messageGroups/{1}/messages", user.Region, messageUserId));
                var          form          = new MultipartContent("mixed", boundary);

                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());

                var messageJson = new SendMessage
                {
                    message = new Message()
                    {
                        body           = post,
                        fakeMessageUid = 1384958573288,
                        messageKind    = 1
                    }
                };
                var json          = JsonConvert.SerializeObject(messageJson);
                var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
                stringContent.Headers.Add("Content-Description", "message");
                form.Add(stringContent);
                request.Content = form;
                HttpResponseMessage response = await theAuthClient.SendAsync(request);

                return(response.IsSuccessStatusCode);
            }
            catch (Exception)
            {
                { return(false); }
            }
        }
예제 #19
0
        public async Task Check_firstBoundryBatchRequest_has_CRLR()
        {
            // Act
            HttpRequestMessage request = new HttpRequestMessage(
                HttpMethod.Post, "/odata/$batch");


            string batchName    = $"batch_{Guid.NewGuid()}";
            var    batchContent = new MultipartContent("mixed", batchName);

            var requestMessage = new HttpRequestMessage(HttpMethod.Get, "http://localhost:5000/odata/Products?$orderby=Name&$select=Id,Name&$skip=0&$top=20");
            var messageContent = new HttpMessageContent(requestMessage);

            if (messageContent.Headers.Contains("Content-Type"))
            {
                messageContent.Headers.Remove("Content-Type");
            }
            messageContent.Headers.Add("Content-Type", "application/http");
            messageContent.Headers.Add("Content-Transfer-Encoding", "binary");
            requestMessage.Headers.Add("Accept", "application/json");

            batchContent.Add(messageContent);

            request.Content = batchContent;

            HttpResponseMessage response = await client.SendAsync(request);

            var responseString = response.Content.ReadAsStringAsync().Result;

            Debug.WriteLine(responseString);

            var test = responseString.Take(54).ToArray();

            Console.WriteLine(test);
            Console.WriteLine("Lenght: " + test.Length);
            Console.WriteLine("last character: " + test[51]);
            Console.WriteLine("char52: " + (int)test[52]);
            Console.WriteLine("char53: " + (int)test[53]);

            Assert.IsTrue(response.IsSuccessStatusCode, $"Status code: " + response.StatusCode.ToString());
        }
예제 #20
0
            public MultipartContent GetFileUploadContent(params string[] paths)
            {
                var content = new MultipartContent();

                foreach (var path in paths)
                {
                    var fileName = Path.GetFileName(path);
                    content.Add(new StreamContent(File.OpenRead(path))
                    {
                        Headers =
                        {
                            ContentDisposition = new ContentDispositionHeaderValue("attachment")
                            {
                                FileNameStar   = fileName
                            }
                        }
                    });
                }

                return(content);
            }
예제 #21
0
        private void AddBlobToMultipartContent(MultipartContent content, Blob blob)
        {
            if (blob.File == null)
            {
                throw new ArgumentNullException("blob.File", "input blob has no file");
            }
            if (!blob.File.Exists)
            {
                throw new FileNotFoundException(blob.File.FullName);
            }
            HttpContent part = new StreamContent(blob.File.OpenRead());

            part.Headers.ContentType        = new MediaTypeHeaderValue(blob.MimeType);
            part.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = blob.Filename
            };
            part.Headers.Add("Content-Transfer-Encoding", "binary");
            part.Headers.Add("Content-ID", "input");
            content.Add(part);
        }
예제 #22
0
        internal async static Task <HttpContent> CreateOuterRequestContent(IEnumerable <IClientServiceRequest> requests)
        {
            var mixedContent = new MultipartContent("mixed");

            foreach (var request in requests)
            {
                mixedContent.Add(await CreateIndividualRequest(request).ConfigureAwait(false));
            }

            // Batch request currently doesn't support GZip. Uncomment when the issue will be resolved.
            // https://code.google.com/p/google-api-dotnet-client/issues/detail?id=409

            /*if (service.GZipEnabled)
             * {
             *  var content = HttpServiceExtenstions.CreateZipContent(await mixedContent.ReadAsStringAsync()
             *      .ConfigureAwait(false));
             *  content.Headers.ContentType = mixedContent.Headers.ContentType;
             *  return content;
             * }*/
            return(mixedContent);
        }
예제 #23
0
        public HttpContent Build(string boundary)
        {
            if (boundary == null)
            {
                throw new ArgumentNullException("boundary");
            }
            if (string.IsNullOrWhiteSpace(boundary))
            {
                throw new ArgumentException("The provided boundary value is invalid", "boundary");
            }
            MultipartContent content = new MultipartContent("mixed", boundary);

            foreach (var request in Requests)
            {
                HttpMessageContent messageContent = new HttpMessageContent(request);
                messageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/http");
                messageContent.Headers.Add("Content-Transfer-Encoding", "binary");
                content.Add(messageContent);
            }
            return(content);
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.Content == null ||
                !request.Content.IsMimeMultipartContent("batch"))
            {
                return(request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "The mediatype is expected to be \"multipart/batch\" for a batching request"));
            }

            MultipartContent    outerContent  = new MultipartContent("batch");
            HttpResponseMessage outerResponse = request.CreateResponse();

            outerResponse.Content = outerContent;

            MultipartMemoryStreamProvider multipart = await request.Content.ReadAsMultipartAsync();

            /// Load requests from multipart content. Submit each of them
            /// to the in memory batch server sequentially. They are then
            /// processed asynchronously.
            /// The individual response are gathered and added to the
            /// multipart content for return response.
            foreach (var content in multipart.Contents)
            {
                HttpResponseMessage innerResponse = null;

                try
                {
                    var innerRequest = await content.ReadAsHttpRequestMessageAsync();

                    innerResponse = await _entry.SendAsync(innerRequest, cancellationToken);
                }
                catch (Exception)
                {
                    innerResponse = new HttpResponseMessage(HttpStatusCode.BadRequest);
                }

                outerContent.Add(new HttpMessageContent(innerResponse));
            }

            return(outerResponse);
        }
예제 #25
0
        public async void GivenAMultipartRequestWithEmptyContent_WhenStoring_TheServerShouldReturnConflict()
        {
            var request = new HttpRequestMessage(HttpMethod.Post, "studies");

            request.Headers.Add(HeaderNames.Accept, DicomWebClient.MediaTypeApplicationDicomJson.MediaType);

            var multiContent = new MultipartContent("related");

            multiContent.Headers.ContentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("type", $"\"{DicomWebClient.MediaTypeApplicationDicom.MediaType}\""));

            var byteContent = new ByteArrayContent(Array.Empty <byte>());

            byteContent.Headers.ContentType = DicomWebClient.MediaTypeApplicationDicom;
            multiContent.Add(byteContent);

            request.Content = multiContent;

            DicomWebException <DicomDataset> exception = await Assert.ThrowsAsync <DicomWebException <DicomDataset> >(
                () => _client.PostMultipartContentAsync(multiContent, "studies"));

            Assert.Equal(HttpStatusCode.Conflict, exception.StatusCode);
        }
        public virtual Task<HttpResponseMessage> CreateResponseMessageAsync(IList<HttpResponseMessage> responses, HttpRequestMessage request)
        {
            if (responses == null)
            {
                throw Error.ArgumentNull("responses");
            }
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            MultipartContent batchContent = new MultipartContent(MultiPartContentSubtype);

            foreach (HttpResponseMessage batchResponse in responses)
            {
                batchContent.Add(new HttpMessageContent(batchResponse));
            }

            HttpResponseMessage response = request.CreateResponse();
            response.Content = batchContent;
            return Task.FromResult(response);
        }
예제 #27
0
        /// <summary>
        /// Builds the multipart content for a batch request using multiple change sets.
        /// </summary>
        private MultipartContent BuildMixedMultipartContent(SLBatchRequest batchRequest, string boundary)
        {
            var multipartContent = new MultipartContent("mixed", boundary);
            var request          = new HttpRequestMessage(batchRequest.HttpMethod, Url.Combine(ServiceLayerRoot.ToString(), batchRequest.Resource));

            if (batchRequest.Data != null)
            {
                request.Content = new StringContent(JsonConvert.SerializeObject(batchRequest.Data, batchRequest.JsonSerializerSettings), batchRequest.Encoding, "application/json");
            }

            if (batchRequest.ContentID.HasValue)
            {
                request.Content.Headers.Add("Content-ID", batchRequest.ContentID.ToString());
            }

            var innerContent = new HttpMessageContent(request);

            innerContent.Headers.Add("content-transfer-encoding", "binary");
            multipartContent.Add(innerContent);

            return(multipartContent);
        }
예제 #28
0
        public static bool TestStorageServiceCreateFile()
        {
            bool done = false;

            using (HttpClient client = HttpClient.Create("localhost", 3333)) {
                HttpClientRequest request = new HttpClientRequest();
                request.Method = "POST";
                request.Path   = "/storage/1/0";
                MultipartContent            content     = new MultipartContent();
                FileContent                 fileContent = new FileContent("../../data/document/text.txt");
                Dictionary <string, string> disposition = new Dictionary <string, string>();
                disposition["name"]     = "file";
                disposition["filename"] = "text.txt";
                fileContent.Headers["content-disposition"] = ContentDisposition.Encode(disposition);
                content.Add(fileContent);
                request.Content = content;
                client.SendRequest(request);
                HttpClientResponse response = client.GetResponse();
                done = (response.StatusCode == 200);
            }
            return(done);
        }
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.Content == null ||
                !request.Content.IsMimeMultipartContent("batch"))
            {
                return request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, "The mediatype is expected to be \"multipart/batch\" for a batching request");
            }

            MultipartContent outerContent = new MultipartContent("batch");
            HttpResponseMessage outerResponse = request.CreateResponse();
            outerResponse.Content = outerContent;

            MultipartMemoryStreamProvider multipart = await request.Content.ReadAsMultipartAsync();

            /// Load requests from multipart content. Submit each of them 
            /// to the in memory batch server sequentially. They are then
            /// processed asynchronously.
            /// The individual response are gathered and added to the 
            /// multipart content for return response.
            foreach (var content in multipart.Contents)
            {
                HttpResponseMessage innerResponse = null;

                try
                {
                    var innerRequest = await content.ReadAsHttpRequestMessageAsync();

                    innerResponse = await _entry.SendAsync(innerRequest, cancellationToken);
                }
                catch (Exception)
                {
                    innerResponse = new HttpResponseMessage(HttpStatusCode.BadRequest);
                }

                outerContent.Add(new HttpMessageContent(innerResponse));
            }

            return outerResponse;
        }
        private HttpRequestMessage SetUpRequest(params string[] parts)
        {
            var content = new MultipartContent("mixed", "xyz-boundary");

            foreach (var part in parts)
            {
                var nestedContent = new StringContent(part);
                nestedContent.Headers.ContentType = new MediaTypeHeaderValue("application/http");
                nestedContent.Headers.Add("Content-Transfer-Encoding", "binary");

                content.Add(nestedContent);
            }

            var request = new HttpRequestMessage(HttpMethod.Post, "http://example.com/api/odata/$batch")
            {
                Content = content
            };

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml+atom"));

            return request;
        }
예제 #31
0
        public override HttpRequestMessage CreateRequest(JsonOperationContext ctx, ServerNode node, out string url)
        {
            var request = new HttpRequestMessage
            {
                Method  = HttpMethod.Post,
                Content = new BlittableJsonContent(stream =>
                {
                    using (var writer = new BlittableJsonTextWriter(ctx, stream))
                    {
                        writer.WriteStartObject();
                        writer.WriteArray("Commands", _commands);
                        writer.WriteEndObject();
                    }
                })
            };

            if (_attachmentStreams != null && _attachmentStreams.Count > 0)
            {
                var multipartContent = new MultipartContent {
                    request.Content
                };
                foreach (var stream in _attachmentStreams)
                {
                    PutAttachmentCommandHelper.PrepareStream(stream);
                    var streamContent = new AttachmentStreamContent(stream, CancellationToken);
                    streamContent.Headers.TryAddWithoutValidation("Command-Type", "AttachmentStream");
                    multipartContent.Add(streamContent);
                }
                request.Content = multipartContent;
            }

            var sb = new StringBuilder($"{node.Url}/databases/{node.Database}/bulk_docs");

            AppendOptions(sb);

            url = sb.ToString();

            return(request);
        }
예제 #32
0
        internal static async Task <bool> DeleteFile(string id)
        {
            CustomerFile custFile = new CustomerFile();

            custFile.Id = new Guid(id);
            //custFile.DocumentType = docType;
            //custFile.CaseId = caseId;
            var json       = JsonConvert.SerializeObject(custFile);
            var strContent = new StringContent(json, Encoding.UTF8, "application/json");

            var content = new MultipartContent();

            content.Add(strContent);

            HttpResponseMessage response = await SendApiRequest("api/Upload/DeleteFile", content);

            if (response.IsSuccessStatusCode)
            {
                return(true);
            }
            return(false);
        }
예제 #33
0
        private HttpRequestMessage SetUpRequest(params string[] parts)
        {
            var content = new MultipartContent("mixed", "xyz-boundary");

            foreach (var part in parts)
            {
                var nestedContent = new StringContent(part);
                nestedContent.Headers.ContentType = new MediaTypeHeaderValue("application/http");
                nestedContent.Headers.Add("Content-Transfer-Encoding", "binary");

                content.Add(nestedContent);
            }

            var request = new HttpRequestMessage(HttpMethod.Post, "http://example.com/api/odata/$batch")
            {
                Content = content
            };

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml+atom"));

            return(request);
        }
예제 #34
0
        public async Task ReadAsStringAsync_OneSubContentWithHeaders_MatchesExpected(MultipartContentToStringMode mode, bool async)
        {
            var subContent = new ByteArrayContent(Encoding.UTF8.GetBytes("This is a ByteArrayContent"));

            subContent.Headers.Add("someHeaderName", "andSomeHeaderValue");
            subContent.Headers.Add("someOtherHeaderName", new[] { "withNotOne", "ButTwoValues" });
            subContent.Headers.Add("oneMoreHeader", new[] { "withNotOne", "AndNotTwo", "butThreeValues" });

            var mc = new MultipartContent("someSubtype", "theBoundary");

            mc.Add(subContent);

            Assert.Equal(
                "--theBoundary\r\n" +
                "someHeaderName: andSomeHeaderValue\r\n" +
                "someOtherHeaderName: withNotOne, ButTwoValues\r\n" +
                "oneMoreHeader: withNotOne, AndNotTwo, butThreeValues\r\n" +
                "\r\n" +
                "This is a ByteArrayContent\r\n" +
                "--theBoundary--\r\n",
                await MultipartContentToStringAsync(mc, mode, async));
        }
예제 #35
0
        public async void GivenAMultipartRequestWithTypeParameterAndFirstSectionWithoutContentType_WhenStoring_TheServerShouldReturnOK()
        {
            var request = new HttpRequestMessage(HttpMethod.Post, "studies");

            request.Headers.Add(HeaderNames.Accept, DicomWebClient.MediaTypeApplicationDicomJson.MediaType);

            var multiContent = new MultipartContent("related");

            multiContent.Headers.ContentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("type", $"\"{DicomWebClient.MediaTypeApplicationDicom.MediaType}\""));

            string studyInstanceUID = TestUidGenerator.Generate();

            try
            {
                DicomFile dicomFile = Samples.CreateRandomDicomFile(studyInstanceUID);

                await using (MemoryStream stream = _recyclableMemoryStreamManager.GetStream())
                {
                    await dicomFile.SaveAsync(stream);

                    var byteContent = new ByteArrayContent(stream.ToArray());
                    multiContent.Add(byteContent);
                }

                request.Content = multiContent;

                DicomWebResponse <DicomDataset> response = await _client.PostMultipartContentAsync(multiContent, "studies");

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);

                ValidationHelpers.ValidateReferencedSopSequence(
                    response.Value,
                    ConvertToReferencedSopSequenceEntry(dicomFile.Dataset));
            }
            finally
            {
                await _client.DeleteStudyAsync(studyInstanceUID);
            }
        }
예제 #36
0
        /// <summary>
        /// Creates the batch response message.
        /// </summary>
        /// <param name="responses">The responses for the batch requests.</param>
        /// <param name="request">The original request containing all the batch requests.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <returns>The batch response message.</returns>
        public virtual Task <HttpResponseMessage> CreateResponseMessageAsync(IList <HttpResponseMessage> responses, HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (responses == null)
            {
                throw new ArgumentNullException(nameof(responses));
            }
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            MultipartContent batchContent = new MultipartContent(MultiPartContentSubtype);

            foreach (HttpResponseMessage batchResponse in responses)
            {
                batchContent.Add(new HttpMessageContent(batchResponse));
            }

            HttpResponseMessage response = request.CreateResponse();

            response.Content = batchContent;
            return(Task.FromResult(response));
        }
        public virtual Task <HttpResponseMessage> CreateResponseMessageAsync(IList <HttpResponseMessage> responses, HttpRequestMessage request)
        {
            if (responses == null)
            {
                throw Error.ArgumentNull("responses");
            }
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            MultipartContent batchContent = new MultipartContent(MultiPartContentSubtype);

            foreach (HttpResponseMessage batchResponse in responses)
            {
                batchContent.Add(new HttpMessageContent(batchResponse));
            }

            HttpResponseMessage response = request.CreateResponse();

            response.Content = batchContent;
            return(Task.FromResult(response));
        }
예제 #38
0
        public async Task GetDisplaysBatchAsync()
        {
            //A batch API endpoint can be used to send multiple requests together. This cuts down on excess HTTP traffic.
            //This Get display batch request can be done as a normal GET request if a batch request is not required.

            //Create the multipart/mixed message content
            MultipartContent content = new MultipartContent("mixed", "batch_" + Guid.NewGuid());

            foreach (Display display in displaysToUse)
            {
                //Create a message to get a display.
                //Create the different parts of the multipart content
                HttpMessageContent getDisplayContent = new HttpMessageContent(new HttpRequestMessage(HttpMethod.Get, $"{ApiServer}/API/api/displays/{display.SerialNumber}"));
                content.Add(getDisplayContent);
            }

            var responses = await SendBatchAndCheckReturnResponsesSuccessAsync(content);

            //Take the response list and read them into a display list
            List <GetDisplaysResponse> displays = new List <GetDisplaysResponse> {
            };

            foreach (HttpResponseMessage individualResponse in responses)
            {
                GetDisplaysResponse displayDetails = await individualResponse.Content.ReadAsAsync <GetDisplaysResponse>();

                displays.Add(displayDetails);
            }

            //Check the results
            Assert.AreEqual(displaysToUse.Count(), displays.Count());

            for (int index = 0; index < displaysToUse.Count; index++)
            {
                Assert.AreEqual(displaysToUse[index].SerialNumber, displays[index].SerialNumber);
            }
        }
예제 #39
0
        public async Task <ServiceLayerResponse> PostMany(string query, List <string> payload, bool noRoute = false, bool returnContent = false)
        {
            MultipartContent multipart = new MultipartContent("mixed");

            StringBuilder messageBuilder  = new StringBuilder(512);
            string        messageTemplate = string.Empty;

            messageBuilder.AppendLine($"POST /{query}");
            messageBuilder.AppendLine("Content-Type: application/json; charset=utf-8");
            if (!returnContent)
            {
                messageBuilder.AppendLine("Prefer: return-no-content");
            }
            messageBuilder.AppendLine("");
            messageBuilder.AppendLine("{0}");
            messageBuilder.AppendLine("");

            messageTemplate = messageBuilder.ToString();

            int index = 0;

            foreach (var s in payload)
            {
                index++;
                string message = string.Format(messageTemplate, s);

                StringContent json = new StringContent(message, Encoding.UTF8, "application/json");

                json.Headers.ContentType = new MediaTypeHeaderValue("application/http");
                json.Headers.Add("Content-Transfer-Encoding", "binary");
                json.Headers.Add("Content-ID", index.ToString());

                multipart.Add(json);
            }

            return(await Send(HttpMethod.Post, "$batch", multipart, noRoute));
        }
        public async Task TestFileUpload()
        {
            var http = new HttpClient();

            byte[] data = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/images/sailbig.jpg"));
            var fileContent = new ByteArrayContent(data);

            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "sailbig.jpg",
                Name="file",
             
            };
            var mp = new MultipartContent();
            mp.Add(fileContent);

            var response = await http.PostAsync(BaseUrl + "samples/PostFileValues", mp);

            Assert.IsTrue(response.IsSuccessStatusCode);

            var result = await response.Content.ReadAsStringAsync();

            Console.WriteLine(result);
        }
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            var boundry = Guid.NewGuid().ToString();
            var multipartFormDataContent = new MultipartContent("mixed", boundry);

            //content. .StatusCode = (int)System.Net.HttpStatusCode.OK;
            var contentType = new MediaTypeHeaderValue("multipart/mixed"); // String.Format("multipart/mixed; boundary={0}", boundry));
            var boundaryParameter = new NameValueHeaderValue("boundary", boundry);
            contentType.Parameters.Add(boundaryParameter);
            contentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("revision", "0.1"));
            content.Headers.ContentType = contentType;
            //content.Headers.Add("Accept", "multipart/mixed");
            //content.Headers.Add("MIME-Version", "1.0");

            var entities = (IEnumerable<object>)value;
            foreach (var entity in entities)
            {
                var entityContent = new ObjectContent<object>(entity, new JsonMediaTypeFormatter());
                entityContent.Headers.LastModified = DateTime.UtcNow; // Add("Last-Modified", entity.LastModified.ToUniversalTime().ToString("R"));
                entityContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-" + entity.GetType().Name);
                multipartFormDataContent.Add(entityContent);
            }
            return multipartFormDataContent.CopyToAsync(writeStream);
        }
예제 #42
0
        public static async Task <Response> PostFileAsync(string url, string file,
                                                          Dictionary <string, string> formContent = null)
        {
            if (!File.Exists(file))
            {
                return(await PostFormAsync(url, formContent));
            }

            var content = new MultipartContent();

            if (formContent != null && formContent.Count > 0)
            {
                foreach (var name in formContent.Keys)
                {
                    content.Headers.Add(name, formContent[name]);
                }
            }

            using (var stream = File.OpenRead(file))
            {
                content.Add(new StreamContent(stream));
                return(await RequestAsync(url, HttpMethod.Post, content));
            }
        }
        public async Task TestFileUpload()
        {
            var http = new HttpClient();

            byte[] data        = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/images/sailbig.jpg"));
            var    fileContent = new ByteArrayContent(data);

            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "sailbig.jpg",
                Name     = "file",
            };
            var mp = new MultipartContent();

            mp.Add(fileContent);

            var response = await http.PostAsync(BaseUrl + "samples/PostFileValues", mp);

            Assert.IsTrue(response.IsSuccessStatusCode);

            var result = await response.Content.ReadAsStringAsync();

            Console.WriteLine(result);
        }
        public async Task UploadMultipartOriginal(string path, int bufferSize = DefaultBufferSize)
        {
            var record = new FileRecord();

            using (var fileStream = File.OpenRead(path))
                using (var bufferedStream = new ProgressStream(fileStream, Progress, bufferSize))
                {
                    using (var multipart = new MultipartContent())
                        using (var fileContent = new StreamContent(bufferedStream, bufferSize))
                        {
                            multipart.Add(fileContent);
                            var contentDispositionHeader = new ContentDispositionHeaderValue("attachment")
                            {
                                CreationDate = DateTime.Now,
                                FileName     = Path.GetFileName(path),
                                Size         = fileStream.Length
                            };

                            fileContent.Headers.ContentDisposition = contentDispositionHeader;

                            var response = await Client.PostAsync($"{Constants.FilesRoute}/{Constants.UploadMultipartOriginal}", multipart);
                        }
                }
        }
        public async Task Post()
        {
            var dir         = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            var file        = dir.Substring(6, dir.Length - 6) + @"\icon.png";
            var bytes       = File.ReadAllBytes(file);
            var fileContent = new ByteArrayContent(bytes);

            fileContent.Headers.ContentType        = new MediaTypeHeaderValue("image/jpeg");
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "myFilename.jpg"
            };

            var preProcessor = Substitute.For <IPreprocessor>();

            preProcessor.Process(bytes, "image/jpeg", "myFilename.jpg");

            var store = Substitute.For <IDataStore>();

            var api = new ImageApi(preProcessor, store)
            {
                Request = new HttpRequestMessage(),
            };
            var content = new MultipartContent();

            content.Add(fileContent);
            api.Request.Content = content;

            var response = await api.Post();

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
            Assert.IsNotNull(response.Content);

            preProcessor.Received().Process(bytes, "image/jpeg", "myFilename.jpg");
        }
        public void ReadAsMultipartAsync_NestedMultipartContent(string boundary)
        {
            const int nesting = 10;
            const string innerText = "Content";

            MultipartContent innerContent = new MultipartContent("mixed", boundary);
            innerContent.Add(new StringContent(innerText));
            for (var cnt = 0; cnt < nesting; cnt++)
            {
                string outerBoundary = String.Format("{0}_{1}", boundary, cnt);
                MultipartContent outerContent = new MultipartContent("mixed", outerBoundary);
                outerContent.Add(innerContent);
                innerContent = outerContent;
            }

            MemoryStream memStream = new MemoryStream();
            innerContent.CopyToAsync(memStream).Wait();
            memStream.Position = 0;
            byte[] data = memStream.ToArray();
            HttpContent content = new ByteArrayContent(data);
            content.Headers.ContentType = innerContent.Headers.ContentType;

            for (var cnt = 0; cnt < nesting + 1; cnt++)
            {
                MultipartMemoryStreamProvider result = content.ReadAsMultipartAsync().Result;
                Assert.Equal(1, result.Contents.Count);
                content = result.Contents[0];
                Assert.NotNull(content);
            }

            string text = content.ReadAsStringAsync().Result;
            Assert.Equal(innerText, text);
        }
예제 #47
0
		public void Add_Resursive ()
		{
			var m = new MultipartContent ("1", "1a");

			var other = new MultipartContent ("2", "2a");
			m.Add (other);

			var other2 = new MultipartContent ("3", "3a");
			other.Add (other2);

			Assert.AreEqual ("multipart/1", m.Headers.ContentType.MediaType, "#1");
			Assert.AreEqual (136, m.Headers.ContentLength, "#2");
			Assert.AreEqual ("--1a\r\nContent-Type: multipart/2; boundary=\"2a\"\r\n\r\n--2a\r\nContent-Type: multipart/3; boundary=\"3a\"\r\n\r\n--3a\r\n\r\n--3a--\r\n\r\n--2a--\r\n\r\n--1a--\r\n",
				m.ReadAsStringAsync ().Result, "#3");
			Assert.AreEqual (other, m.First (), "#4");
		}
예제 #48
0
        public void Configure(IApplicationBuilder app)
        {
            app.Use(async (context, next) =>
            {
                if (!IsMultipartContentType(context.Request.ContentType))
                {
                    await next();
                    return;
                }

                context.Response.ContentType = "text/html";
                await context.Response.WriteAsync("<html><body>Multipart received<br>");

                // Read the request body as multipart sections. This does not buffer the content of each section. If you want to buffer the data
                // then that needs to be added either to the request body before you start or to the individual segments afterward.
                var boundary = GetBoundary(context.Request.ContentType);
                var reader = new MultipartReader(boundary, context.Request.Body);

                var section = await reader.ReadNextSectionAsync();
                while (section != null)
                {
                    await context.Response.WriteAsync("- Header count: " + section.Headers.Count + "<br>");
                    foreach (var headerPair in section.Headers)
                    {
                        await context.Response.WriteAsync("-- " + headerPair.Key + ": " + string.Join(", ", headerPair.Value) + "<br>");
                    }

                    // Consume the section body here.

                    // Nested?
                    if (IsMultipartContentType(section.ContentType))
                    {
                        await context.Response.WriteAsync("-- Nested Multipart<br>");

                        var subBoundary = GetBoundary(section.ContentType);

                        var subReader = new MultipartReader(subBoundary, section.Body);

                        var subSection = await subReader.ReadNextSectionAsync();
                        while (subSection != null)
                        {
                            await context.Response.WriteAsync("--- Header count: " + subSection.Headers.Count + "<br>");
                            foreach (var headerPair in subSection.Headers)
                            {
                                await context.Response.WriteAsync("---- " + headerPair.Key + ": " + string.Join(", ", headerPair.Value) + "<br>");
                            }

                            subSection = await subReader.ReadNextSectionAsync();
                        }
                    }

                    // Drains any remaining section body that has not been consumed and reads the headers for the next section.
                    section = await reader.ReadNextSectionAsync();
                }

                await context.Response.WriteAsync("</body></html>");
            });

            app.Use(async (context, next) =>
            {
                if (context.Request.Path != new PathString("/SendMultipart"))
                {
                    await next();
                    return;
                }

                // For the purposes of the sample we're going to issue a multipart request to ourselves and then tunnel the response to the user.
                var client = new HttpClient();
                client.BaseAddress = new Uri("http://localhost:" + context.GetFeature<IHttpConnectionFeature>().LocalPort);

                var content = new MultipartContent("stuff");
                content.Add(new StringContent("Hello World"));
                content.Add(new FormUrlEncodedContent(new Dictionary<string, string>()));
                content.Add(new MultipartContent("nested") { new StringContent("Nested Hello World") });

                var response = await client.PostAsync("", content);

                context.Response.StatusCode = (int)response.StatusCode;
                context.Response.ContentType = response.Content.Headers.ContentType.ToString();
                await response.Content.CopyToAsync(context.Response.Body);
            });

            app.Run(async context =>
            {
                context.Response.ContentType = "text/html";
                await context.Response.WriteAsync("<html><body>Normal request.<br>");
                await context.Response.WriteAsync("<a href=\"/SendMultipart\">Send Multipart Request</a><br>");
                await context.Response.WriteAsync("</body></html>");
            });
        }
예제 #49
0
        public async Task<ActionResult> Create(EventInformation model)
        {
            var profile = _profileService.GetProfile(User.Identity.GetUserId().ToLong());

            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "All of the form fields are required");
                var createModel = new CreateEventViewModel(profile);
                return View(createModel);
            }

            var start = new DateTime(model.StartDate.Year, model.StartDate.Month, model.StartDate.Day,
                model.StartTime.Hour, model.StartTime.Minute, model.StartTime.Second);

            var end = new DateTime(model.EndDate.Year, model.EndDate.Month, model.EndDate.Day,
                model.EndTime.Hour, model.EndTime.Minute, model.EndTime.Second);

            var ev = new Event
            {
                DateCreated = DateTime.UtcNow,
                StartTime = start,
                EndTime = end,
                Name = model.EventName,
                Description = model.Description,
                Privacy = model.PrivacyLevel,
                Owner = profile.User,
                Location = new Location
                {
                    Name = model.LocationInput,
                    Address = new Address
                    {
                        AddressLine1 = string.Format("{0} {1}", model.street_number, model.route),
                        City = model.locality,
                        CountryRegion = model.country,
                        PostalCode = model.postal_code,
                        StateProvince = model.state
                    }
                }
            };

            if (!model.lng.IsEmpty() && !model.lat.IsEmpty())
            {
                ev.Location.Geography = DbGeography.FromText(string.Format("POINT ({0} {1})", model.lng, model.lat));
            }

            if (model.Picture != null)
            {
                using (var content = new MultipartContent())
                {
                    content.Add(new StreamContent(model.Picture.InputStream));

                    var upload = new MediaUpload
                    {
                        Content = content,
                        ContentSize = model.Picture.ContentLength,
                        ContentType = model.Picture.ContentType
                    };

                    var picture = await _mediaService.UploadMediaAsync(upload);
                    ev.Picture = picture;
                    Log.InfoFormat("Uploaded picture for event. MediaId={0}", picture.Id);
                }
            }

            // If they want to create on facebook, do it here
            try
            {
                if (model.CreateFacebookEvent)
                {
                    var fbEvent = new FacebookEvent
                    {
                        Name = ev.Name,
                        Description = ev.Description,
                        State_Time = start,
                        Owner = new FacebookIdentity
                        {
                            Id = profile.FacebookId
                        }
                    };

                    var eventId = await _facebookService.PublishEvent(profile.User, fbEvent);
                    Log.InfoFormat("Created Facebook Event for new event.  UserId={0} FacebookId={1}", profile.User.Id, eventId);
                    ev.FacebookId = eventId;
                }
            }
            catch (Exception e)
            {
                Log.ErrorFormat("Failed to create Facebook Event for new event.  UserId={0}", profile.User.Id);
            }


            // Add yourself to the invitees list
            ev.Invitations = new List<Invitation>
            {
                new Invitation
                {
                    FacebookUserId = profile.FacebookId,
                    FacebookName = profile.GetFullName(),
                    Response = RSVP.YES
                }
            };

            // Save event
            _eventService.CreateEvent(ev);
            Log.InfoFormat("Created new Event. UserId={0} EventId={1}", profile.User.Id, ev.Id);

            return RedirectToAction("Event", new {Id = ev.Id});
        }
예제 #50
0
        public async Task<ActionResult> UploadMedia(HttpPostedFileBase file, long eventId)
        {
            if (file == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "You must provide a file");
            
            var validExtensions = new[] {".jpg", ".jpeg", ".png", ".gif", ".mp4"};
            var isValid = validExtensions.Any(ext => file.FileName.EndsWith(ext, true, CultureInfo.InvariantCulture));
            if (!isValid) return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "You must provide a file of type jpg, png, gif, or mp4");

            var ev = _eventService.GetEvent(eventId);

            using (var content = new MultipartContent())
            {
                content.Add(new StreamContent(file.InputStream));

                var upload = new MediaUpload
                {
                    Content = content,
                    ContentSize = file.ContentLength,
                    ContentType = file.ContentType
                };

                var picture = await _mediaService.UploadMediaAsync(upload);
                _eventService.AddMediaToEvent(ev, picture);

                return Json(new 
                {
                    Url = picture.Url
                });
            }

        }
        internal MultipartContent PrepareMultipartContent(CancellationToken token)
        {
            var content = new MultipartContent("form-data", syncingBoundary);

            foreach (var item in needList)
            {
                token.ThrowIfCancellationRequested();

                var @from = Convert.ToInt64(item.FileOffset);
                var length = Convert.ToInt64(item.BlockLength);
                var to = from + length - 1;

                switch (item.BlockType)
                {
                    case RdcNeedType.Source:
                        content.Add(new SourceFilePart(new NarrowedStream(sourceStream, from, to)));
                        break;
                    case RdcNeedType.Seed:
                        content.Add(new SeedFilePart(@from, to));
                        break;
                    default:
                        throw new NotSupportedException();
                }
            }

            return content;
        }
        private async Task ExecuteAllOperationsAsync(OperationBatch batch)
        {
            long prevSeq = 0;

            if (this.context.BatchApiEndpoint == null)
            {
                MobileServiceTableOperation operation = await this.OperationQueue.PeekAsync(prevSeq, this.tableKind, this.tableNames);

                // keep taking out operations and executing them until queue is empty or operation finds the bookmark or batch is aborted 
                while (operation != null)
                {
                    using (await this.OperationQueue.LockItemAsync(operation.ItemId, this.CancellationToken))
                    {
                        bool success = await this.ExecuteOperationAsync(operation, batch);

                        if (batch.AbortReason.HasValue)
                        {
                            break;
                        }

                        if (success)
                        {
                            // we successfuly executed an operation so remove it from queue
                            await this.OperationQueue.DeleteAsync(operation.Id, operation.Version);
                        }

                        // get next operation
                        operation = await this.OperationQueue.PeekAsync(operation.Sequence, this.tableKind, this.tableNames);
                    }
                }

                return;
            }
            
            var baseClient = this.client;

            // keep taking out operations and executing them until queue is empty or operation finds the bookmark or batch is aborted 
            while (true)
            {
                var filter = new MultipartRequestHandler();
                this.client = new MobileServiceClient(baseClient.MobileAppUri, filter);

                // Get X Operations off the queue
                List<MobileServiceTableOperation> items = new List<MobileServiceTableOperation>();
                MobileServiceTableOperation operation = await this.OperationQueue.PeekAsync(prevSeq, this.tableKind, this.tableNames);

                while (operation != null && items.Count < context.BatchSize)
                {
                    items.Add(operation);
                    prevSeq = operation.Sequence;
                    operation = await this.OperationQueue.PeekAsync(prevSeq, this.tableKind, this.tableNames);
                }

                if (items.Count == 0)
                {
                    break;
                }

                filter.ExpectedRequests = items.Count;

                // TODO: LOCK OPERATIONS

                // TODO: Trigger pre send hooks...

                List<Task<bool>> runningOperations = new List<Task<bool>>();
                MultipartContent finalContent = new MultipartContent("mixed", "batch_" + Guid.NewGuid().ToString());
                foreach (var tableOperation in items)
                {
                    Task<bool> tableOperationtask = this.ExecuteOperationAsync(tableOperation, batch);
                    runningOperations.Add(tableOperationtask);
                }

                // TODO: Move the actual POST into the filter?

                // TODO: Adjust count if op task is cancelled/etc before hitting filter
                
                await filter.allOperationsQueued();
                foreach (var content in filter.Parts)
                {
                    finalContent.Add(content);
                }

                var batchedResponse = await baseClient.InvokeApiAsync(context.BatchApiEndpoint, finalContent, HttpMethod.Post, null, null, this.CancellationToken);
                MultipartMemoryStreamProvider responseContents = await batchedResponse.Content.ReadAsMultipartAsync();

                // TODO: verify order on response == order on request
                for (int i = 0; i < responseContents.Contents.Count; i++)
                {
                    var response = await responseContents.Contents[i].ReadAsHttpResponseMessageAsync();
                    var promise = filter.Promises[i];
                    promise.SetResult(response);
                }

                // Now review results of all operations in the batch
                for (int i = 0; i < runningOperations.Count; i++) {
                    var tableOperationTask = runningOperations[i];
                    var success = await tableOperationTask;

                    if (success)
                    {
                        // we successfuly executed an operation so remove it from queue
                        var tableOperation = items[i];
                        await this.OperationQueue.DeleteAsync(tableOperation.Id, tableOperation.Version);
                    }
                }

                if (batch.AbortReason.HasValue)
                {
                    break;
                }
            }

            this.client = baseClient;
        }
        public void ReadAsAsync_WhenContentIsMultipartContentAndFormatterCanReadFromTheContent()
        {
            MultipartContent mimeContent = new MultipartContent();
            mimeContent.Add(new StringContent("multipartContent"));

            _formatterMock.Setup(f => f.CanWriteType(It.IsAny<Type>())).Returns(true);
            _formatterMock.Setup(f => f.CanReadType(It.IsAny<Type>())).Returns(true);
            _formatterMock.Setup(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<IFormatterLogger>()))
                .Returns<Type, Stream, HttpContent, IFormatterLogger>((type, stream, content, logger) =>
                    {
                        MultipartMemoryStreamProvider provider = content.ReadAsMultipartAsync().Result;
                        Assert.Equal(1, provider.Contents.Count);
                        return TaskHelpers.FromResult<object>(provider.Contents[0].ReadAsStringAsync().Result);
                    });
            MediaTypeFormatter formatter = _formatterMock.Object;
            formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/mixed"));

            Assert.Equal("multipartContent", mimeContent.ReadAsAsync<string>(new[] { formatter }).Result);
        }
        public async Task PushAsync_ExecutesThePendingOperations_InOrder_BatchedOne()
        {
            var hijack = new TestHttpHandler();
            IMobileServiceClient service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp, hijack);
            var store = new MobileServiceLocalStoreMock();
            await service.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());

            IMobileServiceSyncTable table = service.GetSyncTable("someTable");

            JObject item1 = new JObject() { { "id", "abc" } }, item2 = new JObject() { { "id", "def" } };

            await table.InsertAsync(item1);
            await table.InsertAsync(item2);

            Assert.AreEqual(hijack.Requests.Count, 0);

            // create a new service to test that operations are loaded from store
            hijack = new TestHttpHandler();

            var content = new MultipartContent("mixed", "6f078995-ef2a-4617-a4c9-5d8746b26d32");
            var response = new HttpResponseMessage(HttpStatusCode.OK) {
                Content = new StringContent("{\"id\":\"abc\",\"String\":\"Hey\"}", Encoding.UTF8, "application/json")
            };
            content.Add(new HttpMessageContent(response));
            hijack.AddResponseContent(content);

            content = new MultipartContent("mixed", "6f078995-ef2a-4617-a4c9-5d8746b26d32");
            response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("{\"id\":\"def\",\"String\":\"What\"}", Encoding.UTF8, "application/json")
            };
            content.Add(new HttpMessageContent(response));
            hijack.AddResponseContent(content);

            service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp, hijack);
            await service.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());
            service.SyncContext.BatchApiEndpoint = "batch";
            service.SyncContext.BatchSize = 1;

            Assert.AreEqual(hijack.Requests.Count, 0);
            await service.SyncContext.PushAsync();
            Assert.AreEqual(hijack.Requests.Count, 2);

            Assert.IsTrue(hijack.RequestContents[0].Contains(item1.ToString(Formatting.None)));
            Assert.IsTrue(hijack.RequestContents[0].Contains("X-ZUMO-FEATURES: TU,OL"));
            Assert.IsTrue(hijack.RequestContents[1].Contains(item2.ToString(Formatting.None)));
            Assert.IsTrue(hijack.RequestContents[1].Contains("X-ZUMO-FEATURES: TU,OL"));

            // create yet another service to make sure the old items were purged from queue
            hijack = new TestHttpHandler();
            hijack.AddResponseContent("{\"id\":\"abc\",\"String\":\"Hey\"}");
            service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp, hijack);
            await service.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());
            Assert.AreEqual(hijack.Requests.Count, 0);
            await service.SyncContext.PushAsync();
            Assert.AreEqual(hijack.Requests.Count, 0);
        }
        public void ReadAsMultipartAsync_UsingMultipartContent(string boundary)
        {
            MultipartContent content = new MultipartContent("mixed", boundary);
            content.Add(new StringContent("A"));
            content.Add(new StringContent("B"));
            content.Add(new StringContent("C"));

            MemoryStream memStream = new MemoryStream();
            content.CopyToAsync(memStream).Wait();
            memStream.Position = 0;
            byte[] data = memStream.ToArray();
            var byteContent = new ByteArrayContent(data);
            byteContent.Headers.ContentType = content.Headers.ContentType;

            MultipartMemoryStreamProvider result = byteContent.ReadAsMultipartAsync().Result;
            Assert.Equal(3, result.Contents.Count);
            Assert.Equal("A", result.Contents[0].ReadAsStringAsync().Result);
            Assert.Equal("B", result.Contents[1].ReadAsStringAsync().Result);
            Assert.Equal("C", result.Contents[2].ReadAsStringAsync().Result);
        }
예제 #56
0
        public async Task<bool> CreatePostWithMedia(string messageUserId, string post, String path, byte[] fileStream,
            UserAccountEntity userAccountEntity)
        {
            try
            {
                var user = userAccountEntity.GetUserEntity();
                var url = string.Format(EndPoints.CreatePost, user.Region, messageUserId);
                const string boundary = "abcdefghijklmnopqrstuvwxyz";
                var messageJson = new SendMessage
                {
                    message = new Message()
                    {
                        body = post,
                        fakeMessageUid = 1384958573288,
                        messageKind = 1
                    }
                };

                var json = JsonConvert.SerializeObject(messageJson);
                var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
                stringContent.Headers.Add("Content-Description", "message");
                var form = new MultipartContent("mixed", boundary) { stringContent };

                Stream stream = new MemoryStream(fileStream);
                var t = new StreamContent(stream);
                var s = Path.GetExtension(path);
                if (s != null && s.Equals(".png"))
                {
                    t.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                }
                else
                {
                    var extension = Path.GetExtension(path);
                    if (extension != null && (extension.Equals(".jpg") || extension.Equals(".jpeg")))
                    {
                        t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                    }
                    else
                    {
                        t.Headers.ContentType = new MediaTypeHeaderValue("image/gif");
                    }
                }
                t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                t.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                t.Headers.Add("Content-Description", "image-data-0");
                t.Headers.Add("Content-Transfer-Encoding", "binary");
                t.Headers.ContentLength = stream.Length;
                form.Add(t);

                var result = await _webManager.PostData(new Uri(url), form, null, userAccountEntity);
                return result.IsSuccess;
            }
            catch (Exception ex)
            {

                throw new Exception("Failed to send post (with media)", ex);
            }
        }
        public void MimeMultipartParserTestMultipartContent(string boundary)
        {
            MultipartContent content = new MultipartContent("mixed", boundary);
            content.Add(new StringContent("A"));
            content.Add(new StringContent("B"));
            content.Add(new StringContent("C"));

            MemoryStream memStream = new MemoryStream();
            content.CopyToAsync(memStream).Wait();
            memStream.Position = 0;
            byte[] data = memStream.ToArray();

            for (var readSize = 1; readSize <= data.Length; readSize++)
            {
                MimeMultipartParser parser = CreateMimeMultipartParser(boundary);

                int totalBytesConsumed;
                List<string> bodyParts;
                MimeMultipartParser.State state = ParseBufferInSteps(parser, data, readSize, out bodyParts, out totalBytesConsumed);
                Assert.Equal(MimeMultipartParser.State.BodyPartCompleted, state);
                Assert.Equal(data.Length, totalBytesConsumed);

                Assert.Equal(4, bodyParts.Count);
                Assert.Empty(bodyParts[0]);

                Assert.True(bodyParts[1].EndsWith("A"));
                Assert.True(bodyParts[2].EndsWith("B"));
                Assert.True(bodyParts[3].EndsWith("C"));
            }
        }
예제 #58
0
			/// <summary>
			/// <see cref="HttpContent"/> implementation which provides a byte range view over a stream used to generate HTTP
			/// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend 
			/// of the selected resource represented by the <paramref name="content"/> parameter then an 
			/// <see cref="InvalidByteRangeException"/> is thrown indicating the valid Content-Range of the content. 
			/// </summary>
			/// <param name="content">The stream over which to generate a byte range view.</param>
			/// <param name="range">The range or ranges, typically obtained from the Range HTTP request header field.</param>
			/// <param name="mediaType">The media type of the content stream.</param>
			/// <param name="bufferSize">The buffer size used when copying the content stream.</param>
			public ByteRangeStreamContent(Stream content, RangeHeaderValue range, MediaTypeHeaderValue mediaType, int bufferSize)
			{

				try
				{
					// If we have more than one range then we use a multipart/byteranges content type as wrapper.
					// Otherwise we use a non-multipart response.
					if (range.Ranges.Count > 1)
					{
						// Create Multipart content and copy headers to this content
						MultipartContent rangeContent = new MultipartContent(ByteRangesContentSubtype);
						_byteRangeContent = rangeContent;

						foreach (RangeItemHeaderValue rangeValue in range.Ranges)
						{
							try
							{
								ByteRangeStream rangeStream = new ByteRangeStream(content, rangeValue);
								HttpContent rangeBodyPart = new StreamContent(rangeStream, bufferSize);
								rangeBodyPart.Headers.ContentType = mediaType;
								rangeBodyPart.Headers.ContentRange = rangeStream.ContentRange;
								rangeContent.Add(rangeBodyPart);
							}
							catch (ArgumentOutOfRangeException)
							{
								// We ignore range errors until we check that we have at least one valid range
							}
						}

						// If no overlapping ranges were found then stop
						if (!rangeContent.Any())
						{
							ContentRangeHeaderValue actualContentRange = new ContentRangeHeaderValue(content.Length);
							string msg = "ByteRangeStreamNoneOverlap";
							throw new InvalidByteRangeException(actualContentRange, msg);
						}
					}
					else if (range.Ranges.Count == 1)
					{
						try
						{
							ByteRangeStream rangeStream = new ByteRangeStream(content, range.Ranges.First());
							_byteRangeContent = new StreamContent(rangeStream, bufferSize);
							_byteRangeContent.Headers.ContentType = mediaType;
							_byteRangeContent.Headers.ContentRange = rangeStream.ContentRange;
						}
						catch (ArgumentOutOfRangeException)
						{
							ContentRangeHeaderValue actualContentRange = new ContentRangeHeaderValue(content.Length);
							string msg = "ByteRangeStreamNoOverlap";
							throw new InvalidByteRangeException(actualContentRange, msg);
						}
					}
					else
					{
						throw new ArgumentException("range");
					}

					// Copy headers from byte range content so that we get the right content type etc.
					_byteRangeContent.Headers.CopyTo(Headers);

					_content = content;
					_start = content.Position;
				}
				catch
				{
					if (_byteRangeContent != null)
					{
						_byteRangeContent.Dispose();
					}
					throw;
				}
			}
        /// <summary>
        /// Create a batching request content. The content contains three body part requests.
        /// </summary>
        /// <param name="baseAddress"></param>
        /// <param name="batchContent"></param>
        private static void CreateBatchedRequest(string baseAddress, MultipartContent batchContent)
        {
            batchContent.Add(
                new HttpMessageContent(
                    new HttpRequestMessage(
                        HttpMethod.Get,
                        baseAddress + "/api/demo"
                    )
                )
            );

            // this request is expected to recieve a 404
            batchContent.Add(
                new HttpMessageContent(
                    new HttpRequestMessage(
                        HttpMethod.Get,
                        baseAddress + "/not/found"
                    )
                )
            );

            batchContent.Add(
                new HttpMessageContent(
                    new HttpRequestMessage(
                        HttpMethod.Get,
                        baseAddress + "/api/demo/1"
                    )
                )
            );
        }
 public void Add_Invalid()
 {
     var m = new MultipartContent ("a", "b");
     try {
         m.Add (null);
         Assert.Fail ("#1");
     } catch (ArgumentNullException) {
     }
 }