public async Task EditAsync(NewsEditViewModel newsEditViewModel, string userId)
        {
            var news = this.newsRepository.All().FirstOrDefault(g => g.Id == newsEditViewModel.Id);

            if (news == null)
            {
                throw new NullReferenceException(
                          string.Format(ExceptionMessages.NewsNotFound, newsEditViewModel.Id));
            }

            if (newsEditViewModel.Image != null)
            {
                var newImageUrl = await this.cloudinaryService
                                  .UploadAsync(newsEditViewModel.Image, newsEditViewModel.Title + Suffixes.NewsSuffix);

                news.ImagePath = newImageUrl;
            }

            news.Title            = newsEditViewModel.Title;
            news.Description      = newsEditViewModel.Description;
            news.ShortDescription = newsEditViewModel.ShortDescription;
            news.UserId           = userId;
            news.ModifiedOn       = DateTime.UtcNow;
            news.IsUpdated        = true;

            this.newsRepository.Update(news);
            await this.newsRepository.SaveChangesAsync();
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Edit(NewsEditViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            try
            {
                var existingNews = await _newsService.GetNewsById(model.IdNews);

                Mapper.Map(model, existingNews);

                if (model.ImageUpload != null)
                {
                    string imageString = await GetImageBase64FromFile(model.ImageUpload);

                    if (!String.IsNullOrEmpty(imageString))
                    {
                        existingNews.Image = imageString;
                    }
                    else
                    {
                        return(View(model));
                    }
                }
                _newsService.SaveChanges();
                SetSuccess($"Pomyślnie edytowano news '{model.Title}'");
            }
            catch (Exception ex)
            {
                SetError(ex);
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Edit an existing news
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool EditNews(NewsEditViewModel model)
        {
            bool Result = false;

            try
            {
                News news = _newsRepo.Get(model.Id);
                if (news != null)
                {
                    news.PublishDate            = model.PublishDate;
                    news.Title                  = model.NewsTitle;
                    news.Description            = model.NewsDescription;
                    news.MailSubject            = model.MailSubject;
                    news.TypeId                 = model.TypeId;
                    news.TypeUserMailingId      = model.TypeUserMailingId;
                    news.Active                 = model.Active;
                    news.LastModificationUserId = model.LastModificationUserId;
                    news.ModificationDate       = DateTime.UtcNow;

                    _newsRepo.Edit(news);
                    Result = _newsRepo.Save();
                }
            }
            catch (Exception e)
            {
                Result = false;
                Commons.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            }
            return(Result);
        }
        public async Task CheckIfEditAsyncEditsNewsImage()
        {
            this.SeedDatabase();

            using (var stream = File.OpenRead(TestImagePath))
            {
                var file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
                {
                    Headers     = new HeaderDictionary(),
                    ContentType = TestImageContentType,
                };

                var newsEditViewModel = new NewsEditViewModel()
                {
                    Id               = this.firstNews.Id,
                    Title            = this.firstNews.Title,
                    Description      = this.firstNews.Description,
                    ShortDescription = this.firstNews.Description,
                    Image            = file,
                };

                await this.newsService.EditAsync(newsEditViewModel, this.user.Id);

                await this.cloudinaryService.DeleteImage(this.cloudinary, newsEditViewModel.Title + Suffixes.NewsSuffix);
            }

            var news = await this.newsRepository.All().FirstAsync();

            Assert.NotEqual(TestImageUrl, news.ImagePath);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Creationf of a news
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int CreateNews(NewsEditViewModel model)
        {
            int InsertedId = -1;

            try
            {
                News news = new News();
                news.PublishDate       = model.PublishDate;
                news.Title             = model.NewsTitle;
                news.Description       = model.NewsDescription;
                news.MailSubject       = model.MailSubject;
                news.TypeId            = model.TypeId;
                news.TypeUserMailingId = model.TypeUserMailingId;

                news.ModificationDate       = DateTime.UtcNow;
                news.Active                 = model.Active;
                news.LastModificationUserId = model.LastModificationUserId;
                news.CreationDate           = DateTime.UtcNow;

                _newsRepo.Add(news);
                if (_newsRepo.Save())
                {
                    InsertedId = news.Id;
                }
            }
            catch (Exception e)
            {
                InsertedId = -1;
                Commons.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            }
            return(InsertedId);
        }
Exemplo n.º 6
0
        public IActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(RedirectToAction("Index"));
            }

            var findNews = _newsService.GetAdmin(id);

            if (findNews == null)
            {
                return(RedirectToAction("Index"));
            }

            NewsEditViewModel viewModel = new NewsEditViewModel()
            {
                Id            = findNews.Id,
                Name          = findNews.Name,
                Description   = findNews.Description,
                EditorContent = findNews.EditorContent,
                Slug          = findNews.Slug,
                StatusId      = findNews.StatusId,
                CampusId      = findNews.CampusId
            };

            return(View(viewModel));
        }
        /// <summary>
        /// 編集画面を開きます。
        /// </summary>
        private void OpenEditView()
        {
            var childView      = new NewsEditView();
            var childViewModel = new NewsEditViewModel();

            childViewModel.UserId      = this.viewModel.UserId;
            childViewModel.DisplayName = this.viewModel.DisplayName;
            childViewModel.AccessToken = this.viewModel.AccessToken;
            childViewModel.Color       = this.viewModel.SelectedNews.Color;
            childViewModel.SerialId    = this.viewModel.SelectedNews.SerialId;
            childViewModel.CreatedAt   = this.viewModel.SelectedNews.CreatedAt;
            childViewModel.Category    = this.viewModel.SelectedNews.Category;
            childViewModel.Id          = this.viewModel.SelectedNews.Id;
            childViewModel.Title       = this.viewModel.SelectedNews.Title;
            childViewModel.Author      = this.viewModel.SelectedNews.Author;
            childViewModel.Outline     = this.viewModel.SelectedNews.Outline;
            childViewModel.MediaURL    = this.viewModel.SelectedNews.MediaURL;
            childView.DataContext      = childViewModel;
            childView.Owner            = this;
            var dialogResult = childView.ShowDialog();

            if (dialogResult == true)
            {
                if (this.viewModel.SelectedNewsCategory.Category == '\0')
                {
                    this.RefreshNewsList('\0');
                }
                else
                {
                    this.RefreshNewsList(this.viewModel.SelectedNewsCategory.Category);
                }
            }
        }
Exemplo n.º 8
0
        public IActionResult Edit(NewsEditViewModel obj)
        {
            if (ModelState.IsValid)
            {
                string fileName;

                if (obj.ImageFile != null)
                {
                    fileName = UploadedFile(obj);
                }
                else
                {
                    fileName = obj.Image;
                }

                News news = new News
                {
                    Id              = obj.Id,
                    Title           = obj.Title,
                    Content         = obj.Content,
                    PublicationDate = obj.PublicationDate,
                    AuthorID        = obj.AuthorID,
                    Tags            = obj.Tags,
                    ImagePath       = fileName,
                };

                _db.News.Update(news);
                _db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(obj));
        }
Exemplo n.º 9
0
        public IActionResult Edit(int?id)
        {
            if (id == null || id == 0)
            {
                return(NotFound());
            }

            var obj = _db.News.Find(id);

            if (obj == null)
            {
                return(NotFound());
            }

            var objViewModel = new NewsEditViewModel
            {
                Id              = obj.Id,
                Title           = obj.Title,
                Content         = obj.Content,
                PublicationDate = obj.PublicationDate,
                AuthorID        = obj.AuthorID,
                Tags            = obj.Tags,
                Image           = obj.ImagePath,
            };

            return(View(objViewModel));
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Edit(int id, [FromForm] NewsEditViewModel newsModel)
        {
            var mapper = new MapperConfiguration(cfg => cfg.CreateMap <NewsEditViewModel, NewsEditDto>()).CreateMapper();

            var newsDto = mapper.Map <NewsEditDto>(newsModel);

            await _newsService.UpdateNews(id, newsDto);

            return(Ok());
        }
Exemplo n.º 11
0
 public static NewsEditDto ToDto(this NewsEditViewModel source, string fileName)
 {
     return new NewsEditDto
     {
         Description = source.Description,
         Id = source.Id,
         PrimaryPicture = fileName,
         Title = source.Title,
         Type = source.Type
     };
 }
Exemplo n.º 12
0
        public async Task <IActionResult> Edit(NewsEditViewModel newsEditViewModel)
        {
            var user = await this.userManager.GetUserAsync(this.User);

            if (!this.ModelState.IsValid)
            {
                return(this.View(newsEditViewModel));
            }

            await this.newsService.EditAsync(newsEditViewModel, user.Id);

            return(this.RedirectToAction("GetAll", "News", new { area = "Administration" }));
        }
Exemplo n.º 13
0
        public ActionResult Edit(NewsEditViewModel newsEditViewModel, int id)
        {
            var config = new MapperConfiguration(cfg => cfg.CreateMap <NewsEditViewModel, News>());
            var mapper = config.CreateMapper();

            News news = mapper.Map <News>(newsEditViewModel);

            news.NewsId       = id;
            news.UserId       = Convert.ToInt32(Session["UserId"]);
            news.RestaurantId = _newsContext.Get(id).RestaurantId;
            _newsContext.Update(news);
            return(RedirectToAction("Index", "News"));
        }
        public async Task CheckIfEditingNewsReturnsNullReferenceException()
        {
            this.SeedDatabase();

            var newsEditViewModel = new NewsEditViewModel
            {
                Id = 3,
            };

            var exception = await Assert
                            .ThrowsAsync <NullReferenceException>(async() => await this.newsService.EditAsync(newsEditViewModel, this.user.Id));

            Assert.Equal(string.Format(ExceptionMessages.NewsNotFound, newsEditViewModel.Id), exception.Message);
        }
Exemplo n.º 15
0
        public ActionResult Edit(int id)
        {
            News newsToUpdate = _newsContext.Get(id);
            var  config       = new MapperConfiguration(cfg => cfg.CreateMap <News, NewsEditViewModel>());
            var  mapper       = config.CreateMapper();
            //Copy values

            NewsEditViewModel newsEdit = mapper.Map <NewsEditViewModel>(newsToUpdate);

            TempData["NewsId"]       = id;
            TempData["RestaurantId"] = newsToUpdate.RestaurantId;

            return(View(newsEdit));
        }
Exemplo n.º 16
0
        public async Task <IActionResult> UpdateNews(NewsEditViewModel newsEditViewModel)
        {
            if (ModelState.IsValid)
            {
                var news = await _newsService.GetNewsByIdAsync(newsEditViewModel.Id);

                _mapper.Map(newsEditViewModel, news);
                await _newsService.UpdateNewsAsync(news);

                return(RedirectToAction("NewsManagement"));
            }
            else
            {
                return(RedirectToAction("EditNews", newsEditViewModel));
            }
        }
Exemplo n.º 17
0
        public IActionResult Edit(NewsEditViewModel model)
        {
            var uploadResult  = new ServiceResult <string>();
            var serviceResult = new ServiceResult <string>();

            if (model.PrimaryPicture != null)
            {
                uploadResult = _fileService.Upload(model.PrimaryPicture, "News", 1024 * 500);
            }

            if (!uploadResult.IsSuccess && model.PrimaryPicture != null)
            {
                Swal(false, uploadResult.Errors.FirstOrDefault());
                return(RedirectToAction(nameof(Edit), new { id = model.Id }));
            }

            serviceResult = _adminService.EditNews(model.ToDto(uploadResult.Data));

            if (serviceResult.IsSuccess)
            {
                // delete file
                if (!string.IsNullOrEmpty(serviceResult.Data))
                {
                    _fileService.Delete(serviceResult.Data, "Post");
                }

                Swal(true, "خبر با موفقیت ویرایش شد");
                return(RedirectToAction(nameof(Edit), new { id = model.Id }));
            }

            AddErrors(serviceResult);

            var data = _adminService.GetNews(model.Id);

            List <SelectListItem> typeSelector = new List <SelectListItem>();

            typeSelector.Add(new SelectListItem("نوع خبر", ""));
            typeSelector.Add(new SelectListItem("اخبار محله", NewsType.Mahal.ToString(), data.Type == NewsType.Mahal));
            typeSelector.Add(new SelectListItem("سیاسی", NewsType.Siasi.ToString(), data.Type == NewsType.Siasi));
            typeSelector.Add(new SelectListItem("اقتصادی", NewsType.Eghtesadi.ToString(), data.Type == NewsType.Eghtesadi));
            typeSelector.Add(new SelectListItem("فرهنگی", NewsType.Farhangi.ToString(), data.Type == NewsType.Farhangi));

            ViewBag.TypeSelector = typeSelector;

            return(View(data.ToViewModel()));
        }
Exemplo n.º 18
0
        public ActionResult Edit(string title, string content, string id)
        {
            //NewsRecord news = new NewsRecord()
            //{
            //    Id = int.Parse(id),
            //    NewsTitle = title,
            //    NewsContent = content
            //};
            //_newsService.UpdateRepoNews(news);
            //_newsService.UpdateNews(news);


            //------------------------------------------------------------------------------------------------
            var newspart = _orchardServices.ContentManager.Get <NewsPart>(int.Parse(id), VersionOptions.Latest);

            if (newspart == null)
            {
                return(HttpNotFound());
            }

            var model = _orchardServices.ContentManager.UpdateEditor(newspart, this);

            newspart.NewsTitle   = title;
            newspart.NewsContent = content;
            //var editModel = new NewsEditViewModel () { News = newspart };
            var editModel = new NewsEditViewModel(newspart);

            TryUpdateModel(editModel);

            if (!ModelState.IsValid)
            {
                _orchardServices.TransactionManager.Cancel();


                var editor = Shape.EditorTemplate(TemplateName: "Parts_News_Edit", Model: editModel, Prefix: null);

                model.Content.Add(editor);

                return(View(model));
            }

            _orchardServices.ContentManager.Publish(newspart.ContentItem);
            _orchardServices.Notifier.Information(T("新闻信息修改成功"));
            return(RedirectToAction("Index"));
        }
Exemplo n.º 19
0
        public async Task <IActionResult> OnGetAsync(long?id, string returnUrl)
        {
            if (id == null)
            {
                return(NotFound());
            }
            ReturnUrl = returnUrl;
            var news = await _context.Newses.Include(t => t.ImageFile).SingleOrDefaultAsync(m => m.Id == id);


            if (news == null)
            {
                return(NotFound());
            }

            NewsItem = new NewsEditViewModel(news);
            return(Page());
        }
Exemplo n.º 20
0
        /// <summary>
        /// Get the viewmodel for the News form
        /// </summary>
        /// <param name="NewsId"></param>
        /// <returns></returns>
        public NewsEditViewModel GetNewsEditViewModel(int?NewsId)
        {
            NewsEditViewModel model = new NewsEditViewModel();

            try
            {
                // Creation
                if (NewsId == null || NewsId <= 0)
                {
                    model.Id          = -1;
                    model.Active      = false;
                    model.PublishDate = DateTime.UtcNow.ToLocalTime();
                }
                // Modification
                else
                {
                    News RealNews = GetNewsById(NewsId.Value);
                    model.Id = NewsId.Value;
                    if (RealNews != null)
                    {
                        model.NewsTitle         = RealNews.Title;
                        model.NewsDescription   = RealNews.Description;
                        model.MailSubject       = RealNews.MailSubject;
                        model.TypeUserMailingId = RealNews.TypeUserMailingId;
                        model.TypeId            = RealNews.TypeId;
                        model.Active            = RealNews.Active;
                        model.Id              = RealNews.Id;
                        model.PublishDate     = RealNews.PublishDate.ToLocalTime();
                        model.ScheduledTaskId = RealNews.ScheduledTasks?.FirstOrDefault()?.Id;
                        model.HasScheduledTaskBeenExecuted = RealNews.ScheduledTasks?.FirstOrDefault()?.ExecutionDate < DateTime.UtcNow ? true : false;
                    }
                }


                model.NewsTypeList        = _categoryService.GetSelectionList(CommonsConst.CategoryTypes.NewsType);
                model.TypeUserMailingList = _categoryService.GetSelectionList(CommonsConst.CategoryTypes.TypeUserMailing);
            }
            catch (Exception e)
            {
                Commons.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            }
            return(model);
        }
Exemplo n.º 21
0
        public async Task <IActionResult> Edit(NewsEditViewModel newsPostToEdit)
        {
            var user = await this.userManager.GetUserAsync(this.User);

            var imageUrl = string.Empty;

            if (newsPostToEdit.Picture != null)
            {
                imageUrl = await CloudinaryExtension.UploadSingleAsync(this.cloudinary, newsPostToEdit.Picture);
            }

            string latinTitle = Transliteration.CyrillicToLatin(newsPostToEdit.Title, Language.Bulgarian);

            latinTitle = latinTitle.Replace(' ', '-');

            await this.newsService.EditAsync(newsPostToEdit.Title, newsPostToEdit.Content, user.Id, imageUrl, latinTitle, newsPostToEdit.Author, newsPostToEdit.Id);

            return(this.RedirectToAction("ByName", new { name = latinTitle }));
        }
        public async Task EditAsyncEditsNewsWhenImageStaysTheSame()
        {
            this.SeedDatabase();

            var newsEditViewModel = new NewsEditViewModel
            {
                Id               = this.firstNews.Id,
                Title            = "Changed News title",
                Description      = "Changed News description",
                ShortDescription = "Changed Short description",
                Image            = null,
            };

            await this.newsService.EditAsync(newsEditViewModel, this.user.Id);

            Assert.Equal(newsEditViewModel.Title, this.firstNews.Title);
            Assert.Equal(newsEditViewModel.Description, this.firstNews.Description);
            Assert.Equal(newsEditViewModel.ShortDescription, this.firstNews.ShortDescription);
        }
Exemplo n.º 23
0
        public IActionResult Edit(NewsEditViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(viewModel));
            }
            string uniqueFileName = null;

            if (viewModel.Photos != null && viewModel.Photos.Count > 0)
            {
                foreach (IFormFile photo in viewModel.Photos)
                {
                    var extension = Path.GetExtension(photo.FileName).ToLower();
                    if (extension == ".jpg" || extension == ".jpeg" || extension == ".png")
                    {
                        string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images");
                        uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName;
                        string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                        photo.CopyTo(new FileStream(filePath, FileMode.Create));
                    }
                    else
                    {
                        throw new Exception("Dosya türü .JPG , .JPEG veya .PNG olmalıdır..");
                    }
                }
            }
            News editedNews = new News()
            {
                Id            = viewModel.Id,
                Name          = viewModel.Name,
                Description   = viewModel.Description,
                Slug          = viewModel.Slug,
                EditorContent = viewModel.EditorContent,
                ImageUrl      = uniqueFileName,
                StatusId      = viewModel.StatusId,
                CampusId      = viewModel.CampusId
            };

            _newsService.Edit(editedNews);
            return(RedirectToAction("Index"));
        }
Exemplo n.º 24
0
        public ActionResult EditView(int id)
        {
            var               newsQuery = _newsService.GetRepoNewsById(id);
            dynamic           news      = Shape.News(id: newsQuery.Id, newsTitle: newsQuery.NewsTitle, newsContent: newsQuery.NewsContent, newsCategory: newsQuery.NewsCategory);
            NewsEditViewModel model     = new NewsEditViewModel(news);

            return(View("EditView", model));

            //var newspart = _orchardServices.ContentManager.Get<NewsPart>(id);
            //if (newspart == null)
            //    return HttpNotFound();

            //var editModel = new NewsEditViewModel() { News = newspart };

            //var model = _orchardServices.ContentManager.BuildEditor(newspart);
            //var editor = Shape.EditorTemplate(TemplateName: "Parts_News_Edit", Model: editModel, Prefix: null);

            //model.Content.Add(editor);

            //return View(model);
        }
Exemplo n.º 25
0
        public ActionResult EditNews(int?Id)
        {
            NewsEditViewModel Model = new NewsEditViewModel();

            try
            {
                if (Id != null && Id > 0)
                {
                    ViewBag.Title = "[[[News Letter Edit]]]";
                }
                else
                {
                    ViewBag.Title = "[[[News Letter Creation]]]";
                }
                ViewBag.NewsId = Id;
                Model          = _newsService.GetNewsEditViewModel(Id);
            }
            catch (Exception e)
            {
                Commons.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Id = " + Id);
            }
            return(View(Model));
        }
Exemplo n.º 26
0
 /// <summary>
 /// 画面が読み込まれた後に呼ばれます
 /// </summary>
 /// <param name="sender">sender</param>
 /// <param name="e">e</param>
 private void ViewLoaded(object sender, RoutedEventArgs e)
 {
     this.viewModel = this.DataContext as NewsEditViewModel;
 }
Exemplo n.º 27
0
        public ActionResult EditNews(NewsEditViewModel Model)
        {
            bool   _success    = false;
            string _Error      = "";
            bool   _isCreation = false;

            try
            {
                if (User.Identity.IsAuthenticated)
                {
                    if (ModelState.IsValid)
                    {
                        Model.PublishDate            = Model.PublishDate.ToUniversalTime();
                        Model.LastModificationUserId = UserSession.UserId;
                        if (Model.TypeId == CommonsConst.NewsType.PublishOnly)
                        {
                            Model.MailSubject       = null;
                            Model.TypeUserMailingId = null;
                        }

                        if (Model.Id <= 0)
                        {
                            _isCreation = true;
                            int NewsId = _newsService.CreateNews(Model);
                            Model.Id = NewsId;
                            if (NewsId > 0)
                            {
                                _success = true;
                            }
                        }
                        else
                        {
                            _success = _newsService.EditNews(Model);
                        }

                        // Scehdule
                        if (_success)
                        {
                            if (!Model.HasScheduledTaskBeenExecuted && Model.ScheduledTaskId.HasValue)
                            {
                                _success = _scheduledTaskService.CancelTaskById(Model.ScheduledTaskId.Value);
                            }

                            if (_success && !Model.HasScheduledTaskBeenExecuted && Model.TypeId != CommonsConst.NewsType.PublishOnly && Model.Active)
                            {
                                if (Model.PublishDate < DateTime.UtcNow)
                                {
                                    Model.PublishDate = DateTime.UtcNow.AddSeconds(5);
                                }

                                _success = _scheduledTaskService.ScheduleNews(Model.Id, Model.PublishDate - DateTime.UtcNow);
                            }
                        }
                    }
                    else
                    {
                        _Error = ModelStateHelper.GetModelErrorsToDisplay(ModelState);
                    }
                }
                else
                {
                    _Error = "[[[You are not logged in.]]]";
                }

                if (!_success && String.IsNullOrWhiteSpace(_Error))
                {
                    _Error = "[[[Error while saving the update.]]]";
                }
            }
            catch (Exception e)
            {
                _success = false;
                Commons.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Id = " + Model.Id);
            }
            return(Json(new { Result = _success, Error = _Error, IsCreation = _isCreation }));
        }