public UserProfileValidator(
            IStringLocalizer <UserProfileValidator> localizer,
            ImageValidator imageValidator)
        {
            RuleFor(model => model.FirstName)
            .Cascade(CascadeMode.Stop)
            .NotNull()
            .WithMessage(localizer["MissingFirstName"])
            .NotEmpty()
            .WithMessage(localizer["MissingFirstName"]);

            RuleFor(model => model.LastName)
            .Cascade(CascadeMode.Stop)
            .NotNull()
            .WithMessage(localizer["MissingLastName"])
            .NotEmpty()
            .WithMessage(localizer["MissingLastName"]);

            RuleFor(model => model.Avatar)
            .SetValidator(imageValidator);

            RuleFor(model => model.Avatar)
            .Must(avatar => avatar.LongLength <= Constants.UserProfileInput.AvatarMaxAllowedSizeInBytes)
            .WithMessage(string.Format(localizer["AvatarFileSizeTooLarge"], AvatarMaxAllowedSizeInMb));
        }
Example #2
0
        public void TestValidator()
        {
            ByteWrapper    image1    = ImageConvert.ReturnByteWrapper(@"F:\temp\analysis\640x480\test_0.jpg");
            ImageValidator validator = new ImageValidator();

            try
            {
                List <int> dimensions = ReturnDimensions();
                Stopwatch  sw         = new Stopwatch();
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"f:\temp\runtime\validator_analysis.txt", true))
                {
                    for (int i = 0; i < 10; i++)
                    {
                        sw.Restart();
                        validator.FileCreated(image1, EventArgs.Empty);
                        sw.Stop();
                        file.WriteLine(sw.Elapsed.TotalMilliseconds);
                    }
                }
                Assert.IsTrue(true);
            }
            catch
            {
                Assert.IsTrue(false);
            }
        }
Example #3
0
        public DialogResult ShowDialog()
        {
            DialogResult dialogResult = ImageOpenDialogStarter.Execute(ofdImage);

            if (dialogResult == DialogResult.OK)
            {
                if (ImageValidator.GetInstance().IsValidImage(ofdImage.FileName))
                {
                    PictureAsBytes = ImageLoader.GetByteFromFile(ofdImage.FileName);

                    if (ImageSizeChecker.MaxSizeExceeded(PictureAsBytes))
                    {
                        ShowInfo();
                        dialogResult = StartImageViewer(dialogResult);
                    }
                }
                else
                {
                    MessageBox.ShowInfo(Windows.Core.Localization.ImageMessages.UnkownImageFileFormatMsg,
                                        Windows.Core.Localization.ImageMessages.UnkownImageFileFormat);
                    dialogResult = DialogResult.Cancel;
                }
            }
            return(dialogResult);
        }
Example #4
0
 private static void ValidateMemberImage(string mimeType, byte[] data)
 {
     if (!ImageValidator.IsValidMimeType(mimeType) || !ImageValidator.IsValidData(data))
     {
         throw new OdkServiceException("File is not a valid image");
     }
 }
Example #5
0
        public HttpResponseMessage PostProfileImage(string sessionKey)
        {
            HttpResponseMessage result = null;
            var httpRequest            = HttpContext.Current.Request;

            if (httpRequest.Files.Count > 0)
            {
                string imageUrl = string.Empty;

                var postedFile = httpRequest.Files[0];

                if (!ImageValidator.CheckImageFormat(postedFile.FileName))
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest));
                }

                imageUrl = DropboxUploader.DropboxShareFile(postedFile.InputStream, postedFile.FileName);

                imageUrl = imageUrl.Substring(0, imageUrl.Length - 5);

                this.repository.UpdateImageUrl(sessionKey, imageUrl);

                result = Request.CreateResponse(HttpStatusCode.OK);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            return(result);
        }
Example #6
0
 public PostImageService(
     IDefaultDbContext context,
     ImageValidator entityValidator,
     PostImageSpecificationsValidator domainValidator
     ) : base(entityValidator, domainValidator)
 {
     Context = context;
 }
Example #7
0
        public void ImageExtensionValidation_ShouldReturnTrue()
        {
            // Arrange
            var imageExtension = ".png";
            // Act
            var result = ImageValidator.ImageExtensionValidation(imageExtension);

            // Assert
            Assert.True(result);
        }
Example #8
0
        public void ImageSizeValidation_ShouldReturnTrue()
        {
            // Arrange
            var imageSize = 1;
            // Act
            var result = ImageValidator.ImageSizeValidation(imageSize);

            // Assert
            Assert.True(result);
        }
Example #9
0
        /// <summary>
        /// Runs a number of single extractions from the IP camera
        /// Times the change to Bitmap and count of the pixels for
        /// These images
        /// </summary>
        public void RunBenchmarking(string logfile)
        {
            //extract the images
            List <String> saveLocations = new List <string>();
            string        url           = "http://192.168.0.2/axis-cgi/mjpg/video.cgi?resolution=";

            List <String[]> resolutions = ReturnResolutions();

            for (int i = 0; i < resolutions.Count; i++)
            {
                string actualurl = url + resolutions[i][0] + "x" + resolutions[i][1];

                //set up the extractor
                ImageExtractor imageExtractor = new ImageExtractor(actualurl, "root", "root");

                //set up the save file object
                ImageSaver imageSaver = new ImageSaver(0, 1);
                saveLocations.Add(imageSaver.CaptureDirectory);

                //create the validator
                ImageValidator imageValidator = new ImageValidator();
                imageValidator.ListenForImages(imageExtractor);
                imageValidator.imageValidated += new ImageValidator.ImageValidatedEvent(imageSaver.ImageCreatedAsync);//subscribe to events from the validator

                imageExtractor.Run(true);

                System.Threading.Thread.Sleep(5000); //wait 5 seconds to let the async requests complete
            }

            //do the analysis
            for (int i = 0; i < saveLocations.Count; i++)
            {
                string header = resolutions[i][0] + "x" + resolutions[i][1];
                Console.WriteLine(Environment.NewLine + resolutions[i][0] + "x" + resolutions[i][1]);
                JPEG jpeg = new JPEG(saveLocations[i] + @"\1\test_0.jpg");

                string msToBitmap             = MsToBitmap(jpeg).ToString();
                string msToBitmapAndSumPixels = MsToBitmapAndSumPixels(jpeg).ToString();
                string totalPixels            = TotalPixels(jpeg).ToString();

                Console.WriteLine(msToBitmap);
                Console.WriteLine(msToBitmapAndSumPixels);
                Console.WriteLine(totalPixels);

                using (System.IO.StreamWriter file = new System.IO.StreamWriter(logfile, true))
                {
                    file.WriteLine(header);
                    file.WriteLine(msToBitmap);
                    file.WriteLine(msToBitmapAndSumPixels);
                    file.WriteLine(totalPixels);
                    file.WriteLine("------------------------------");
                }
            }
        }//RunBenchmarking
Example #10
0
 public bool ValidateMultupleFiles(IEnumerable <IFormFile> files)
 {
     foreach (var file in files)
     {
         if (ImageValidator.CheckIfFileIsBigger(file) ||
             ImageValidator.CheckIfFileIsForbidden(file))
         {
             return(false);
         }
     }
     return(true);
 }
Example #11
0
        public void Dispose()
        {
            if (!isDisposed)
            {
                if (_ImageValidator != null)
                {
                    _ImageValidator.Dispose();
                    _ImageValidator = null;
                }

                isDisposed = !isDisposed;
            }
        }
        /// <summary>
        /// called once the Setups are complete
        /// </summary>
        private void Go()
        {
            //create the motion sensor, and listen for images
            MotionSensor_2a motionSensor = new MotionSensor_2a();

            motionSensor.settings = settings == null ? motionSensor.settings = new MotionSensorSettings() : motionSensor.settings = settings;

            motionSensor.motionDetected   += new MotionSensor_2.MotionDetected(MotionDetected); //set up the motion detector hook
            motionSensor.logging.LoggingOn = true;

            //create the validator
            ImageValidator imageValidator = new ImageValidator();

            imageValidator.ListenForImages(imageExtractor);

            imageExtractor.asyncrohous = settings.asynchronous;

            if (settings.asynchronous)
            {
                imageValidator.imageValidated += new ImageValidator.ImageValidatedEvent(motionSensor.ImageCreatedAsync); //subscribe to events from the validator
            }
            else
            {
                imageValidator.imageValidated += new ImageValidator.ImageValidatedEvent(motionSensor.ImageCreated); //subscribe to events from the validator
            }

            if (timedTest)
            {
                testTimer = new Stopwatch(); testTimer.Start();
            }

            imageExtractor.Run();

            //if here and async then the motion detector is likely still going
            //wait for i to finish and record the lag
            if (settings.asynchronous && timedTest)
            {
                imageExtractionEnd = DateTime.Now;
                while (motionSensor.logging.imagesReceived + 3 < expectedFrames)
                {
                    System.Threading.Thread.Sleep(250);
                }

                testTimer.Stop();
            }
            else
            {
                testTimer.Stop();
            }
        }
Example #13
0
        public async Task ImageMustHaveValidBinData()
        {
            //arrange
            var manager   = GetTestShopManager();
            var validator = new ImageValidator();

            var image = new Image {
                ProductId = 1, BinData = new ImageBinData()
            };

            //act
            var result = await validator.ValidateAsync(manager, image);

            Assert.True(!result.Succeeded &&
                        result.Errors.Any(x => x.Code == nameof(OperationErrorDescriber.InvalidImageFormat)));
        }
Example #14
0
        /// <summary>
        /// Byte-Array aus Datei lesen
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static byte[] GetByteFromFile(string fileName)
        {
            byte[] result = null;

            if (File.Exists(fileName))
            {
                result = File.ReadAllBytes(fileName);

                if (!ImageValidator.GetInstance().IsValidImage(result))
                {
                    result = null;
                }
            }

            return(result);
        }
Example #15
0
        /// <summary>
        /// Rule implementation.
        /// </summary>
        /// <param name="context">Rule context.</param>
        protected override void Execute(RuleContext context)
        {
            var target = (IImage)context.Target;

            if (target.Img != null)
            {
                if (!ImageValidator.GetInstance().IsValidImage(target.Img))
                {
                    string message = Localization.ImageRules.UnkownImageFormat;
                    context.Results.Add(new RuleResult(RuleName, PrimaryProperty, message)
                    {
                        Severity = Severity
                    });
                }
            }
        }
        public IActionResult Edit(MainSliderContent model, IFormFile titleImageFile)
        {
            if (ModelState.IsValid)
            {
                var tupleExtImg = ImageValidator.ValidateImg(titleImageFile);

                if (tupleExtImg != default)
                {
                    model.Extension = tupleExtImg.Item1;
                    model.Image     = tupleExtImg.Item2;
                }

                dataManager.MainSliderContent.SaveMainSliderContent(model);
                return(RedirectToAction(nameof(MainSliderContentController.EditMainSliderContent), nameof(MainSliderContentController).CutController()));
            }
            return(View(model));
        }
Example #17
0
        public IActionResult Edit(Category model, IFormFile titleImageFile)
        {
            if (ModelState.IsValid)
            {
                var tupleExtImg = ImageValidator.ValidateImg(titleImageFile);

                if (tupleExtImg != default)
                {
                    model.Extension = tupleExtImg.Item1;
                    model.Image     = tupleExtImg.Item2;
                }

                dataManager.Category.SaveCategory(model);
                return(RedirectToAction(nameof(CategoriesOfTheMonthController.Edit), nameof(CategoriesOfTheMonthController).CutController()));
            }
            return(View(model));
        }
Example #18
0
        public static DialogResult Execute(OpenFileDialog ofdImage)
        {
            var settingsProvider = Provider.Get();
            var section          = settingsProvider.LoadSection("BasicWindowSettings");

            ofdImage.InitialDirectory = section.GetSetting("ImageLoadPath", @"u:\").Value;

            ImageValidator imageValidator = ImageValidator.GetInstance();

            ofdImage.Filter      = imageValidator.GetSupportedImagesFilter();
            ofdImage.FilterIndex = 1;

            DialogResult dialogResult = ofdImage.ShowDialog();

            SaveImageLoadPath(ofdImage);

            return(dialogResult);
        }
Example #19
0
        private DeleteImageService GetMockedDeleteImageService()
        {
            var mockedDbContext = MockDefaultHelper
                                  .GetMockedDbContext()
                                  .AddMockedImages();

            var mockedImageValidator = new ImageValidator();

            var mockedDeleteImageSpecificationsValidator = new DeleteImageSpecificationsValidator();

            var mockedDeleteImageService = new DeleteImageService(
                mockedDbContext.Object,
                mockedImageValidator,
                mockedDeleteImageSpecificationsValidator
                );

            return(mockedDeleteImageService);
        }
        public void Run(string captureKey)
        {
            //set up the extractor
            string uri = "http://localhost:9000/api/jpeg/0/" + captureKey;

            ImageExtractor imageExtractor = new ImageExtractor(uri, "root", "root");

            //create the motion sensor, and listen for images
            MotionSensor_2b motionSensor = new MotionSensor_2b();

            motionSensor.motionDetected += new MotionSensor_2.MotionDetected(MotionDetected);

            //create the validator
            ImageValidator imageValidator = new ImageValidator();

            imageValidator.ListenForImages(imageExtractor);
            imageValidator.imageValidated += new ImageValidator.ImageValidatedEvent(motionSensor.ImageCreatedAsync);//subscribe to events from the validator

            imageExtractor.Run();
        }
        public void Run(string captureKey)
        {
            //set up the extractor
            string uri = "http://*****:*****@"F:\temp\MotionSensor\2.1\movement\info.txt";
            motionSensor.motionDetected += new MotionSensor_2.MotionDetected(MotionDetected);

            //create the validator 
            ImageValidator imageValidator = new ImageValidator();
            imageValidator.ListenForImages(imageExtractor);
            imageValidator.imageValidated += new ImageValidator.ImageValidatedEvent(motionSensor.ImageCreatedAsync);//subscribe to events from the validator

            imageExtractor.Run();

        }
Example #22
0
        public async Task PassValidImage()
        {
            //arrange
            var manager   = GetTestShopManager();
            var validator = new ImageValidator();

            var imageBytes = TestFactory.GenerateValidImageBytes(1001, 1001, ImageFormat.Png);
            var image      = new Image()
            {
                ProductId = 322,
                BinData   = new ImageBinData()
                {
                    FullData = imageBytes
                }
            };

            //act
            var result = await validator.ValidateAsync(manager, image);

            Assert.True(result.Succeeded);
        }
Example #23
0
        public async Task <MediaFile> SaveMediaFile(Guid currentMemberId, Guid chapterId, string name, byte[] data)
        {
            await AssertMemberIsChapterAdmin(currentMemberId, chapterId);

            if (!ImageValidator.IsValidData(data))
            {
                throw new OdkServiceException("File must be an image");
            }

            string filePath = await _mediaFileProvider.GetMediaFilePath(chapterId, name);

            int version = 1;

            while (File.Exists(filePath))
            {
                FileInfo file = new FileInfo(filePath);
                string   versionedFileName = $"{file.Name.Substring(0, file.Name.Length - file.Extension.Length)}{++version}{file.Extension}";
                filePath = Path.Combine(file.Directory.FullName, versionedFileName);
            }

            await File.WriteAllBytesAsync(filePath, data);

            return(await _mediaFileProvider.GetMediaFile(chapterId, new FileInfo(filePath).Name));
        }
Example #24
0
        public async Task <PhotoToReturnDto> UploadPhoto(int userId, PhotoForCreationDto photoForCreationDto)
        {
            var image = photoForCreationDto.File;

            if (ImageValidator.ImageExtensionValidation(image.FileName) &&
                ImageValidator.ImageSizeValidation(image.Length) &&
                ImageValidator.ImageSignatureValidation(image))
            {
                using (var memoryStream = new MemoryStream())
                {
                    await photoForCreationDto.File.CopyToAsync(memoryStream);

                    var photo = _mapper.Map <Photo>(photoForCreationDto);

                    photo.Image  = memoryStream.ToArray();
                    photo.UserId = userId;

                    // Check if photo that is going to be uploaded is main profile photo
                    // If it is, we have to find current main photo, and change it to not be main
                    var currentMainPhoto = await _unitOfWork.Photos.GetMainPhotoForUser(userId);

                    if (photo.IsMain && currentMainPhoto != null)
                    {
                        currentMainPhoto.IsMain = false;
                    }
                    _unitOfWork.Photos.Add(photo);

                    if (await _unitOfWork.Complete())
                    {
                        return(_mapper.Map <PhotoToReturnDto>(photo));
                    }
                }
            }

            return(null);
        }
        public ActionResult Upload(PictureViewModel model, HttpPostedFileBase image)
        {
            if (ModelState.IsValid)
            {
                using (var db = new GalleryDbContext())
                {
                    // Get uploader's ID
                    var uploaderId = db.Users
                                     .First(u => u.UserName == User.Identity.Name)
                                     .Id;

                    var picture = new Picture(uploaderId, model.PicTitle, model.PicDescription, model.CategoryId);

                    // Getting the name of the category to add it to the current picture's property:
                    var picCategoryName = db.Categories
                                          .Where(c => c.Id == picture.CategoryId)
                                          .Select(c => c.Name)
                                          .ToArray();

                    picture.CategoryName = picCategoryName[0];

                    SetPictureTags(picture, model, db);

                    if (image != null && image.ContentLength > 0)
                    {
                        var imagesOfThatCategoryDir = $"~/Content/images/astroPics/{picture.CategoryName}/";
                        var picFileName             = image.FileName;
                        var uploadPath   = imagesOfThatCategoryDir + picFileName;
                        var physicalPath = Server.MapPath(uploadPath);

                        // In case the picture already exists a notification is shown:
                        if (System.IO.File.Exists(physicalPath))
                        {
                            this.AddNotification("Picture with this file name already exists in that category.", NotificationType.ERROR);

                            model.Categories = db.Categories
                                               .OrderBy(c => c.Name)
                                               .ToList();

                            return(View(model));
                        }

                        image.SaveAs(physicalPath);

                        if (ImageValidator.IsImageValid(physicalPath))
                        {
                            picture.ImagePath = uploadPath;

                            AdjustCategoryPositions.Upload(db, picture);

                            return(RedirectToAction("Details", new { id = picture.Id }));
                        }
                        else
                        {
                            // Deleting the file from ~/Content/images/astroPics/:
                            System.IO.File.Delete(physicalPath);

                            this.AddNotification("Invalid picture format.", NotificationType.ERROR);

                            model.Categories = db.Categories
                                               .OrderBy(c => c.Name)
                                               .ToList();

                            return(View(model));
                        }
                    }
                    else
                    {
                        this.AddNotification("No picture selected for upload or empty file chosen.", NotificationType.ERROR);

                        model.Categories = db.Categories
                                           .OrderBy(c => c.Name)
                                           .ToList();

                        return(View(model));
                    }
                }
            }

            using (var db = new GalleryDbContext())
            {
                model.Categories = db.Categories
                                   .OrderBy(c => c.Name)
                                   .ToList();

                return(View(model));
            }
        }
Example #26
0
 public FileUploadImp() : base()
 {
     _ImageValidator = new ImageValidator();
 }
Example #27
0
        public async Task <IActionResult> Save()
        {
            string  targetFilePath = null;
            BookDTO dto            = null;

            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Requisição precisa ser 'multipart'."));
            }

            var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), MaxBoundaryLengthLimit);
            var reader   = new MultipartReader(boundary, HttpContext.Request.Body);
            var section  = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                ContentDispositionHeaderValue contentDisposition;
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);
                var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        if (key.ToString() == "file")
                        {
                            var imageValidator        = new ImageValidator();
                            var fileName              = HeaderUtilities.RemoveQuotes(contentDisposition.FileName).ToString();
                            var imageValidationResult = imageValidator.Validate(fileName);

                            if (imageValidationResult.HasError)
                            {
                                return(BadRequest(imageValidationResult.ErrorMessage));
                            }

                            targetFilePath = Path.GetTempFileName();
                            using (var targetStream = System.IO.File.Create(targetFilePath))
                            {
                                await section.Body.CopyToAsync(targetStream);
                            }
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        if (key.ToString() == "value")
                        {
                            using (var streamReader = new StreamReader(section.Body))
                            {
                                var json = await streamReader.ReadToEndAsync();

                                dto = JsonConvert.DeserializeObject <BookDTO>(json);
                            }
                        }
                    }
                }
                section = await reader.ReadNextSectionAsync();
            }
            var validationContext = new ValidationContext(bookFacade, authorService, publisherService);
            var bookValidator     = new BookValidator(validationContext);
            var validationResult  = bookValidator.Validate(dto);

            if (validationResult.HasError)
            {
                return(BadRequest(validationResult.ErrorMessage));
            }

            var bookFound = await bookFacade.FindById(dto.Id);

            if (bookFound == null && dto.Id != 0)
            {
                return(NotFound($"Nenhum livro encontrado com o ID: {dto.Id}."));
            }

            try
            {
                var book = dto.FromBookViewItem(new DefaultValidationResultDataLookUp(validationResult));

                book = await bookFacade.Save(book, targetFilePath);

                return(Ok(await book.ToBookViewItem(serviceDataLookUp)));
            }
            catch (BookSaveException ex)
            {
                try
                {
                    System.IO.File.Delete(targetFilePath);
                }
                catch
                {
                    //Ignore
                }
                return(BadRequest(ex.Message));
            }
            catch (ImageSaveException ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Example #28
0
        public async Task <KeyValuePair <bool, string> > CreateGroup(int userId, GroupForCreationDto group)
        {
            // Groups and User relationship is based on Membership so
            // when we add group we need to add new Membership with desired user
            var user = await _unitOfWork.Users.GetById(userId);

            if (user == null)
            {
                return(new KeyValuePair <bool, string>(false, "User doesn't exist!"));
            }

            if (!(user is PowerUser))
            {
                return(new KeyValuePair <bool, string>(false, "Unauthorized"));
            }

            PowerUser powerUser  = (PowerUser)user;
            var       groupToAdd = _mapper.Map <Group>(group);

            if (group.Image != null)
            {
                if (ImageValidator.ImageExtensionValidation(group.Image.FileName) &&
                    ImageValidator.ImageSizeValidation(group.Image.Length) &&
                    ImageValidator.ImageSignatureValidation(group.Image))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        await group.Image.CopyToAsync(memoryStream);

                        groupToAdd.Image = memoryStream.ToArray();
                    }
                }
                else
                {
                    return(new KeyValuePair <bool, string>(false, "Image cannot be uploaded"));
                }
            }

            // We check if selected location exists
            // If it doesn't we create a new one with specified country and city
            var location = await _unitOfWork.Locations.GetByName(groupToAdd.Name);

            if (location == null)
            {
                location = new Location {
                    Name = group.Location, CityId = group.CityId, CountryId = group.CountryId
                };
                _unitOfWork.Locations.Add(location);
            }

            groupToAdd.CreatedBy = powerUser;
            groupToAdd.Location  = location;

            powerUser.NumberOfGroupsCreated += 1;
            _unitOfWork.Groups.Add(groupToAdd);

            if (!await _unitOfWork.Complete())
            {
                return(new KeyValuePair <bool, string>(false, "Couldn't create group"));
            }

            var membership = new Membership {
                UserId = powerUser.Id, GroupId = groupToAdd.Id, DateSent = DateTime.Now, Role = Role.Owner, Accepted = true, DateAccepted = DateTime.Now, User = powerUser, Group = groupToAdd, MembershipStatus = MembershipStatus.Accepted
            };

            _unitOfWork.Memberships.Add(membership);

            if (await _unitOfWork.Complete())
            {
                return(new KeyValuePair <bool, string>(true, "Group created successfully!"));
            }

            return(new KeyValuePair <bool, string>(false, "Something went wrong!"));
        }
Example #29
0
        private async Task <(MemberDto, ImageDto?)> UploadUserImageMultipartContent(Guid targetUserId, Stream requestBody, byte[] rowVersion, string?contentType, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var now = _systemClock.UtcNow.UtcDateTime;

            var defaultFormOptions = new FormOptions();
            // Create a Collection of KeyValue Pairs.
            var formAccumulator = new KeyValueAccumulator();
            // Determine the Multipart Boundary.
            var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(contentType), defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader   = new MultipartReader(boundary, requestBody);
            var section  = await reader.ReadNextSectionAsync(cancellationToken);

            ImageDto? imageDto = null;
            MemberDto userDto  = new MemberDto();

            // Loop through each 'Section', starting with the current 'Section'.
            while (section != null)
            {
                // Check if the current 'Section' has a ContentDispositionHeader.
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        if (contentDisposition != null)
                        {
                            var sectionFileName = contentDisposition.FileName.Value;
                            // use an encoded filename in case there is anything weird
                            var encodedFileName = WebUtility.HtmlEncode(Path.GetFileName(sectionFileName));

                            // read the section filename to get the content type
                            var fileExtension = Path.GetExtension(sectionFileName);

                            // now make it unique
                            var uniqueFileName = $"{Guid.NewGuid()}{fileExtension}";

                            if (!_acceptedFileTypes.Contains(fileExtension.ToLower()))
                            {
                                _logger.LogError("file extension:{0} is not an accepted image file", fileExtension);
                                throw new ValidationException("Image", "The image is not in an accepted format");
                            }

                            var compressedImage = _imageService.TransformImageForAvatar(section.Body);

                            try
                            {
                                await _blobStorageProvider.UploadFileAsync(compressedImage.Image, uniqueFileName,
                                                                           MimeTypesMap.GetMimeType(encodedFileName), cancellationToken);
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError(ex, "An error occurred uploading file to blob storage");
                                throw;
                            }

                            // trick to get the size without reading the stream in memory
                            var size = section.Body.Position;

                            imageDto = new ImageDto
                            {
                                FileSizeBytes = size,
                                FileName      = uniqueFileName,
                                Height        = compressedImage.Height,
                                Width         = compressedImage.Width,
                                IsDeleted     = false,
                                MediaType     = compressedImage.MediaType,
                                CreatedBy     = targetUserId,
                                CreatedAtUtc  = now
                            };

                            var imageValidator        = new ImageValidator(MaxFileSizeBytes);
                            var imageValidationResult = await imageValidator.ValidateAsync(imageDto, cancellationToken);

                            if (imageValidationResult.Errors.Count > 0)
                            {
                                await _blobStorageProvider.DeleteFileAsync(uniqueFileName);

                                _logger.LogError("File size:{0} is greater than the max allowed size:{1}", size, MaxFileSizeBytes);
                                throw new ValidationException(imageValidationResult);
                            }
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // if for some reason other form data is sent it would get processed here
                        var key = HeaderUtilities.RemoveQuotes(contentDisposition?.Name.ToString().ToLowerInvariant());

                        var encoding = GetEncoding(section);
                        using (var streamReader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
                        {
                            var value = await streamReader.ReadToEndAsync();

                            if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = string.Empty;
                            }
                            formAccumulator.Append(key.Value, value);
                            if (formAccumulator.ValueCount > defaultFormOptions.ValueCountLimit)
                            {
                                _logger.LogError("UserEdit: Form key count limit {0} exceeded.", defaultFormOptions.ValueCountLimit);
                                throw new FormatException($"Form key count limit { defaultFormOptions.ValueCountLimit } exceeded.");
                            }
                        }
                    }
                }
                // Begin reading the next 'Section' inside the 'Body' of the Request.
                section = await reader.ReadNextSectionAsync(cancellationToken);
            }

            if (formAccumulator.HasValues)
            {
                var formValues = formAccumulator.GetResults();

                // Check if users been updated
                // Unable to place in controller due to disabling form value model binding
                var user = await _userCommand.GetMemberAsync(targetUserId, cancellationToken);

                if (!user.RowVersion.SequenceEqual(rowVersion))
                {
                    _logger.LogError($"Precondition Failed: UpdateUserAsync - User:{0} has changed prior to submission", targetUserId);
                    throw new PreconditionFailedExeption("Precondition Failed: User has changed prior to submission");
                }

                var firstNameFound = formValues.TryGetValue("firstName", out var firstName);
                if (firstNameFound is false || string.IsNullOrEmpty(firstName))
                {
                    throw new ArgumentNullException($"First name was not provided");
                }
                formValues.TryGetValue("lastName", out var surname);

                var pronoundsFound = formValues.TryGetValue("pronouns", out var pronouns);
                if (pronoundsFound is false)
                {
                    throw new ArgumentNullException($"Pronouns were not provided");
                }

                formValues.TryGetValue("imageid", out var image);

                var imageId = Guid.TryParse(image, out var imageGuid) ? (Guid?)imageGuid : null;
                if (imageId.HasValue)
                {
                    if (imageId == new Guid())
                    {
                        throw new ArgumentOutOfRangeException($"Incorrect Id provided");
                    }
                }

                userDto = new MemberDto
                {
                    Id            = targetUserId,
                    FirstName     = firstName,
                    Surname       = surname,
                    Pronouns      = pronouns,
                    ImageId       = imageId,
                    ModifiedAtUTC = now,
                    ModifiedBy    = targetUserId,
                };
            }

            return(userDto, imageDto);
        }
Example #30
0
        public ActionResult Edit(EditViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var postedProfilePic = Request.Files["image"];

            var pic          = Path.GetFileName(postedProfilePic.FileName);
            var hasNewImage  = false;
            var userIdFolder = model.Id;

            // If a picture is selected AND the remove picture option is not selected:
            if (!string.IsNullOrEmpty(pic) && !model.RemovePicture)
            {
                var userDirectory = Server.MapPath($"~/Content/images/profilePics/{userIdFolder}");

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

                var path = Path.Combine(Server.MapPath($"~/Content/images/profilePics/{userIdFolder}/"), pic);
                postedProfilePic.SaveAs(path);

                if (ImageValidator.IsImageValid(path))
                {
                    hasNewImage = true;
                }
                else
                {
                    // Deleting the file from ~/Content/images/profilePics:
                    System.IO.File.Delete(path);

                    // If the person does not have a previous profile picture his/her whole folder is deleted
                    if (!Directory.EnumerateFiles(Server.MapPath($"~/Content/images/profilePics/{userIdFolder}")).Any())
                    {
                        Directory.Delete(Server.MapPath($"~/Content/images/profilePics/{userIdFolder}"), true);
                    }

                    this.AddNotification("Invalid picture format.", NotificationType.ERROR);
                    return(View(model));
                }
            }

            var id = User.Identity.GetUserId();

            using (var db = new GalleryDbContext())
            {
                var user = db.Users.FirstOrDefault(u => u.Id == id);

                if (user == null)
                {
                    this.AddNotification("Such a user doesn't exist.", NotificationType.ERROR);
                    return(RedirectToAction("Index", "Home"));
                }

                user.FirstName   = model.FirstName;
                user.LastName    = model.LastName;
                user.PhoneNumber = model.PhoneNumber;
                user.Gender      = model.Gender;
                user.City        = model.City;
                user.Country     = model.Country;

                if (string.IsNullOrEmpty(model.Birthday))
                {
                    user.Birthday = string.Empty;
                }
                else
                {
                    user.Birthday = user.Birthday;
                }

                if (model.RemoveBirthday)
                {
                    user.Birthday = string.Empty;
                }
                else
                {
                    user.Birthday = model.Birthday;
                }

                if (model.RemovePicture)
                {
                    // Delete the user's directory and the pic in there from ~/Content/images/profilePics:
                    Directory.Delete(Server.MapPath($"~/Content/images/profilePics/{userIdFolder}"), true);

                    hasNewImage    = false;
                    user.ImagePath = null;
                }

                if (hasNewImage)
                {
                    // Deleting the previous image from ~/Content/images/profilePics:
                    if (user.ImagePath != null)
                    {
                        var previousPicPath = Server.MapPath(user.ImagePath);
                        System.IO.File.Delete(previousPicPath);
                    }

                    user.ImagePath = $"~/Content/images/profilePics/{userIdFolder}/" + pic;
                }

                if (model.IsEmailPublic)
                {
                    user.IsEmailPublic = true;
                }
                else
                {
                    user.IsEmailPublic = false;
                }

                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
            }

            this.AddNotification("Profile edited.", NotificationType.SUCCESS);
            return(RedirectToAction("MyProfile", "Account"));
        }
Example #31
0
        /// based on microsoft example https://github.com/dotnet/AspNetCore.Docs/tree/main/aspnetcore/mvc/models/file-uploads/samples/
        /// and large file streaming example https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-5.0#upload-large-files-with-streaming
        private async Task <(GroupDto, ImageDto?)> UploadGroupImageMultipartContent(GroupData groupData, Guid userId, string slug, Stream requestBody, byte[] rowVersion, string?contentType, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            // Check if HttpRequest (Form Data) is a Multipart Content Type
            if (!MultipartRequestHelper.IsMultipartContentType(contentType))
            {
                throw new InvalidDataException($"Expected a multipart request, but got {contentType}");
            }

            var now = _systemClock.UtcNow.UtcDateTime;

            var defaultFormOptions = new FormOptions();
            // Create a Collection of KeyValue Pairs.
            var formAccumulator = new KeyValueAccumulator();
            // Determine the Multipart Boundary.
            var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(contentType), defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader   = new MultipartReader(boundary, requestBody);
            var section  = await reader.ReadNextSectionAsync(cancellationToken);

            ImageDto?imageDto = null;
            GroupDto groupDto = new GroupDto();

            // Loop through each 'Section', starting with the current 'Section'.
            while (section != null)
            {
                // Check if the current 'Section' has a ContentDispositionHeader.
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        if (contentDisposition != null)
                        {
                            var sectionFileName = contentDisposition.FileName.Value;
                            // use an encoded filename in case there is anything weird
                            var encodedFileName = WebUtility.HtmlEncode(Path.GetFileName(sectionFileName));

                            // read the section filename to get the content type
                            var fileExtension = Path.GetExtension(sectionFileName);

                            // now make it unique
                            var uniqueFileName = $"{Guid.NewGuid()}{fileExtension}";

                            if (!_acceptedFileTypes.Contains(fileExtension.ToLower()))
                            {
                                _logger.LogError("file extension:{0} is not an accepted image file", fileExtension);
                                throw new ValidationException("Image", "The image is not in an accepted format");
                            }

                            var compressedImage = _imageService.TransformImageForGroupHeader(section.Body);

                            try
                            {
                                await _blobStorageProvider.UploadFileAsync(compressedImage.Image, uniqueFileName,
                                                                           MimeTypesMap.GetMimeType(encodedFileName), cancellationToken);
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError(ex, "An error occurred uploading file to blob storage");
                                throw;
                            }

                            // trick to get the size without reading the stream in memory
                            var size = section.Body.Position;

                            // TODO MimeDetective does not work when stream has already been uploaded - figure out a solution
                            //if (fileContentTypeMatchesExtension is false)
                            //{
                            //    await _blobStorageProvider.DeleteFileAsync(uniqueFileName);
                            //    _logger.LogError("File extension:{0} does not match the file signature", fileExtension);
                            //    throw new FormatException("File extension} does not match the file signature");
                            //}

                            imageDto = new ImageDto
                            {
                                FileSizeBytes = size,
                                FileName      = uniqueFileName,
                                Height        = compressedImage.Height,
                                Width         = compressedImage.Width,
                                IsDeleted     = false,
                                MediaType     = compressedImage.MediaType,
                                CreatedBy     = userId,
                                CreatedAtUtc  = now
                            };

                            var imageValidator        = new ImageValidator(MaxFileSizeBytes);
                            var imageValidationResult = await imageValidator.ValidateAsync(imageDto, cancellationToken);

                            if (imageValidationResult.Errors.Count > 0)
                            {
                                await _blobStorageProvider.DeleteFileAsync(uniqueFileName);

                                _logger.LogError("File size:{0} is greater than the max allowed size:{1}", size, MaxFileSizeBytes);
                                throw new ValidationException(imageValidationResult);
                            }
                        }
                    }
                    else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
                    {
                        // if for some reason other form data is sent it would get processed here
                        var key = HeaderUtilities.RemoveQuotes(contentDisposition?.Name.ToString().ToLowerInvariant());

                        var encoding = GetEncoding(section);
                        using (var streamReader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
                        {
                            var value = await streamReader.ReadToEndAsync();

                            if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                            {
                                value = string.Empty;
                            }
                            formAccumulator.Append(key.Value, value);
                            if (formAccumulator.ValueCount > defaultFormOptions.ValueCountLimit)
                            {
                                _logger.LogError("GroupEdit: Form key count limit {0} exceeded.", defaultFormOptions.ValueCountLimit);
                                throw new FormatException($"Form key count limit { defaultFormOptions.ValueCountLimit } exceeded.");
                            }
                        }
                    }
                }
                // Begin reading the next 'Section' inside the 'Body' of the Request.
                section = await reader.ReadNextSectionAsync(cancellationToken);
            }

            if (formAccumulator.HasValues)
            {
                var formValues = formAccumulator.GetResults();

                // Get values from multipart form
                var nameFound = formValues.TryGetValue("name", out var name);
                if (nameFound is false)
                {
                    throw new ValidationException("Name", "Name was not provided");
                }
                var straplineFound = formValues.TryGetValue("strapline", out var strapline);
                if (straplineFound is false)
                {
                    throw new ValidationException("Strapline", "Strapline was not provided");
                }

                formValues.TryGetValue("themeid", out var theme);
                if (Guid.TryParse(theme, out var themeId) is false || themeId == new Guid())
                {
                    throw new ValidationException(nameof(GroupDto.ThemeId), "Theme was not provided");
                }

                formValues.TryGetValue("imageid", out var image);
                var imageId = Guid.TryParse(image, out var imageGuid) ? (Guid?)imageGuid : null;
                if (imageId.HasValue)
                {
                    if (imageId == new Guid())
                    {
                        throw new ArgumentOutOfRangeException($"Incorrect Id provided");
                    }
                }

                formValues.TryGetValue("isPublic", out var publicGroup);
                var isPublic = bool.TryParse(publicGroup, out var isPublicBool) ? isPublicBool : false;
                if (!groupData.IsPublic)
                {
                    if (isPublic != groupData.IsPublic)
                    {
                        throw new ValidationException("isPublic", "Cannot make a private group public");
                    }
                }

                groupDto = new GroupDto
                {
                    Slug          = slug,
                    Name          = _htmlSanitizer.Sanitize(name),
                    Strapline     = _htmlSanitizer.Sanitize(strapline),
                    ThemeId       = themeId,
                    ImageId       = imageId,
                    ModifiedBy    = userId,
                    ModifiedAtUtc = now,
                    IsPublic      = isPublic,
                    RowVersion    = rowVersion
                };
            }
            return(groupDto, imageDto);
        }