public FormResult PostUpload(string id, string context, string name, string contentType, byte[] content)
        {
            try
            {
                // Check permissions
                _authorizationService.AuthorizeUserForFunction(Functions.UpdatePageElements);

                // Get page and element identifiers
                string[] parts = context.Split('|');
                long pageId = Convert.ToInt64(parts[0]);
                long elementId = Convert.ToInt64(parts[1]);

                // Get upload model
                long tenantId = _authenticationService.TenantId;
                CreateUploadModel model = new CreateUploadModel
                {
                    Content = content,
                    ContentType = contentType,
                    Name = name,
                    TenantId = tenantId
                };

                // Create uploads, ready to be assigned to HTML element when form submitted
                IUploadElementService htmlService = (IUploadElementService)_elementFactory.GetElementService(FormId);
                long htmlUploadId = htmlService.PrepareImages(tenantId, elementId, model);

                // Return form result
                string status = _htmlUrlService.GetHtmlUploadUrl(elementId, htmlUploadId);
                return _formHelperService.GetFormResult(status);
            }
            catch (ValidationErrorException ex)
            {
                // Return form result containing errors
                return _formHelperService.GetFormResultWithValidationErrors(ex.Errors);
            }
            catch (Exception)
            {
                // Return form result containing unexpected error message
                return _formHelperService.GetFormResultWithErrorMessage(ApplicationResource.UnexpectedErrorMessage);
            }
        }
예제 #2
0
        public Size ValidatePrepareImages(long tenantId, long masterPageId, CreateUploadModel model, string keyPrefix = null)
        {
            // Check that content type identifies an image
            UploadType uploadType = _uploadService.GetUploadType(model.ContentType);

            if (uploadType != UploadType.Image)
            {
                throw new ValidationErrorException(new ValidationError(HtmlPropertyNames.Image, ElementResource.HtmlImageInvalidMessage, keyPrefix));
            }

            // Check that supplied upload is an image
            Size?size = _imageAnalysisService.GetImageDimensions(model.Content);

            if (size == null)
            {
                throw new ValidationErrorException(new ValidationError(HtmlPropertyNames.Image, ElementResource.HtmlImageInvalidMessage, keyPrefix));
            }

            // Return result
            return(size.Value);
        }
예제 #3
0
        /// <summary>
        /// Called when file uploaded posted to this controller.
        /// Credit: http://stackoverflow.com/questions/10320232/how-to-accept-a-file-post-asp-net-mvc-4-webapi (Mike Wasson's answer) (Old)
        /// Credit: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads (New)
        /// </summary>
        /// <param name="files">Uploaded files.</param>
        /// <returns>An HTTP action result.</returns>
        public async Task <IActionResult> Post(List <IFormFile> files)
        {
            // Get tenant identifier
            long tenantId = _authenticationService.TenantId;

            // Process each file
            List <long> uploadIds = new List <long>();

            foreach (IFormFile file in files)
            {
                // Get file
                string name        = file.FileName.Trim('\"');
                string contentType = file.ContentType;
                byte[] content;
                using (MemoryStream ms = new MemoryStream())
                {
                    await file.CopyToAsync(ms);

                    content = ms.ToArray();
                }

                // Create upload
                CreateUploadModel model = new CreateUploadModel
                {
                    TenantId    = tenantId,
                    Name        = name,
                    Content     = content,
                    ContentType = contentType
                };
                long uploadId = _uploadService.Create(model);
                uploadIds.Add(uploadId);
            }

            // Convert upload IDs to comma separated string and return this
            string responseContent = string.Join(",", uploadIds);

            // Everything completed successfully - return list of newly allocated upload identifiers
            return(Ok(responseContent));
        }
        private FormResult PostUpdateUserUpload(string id, string context, string name, string contentType, byte[] content)
        {
            // Get website details
            Web web = _authenticationService.Web;

            // Get upload model
            CreateUploadModel model = new CreateUploadModel
            {
                Content     = content,
                ContentType = contentType,
                Name        = name,
                TenantId    = web.TenantId
            };

            // Create uploads, ready to be assigned to user when form submitted
            ImageUploadIds uploadIds = _authenticationService.PrepareImages(web.TenantId, model);

            // Return form result
            string status = string.Format("{0}|{1}|{2}", uploadIds.ThumbnailImageUploadId, uploadIds.PreviewImageUploadId, uploadIds.ImageUploadId);

            return(_formHelperService.GetFormResult(status));
        }
예제 #5
0
        private FormResult PostCreateUpload(long elementId, string name, string contentType, byte[] content)
        {
            // Get tenant identifier, website identifier
            long tenantId = _authenticationService.TenantId;

            // Get upload model
            CreateUploadModel model = new CreateUploadModel {
                Content     = content,
                ContentType = contentType,
                Name        = name,
                TenantId    = tenantId
            };

            // Create uploads, ready to be assigned to photo when form submitted
            IUploadElementService albumService = (IUploadElementService)_elementFactory.GetElementService(FormId);
            ImageUploadIds        uploadIds    = albumService.PrepareImages2(tenantId, elementId, model);

            // Return form result
            string status = string.Format("{0}|{1}|{2}", uploadIds.ThumbnailImageUploadId, uploadIds.PreviewImageUploadId, uploadIds.ImageUploadId);

            return(_formHelperService.GetFormResult(status));
        }
예제 #6
0
        /// <summary>
        /// Handles form upload.
        /// </summary>
        /// <param name="masterPageId">Master page with page image rules.</param>
        /// <param name="name">The name of the upload (e.g. "MyImage.png").</param>
        /// <param name="contentType">The type of the upload content (e.g. "image/png").</param>
        /// <param name="content">Byte buffer containing uploaded content.</param>
        /// <returns>Result of form upload post.</returns>
        private FormResult PostPageUpload(long masterPageId, string name, string contentType, byte[] content)
        {
            // Get tenant identifier, website identifier
            long tenantId = _authenticationService.TenantId;

            // Get upload model
            CreateUploadModel model = new CreateUploadModel
            {
                Content     = content,
                ContentType = contentType,
                Name        = name,
                TenantId    = tenantId
            };

            // Create uploads, ready to be assigned to page when form submitted
            ImageUploadIds uploadIds = _pageService.PrepareImages(tenantId, masterPageId, model);

            // Return form result
            string status = string.Format("{0}|{1}|{2}", uploadIds.ThumbnailImageUploadId, uploadIds.PreviewImageUploadId, uploadIds.ImageUploadId);

            return(_formHelperService.GetFormResult(status));
        }
        /// <summary>
        /// Validates avatar upload details before images can be prepared for a user.
        /// </summary>
        /// <param name="tenantId">Website that user belongs to.</param>
        /// <param name="model">Uploaded image.</param>
        /// <param name="keyPrefix">Validation key prefix.</param>
        /// <returns>Useful information retrieved during validation.</returns>
        public AuthenticationValidateResult ValidatePrepareImages(long tenantId, CreateUploadModel model, string keyPrefix = null)
        {
            // Check that website allows avatars
            Web web = _webRepository.Read(tenantId);

            if (!web.UserHasImage)
            {
                throw new ValidationErrorException(new ValidationError(AuthenticationPropertyNames.Image, AuthenticationResource.UpdateUserImageNotAllowedMessage, keyPrefix));
            }

            // Check that content type identifies an image
            UploadType uploadType = _uploadService.GetUploadType(model.ContentType);

            if (uploadType != UploadType.Image)
            {
                throw new ValidationErrorException(new ValidationError(AuthenticationPropertyNames.Image, AuthenticationResource.UpdateUserImageInvalidMessage, keyPrefix));
            }

            // Check that supplied upload is an image
            Size?size = _imageAnalysisService.GetImageDimensions(model.Content);

            if (size == null)
            {
                throw new ValidationErrorException(new ValidationError(AuthenticationPropertyNames.Image, AuthenticationResource.UpdateUserImageInvalidMessage, keyPrefix));
            }

            // Check image dimension constraints (minimum width and height)
            if (size.Value.Width < web.UserImageMinWidth.Value || size.Value.Height < web.UserImageMinHeight.Value)
            {
                throw new ValidationErrorException(new ValidationError(AuthenticationPropertyNames.Image, string.Format(AuthenticationResource.UpdateUserImageDimensionsInvalidMessage, web.UserImageMinWidth.Value, web.UserImageMinHeight.Value), keyPrefix));
            }

            // Return result
            return(new AuthenticationValidateResult {
                Web = web, Size = size.Value
            });
        }
예제 #8
0
        public void ValidatePrepareImages(long tenantId, long elementId, CreateUploadModel model, string keyPrefix = null)
        {
            // Check that content type identifies an image
            UploadType uploadType = _uploadService.GetUploadType(model.ContentType);

            if (uploadType != UploadType.Image)
            {
                throw new ValidationErrorException(new ValidationError(CarouselPropertyNames.Image, ElementResource.CarouselImageInvalidMessage, keyPrefix));
            }

            // Check that supplied upload is an image
            Size?size = _imageAnalysisService.GetImageDimensions(model.Content);

            if (size == null)
            {
                throw new ValidationErrorException(new ValidationError(CarouselPropertyNames.Image, ElementResource.CarouselImageInvalidMessage, keyPrefix));
            }

            // Check image dimension constraints (minimum width and height)
            if (size.Value.Width < ImageMinWidth || size.Value.Height < ImageMinHeight)
            {
                throw new ValidationErrorException(new ValidationError(CarouselPropertyNames.Image, string.Format(ElementResource.CarouselImageDimensionsInvalidMessage, ImageMinWidth, ImageMinHeight), keyPrefix));
            }
        }
예제 #9
0
        /// <summary>
        /// From a single uploaded file, creates thumbnail, preview and original images in underlying storage that may be associated with a page.
        /// </summary>
        /// <param name="tenantId">Website that page belongs to.</param>
        /// <param name="masterPageId">Master page containing image upload rules.</param>
        /// <param name="model">Image upload.</param>
        /// <param name="unitOfWork">Unit of work.</param>
        /// <returns>Identifiers of newly created thumbnail, preview and source images.</returns>
        public ImageUploadIds PrepareImages(long tenantId, long masterPageId, CreateUploadModel model, IUnitOfWork unitOfWork = null)
        {
            // If we don't have a unit of work in place, create one now so that we can rollback all changes in case of failure
            IUnitOfWork localUnitOfWork = unitOfWork == null?_unitOfWorkFactory.CreateUnitOfWork() : null;

            // Begin work
            try
            {
                // Check that master page allows page images and that uploaded content is valid image
                ValidatePrepareImagesResult result = _pageValidator.ValidatePrepareImages(tenantId, masterPageId, model);

                // Create thumbnail model
                ResizeInfo thumbnailResizeInfo = new ResizeInfo
                {
                    Width      = result.MasterPage.ThumbnailImageWidth.Value,
                    Height     = result.MasterPage.ThumbnailImageHeight.Value,
                    ResizeMode = result.MasterPage.ThumbnailImageResizeMode.Value
                };
                byte[]            thumbnailContent = _imageAnalysisService.ResizeImage(model.Content, thumbnailResizeInfo);
                CreateUploadModel thumbnailModel   = new CreateUploadModel
                {
                    Content     = thumbnailContent,
                    ContentType = model.ContentType,
                    Name        = model.Name,
                    TenantId    = model.TenantId
                };

                // Create preview model
                ResizeInfo previewResizeInfo = new ResizeInfo
                {
                    Width      = result.MasterPage.PreviewImageWidth.Value,
                    Height     = result.MasterPage.PreviewImageHeight.Value,
                    ResizeMode = result.MasterPage.PreviewImageResizeMode.Value
                };
                byte[]            previewContent = _imageAnalysisService.ResizeImage(model.Content, previewResizeInfo);
                CreateUploadModel previewModel   = new CreateUploadModel
                {
                    Content     = previewContent,
                    ContentType = model.ContentType,
                    Name        = model.Name,
                    TenantId    = model.TenantId
                };

                // Create uploads for thumbnail, preview and original image
                long thumbnailImageUploadId = _uploadService.Create(thumbnailModel, unitOfWork ?? localUnitOfWork);
                long previewImageUploadId   = _uploadService.Create(previewModel, unitOfWork ?? localUnitOfWork);
                long imageUploadId          = _uploadService.Create(model, unitOfWork ?? localUnitOfWork);

                // Commit work if local unit of work in place and return result
                if (localUnitOfWork != null)
                {
                    localUnitOfWork.Commit();
                }
                return(new ImageUploadIds {
                    ThumbnailImageUploadId = thumbnailImageUploadId, PreviewImageUploadId = previewImageUploadId, ImageUploadId = imageUploadId
                });
            }
            catch (ValidationErrorException)
            {
                if (localUnitOfWork != null)
                {
                    localUnitOfWork.Rollback();
                }
                throw;
            }
            catch (Exception ex)
            {
                if (localUnitOfWork != null)
                {
                    localUnitOfWork.Rollback();
                }
                throw new ValidationErrorException(new ValidationError(null, ApplicationResource.UnexpectedErrorMessage), ex);
            }
            finally
            {
                if (localUnitOfWork != null)
                {
                    localUnitOfWork.Dispose();
                }
            }
        }
예제 #10
0
 public long PrepareImages(long tenantId, long elementId, CreateUploadModel model, IUnitOfWork unitOfWork = null)
 {
     throw new NotImplementedException();
 }
예제 #11
0
        /// <summary>
        /// Validates page, master page and file upload details before images can be prepared for a page.
        /// </summary>
        /// <param name="tenantId">Website that page belongs to.</param>
        /// <param name="masterPageId">Master page containing image upload rules.</param>
        /// <param name="model">Uploaded image.</param>
        /// <param name="keyPrefix">Validation key prefix.</param>
        /// <returns>Useful information retrieved during validation.</returns>
        public ValidatePrepareImagesResult ValidatePrepareImages(long tenantId, long masterPageId, CreateUploadModel model, string keyPrefix = null)
        {
            // Check that master page associated with page allows images
            MasterPage masterPage = _masterPageRepository.Read(tenantId, masterPageId);

            if (!masterPage.HasImage)
            {
                throw new ValidationErrorException(new ValidationError(PagePropertyNames.Image, PageResource.ImageNotAllowedMessage, keyPrefix));
            }

            // Check that content type identifies an image
            UploadType uploadType = _uploadService.GetUploadType(model.ContentType);

            if (uploadType != UploadType.Image)
            {
                throw new ValidationErrorException(new ValidationError(PagePropertyNames.Image, PageResource.ImageInvalidMessage, keyPrefix));
            }

            // Check that supplied upload is an image
            Size?size = _imageAnalysisService.GetImageDimensions(model.Content);

            if (size == null)
            {
                throw new ValidationErrorException(new ValidationError(PagePropertyNames.Image, PageResource.ImageInvalidMessage, keyPrefix));
            }

            // Check image dimension constraints (minimum width and height)
            if (size.Value.Width < masterPage.ImageMinWidth.Value || size.Value.Height < masterPage.ImageMinHeight.Value)
            {
                throw new ValidationErrorException(new ValidationError(PagePropertyNames.Image, string.Format(PageResource.ImageDimensionsInvalidMessage, masterPage.ImageMinWidth.Value, masterPage.ImageMinHeight.Value), keyPrefix));
            }

            // Return result
            return(new ValidatePrepareImagesResult {
                MasterPage = masterPage, Size = size.Value
            });
        }
예제 #12
0
        public long PrepareImages(long tenantId, long elementId, CreateUploadModel model, IUnitOfWork unitOfWork = null)
        {
            // If we don't have a unit of work in place, create one now so that we can rollback all changes in case of failure
            IUnitOfWork localUnitOfWork = unitOfWork == null?_unitOfWorkFactory.CreateUnitOfWork() : null;

            // Begin work
            try
            {
                // Check that uploaded content is valid image
                System.Drawing.Size imageSize = _htmlValidator.ValidatePrepareImages(tenantId, elementId, model);

                // Get HTML settings (does not have to be within unit of work)
                HtmlSettings htmlSettings = (HtmlSettings)New(tenantId);
                htmlSettings.ElementId = elementId;
                Read(htmlSettings);

                // Create thumbnail model
                byte[] thumbnailContent = model.Content;
                if (imageSize.Width > htmlSettings.ThumbnailImageWidth || imageSize.Height > htmlSettings.ThumbnailImageHeight)
                {
                    ResizeInfo thumbnailResizeInfo = new ResizeInfo
                    {
                        Width      = htmlSettings.ThumbnailImageWidth,
                        Height     = htmlSettings.ThumbnailImageHeight,
                        ResizeMode = htmlSettings.ThumbnailImageResizeMode
                    };
                    thumbnailContent = _imageAnalysisService.ResizeImage(model.Content, thumbnailResizeInfo);
                }
                CreateUploadModel thumbnailModel = new CreateUploadModel
                {
                    Content     = thumbnailContent,
                    ContentType = model.ContentType,
                    Name        = model.Name,
                    TenantId    = model.TenantId
                };

                // Create preview model
                byte[] previewContent = model.Content;
                if (imageSize.Width > htmlSettings.PreviewImageWidth || imageSize.Height > htmlSettings.PreviewImageHeight)
                {
                    ResizeInfo previewResizeInfo = new ResizeInfo
                    {
                        Width      = htmlSettings.PreviewImageWidth,
                        Height     = htmlSettings.PreviewImageHeight,
                        ResizeMode = htmlSettings.PreviewImageResizeMode
                    };
                    previewContent = _imageAnalysisService.ResizeImage(model.Content, previewResizeInfo);
                }
                CreateUploadModel previewModel = new CreateUploadModel
                {
                    Content     = previewContent,
                    ContentType = model.ContentType,
                    Name        = model.Name,
                    TenantId    = model.TenantId
                };

                // Create uncommitted uploads for thumbnail, preview and original image
                long thumbnailImageUploadId = _uploadService.Create(thumbnailModel, unitOfWork ?? localUnitOfWork);
                long previewImageUploadId   = _uploadService.Create(previewModel, unitOfWork ?? localUnitOfWork);
                long imageUploadId          = _uploadService.Create(model, unitOfWork ?? localUnitOfWork);

                // Commit uploads
                _uploadService.Commit(tenantId, thumbnailImageUploadId, GetHtmlUploadStorageHierarchy(elementId), unitOfWork ?? localUnitOfWork);
                _uploadService.Commit(tenantId, previewImageUploadId, GetHtmlUploadStorageHierarchy(elementId), unitOfWork ?? localUnitOfWork);
                _uploadService.Commit(tenantId, imageUploadId, GetHtmlUploadStorageHierarchy(elementId), unitOfWork ?? localUnitOfWork);

                // Create HTML image, recording upload IDs of newly created images
                HtmlUpload upload = new HtmlUpload
                {
                    TenantId               = tenantId,
                    ElementId              = elementId,
                    ImageTenantId          = tenantId,
                    ThumbnailImageUploadId = thumbnailImageUploadId,
                    PreviewImageUploadId   = previewImageUploadId,
                    ImageUploadId          = imageUploadId
                };
                long htmlImageId = _htmlRepository.CreateUpload(upload, unitOfWork ?? localUnitOfWork);

                // Commit work if local unit of work in place and return result
                if (localUnitOfWork != null)
                {
                    localUnitOfWork.Commit();
                }
                return(htmlImageId);
            }
            catch (ValidationErrorException)
            {
                if (localUnitOfWork != null)
                {
                    localUnitOfWork.Rollback();
                }
                throw;
            }
            catch (Exception ex)
            {
                if (localUnitOfWork != null)
                {
                    localUnitOfWork.Rollback();
                }
                throw new ValidationErrorException(new ValidationError(null, ApplicationResource.UnexpectedErrorMessage), ex);
            }
            finally
            {
                if (localUnitOfWork != null)
                {
                    localUnitOfWork.Dispose();
                }
            }
        }