コード例 #1
0
        public async Task CommentOnPost()
        {
            // Create Post
            PostModel model = new PostModel
            {
                Title     = "This is a new book",
                Body      = "The body of the post",
                Posted_At = DateTime.Now,
                ISBN      = "9780553573404"
            };

            model = await postService.CreatePost(authUser, model, openLibraryService);

            // Add a comment under the post
            CommentModel commentModel = new CommentModel
            {
                Post_Id = model.Id,
                Body    = "This is a comment on a post"
            };

            commentModel = commentService.CreateComment(authUser, commentModel);

            Comment comment = context.Comments
                              .Where(com => com.Id == commentModel.Id)
                              .FirstOrDefault();

            // Verify the comment has the correct information
            Assert.AreEqual(commentModel.Body, comment.Body);
            Assert.AreEqual(commentModel.Commented_By, comment.Commented_By.Username);
            Assert.AreEqual(commentModel.Post_Id, comment.Commented_OnId);
        }
コード例 #2
0
 public ActionResult <Post> Post([FromBody] Post post)
 {
     //post.Time = DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss");
     post.Time = DateTime.Now;
     _postService.CreatePost(post);
     return(CreatedAtAction("Post", new { id = post.Id, post }));
 }
コード例 #3
0
        public void GetPosts_ViewerIsInAccountCircle_ReturnsPosts()
        {
            using (var context = new InnerCircleDataContext(ContextOptions))
            {
                /// Arrange
                // Create a post service
                var postService = new PostService(context);

                // Create a post (1 is account in seeded database)
                var post = new Post
                {
                    AccountId   = 1,
                    Description = "Post Description",
                    MediaUrl    = "UrlToMedia"
                };

                // Save post
                postService.CreatePost(post, 1);

                /// Act
                // View account 1's posts as account 2
                var posts = postService.GetPosts(2, 1);

                /// Assert
                // Make sure correct amount of posts are returned
                Assert.True(posts.Count > 0);
            }
        }
コード例 #4
0
        public async void CreatePostWithrightArgs()
        {
            // Arrange
            PostViewModel post = new PostViewModel
            {
                Title    = "Title",
                Body     = "Body",
                Category = 0
            };
            string username = "******";

            // On renvoie juste un utilisateur avec un id car c'est la seule valeur nécessaire
            _identityService.GetUserByUsername(Arg.Any <string>()).ReturnsForAnyArgs(new User {
                Id = "id"
            });
            _categoryRepository.GetCategory(Arg.Any <int>()).ReturnsForAnyArgs(new Category());
            _postRepository.CreatePost(Arg.Any <Post>()).ReturnsForAnyArgs(1);

            // Act
            PostService postService = new PostService(_postRepository, _identityService, _categoryRepository, _commentService, _imageService);

            var result = await postService.CreatePost(post, username);

            // Assert
            Assert.True(result.Succeeded);
        }
コード例 #5
0
        public async Task PostTest_Ok()
        {
            //Arrange
            PostView pv = new PostView()
            {
                Create = DateTime.Now, Id = new Guid(), PosterEmail = "*****@*****.**"
            };

            this.fakeRepository.Setup(fk => fk.CreateAsync(It.IsAny <Post>()));

            //Act
            var result = await postService.CreatePost(pv);

            //Assert
            Assert.Equal(pv.Id, result.Id);
        }
コード例 #6
0
        public void CreatePostShould_CallCommitMethod()
        {
            //// Arrange
            var mockPost = new Post()
            {
                Id          = Guid.NewGuid(),
                Title       = "testTitle",
                ImageUrl    = "testUrl",
                ImageTarget = "testTarget",
                ImageInfo   = "testInfo",
                Location    = "TestLocation",
                Time        = DateTime.Now,
                AuthorId    = "authorId",
                Author      = new Data.Models.Users.User()
                {
                    UserName = "******",
                    Id       = "testUserId"
                }
            };
            var mockPostRepository = new Mock <IPostRepository>();
            var mockUserRepository = new Mock <IUserRepository>();
            var mockSaveContext    = new Mock <ISaveContext>();

            mockSaveContext.Setup(x => x.Commit());

            var sut = new PostService(mockUserRepository.Object, mockPostRepository.Object, mockSaveContext.Object);

            sut.CreatePost(mockPost.Title, mockPost.ImageTarget, mockPost.ImageUrl, mockPost.ImageInfo, mockPost.Location, mockPost.Time, mockPost.AuthorId);
            mockSaveContext.Verify(x => x.Commit(), Times.Once);
        }
コード例 #7
0
        public bool CreatePost(JObject postDto)
        {
            try
            {
                var creatingPost = new PostDto
                {
                    PostTitle      = postDto["PostTitle"].ToString(),
                    PostContent    = postDto["PostContent"].ToString(),
                    CreationDate   = DateTime.Now,
                    RelatedTo      = postDto["RelatedTo"].ToObject <BlogDto>(),
                    PostCategories = postDto["PostCategories"].ToObject <List <CategoryDto> >()
                };

                var result = PostService.CreatePost(creatingPost);

                if (result == AnswerStatus.Successfull)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
        }
        public void CreateNewPostCheckReturnPost_Test()
        {
            var  mock1     = new Mock <IRepository <Post> >();
            var  mock2     = new Mock <IHostingEnvironment>();
            var  fileMock  = new Mock <IFormFile>();
            var  fileName  = "i.jpeg";
            Post postModel = new Post
            {
                Id               = 4,
                Title            = "Luxury interior in the design of apartments and houses",
                ShortDescription = "Designing premium interiors is a rejection of typical planning.",
                ImageUrl         = "i.jpeg"
            };


            byte[] imageData = new byte[255];

            fileMock.Setup(_ => _.FileName).Returns(fileName);

            mock1.Setup(repo => repo.InsertAsync(It.IsAny <Post>())).Returns(async() => { return(postModel); });

            var webRootPath = "C:\\Task\\Lvivity_Intern\\WebApi\\LearningProject\\wwwroot";

            var postService = new PostService(mock1.Object, Mock.Of <IHostingEnvironment>(w => w.WebRootPath == webRootPath));

            var result = postService.CreatePost(postModel.Title,
                                                postModel.ShortDescription, postModel.ImageUrl, imageData);

            Assert.IsType <Post>(result.Result);
        }
コード例 #9
0
        public void GetPosts_ViewerIsTheAccount_ReturnsPosts()
        {
            using (var context = new InnerCircleDataContext(ContextOptions))
            {
                /// Arrange
                // Create a post service
                var postService = new PostService(context);

                //  Create a post for account 1
                var post = new Post
                {
                    AccountId   = 1,
                    Description = "Post Description",
                    MediaUrl    = "UrlToMedia"
                };

                // Save post
                postService.CreatePost(post, 1);

                /// Act
                // GetPosts where viewerId and accountId are 1
                /// Act
                // View account 1's posts as account 2
                var posts = postService.GetPosts(1, 1);

                /// Assert
                // The posts are returned
                Assert.True(posts.Count > 0);
            }
        }
コード例 #10
0
        public ActionResult <Post> CreatePost(PostDTO postDto)
        {
            // Set AccountId to the user AccountId given form auth
            var postAccountId = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "AccountID").Value;

            if (postDto.Bytes != null)
            {
                var Media = PostService.ParseDataURL(postDto.Bytes);
                var bytes = Convert.FromBase64String(Media["data"]);
            }

            // Parse the string claim for a long value
            long longAccountId;

            long.TryParse(postAccountId, out longAccountId);

            var post = new Post
            {
                MediaUrl    = postDto.Bytes,//PostService.UploadMediaToBlob(bytes,Media["extension"]),
                Description = postDto.Description,
            };



            // Create the post
            post = PostService.CreatePost(post, longAccountId);
            return(Ok(post));
        }
コード例 #11
0
 public ActionResult <Post> Create(Post post)
 {
     _postService.CreatePost(post);
     return(CreatedAtRoute("GetPosts", new {
         id = post.Id.ToString()
     }, post));
 }
        public async Task CreateNewPostCheckIsTypeOfFile_Test()
        {
            var mock1    = new Mock <IRepository <Post> >();
            var mock2    = new Mock <IHostingEnvironment>();
            var fileMock = new Mock <IFormFile>();
            var fileName = "i.txt";

            fileMock.Setup(_ => _.FileName).Returns(fileName);

            CreatePostModel createPostModel = new CreatePostModel
            {
                Title            = "Luxury interior in the design of apartments and houses",
                ShortDescription = "Designing premium interiors is a rejection of typical planning.",
                Image            = fileMock.Object
            };

            byte[] imageData = null;

            var postService = new PostService(mock1.Object, mock2.Object);

            Exception ex = await Assert.ThrowsAsync <Exception>(() => postService.CreatePost(createPostModel.Title,
                                                                                             createPostModel.ShortDescription, createPostModel.Image.FileName, imageData));

            Assert.Equal("Invalid file type.", ex.Message);
        }
コード例 #13
0
        public void CreatePost_PassedValidPost_PostIsCreated()
        {
            using (var context = new InnerCircleDataContext(ContextOptions))
            {
                /// Arrange
                // Create a post service
                var postService = new PostService(context);

                // Create a post (1 is account in seeded database)
                var post = new Post
                {
                    AccountId   = 1,
                    Description = "Post Description",
                    MediaUrl    = "UrlToMedia"
                };

                /// Act
                // Save post
                postService.CreatePost(post, 1);

                /// Assert
                // Ensure post was created
                Assert.NotNull(context.Posts.FirstOrDefault(p => p.AccountId == 1));
            }
        }
コード例 #14
0
        public int CreatePost(PostDC postDC, int userId, List <CategoryDC> categoryListDC)
        {
            try
            {
                List <CategoryDto> categoryDtoList = new List <CategoryDto>();
                foreach (CategoryDC categoryDC in categoryListDC)
                {
                    categoryDtoList.Add(new CategoryDto
                    {
                        Id           = categoryDC.Id,
                        CategoryName = categoryDC.CategoryName
                    });
                }

                return(PostService.CreatePost(new PostDto
                {
                    Title = postDC.Title,
                    Body = postDC.Body,
                    PostImage = postDC.PostImage
                }, userId, categoryDtoList));
            }
            catch (ApplicationException ex)
            {
                throw new FaultException(ex.Message);
            }
        }
コード例 #15
0
        public Post CreatePost([FromForm] string title, [FromForm] string description)
        {
            string      username = HttpContext.User.FindFirst("Username").Value.ToString();
            PostService pService = new PostService();

            Post post = pService.CreatePost(username, title, description);

            return(post);
        }
コード例 #16
0
ファイル: PostController.cs プロジェクト: art-Tests/MsgBoard
 public ActionResult Create(PostViewModel model)
 {
     if (!ModelState.IsValid)
     {
         return(View(model));
     }
     _postService.CreatePost(model);
     return(RedirectToAction("Index", "Post"));
 }
コード例 #17
0
        public ActionResult CreateUpdatePostDo(PostViewModel postViewModel)
        {
            RemoveCategoryValidationErrors();

            if (postViewModel.Categories is null)
            {
                postViewModel.Categories = new CategoryViewModel[0];
            }

            if (string.IsNullOrEmpty(postViewModel.PostImage))
            {
                postViewModel.PostImage = "Default.jpeg";
            }

            if (ModelState.IsValid)
            {
                try
                {
                    List <CategoryViewModel> postCategories = new List <CategoryViewModel>();

                    foreach (var categoryItem in postViewModel.Categories)
                    {
                        if (categoryItem.IsChecked)
                        {
                            postCategories.Add(new CategoryViewModel {
                                Id = categoryItem.Id
                            });
                        }
                    }

                    if (postViewModel.Id == 0)
                    {
                        postViewModel.Body = HttpUtility.HtmlEncode(postViewModel.Body);

                        PostService.CreatePost(postViewModel, 1, postCategories);

                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        postViewModel.Body = HttpUtility.HtmlEncode(postViewModel.Body);
                        PostService.UpdatePost(postViewModel, postCategories);

                        return(RedirectToAction("Post", "Admin", postViewModel));
                    }
                }
                catch (ApplicationException)
                {
                    return(RedirectToAction("CreateUpdatePost", "Admin", postViewModel));
                }
            }
            else
            {
                return(RedirectToAction("CreateUpdatePost", "Admin"));
            }
        }
コード例 #18
0
        public IActionResult CreatePost([FromForm(Name = "title")] string title, [FromForm(Name = "description")] string description)
        {
            // username missing
            PostService pService = new PostService();
            string      username = HttpContext.User.FindFirst("Username").Value.ToString();

            pService.CreatePost(username, title, description);

            return(RedirectToAction("Index", "Home"));
        }
コード例 #19
0
        public async void CreatePostWithNullPost()
        {
            // Act
            PostService postService = new PostService(_postRepository, _identityService, _categoryRepository, _commentService, _imageService);

            var result = await postService.CreatePost(null, null);

            // Assert
            Assert.False(result.Succeeded);
        }
コード例 #20
0
        public async Task CreatePost()
        {
            PostModel model = new PostModel
            {
                Title     = "This is a new book",
                Body      = "The body of the post",
                Posted_At = DateTime.Now,
                ISBN      = "9780553573404",
                Posted_By = authUser.Username
            };

            await postService.CreatePost(authUser, model, openLibraryService);

            Post post = context.Posts.FirstOrDefault();

            Assert.AreEqual(model.Title, post.Title);
            Assert.AreEqual(model.Body, post.Body);
            Assert.AreEqual(model.Posted_By, post.Posted_By.Username);
        }
コード例 #21
0
        public IHttpActionResult Create(PostModel post)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }


            ResponseModel response = PostService.CreatePost(post);

            return(Ok(response));
            //return Ok(customerFake);
        }
コード例 #22
0
ファイル: Queries.cs プロジェクト: SBrahe/Dab3_SocialNetwork
        //////////////////////////////////////CREATIONS/////////////////////////////////////////////////////
        public void CreatePost(User author, string postText, bool isPublic)
        {
            var post = new Post
            {
                Author   = author,
                PostText = postText,
                Created  = DateTime.Now,
                IsPublic = isPublic,
                Comments = new List <Comment>()
            };

            _postService.CreatePost(post);
        }
コード例 #23
0
        private static AnswerStatus CreateValidPost(bool withCategories = false)
        {
            var dto = new PostDto
            {
                PostTitle    = "test",
                PostContent  = "test",
                CreationDate = DateTime.Now,
                RelatedTo    = new BlogDto
                {
                    BlogTitle    = "testblog",
                    CreationDate = DateTime.Now
                }
            };

            if (withCategories)
            {
                dto.PostCategories = new List <CategoryDto> {
                    new CategoryDto()
                };
            }

            return(_postService.CreatePost(dto));
        }
コード例 #24
0
        public async Task <Post> CreatePost()
        {
            dynamic entity = new ExpandoObject();

            entity.Content = "Entity content";
            entity.Title   = "Title here";
            entity.UserId  = 3;

            var postEntity = _entityFactory.Make <Post>(entity);

            var post = await _postService.CreatePost(postEntity);

            return(post);
        }
コード例 #25
0
        public async Task AddPostShoutAddItInDB()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

            var dbContext = new ApplicationDbContext(options);

            var postRepository = new EfDeletableEntityRepository <Post>(dbContext);

            var service = new PostService(postRepository);

            await service.CreatePost("userIdText", "postText", "david");

            Assert.Equal(1, dbContext.Posts.Count());
        }
コード例 #26
0
        protected async Task HandleValidSubmit()
        {
            PostDetailViewModel.CategoryId = int.Parse(SelectedCategoryId);
            ResponseFromApi <int> response;

            if (SelectedPostId == 0)
            {
                response = await PostService.CreatePost(PostDetailViewModel);
            }
            else
            {
                response = await PostService.UpdatePost(PostDetailViewModel);
            }
            HandleResponse(response);
        }
コード例 #27
0
        public async Task CreatePost_PostCreated_CreateSuccess(
            [Frozen] Mock <IRepositoryWrapper> mockRepositoryWrapper,
            [Frozen] Mock <Post> post)
        {
            //Arrange
            mockRepositoryWrapper.Setup(x => x.PostRepository.Add(It.IsAny <Post>()));
            var Sut = new PostService(mockRepositoryWrapper.Object);

            //Act
            await Sut.CreatePost(post.Object);

            //Assert
            mockRepositoryWrapper.Verify(x => x.PostRepository.Add(It.IsAny <Post>()));
            mockRepositoryWrapper.Verify(x => x.SaveAsync());
        }
コード例 #28
0
        public void InsertAndGetPost()
        {
            using (var context = Context.CreateContext())
            {
                PostService postService = new PostService(context);
                var         post        = new Post
                {
                    Header = "Test",
                };
                postService.CreatePost(post);
                Assert.Equal(post.Header, postService.GetPosts().Where(x => x.Header == post.Header).FirstOrDefault().Header);

                context.Posts.Remove(post);
                context.SaveChanges();
            }
        }
コード例 #29
0
        public async Task <ActionResult> Create(PostEditAddModel model)
        {
            try
            {
                await _postService.CreatePost(model);

                var roleId = (ulong)HttpContext.Session.GetInt32("RoleId");
                return(RedirectToAction(nameof(Index), new { userId = model.AutorId, roleId = model.RoleId }));
            }
            catch
            {
                model.PostsStatusOptions = (List <PostStatusModel>) await _postService.GetPostStatus();

                return(View(model));
            }
        }
コード例 #30
0
ファイル: PostController.cs プロジェクト: rdarku/BlazorBlog
        public IHttpActionResult Post(PostCreate note)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            PostService postservice = CreatePostService();

            if (!postservice.CreatePost(note))
            {
                return(InternalServerError());
            }

            return(Ok());
        }