/// <summary>
        /// Permanently delete a a media file
        /// </summary>
        /// <param name="media">Media</param>
        public void DeleteMedia(Media media)
        {
            if (media == null)
                throw new ArgumentNullException("media");

            string file = System.Web.HttpContext.Current.Server.MapPath("/Uploads/Media/" + media.FileName);
            if(File.Exists(file))
                File.Delete(file);

            _mediaRepository.Delete(media, true);
        }
        public ActionResult Edit(PageModel model, HttpPostedFileBase uploadedFile)
        {
            if (!_permissionService.Authorize(PermissionProvider.ManagePages))
                return AccessDeniedView();

            bool validUpload = true;

            if (string.IsNullOrEmpty(model.MediaItem.Name))
            {
                if (ModelState.ContainsKey("MediaItem.Name"))
                    ModelState["MediaItem.Name"].Errors.Add(new ModelError("Name is required."));
                validUpload = false;
            }

            if (uploadedFile == null || uploadedFile.ContentLength <= 0)
            {
                ErrorNotification("Please select a file to upload.");
                validUpload = false;
            }

            if (validUpload)
            {
                string path = HttpContext.Server.MapPath("/Uploads/Media/");
                string filename = _webHelper.GetUniqueFileName(path, uploadedFile.FileName);

                // Create the media object
                var media = new Media
                {
                    EntityId = model.Id,
                    EntityTypeId = (int) EntityType.Page,
                    FileName = filename,
                    Link = model.MediaItem.Link,
                    Name = model.MediaItem.Name
                };

                // Save the file locally
                uploadedFile.SaveAs(path + filename);

                // Insert the media record
                _mediaService.InsertMedia(media);

                // Clear the fields
                model.MediaItem.Link = "";
                model.MediaItem.Name = "";
            }

            model.Media = _mediaService.GetAllMediaByEntityId(EntityType.Page, model.Id).Select(x => x.ToModel()).Select(PrepareListMediaModel).OrderBy(m => m.FileName).ToList();

            var page = _pageService.GetPageById(model.Id);
            model.IsSystemPage = page.IsSystemPage;
            model.CreatedDate = page.CreatedDate;

            PrepareBreadcrumbs();
            AddBreadcrumb("Edit Page", null);

            return View(model);
        }
        public ActionResult Add(SuccessStoryModel model, string add)
        {
            if (!_permissionService.Authorize(PermissionProvider.ManageSuccessStories))
                return AccessDeniedView();

            if (ModelState.IsValid)
            {
                try
                {
                    // Build the story entity
                    SuccessStory success = model.ToEntity();
                    success.Active = (add.ToLower() == "publish");
                    success.Author = _userService.GetUserById(model.AuthorId);

                    // Insert the story entity
                    _successStoryService.InsertSuccessStory(success);
                    _slugService.InsertSlug(new Slug{ SlugUrl = SeoExtensions.GetSeoName(success.Title), SuccessStoryId = success.Id});

                    // Build the uploaded file name and store the file
                    string path = HttpContext.Server.MapPath("/Uploads/Media/");
                    string filename = _webHelper.GetUniqueFileName(path, model.UploadedFile.FileName);
                    model.UploadedFile.SaveAs(path + filename);

                    // Build the media entity
                    var media = new Media
                    {
                        EntityId = success.Id,
                        EntityType = EntityType.SuccessStory,
                        FileName = filename
                    };

                    // Insert the media entity
                    _mediaService.InsertMedia(media);

                    SuccessNotification("The success story details have been added successfully.");
                    return RedirectToAction("Index");
                }
                catch (Exception ex)
                {
                    ErrorNotification(ex.ToString());
                }
            }

            PrepareBreadcrumbs();
            AddBreadcrumb("Add New Story", null);

            return View(PrepareSuccessStoryModel(null));
        }
        public ActionResult Edit(SuccessStoryModel model, string save)
        {
            if (!_permissionService.Authorize(PermissionProvider.ManageSuccessStories))
                return AccessDeniedView();

            save = save.ToLower();

            // get the category
            var story = _successStoryService.GetSuccessStoryById(model.Id);

            // check we have a category and they are not deleted
            if (story == null || story.Deleted)
            {
                ErrorNotification("The story couldn't be found or has been deleted.");
                return RedirectToAction("Index");
            }

            story.Active = (save == "update" ? story.Active : (save == "publish"));
            story.Author = _userService.GetUserById(model.AuthorId);
            story.Title = model.Title;
            story.ShortSummary = model.ShortSummary;
            story.Article = model.Article;
            story.MetaTitle = model.MetaTitle;
            story.MetaDescription = model.MetaDescription;
            story.MetaKeywords = model.MetaKeywords;
            story.MetaTitle = model.MetaTitle;
            if (ModelState.IsValid)
            {
                try
                {
                    _successStoryService.UpdateSuccessStory(story);
                    _slugService.UpdateSlug(story.Id, SeoExtensions.GetSeoName(story.Title));

                    if (model.UploadedFile != null && model.UploadedFile.ContentLength > 0)
                    {
                        Media currentMedia =
                       _mediaService.GetAllMediaByEntityId(EntityType.SuccessStory, model.Id).FirstOrDefault();
                        if (currentMedia != null)
                            _mediaService.DeleteMedia(currentMedia);
                        string path = HttpContext.Server.MapPath("/Uploads/Media/");
                        string filename = _webHelper.GetUniqueFileName(path, model.UploadedFile.FileName);
                        Media media = new Media
                                          {
                                              EntityId = model.Id,
                                              EntityTypeId = (int) EntityType.SuccessStory,
                                              EntityType = EntityType.SuccessStory,
                                              FileName = filename
                                          };
                        model.UploadedFile.SaveAs(path + filename);
                        _mediaService.InsertMedia(media);
                    }
                    SuccessNotification("The success story details have been updated successfully.");
                    return RedirectToAction("Edit", story.Id);
                }
                catch (Exception)
                {
                    ErrorNotification("An error occurred saving the success story details, please try again.");
                }
            }
            else
            {
                ErrorNotification("We were unable to make the change, please review the form and correct the errors.");
            }

            PrepareBreadcrumbs();
            AddBreadcrumb("Edit Story", null);

            return View(PrepareSuccessStoryModel(story));
        }
        /// <summary>
        /// Insert a media file
        /// </summary>
        /// <param name="media">Media File</param>
        public void InsertMedia(Media media)
        {
            if (media == null)
                throw new ArgumentNullException("media");

            if ((Path.GetExtension(media.FileName) ?? "").ToLower() == ".pdf")
                media.FileType = FileType.PDF;
            else
                media.FileType = FileType.Image;

            media.UploadedById = _workContext.CurrentUser.Id;
            media.UploadedDate = DateTime.Now;

            _mediaRepository.Insert(media);
        }
        private void InstallSuccessStories()
        {
            var story = new SuccessStory
            {
                Active = true,
                Article = "Congratulations, you've successfully installed #wewillgather. You can delete this post and add your own new ones via the site admin area.",
                Author = _userService.GetSiteOwner(),
                CreatedBy = 1,
                CreatedDate = DateTime.Now,
                Deleted = false,
                LastModifiedDate = DateTime.Now,
                Title = "You've installed #wewillgather!"
            };

            _successStoryRepository.Insert(story);

            var storyImage = new Media
            {
                EntityId = story.Id,
                EntityType = EntityType.SuccessStory,
                FileName = "install-post.jpg",
                FileType = FileType.Image,
                UploadedById = 1,
                UploadedDate = DateTime.Now
            };

            _mediaRepository.Insert(storyImage);
        }