public bool UpdateTopic(int id, [FromBody] CreateTopicCommand request)
        {
            TopicContext       context = HttpContext.RequestServices.GetService(typeof(TopicContext)) as TopicContext;
            UpdateTopicHandler handler = new UpdateTopicHandler(context);

            return(handler.Handle(id, request));
        }
        public bool Handle(CreateTopicCommand request)
        {
            var model = request.Adapt <Model.Topic>();
            int id    = FindCountInDB("select count(*) from Topics where Courses_course_id=" + model.CourseId.ToString()) + 1;

            using (MySqlConnection conn = _context.GetConnection())
            {
                conn.Open();
                string query = string.Format("insert into Topics(topic_id, topic_name, count_of_questions, Courses_course_id) " +
                                             "values('{0}', '{1}', '{2}', '{3}')", id, model.Name, model.CountOfQuestions, model.CourseId);
                MySqlCommand cmd = new MySqlCommand(query, conn);
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    return(false);
                }
                finally
                {
                    conn.CloseAsync();
                }
            }

            return(true);
        }
        public async Task <IActionResult> Create(CreateTopicCommand command)
        {
            if (!ModelState.IsValid)
            {
                throw new ArgumentException("Wrong input parameters");
            }

            var user = await _userManager.FindByNameAsync(User.Identity.Name);

            if (user == null)
            {
                throw new ArgumentException("User not found");
            }

            try
            {
                command.UserId = user.Id;
                var result = await _mediator.Send(command);

                return(RedirectToAction("Details", new { id = result }));
            }
            catch (Exception e)
            {
                _logger.LogError(e, "{Message} {TopicTitle} {UserId} {OptionsCount}",
                                 "Failed at creating topic action", command.Title, command.UserId, command.AddOptionModels.Count);
                return(ErrorView(e.Message, HttpContext.TraceIdentifier));
            }
        }
Пример #4
0
        public bool Handle(int topicId, CreateTopicCommand request)
        {
            var model = request.Adapt <Model.Topic>();

            using (MySqlConnection conn = _context.GetConnection())
            {
                conn.Open();
                string query = string.Format("update Topics set topic_name='{1}', count_of_questions={2}," +
                                             "Courses_course_id={3} where topic_id={0}",
                                             topicId,
                                             model.Name,
                                             model.CountOfQuestions,
                                             model.CourseId);

                MySqlCommand cmd = new MySqlCommand(query, conn);
                try
                {
                    cmd.ExecuteNonQuery();
                }
                catch
                {
                    return(false);
                }
                finally
                {
                    conn.CloseAsync();
                }
            }

            return(true);
        }
Пример #5
0
        public async Task Handler_ShouldAddTopic()
        {
            // Arrange
            var topic = new TopicDTO
            {
                Id   = 7,
                Text = "Topic_test",
            };

            var command = new CreateTopicCommand {
                Model = topic
            };

            // Act
            var handler = new CreateTopicCommand.CreateTopicCommandHandler(Context, Mapper);
            await handler.Handle(command, CancellationToken.None);

            var entity = Context.Topics.Find(topic.Id);

            // Assert
            entity.ShouldNotBeNull();

            entity.Id.ShouldBe(command.Model.Id);
            entity.Text.ShouldBe(command.Model.Text);
        }
Пример #6
0
        public void ShouldRequireMinimumFields()
        {
            var command = new CreateTopicCommand();

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().Throw <ValidationException>();
        }
Пример #7
0
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            var createTopicCommand = new CreateTopicCommand("Billy", "About CQRS", "Are you interested in CQRS?");
            createTopicCommand.Send();

            return View();
        }
Пример #8
0
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            var createTopicCommand = new CreateTopicCommand("Billy", "About CQRS", "Are you interested in CQRS?");
            createTopicCommand.Send();

            return View();
        }
Пример #9
0
        public async Task <IActionResult> Edit(EditPostViewModel model)
        {
            if (ModelState.IsValid)
            {
                /* Update topic of the post.
                 * We use `create` command instead of `update`,
                 * because one topic can relate to multiple posts (one-to-many relations)*/
                var topicDTO = new TopicDTO {
                    Text = model.Topic
                };
                var topicCommand = new CreateTopicCommand {
                    Model = topicDTO
                };

                int topicId;

                try
                {
                    topicId = await _mediator.Send(topicCommand);
                }
                catch (RequestValidationException failures)
                {
                    foreach (var error in failures.Failures)
                    {
                        ModelState.AddModelError(string.Empty, error.Value[0]);
                    }
                    return(View(model));
                }

                // Update post.
                var postDTO = _mapper.Map <EditPostViewModel, PostDTO>(model);
                postDTO.TopicId = topicId;
                var postCommand = new UpdatePostCommand {
                    Model = postDTO
                };

                try
                {
                    await _mediator.Send(postCommand);
                }
                catch (RequestValidationException failures)
                {
                    foreach (var error in failures.Failures)
                    {
                        ModelState.AddModelError(string.Empty, error.Value[0]);
                    }
                    return(View(model));
                }
                return(RedirectToAction("Read", "Posts", new { id = postDTO.Id }));
            }
            return(View(model));
        }
Пример #10
0
        public async Task ShouldCreateTopicWithoutAttachment()
        {
            await SeedTestData();

            var command = new CreateTopicCommand()
            {
                BoardId   = 1,
                Title     = "Test Title",
                Text      = "Test Text",
                Signature = "Test Signature"
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().NotThrow();
        }
Пример #11
0
        public async Task ShouldNotCreateTopicForNonExistentBoard()
        {
            await SeedTestData();

            var command = new CreateTopicCommand()
            {
                BoardId   = 10,
                Title     = "Test Title",
                Text      = "Test Text",
                Signature = "Test Signature"
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().Throw <NotFoundException>();
        }
Пример #12
0
        public void CreateTopic()
        {
            var parentCategory = Substitute.For <Domain.Category>("category", 1, "desc");

            parentCategory.Id.Returns("1");

            var parentForum = Substitute.For <Domain.Forum>(parentCategory, "forum", 1, "desc");

            parentForum.Id.Returns("1");

            var inputParameter = new Domain.Topic(parentForum, "topic subject", "bla bla bla ", Domain.TopicType.Regular);
            var command        = new CreateTopicCommand {
                ForumId = parentForum.Id, Content = inputParameter.Content, State = inputParameter.State, Subject = inputParameter.Subject, Type = inputParameter.Type
            };
            var dto = Substitute.For <ITopicDto>();

            var categoryDatastore = Substitute.For <ICategoryDatastore>();
            var datalayerCategory = Substitute.For <ICategoryDto>();

            datalayerCategory.Id.Returns("1");
            var forumDatastore = Substitute.For <IForumDatastore>();
            var datalayerForum = Substitute.For <IForumDto>();

            datalayerForum.Id.Returns("1");
            categoryDatastore.ReadById(parentCategory.Id).Returns(datalayerCategory);
            forumDatastore.ReadById(parentForum.Id).Returns(datalayerForum);

            var datastore = Substitute.For <ITopicDatastore>();

            datastore.Create(inputParameter).Returns <ITopicDto>(dto);

            var taskDatastore = Substitute.For <ITaskDatastore>();
            var user          = Substitute.For <IPrincipal>();

            CreateTopicCommandHandler handler = new CreateTopicCommandHandler(forumDatastore, datastore, taskDatastore, user);
            GenericValidationCommandHandlerDecorator <CreateTopicCommand> val =
                new GenericValidationCommandHandlerDecorator <CreateTopicCommand>(
                    handler,
                    new List <IValidator <NForum.CQS.Commands.Topics.CreateTopicCommand> > {
                new NForum.CQS.Validators.Topics.CreateTopicValidator(TestUtils.GetInt32IdValidator())
            }
                    );

            val.Execute(command);

            // Let's make sure the Create method on the datastore is actually called once. Nevermind the input argument.
            datastore.ReceivedWithAnyArgs(1).Create(inputParameter);
        }
Пример #13
0
        public async Task ShouldCreateTopicWithAttachment()
        {
            await SeedTestData();

            var command = new CreateTopicCommand()
            {
                BoardId     = 1,
                Title       = "Test Title",
                Text        = "Test Text",
                Signature   = "Test Signature",
                Attachments = new FormFileCollection()
                {
                    new FakeFormFile("TestFiles\\sasha.jpeg", "image/jpeg")
                }
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().NotThrow();
        }
Пример #14
0
        public async Task CreateTopic(Guid topicId, CreateTopicCommand createTopicCommand)
        {
            var document = new Document <TopicDocument>
            {
                Id      = topicId.ToString(),
                Content = new TopicDocument
                {
                    Name        = createTopicCommand.Name,
                    Description = createTopicCommand.Description
                }
            };

            var documentResult = await _topicsBucket.InsertAsync(document);

            if (!documentResult.Success)
            {
                throw documentResult.Exception;
            }
        }
Пример #15
0
        protected void Reg_Top(object sender, EventArgs e)
        {
            section       = new Section();
            section.Id    = Int32.Parse(list_section.SelectedValue);
            section.Name  = list_section.DataTextField;
            topic         = new Topic();
            topic.Name    = name.Value;
            topic.Section = section;
            CreateTopicCommand cmd = new CreateTopicCommand(topic);

            cmd.Execute();
            if (topic.Code == 200)
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "random", "alertme_succ()", true);
            }
            else
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "random", "alertme()", true);
            }
        }
Пример #16
0
        public async Task ShouldNotCreateTopicWithBadAttachments()
        {
            await SeedTestData();

            var command = new CreateTopicCommand()
            {
                BoardId     = 1,
                Title       = "Test Title",
                Text        = "Test Text",
                Signature   = "Test Signature",
                Attachments = new FormFileCollection()
                {
                    new FakeFormFile("TestFiles\\sasha.jpeg", "image/jpeg"),
                    new FakeFormFile("TestFiles\\html.png", "image/png"),
                }
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().Throw <ValidationException>();
        }
        public async Task <IActionResult> Create(CreateTopicCommand topicCommand)
        {
            var validator = new CreateTopicCommandValidator();
            var results   = validator.Validate(topicCommand);

            if (!results.IsValid)
            {
                results.AddToModelState(ModelState, null);
                return(View());
            }

            var newTopic = new Topic
                           (
                topicCommand.Title,
                topicCommand.Description,
                _userManager.GetUserId(User)
                           );

            _context.Topics.Add(newTopic);
            await _context.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
Пример #18
0
        public IHttpActionResult PostTopic([FromBody] CreateTopicCommand command)
        {
            var resposta = _mediator.Send(command);

            return(Ok(resposta));
        }
Пример #19
0
        public async Task <IActionResult> Create(CreatePostViewModel model)
        {
            if (ModelState.IsValid)
            {
                // Add new topic.
                var topicDTO = new TopicDTO {
                    Text = model.Topic
                };
                var topicCommand = new CreateTopicCommand {
                    Model = topicDTO
                };

                int topicId;

                try
                {
                    topicId = await _mediator.Send(topicCommand);
                }
                catch (RequestValidationException failures)
                {
                    foreach (var error in failures.Failures)
                    {
                        ModelState.AddModelError(string.Empty, error.Value[0]);
                    }
                    return(View(model));
                }

                // Get current author.
                var userId = await _identityService.GetUserIdByNameAsync(HttpContext.User.Identity.Name);

                var authorQuery = new GetAuthorByUserIdQuery {
                    UserId = userId
                };
                var author = await _mediator.Send(authorQuery);

                // Create new post.
                var postDTO = new PostDTO
                {
                    Title    = model.Title,
                    Text     = model.Text,
                    AuthorId = author.Id,
                    TopicId  = topicId,
                    Date     = DateTime.Now,
                };

                var postCommand = new CreatePostCommand {
                    Model = postDTO
                };

                int postId;
                try
                {
                    postId = await _mediator.Send(postCommand);
                }
                catch (RequestValidationException failures)
                {
                    foreach (var error in failures.Failures)
                    {
                        ModelState.AddModelError(string.Empty, error.Value[0]);
                    }
                    return(View(model));
                }

                return(RedirectToAction("Read", "Posts", new { id = postId }));
            }

            return(View(model));
        }
Пример #20
0
        public async Task <ActionResult <int> > Post([FromBody] CreateTopicCommand command)
        {
            int result = await _Mediator.Send(command);

            return(Ok(new { result }));
        }
Пример #21
0
 public async Task <int> Create([FromForm] CreateTopicCommand command)
 {
     return(await Mediator.Send(command));
 }