Exemplo n.º 1
0
        public static UploadFileResult UploadFile(HttpPostedFileBase file, string uploadFolderPath, ILocalizationService localizationService, bool onlyImages = false)
        {
            var upResult = new UploadFileResult { UploadSuccessful = true };
            const string imageExtensions = "jpg,jpeg,png,gif";
            var fileName = Path.GetFileName(file.FileName);

            if (fileName != null)
            {
                // Lower case
                fileName = fileName.ToLower();

                // Get the file extension
                var fileExtension = Path.GetExtension(fileName.ToLower());

                //Before we do anything, check file size
                if (file.ContentLength > Convert.ToInt32(SiteConstants.FileUploadMaximumFileSizeInBytes))
                {
                    //File is too big
                    upResult.UploadSuccessful = false;
                    upResult.ErrorMessage = localizationService.GetResourceString("Post.UploadFileTooBig");
                    return upResult;
                }

                // now check allowed extensions
                var allowedFileExtensions = SiteConstants.FileUploadAllowedExtensions;

                if (onlyImages)
                {
                    allowedFileExtensions = imageExtensions;
                }

                if (!string.IsNullOrEmpty(allowedFileExtensions))
                {
                    // Turn into a list and strip unwanted commas as we don't trust users!
                    var allowedFileExtensionsList = allowedFileExtensions.ToLower().Trim()
                                                     .TrimStart(',').TrimEnd(',').Split(',').ToList();


                    // If can't work out extension then just error
                    if (string.IsNullOrEmpty(fileExtension))
                    {
                        upResult.UploadSuccessful = false;
                        upResult.ErrorMessage = localizationService.GetResourceString("Errors.GenericMessage");
                        return upResult;
                    }

                    // Remove the dot then check against the extensions in the web.config settings
                    fileExtension = fileExtension.TrimStart('.');
                    if (!allowedFileExtensionsList.Contains(fileExtension))
                    {
                        upResult.UploadSuccessful = false;
                        upResult.ErrorMessage = localizationService.GetResourceString("Post.UploadBannedFileExtension");
                        return upResult;
                    }
                }

                // Store these here as we may change the values within the image manipulation
                var newFileName = string.Empty;
                var path = string.Empty;

                if (imageExtensions.Split(',').ToList().Contains(fileExtension))
                {
                    // Rotate image if wrong want around
                    using (var sourceimage = Image.FromStream(file.InputStream))
                    {
                        if (sourceimage.PropertyIdList.Contains(0x0112))
                        {
                            int rotationValue = sourceimage.GetPropertyItem(0x0112).Value[0];
                            switch (rotationValue)
                            {
                                case 1: // landscape, do nothing
                                    break;

                                case 8: // rotated 90 right
                                    // de-rotate:
                                    sourceimage.RotateFlip(RotateFlipType.Rotate270FlipNone);
                                    break;

                                case 3: // bottoms up
                                    sourceimage.RotateFlip(RotateFlipType.Rotate180FlipNone);
                                    break;

                                case 6: // rotated 90 left
                                    sourceimage.RotateFlip(RotateFlipType.Rotate90FlipNone);
                                    break;
                            }
                        }

                        using (var stream = new MemoryStream())
                        {
                            // Save the image as a Jpeg only
                            sourceimage.Save(stream, ImageFormat.Jpeg);
                            stream.Position = 0;

                            // Change the extension to jpg as that's what we are saving it as
                            fileName = fileName.Replace(fileExtension, "");
                            fileName = string.Concat(fileName, "jpg");
                            file = new MemoryFile(stream, "image/jpeg", fileName);

                            // Sort the file name
                            newFileName = CreateNewFileName(fileName);
                            path = Path.Combine(uploadFolderPath, newFileName);

                            // Save the file to disk
                            file.SaveAs(path);
                        }
                    }

                }
                else
                {
                    // Sort the file name
                    newFileName = CreateNewFileName(fileName);
                    path = Path.Combine(uploadFolderPath, newFileName);

                    // Save the file to disk
                    file.SaveAs(path);
                }



                var hostingRoot = HostingEnvironment.MapPath("~/") ?? "";
                var fileUrl = path.Substring(hostingRoot.Length).Replace('\\', '/').Insert(0, "/");

                upResult.UploadedFileName = newFileName;
                upResult.UploadedFileUrl = fileUrl;

            }

            return upResult;
        }
Exemplo n.º 2
0
        public ActionResult MemberRegisterLogic(MemberAddViewModel userModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var userToSave = new MembershipUser
                {
                    UserName = _bannedWordService.SanitiseBannedWords(userModel.UserName),
                    Email = userModel.Email,
                    Password = userModel.Password,
                    IsApproved = userModel.IsApproved,
                    Comment = userModel.Comment,
                };

                var homeRedirect = false;

                // Now check settings, see if users need to be manually authorised
                // OR Does the user need to confirm their email
                var manuallyAuthoriseMembers = SettingsService.GetSettings().ManuallyAuthoriseNewMembers;
                var memberEmailAuthorisationNeeded = SettingsService.GetSettings().NewMemberEmailConfirmation ?? false;
                if (manuallyAuthoriseMembers || memberEmailAuthorisationNeeded)
                {
                    userToSave.IsApproved = false;
                }

                var createStatus = MembershipService.CreateUser(userToSave);
                if (createStatus != MembershipCreateStatus.Success)
                {
                    ModelState.AddModelError(string.Empty, MembershipService.ErrorCodeToString(createStatus));
                }
                else
                {
                    // See if this is a social login and we have their profile pic
                    if (!string.IsNullOrEmpty(userModel.SocialProfileImageUrl))
                    {
                        // We have an image url - Need to save it to their profile
                        var image = AppHelpers.GetImageFromExternalUrl(userModel.SocialProfileImageUrl);

                        // Set upload directory - Create if it doesn't exist
                        var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(SiteConstants.UploadFolderPath, userToSave.Id));
                        if (!Directory.Exists(uploadFolderPath))
                        {
                            Directory.CreateDirectory(uploadFolderPath);
                        }

                        // Get the file name
                        var fileName = Path.GetFileName(userModel.SocialProfileImageUrl);

                        // Create a HttpPostedFileBase image from the C# Image
                        using (var stream = new MemoryStream())
                        {
                            // Microsoft doesn't give you a file extension - See if it has a file extension
                            // Get the file extension
                            var fileExtension = Path.GetExtension(fileName);
                            if (string.IsNullOrEmpty(fileExtension))
                            {
                                // no file extension so give it one
                                fileName = string.Concat(fileName, ".jpg");
                            }

                            image.Save(stream, ImageFormat.Jpeg);
                            stream.Position = 0;
                            HttpPostedFileBase formattedImage = new MemoryFile(stream, "image/jpeg", fileName);

                            // Upload the file
                            var uploadResult = AppHelpers.UploadFile(formattedImage, uploadFolderPath, LocalizationService, true);

                            // Don't throw error if problem saving avatar, just don't save it.
                            if (uploadResult.UploadSuccessful)
                            {
                                userToSave.Avatar = uploadResult.UploadedFileName;
                            }
                        }

                    }

                    // Store access token for social media account in case we want to do anything with it
                    if (userModel.LoginType == LoginType.Facebook)
                    {
                        userToSave.FacebookAccessToken = userModel.UserAccessToken;
                    }
                    if (userModel.LoginType == LoginType.Google)
                    {
                        userToSave.GoogleAccessToken = userModel.UserAccessToken;
                    }
                    if (userModel.LoginType == LoginType.Google)
                    {
                        userToSave.MicrosoftAccessToken = userModel.UserAccessToken;
                    }

                    // Set the view bag message here
                    SetRegisterViewBagMessage(manuallyAuthoriseMembers, memberEmailAuthorisationNeeded, userToSave);

                    if (!manuallyAuthoriseMembers && !memberEmailAuthorisationNeeded)
                    {
                        homeRedirect = true;
                    }

                    try
                    {
                        // Only send the email if the admin is not manually authorising emails or it's pointless
                        SendEmailConfirmationEmail(userToSave);

                        unitOfWork.Commit();

                        if (homeRedirect)
                        {
                            if (Url.IsLocalUrl(userModel.ReturnUrl) && userModel.ReturnUrl.Length > 1 && userModel.ReturnUrl.StartsWith("/")
                            && !userModel.ReturnUrl.StartsWith("//") && !userModel.ReturnUrl.StartsWith("/\\"))
                            {
                                return Redirect(userModel.ReturnUrl);
                            }
                            return RedirectToAction("Index", "Home", new { area = string.Empty });
                        }
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        FormsAuthentication.SignOut();
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                    }
                }
            }

            return View("Register");
        }
Exemplo n.º 3
0
        public static UploadFileResult UploadFile(HttpPostedFileBase file, string uploadFolderPath, ILocalizationService localizationService, bool onlyImages = false)
        {
            var upResult = new UploadFileResult {
                UploadSuccessful = true
            };
            const string imageExtensions = "jpg,jpeg,png,gif";
            var          fileName        = Path.GetFileName(file.FileName);
            var          storageProvider = StorageProvider.Current;

            if (fileName != null)
            {
                // Lower case
                fileName = fileName.ToLower();

                // Get the file extension
                var fileExtension = Path.GetExtension(fileName);

                //Before we do anything, check file size
                if (file.ContentLength > Convert.ToInt32(SiteConstants.Instance.FileUploadMaximumFileSizeInBytes))
                {
                    //File is too big
                    upResult.UploadSuccessful = false;
                    upResult.ErrorMessage     = localizationService.GetResourceString("Post.UploadFileTooBig");
                    return(upResult);
                }

                // now check allowed extensions
                var allowedFileExtensions = SiteConstants.Instance.FileUploadAllowedExtensions;

                if (onlyImages)
                {
                    allowedFileExtensions = imageExtensions;
                }

                if (!string.IsNullOrEmpty(allowedFileExtensions))
                {
                    // Turn into a list and strip unwanted commas as we don't trust users!
                    var allowedFileExtensionsList = allowedFileExtensions.ToLower().Trim()
                                                    .TrimStart(',').TrimEnd(',').Split(',').ToList();

                    // If can't work out extension then just error
                    if (string.IsNullOrEmpty(fileExtension))
                    {
                        upResult.UploadSuccessful = false;
                        upResult.ErrorMessage     = localizationService.GetResourceString("Errors.GenericMessage");
                        return(upResult);
                    }

                    // Remove the dot then check against the extensions in the web.config settings
                    fileExtension = fileExtension.TrimStart('.');
                    if (!allowedFileExtensionsList.Contains(fileExtension))
                    {
                        upResult.UploadSuccessful = false;
                        upResult.ErrorMessage     = localizationService.GetResourceString("Post.UploadBannedFileExtension");
                        return(upResult);
                    }
                }

                // Store these here as we may change the values within the image manipulation
                var newFileName = string.Empty;
                var path        = string.Empty;

                if (imageExtensions.Split(',').ToList().Contains(fileExtension))
                {
                    // Rotate image if wrong want around
                    using (var sourceimage = Image.FromStream(file.InputStream))
                    {
                        if (sourceimage.PropertyIdList.Contains(0x0112))
                        {
                            int rotationValue = sourceimage.GetPropertyItem(0x0112).Value[0];
                            switch (rotationValue)
                            {
                            case 1:     // landscape, do nothing
                                break;

                            case 8:     // rotated 90 right
                                // de-rotate:
                                sourceimage.RotateFlip(RotateFlipType.Rotate270FlipNone);
                                break;

                            case 3:     // bottoms up
                                sourceimage.RotateFlip(RotateFlipType.Rotate180FlipNone);
                                break;

                            case 6:     // rotated 90 left
                                sourceimage.RotateFlip(RotateFlipType.Rotate90FlipNone);
                                break;
                            }
                        }

                        using (var stream = new MemoryStream())
                        {
                            // Save the image as a Jpeg only
                            sourceimage.Save(stream, ImageFormat.Jpeg);
                            stream.Position = 0;

                            // Change the extension to jpg as that's what we are saving it as
                            fileName = fileName.Replace(fileExtension, "");
                            fileName = string.Concat(fileName, "jpg");
                            file     = new MemoryFile(stream, "image/jpeg", fileName);

                            // Sort the file name
                            newFileName = CreateNewFileName(fileName);

                            // Get the storage provider and save file
                            upResult.UploadedFileUrl = storageProvider.SaveAs(uploadFolderPath, newFileName, file);
                        }
                    }
                }
                else
                {
                    // Sort the file name
                    newFileName = CreateNewFileName(fileName);
                    upResult.UploadedFileUrl = storageProvider.SaveAs(uploadFolderPath, newFileName, file);
                }

                upResult.UploadedFileName = newFileName;
            }

            return(upResult);
        }