Exemplo n.º 1
0
        public ActionResult Edit(int id, EditTopicViewModel viewModel)
        {
            List <string> errorMessages;

            if (!IsValid(viewModel, out errorMessages))
            {
                return(View("Error", errorMessages));
            }

            var editedTopic = CreateEditedTopic(viewModel);

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

            try
            {
                _dbContext.Update(editedTopic);
                _dbContext.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                return(View("Error", new List <string> {
                    "Unable to save changes."
                }));
            }

            ViewData["Message"]   = "The topic is successfully edited.";
            ViewData["SectionId"] = viewModel.SectionId;

            return(View("Success"));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Edit(EditTopicViewModel model)
        {
            if (ModelState.IsValid && model.Questions.Count != 0)
            {
                Topic topic = await _db.Topics.FindAsync(model.Id);

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

                topic.Name = model.Name;

                var listQuestions = _db.Questions.Where(x => x.TopicId == topic.Id).ToList();
                _db.Questions.RemoveRange(listQuestions);
                foreach (var item in model.Questions)
                {
                    Question question = new Question()
                    {
                        Id             = Guid.NewGuid().ToString(),
                        QuestionString = item.QuestionString,
                        AnswerString   = item.AnswerString,
                        Topic          = topic,
                        TopicId        = topic.Id
                    };
                    await _db.Questions.AddAsync(question);
                }

                await _db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Delete(int id, bool?saveChangesError = false)
        {
            var topic = await this.topicService.GetById(id);

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

            var topicToDelete = new EditTopicViewModel()
            {
                Id              = topic.Id,
                Title           = topic.Title,
                Description     = topic.Description,
                StateOfApproval = topic.StateOfTopic,
                SubjectId       = topic.SubjectId
            };

            if (saveChangesError.GetValueOrDefault())
            {
                ViewData["ErrorMessage"] =
                    "Delete failed. Try again, and if the problem persists " +
                    "see your system administrator.";
            }

            return(View(topicToDelete));
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Edit(string id)
        {
            Topic topic = await _db.Topics.FindAsync(id);

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

            var questions = _db.Questions.Where(x => x.TopicId == topic.Id).ToList();
            List <QuestionsViewModel> questionsViewModel = new List <QuestionsViewModel>();

            foreach (var item in questions)
            {
                questionsViewModel.Add(new QuestionsViewModel()
                {
                    QuestionString = item.QuestionString,
                    AnswerString   = item.AnswerString
                });
            }

            EditTopicViewModel viewModel = new EditTopicViewModel()
            {
                Name      = topic.Name,
                Questions = questionsViewModel
            };

            return(View(viewModel));
        }
Exemplo n.º 5
0
        public virtual ActionResult EditTopic(string id)
        {
            EditTopicViewModel viewModel = this.forumStorageReader.GetEditTopicViewModel(id, this.User.Identity.Name);

            viewModel.AllUserNames = this.GetSelectListOfAllUsernamesExceptCurrent();
            return(this.View(viewModel));
        }
Exemplo n.º 6
0
        private Topic UpdateTopic(EditTopicViewModel viewModel)
        {
            var topic = this.ravenSession.Load <Topic>(viewModel.Id);

            topic.Title = viewModel.Title;
            topic.PostsInOrder.First().Text = viewModel.Text;
            topic.ExcludedUserNames = viewModel.ExcludedUserNames ?? new List <string>();

            if (viewModel.Poll.IsEmpty())
            {
                topic.Poll = null;
            }
            else
            {
                if (topic.Poll == null)
                {
                    topic.Poll = viewModel.Poll.ToNewPoll();
                }
                else
                {
                    viewModel.Poll.UpdatePoll(topic.Poll);
                }
            }

            topic.IsWiki          = viewModel.IsWiki;
            topic.DisplayPriority = viewModel.IsSticky ? TopicDisplayPriority.Sticky : TopicDisplayPriority.None;
            return(topic);
        }
Exemplo n.º 7
0
        public EditTopicViewModel GetEditTopicViewModel(string id, string currentUsername)
        {
            Topic topic = this.ravenSession.Load <Topic>(id);

            if (topic.ExcludedUserNames.Any(u => u.Equals(currentUsername, StringComparison.OrdinalIgnoreCase)))
            {
                throw new UnauthorizedAccessException($"{currentUsername} is not allowed to access {topic.Title}");
            }

            var viewModel = new EditTopicViewModel
            {
                ExcludedUserNames = topic.ExcludedUserNames ?? new List <string>(),
                Title             = topic.Title,
                Text     = topic.PostsInOrder.First().Text,
                IsSticky = topic.DisplayPriority == TopicDisplayPriority.Sticky,
                IsWiki   = topic.IsWiki,
                Id       = topic.Id
            };

            if (topic.Poll != null)
            {
                viewModel.Poll = new EditPollViewModel {
                    Answers = topic.Poll?.Answers?.Select(a => new EditPollAnswerViewModel {
                        Id = a.Id, Text = a.Text
                    }).ToList(), Question = topic.Poll?.Question
                };
            }

            return(viewModel);
        }
Exemplo n.º 8
0
        private Topic CreateTopic(EditTopicViewModel viewModel, string currentUsername)
        {
            var topic = new Topic
            {
                ExcludedUserNames = viewModel.ExcludedUserNames ?? new List <string>(),
                Title             = viewModel.Title,
                IsWiki            = viewModel.IsWiki,
                Posts             =
                    new List <Post>
                {
                    new Post
                    {
                        AuthorName   = currentUsername,
                        CreatedAt    = DateTime.UtcNow,
                        IndexInTopic = 0,
                        Text         = viewModel.Text,
                    }
                }
            };

            topic.DisplayPriority = viewModel.IsSticky ? TopicDisplayPriority.Sticky : TopicDisplayPriority.None;

            if (!viewModel.Poll.IsEmpty())
            {
                topic.Poll = viewModel.Poll.ToNewPoll();
            }

            this.ravenSession.Store(topic);
            return(topic);
        }
Exemplo n.º 9
0
        public ActionResult Edit(int id, EditTopicViewModel model)
        {
            try
            {
                var repository = new TopicRepository(context);
                if (model.Name != model.NombreAnterior)
                {
                    var existeNombre = repository.Query(x => x.Name == model.Name && x.Id != model.Id).Count > 0;
                    if (existeNombre)
                    {
                        ModelState.AddModelError("Name", "El nombre ya está ocupado por otro tópico.");
                        return(View(model));
                    }
                }
                else
                {
                    ModelState.Remove("Nombre");
                }

                if (ModelState.IsValid)
                {
                    var topic = MapperHelper.Map <Topic>(model);
                    repository.Update(topic);
                    context.SaveChanges();
                }
                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Exemplo n.º 10
0
 public EditTopicPage(EditTopicViewModel vm)
 {
     InitializeComponent();
     this.BindingContext = new EditTopicViewModel(this);
     ViewModel           = vm;
     this.BindingContext = ViewModel;
 }
Exemplo n.º 11
0
        private void CreateTopics()
        {
            for (int i = 0; i < 500; i++)
            {
                var topic = new EditTopicViewModel
                {
                    Text  = GetRandomText(i),
                    Title = GetRandomTopicTitle(i)
                };

                if (i % 5 == 0)
                {
                    topic.Poll = new EditPollViewModel {
                        Question = GetRandomPollQuestion(), Answers = GetRandomPollAnswers()
                    };
                }

                string topicId = this.forumStorageWriter.SaveTopic(topic, GetRandomUser());

                for (int j = 0; j < i; j++)
                {
                    this.forumStorageWriter.AddReply(new ReplyViewModel {
                        Text = GetRandomText(j), TopicId = topicId
                    }, GetRandomUser());
                }
            }
        }
Exemplo n.º 12
0
        public ActionResult Edit(EditTopicViewModel model)
        {
            if (ModelState.IsValid)
            {
                Topic topic = topicRepository.TopicsRepository
                              .Where(e => e.TitleID == model.TopicID)
                              .FirstOrDefault();

                if (topic != null)
                {
                    topic.Title = model.Title;
                    topic.Text  = model.Text;
                    topicRepository.Update(topic);
                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(View("Error", new string[] { "Wybrany temat nie istnieje!" }));
                }
            }
            else
            {
                return(View("Error", new string[] { "Model jest nieprawidłowy!" }));
            }
        }
Exemplo n.º 13
0
        public ActionResult Create(int sectionId)
        {
            var vm = new EditTopicViewModel();

            vm.SectionId = sectionId.ToString();

            return(View(vm));
        }
Exemplo n.º 14
0
        public async Task <IActionResult> Create([Bind("Title, Body, SectionId, Accessibility")] EditTopicViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var user = _userManager.GetUserAsync(User).Result;

                int sectionId = default;

                try
                {
                    sectionId = Convert.ToInt32(viewModel.SectionId);
                }
                catch (Exception)
                {
                    return(BadRequest());
                }

                var section = _dbContext.Sections.FirstOrDefault(s => s.Id == sectionId);

                if (section == null)
                {
                    return(Error());
                }

                if (section.Topics == null)
                {
                    section.Topics = new List <Topic>();
                }

                var newTopic = new Topic
                {
                    Title         = viewModel.Title,
                    Body          = viewModel.Body,
                    Created       = DateTime.Now,
                    AuthorId      = user.Id,
                    Author        = user,
                    SectionId     = section.Id,
                    Section       = section,
                    Accessibility = (Accessibility)Enum.Parse(typeof(Accessibility), viewModel.Accessibility)
                };

                newTopic = _dbContext.Topics.Add(newTopic).Entity;
                await _dbContext.SaveChangesAsync();

                user.Topics.Add(newTopic);

                section.Topics.ToList().Add(newTopic);

                await _dbContext.SaveChangesAsync();

                ViewData["Message"]   = $"Topic `{viewModel.Title}` successfully created.";
                ViewData["SectionId"] = viewModel.SectionId;

                return(View("Success"));
            }

            return(View(viewModel));
        }
Exemplo n.º 15
0
        private bool IsValid(EditTopicViewModel viewModel, out List <string> errorMessages)
        {
            bool isValid = true;

            errorMessages = new List <string>();

            var topic = _dbContext.Topics /*.AsNoTracking()*/.FirstOrDefault(t => t.Id == viewModel.Id);

            if (topic == null)
            {
                errorMessages.Add("Topic not found.");
                isValid = false;
            }

            var vm = new TopicViewModel(topic, Request);

            topic.Section = _dbContext.Sections.FirstOrDefault(s => s.Id == topic.SectionId);
            SetAccessibilityParams(
                vm,
                User,
                IsOwner(User, topic),
                _dbContext.SectionModerators.Where(sm => sm.SectionId.Equals(topic.SectionId)).Select(sm => sm.Moderator).ToList(),
                topic.Accessibility);

            if (!vm.CanEditTopic)
            {
                errorMessages.Add("No editing rights.");
                return(false); // There is no point in validating the next data.
            }

            if (string.IsNullOrEmpty(viewModel.Title))
            {
                errorMessages.Add("Title required.");
                isValid = false;
            }

            try
            {
                int sectionId = Convert.ToInt32(viewModel.SectionId);

                if (_dbContext.Sections.FirstOrDefault(s => s.Id == sectionId) == null)
                {
                    errorMessages.Add("Invalid section id.");
                    isValid = false;
                }
            }
            catch
            {
                errorMessages.Add("Invalid section id.");
                isValid = false;
            }

            topic.Section = _dbContext.Sections.Where(s => s.Id == topic.SectionId).FirstOrDefault();

            return(isValid);
        }
Exemplo n.º 16
0
        public ActionResult EditTopic(int id)
        {
            if (id < 1)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            EditTopicViewModel viewModel = this.service.GetEditViewModel(id);

            return(this.View(viewModel));
        }
Exemplo n.º 17
0
        public ActionResult Edit()
        {
            EditTopicViewModel model = new EditTopicViewModel()
            {
                Topics     = adminService.GetAllTopic(),
                MasterPage = UpdateMasterPageData()
            };

            return(View("~/Views/Admin/EditTopic.cshtml", model));
        }
Exemplo n.º 18
0
        public IActionResult EditPost(EditTopicViewModel input, int id)
        {
            this.topicService.Edit(input, id);

            return(RedirectToAction("Details", new RouteValueDictionary(new
            {
                controller = "Subjects",
                action = "Details",
                Id = input.SubjectId
            })));
        }
 public int SaveTopic(EditTopicViewModel editTopicViewModel)
 {
     if (editTopicViewModel.Id == 0)
     {
         return(AddTopic(editTopicViewModel));
     }
     else
     {
         return(UpdateTopic(editTopicViewModel));
     }
 }
Exemplo n.º 20
0
        public EditTopicViewModel GetEditViewModel(int id)
        {
            Topic topic = this.Context.Topics.Find(id);

            if (topic == null)
            {
                throw new ArgumentNullException(nameof(id), "There is no Topic with such Id.");;
            }
            EditTopicViewModel viewModel = Mapper.Instance.Map <EditTopicViewModel>(topic);

            return(viewModel);
        }
Exemplo n.º 21
0
 public IActionResult SaveTopic(EditTopicViewModel editTopicViewModel)
 {
     try
     {
         _categoriesRepository.SaveTopic(editTopicViewModel);
         TempData["success"] = "Temat został zapisany.";
     }
     catch (MrRollException)
     {
         TempData["error"] = "Operacja zakończona niepowodzeniem.";
     }
     return(RedirectToAction("Index"));
 }
Exemplo n.º 22
0
        public async Task <IActionResult> Edit(int id, EditTopicViewModel viewmodel)
        {
            if (id != viewmodel.Topic.TopicId)
            {
                return(NotFound());
            }

            ModelState.Remove("Topic.User");
            ModelState.Remove("Topic.UserId");


            if (ModelState.IsValid)
            {
                try
                {
                    Topic topic = await _context.Topic.SingleOrDefaultAsync(t => t.TopicId == id);

                    topic.Title           = viewmodel.Topic.Title;
                    topic.Content         = viewmodel.Topic.Content;
                    topic.TopicCategoryId = viewmodel.Topic.TopicCategoryId;
                    topic.HouseExclusive  = viewmodel.Topic.HouseExclusive;

                    _context.Update(topic);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TopicExists(viewmodel.Topic.TopicId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction("Details", new { id = viewmodel.Topic.TopicId }));
            }

            List <TopicCategory> topicCategories = await _context.TopicCategory.ToListAsync();

            viewmodel.CategoryOptions = topicCategories
                                        .Select(tc => new SelectListItem
            {
                Text  = tc.Label,
                Value = tc.TopicCategoryId.ToString()
            })
                                        .ToList();
            return(View(viewmodel));
        }
Exemplo n.º 23
0
        public void Edit(EditTopicViewModel input, int id)
        {
            // Try to make it async
            var topicToUpdate = this.GetById(id).Result;

            // Fix error handling (but in controller)
            // Think about asynchronously updating the database

            topicToUpdate.Title        = input.Title;
            topicToUpdate.Description  = input.Description;
            topicToUpdate.StateOfTopic = input.StateOfApproval;

            this.context.Topics.Update(topicToUpdate);
            this.context.SaveChanges();
        }
Exemplo n.º 24
0
        public async Task <IActionResult> Edit(long id, [FromBody] EditTopicViewModel vm)
        {
            var topic = await _topicsRepository.GetByIdAsync(id);

            if (topic != null)
            {
                topic.Title      = vm.Title;
                topic.Content    = vm.Content;
                topic.CategoryId = vm.CategoryId;

                await _topicsRepository.UpdateAsync(topic);

                return(Ok());
            }

            return(BadRequest());
        }
Exemplo n.º 25
0
        private Topic CreateEditedTopic(EditTopicViewModel viewModel)
        {
            var topic = _dbContext.Topics.FirstOrDefault(t => t.Id.Equals(viewModel.Id));

            if (topic == null)
            {
                return(null);
            }

            topic.Title         = viewModel.Title;
            topic.Body          = viewModel.Body;
            topic.Editor        = _userManager.GetUserAsync(User).Result;
            topic.Edited        = DateTime.Now;
            topic.Accessibility = (Accessibility)Enum.Parse(typeof(Accessibility), viewModel.Accessibility);

            return(topic);
        }
Exemplo n.º 26
0
        public virtual ActionResult EditTopic(EditTopicViewModel viewModel)
        {
            if (!this.ModelState.IsValid)
            {
                viewModel.AllUserNames = this.GetSelectListOfAllUsernamesExceptCurrent();
                return(this.View(MVC.Forum.Views.EditTopic, viewModel));
            }

            string topicId = this.forumStorageWriter.SaveTopic(viewModel, this.User.Identity.Name);

            if (string.IsNullOrEmpty(viewModel.Id))
            {
                this.forumNotificationSender.SendNewTopicNotifications(topicId);
            }

            return(this.RedirectToAction(MVC.Forum.Topic().AddRouteValues(new { id = topicId, name = UrlEncoder.ToFriendlyUrl(viewModel.Title) })));
        }
 private int UpdateTopic(EditTopicViewModel editTopicViewModel)
 {
     using (var client = new HttpClient())
     {
         try
         {
             client.BaseAddress = new Uri("http://jsswirus.nazwa.pl:8080/mrroll-1.0/");
             var httpContent = ToJsonHttpContent(new { name = editTopicViewModel.Name });
             var response    = client.PutAsync($"rest/v1/categories/{editTopicViewModel.CategoryId}/topics/{editTopicViewModel.Id}", httpContent).Result;
             response.EnsureSuccessStatusCode();
             return(editTopicViewModel.Id);
         }
         catch (HttpRequestException)
         {
             throw new MrRollException();
         }
     }
 }
Exemplo n.º 28
0
        public string SaveTopic(EditTopicViewModel viewModel, string currentUsername)
        {
            if (viewModel.ExcludedUserNames != null && viewModel.ExcludedUserNames.Contains(currentUsername))
            {
                viewModel.ExcludedUserNames.Remove(currentUsername);
            }

            Topic topic;

            if (viewModel.Id != null)
            {
                topic = this.UpdateTopic(viewModel);
            }
            else
            {
                topic = this.CreateTopic(viewModel, currentUsername);
            }

            return(topic.Id);
        }
Exemplo n.º 29
0
        public async Task <IActionResult> Edit(int id)
        {
            var topic = await this.topicService.GetById(id);

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

            var topicToEdit = new EditTopicViewModel()
            {
                Id              = topic.Id,
                Title           = topic.Title,
                Description     = topic.Description,
                StateOfApproval = topic.StateOfTopic,
                SubjectId       = topic.SubjectId
            };

            return(View(topicToEdit));
        }
        private int AddTopic(EditTopicViewModel editTopicViewModel)
        {
            using (var client = new HttpClient())
            {
                try
                {
                    client.BaseAddress = new Uri("http://jsswirus.nazwa.pl:8080/mrroll-1.0/");
                    var httpContent = ToJsonHttpContent(new { name = editTopicViewModel.Name });
                    var response    = client.PostAsync($"rest/v1/categories/{editTopicViewModel.CategoryId}/topics/", httpContent).Result;
                    response.EnsureSuccessStatusCode();

                    var stringResult = response.Content.ReadAsStringAsync().Result;
                    var result       = JsonConvert.DeserializeObject <Dictionary <string, string> >(stringResult);
                    return(Int32.Parse(result["topicID"]));
                }
                catch (HttpRequestException)
                {
                    throw new MrRollException();
                }
            }
        }