Ejemplo n.º 1
0
        public async Task AddAsync(T entity)
        {
            using var context = new BlogDbContext();
            await context.AddAsync(entity);

            await context.SaveChangesAsync();
        }
Ejemplo n.º 2
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("Не удалось создать пост"));
        }
        public static async Task SeedDefaultCulturesAsync(this BlogDbContext blogDbContext)
        {
            var cultureEnglish = new Culture
            {
                Code        = "en-us",
                DisplayName = "English-UnitedState"
            };
            var cultureFarsi = new Culture
            {
                Code        = "fa-ir",
                DisplayName = "Farsi-Iran"
            };
            var cultureArabic = new Culture
            {
                Code        = "ar-sa",
                DisplayName = "Arabic"
            };

            //var cultureChina = new Culture
            //{
            //    Code = "ch-",
            //    DisplayName = "China"
            //};

            if (!blogDbContext.Cultures.Any(u => u.Code == cultureEnglish.Code))
            {
                await blogDbContext.AddAsync(cultureEnglish);

                await blogDbContext.SaveChangesAsync();
            }
            if (!blogDbContext.Cultures.Any(u => u.Code == cultureFarsi.Code))
            {
                await blogDbContext.AddAsync(cultureFarsi);

                await blogDbContext.SaveChangesAsync();
            }
            if (!blogDbContext.Cultures.Any(u => u.Code == cultureArabic.Code))
            {
                await blogDbContext.AddAsync(cultureArabic);

                await blogDbContext.SaveChangesAsync();
            }
        }
Ejemplo n.º 4
0
        public async Task <Response> CreateAsync(CreatePostRequest request)
        {
            var slug = SlugHelper.GenerateSlug(request.BlogPost.Title);

            var post = await _context.Posts.SingleOrDefaultAsync(i => i.Slug == slug);

            if (post != null)
            {
                var error = new ErrorModel
                {
                    Message = $"The blog post {request.BlogPost.Title} already exists"
                };

                return(new ErrorResponse(error));
            }

            post = _mapper.Map <Post>(request.BlogPost);

            await _context.AddAsync(post);

            await _context.SaveChangesAsync();

            foreach (var item in request.BlogPost.TagList)
            {
                var tag = await _context.Tags.SingleOrDefaultAsync(i => i.Name == item);

                if (tag == null)
                {
                    tag = new Tag
                    {
                        Name = item
                    };
                }

                post.PostTags.Add(new PostTag
                {
                    Post = post,
                    Tag  = tag
                });
            }

            await _context.SaveChangesAsync();

            var response = _mapper.Map <PostModel>(post);

            return(new PostResponse
            {
                BlogPost = response
            });
        }
        public static async Task SeedDefaultPostsAsync(this BlogDbContext blogDbContext)
        {
            var post = new Post
            {
                Locales = new List <PostLocale>()
                {
                    new PostLocale
                    {
                        Title        = "Default Post Title",
                        Content      = "Default Post Body",
                        Slug         = "default-post-slug",
                        LocalCulture = blogDbContext.Cultures
                                       .AsNoTracking()
                                       .FirstOrDefault(x => x.Code == "en-us")
                    },
                    new PostLocale
                    {
                        Title        = "عنوان مطلب پیشفرض",
                        Content      = "محتوای مطلب پیشفرض",
                        Slug         = "اسلاگ-مطلب-پیشفرض",
                        LocalCulture = blogDbContext.Cultures
                                       .AsNoTracking()
                                       .FirstOrDefault(x => x.Code == "fa-ir")
                    },
                    new PostLocale
                    {
                        Title        = "العنوان",
                        Content      = "المحتوی",
                        Slug         = "المطلب-اسلاگ",
                        LocalCulture = blogDbContext.Cultures
                                       .AsNoTracking()
                                       .FirstOrDefault(x => x.Code == "ar-sa")
                    }
                },
                Tags        = "tag1;tag2;تگ آزمایشی;",
                Description = "Default Post Description",
                Created     = DateTime.UtcNow,
                IsArchive   = false,
                IsPublic    = true,
                Visits      = 1
            };

            if (!blogDbContext.Posts.Any())
            {
                await blogDbContext.AddAsync(post);

                await blogDbContext.SaveChangesAsync();
            }
        }
Ejemplo n.º 6
0
            public async Task <Blog.Entities.Post> Handle(Command request, CancellationToken cancellationToken)
            {
                var post = new Blog.Entities.Post
                {
                    CreatorId   = request.CreatorId,
                    Content     = request.Content,
                    BlogId      = request.BlogId,
                    CreatorName = request.CreatorName
                };

                await dbContext.AddAsync(post, cancellationToken);

                await dbContext.SaveChangesAsync(cancellationToken);

                return(post);
            }
Ejemplo n.º 7
0
        public async Task CreatePost(CreatePostCommand createPostCommand)
        {
            var authorId  = createPostCommand.CreatedBy.Id;
            var createdBy = await _blogDbContext.Users.SingleOrDefaultAsync(x => x.Id == authorId);

            var claims = await GetCreatorClaims(authorId);

            var slug = new PostSlugEntity
            {
                Path         = createPostCommand.Slug,
                IsDefault    = true,
                CreatedBy    = createdBy,
                CreatedOnUtc = DateTime.UtcNow
            };

            var postEntity = new PostEntity
            {
                Title             = createPostCommand.Title,
                Abstract          = createPostCommand.Abstract,
                Content           = createPostCommand.Content,
                Language          = "en-US",
                Format            = PostFormatEntity.Html,
                CreatedBy         = createdBy,
                CreatedOnUtc      = DateTime.UtcNow,
                CreationIpAddress = createPostCommand.IPAddress,
                Slugs             = new List <PostSlugEntity> {
                    slug
                },
                Tags = new Collection <PostTagEntity>(createPostCommand.Tags.Select(t => new PostTagEntity
                {
                    Tag = new TagEntity {
                        Name = t
                    }
                }).ToList()),
                ApprovalStatus = createPostCommand.Approved
                    ? ApprovalStatusEntity.Approved
                    : ApprovalStatusEntity.Disapproved
            };

            await _blogDbContext.AddAsync(postEntity);

            await _blogDbContext.SaveChangesAsync();
        }
Ejemplo n.º 8
0
            public async Task <Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                var blog = new Entities.Blog
                {
                    Content     = request.Content,
                    Title       = request.Title,
                    CreatorId   = request.CreatorId,
                    CreatorName = request.CreatorName,
                    Created     = DateTime.Now
                };

                await dbContext.AddAsync(blog, cancellationToken);

                await dbContext.SaveChangesAsync(cancellationToken);

                await bus.Publish(new UserPostedBlogEvent(request.CreatorId), cancellationToken);

                return(Unit.Value);
            }