public void GetStream_ThrowsOnNullParent()
        {
            TProvider          provider = new TProvider();
            HttpContentHeaders headers  = FormattingUtilities.CreateEmptyContentHeaders();

            Assert.ThrowsArgumentNull(() => provider.GetStream(null, headers), "parent");
        }
        /// <summary>
        /// Read the non-file contents as form data.
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the post processing.</returns>
        public static async Task ReadFormDataAsync(
            Collection <HttpContent> contents,
            NameValueCollection formData,
            CancellationToken cancellationToken
            )
        {
            // Find instances of HttpContent for which we created a memory stream and read them asynchronously
            // to get the string content and then add that as form data
            foreach (HttpContent content in contents)
            {
                ContentDispositionHeaderValue contentDisposition =
                    content.Headers.ContentDisposition;
                // If FileName is null or empty, the content is form data and will be processed.
                if (String.IsNullOrEmpty(contentDisposition.FileName))
                {
                    // Extract name from Content-Disposition header. We know from earlier that the header is present.
                    string formFieldName =
                        FormattingUtilities.UnquoteToken(contentDisposition.Name) ?? String.Empty;

                    // Read the contents as string data and add to form data
                    cancellationToken.ThrowIfCancellationRequested();
                    string formFieldValue = await content.ReadAsStringAsync();

                    formData.Add(formFieldName, formFieldValue);
                }
            }
        }
Ejemplo n.º 3
0
        public void CreateEmptyContentHeadersReturnsEmptyHeaders()
        {
            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();

            Assert.NotNull(headers);
            Assert.Equal(0, headers.Count());
        }
Ejemplo n.º 4
0
        public void TryParseDate_AcceptsValidDates(string dateValue, DateTimeOffset expectedDate)
        {
            DateTimeOffset actualDate;

            Assert.True(FormattingUtilities.TryParseDate(dateValue, out actualDate));
            Assert.Equal(expectedDate, actualDate);
        }
Ejemplo n.º 5
0
        public void TryParseInt32_AcceptsValidNumbers(string intValue, int expectedInt)
        {
            int actualInt;

            Assert.True(FormattingUtilities.TryParseInt32(intValue, out actualInt));
            Assert.Equal(expectedInt, actualInt);
        }
Ejemplo n.º 6
0
 public void IsJsonValueTypeReturnsTrue()
 {
     Assert.True(FormattingUtilities.IsJTokenType(typeof(JToken)), "Should return true");
     Assert.True(FormattingUtilities.IsJTokenType(typeof(JValue)), "Should return true");
     Assert.True(FormattingUtilities.IsJTokenType(typeof(JObject)), "Should return true");
     Assert.True(FormattingUtilities.IsJTokenType(typeof(JArray)), "Should return true");
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Looks for the "start" parameter of the parent's content type and then finds the corresponding
        /// child HttpContent with a matching Content-ID header field.
        /// </summary>
        /// <returns>The matching child or null if none found.</returns>
        private static HttpContent FindRootContent(HttpContent parent, IEnumerable <HttpContent> children)
        {
            Contract.Assert(children != null);

            // Find 'start' parameter from parent content type. The value is used
            // to identify the MIME body with the corresponding Content-ID header value.
            NameValueHeaderValue startNameValue = FindMultipartRelatedParameter(parent, StartParameter);

            if (startNameValue == null)
            {
                // If we didn't find a "start" parameter then take the first child.
                return(children.FirstOrDefault());
            }

            // Look for the child with a Content-ID header that corresponds to the "start" value.
            // If no matching child is found then we return null.
            string startValue = FormattingUtilities.UnquoteToken(startNameValue.Value);

            return(children.FirstOrDefault(
                       content =>
            {
                IEnumerable <string> values;
                if (content.Headers.TryGetValues(ContentID, out values))
                {
                    return String.Equals(
                        FormattingUtilities.UnquoteToken(values.ElementAt(0)),
                        startValue,
                        StringComparison.OrdinalIgnoreCase);
                }

                return false;
            }));
        }
        public void Constructor_ThrowsOnNullLocation()
        {
            // Arrange
            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();

            // Act & Assert
            Assert.ThrowsArgumentNull(() => new RemoteStreamInfo(new MemoryStream(), null, "Name"), "location");
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MimeBodyPart"/> class.
 /// </summary>
 /// <param name="streamProvider">The stream provider.</param>
 /// <param name="maxBodyPartHeaderSize">The max length of the MIME header within each MIME body part.</param>
 public MimeBodyPart(MultipartStreamProvider streamProvider, int maxBodyPartHeaderSize)
 {
     Contract.Assert(streamProvider != null);
     _streamProvider = streamProvider;
     Segments        = new List <ArraySegment <byte> >(2);
     _headers        = FormattingUtilities.CreateEmptyContentHeaders();
     HeaderParser    = new InternetMessageFormatHeaderParser(_headers, maxBodyPartHeaderSize);
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MimeBodyPart"/> class.
 /// </summary>
 /// <param name="streamProvider">The stream provider.</param>
 /// <param name="maxBodyPartHeaderSize">The max length of the MIME header within each MIME body part.</param>
 public MimeBodyPart(IMultipartStreamProvider streamProvider, int maxBodyPartHeaderSize)
 {
     Contract.Assert(streamProvider != null, "Stream provider cannot be null.");
     _streamProvider = streamProvider;
     Segments        = new ArrayList(2);
     _headers        = FormattingUtilities.CreateEmptyContentHeaders();
     HeaderParser    = new InternetMessageFormatHeaderParser(_headers, maxBodyPartHeaderSize);
 }
        public void GetStream_ThrowsOnNoContentDisposition()
        {
            MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(ValidPath);
            HttpContent        content = new StringContent(String.Empty);
            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();

            Assert.Throws <InvalidOperationException>(() => { provider.GetStream(content, headers); });
        }
Ejemplo n.º 12
0
        public void Constructor_ThrowsOnNullLocation()
        {
            // Arrange
            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();

            // Act and Assert
            Assert.ThrowsArgumentNull(() => new MultipartRemoteFileData(headers, null, "Name"), "location");
        }
Ejemplo n.º 13
0
        public void Constructor_ThrowsOnNullFileName()
        {
            // Arrange
            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();

            // Act and Assert
            Assert.ThrowsArgumentNull(() => new MultipartRemoteFileData(headers, "http://some/path/to", null),
                                      "fileName");
        }
        public void Constructor_ThrowsOnNullFileName()
        {
            // Arrange
            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();

            // Act & Assert
            Assert.ThrowsArgumentNull(() => new RemoteStreamInfo(new MemoryStream(), "http://some/path/to", null),
                                      "fileName");
        }
        public void GetStream_ThrowsOnNoContentDisposition()
        {
            // Arrange
            CustomMultipartFormDataRemoteStreamProvider provider = new CustomMultipartFormDataRemoteStreamProvider();
            HttpContent        content = new StringContent(String.Empty);
            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();

            // Act & Assert
            Assert.Throws <InvalidOperationException>(() => { provider.GetStream(content, headers); });
        }
 private static bool FirstDispositionName(HttpContent content, string dispositionName)
 {
     Contract.Assert(content != null, "content cannot be null");
     Contract.Assert(dispositionName != null, "dispositionName cannot be null");
     return(content.Headers != null && content.Headers.ContentDisposition != null &&
            String.Equals(
                FormattingUtilities.UnquoteToken(content.Headers.ContentDisposition.Name),
                FormattingUtilities.UnquoteToken(dispositionName),
                StringComparison.OrdinalIgnoreCase));
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Validates whether the content contains an HTTP Request or an HTTP Response.
        /// </summary>
        /// <param name="content">The content to validate.</param>
        /// <param name="isRequest">if set to <c>true</c> if the content is either an HTTP Request or an HTTP Response.</param>
        /// <param name="throwOnError">Indicates whether validation failure should result in an <see cref="Exception"/> or not.</param>
        /// <returns><c>true</c> if content is either an HTTP Request or an HTTP Response</returns>
        internal static bool ValidateHttpMessageContent(HttpContent content, bool isRequest, bool throwOnError)
        {
            if (content == null)
            {
                throw Error.ArgumentNull("content");
            }

            MediaTypeHeaderValue contentType = content.Headers.ContentType;

            if (contentType != null)
            {
                if (!contentType.MediaType.Equals(DefaultMediaType, StringComparison.OrdinalIgnoreCase))
                {
                    if (throwOnError)
                    {
                        throw Error.Argument("content", Properties.Resources.HttpMessageInvalidMediaType, FormattingUtilities.HttpContentType.Name,
                                             isRequest ? DefaultRequestMediaType : DefaultResponseMediaType);
                    }
                    else
                    {
                        return(false);
                    }
                }

                foreach (NameValueHeaderValue parameter in contentType.Parameters)
                {
                    if (parameter.Name.Equals(MsgTypeParameter, StringComparison.OrdinalIgnoreCase))
                    {
                        string msgType = FormattingUtilities.UnquoteToken(parameter.Value);
                        if (!msgType.Equals(isRequest ? DefaultRequestMsgType : DefaultResponseMsgType, StringComparison.OrdinalIgnoreCase))
                        {
                            if (throwOnError)
                            {
                                throw Error.Argument("content", Properties.Resources.HttpMessageInvalidMediaType, FormattingUtilities.HttpContentType.Name, isRequest ? DefaultRequestMediaType : DefaultResponseMediaType);
                            }
                            else
                            {
                                return(false);
                            }
                        }

                        return(true);
                    }
                }
            }

            if (throwOnError)
            {
                throw Error.Argument("content", Properties.Resources.HttpMessageInvalidMediaType, FormattingUtilities.HttpContentType.Name, isRequest ? DefaultRequestMediaType : DefaultResponseMediaType);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 18
0
        public void Constructor_InitializesCorrectly()
        {
            // Arrange
            HttpContentHeaders headers  = FormattingUtilities.CreateEmptyContentHeaders();
            string             fileName = "filename";

            // Act
            MultipartFileData fileData = new MultipartFileData(headers, fileName);

            Assert.Same(headers, fileData.Headers);
            Assert.Same(fileName, fileData.LocalFileName);
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MimeBodyPart"/> class.
 /// </summary>
 /// <param name="streamProvider">The stream provider.</param>
 /// <param name="maxBodyPartHeaderSize">The max length of the MIME header within each MIME body part.</param>
 /// <param name="parentContent">The part's parent content</param>
 public MimeBodyPart(MultipartStreamProvider streamProvider, int maxBodyPartHeaderSize, HttpContent parentContent)
 {
     Contract.Assert(streamProvider != null);
     Contract.Assert(parentContent != null);
     _streamProvider = streamProvider;
     _parentContent  = parentContent;
     Segments        = new List <ArraySegment <byte> >(2);
     _headers        = FormattingUtilities.CreateEmptyContentHeaders();
     HeaderParser    = new InternetMessageFormatHeaderParser(
         _headers,
         maxBodyPartHeaderSize,
         ignoreHeaderValidation: true);
 }
Ejemplo n.º 20
0
        public void Constructor_InitializesCorrectly()
        {
            // Arrange
            HttpContentHeaders headers       = FormattingUtilities.CreateEmptyContentHeaders();
            string             remoteFileURL = "http://some/path/to";
            string             fileName      = "Name";

            // Act
            MultipartRemoteFileData fileData = new MultipartRemoteFileData(headers, remoteFileURL, fileName);

            // Assert
            Assert.Same(headers, fileData.Headers);
            Assert.Same(remoteFileURL, fileData.Location);
            Assert.Same(fileName, fileData.FileName);
        }
        /// <summary>
        /// Copies the unsorted header fields to a sorted collection.
        /// </summary>
        /// <param name="source">The unsorted source headers</param>
        /// <param name="destination">The destination <see cref="HttpRequestHeaders"/> or <see cref="HttpResponseHeaders"/>.</param>
        /// <param name="contentStream">The input <see cref="Stream"/> used to form any <see cref="HttpContent"/> being part of this HTTP request.</param>
        /// <param name="rewind">Start location of any request entity within the <paramref name="contentStream"/>.</param>
        /// <returns>An <see cref="HttpContent"/> instance if header fields contained and <see cref="HttpContentHeaders"/>.</returns>
        private static HttpContent CreateHeaderFields(
            HttpHeaders source,
            HttpHeaders destination,
            Stream contentStream,
            int rewind
            )
        {
            Contract.Assert(source != null, "source headers cannot be null");
            Contract.Assert(destination != null, "destination headers cannot be null");
            Contract.Assert(contentStream != null, "contentStream must be non null");
            HttpContentHeaders contentHeaders = null;
            HttpContent        content        = null;

            // Set the header fields
            foreach (KeyValuePair <string, IEnumerable <string> > header in source)
            {
                if (!destination.TryAddWithoutValidation(header.Key, header.Value))
                {
                    if (contentHeaders == null)
                    {
                        contentHeaders = FormattingUtilities.CreateEmptyContentHeaders();
                    }

                    contentHeaders.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            // If we have content headers then create an HttpContent for this Response
            if (contentHeaders != null)
            {
                // Need to rewind the input stream to be at the position right after the HTTP header
                // which we may already have parsed as we read the content stream.
                if (!contentStream.CanSeek)
                {
                    throw Error.InvalidOperation(
                              Properties.Resources.HttpMessageContentStreamMustBeSeekable,
                              "ContentReadStream",
                              FormattingUtilities.HttpResponseMessageType.Name
                              );
                }

                contentStream.Seek(0 - rewind, SeekOrigin.Current);
                content = new StreamContent(contentStream);
                contentHeaders.CopyTo(content.Headers);
            }

            return(content);
        }
Ejemplo n.º 22
0
        public void Constructor_InitializesCorrectly()
        {
            // Arrange
            HttpContentHeaders headers       = FormattingUtilities.CreateEmptyContentHeaders();
            string             remoteFileURL = "http://some/path/to";
            string             fileName      = "Name";
            Stream             stream        = new MemoryStream();

            // Act
            RemoteStreamInfo fileData = new RemoteStreamInfo(stream, remoteFileURL, fileName);

            // Assert
            Assert.Same(stream, fileData.RemoteStream);
            Assert.Same(remoteFileURL, fileData.Location);
            Assert.Same(fileName, fileData.FileName);
        }
        private static bool FirstStart(HttpContent content, string start)
        {
            Contract.Assert(content != null, "content cannot be null");
            Contract.Assert(start != null, "start cannot be null");
            if (content.Headers != null)
            {
                IEnumerable <string> values;
                if (content.Headers.TryGetValues(ContentID, out values))
                {
                    return(String.Equals(
                               FormattingUtilities.UnquoteToken(values.ElementAt(0)),
                               FormattingUtilities.UnquoteToken(start),
                               StringComparison.OrdinalIgnoreCase));
                }
            }

            return(false);
        }
        public void CopyTo_CopiesContentHeaders()
        {
            // Arrange
            HttpContentHeaders source = FormattingUtilities.CreateEmptyContentHeaders();

            source.ContentType     = MediaTypeHeaderValue.Parse("application/json; charset=utf8; parameter=value");
            source.ContentLength   = 1234;
            source.ContentLocation = new Uri("http://some.host");
            source.Add("test-name1", "test-value1");
            source.Add("test-name2", "test-value2");

            HttpContentHeaders destination = FormattingUtilities.CreateEmptyContentHeaders();

            // Act
            source.CopyTo(destination);

            // Assert
            Assert.Equal(source.ToString(), destination.ToString());
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Read the non-file contents as form data.
        /// </summary>
        /// <returns></returns>
        public override async Task ExecutePostProcessingAsync()
        {
            // Find instances of HttpContent for which we created a memory stream and read them asynchronously
            // to get the string content and then add that as form data
            for (int index = 0; index < Contents.Count; index++)
            {
                if (_isFormData[index])
                {
                    HttpContent formContent = Contents[index];
                    // Extract name from Content-Disposition header. We know from earlier that the header is present.
                    ContentDispositionHeaderValue contentDisposition = formContent.Headers.ContentDisposition;
                    string formFieldName = FormattingUtilities.UnquoteToken(contentDisposition.Name) ?? String.Empty;

                    // Read the contents as string data and add to form data
                    string formFieldValue = await formContent.ReadAsStringAsync();

                    FormData.Add(formFieldName, formFieldValue);
                }
            }
        }
Ejemplo n.º 26
0
        public void GetStream_ReturnsNewMemoryStream()
        {
            // Arrange
            MultipartMemoryStreamProvider instance = new MultipartMemoryStreamProvider();
            HttpContent        parent  = new StringContent(String.Empty);
            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();

            // Act
            Stream stream1 = instance.GetStream(parent, headers);
            Stream stream2 = instance.GetStream(parent, headers);

            // Assert
            Assert.IsType <MemoryStream>(stream1);
            Assert.Equal(0, stream1.Length);
            Assert.Equal(0, stream1.Position);

            Assert.IsType <MemoryStream>(stream2);
            Assert.Equal(0, stream2.Length);
            Assert.Equal(0, stream2.Position);

            Assert.NotSame(stream1, stream2);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Read the non-file contents as form data.
        /// </summary>
        /// <returns></returns>
        public override Task ExecutePostProcessingAsync()
        {
            // Find instances of HttpContent for which we created a memory stream and read them asynchronously
            // to get the string content and then add that as form data
            IEnumerable <Task> readTasks = Contents.Where((content, index) => _isFormData[index] == true).Select(
                formContent =>
            {
                // Extract name from Content-Disposition header. We know from earlier that the header is present.
                ContentDispositionHeaderValue contentDisposition = formContent.Headers.ContentDisposition;
                string formFieldName = FormattingUtilities.UnquoteToken(contentDisposition.Name) ?? String.Empty;

                // Read the contents as string data and add to form data
                return(formContent.ReadAsStringAsync().Then(
                           formFieldValue =>
                {
                    FormData.Add(formFieldName, formFieldValue);
                }, runSynchronously: true));
            });

            // Actually execute the read tasks while trying to stay on the same thread
            return(TaskHelpers.Iterate(readTasks));
        }
Ejemplo n.º 28
0
        public void TryParseInt32_RejectsInvalidNumbers(string intValue)
        {
            int actualInt;

            Assert.False(FormattingUtilities.TryParseInt32(intValue, out actualInt));
        }
Ejemplo n.º 29
0
        public void TryStringToDate_RejectsInvalidDates(string dateValue)
        {
            DateTimeOffset actualDate;

            Assert.False(FormattingUtilities.TryParseDate(dateValue, out actualDate));
        }
Ejemplo n.º 30
0
        public void DateToString_GeneratesValidValue(DateTimeOffset input, string expectedValue)
        {
            string actualValue = FormattingUtilities.DateToString(input);

            Assert.Equal(expectedValue, actualValue);
        }