public void Create_Post_Return_Post()
        {
            var id    = Guid.NewGuid().ToString();
            var model = _postRepository.Create(new Post()
            {
                Id = id, Title = "Something", Content = "Something", CreatedDate = DateTime.Today
            });

            Assert.IsTrue(model.Id == id);
        }
Example #2
0
        public void Create_Increases_Count()
        {
            underTest.Create(new Post()
            {
                Title = "Foo"
            });

            var count = underTest.Count();

            Assert.Equal(1, count);
        }
Example #3
0
        public void Create_Increases_Count()
        {
            underTest.Create(new PostModel()
            {
                Title = "This Is Great"
            });

            var count = underTest.Count();

            Assert.Equal(4, count);
        }
Example #4
0
        public void GivenANewPost_WhenIAddThePostToTheDatabase_AndTheBlogDoesNotExist_ThenThePostIsNotAdded()
        {
            _userRepository.Create(_user1);
            var post = new Post
            {
                Title    = "Title",
                BlogPost = "Post",
                Edited   = DateTime.UtcNow,
                Posted   = DateTime.UtcNow,
                BlogId   = 10
            };

            Assert.Throws <DbUpdateException>(() => _postRepository.Create(post));
        }
Example #5
0
        public void AddPost(Post post)
        {
            post.Score     = 0;
            post.Timestamp = (int)ConvertToUnixTimestamp(DateTime.Now);

            postRepo.Create(post);
        }
Example #6
0
 public void CreateItem(Post post)
 {
     if (post != null)
     {
         _repository.Create(post);
     }
 }
Example #7
0
 public void GivenABlogEntry_WhenThenFileIsCreated_AndTheFileIsNotFound_ThenTheCorrectExceptionIsThrown()
 {
     _fileInfo.Setup(f => f.Create()).Throws(new IOException());
     var entry = new Post { Title = "title", EntryAddedDate = new DateTime(1990, 1, 1) };
     var repository = new PostRepository(Path, _fileInfoFactory.Object, null);
     Assert.Throws<RepositoryException>(() => repository.Create(entry));
 }
Example #8
0
        public ActionResult Create(Post post)
        {
            PostRepository postRepository = new PostRepository();

            postRepository.Create(post);
            return(RedirectToAction("Index"));
        }
Example #9
0
        public async Task <IActionResult> Create([Bind("PostId,Title,Text,TopicId")] Post post, IFormFile uploadedFile)
        {
            if (ModelState.IsValid)
            {
                if (uploadedFile != null && uploadedFile != null && uploadedFile.ContentType.ToLower().Contains("image"))
                {
                    post.Image = await _imageService.SaveImageAsync(uploadedFile, 1);
                }
                else
                {
                    ModelState.AddModelError("Image", "Некорректный формат");
                    ViewData["topics"] = await _topicRepository.FindAll();

                    return(View(post));
                }
                var user = await _userManager.FindByNameAsync(User.Identity.Name);

                post.User     = user;
                post.DateTime = DateTime.Now;
                post.Topic    = await _topicRepository.FindAsyncById(post.TopicId);

                await _postRepository.Create(post);

                return(RedirectPermanent("~/Posts/Index"));
            }
            return(View(post));
        }
Example #10
0
 public void CreatePost([FromBody] PostModel value)
 {
     try
     {
         _repository.Create(value);
     }
     catch (Exception e)
     {
     }
 }
        public async Task <ActionResult> Post(Post model)
        {
            try {
                await PostRepository.Create(model);

                return(Ok());
            }
            catch (Exception e) {
                return(StatusCode(500, e));
            }
        }
 public ActionResult <Post> Post([FromBody] Post data)
 {
     try
     {
         return(Ok(_Repo.Create(data)));
     }
     catch (Exception e)
     {
         return(BadRequest(e.Message));
     }
 }
Example #13
0
        public async Task Create(PostViewModel entity)
        {
            Post post = new Post();

            post.Id       = entity.Id;
            post.Title    = entity.Title;
            post.Content  = entity.Content;
            post.Author   = entity.Author;
            post.Likes    = entity.Likes;
            post.Comments = entity.Comments;
            await postRepository.Create(post);
        }
Example #14
0
        public IActionResult Publish([FromBody] JObject _data)
        {
            //мапинг входящих параметров их json объекта
            string _title     = _data["title"].ToObject <string>();
            string _preview   = _data["preview"].ToObject <string>();
            string _content   = _data["content"].ToObject <string>();
            string authorGuid = _account.Claims().FirstOrDefault(x => x.Type == "g").Value;

            //генерация нового гуида для статьи
            string      _post_guid = Guid.NewGuid().ToString();
            CategoryDTO _category  = _data["category"].ToObject <CategoryDTO>();

            //проверка на существование категории
            if (_category_repository.FindById(_category.id) is null)
            {
                throw new HumanException("Категория не существует.");
            }

            //проверка на запись в бд (1 - успешно)
            if (_post_repo.Create(new PostEntityCreate(_post_guid, _title, _preview, _content, authorGuid)) == 0)
            {
                throw new HumanException("К сожалению, статья не была добавлена. Повторите попытку ещё раз.");
            }

            //запись в таблицу связей (категория - пост)
            if (_category_post_repository.Create(new CategoryPostEntityCreate(Guid.NewGuid().ToString(), _category.id, _post_guid)) == 0)
            {
                throw new HumanException("К сожалению, категороия не была добавлена. Повторите попытку ещё раз.");
            }


            return(Ok(new { message = "Пост успешно опубликован." }));

            //валидация тегов
            //List<TagDTO> tags = _data["tags"].ToObject<List<TagDTO>>();
            //if (tags.Count == 0) throw new HumanException("Необходимо указать как минимум один тэг для статьи.");


            //добавление тегов к посту
            //tags.ForEach(v =>
            //{
            //    if (String.IsNullOrEmpty(v.id))
            //    {

            //        string _tag_guid = Guid.NewGuid().ToString();
            //        _tag_repo.Create(new TagEntityCreate(_tag_guid, v.title, ""));
            //        v.id = _tag_guid;
            //    }
            //    string _post_tag_guid = Guid.NewGuid().ToString();
            //    _post_tag_repo.Create(new PostTagEntityCreate(_post_tag_guid, _post_guid, v.id));
            //});
        }
        public ActionResult Create([Bind(Include = "Id,Subject,Context,Created,TopicID,UserID,StatusID")] Post post)
        {
            if (ModelState.IsValid)
            {
                repPost.Create(post);
                return(RedirectToAction("Index"));
            }

            ViewBag.StatusID = new SelectList(db.Status, "Id", "Name", post.StatusID);
            ViewBag.TopicID  = new SelectList(db.Topics, "TopicId", "Subject", post.TopicID);
            ViewBag.UserID   = new SelectList(db.Users, "Id", "UserName", post.UserID);
            return(View(post));
        }
        public IActionResult Create(Post post)
        {
            UserRepository userRepo = new UserRepository();

            if (post != null && userRepo.ReadById(post.UserId) != null)
            {
                var response = repository.Create(post);
                return(Ok(response));
            }
            else
            {
                return(BadRequest());
            }
        }
Example #17
0
        public int Create(PostViewModel postViewModel, Distributor distributor)
        {
            try
            {
                var postToCreate = new Post();
                MapViewModelToModel(postViewModel, ref postToCreate);

                return(_postRepository.Create(postToCreate));
            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message);
            }
        }
Example #18
0
        public async void TestCreate()
        {
            var Posts = await repository.FindAll();

            Assert.NotNull(Posts);
            Assert.Equal(4, Posts.Count);
            await repository.Create(new Post { DateTime = DateTime.Now, Title = "First", Text = "Test3", Topic = new Topic {
                                                   TopicName = "Test6"
                                               } });

            Posts = await repository.FindAll();

            Assert.NotNull(Posts);
            Assert.Equal(5, Posts.Count);
        }
Example #19
0
 public void GivenABlogEntry_WhenTheEntryIsWrittenToAFile_ThenTheCorrectJsonIsWritten()
 {
     var stream = new MemoryStream();
     _fileInfo.Setup(f => f.Create()).Returns(stream);
     var entry = new Post { Title = "title", EntryAddedDate = new DateTime(1990, 1, 1), EntryUpdateDate = new DateTime(1991, 2, 2), Body = "post" };
     var repository = new PostRepository(Path, _fileInfoFactory.Object, null);
     repository.Create(entry);
     var data = stream.ToArray();
     var json = Encoding.UTF8.GetString(data);
     var savedentry = JsonSerializer.Deserialize<Post>(json);
     savedentry.Title.Should().Be("title");
     savedentry.Body.Should().Be("post");
     savedentry.EntryAddedDate.Should().Be(new DateTime(1990, 1, 1));
     savedentry.EntryUpdateDate.Should().Be(new DateTime(1991, 2, 2));
 }
        public Post AddPost(Post post, string user)
        {
            post.TimeStamp = Stopwatch.GetTimestamp();
            if (userrepo.Read(user) != null)
            {
                post.UserId = userrepo.Read(user).UserId;
            }
            else
            {
                post.Owner = null;
            }


            return(postrepo.Create(post));
        }
Example #21
0
        private void Save(PostModel model)
        {
            var post = new Post
            {
                Title   = model.Title,
                Content = model.Content.Replace(Environment.NewLine, "<br />")
            };

            _postRepository.Create(post);
            model.Id = post.Id;

            var tags = model.Tags.Split(',');

            AddTagsToPost(post.Id, tags);
        }
Example #22
0
        public void Multiple_Operations()
        {
            InitializeInMemoryDbContext(options =>
            {
                using (var uowManager = new EfCoreUnitOfWorkManager())
                {
                    var r1 = new PostRepository(new BloggingDbContext(options));
                    uowManager.Register(new EfCoreUnitOfWork(
                                            ((IRepositoryWithDbContext)r1).GetDbContext()
                                            ));

                    var r2 = new PostRepository(new BloggingDbContext(options));
                    uowManager.Register(new EfCoreUnitOfWork(
                                            ((IRepositoryWithDbContext)r2).GetDbContext()
                                            ));

                    var r3 = new EfCoreRepositoryBase <BloggingDbContext, Comment>(new BloggingDbContext(options));
                    uowManager.Register(new EfCoreUnitOfWork(
                                            ((IRepositoryWithDbContext)r3).GetDbContext()
                                            ));

                    var p1 = new Post
                    {
                        Title = "r1 新增 Post"
                    };
                    r1.Create(p1);

                    var p2   = r2.All().First();
                    p2.Title = "r2 修改 Post";
                    r2.Modify(p2);

                    var c3Id = r3.All().First().Id;
                    r3.Remove(c3Id);

                    uowManager.Commit();

                    var r4 = new PostRepository(new BloggingDbContext(options));

                    r4.All().Count().ShouldBe(3);
                    r4.Single(s => s.Id.Equals(p2.Id)).Title.ShouldBe("r2 修改 Post");

                    var r5 = new EfCoreRepositoryBase <BloggingDbContext, Comment>(new BloggingDbContext(options));
                    r5.SingleOrDefault(s => s.Id == c3Id).ShouldBeNull();
                }
            });
        }
Example #23
0
        public void PostRepositoryInsertsTest()
        {
            //  Setup
            Post testPost = new Post()
            {
                Id = ObjectId.GenerateNewId().ToString(), Text = "UnitTestGeneratedPost"
            };

            //  Execute Tests
            postRepository_.Create(testPost);
            Post insertedPost = postRepository_.Get(testPost.Id);

            //  Assert Results
            Assert.IsNotNull(insertedPost);
            Assert.AreEqual(insertedPost.Id, testPost.Id);
            Assert.AreEqual(insertedPost.Text, testPost.Text);
        }
        public void Create(PostSendViewModel postSendViewModel)
        {
            //var post = Mapper.Map<PostSendViewModel, Post>(postSendViewModel);
            Post post = new Post();

            post.Author      = postSendViewModel.Author;
            post.Title       = postSendViewModel.Title;
            post.Description = postSendViewModel.Description;



            if (post == null)
            {
                return;
            }
            post.DateTime = DateTime.Now;
            _postRepository.Create(post);
        }
Example #25
0
        public void Create_Inserts_New_Post()
        {
            // Arrange
            var repository = new PostRepository(new BlogAppSqlServerContext(DbConnectionString), _mapper);

            var postToCreate = new PostDto()
            {
                BlogId  = 1,
                Title   = "Some fake title",
                Content = "Some fake content"
            };

            // Act
            repository.Create(postToCreate);

            // Assert
            Assert.True(postToCreate.Id > 0);
        }
Example #26
0
        public ActionResult Create(Post post)
        {
            if (!ModelState.IsValid)
            {
                return(View(post));
            }

            post.Fecha = DateTime.UtcNow;
            _postRepository.Create(post);

            if (Request.IsAjaxRequest())
            {
                return(Json(new { Result = true, Url = Url.Action("Index") }));
            }
            else
            {
                return(RedirectToAction("Index"));
            }
        }
Example #27
0
        public async Task <IActionResult> Reply(ReplyViewModel vm)
        {
            User user = await _userManager.GetUserAsync(HttpContext.User);

            Post post = new Post()
            {
                Contents = vm.Contents,
                Topic    = await _topicRepository.GetById(vm.Topic.Id),
                User     = user,
                Created  = DateTime.Now,
                Updated  = DateTime.Now
            };

            await _postRepository.Create(post);

            await _userRepository.CountPost(user.Id);

            return(RedirectToAction("Topic", new { id = vm.Topic.Id }));
        }
Example #28
0
        public async Task <IHttpActionResult> Create([FromBody] Post model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                log.Info(new MDCSet(this.ControllerContext.RouteData));
                await _entityRepo.Create(model);

                return(Ok("Registro creado exitosamente!"));
            }
            catch (Exception e)
            {
                log.Error(new MDCSet(this.ControllerContext.RouteData), e);
                return(InternalServerError(e));
            }
        }
Example #29
0
        public async Task <IActionResult> Post(BlogCreationModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }
                var user = await _userManager.GetUserAsync(User);

                Post post = new Post
                {
                    Permitted        = true,
                    Title            = model.Title,
                    ShortDescription = model.ShortDescription,
                    Type             = model.Type,
                    PostContent      = new PostContent
                    {
                        Content = model.Content
                    },
                    UserId          = user.Id,
                    PostLikeAndView = new PostLikeAndView(),
                };
                post = _postRepository.Create(post);
                if (post != null)
                {
                    List <int> uPosts = user.PostsId == null ? new List <int>() : user.PostsId.ToList();
                    uPosts.Add(post.Id);
                    user.PostsId = uPosts.ToArray();
                    await _userManager.UpdateAsync(user);

                    return(RedirectToAction("Item", new { id = post.Id }));
                }
                return(View(model));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(View(model));
            }
        }
Example #30
0
        private static void CreatePost(string title)
        {
            var postRepository = new PostRepository();
            var categoryRepository = new CategoryRepository();
            var commentRepository = new CommentRepository();

            var post = new Post
                           {
                               Title = title,
                               PostedDate = DateTime.Now,
                               Contents = "This is just a simple test post..."
                           };

            for (int i = 0; i < 10; i++)
            {
                var category = new Category
                                   {
                                       Name = "Category " + i,
                                       CreatedDate = DateTime.Now,
                                       Description = "Just a test..."
                                   };

                post.AddCategory(category);
                categoryRepository.Create(category);
            }

            for (int i = 0; i < 20; i++)
            {
                var comment = new Comment
                                  {
                                      PostedDate = DateTime.Now,
                                      Author = "Author " + i,
                                      Text = "testing..."
                                  };

                post.AddComment(comment);
                commentRepository.Create(comment);
            }

            postRepository.Create(post);
        }
        public async Task Index_ReturnsAViewResult_WithAListOfPosts()
        {
            // Arrange
            var options = new DbContextOptionsBuilder <BlogDbContext>()
                          .UseInMemoryDatabase(databaseName: "SomeDatabase")
                          .Options;
            var context    = new BlogDbContext(options);
            var repository = new PostRepository(context);

            foreach (var count in GetTestPosts())
            {
                await repository.Create(count);
            }
            // Act
            var resultPosts = await repository.GetAll();

            var resultList = new List <Post>(resultPosts);

            // Assert
            Assert.Equal(2, resultList.Count);
        }
Example #32
0
        public void CreateCommentModelTest()
        {
            //Arrange
            var postDetailModel = new PostDetailModel()
            {
                Title    = "NewTitle",
                Comments = new List <CommentDetailModel>(5)
            };

            var postListModel = new PostListModel()
            {
                Title = "NewTitle"
            };

            var commentModel = new CommentDetailModel()
            {
                CreationTime = new DateTime(),
                BelongsTo    = postListModel,
            };
            var userDetailModel = new UserDetailModel()
            {
                Name     = "NewUser",
                Email    = "*****@*****.**",
                Password = "******"
            };

            //Act
            var returnedUserModel          = _userRepository.Create(userDetailModel);
            var returnedPostDetailModel    = _postRepository.Create(postDetailModel, returnedUserModel);
            var returnedCommentDetailModel = _commentRepository.Create(commentModel, returnedUserModel, returnedPostDetailModel);

            //Assert
            Assert.NotNull(returnedCommentDetailModel);

            //Teardown
            _commentRepository.Delete(returnedCommentDetailModel);
            _postRepository.Delete(returnedPostDetailModel);
            _userRepository.Delete(returnedUserModel);
        }
Example #33
0
        public async Task Create_PostIsCreated_ReturnsPostWithExpectedValues()
        {
            var create = new CreatePost();
            var post   = new Post {
                Content = "Content"
            };
            var forum = new Forum {
                Id = 1
            };

            A.CallTo(() => User.Exists()).Returns(true);
            A.CallTo(() => ForumService.Read(forum.Id)).Returns(forum);
            A.CallTo(() => Mapper.Map <Post>(create)).Returns(post);
            A.CallTo(() => User.Id()).Returns("User Id");

            var result = await PostService.Create(1, create);

            Assert.Equal("User Id", result.UserId);
            A.CallTo(() => PostRepository.Create(A <Post> .That.Matches(p =>
                                                                        p.Content == "Content" &&
                                                                        p.UserId == "User Id" &&
                                                                        p.Forum.Id == forum.Id
                                                                        ))).MustHaveHappenedOnceExactly();
        }
Example #34
0
        public void GivenABlogEntry_WhenThenFileIsCreated_ThenTheCorrectFileNameIsUsed()
        {
            _fileInfo.Setup(f => f.Create()).Returns(new MemoryStream());

            var entry = new Post { Title = "title", EntryAddedDate = new DateTime(1990, 1, 1) };
            var repository = new PostRepository(Path, _fileInfoFactory.Object, null);
            repository.Create(entry);
            _fileInfo.Verify(f => f.Create(), Times.Once());
        }