Ejemplo n.º 1
0
        public async Task <IActionResult> CreateThread(ThreadCreateDto threadCreateDto)
        {
            try
            {
                // get current logged in user
                var user = await _userManager.GetUserAsync(HttpContext.User);

                var threadToAdd = _mapper.Map <Thread>(threadCreateDto);

                // set thread creator to current logged in user
                threadToAdd.ApplicationUser = user;

                await _threadService.AddThreadToDatabase(threadToAdd);

                // create opening post
                var openingPostCreateDto = new PostCreateDto
                {
                    Content    = threadCreateDto.OpeningPost,
                    TimePosted = threadCreateDto.TimeCreated
                };

                var openingPost = _mapper.Map <Post>(openingPostCreateDto);

                openingPost.Thread = threadToAdd;

                await _postService.AddPostToDatabase(openingPost, user);

                return(GetAllThreadsByMostRecentPost());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Ejemplo n.º 2
0
        public ServiceResult CreatePost(PostCreateDto model)
        {
            var serviceResult = new ServiceResult(true);

            #region validation
            if (string.IsNullOrEmpty(model.Title))
            {
                serviceResult.AddError("عنوان پست نمی تواند فاقد مقدار باشد");
            }
            if (!string.IsNullOrEmpty(model.Title) && model.Title.Length > 128)
            {
                serviceResult.AddError("تعداد کاراکترهای عنوان پست نمی تواند بیش از 128 کاراکتر باشد".ToPersianNumbers());
            }
            if (string.IsNullOrEmpty(model.PrimaryPicture))
            {
                serviceResult.AddError("عکس اصلی پست نمی تواند فاقد مقدار باشد");
            }
            #endregion

            if (serviceResult.IsSuccess)
            {
                var entity = model.ToEntity();
                entity.CreateDate = DateTime.Now;

                _context.Posts.Add(entity);

                if (_context.SaveChanges() == 0)
                {
                    serviceResult.AddError("در انجام عملیات خطایی رخ داد");
                }
            }

            return(serviceResult);
        }
Ejemplo n.º 3
0
        public async Task <ActionResult <PostDto> > Post([FromBody] PostCreateDto dto)
        {
            var repo = GetConcreteRepoFromType(dto.Type);

            PostDto createDto = null;

            switch (dto)
            {
            case ImagePostCreateDto imgPostCreateDto:
                createDto = await _imagePostRepository.CreateAsync(imgPostCreateDto);

                break;

            case VideoPostCreateDto vidPostCreateDto:
                createDto = await _videoPostRepository.CreateAsync(vidPostCreateDto);

                break;

            case QuotePostCreateDto qPostCreateDto:
                createDto = await _quotePostRepository.CreateAsync(qPostCreateDto);

                break;
            }

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

            return(Ok(createDto));
        }
Ejemplo n.º 4
0
        [TransactionScopeAspect]//+++
        public IDataResult <Post> Add(PostCreateDto postCreateDto, string imageName)
        {
            var post = new Post
            {
                Title     = postCreateDto.Title,
                Content   = postCreateDto.Content,
                ImageName = imageName,
                UserId    = postCreateDto.UserId,
                Created   = DateTime.Now
            };

            _postDal.Add(post);
            var postSave = new SuccessDataResult <Post>(post, Messages.UserRegistered);

            string[] category = postCreateDto.CategoryId.Split("*");
            foreach (var item in category)
            {
                if (item != "")
                {
                    var postCategory = new PostCategoryCreateDto {
                        PostId = postSave.Data.Id, CategoryId = item
                    };
                    _postCategoryService.Add(postCategory);
                }
            }
            return(new SuccessDataResult <Post>(post, Messages.PostAdded));
        }
Ejemplo n.º 5
0
		public async Task<ResultResponse<PostGetDto>> CreatePostAsync(PostCreateDto dto, int creatorId)
		{
			try
			{
				var creator = await _usersRepository.GetAsync(creatorId);
				if (creator == null)
				{
					return ResultResponse<PostGetDto>.GetBadResponse(StatusCode.NotFound, "Пользователь не найден");
				}

				var post = _mapper.Map<Post>(dto);
				post.creator_id = creatorId;
				post.created = DateTime.Now;
				var added = await _postsRepository.AddAsync(post);
				if (added == null)
				{
					return ResultResponse<PostGetDto>.GetBadResponse(StatusCode.InternalServerError, "Не удалось добавить пост");
				}
				var addedView = await _postsViewRepository.GetAsync(post.id);
				var addedViewDto = _mapper.Map<PostGetDto>(addedView);

				return ResultResponse<PostGetDto>.GetSuccessResponse(addedViewDto);
			}
			catch (Exception ex)
			{
				_progressLogger.Error(ex, new { dto, creatorId }, GetType().Name, nameof(CreatePostAsync));
				return ResultResponse<PostGetDto>.GetInternalServerErrorResponse();
			}
		}
Ejemplo n.º 6
0
        public async Task <Post> CreatePost(PostCreateDto postDto)
        {
            var destination = this.mapper.Map <Post>(postDto);

            if (postDto.FirmUniqueId != null)
            {
                destination.FirmId = (await this.firmsService
                                      .GetFirmByUniqueId <Firm>(postDto.FirmUniqueId)).Id;
            }

            var areThereAnyPostsWithSameTitle =
                this.postsRepository.All().Where(p => p.Title == destination.Title).Any();

            if (areThereAnyPostsWithSameTitle)
            {
                return(null);
            }

            await this.postsRepository.AddAsync(destination);

            var statusCode = await this.postsRepository.SaveChangesAsync();

            if (statusCode != GlobalConstants.SuccessfullySavedIntoDbContextStatusCode)
            {
                return(null);
            }

            var currentPost = this.postsRepository.All().Where(p => p.Title == destination.Title).FirstOrDefault();

            return(currentPost);
        }
        PostGetAllDto IPostBusinessLogic.Create(PostCreateDto post)
        {
            Post createdPost = mapper.Map <Post>(post);

            ImageGetDto image = imageService.Create(new ImageCreateDto()
            {
                Image  = post.MediaPath,
                Prefix = "posts"
            });

            CreateContentScanTaskDto createContentScanTaskDto = new CreateContentScanTaskDto()
            {
                ImageUrl                                     = image != null?imageService.GetFullImageUrl(image.Url) : null,
                                                 Text        = post.Description,
                                                 CallbackUrl = $"/api/v1/trends/{post.TrendId}/posts/{createdPost.Id}/content-scan-result"
            };

            contentScanTaskService.CreateTask(createContentScanTaskDto);

            createdPost.MediaPath = image != null ? image.Url : imageService.GetDefaultImageUrl();
            postRepository.Insert(createdPost);
            postRepository.SaveChanges();

            return(mapper.Map <PostGetAllDto>(createdPost));
        }
Ejemplo n.º 8
0
        [HttpPost("add")]//+++
        public async Task <IActionResult> Add([FromForm] PostCreateDto postCreateDto)
        {
            //if (string.IsNullOrEmpty(postCreateDto.CategoryId)) return BadRequest("Kategori Seçmediniz.");
            if (postCreateDto.Image == null)
            {
                return(BadRequest("Resim Eklenmedi"));
            }


            string Id        = Guid.NewGuid().ToString();                           //resimlere guid Id şeklinde isim ataması yaptım.
            var    resimler  = Path.Combine(_environment.WebRootPath, "postImage"); //dizin bilgisi
            string imageName = $"{Id}.jpg";                                         //Db ye kaydedilecek olan resimlerin ismi

            var result = _postService.Add(postCreateDto, imageName);                //post ekleme işlemi

            if (result.Success)
            {
                if (postCreateDto.Image.Length > 0)
                {
                    using (var fileStream = new FileStream(Path.Combine(resimler, imageName), FileMode.Create))
                    {
                        await postCreateDto.Image.CopyToAsync(fileStream);
                    }
                }
                return(Ok(result.Message));
            }
            return(BadRequest(result.Message));
        }
Ejemplo n.º 9
0
        public string Create(PostCreateDto model)
        {
            try
            {
                Posts po = new Posts
                {
                    PostId        = Guid.NewGuid(),
                    ForumId       = new Guid(model.ForumId),
                    UserId        = new Guid(model.UserId),
                    Title         = model.Title,
                    Description   = model.Description,
                    CreatedDate   = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.Local),
                    Img           = null,
                    LikeNumber    = 0,
                    DisLikeNumber = 0,
                    State         = true
                };
                // 每PO一篇文 +50 points
                ForumMembers user = _members.GetAll2().FirstOrDefault(x => x.UserId.ToString() == model.UserId);
                user.Points = user.Points + 50;

                _posts.Create(po);
                _posts.SaveContext();

                _members.Update(user);
                _members.SaveContext();
                return("Po文成功,積分增加50點");
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Ejemplo n.º 10
0
        public ActionResult <PostReadDto> CreatePost(PostCreateDto post)
        {
            var postModel = _mapper.Map <Post>(post);

            _repository.CreatePost(postModel);
            _repository.SaveChanges();
            return(Ok(postModel));
        }
Ejemplo n.º 11
0
 public string Create(PostCreateDto createpost)
 {
     if (ModelState.IsValid)
     {
         return(_postservice.Create(createpost));
     }
     return("Po文失敗");
 }
Ejemplo n.º 12
0
        public async Task <int> CreateAsync(PostCreateDto model)
        {
            var entity = await _factory.MakeAsync(model);

            await _repository.AddAndSaveAsync(entity);

            return(await Task.FromResult(entity.Id));
        }
Ejemplo n.º 13
0
 public static Post ToEntity(this PostCreateDto source)
 {
     return(new Post
     {
         Description = source.Description,
         PrimaryPicture = source.PrimaryPicture,
         Title = source.Title,
     });
 }
Ejemplo n.º 14
0
        public async Task <IActionResult> CreatePost(PostCreateDto request)
        {
            bool isSuccessPost = await _postService.CreatePost(request);

            if (!isSuccessPost)
            {
                return(BadRequest());
            }
            return(Ok());
        }
Ejemplo n.º 15
0
        public ActionResult <PostReadDto> CreatePost(PostCreateDto _PostCreateDto)
        {
            var postModel = _mapper.Map <Post>(_PostCreateDto);

            _repository.createPost(postModel);
            _repository.SaveChanges();
            var postItem = _mapper.Map <PostReadDto>(postModel);

            return(Ok(postItem));
        }
Ejemplo n.º 16
0
 public async Task <long> CreateNewAsync(PostCreateDto newPost)
 {
     try
     {
         return(await _postDalFacade.InsertAndGetIdAsync(newPost));
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Ejemplo n.º 17
0
 public async Task <bool> UpdateAsync(PostCreateDto entity)
 {
     try
     {
         return(await _postDalFacade.UpdateAsync(entity));
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Ejemplo n.º 18
0
        public void Create_SavesChangesAfterInsert()
        {
            //Arrange
            PostCreateDto postCreateDto = new PostCreateDto();
            Post          mappedPost    = mapper.Map <Post>(postCreateDto);

            //Act
            systemUnderTest.Create(postCreateDto);

            //Assert
            postRepositoryMock.Verify(m => m.SaveChanges(), Times.Once);
        }
Ejemplo n.º 19
0
        public async Task <ActionResult <PostReadDto> > CreatePostAsync(PostCreateDto post)
        {
            var postModel = _mapper.Map <Post>(post);
            await _repository.CreatePostAsync(postModel);

            await _repository.SaveChangesAsync();

            var postReadDto = _mapper.Map <PostReadDto>(postModel);

            return(CreatedAtRoute(nameof(GetPostByIdAsync), new { Id = postReadDto.Id }, postReadDto));
            // return Ok(postReadDto);
        }
Ejemplo n.º 20
0
 public async Task <ResultResponse <PostGetDto> > AddPost([FromBody] PostCreateDto dto)
 {
     if (await IsInRole(Roles.Admin, Roles.Moderator))
     {
         if (dto == null || !ModelState.IsValid)
         {
             return(ResultResponse <PostGetDto> .GetBadResponse(BussinesLogic.Models.StatusCode.BadRequest));
         }
         return(await _postsService.CreatePostAsync(dto, UserId.Value));
     }
     return(ResultResponse <PostGetDto> .GetBadResponse(BussinesLogic.Models.StatusCode.Forbidden));
 }
Ejemplo n.º 21
0
        public ActionResult <PostReadDto> CreatePost(PostCreateDto postCreateDto)
        {
            var postModel = _mapper.Map <Post>(postCreateDto);

            _repository.CreatePost(postModel);
            _repository.SaveChanges();

            var postReadDto = _mapper.Map <PostReadDto>(postModel);

            return(CreatedAtRoute(nameof(GetPostById), new { Id = postReadDto.PostId }, postReadDto));
            //return created
        }
Ejemplo n.º 22
0
        public async Task <ActionResult <Post> > PostPost(PostCreateDto dto)
        {
            Post post = _mapper.Map <Post>(dto);

            _context.Posts.Add(post);

            await _context.SaveChangesAsync();

            await BroadcastPostUpdated(post.Id);

            return(Ok());
        }
Ejemplo n.º 23
0
        public async Task <Post> MakeAsync(PostCreateDto model)
        {
            model.CheckArgumentIsNull();

            var post = model.Adapt <Post>();

            post.CreateDate    = post.ModifyDate = _dateService.UtcNow();
            post.CreatorUserId = _userContext.UserId;
            post.WebsiteId     = _userContext.WebsiteId;
            if (string.IsNullOrWhiteSpace(model.Slug))
            {
                post.Slug = model.Title;
            }
            post.Slug = post.Slug.MakeSlug();

            if (post.Status == PostStatus.Published || post.Status == PostStatus.Planned)
            {
                post.PublishDate = model.PublishDate;
            }
            else
            {
                post.PublishDate = null;
            }


            if (!model.Tags.IsNullOrEmpty())
            {
                foreach (var tag in model.Tags.Split(','))
                {
                    var existingTag = await _tagRepository.GetByTitleAsync(tag, _websiteInfo.Id);

                    if (existingTag != null)
                    {
                        post.PostTags.Add(new PostTag {
                            TagId = existingTag.Id
                        });
                    }
                    else
                    {
                        var newTag = await _tagFactory.MakeAsync(tag);

                        await _tagRepository.AddAndSaveAsync(newTag);

                        post.PostTags.Add(new PostTag {
                            TagId = newTag.Id
                        });
                    }
                }
            }

            return(post);
        }
Ejemplo n.º 24
0
        public async Task <PostGetDto> CreatePostAsync(PostCreateDto postDto)
        {
            var post = _mapper.Map <Post>(postDto);

            if (postDto.Image != null)
            {
                post.ImagePath = await _imageService.UploadImageAsync(postDto.Image);
            }
            _postRepository.Add(post);
            await _postRepository.SaveChangesAsync();

            return(_mapper.Map <PostGetDto>(post));
        }
Ejemplo n.º 25
0
 public async Task <ActionResult> Create([FromForm] PostCreateDto PostCreateDto)
 {
     return(await HandleExceptions(async() =>
     {
         if (ModelState.IsValid)
         {
             var hostRoot = _hostServices.GetHostPath();
             await _postManager.AddPostAsync(PostCreateDto, hostRoot);
             return Ok();
         }
         return BadRequest("Model state is not valid");
     }));
 }
Ejemplo n.º 26
0
        public async Task <PostGetDto> CreatePostAsync(PostCreateDto post)
        {
            var dict = new Dictionary <string, string>();

            dict.Add("title", post.Title);
            dict.Add("body", post.Body);
            dict.Add("bodyMarkDown", post.BodyMarkDown);
            dict.Add("userId", post.UserId.ToString());
            var httpResponse = await _httpClient.PostAsync("/api/Post", new FormUrlEncodedContent(dict));

            PostGetDto postCreated = JsonSerializer.Deserialize <PostGetDto>(await httpResponse.Content.ReadAsStringAsync());

            return(postCreated);
        }
Ejemplo n.º 27
0
        public ActionResult <PostCreateDto> CreatePost(PostCreateDto postCreateDto)
        {
            var post = _mapper.Map <BlogPost>(postCreateDto);

            _repository.CreateBlogPost(post);

            _repository.savechanges();

            var postReadDto = _mapper.Map <PostReadDto>(post);

            /*return CreatedAtRoute(nameof(GetPostById), new { Id = post.Id }, postReadDto);*/

            return(Ok(postReadDto));
        }
Ejemplo n.º 28
0
        public async Task <long> InsertAndGetIdAsync(PostCreateDto entity)
        {
            try
            {
                var newEntity = _mapper.Map <Post>(entity);
                _context.Posts.Add(newEntity);
                await _context.SaveChangesAsync();

                return(newEntity.Id);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Ejemplo n.º 29
0
        public IActionResult CreatePost([FromBody] PostCreateDto PostDto)
        {
            if (PostDto == null)
            {
                return(BadRequest(ModelState));
            }
            var PostObj = _mapper.Map <Post>(PostDto);

            if (!_psRepo.CreatePost(PostObj))
            {
                ModelState.AddModelError("", $"Something went wrong when saving the record {PostObj.Id}");
                return(StatusCode(500, ModelState));
            }
            return(CreatedAtRoute("GetPost", new { version = HttpContext.GetRequestedApiVersion().ToString(),
                                                   PostId = PostObj.Id }, PostObj));
        }
Ejemplo n.º 30
0
        public ActionResult <PostOutDto> Create([FromBody] PostCreateDto postInDto)
        {
            if (!ModelState.IsValid || postInDto == null)
            {
                return(BadRequest(new Message("Post not valid or null")));
            }

            if (string.IsNullOrEmpty(postInDto.OwnerId))
            {
                return(BadRequest(new Message("Please give valid owner Id")));
            }

            if (string.IsNullOrEmpty(postInDto.CategoryId))
            {
                return(BadRequest(new Message("Please give valid category Id")));
            }

            if (string.IsNullOrEmpty(postInDto.Content))
            {
                return(BadRequest(new Message("Please give valid content")));
            }

            if (string.IsNullOrEmpty(postInDto.Title))
            {
                return(BadRequest(new Message("Please give valid title")));
            }

            var postIn = _mapper.Map <Post>(postInDto);

            //Check if post is being created by its owner
            var tokenUser = HttpContext.User;

            if (!AuthorizationHelpers.IsAuthorizedUser(tokenUser, postInDto.OwnerId))
            {
                return(Unauthorized(new Message("Unauthorized user.")));
            }

            //Update previous post, current post and owner.
            if (!_postRepository.Add(postIn))
            {
                return(BadRequest(new Message("Error when adding post into table. Please check owner Id")));
            }

            var postOutDto = _mapper.Map <PostOutDto>(postIn);

            return(postOutDto);
        }