Provides methods to parse a multipart/form-data stream into it's parameters and file data.

A parameter is defined as any non-file data passed in the multipart stream. For example any form fields would be considered a parameter.

The parser determines if a section is a file or not based on the presence or absence of the filename argument for the Content-Type header. If filename is set then the section is assumed to be a file, otherwise it is assumed to be parameter data.

Ejemplo n.º 1
0
        /// <summary>
        ///     Parse the stream into a new instance of the <see cref="MultipartFormDataParser" /> class
        ///     with the boundary, input encoding and buffer size.
        /// </summary>
        /// <param name="stream">
        ///     The stream containing the multipart data.
        /// </param>
        /// <param name="boundary">
        ///     The multipart/form-data boundary. This should be the value
        ///     returned by the request header.
        /// </param>
        /// <param name="encoding">
        ///     The encoding of the multipart data.
        /// </param>
        /// <param name="binaryBufferSize">
        ///     The size of the buffer to use for parsing the multipart form data. This must be larger
        ///     then (size of boundary + 4 + # bytes in newline).
        /// </param>
        /// <returns>
        ///     A new instance of the <see cref="MultipartFormDataParser"/> class.
        /// </returns>
        public static MultipartFormDataParser Parse(Stream stream, string boundary, Encoding encoding, int binaryBufferSize)
        {
            var parser = new MultipartFormDataParser();

            parser.ParseStream(stream, boundary, encoding, binaryBufferSize);
            return(parser);
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     Asynchronously parse the stream into a new instance of the <see cref="MultipartFormDataParser" /> class
        ///     with the boundary, input encoding and buffer size.
        /// </summary>
        /// <param name="stream">
        ///     The stream containing the multipart data.
        /// </param>
        /// <param name="boundary">
        ///     The multipart/form-data boundary. This should be the value
        ///     returned by the request header.
        /// </param>
        /// <param name="encoding">
        ///     The encoding of the multipart data.
        /// </param>
        /// <param name="binaryBufferSize">
        ///     The size of the buffer to use for parsing the multipart form data. This must be larger
        ///     then (size of boundary + 4 + # bytes in newline).
        /// </param>
        /// <returns>
        ///     A new instance of the <see cref="MultipartFormDataParser"/> class.
        /// </returns>
        public static async Task <MultipartFormDataParser> ParseAsync(Stream stream, string boundary, Encoding encoding, int binaryBufferSize)
        {
            var parser = new MultipartFormDataParser();
            await parser.ParseStreamAsync(stream, boundary, encoding, binaryBufferSize).ConfigureAwait(false);

            return(parser);
        }
Ejemplo n.º 3
0
        /// <summary>
        ///     Parse the stream into a new instance of the <see cref="MultipartFormDataParser" /> class
        ///     with the boundary, input encoding and buffer size.
        /// </summary>
        /// <param name="stream">
        ///     The stream containing the multipart data.
        /// </param>
        /// <param name="boundary">
        ///     The multipart/form-data boundary. This should be the value
        ///     returned by the request header.
        /// </param>
        /// <param name="encoding">
        ///     The encoding of the multipart data.
        /// </param>
        /// <param name="binaryBufferSize">
        ///     The size of the buffer to use for parsing the multipart form data. This must be larger
        ///     then (size of boundary + 4 + # bytes in newline).
        /// </param>
        /// <param name="binaryMimeTypes">
        ///     List of mimetypes that should be detected as file.
        /// </param>
        /// <returns>
        ///     A new instance of the <see cref="MultipartFormDataParser"/> class.
        /// </returns>
        public static MultipartFormDataParser Parse(Stream stream, string boundary = null, Encoding encoding = null, int binaryBufferSize = DefaultBufferSize, string[] binaryMimeTypes = null)
        {
            var parser = new MultipartFormDataParser();

            parser.ParseStream(stream, boundary, encoding, binaryBufferSize, binaryMimeTypes);
            return(parser);
        }
Ejemplo n.º 4
0
        /// <summary>
        ///     Asynchronously parse the stream into a new instance of the <see cref="MultipartFormDataParser" /> class
        ///     with the boundary, input encoding and buffer size.
        /// </summary>
        /// <param name="stream">
        ///     The stream containing the multipart data.
        /// </param>
        /// <param name="boundary">
        ///     The multipart/form-data boundary. This should be the value
        ///     returned by the request header.
        /// </param>
        /// <param name="encoding">
        ///     The encoding of the multipart data.
        /// </param>
        /// <param name="binaryBufferSize">
        ///     The size of the buffer to use for parsing the multipart form data. This must be larger
        ///     then (size of boundary + 4 + # bytes in newline).
        /// </param>
        /// <param name="binaryMimeTypes">
        ///     List of mimetypes that should be detected as file.
        /// </param>
        /// <returns>
        ///     A new instance of the <see cref="MultipartFormDataParser"/> class.
        /// </returns>
        public static async Task <MultipartFormDataParser> ParseAsync(Stream stream, string boundary = null, Encoding encoding = null, int binaryBufferSize = DefaultBufferSize, string[] binaryMimeTypes = null)
        {
            var parser = new MultipartFormDataParser();
            await parser.ParseStreamAsync(stream, boundary, encoding, binaryBufferSize, binaryMimeTypes).ConfigureAwait(false);

            return(parser);
        }
Ejemplo n.º 5
0
		public static NameValueCollection Parse(Stream stream, string contentType, out PostedFile[] files)
		{
			var parser = new MultipartFormDataParser(stream);
			var filesloaded = new List<PostedFile>();
			var form = new NameValueCollection();

			foreach(var f in parser.Files)
			{
				Stream data = f.Data;
				var file = new PostedFile();
				file.Contents = new MemoryStream (f.Data.ReadAllBytes ());
				file.Filename = f.FileName;
				filesloaded.Add (file);
			}

			files = filesloaded.ToArray ();

			var result = new NameValueCollection ();
			foreach (var kvp in parser.Parameters) 
			{
				result.Add (kvp.Key.ToString (), kvp.Value.ToString ());
			}

			return result;
		}
Ejemplo n.º 6
0
        public static HttpResponseMessage Process(HttpRequestMessage request)
        {
            // Check if the request contains multipart/form-data.
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            try
            {
                Stream reqStream = request.Content.ReadAsStreamAsync().Result;
                MemoryStream tempStream = new MemoryStream();
                reqStream.CopyTo(tempStream);
                
                tempStream.Seek(0, SeekOrigin.End);
                Log.Submit(LogLevel.Debug, "Upload request has " + tempStream.Length + " bytes");
                tempStream.Position = 0;
                
                StreamContent streamContent = new StreamContent(tempStream);
                foreach (KeyValuePair<string, IEnumerable<string>> header in request.Content.Headers)
                {
                    streamContent.Headers.Add(header.Key, header.Value);
                    Log.Submit(LogLevel.Debug, "Header " + header.Key + ": " + string.Join(",", header.Value));
                }

                MultipartFormDataParser parser = new MultipartFormDataParser(tempStream);

                // This illustrates how to get the file names.
                FilePart file = parser.Files.FirstOrDefault();
                if (parser.Files == null || parser.Files.Count != 1)
                    throw new InvalidOperationException();
                if (file == null || file.FileName != "package")
                    throw new InvalidOperationException();

                PackageDAO.ProcessPackage(file.Data);

                return request.CreateResponse(HttpStatusCode.Created);
            }
            catch (AlreadyExistsException e)
            {
                Log.SubmitException(e);
                return request.CreateErrorResponse(HttpStatusCode.Conflict, e);
            }
            catch (InvalidOperationException e)
            {
                Log.SubmitException(e);
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, e);
            }
            catch (Exception e)
            {
                Log.SubmitException(e);
                return request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
Ejemplo n.º 7
0
        public virtual Request GetRequest()
        {
            Request destination = new Request();

            destination.AcceptTypes = Source.AcceptTypes;
            destination.ContentEncoding = Source.ContentEncoding;
            destination.ContentLength = Source.ContentLength64;
            destination.ContentType = Source.ContentType;
            destination.Cookies = Source.Cookies;
            destination.Headers = Source.Headers;
            destination.RawUrl = Source.RawUrl;
            destination.UserAgent = Source.UserAgent;
            destination.QueryString = Source.QueryString;
            destination.LowLevelRequest = Source;
            destination.Form = new Dictionary<string, string>();
            destination.Files = new List<HttpFile>();

            if (Source.ContentLength64 < 1)
                return destination;

            Stream inputStream = Source.InputStream;
            MultipartFormDataParser parser = new MultipartFormDataParser(inputStream);

            foreach (var parameterName in parser.Parameters.Keys)
            {
                destination.Form.Add(parameterName, parser.Parameters[parameterName].Data);
            }

            foreach (var file in parser.Files)
            {
                HttpFile httpFile = new HttpFile
                {
                    ContentType = file.ContentType,
                    ContentDisposition = file.ContentDisposition,
                    FileName = file.FileName,
                    Name = file.Name,
                    Data = file.Data
                };
            }

            return destination;
        }
            /// <summary>
            /// Validates the output of the parser against the expected outputs for 
            /// this test
            /// </summary>
            /// <param name="parser">
            /// The parser to validate.
            /// </param>
            /// <returns>
            /// The <see cref="bool"/> representing if this test passed.
            /// </returns>
            public bool Validate(MultipartFormDataParser parser)
            {
                // Validate parameters
                foreach (var pair in this.ExpectedParams)
                {
                    if (!parser.Parameters.ContainsKey(pair.Key))
                    {
                        return false;
                    }

                    ParameterPart expectedPart = pair.Value;
                    ParameterPart actualPart = parser.Parameters[pair.Key];

                    Console.WriteLine("Expected {0} = {1}, Found {2} = {3}", expectedPart.Name, expectedPart.Data, actualPart.Name, actualPart.Data);

                    if (expectedPart.Name != actualPart.Name || expectedPart.Data != actualPart.Data)
                    {
                        return false;
                    }
                }

                // Validate files
                foreach (var file in parser.Files)
                {
                    bool foundPairMatch = false;
                    foreach (var pair in this.ExpectedFileData)
                    {
                        if (pair.Key == file.Name)
                        {
                            foundPairMatch = true;

                            FilePart expectedFile = pair.Value;
                            FilePart actualFile = file;

                            if (expectedFile.Name != actualFile.Name || expectedFile.FileName != actualFile.FileName)
                            {
                                return false;
                            }

                            if (expectedFile.ContentType != actualFile.ContentType || expectedFile.ContentDisposition != actualFile.ContentDisposition)
                            {
                                return false;
                            }

                            // Read the data from the files and see if it's the same
                            var reader = new StreamReader(expectedFile.Data);
                            string expectedFileData = reader.ReadToEnd();

                            reader = new StreamReader(actualFile.Data);
                            string actualFileData = reader.ReadToEnd();

                            if (expectedFileData != actualFileData)
                            {
                                return false;
                            }

                            break;
                        }
                    }

                    if (!foundPairMatch)
                    {
                        return false;
                    }
                }

                return true;
            }
        public void SmallDataTest()
        {
            using (Stream stream = TestUtil.StringToStream(SmallTestCase.Request))
            {
                // The boundry is missing the first two -- in accordance with the multipart
                // spec. (A -- is added by the parser, this boundry is what would be sent in the
                // requset header)
                var parser = new MultipartFormDataParser(stream, "---------------------------265001916915724");
                Assert.IsTrue(SmallTestCase.Validate(parser));

            }
        }
 public void CanDetectBoundriesWithNewLineInNextBuffer()
 {
     for (int i = 16; i < TinyTestCase.Request.Length; i++)
     {
         using (Stream stream = TestUtil.StringToStream(TinyTestCase.Request, Encoding.UTF8))
         {
             var parser = new MultipartFormDataParser(stream, "boundry", Encoding.UTF8, i);
             Assert.True(TinyTestCase.Validate(parser), $"Failure in buffer length {i}");
         }
     }
 }
 public void CanDetectBoundariesCrossBuffer()
 {
     using (Stream stream = TestUtil.StringToStream(TinyTestCase.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, "boundry", Encoding.UTF8, 16);
         Assert.IsTrue(TinyTestCase.Validate(parser));
     }
 }
            /// <summary>
            ///     Validates the output of the parser against the expected outputs for
            ///     this test
            /// </summary>
            /// <param name="parser">
            ///     The parser to validate.
            /// </param>
            /// <returns>
            ///     The <see cref="bool" /> representing if this test passed.
            /// </returns>
            public bool Validate(MultipartFormDataParser parser)
            {
                // Deal with all the parameters who are only expected to have one value.
                var expectedParametersWithSingleValue = ExpectedParams
                    .GroupBy(p => p.Name)
                    .Where(g => g.Count() == 0)
                    .Select(g => g.Single());

                foreach (var expectedParameter in expectedParametersWithSingleValue)
                {
                    if (!parser.HasParameter(expectedParameter.Name))
                    {
                        return false;
                    }

                    var actualValue = parser.GetParameterValue(expectedParameter.Name);
                    var actualValueFromValues = parser.GetParameterValues(expectedParameter.Name).Single();

                    if (actualValue != actualValueFromValues)
                    {
                        Console.WriteLine("GetParameterValue vs. GetParameterValues mismatch! ({0} != {1})", actualValue, actualValueFromValues);
                        return false;
                    }

                    Console.WriteLine("Expected {0} = {1}. Found {2} = {3}", expectedParameter.Name, expectedParameter.Data, expectedParameter.Name, actualValue);

                    if (expectedParameter.Data != actualValue)
                    {
                        return false;
                    }
                }

                // Deal with the parameters who are expected to have more then one value
                var expectedParametersWithMultiValues = ExpectedParams
                    .GroupBy(p => p.Name)
                    .Where(a => a.Count() > 1);

                foreach (var expectedParameters in expectedParametersWithMultiValues)
                {
                    var key = expectedParameters.Key;
                    if (!parser.HasParameter(key))
                    {
                        return false;
                    }

                    var actualValues = parser.GetParameterValues(key);

                    Console.WriteLine("Expected {0} = {1}. Found {2} = {3}",
                        key,
                        string.Join(",", expectedParameters.Select(p => p.Data)),
                        key,
                        string.Join(",", actualValues)
                    );

                    if (actualValues.Count() != expectedParameters.Count() || actualValues.Zip(expectedParameters, Tuple.Create).Any(t => t.Item1 != t.Item2.Data))
                    {
                        return false;
                    }
                }

                // Validate files
                foreach (var filePart in ExpectedFileData)
                {
                    var foundPairMatch = false;
                    foreach (var file in parser.Files)
                    {
                        if (filePart.Name == file.Name)
                        {
                            foundPairMatch = true;

                            FilePart expectedFile = filePart;
                            FilePart actualFile = file;

                            if (expectedFile.Name != actualFile.Name || expectedFile.FileName != actualFile.FileName)
                            {
                                return false;
                            }

                            if (expectedFile.ContentType != actualFile.ContentType ||
                                expectedFile.ContentDisposition != actualFile.ContentDisposition)
                            {
                                return false;
                            }

                            // Read the data from the files and see if it's the same
                            var reader = new StreamReader(expectedFile.Data);
                            string expectedFileData = reader.ReadToEnd();

                            reader = new StreamReader(actualFile.Data);
                            string actualFileData = reader.ReadToEnd();

                            if (expectedFileData != actualFileData)
                            {
                                return false;
                            }

                            break;
                        }
                    }

                    if (!foundPairMatch)
                    {
                        return false;
                    }
                }

                return true;
            }
        public void DoesNotCloseTheStream()
        {
            using (Stream stream = TestUtil.StringToStream(TinyTestCase.Request, Encoding.UTF8))
            {
                var parser = new MultipartFormDataParser(stream, "boundry", Encoding.UTF8);
                Assert.IsTrue(TinyTestCase.Validate(parser));

                stream.Position = 0;
                Assert.IsTrue(true, "A closed stream would throw ObjectDisposedException");
            }
        }
 public void AcceptSeveralValuesWithSameProperty()
 {
     using (Stream stream = TestUtil.StringToStream(SeveralValuesWithSameProperty.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, Encoding.UTF8);
         Assert.IsTrue(SeveralValuesWithSameProperty.Validate(parser));
     }
 }
 public void CorrectlyHandleMixedNewlineFormats()
 {
     // Replace the first '\n' with '\r\n'
     var regex = new Regex(Regex.Escape("\n"));
     string request = regex.Replace(TinyTestCase.Request, "\r\n", 1);
     using (Stream stream = TestUtil.StringToStream(request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, "boundry", Encoding.UTF8);
         Assert.IsTrue(TinyTestCase.Validate(parser));
     }
 }
 /// <summary>
 ///     Parse the stream into a new instance of the <see cref="MultipartFormDataParser" /> class
 ///     with the boundary and stream encoding.
 /// </summary>
 /// <param name="stream">
 ///     The stream containing the multipart data.
 /// </param>
 /// <param name="boundary">
 ///     The multipart/form-data boundary. This should be the value
 ///     returned by the request header.
 /// </param>
 /// <param name="encoding">
 ///     The encoding of the multipart data.
 /// </param>
 /// <returns>
 ///     A new instance of the <see cref="MultipartFormDataParser"/> class.
 /// </returns>
 public static MultipartFormDataParser Parse(Stream stream, string boundary, Encoding encoding)
 {
     return(MultipartFormDataParser.Parse(stream, boundary, encoding, DefaultBufferSize, null));
 }
 public void GetParameterValueReturnsNullIfNoParameterFound()
 {
     using (Stream stream = TestUtil.StringToStream(TinyTestCase.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, "boundry", Encoding.UTF8);
         Assert.Null(parser.GetParameterValue("does not exist"));
     }
 }
        public void HandlesFileWithLastCrLfImmediatlyAfterBufferLength()
        {
            string request =
            @"------WebKitFormBoundaryphElSb1aBJGfLyAP
            Content-Disposition: form-data; name=""fileName""

            Testfile
            ------WebKitFormBoundaryphElSb1aBJGfLyAP
            Content-Disposition: form-data; name=""file""; filename=""Testfile""
            Content-Type: application/pdf

            "
            + new string('\0', 8149)
            + @"
            ------WebKitFormBoundaryphElSb1aBJGfLyAP--
            ";

            using (Stream stream = TestUtil.StringToStream(request, Encoding.UTF8))
            {
                var parser = new MultipartFormDataParser(stream, Encoding.UTF8);
            }
        }
 public void SingleFileTest()
 {
     using (Stream stream = TestUtil.StringToStream(SingleFileTestCase.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, "boundry", Encoding.UTF8, 16);
         Assert.True(SingleFileTestCase.Validate(parser));
     }
 }
 public void CanHandleFinalDashesInSeperateBufferFromEndBinary()
 {
     using(Stream stream = TestUtil.StringToStream(ExactBufferTruncateTestCase.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, "boundry", Encoding.UTF8, 16);
         Assert.IsTrue(ExactBufferTruncateTestCase.Validate(parser));
     }
 }
Ejemplo n.º 21
0
 /// <summary>
 ///     Parse the stream into a new instance of the <see cref="MultipartFormDataParser" /> class
 ///     with the boundary.
 /// </summary>
 /// <param name="stream">
 ///     The stream containing the multipart data.
 /// </param>
 /// <param name="boundary">
 ///     The multipart/form-data boundary. This should be the value
 ///     returned by the request header.
 /// </param>
 /// <returns>
 ///     A new instance of the <see cref="MultipartFormDataParser"/> class.
 /// </returns>
 public static MultipartFormDataParser Parse(Stream stream, string boundary)
 {
     return(MultipartFormDataParser.Parse(stream, boundary, Encoding.UTF8, DefaultBufferSize));
 }
 public void DoesntInfiniteLoopOnUnclosedInput()
 {
     using (Stream stream = TestUtil.StringToStream(UnclosedBoundary.Request, Encoding.UTF8))
     {
         // We expect this to throw!
         var parser = new MultipartFormDataParser(stream, Encoding.UTF8);
     }
 }
Ejemplo n.º 23
0
 /// <summary>
 ///     Parse the stream into a new instance of the <see cref="MultipartFormDataParser" /> class
 ///     with the stream encoding. Boundary is automatically detected.
 /// </summary>
 /// <param name="stream">
 ///     The stream containing the multipart data.
 /// </param>
 /// <param name="encoding">
 ///     The encoding of the multipart data.
 /// </param>
 /// <returns>
 ///     A new instance of the <see cref="MultipartFormDataParser"/> class.
 /// </returns>
 public static MultipartFormDataParser Parse(Stream stream, Encoding encoding)
 {
     return(MultipartFormDataParser.Parse(stream, null, encoding, DefaultBufferSize));
 }
 public void CanHandleMixedSingleByteAndMultiByteWidthCharacters()
 {
     using (
         Stream stream = TestUtil.StringToStream(MixedSingleByteAndMultiByteWidthTestCase.Request, Encoding.UTF8)
         )
     {
         var parser = new MultipartFormDataParser(stream, Encoding.UTF8);
         Assert.IsTrue(MixedSingleByteAndMultiByteWidthTestCase.Validate(parser));
     }
 }
Ejemplo n.º 25
0
 /// <summary>
 ///     Parse the stream into a new instance of the <see cref="MultipartFormDataParser" /> class
 ///     with the input encoding and buffer size. Boundary is automatically detected.
 /// </summary>
 /// <param name="stream">
 ///     The stream containing the multipart data.
 /// </param>
 /// <param name="encoding">
 ///     The encoding of the multipart data.
 /// </param>
 /// <param name="binaryBufferSize">
 ///     The size of the buffer to use for parsing the multipart form data. This must be larger
 ///     then (size of boundary + 4 + # bytes in newline).
 /// </param>
 /// <returns>
 ///     A new instance of the <see cref="MultipartFormDataParser"/> class.
 /// </returns>
 public static MultipartFormDataParser Parse(Stream stream, Encoding encoding, int binaryBufferSize)
 {
     return(MultipartFormDataParser.Parse(stream, null, encoding, binaryBufferSize));
 }
 public void HandlesFullPathAsFileNameWithSemicolonCorrectly()
 {
     using (Stream stream = TestUtil.StringToStream(FullPathAsFileNameWithSemicolon.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, Encoding.UTF8);
         Assert.IsTrue(FullPathAsFileNameWithSemicolon.Validate(parser));
     }
 }
 public void CanHandleUnicodeWidthAndAsciiWidthCharacters()
 {
     using (
         var stream = TestUtil.StringToStream(MixedUnicodeWidthAndAsciiWidthCharactersTestCase.Request,
                                              Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, Encoding.UTF8);
         Assert.IsTrue(MixedUnicodeWidthAndAsciiWidthCharactersTestCase.Validate(parser));
     }
 }
 public void CanAutoDetectBoundary()
 {
     using (Stream stream = TestUtil.StringToStream(TinyTestCase.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream);
         Assert.IsTrue(TinyTestCase.Validate(parser));
     }
 }
        public void CorrectlyHandlesMultilineParameter()
        {
            string request = TestUtil.TrimAllLines(
                @"-----------------------------41952539122868
                Content-Disposition: form-data; name=""multilined""

                line 1
                line 2
                line 3
                -----------------------------41952539122868--");

            using (Stream stream = TestUtil.StringToStream(request, Encoding.UTF8))
            {
                var parser = new MultipartFormDataParser(stream, Encoding.UTF8);
                Assert.AreEqual(parser.Parameters["multilined"].Data, "line 1\r\nline 2\r\nline 3");
            }
        }
 public void CanHandleFileAsLastSection()
 {
     using (Stream stream = TestUtil.StringToStream(FileIsLastTestCase.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, Encoding.UTF8);
         Assert.IsTrue(FileIsLastTestCase.Validate(parser));
     }
 }
 /// <summary>
 ///     Asynchronously parse the stream into a new instance of the <see cref="MultipartFormDataParser" /> class
 ///     with the stream encoding. Boundary is automatically detected.
 /// </summary>
 /// <param name="stream">
 ///     The stream containing the multipart data.
 /// </param>
 /// <param name="encoding">
 ///     The encoding of the multipart data.
 /// </param>
 /// <returns>
 ///     A new instance of the <see cref="MultipartFormDataParser"/> class.
 /// </returns>
 public static Task <MultipartFormDataParser> ParseAsync(Stream stream, Encoding encoding)
 {
     return(MultipartFormDataParser.ParseAsync(stream, null, encoding, DefaultBufferSize, null));
 }
 public void CorrectlyHandlesCRLF()
 {
     string request = TinyTestCase.Request.Replace("\n", "\r\n");
     using (Stream stream = TestUtil.StringToStream(request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, "boundry", Encoding.UTF8);
         Assert.IsTrue(TinyTestCase.Validate(parser));
     }
 }
Ejemplo n.º 33
0
 /// <summary>
 ///     Asynchronously parse the stream into a new instance of the <see cref="MultipartFormDataParser" /> class.
 ///     Boundary will be automatically detected based on the first line of input.
 /// </summary>
 /// <param name="stream">
 ///     The stream containing the multipart data.
 /// </param>
 /// <returns>
 ///     A new instance of the <see cref="MultipartFormDataParser"/> class.
 /// </returns>
 public static Task <MultipartFormDataParser> ParseAsync(Stream stream)
 {
     return(MultipartFormDataParser.ParseAsync(stream, null, Encoding.UTF8, DefaultBufferSize));
 }
 public void MultipleFilesAndParamsTest()
 {
     using (Stream stream = TestUtil.StringToStream(MultipleParamsAndFilesTestCase.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, "boundry", Encoding.UTF8, 16);
         Assert.IsTrue(MultipleParamsAndFilesTestCase.Validate(parser));
     }
 }
Ejemplo n.º 35
0
 /// <summary>
 ///     Asynchronously parse the stream into a new instance of the <see cref="MultipartFormDataParser" /> class
 ///     with the boundary and stream encoding.
 /// </summary>
 /// <param name="stream">
 ///     The stream containing the multipart data.
 /// </param>
 /// <param name="boundary">
 ///     The multipart/form-data boundary. This should be the value
 ///     returned by the request header.
 /// </param>
 /// <param name="encoding">
 ///     The encoding of the multipart data.
 /// </param>
 /// <returns>
 ///     A new instance of the <see cref="MultipartFormDataParser"/> class.
 /// </returns>
 public static Task <MultipartFormDataParser> ParseAsync(Stream stream, string boundary, Encoding encoding)
 {
     return(MultipartFormDataParser.ParseAsync(stream, boundary, encoding, DefaultBufferSize));
 }
 public void TinyDataTest()
 {
     using (Stream stream = TestUtil.StringToStream(TinyTestCase.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, "boundry", Encoding.UTF8);
         Assert.IsTrue(TinyTestCase.Validate(parser));
     }
 }
Ejemplo n.º 37
0
 /// <summary>
 ///     Asynchronously parse the stream into a new instance of the <see cref="MultipartFormDataParser" /> class
 ///     with the input encoding and buffer size. Boundary is automatically detected.
 /// </summary>
 /// <param name="stream">
 ///     The stream containing the multipart data.
 /// </param>
 /// <param name="encoding">
 ///     The encoding of the multipart data.
 /// </param>
 /// <param name="binaryBufferSize">
 ///     The size of the buffer to use for parsing the multipart form data. This must be larger
 ///     then (size of boundary + 4 + # bytes in newline).
 /// </param>
 /// <returns>
 ///     A new instance of the <see cref="MultipartFormDataParser"/> class.
 /// </returns>
 public static Task <MultipartFormDataParser> ParseAsync(Stream stream, Encoding encoding, int binaryBufferSize)
 {
     return(MultipartFormDataParser.ParseAsync(stream, null, encoding, binaryBufferSize));
 }
Ejemplo n.º 38
0
        public object[] Deserialize(Stream readStream, Type[] types, string[] names)
        {
            var retVal = new object[types.Length];

            if (!types.Any())
            {
                return(retVal);
            }
            var parser = new HttpMultipartParser.MultipartFormDataParser(readStream);

            for (int i = 0; i < types.Length; i++)
            {
                var type = types[i];
                if (simpleTypes.Any(x => x == types[i]))
                {
                    var part = parser.BodyParts.FirstOrDefault(x => x.Name.Equals(names[i], StringComparison.OrdinalIgnoreCase));
                    if (part == null)
                    {
                        retVal[i] = null;
                    }
                    else
                    {
                        var token = Newtonsoft.Json.Linq.JToken.Parse((part as ParameterPart).Data);
                        retVal[i] = token.ToObject(type);
                    }
                }
                else if (typeof(Stream).IsAssignableFrom(type))
                {
                    var part = parser.BodyParts.FirstOrDefault(x => x.Name.Equals(names[i], StringComparison.OrdinalIgnoreCase));
                    if (part == null)
                    {
                        retVal[i] = null;
                    }
                    else
                    {
                        retVal[i] = (part as FilePart).Data;
                    }
                }
                else if (typeof(IRpcEventHandleResult).IsAssignableFrom(type))
                {
                    var part = parser.BodyParts.FirstOrDefault(x => x.Name.Equals(names[i], StringComparison.OrdinalIgnoreCase));
                    if (part == null)
                    {
                        retVal[i] = null;
                    }
                    else
                    {
                        retVal[i] = CoreObject.Deserialize(type, (part as FilePart).Data);
                    }
                }
                else if (type.IsClass && !type.IsAbstract)
                {
                    //class model
                    try
                    {
                        var properties = type.GetProperties().Where(x => x.CanRead && x.CanWrite).ToArray();
                        var obj        = Activator.CreateInstance(type);
                        var values     = DeserializeInternal(parser, properties.Select(x => x.PropertyType).ToArray(), properties.Select(x => x.Name).ToArray());
                        for (int idx = 0; idx < properties.Length; idx++)
                        {
                            properties[idx].SetValue(obj, values[i]);
                        }
                        retVal[i] = obj;
                    }
                    catch (Exception ex)
                    {
                        throw new NotSupportedException(string.Format("parameter at {0} using type {1} is not supported by HttpMultipartSerializer", i, types[i]), ex);
                    }
                }
                else
                {
                    throw new NotSupportedException(string.Format("parameter at {0} using type {1} is not supported by HttpMultipartSerializer", i, types[i]));
                }
            }
            return(retVal);
        }
 /// <summary>
 ///     Parse the stream into a new instance of the <see cref="MultipartFormDataParser" /> class.
 ///     Boundary will be automatically detected based on the first line of input.
 /// </summary>
 /// <param name="stream">
 ///     The stream containing the multipart data.
 /// </param>
 /// <returns>
 ///     A new instance of the <see cref="MultipartFormDataParser"/> class.
 /// </returns>
 public static MultipartFormDataParser Parse(Stream stream)
 {
     return(MultipartFormDataParser.Parse(stream, null, Encoding.UTF8, DefaultBufferSize, null));
 }