示例#1
0
        protected async Task <PostResponse> CreatePostAsync(CreatePostRequest request)
        {
            var response = await httpClient.PostAsJsonAsync(ApiRoutes.Posts.Create, request);

            return(await response.Content.ReadAsAsync <PostResponse>());
        }
示例#2
0
        public ActionResult Create(CreatePostViewModel model)
        {
            if ((bool)TempData["UserAccountSuspended"])
            {
                return(RedirectToAction("Suspended", "Account"));
            }

            var    userService     = new UserService();
            var    postService     = new PostService();
            var    categoryService = new CategoryService();
            string finalFileName   = string.Empty;

            //TODO > Más adelante hay que validar el estado del usuario antes de permitir publicar.

            var user = userService.GetUserByAccountId(new GetUserByAccountIdRequest {
                AccountId = User.Identity.GetUserId()
            }).User;

            if (user != null)
            {
                model.IdWriter = user.Id;
            }

            if (ModelState.IsValid)
            {
                // Verifica si el modelo no tiene imagen, o tiene imagen y la misma tiene una extensión permitida.
                if (model.File == null ||
                    (model.File != null &&
                     (new AllowedExtensions()).ImageExtensions.Contains(Path.GetExtension(model.File.FileName).Remove(0, 1).ToLower()))
                    )
                {
                    var request = new CreatePostRequest
                    {
                        IdWriter   = model.IdWriter,
                        Title      = model.Title,
                        Summary    = model.Summary,
                        Body       = model.Body,
                        CategoryId = model.IdCategory,
                        IsDraft    = model.IsDraft,
                        Tags       = model.Tags
                    };

                    var createResult = postService.CreatePost(request);

                    if (model.File != null)
                    {
                        var pathPostPrincipalImages = ConfigurationManager.AppSettings["PathPostPrincipalImages"];
                        var newImage = new WebImage(model.File.InputStream);
                        finalFileName = createResult.PostId.ToString() + Path.GetExtension(model.File.FileName);
                        var directory = Server.MapPath(pathPostPrincipalImages);

                        // Se crea el directorio; si ya existe el directorio, la función no hace nada.
                        Directory.CreateDirectory(directory);
                        var finalpath = directory + finalFileName;

                        newImage.Save(finalpath);

                        var updateResult = postService.UpdatePost(new UpdatePostRequest
                        {
                            Id                 = createResult.PostId,
                            Title              = model.Title,
                            Summary            = model.Summary,
                            Body               = model.Body,
                            IdCategory         = model.IdCategory,
                            IsDraft            = model.IsDraft,
                            PrincipalImageName = finalFileName,
                            Tags               = model.Tags
                        });
                    }

                    return(RedirectToAction("Index", "Post"));
                }
                else
                {
                    ModelState.AddModelError("", "La extensión de la imagen no es válida, vuelva a cargarla.");
                }
            }

            var categories = categoryService.SearchCategories(new SearchCategoriesRequest()).Categories;

            ViewBag.Categories = categories.Select(x => new SelectListItem()
            {
                Text  = x.Title,
                Value = x.Id.ToString()
            });

            return(View(model));
        }
示例#3
0
        public async Task <CreatePostResponse> Create([FromBody] CreatePostRequest request)
        {
            Guid currentUserId = await this.userLogged.GetUserId();

            return(await this.postService.CreatePost(currentUserId, request.Description, request.Alias, request.ColorProfileUsed));
        }
示例#4
0
        public Response <PostEntity> CreateNewPost(CreatePostRequest request)
        {
            return(TryExecute(() =>
            {
                var postModel = new PostEntity
                {
                    CommentEnabled = request.EnableComment,
                    Id = Guid.NewGuid(),
                    PostContent = _htmlCodec.HtmlEncode(request.HtmlContent),
                    ContentAbstract = Utils.GetPostAbstract(request.HtmlContent, AppSettings.PostSummaryWords),
                    CreateOnUtc = DateTime.UtcNow,
                    Slug = request.Slug.ToLower().Trim(),
                    Title = request.Title.Trim(),
                    PostPublish = new PostPublishEntity
                    {
                        IsDeleted = false,
                        IsPublished = request.IsPublished,
                        PubDateUtc = request.IsPublished ? DateTime.UtcNow : (DateTime?)null,
                        ExposedToSiteMap = request.ExposedToSiteMap,
                        IsFeedIncluded = request.IsFeedIncluded,
                        Revision = 0,
                        ContentLanguageCode = request.ContentLanguageCode
                    },
                    PostExtension = new PostExtensionEntity
                    {
                        Hits = 0,
                        Likes = 0
                    }
                };

                // check if exist same slug under the same day
                // linq to sql fix:
                // cannot write "p.PostPublish.PubDateUtc.GetValueOrDefault().Date == DateTime.UtcNow.Date"
                // it will not blow up, but can result in select ENTIRE posts and evaluated in memory!!!
                // - The LINQ expression 'where (Convert([p.PostPublish]?.PubDateUtc?.GetValueOrDefault(), DateTime).Date == DateTime.UtcNow.Date)' could not be translated and will be evaluated locally
                // Why EF Core this diao yang?
                if (_postRepository.Any(p =>
                                        p.Slug == postModel.Slug &&
                                        p.PostPublish.PubDateUtc != null &&
                                        p.PostPublish.PubDateUtc.Value.Year == DateTime.UtcNow.Date.Year &&
                                        p.PostPublish.PubDateUtc.Value.Month == DateTime.UtcNow.Date.Month &&
                                        p.PostPublish.PubDateUtc.Value.Day == DateTime.UtcNow.Date.Day))
                {
                    var uid = Guid.NewGuid();
                    postModel.Slug += $"-{uid.ToString().ToLower().Substring(0, 8)}";
                    Logger.LogInformation($"Found conflict for post slug, generated new slug: {postModel.Slug}");
                }

                // add categories
                if (null != request.CategoryIds && request.CategoryIds.Length > 0)
                {
                    foreach (var cid in request.CategoryIds)
                    {
                        if (_categoryRepository.Any(c => c.Id == cid))
                        {
                            postModel.PostCategory.Add(new PostCategoryEntity
                            {
                                CategoryId = cid,
                                PostId = postModel.Id
                            });
                        }
                    }
                }

                // add tags
                if (null != request.Tags && request.Tags.Length > 0)
                {
                    foreach (var item in request.Tags)
                    {
                        var tag = _tagRepository.Get(q => q.DisplayName == item);
                        if (null == tag)
                        {
                            var newTag = new TagEntity
                            {
                                DisplayName = item,
                                NormalizedName = Utils.NormalizeTagName(item)
                            };

                            tag = _tagRepository.Add(newTag);
                        }

                        postModel.PostTag.Add(new PostTagEntity
                        {
                            TagId = tag.Id,
                            PostId = postModel.Id
                        });
                    }
                }

                _postRepository.Add(postModel);
                Logger.LogInformation($"New Post Created Successfully. PostId: {postModel.Id}");
                return new SuccessResponse <PostEntity>(postModel);
            }));
        }
示例#5
0
        public async Task <PostEntity> CreateAsync(CreatePostRequest request)
        {
            var abs = GetPostAbstract(
                request.EditorContent, AppSettings.PostAbstractWords,
                AppSettings.Editor == EditorChoice.Markdown);

            var post = new PostEntity
            {
                CommentEnabled      = request.EnableComment,
                Id                  = Guid.NewGuid(),
                PostContent         = request.EditorContent,
                ContentAbstract     = abs,
                CreateOnUtc         = DateTime.UtcNow,
                Slug                = request.Slug.ToLower().Trim(),
                Title               = request.Title.Trim(),
                ContentLanguageCode = request.ContentLanguageCode,
                ExposedToSiteMap    = request.ExposedToSiteMap,
                IsFeedIncluded      = request.IsFeedIncluded,
                PubDateUtc          = request.IsPublished ? DateTime.UtcNow : (DateTime?)null,
                IsDeleted           = false,
                IsPublished         = request.IsPublished,
                PostExtension       = new PostExtensionEntity
                {
                    Hits  = 0,
                    Likes = 0
                }
            };

            // check if exist same slug under the same day
            // linq to sql fix:
            // cannot write "p.PubDateUtc.GetValueOrDefault().Date == DateTime.UtcNow.Date"
            // it will not blow up, but can result in select ENTIRE posts and evaluated in memory!!!
            // - The LINQ expression 'where (Convert([p]?.PubDateUtc?.GetValueOrDefault(), DateTime).Date == DateTime.UtcNow.Date)' could not be translated and will be evaluated locally
            // Why EF Core this diao yang?
            if (_postRepository.Any(p =>
                                    p.Slug == post.Slug &&
                                    p.PubDateUtc != null &&
                                    p.PubDateUtc.Value.Year == DateTime.UtcNow.Date.Year &&
                                    p.PubDateUtc.Value.Month == DateTime.UtcNow.Date.Month &&
                                    p.PubDateUtc.Value.Day == DateTime.UtcNow.Date.Day))
            {
                var uid = Guid.NewGuid();
                post.Slug += $"-{uid.ToString().ToLower().Substring(0, 8)}";
                Logger.LogInformation($"Found conflict for post slug, generated new slug: {post.Slug}");
            }

            // add categories
            if (null != request.CategoryIds && request.CategoryIds.Length > 0)
            {
                foreach (var cid in request.CategoryIds)
                {
                    if (_categoryRepository.Any(c => c.Id == cid))
                    {
                        post.PostCategory.Add(new PostCategoryEntity
                        {
                            CategoryId = cid,
                            PostId     = post.Id
                        });
                    }
                }
            }

            // add tags
            if (null != request.Tags && request.Tags.Length > 0)
            {
                foreach (var item in request.Tags)
                {
                    if (!TagService.ValidateTagName(item))
                    {
                        continue;
                    }

                    var tag = await _tagRepository.GetAsync(q => q.DisplayName == item);

                    if (null == tag)
                    {
                        var newTag = new TagEntity
                        {
                            DisplayName    = item,
                            NormalizedName = TagService.NormalizeTagName(item)
                        };

                        tag = await _tagRepository.AddAsync(newTag);

                        await _blogAudit.AddAuditEntry(EventType.Content, AuditEventId.TagCreated,
                                                       $"Tag '{tag.NormalizedName}' created.");
                    }

                    post.PostTag.Add(new PostTagEntity
                    {
                        TagId  = tag.Id,
                        PostId = post.Id
                    });
                }
            }

            await _postRepository.AddAsync(post);

            await _blogAudit.AddAuditEntry(EventType.Content, AuditEventId.PostCreated, $"Post created, id: {post.Id}");

            return(post);
        }
示例#6
0
        public async Task <Guid> CreatePost(CreatePostRequest request)
        {
            var postId = await ProcessRequest(request, _postsRepository.CreatePost);

            return(postId);
        }
示例#7
0
        private async void PublishExecute()
        {
            if (!_findierService.IsAuthenticated)
            {
                NavigationService.Navigate(typeof(AuthenticationPage), true);
                return;
            }

            var     type  = PostType.Freebie;
            decimal price = 0;

            if (IsFixed)
            {
                type = PostType.Fixed;
                // convert the price into a decimal
                if (!decimal.TryParse(Price, out price) || price < 1)
                {
                    CurtainPrompt.ShowError("Please enter a valid price.");
                    return;
                }
            }
            else if (IsMoney)
            {
                type = PostType.Money;
            }

            if (string.IsNullOrWhiteSpace(Title))
            {
                CurtainPrompt.ShowError("Don't forget to set a title!");
                return;
            }
            if (Title.Length < 5)
            {
                CurtainPrompt.ShowError("The title is a bit too short.");
                return;
            }

            if (!string.IsNullOrWhiteSpace(Email) && !Email.IsEmail())
            {
                CurtainPrompt.ShowError("Please enter a valid email.");
                return;
            }

            if (!string.IsNullOrWhiteSpace(PhoneNumber) && !PhoneNumber.IsPhoneNumber())
            {
                CurtainPrompt.ShowError("Please enter a valid phone number.");
                return;
            }

            if (string.IsNullOrWhiteSpace(Email) &&
                string.IsNullOrWhiteSpace(PhoneNumber))
            {
                CurtainPrompt.ShowError("Please enter at least one contact method.");
                return;
            }

            var createPostRequest = new CreatePostRequest(_category.Id,
                                                          Title,
                                                          Text,
                                                          type,
                                                          price,
                                                          IsNsfw,
                                                          Email,
                                                          PhoneNumber);

            IsLoading = true;
            var restResponse = await _findierService.SendAsync <CreatePostRequest, string>(createPostRequest);

            IsLoading = false;

            if (restResponse.IsSuccessStatusCode)
            {
                CurtainPrompt.Show("You post is live!");
                NavigationService.GoBack();
            }
            else
            {
                CurtainPrompt.ShowError(restResponse.DeserializedResponse?.Error
                                        ?? "Problem publishing post. Try again later.");
            }

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

            if (restResponse.IsSuccessStatusCode)
            {
                props.Add("Error", restResponse.DeserializedResponse?.Error ?? "Unknown");
                props.Add("StatusCode", restResponse.StatusCode.ToString());
            }
            _insightsService.TrackEvent("PublishPost", props);
        }
示例#8
0
 public async Task <OkObjectResult> Create(CreatePostRequest request)
 {
     return(Ok(await postService.CreatePost(request)));
 }
示例#9
0
        public async Task <BaseResponseDto <PostDto> > Post([FromBody] CreatePostRequest createPostRequest)
        {
            BaseResponseDto <PostDto> response = await _mediator.Send(createPostRequest);

            return(response);
        }
示例#10
0
 public async Task <CreatePostResult> CreatePost(CreatePostRequest request)
 {
     return(await postRepository.CreatePost(request));
 }
示例#11
0
        public async Task <PostVM> CreatePost(CreatePostRequest request, string id, string fullName)
        {
            // Tên file hình ảnh có thêm ngày tháng năm tạo, được chuyển vào lưu tại thư mục
            //                                                      /Blog.API1/wwwRoot/Image
            //string wwwRoot = Path.GetFullPath(Directory.GetParent(Directory.GetCurrentDirectory()) + "\\Blog.API1\\wwwroot\\ImageNash");


            //string wwwRoot = Path.GetFullPath(Directory.GetParent(Directory.GetCurrentDirectory())
            //    + "\\"
            //    + Assembly.GetCallingAssembly().GetName().Name
            //    + "\\wwwroot\\Image");
            //string fileName = Path.Combine(wwwRoot,
            //    (Path.GetFileNameWithoutExtension(request.ImageFileName.FileName)
            //    + "_" + DateTime.Now.ToString("yymmss")
            //    + Path.GetExtension(request.ImageFileName.FileName)));

            string fileName = CreateFileNamePath(request.ImageFileName);

            try
            {
                using (Stream stream = new FileStream(fileName, FileMode.Create))
                {
                    await request.ImageFileName.CopyToAsync(stream);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            var newPost = new Post()
            {
                Title         = request.Title,
                Content       = request.Content,
                DateCreated   = DateTime.Now,
                Caption       = request.Caption,
                Id            = id,
                Author        = fullName,
                ImageFileName = fileName
            };

            _context.Add(newPost);
            int ketQua = await _context.SaveChangesAsync();

            var postVM = new PostVM()
            {
                PostID        = newPost.PostID,
                Title         = newPost.Title,
                DateCreated   = newPost.DateCreated,
                Caption       = newPost.Caption,
                Author        = newPost.Author,
                ImageFileName = Path.GetFileName(newPost.ImageFileName),
                Content       = newPost.Content,
                ListComments  = new List <CommentVM>()
            };

            if (ketQua == 0)
            {
                postVM = null;
            }

            return(postVM);
        }
示例#12
0
 public int CreatePost(CreatePostRequest rq)
 {
     return(_repository.CreatePost(rq));
 }
示例#13
0
 public async Task <CreatePostResponse> CreatePost(CreatePostRequest request)
 {
     return(await Post <CreatePostResponse>(Endpoints.Posts.CreatePost, request));
 }
        private async Task <PostResponse> CreatePostAsync(CreatePostRequest createPostRequest)
        {
            var response = await this.client.PostAsJsonAsync(ApiRoutes.Posts.Create, createPostRequest);

            return(await response.Content.ReadAsAsync <PostResponse>());
        }
示例#15
0
        public async Task <IActionResult> CreatePost([FromBody] CreatePostRequest request)
        {
            await _createPostCreatePostCommandHandler.Handle(new CreatePostCommand(request.Title, request.Content, request.Tags));

            return(Ok());
        }