Exemplo n.º 1
0
        private void ProccesRequest(HttpListenerRequest request)
        {
            Console.WriteLine("I have an request: " + request.ContentType);

            var parser = new MultipartFormDataParser(request.InputStream, Encoding.UTF8);

            string method = parser.Parameters[0].Data;

            var    file     = parser.Files.First();
            var    filename = file.FileName;
            Stream data     = file.Data;

            switch (method)
            {
            case "Create":
                ProcessCreate(filename, data);
                break;

            case "Change":
                ProcessChange(filename, data);
                break;

            default:
                break;
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Binds the model.
        /// </summary>
        /// <typeparam name="T">Model type</typeparam>
        /// <param name="args">The <see cref="ModelBinderEventArgs{T}" /> instance containing the event data.</param>
        public async Task BindAsync <T>(ModelBinderEventArgs <T> args)
        {
            if (!args.Context.Request.ContentType.Contains("multipart/form-data"))
            {
                return;
            }

            var multipartModelType = typeof(MultipartViewModel);

            if (typeof(T) != multipartModelType)
            {
                throw new ModelBindingException("For HTTP multipart form data model type should be: " + multipartModelType.Name);
            }

            var parser = await MultipartFormDataParser.ParseAsync(args.Context.Request.Body);

            var obj = Activator.CreateInstance <T>();

            var model = (MultipartViewModel)(object)obj;

            model.Files      = parser.Files;
            model.Parameters = parser.Parameters;

            args.SetModel(obj);
        }
Exemplo n.º 3
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            using (var stream = await request.Content.ReadAsStreamAsync())
            {
                var parameters = MultipartFormDataParser.Parse(stream);
                var from       = parameters.Parameters.Where(x => x.Name == "from")
                                 .Select(x => GetSingleMailAddress(x.Data))
                                 .FirstOrDefault();

                var tos = parameters.Parameters.Where(x => x.Name == "to")
                          .Select(x => GetMultipleMailAddress(x.Data));

                var mailGunResponse = new MailGunResponse();

                if (from == _validSenderMailAddress && tos.Any(x => x.Contains(_validRecipientMailAddress)))
                {
                    mailGunResponse.Id      = "<fake-domain.mailgun.org>";
                    mailGunResponse.Message = "Queued. Thank you.";
                }
                else
                {
                    mailGunResponse.Id = string.Empty;
                }

                var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
                httpResponseMessage.Content = new ReadOnlyMemoryContent(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(mailGunResponse)));
                return(httpResponseMessage);
            }
        }
Exemplo n.º 4
0
        public ServiceDetailsModule() : base("/service")
        {
            Get("/", _ => "Hello again, Swagger!", null, "ServiceHome");

            Get("/details", _ => new ServiceDetails()
            {
                Name  = "Nancy Swagger Service",
                Owner = new ServiceOwner()
                {
                    CompanyName         = "Swagger Example Inc.",
                    CompanyContactEmail = "*****@*****.**"
                },
                Customers = new []
                {
                    new ServiceCustomer()
                    {
                        CustomerName = "Jack"
                    },
                    new ServiceCustomer()
                    {
                        CustomerName = "Jill"
                    }
                }
            }, null, "GetDetails");

            Get("/customers", _ => new[]
            {
                new ServiceCustomer()
                {
                    CustomerName = "Jack"
                },
                new ServiceCustomer()
                {
                    CustomerName = "Jill"
                }
            }, null, "GetCustomers");

            Get("/customers/{name}", _ => new ServiceCustomer()
            {
                CustomerName = "Jack"
            }, null, "GetCustomer");

            Post("/customer/{service}", parameters =>
            {
                var result = this.Bind <ServiceCustomer>();
                return(result);
            }, null, "PostNewCustomer");

            Post("/customer/{name}/file", async parameters =>
            {
                var parsed = new MultipartFormDataParser(Request.Body);
                var file   = parsed.Files.FirstOrDefault()?.Data;
                if (file == null)
                {
                    return("File Parsing Failed");
                }
                var reader = new StreamReader(file);
                return(await reader.ReadToEndAsync());
            }, null, "PostCustomerReview");
        }
Exemplo n.º 5
0
 // Make sure the parsed multipart form data has been parsed
 private void GetBodyFiles()
 {
     if (_BodyParser == null)
     {
         _BodyParser = MultipartFormDataParser.Parse(_listenerContext.Request.InputStream);
     }
 }
Exemplo n.º 6
0
        internal HttpResponse UploadWorld(HttpRequest req)
        {
            try
            {
                var header = req.ContentType;
                var parser = new MultipartFormDataParser(new MemoryStream(req.Data), req.GetMultipartBoundary(), Encoding.UTF8);
                var uid    = parser.GetParameterValue("uid");
                var token  = parser.GetParameterValue("token");
                this.characterService.FindAndAuthorize(token, Convert.ToUInt32(uid));

                if (parser.Files.Count() < 1)
                {
                    Log.Error("Client {ip}:{port} failed to provide file for UploadWorld", req.SourceIp, req.SourcePort);
                    return(req.FailureResponse());
                }

                var file = parser.Files[0];
                Log.Information("Uploading world {uid} from client {ip}:{port}", uid, req.SourceIp, req.SourcePort);
                this.storage.SaveWorldData(uid, file.Data);
                Log.Information("Successfully saved world {uid} from client {ip}:{port}", uid, req.SourceIp, req.SourcePort);
                return(new HttpResponse(req, 200, null));
            }
            catch (Exception e)
            {
                Request.HandleException(req, e, false);
                if (e is CharacterService.NotAuthorizedException || e is CharacterService.NotFoundException)
                {
                    return(req.FailureResponse());
                }
                else
                {
                    throw e;
                }
            }
        }
        private bool ValidateParameters(MultipartFormDataParser parser)
        {
            var actualParameters   = parser.Parameters.GroupBy(p => p.Name);
            var expectedParameters = ExpectedParams.GroupBy(p => p.Name);

            // Make sure the number of actual parameters matches the number of expected parameters
            if (actualParameters.Count() != expectedParameters.Count())
            {
                return(false);
            }

            // Validate that each expected value has a corresponding actual value
            return(actualParameters.Zip(expectedParameters, Tuple.Create).All(t =>
            {
                // Make sure the name of the actual parameter matches the name of the expected parameter
                if (t.Item1.Key != t.Item2.Key)
                {
                    return false;
                }

                var actualValues = t.Item1.Select(i => i.Data);
                var expectedValues = t.Item2.Select(i => i.Data);

                // Make sure the number of actual values matches the number of expected values
                if (actualValues.Count() != expectedValues.Count())
                {
                    return false;
                }

                // Validate that each expected value has a corresponding actual value
                return actualValues.Zip(expectedValues, Tuple.Create).All(v => v.Item1 == v.Item2);
            }));
        }
        public Object[] handle(Hashtable httpHeaders, MemoryStream ms)
        {
            ArrayList responseDatas = new ArrayList();

            var parser = new MultipartFormDataParser(ms, Encoding.UTF8);
            // Multi-file access
            int i = 0;

            logger.Debug("Input face images: " + parser.Files.Count);

            foreach (var f in parser.Files)
            {
                HttpRequestDataObj reqObject = JsonConvert.DeserializeObject <HttpRequestDataObj>(parser.Parameters[i].Data);
                logger.Debug("reqHeader.uid: [ " + reqObject.capturedTime + " ]");
                logger.Debug("reqHeader.imageFilename: [ " + parser.Files.ElementAt(i).Name + " ]");
                //string filename = reqObject.imageFilename;
                //CopyStream(f.Data, filename);
                //f.Data.Flush();
                //f.Data.Close();

                // do
                Thread.Sleep(300);

                HttpResponseDataObj resp = new HttpResponseDataObj();
                resp.capturedTime = reqObject.capturedTime;
                resp.message      = @"got " + reqObject.imageFilename;
                responseDatas.Add(resp);
                i++;
            }

            return(responseDatas.ToArray(typeof(Object)) as Object[]);
        }
        private bool ValidateMultipleValuesParameters(MultipartFormDataParser parser)
        {
            // Deal with the parameters that are expected to have more than 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);

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

            return(true);
        }
Exemplo n.º 10
0
        public ImageJSON Upload()
        {
            try
            {
                MultipartFormDataParser parser = new MultipartFormDataParser(HttpContext.Current.Request.InputStream);

                ImageJSON imageJson     = new ImageJSON();
                int       uploadImageId = 0;

                // Single file access:
                FilePart file     = parser.Files.First();
                string   filename = file.FileName;
                if (file != null && file.Data != null)
                {
                    // Save the file to db
                    Application.Services.Abstract.DTO.IImage image = new Application.Services.DTO.Image();
                    image.UserImage           = parser.ReadFully(file.Data);
                    uploadImageId             = _imageService.UploadImage(image);
                    imageJson.UploadedImageId = uploadImageId;
                }
                else
                {
                    throw new WebException("The posted file was not recognised.", WebExceptionStatus.SendFailure);
                }

                return(imageJson);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw ex;
            }
        }
Exemplo n.º 11
0
        public bool UploadImage(WebServer serve, HttpListenerContext context, string name)
        {
            var path = serve.Module <StorageModule>().GetFile(name);

            var    parser   = new MultipartFormDataParser(context.Request.InputStream);
            var    file     = parser.Files.First();
            string filename = file.FileName;
            Stream data     = file.Data;

            var f    = new File(path);
            var dirs = new File(f.Parent);

            if (!dirs.Exists())
            {
                dirs.Mkdirs();
            }

            f.CreateNewFile();
            Log.Debug(WiFiDirectActivity.Tag, "Server: copying files " + f);

            using (var stream = new FileStream(f.ToString(), FileMode.OpenOrCreate))
            {
                data.CopyTo(stream);
            }

            var intent = new Intent();

            intent.SetAction(Intent.ActionView);
            intent.SetDataAndType(Android.Net.Uri.Parse("file://" + path), "image/*");
            _activity.StartActivity(intent);

            return(context.JsonResponse(new { Success = "OK" }));
        }
        private bool ValidateSingleValueParameters(MultipartFormDataParser parser)
        {
            // Deal with the parameters that are expected to have only one value.
            var expectedParametersWithSingleValue = ExpectedParams
                                                    .GroupBy(p => p.Name)
                                                    .Where(g => g.Count() == 1)
                                                    .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)
                {
                    return(false);
                }

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

            return(true);
        }
 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));
     }
 }
 public void CanAutoDetectBoundary()
 {
     using (Stream stream = TestUtil.StringToStream(TinyTestCase.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream);
         Assert.IsTrue(TinyTestCase.Validate(parser));
     }
 }
 public void DoesntInfiniteLoopOnUnclosedInput()
 {
     using (Stream stream = TestUtil.StringToStream(UnclosedBoundary.Request, Encoding.UTF8))
     {
         // We expect this to throw!
         var parser = new MultipartFormDataParser(stream, Encoding.UTF8);
     }
 }
 public void CanHandleFileAsLastSection()
 {
     using (Stream stream = TestUtil.StringToStream(FileIsLastTestCase.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, Encoding.UTF8);
         Assert.IsTrue(FileIsLastTestCase.Validate(parser));
     }
 }
Exemplo n.º 17
0
 public void Parse_empty_form_boundary_omitted()
 {
     using (Stream stream = TestUtil.StringToStream(_testCase.Request, Encoding.UTF8))
     {
         var parser = MultipartFormDataParser.Parse(stream);
         Assert.True(_testCase.Validate(parser));
     }
 }
Exemplo n.º 18
0
 public void Parse_empty_form_boundary_specified()
 {
     using (Stream stream = TestUtil.StringToStream(_testCase.Request, Encoding.UTF8))
     {
         var parser = MultipartFormDataParser.Parse(stream, "----WebKitFormBoundaryb4SfPlH9Bv7c2PKS");
         Assert.True(_testCase.Validate(parser));
     }
 }
Exemplo n.º 19
0
 public void MultipleFilesWithSameNameTest()
 {
     using (Stream stream = TestUtil.StringToStream(_testCase.Request, Encoding.UTF8))
     {
         var parser = MultipartFormDataParser.Parse(stream, "boundry", Encoding.UTF8, 16);
         Assert.True(_testCase.Validate(parser));
     }
 }
 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));
     }
 }
 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));
     }
 }
Exemplo n.º 22
0
 public void MjpegStreamTest()
 {
     using (Stream stream = TestUtil.StringToStream(_testCase.Request, Encoding.UTF8))
     {
         var parser = MultipartFormDataParser.Parse(stream, "MOBOTIX_Fast_Serverpush", Encoding.UTF8, 32);
         Assert.True(_testCase.Validate(parser));
     }
 }
 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 SingleFileTest()
 {
     using (Stream stream = TestUtil.StringToStream(SingleFileTestCase.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, "boundry", Encoding.UTF8, 16);
         Assert.True(SingleFileTestCase.Validate(parser));
     }
 }
Exemplo n.º 25
0
 public void CanHandleFinalDashesInSeperateBufferFromEndBinary()
 {
     using (Stream stream = TestUtil.StringToStream(_testCase.Request, Encoding.UTF8))
     {
         var parser = MultipartFormDataParser.Parse(stream, "boundry", Encoding.UTF8, 16);
         Assert.True(_testCase.Validate(parser));
     }
 }
 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 AcceptSeveralValuesWithSameProperty()
 {
     using (Stream stream = TestUtil.StringToStream(_testCase.Request, Encoding.UTF8))
     {
         var parser = MultipartFormDataParser.Parse(stream, Encoding.UTF8);
         Assert.True(_testCase.Validate(parser));
     }
 }
 public void FileWithAdditionalParameterTest()
 {
     using (Stream stream = TestUtil.StringToStream(_testCase.Request, Encoding.UTF8))
     {
         var parser = MultipartFormDataParser.Parse(stream, Encoding.UTF8);
         Assert.True(_testCase.Validate(parser));
     }
 }
Exemplo n.º 29
0
 public void CanHandleMixedSingleByteAndMultiByteWidthCharacters()
 {
     using (var stream = TestUtil.StringToStream(MixedSingleByteAndMultiByteWidthTestCase.Request, Encoding.UTF8))
     {
         var parser = new MultipartFormDataParser(stream, Encoding.UTF8);
         Assert.IsTrue(MixedSingleByteAndMultiByteWidthTestCase.Validate(parser));
     }
 }
Exemplo n.º 30
0
        /// <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)
        {
            var result = ValidateParameters(parser);

            result &= ValidateFiles(parser);

            return(result);
        }
Exemplo n.º 31
0
        private void HandleLargeBody()
        {
            if (Request.Method != "POST" && Request.Method != "PUT")
                throw new InvalidOperationException ("Large Request bodies are only allowed with PUT or POST operations.");

            string ct = Request.Headers ["Content-Type"];
            if (ct == null || !ct.StartsWith ("multipart/form-data", StringComparison.InvariantCultureIgnoreCase)) {
                // TODO: Maybe someone wants to post large www-form-urlencoded data?
                throw new InvalidOperationException ("Large Request bodies are only allowed with multipart form data.");
            }

            string boundary = ParseBoundary (ct);
            IMFDStream stream = new TempFileMFDStream (IOStream);

            MultipartFormDataParser parser = new MultipartFormDataParser (this.Request, boundary, stream, () => {
                IOStream.DisableReading ();
                Server.RunTransaction (this);
            });

            parser.ParseParts ();
        }
Exemplo n.º 32
0
        private void OnMultiPartFormData(string boundary, byte [] data)
        {
            IMFDStream stream = new InMemoryMFDStream (data);
            MultipartFormDataParser parser = new MultipartFormDataParser (this.Request, boundary, stream, () => {
                IOStream.DisableReading ();
                Server.RunTransaction (this);
            });

            parser.ParseParts ();
        }