Пример #1
0
        public void Post([FromBody] CreatePostDto createPostDto)
        {
            Post post = _mapper.Map <Post>(createPostDto);

            post.ReplyTime = DateTime.Now;
            _fsql.Insert(post).ExecuteAffrows();
        }
        public async Task CreatePost()
        {
            // Arrange
            const string Url            = "/api/Posts";
            var          postRepository = this.GetService <IUnitOfWorkFactory>().CreateUnitOfWork().CreateEntityRepository <Post>();
            var          postDto        = new CreatePostDto
            {
                Text      = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
                Latitude  = 43,
                Longitude = 8
            };

            // Act
            var response = await this.Client.PostAsync(Url, new StringContent(JsonConvert.SerializeObject(postDto), Encoding.UTF8, "application/json"));

            var result = await response.Content.ReadAsStringAsync();

            var createdMessage = JsonConvert.DeserializeObject <CreatedApiResult>(result);
            var post           = postRepository.FindById(createdMessage.CreatedId);

            // Assert
            Assert.IsTrue(createdMessage.Success);
            Assert.AreEqual(createdMessage.Entity, OctopostEntityName.Post);
            Assert.AreEqual(post.Text, postDto.Text);
        }
Пример #3
0
        public async Task CreatePost(CreatePostDto input)
        {
            var post = new Post
            {
                Content          = input.Content,
                Title            = input.Title,
                CategoryId       = input.CategoryId,
                ShortDescription = input.ShortDescription,
                PostState        = PostState.Active,
                ImagePath        = await _blobService.InsertFile(input.ImageFile)
            };

            if (input.EducatorId != null)
            {
                post.EducatorId = input.EducatorId;
                post.EntityType = EntityType.Educator;
            }

            if (input.TenantId != null)
            {
                post.TenantId   = input.TenantId;
                post.EntityType = EntityType.Tenant;
            }
            await _postRepository.AddAsync(post);
        }
Пример #4
0
        /// <summary>
        /// Creates a Post using the specified DTO.
        /// </summary>
        /// <param name="model"></param>
        /// <returns>Details of the Post if successful, otherwise a BadRequest with Detail.</returns>
        public IHttpActionResult CreatePost(CreatePostDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (_userService.Get(model.AuthorId) == null)
            {
                return(BadRequest("User doesn't exist."));
            }
            if (_topicService.Get(model.TopicId) == null)
            {
                return(BadRequest("Topic doesn't exist."));
            }

            var post = _postService.Add(new Post
            {
                Id             = Guid.NewGuid(),
                Title          = model.Title,
                Description    = model.Description,
                TopicId        = model.TopicId,
                AuthorId       = model.AuthorId,
                CreateDateTime = DateTime.Now
            });

            return(Ok(Mapper.Map <BasicPostDto>(post)));
        }
Пример #5
0
        public IActionResult CreatePost([FromBody] CreatePostDto createPost)
        {
            if (createPost == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var finalPost = Mapper.Map <Entities.Posts>(createPost);

            _postsInfoRepository.AddPost(finalPost);

            if (!_postsInfoRepository.Save())
            {
                return(StatusCode(500, "A problem happened on the server"));
            }

            var createdPostToReturn = Mapper.Map <Models.PostsDto>(finalPost);

            return(CreatedAtRoute("GetPost", new
                                  { id = createdPostToReturn.Id }, createdPostToReturn));
        }
Пример #6
0
        public void TestCreateValidPost_ShouldReturnOK()
        {
            var testPost = new CreatePostDto
            {
                Title = "NEW POST",
                Text  = "this is just a test post",
                Tags  = new string[] { "post" }
            };

            var testUser = new UserDto
            {
                Username    = "******",
                DisplayName = "Peter Petroff",
                AuthCode    = "bfff2dd4f1b310eb0dbf593bd83f94dd8d34077e"
            };

            var response = httpServer.Post("api/users/register", testUser);

            string contentString = response.Content.ReadAsStringAsync().Result;
            var    loggedUser    = JsonConvert.DeserializeObject <LoggedUserDto>(contentString);

            var headers = new Dictionary <string, string>();

            headers["X-SessionKey"] = loggedUser.SessionKey;

            var createPostResponse = httpServer.Post("api/posts", testPost, headers);

            string resultString = createPostResponse.Content.ReadAsStringAsync().Result;
            var    createdPost  = JsonConvert.DeserializeObject <CreatePostDto>(resultString);

            Assert.AreEqual(HttpStatusCode.Created, createPostResponse.StatusCode);
            Assert.AreEqual(testPost.Title, createdPost.Title);
            Assert.AreEqual(testPost.Text, createdPost.Text);
            Assert.IsNotNull(createdPost.Id);
        }
Пример #7
0
 public virtual async Task <PostWithDetailsDto> CreateAsync(CreatePostDto input)
 {
     return(await RequestAsync <PostWithDetailsDto>(nameof(CreateAsync), new ClientProxyRequestTypeValue
     {
         { typeof(CreatePostDto), input }
     }));
 }
Пример #8
0
        public async Task <Post> Create(CreatePostDto dto)
        {
            User user = await _sessionService.GetUser();

            Validate("create", dto.Content, dto.Title, user);

            var post = new Post
            {
                Title          = dto.Title,
                Content        = dto.Content,
                CreationTime   = DateTime.Now,
                LastUpdateTime = DateTime.Now,
                AuthorId       = user.Id,
                Likes          = 0,
                Dislikes       = 0,
                Tags           = TagHelpers.GetTagsFromText(dto.Content),
                Id             = Guid.NewGuid().ToString()
            };

            await _postRepository.Create(post);

            _logger.LogInformation($"Post {post.Id} has been created");

            await _tagRepository.Create(post.Tags.Select(x => new Tag
            {
                Name = x,
                PostsNumber = 1
            }).ToArray());

            _logger.LogInformation("Tags have been added");

            return(post);
        }
        public long CreatePost(CreatePostDto createPostDto)
        {
            using (var unitOfWork = this.unitOfWorkFactory.CreateUnitOfWork())
            {
                if (createPostDto.FileId.HasValue)
                {
                    var fileRepository = unitOfWork.CreateEntityRepository <File>();
                    var file           = fileRepository.Query().FirstOrDefault(x => x.Id == createPostDto.FileId.Value);
                    if (file == null)
                    {
                        throw new ApiException(x => x.BadRequestResult(
                                                   (ErrorCode.Parse(ErrorCodeType.InvalidReferenceId, OctopostEntityName.Post, PropertyName.Post.FileId, OctopostEntityName.File),
                                                    new ErrorDefinition(createPostDto.FileId, "The file was not found", PropertyName.Post.FileId))));
                    }
                }

                var repository = unitOfWork.CreateEntityRepository <Post>();
                var post       = createPostDto.MapTo <Post>();
                post.Topic = this.PredictTopic(post.Text);
                var namedLocationId = this.locationNameService.NameLocation(post);
                post.LocationNameId = namedLocationId;
                repository.Create(post);
                unitOfWork.Save();
                return(post.Id);
            }
        }
Пример #10
0
        public async Task <IActionResult> Add([FromForm] CreatePostDto createPostDto)
        {
            try
            {
                string createdFilePath = _fileService.CreateLocalFile(createPostDto.PhotoFile, PostPhotosFolder);

                var user = await _userManager.GetUserAsync(User);

                if (user == null)
                {
                    return(BadRequest());
                }

                createPostDto.AuthorId = user.Id;

                CreatePostViewModel createPostViewModel = CustomMapper.GetCreatePostViewModel(createPostDto, createdFilePath);
                var result = await _postService.Add(createPostViewModel);

                if (result.IsValid)
                {
                    return(Ok());
                }

                return(BadRequest(result.Errors));
            }
            catch (IOException) { }

            return(BadRequest());
        }
Пример #11
0
        public async Task <IActionResult> CreatePost([FromBody] CreatePostDto createPostDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

            var postToCreate = new Post
            {
                Content       = createPostDto.Content,
                UserId        = currentUserId,
                DatePublished = DateTime.UtcNow,
                LikesNum      = createPostDto.LikesNum
            };

            _repo.Add(postToCreate);

            if (await _repo.SaveAll())
            {
                return(StatusCode(201));
            }

            throw new Exception("Failed on save.");
        }
Пример #12
0
        private async Task <Post> CreatePostAsync(CreatePostDto dto)
        {
            ValidateDto(dto);

            var authors        = _userRepository.Query(new GetAuthorsQuery(dto.Authors));
            var missingAuthors = dto.Authors
                                 .Where(authorName => authors.All(a => a.Name != authorName))
                                 .ToList();

            if (missingAuthors.Any())
            {
                throw new ArgumentException($"User(s) not found: {string.Join(",", missingAuthors)}");
            }

            var post = new Post
            {
                CreatedOn = DateTime.UtcNow,
                Title     = dto.Title
            };

            var postAuthors = authors.Select(a => new PostAuthor
            {
                Post   = post,
                Author = a
            }).ToList();

            post.Authors = postAuthors;

            await _postRepository.AddAsync(post);

            return(post);
        }
        public void Execute(CreatePostDto request)
        {
            _validator.ValidateAndThrow(request); // ValidationException

            var newFileName = Guid.NewGuid() + Path.GetExtension(request.Photo.FileName);

            using (Image image = Image.Load(request.Photo.OpenReadStream()))
            {
                image.Save(Path.Combine("wwwroot", Photo.PhotoFolderPath, newFileName));

                image.Mutate(x => x.Resize(250, 250));
                image.Save(Path.Combine("wwwroot", Photo.ThumbnailPhotoFolderPath, newFileName));
            }

            var photo = new Photo
            {
                Caption  = request.PhotoCaption,
                FileName = newFileName
            };

            _context.Photos.Add(photo);

            var post = new Post
            {
                Title = request.Title,
                Text  = request.Text,
                Photo = photo
            };

            _context.Posts.Add(post);

            _context.SaveChanges(_actor.Id);
        }
Пример #14
0
        public async Task <ActionResult> OnPost(CreatePostDto post)
        {
            var insertedPost = await _postAppService.CreateAsync(post);

            var blog = await _blogAppService.GetAsync(insertedPost.BlogId);

            return(Redirect(Url.Content($"~/blog/{blog.ShortName}/{insertedPost.Title}")));
        }
Пример #15
0
        public async Task <IActionResult> PostAsync([FromBody] CreatePostDto createPostDto)
        {
            var post = await _postService.CreatePost(_mapper.Map <Post>(createPostDto));

            var readPostDto = _mapper.Map <ReadPostDto>(post);

            return(Created(nameof(GetAsync), new Response <ReadPostDto>(readPostDto)));
        }
Пример #16
0
        public async Task <IActionResult> Create([FromBody] CreatePostDto createPostDto)
        {
            string userId = _httpContext.User.FindFirstValue("sub");

            var    command = new CreatePostCommand(userId, createPostDto);
            string postId  = await _mediator.Send(command);

            return(Created($"{HttpContext.Request.GetDisplayUrl()}/{postId}", null));
        }
Пример #17
0
        public async Task <IActionResult> CreatePost([FromBody] CreatePostDto createPostDto)
        {
            var result = await Mediator.Send(new CreatePostCommand
            {
                CreatePostDto = new CreatePostDto(createPostDto, AuthorizedUserId)
            });

            return(Ok(result));
        }
Пример #18
0
        private async Task Save()
        {
            try
            {
                IsBusy = true;
                string[] tags = null;

                if (Tags != null)
                {
                    tags = new string[Tags.Count];
                    Tags.CopyTo(tags, 0);
                }

                if (_photoStream != null)
                {
                    byte[] byteImage;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        _photoStream.CopyTo(ms);
                        byteImage = ms.ToArray();
                    }

                    CreatePostDto newPost = new CreatePostDto
                    {
                        Description = Description,
                        ImageData   = byteImage,
                        Tags        = tags
                    };

                    await _postService.CreatePost(newPost, _runtimeContext.Token);

                    await _navigationService.NavigateAsync <PostsViewModel>();
                }

                //Edit
                if (_postId != default(Guid))
                {
                    EditPostDto newPost = new EditPostDto
                    {
                        Description = Description,
                        Tags        = tags
                    };

                    await _postService.EditPost(newPost, _postId, _runtimeContext.Token);

                    await _navigationService.NavigateAsync <PostsViewModel>();
                }
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK");
            }
            finally
            {
                IsBusy = false;
            }
        }
Пример #19
0
        public async Task <IActionResult> AddPost([FromBody] CreatePostDto postDto)
        {
            var user = await _userRepository.QueryAsync(postDto.UserId);

            var post = new Post(user, postDto.Title, postDto.Content);
            await _postsRepository.IndexAsync(post);

            return(Ok(post));
        }
Пример #20
0
        public async Task <IActionResult> CreatePost([FromBody] CreatePostDto createPostDto)
        {
            var postId = await _mediator.Send(new CreatePostCommand
            {
                CreatePostDto = createPostDto
            });

            return(Ok(postId));
        }
Пример #21
0
        public async Task <IActionResult> Post([FromBody] CreatePostDto value)
        {
            //проверка прав юзера
            var user = await _ctx.Users.FirstOrDefaultAsync(u => u.UserId == value.UserId);

            if (user == null || user.Privs < (int)UserPermission.AddPost)
            {
                return(BadRequest("Недостаточно прав для добавления поста"));
            }

            var author = await _ctx.Authors
                         .FirstOrDefaultAsync(x => x.AuthorId == value.AuthorId);

            if (author == null)
            {
                return(BadRequest("Ошибка: автор не зарегистрирован"));
            }

            var allContentsGiven = value.Contents.Any(x => x.Color == 0) &&
                                   value.Contents.Any(x => x.Color == 1);

            if (!allContentsGiven)
            {
                return(BadRequest("Нельзя создать пост с контентом одной стороны"));
            }

            //создание поста
            var post = new Post()
            {
                Author   = author,
                PostDate = DateTime.UtcNow
            };
            //создание контентов к нему
            var postContents = value.Contents.Select(content => new PostContent()
            {
                Title     = content.Title,
                ImageLink = content.PicLink,
                Content   = content.HtmlContent,
                PostColor = content.Color,
                Post      = post
            })
                               .ToList();

            //соединяем пост с контентами
            post.PostContents = postContents;
            //добавляем созданный пост
            await _ctx.AddAsync(post);

            //сохраняем изменения
            var result = await _ctx.SaveChangesAsync();

            if (result > 0)
            {
                return(Ok(post.PostId));
            }
            return(BadRequest("Не удалось создать пост"));
        }
Пример #22
0
        public void CreateNewPost(CreatePostDto createPostDto)
        {
            var postItem = Mapper.Map <Post>(createPostDto);

            postItem.UserId = _profileRepo.GetProfileIdByAccountId(createPostDto.UserId);

            _postRepo.AddNewItem(postItem);
            _postRepo.SaveChanges();
        }
Пример #23
0
        public PostDto AddNewPost(CreatePostDto newPost)
        {
            if (string.IsNullOrEmpty(newPost.Title))
            {
                throw new Exception("Post can not have an empty title.");
            }
            var post = _mapper.Map <Post>(newPost);

            _postRepository.Add(post);
            return(_mapper.Map <PostDto>(post));
        }
Пример #24
0
 public static CreatePostViewModel GetCreatePostViewModel(CreatePostDto createPostDto, string photoPath)
 {
     return(new CreatePostViewModel(
                createPostDto.Title,
                createPostDto.Content,
                photoPath,
                createPostDto.BlogId,
                createPostDto.CategoryId,
                createPostDto.IsActive,
                createPostDto.AuthorId));
 }
Пример #25
0
        public async void OnGet()
        {
            var blog = await _blogAppService.GetByShortNameAsync(BlogShortName);

            Post = new CreatePostDto()
            {
                BlogId = blog.Id
            };

            Blog = blog;
        }
Пример #26
0
        public async Task <Post> Post([FromBody] CreatePostDto post)
        {
            Guid userId = Guid.NewGuid(); // TODO change to get from authentications claims

            HttpContext.Response.StatusCode = (int)HttpStatusCode.Created;
            var createPostViewModel = new CreatePostViewModel()
            {
                FromId = userId, Text = post.Text, Title = post.Title
            };

            return(await _postService.CreatePostAsync(createPostViewModel));
        }
Пример #27
0
        public async Task <PostDto> AddNewPostAsync(CreatePostDto newPost)
        {
            if (string.IsNullOrEmpty(newPost.Title))
            {
                throw new Exception("Post can not have an empty title.");
            }

            var post   = _mapper.Map <Post>(newPost);
            var result = await _postRepository.AddAsync(post);

            return(_mapper.Map <PostDto>(result));
        }
Пример #28
0
        public IActionResult CreateNewPost(CreatePostDto newpost)
        {
            if (ModelState.IsValid)
            {
                var result = _mapper.Map <Post>(newpost);
                _blogService.AddNewPost(result);
                _uow.SaveChanges();
                return(Ok());
            }

            return(BadRequest());
        }
Пример #29
0
        public async void Posts_POST_Returns_400()
        {
            CreatePostDto post = new CreatePostDto()
            {
                Text  = "New post",
                Title = string.Empty
            };

            var response = await this.HttpClient.PostAsync($"/api/v1/posts/", new StringContent(JsonConvert.SerializeObject(post), Encoding.UTF8, "application/json"));

            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        }
        public async Task CreatePostByMakrdown(CreatePostDto input)
        {
            //检查下当前文章是否存在
            //如果存在则替换下内容。将以前的文章存放在历史内容中

            var oldpost = await _postManager.GetPostByUrl(input.BlogId, input.Url);

            if (oldpost != null)
            {
                var dto = ObjectMapper.Map <PostEditDto>(oldpost);

                if (input.Content != dto.Content)
                {
                    dto.HistoryContent = dto.Content;
                    dto.Title          = input.Title;
                    dto.PostType       = input.PostType;
                    dto.CoverImage     = input.CoverImage;
                    dto.Content        = input.Content;

                    oldpost = await UpdateByMakrdown(dto).ConfigureAwait(false);

                    //保存Tag标签内容
                    if (input.NewTags != null && input.NewTags.Count > 0)
                    {
                        await _tagManager.SaveTagsByName(input.NewTags, oldpost);
                    }
                    await CurrentUnitOfWork.SaveChangesAsync().ConfigureAwait(false);
                }
            }
            else
            {
                input.Url = await RenameUrlIfItAlreadyExistAsync(input.Url).ConfigureAwait(false);

                var entity = ObjectMapper.Map <Post>(input);

                if (AbpSession.UserId == null)
                {
                    entity.CreatorUserId = 2;
                }


                //调用领域服务
                entity = await _postManager.CreateAsync(entity).ConfigureAwait(false);

                //保存Tag标签内容
                if (input.NewTags != null && input.NewTags.Count > 0)
                {
                    await _tagManager.SaveTagsByName(input.NewTags, entity);
                }
                await CurrentUnitOfWork.SaveChangesAsync().ConfigureAwait(false);
            }
        }