コード例 #1
0
        private async Task <T> GetPostsWithScratchIfUserValid <T>(BlogPostDto post)
            where T : class, IBlogPost
        {
            var result = await GetPostsWithScratchIfUserValid <T>(new[] { post });

            return(result.FirstOrDefault());
        }
コード例 #2
0
        public void Post([FromBody] BlogPostDto blogPostDto)
        {
            string toSlug = blogPostDto.Title.ToString();

            blogPostDto.Slug = StringHelper.UrlFriendly(toSlug);

            string tags = "";

            foreach (var tag in blogPostDto.TagList)
            {
                tags += tag + ",";
            }
            tags = tags.Remove(tags.LastIndexOf(","));

            BlogPost blogPostToInsert = new BlogPost();

            blogPostToInsert.Slug        = blogPostDto.Slug;
            blogPostToInsert.Body        = blogPostDto.Body;
            blogPostToInsert.Description = blogPostDto.Description;
            blogPostToInsert.Title       = blogPostDto.Title;
            blogPostToInsert.CreatedAt   = blogPostDto.CreatedAt;
            blogPostToInsert.UpdatedAt   = blogPostDto.UpdatedAt;
            blogPostToInsert.Tags        = tags;

            _repo.Add(blogPostToInsert);
        }
コード例 #3
0
        public async Task <IEnumerable <BlogPostDto> > GetAllBlogPosts()
        {
            var posts = new List <BlogPostDto>();

            try
            {
                using (var connection = new SqlConnection(_connectionString))
                {
                    connection.Open();

                    string     sqlProcedure = "GetAllBlogPosts";
                    SqlCommand command      = new SqlCommand(sqlProcedure, connection);
                    command.CommandType = CommandType.StoredProcedure;

                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (await reader.ReadAsync().ConfigureAwait(false))
                        {
                            var postDto = new BlogPostDto();

                            postDto = MapToBlogPost(reader);

                            posts.Add(postDto);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }

            return(posts);
        }
コード例 #4
0
ファイル: BlogController.cs プロジェクト: emreoz37/MyBlog
        public IActionResult CreatePost([FromBody] BlogPostForCreationDto blogPost)
        {
            try
            {
                if (blogPost == null)
                {
                    _logger.LogError("BlogPost object sent from client is null.");
                    return(BadRequest("BlogPost object is null"));
                }

                if (!ModelState.IsValid)
                {
                    _logger.LogError("Invalid blogpost object sent from client.");
                    return(BadRequest("Invalid model object"));
                }


                var blogPostEntity = blogPost.ToEntity <BlogPost>();
                blogPostEntity.CreatedOnUtc = DateTime.UtcNow;
                _blogService.InsertBlogPost(blogPostEntity);

                var blogPostDto = new BlogPostDto();
                _blogFactory.PrepareBlogPostResponse(blogPostDto, blogPostEntity, false);

                return(CreatedAtRoute("PostById", new { id = blogPostDto.Id }, blogPostDto));
            }
            catch (Exception ex)
            {
                var logMessage = $"BlogController PostCreate Method. Something went wrong. Request : { JsonConvert.SerializeObject(blogPost) } Ex Message : { ex.Message }";
                _logger.LogError(ex, logMessage);
                return(StatusCode(500, "Internal server error"));
            }
        }
コード例 #5
0
        public async Task <IEnumerable <BlogPostDto> > GetRecomendedBlogs(int id)
        {
            var output = new List <BlogPostDto>();

            try
            {
                using (var connection = new SqlConnection(_connectionString))
                {
                    connection.Open();

                    string     sqlProcedure = "GetRecomendedBlogs";
                    SqlCommand command      = new SqlCommand(sqlProcedure, connection);
                    command.CommandType = CommandType.StoredProcedure;

                    command.Parameters.AddWithValue("@Id", id);

                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (await reader.ReadAsync().ConfigureAwait(false))
                        {
                            var blogPostDto = new BlogPostDto();
                            blogPostDto = MapToBlogPost(reader);

                            output.Add(blogPostDto);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }

            return(output);
        }
コード例 #6
0
        public async Task <BlogPostDto> GetBlogPostById(int id)
        {
            var postDto = new BlogPostDto();

            try
            {
                using (var connection = new SqlConnection(_connectionString))
                {
                    connection.Open();

                    string     sqlProcedure = "GetBlogPostById";
                    SqlCommand command      = new SqlCommand(sqlProcedure, connection);
                    command.CommandType = CommandType.StoredProcedure;

                    command.Parameters.AddWithValue("@Id", id);

                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (await reader.ReadAsync().ConfigureAwait(false))
                        {
                            postDto = MapToBlogPost(reader);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }

            return(postDto);
        }
コード例 #7
0
        public bool InsertBlogPost(BlogPostDto blogPostDto)
        {
            bool result = true;

            try
            {
                using (var connection = new SqlConnection(_connectionString))
                {
                    connection.Open();

                    string     sqlProcedure = "InsertBlogPost";
                    SqlCommand command      = new SqlCommand(sqlProcedure, connection);
                    command.CommandType = CommandType.StoredProcedure;

                    command.Parameters.AddWithValue("@UserName", blogPostDto.UserName);
                    command.Parameters.AddWithValue("@CategoryId", blogPostDto.CategoryId);
                    command.Parameters.AddWithValue("@Title", blogPostDto.Title);
                    command.Parameters.AddWithValue("@Description", blogPostDto.Description);
                    command.Parameters.AddWithValue("@Content", blogPostDto.Content);
                    command.Parameters.AddWithValue("@MainImage", blogPostDto.MainImage);
                    command.Parameters.AddWithValue("@Promote", blogPostDto.Promote);
                    command.Parameters.AddWithValue("@Created", blogPostDto.Created);

                    command.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                result = false;
            }

            return(result);
        }
コード例 #8
0
        public BlogPostDto GetBlogPostBySlug(string slug)
        {
            BlogPost blogPost = BlogDBContext.BlogPosts.Where(m => m.Slug == slug).FirstOrDefault();

            if (blogPost == null)
            {
                throw new ArgumentException();
            }

            BlogPostDto blogPostDto = MapFromDb(blogPost);

            try
            {
                if (blogPost.BlogPostTags.ToList() != null || blogPost.BlogPostTags.Count != 0)
                {
                    List <BlogPostTags> blogPostTags = blogPost.BlogPostTags.ToList();
                    foreach (BlogPostTags blog in blogPostTags)
                    {
                        blogPostDto.TagList.Add(blog.Tag.Name);
                    }
                }
                return(blogPostDto);
            }
            catch (ArgumentNullException e)
            {
                return(blogPostDto);
            }
        }
コード例 #9
0
ファイル: BlogController.cs プロジェクト: emreoz37/MyBlog
        public IActionResult GetPostId(int id)
        {
            try
            {
                var blogPost = _blogService.GetBlogPostById(id);
                if (blogPost == null)
                {
                    _logger.LogError("BlogPost object sent from client is null.");
                    return(NotFound());
                }

                _logger.LogInformation($"Returned blog with id: {id}");
                var blogPostDto = new BlogPostDto();
                _blogFactory.PrepareBlogPostResponse(blogPostDto, blogPost, false);

                if (blogPostDto.NumberOfComments > 0)
                {
                    blogPostDto.PostWithCommentsLink = new BaseLinkInfo
                    {
                        Href   = Url.Link("GetPostWithComments", new { blogPostDto.Id }),
                        Rel    = "postWithCommentsPage",
                        Method = HttpMethods.Get.ToString()
                    };
                }

                return(Ok(blogPostDto));
            }
            catch (Exception ex)
            {
                var logMessage = $"BlogController GetPostId Method. Something went wrong. Ex Message : { ex.Message }";
                _logger.LogError(ex, logMessage);
                return(StatusCode(500, "Internal server error"));
            }
        }
コード例 #10
0
        public async Task Test4()
        {
            var dbContext = Setup.ServiceProvider.GetService <SqliteConnection>();
            var time      = DateTimeOffset.UtcNow;
            var blogPost  = new BlogPostDto
            {
                Title          = "SqLite",
                DeprecatedDate = time
            };

            var(sql, parameters) = blogPost.CreateInsertSqlStatement(ConnectionType.SqLite);
            await dbContext.ExecuteAsync(sql, parameters).ConfigureAwait(false);

            var results = await dbContext.QueryAsync <BlogPostDto>("select Id, Title, DeprecatedDate from blog_Posts").ConfigureAwait(false);

            var comment = new CommentDto
            {
                BlogPostId = 2,
                Comment    = "Hello world!"
            };

            (sql, parameters) = comment.CreateInsertSqlStatement(ConnectionType.SqLite);
            await dbContext.ExecuteAsync(sql, parameters).ConfigureAwait(false);

            Assert.AreEqual(1, results.First().Id);
            Assert.AreEqual("SqLite", results.First().Title);
            Assert.AreEqual(time, results.First().DeprecatedDate);
        }
コード例 #11
0
        public async Task <IActionResult> AddBlogPost([FromBody] BlogPostDto post)
        {
            if (post == null)
            {
                return(BadRequest("Blog object is null."));
            }
            if (post.Id != 0)
            {
                return(BadRequest("Post Id is not zero."));
            }
            if (post.BlogId == 0)
            {
                return(BadRequest("BlogId is zero."));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            else
            {
                await _blogCommands.AddBlogPostAsync(post);
            }

            return(CreatedAtAction(nameof(AddBlogPost), post));
        }
コード例 #12
0
ファイル: BlogFeature.cs プロジェクト: pekkah/tanka
        private void PublishBlogPost(BlogPostDto post)
        {
            post.State = DocumentState.Published;
            post.PublishedOn = DateTimeOffset.Now;

            var result = Post("api/admin/blogposts", post);
            result.StatusCode.ShouldBeEquivalentTo(HttpStatusCode.OK);
        }
コード例 #13
0
ファイル: AdminService.cs プロジェクト: oguzc/blog-insecure
        public async Task CreatePost(BlogPostDto blogPostDto, string token)
        {
            var requestMessage = _apiClient.CreatePostRequest($"{_appSettings.AdminApiUrl}{BasePath}/CreatePost", blogPostDto);

            requestMessage.Headers.Add("Authorization", "Bearer " + token);
            var response = await _apiClient.SendAsync(requestMessage);

            string responseBody = await response.Content.ReadAsStringAsync();
        }
コード例 #14
0
        public void InsertBlogPost(BlogPostDto blogPostDto)
        {
            var blogPost = new Repository.Domain.Blog.BlogPost()
            {
                CreatedOnUtc = DateTime.UtcNow, BlogId = blogPostDto.BlogId, Body = blogPostDto.BlogPostBody, Title = blogPostDto.BlogPostTitle
            };

            _unitOfWork.BlogPosts.Insert(blogPost);
            _unitOfWork.Commit();
            _cacheManager.RemoveByPattern(BlogpostPatternKey);
        }
コード例 #15
0
 public static EditBlogPostCommand ToCommand(this BlogPostDto blogPost)
 {
     return(new EditBlogPostCommand
     {
         Title = blogPost.Title,
         Body = blogPost.Body,
         BlogTags = blogPost.BlogTags.ToCommand(),
         //  BlogCategories = blogPost.BlogCategory.ToCommand(),
         BlogPictures = blogPost.BlogPictures.ToCommand()
     });
 }
コード例 #16
0
        public IActionResult AddBlogPost(int blogId)
        {
            BlogPostDto blogPost = new BlogPostDto();
            BlogDto     blog     = _blogQueries.GetBlog(blogId);

            blogPost.BlogId          = blogId;
            blogPost.BlogDisplayName = blog.DisplayName;
            blogPost.PostStatusId    = (int)PostStatuses.Draft;
            blogPost.CommentStatusId = (int)CommentStatuses.MemberOnly;
            return(Ok(blogPost));
        }
コード例 #17
0
        protected override void OnInitialized()
        {
            //Llamar a backend con el id para obtener el objeto BlogPost

            BlogPostModel = new BlogPostDto
            {
                Title       = "The Title",
                Date        = DateTime.Now,
                Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
            };

            //Agregar boton para volver a la lista de posts.
        }
コード例 #18
0
        private static BlogPostDto MapFromDb(BlogPost blogPost)
        {
            BlogPostDto blogPostDto = new BlogPostDto();

            blogPostDto.Slug        = blogPost.Slug;
            blogPostDto.Title       = blogPost.Title;
            blogPostDto.Description = blogPost.Description;
            blogPostDto.Body        = blogPost.Body;
            blogPostDto.CreatedAt   = blogPost.CreatedAt;
            blogPostDto.UpdatedAt   = blogPost.UpdatedAt;

            return(blogPostDto);
        }
コード例 #19
0
        private void SetPropertiesFromModel(BlogPostDto objDb, BlogPostViewModel post)
        {
            var previousId = post?.Previous?.Id;
            var nextId     = post?.Next?.Id;

            objDb.PreviousId = previousId == 0 ? null : previousId;
            objDb.NextId     = nextId == 0 ? null : nextId;
            objDb.CategoryId = post.Category.Id;
            objDb.Previous   = null;
            objDb.Next       = null;
            objDb.Category   = null;
            objDb.Tags       = string.Join(',', post.Tags);
        }
コード例 #20
0
        //Q [MapToApiVersion("1.0")]
        public async Task <IActionResult> Post([FromBody] BlogPostDto blogPostDto)
        {
            var command = new CreatePostCommand()
            {
                Title        = blogPostDto.Title,   // "",
                Content      = blogPostDto.Content, //"Great Blog Content",
                CreationDate = DateTime.Now,
                IsArchived   = blogPostDto.IsArchived
            };

            var result = await mediator.Send(command);

            return(result is null?BadRequest(result) : (IActionResult)Created("New post created", result));
        }
コード例 #21
0
        public void UpdateBlogPost(BlogPostDto blogPostDto)
        {
            var blogPost = _unitOfWork.BlogPosts.GetById(blogPostDto.BlogPostId);

            if (blogPost != null)
            {
                blogPost.Body  = blogPostDto.BlogPostBody;
                blogPost.Title = blogPostDto.BlogPostTitle;

                _unitOfWork.BlogPosts.Update(blogPost);
                _unitOfWork.Commit();
                _cacheManager.RemoveByPattern(BlogpostPatternKey);
            }
        }
コード例 #22
0
        public BlogPostDto MapToBlogPost(SqlDataReader reader)
        {
            var post = new BlogPostDto();

            post.Id                  = Convert.ToInt32(reader["Id"]);
            post.CategoryId          = Convert.ToInt32(reader["CategoryId"]);
            post.CategoryDescription = reader["CategoryDescription"].ToString();
            post.UserName            = reader["UserName"].ToString();
            post.Title               = reader["Title"].ToString();
            post.Description         = reader["Description"].ToString();
            post.Content             = reader["Content"].ToString();
            post.MainImage           = reader["MainImage"].ToString();
            post.Promote             = Convert.ToBoolean(reader["Promote"]);
            post.Created             = Convert.ToDateTime(reader["Created"]);

            return(post);
        }
コード例 #23
0
        public static BlogPostViewModel MapTo(BlogPostDto blogPostDto)
        {
            var blogPostViewModel = new BlogPostViewModel();

            blogPostViewModel.Id                  = blogPostDto.Id;
            blogPostViewModel.UserName            = blogPostDto.UserName;
            blogPostViewModel.CategoryId          = blogPostDto.CategoryId;
            blogPostViewModel.CategoryDescription = blogPostDto.CategoryDescription;
            blogPostViewModel.Title               = blogPostDto.Title;
            blogPostViewModel.Description         = blogPostDto.Description.Length >= 300 ?  $"{blogPostDto.Description.Substring(0, 300)} ..." : blogPostDto.Description;
            blogPostViewModel.Content             = blogPostDto.Content;
            blogPostViewModel.MainImage           = blogPostDto.MainImage;
            blogPostViewModel.Promote             = blogPostDto.Promote;
            blogPostViewModel.Created             = blogPostDto.Created;

            return(blogPostViewModel);
        }
コード例 #24
0
        public static BlogPostDto MapFrom(BlogPostViewModel blogPostViewModel)
        {
            var blogPostDto = new BlogPostDto();

            blogPostDto.Id                  = blogPostViewModel.Id;
            blogPostDto.UserName            = blogPostViewModel.UserName;
            blogPostDto.CategoryId          = blogPostViewModel.CategoryId;
            blogPostDto.CategoryDescription = blogPostViewModel.CategoryDescription;
            blogPostDto.Title               = blogPostViewModel.Title;
            blogPostDto.Description         = blogPostViewModel.Description;
            blogPostDto.Content             = blogPostViewModel.Content;
            blogPostDto.MainImage           = blogPostViewModel.MainImage;
            blogPostDto.Promote             = blogPostViewModel.Promote;
            blogPostDto.Created             = blogPostViewModel.Created;

            return(blogPostDto);
        }
コード例 #25
0
        public async Task <ItemResult <BlogPostDto> > AddAsync(BlogPostDto blogPost)
        {
            var url     = $"{_blogUrl}";
            var postStr = JsonConvert.SerializeObject(blogPost, new JsonSerializerSettings()
            {
                DateFormatHandling   = DateFormatHandling.IsoDateFormat,
                DateTimeZoneHandling = DateTimeZoneHandling.Local
            });


            var response = await PostResponseAsync(url, postStr);

            var result = new ItemResult <BlogPostDto>
            {
                StatusCode = (int)response.StatusCode
            };

            if (!response.IsSuccessStatusCode)
            {
                result.IsFailed = true;
                switch ((int)response.StatusCode)
                {
                case StatusCode.Status422UnprocessableEntity:
                {
                    result.Massage = "Има некоректно попълнени данни! Моля попълнете всички полета коректно";
                    break;
                }

                default:
                {
                    result.Massage = "Възникна грешка моля опитайте отново";
                    break;
                }
                }
            }
            else
            {
                result.Massage = "Поста беше добавен успешно";
                var jsonResult = await response.Content.ReadAsStringAsync();

                result.Result = JsonConvert.DeserializeObject <BlogPostDto>(jsonResult);
            }

            return(result);
        }
コード例 #26
0
ファイル: BlogFeature.cs プロジェクト: pekkah/tanka
        private BlogPostDto WriteBlogPost(string title, string content)
        {
            var post = new BlogPostDto
            {
                Title = title,
                Slug = Snail.ToSlug(title),
                Content = content,
                ModifiedOn = DateTimeOffset.UtcNow,
                PublishedOn = null
            };

            var result = Post("api/admin/blogposts", post);

            result.StatusCode.ShouldBeEquivalentTo(HttpStatusCode.Created);

            var getResult = Get(result.Headers["Location"]);

            return getResult.ToObject<BlogPostDto>();
        }
コード例 #27
0
        public async Task <NoDataResult> EditAsync(BlogPostDto blogPost, Guid id)
        {
            var url     = $"{_blogUrl}({id})";
            var postStr = JsonConvert.SerializeObject(blogPost, new JsonSerializerSettings()
            {
                DateFormatHandling   = DateFormatHandling.IsoDateFormat,
                DateTimeZoneHandling = DateTimeZoneHandling.Local
            });
            var response = await PutResponseAsync(url, postStr);

            var result = new NoDataResult
            {
                StatusCode = (int)response.StatusCode
            };

            if (!response.IsSuccessStatusCode)
            {
                result.IsFailed = true;
                switch ((int)response.StatusCode)
                {
                case StatusCode.Status422UnprocessableEntity:
                {
                    result.Massage = "Има некоректно попълнени данни! Моля попълнете всички полета коректно";
                    break;
                }

                default:
                {
                    result.Massage = "Възникна грешка моля опитайте отново";
                    break;
                }
                }
            }
            else
            {
                result.Massage = "Поста беше редактиран успешно";
            }

            return(result);
        }
コード例 #28
0
        public BlogPost Update(string slug, [FromBody] BlogPostDto blogPostDto)
        {
            string tags = "";

            foreach (var tag in blogPostDto.TagList)
            {
                tags += tag + ",";
            }
            tags = tags.Remove(tags.LastIndexOf(","));

            BlogPost blogPost = new BlogPost();

            blogPost.Slug        = blogPostDto.Slug;
            blogPost.Body        = blogPostDto.Body;
            blogPost.Description = blogPostDto.Description;
            blogPost.Title       = blogPostDto.Title;
            blogPost.CreatedAt   = blogPostDto.CreatedAt;
            blogPost.UpdatedAt   = blogPostDto.UpdatedAt;
            blogPost.Tags        = tags;

            return(_repo.Update(slug, blogPost));
        }
コード例 #29
0
        public async Task <BlogPostDto> GetBlogPost(int id)
        {
            var entity = await Context.BlogPost
                         .Include(i => i.Blog)
                         .Include(i => i.Post).ThenInclude(i => i.PostTag).ThenInclude(i => i.Tag)
                         .Include(i => i.Post).ThenInclude(i => i.PostAuthor)
                         .Where(i => i.PostId == id).FirstOrDefaultAsync();

            if (entity == null)
            {
                throw new ArgumentException("Invalid post id");
            }

            BlogPostDto blogPost = new BlogPostDto()
            {
                Id              = entity.Post.Id,
                GUID            = entity.Post.GUID,
                BlogDisplayName = entity.Blog.DisplayName,
                BlogId          = entity.BlogId,
                CommentCount    = entity.Post.CommentCount,
                CommentStatusId = entity.Post.CommentStatusId,
                Excerpt         = entity.Post.Excerpt,
                PostContent     = entity.Post.PostContent,
                PostStatusId    = entity.Post.PostStatusId,
                Title           = entity.Post.Title,
                UpdatedAt       = entity.Post.UpdatedAt
            };

            blogPost.Tags.AddRange(entity.Post.PostTag.Select(i => i.Tag.Name).ToList());

            var pa = entity.Post.PostAuthor.FirstOrDefault(i => i.PostId == id && i.IsPrimary);

            if (pa != null)
            {
                blogPost.PrimaryAuthorId = pa.AuthorId;
            }
            return(blogPost);
        }
コード例 #30
0
ファイル: BlogController.cs プロジェクト: emreoz37/MyBlog
        public IActionResult GetPostWithComments(int id)
        {
            try
            {
                var blogPost = _blogService.GetBlogPostById(id);
                if (blogPost == null)
                {
                    _logger.LogError("BlogPost object sent from client is null.");
                    return(NotFound());
                }

                _logger.LogInformation($"Returned blog with comments id: {id}");
                var blogPostDto = new BlogPostDto();
                _blogFactory.PrepareBlogPostResponse(blogPostDto, blogPost, true);
                return(Ok(blogPostDto));
            }
            catch (Exception ex)
            {
                var logMessage = $"BlogController GetPostId Method. Something went wrong. Ex Message : { ex.Message }";
                _logger.LogError(ex, logMessage);
                return(StatusCode(500, "Internal server error"));
            }
        }
コード例 #31
0
        public async Task <IActionResult> CreateAsync(IFormCollection collection)
        {
            try
            {
                var imageFile = Request?.Form.Files[0];

                if (imageFile != null && imageFile.Length > 0 && imageFile.ContentType.Contains("image"))
                {
                    var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images/blog-images", imageFile.FileName);

                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        await imageFile.CopyToAsync(stream);
                    }
                }

                var blogPostDto = new BlogPostDto();

                blogPostDto.CategoryId  = Convert.ToInt32(collection["CategoryId"]);
                blogPostDto.UserName    = User.Identity.Name;
                blogPostDto.Title       = collection["Title"];
                blogPostDto.Description = collection["Description"];
                blogPostDto.Content     = collection["Content"];
                blogPostDto.Created     = DateTime.Now;
                blogPostDto.MainImage   = string.IsNullOrEmpty(imageFile.FileName) ? string.Empty : $"{Request.Scheme}://{Request.Host}/images/blog-images/{imageFile.FileName}";
                blogPostDto.Promote     = Convert.ToBoolean(collection["Promote"]);

                bool result = _blogDal.InsertBlogPost(blogPostDto);

                return(RedirectToAction(nameof(Index), new { createPost = result }));
            }

            catch (Exception ex)
            {
                return(View("Index"));
            }
        }
コード例 #32
0
        public BlogPostDto CreateBlogPost(CreateBlogPost createBlogPost)
        {
            if (createBlogPost.Title == null)
            {
                throw new ArgumentNullException();
            }

            BlogPost blogPost = new BlogPost();

            SlugHelper slugHelper = new SlugHelper();
            string     Slug       = slugHelper.GenerateSlug(createBlogPost.Title);

            ValidateBlogPost(Slug);

            blogPost.Title       = createBlogPost.Title;
            blogPost.Slug        = Slug;
            blogPost.Description = createBlogPost.Description;
            blogPost.Body        = createBlogPost.Body;

            blogPost.CreatedAt = DateTime.Now;
            blogPost.UpdatedAt = DateTime.Now;
            BlogDBContext.BlogPosts.Add(blogPost);
            BlogDBContext.SaveChanges();

            BlogPostDto blogPostDto = new BlogPostDto
            {
                Slug        = blogPost.Slug,
                Title       = blogPost.Title,
                Description = blogPost.Description,
                Body        = blogPost.Body
            };

            blogPostDto.CreatedAt = blogPost.CreatedAt;
            blogPostDto.UpdatedAt = blogPost.UpdatedAt;
            return(blogPostDto);
        }