Exemplo n.º 1
0
        public async Task <IActionResult> MoveThread(MoveThreadPost IDs)
        {
            if (!Guid.TryParse(IDs.threadID, out Guid threadGuid))
            {
                return(StatusCode(400, JsonFormatter.FailResponse("Wrong Format")));
            }
            if (!Guid.TryParse(IDs.subForumID, out Guid subGuid))
            {
                return(StatusCode(400, JsonFormatter.FailResponse("Wrong Format")));
            }
            var thread = await _forumDbContext.Threads.FirstOrDefaultAsync(x => x.ThreadID == threadGuid);

            var sub = await _forumDbContext.SubForums.FirstOrDefaultAsync(x => x.SubForumID == subGuid);

            if (thread == null)
            {
                return(StatusCode(400, JsonFormatter.FailResponse("Thread does not exist")));
            }
            if (sub == null)
            {
                return(StatusCode(400, JsonFormatter.FailResponse("Forum destination does not exist")));
            }
            _databaseCache.MoveThread(thread.ParentID.ToString(), sub.SubForumID.ToString());
            thread.ParentForum = sub;
            await _forumDbContext.SaveChangesAsync();

            return(NoContent());
        }
Exemplo n.º 2
0
        public async Task Add(Theme theme)
        {
            //theme.Id = 0; если сущность будет добавляться изнутри форума, то придется применять данную строчку
            await _context.Themes.AddAsync(theme);

            await _context.SaveChangesAsync();
        }
Exemplo n.º 3
0
        public async Task <IActionResult> RegisterAsync([FromForm] AppUserRegisterPost user)
        {
            var appuser = new AppUser()
            {
                Email    = user.Email,
                UserName = user.Username,
            };
            var createResult = await _userManager.CreateAsync(appuser, user.Password);

            if (!createResult.Succeeded)
            {
                return(StatusCode(400, JsonFormatter.ErrorResponse("Problem Creating A User", createResult.Errors)));
            }
            await _userManager.AddToRoleAsync(appuser, "NormalUser");

            var roles = await _userManager.GetRolesAsync(appuser);

            appuser = await _forumDbContext.Users.Include(x => x.RefreshTokens)
                      .FirstOrDefaultAsync(x => x.Email == appuser.Email);

            var response = _tokenGenerator.StandardRefreshToken();

            appuser.RefreshTokens.Add(response);
            await _forumDbContext.SaveChangesAsync();

            await _signInManager.SignInAsync(appuser, false);

            return(JsonFormatter.SuccessResponse(new
            {
                AccessToken = _tokenGenerator.StandardAccessToken(appuser, roles),
                RefreshToken = response.Token
            }));
        }
Exemplo n.º 4
0
        public async Task <IActionResult> PutTopic(int id, Topic topic)
        {
            if (id != topic.Id)
            {
                return(BadRequest());
            }

            _context.Entry(topic).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TopicExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Exemplo n.º 5
0
        public async Task <IActionResult> CreateItem([FromBody] Thread thread)
        {
            _logger.LogDebug("{Action} request starting.", nameof(CreateItem));

            thread.TimeCreated = DateTime.UtcNow;
            _forumDbContext.Threads.Add(thread);
            await _forumDbContext.SaveChangesAsync();

            return(CreatedAtAction("GetItemById", new { id = thread.Id }, thread));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> OnPostResetPassword()
        {
            var lang = LanguageProvider.GetValidatedLanguage(null, Request);

            try
            {
                var user = _context.PhpbbUsers.FirstOrDefault(
                    x => x.UsernameClean == _utils.CleanString(UserNameForPwdReset) &&
                    x.UserEmailHash == _utils.CalculateCrc32Hash(EmailForPwdReset !)
                    );

                if (user == null)
                {
                    ModelState.AddModelError(nameof(PwdResetErrorMessage), LanguageProvider.Errors[lang, "WRONG_EMAIL_USER"]);
                    ShowPwdResetOptions = true;
                    Mode = LoginMode.PasswordReset;
                    return(Page());
                }

                var resetKey = Guid.NewGuid().ToString("n");
                var(encrypted, iv) = await _utils.EncryptAES(resetKey);

                user.UserNewpasswd = encrypted;

                var dbChangesTask = _context.SaveChangesAsync();

                var emailTask = _utils.SendEmail(
                    to: EmailForPwdReset !,
                    subject: string.Format(LanguageProvider.Email[lang, "RESETPASS_SUBJECT_FORMAT"], _config.GetValue <string>("ForumName")),
                    body: await _utils.RenderRazorViewToString(
                        "_ResetPasswordPartial",
                        new _ResetPasswordPartialModel
                {
                    Code     = resetKey,
                    IV       = iv,
                    UserId   = user.UserId,
                    UserName = user.Username
                },
                        PageContext,
                        HttpContext
                        ));

                await Task.WhenAll(dbChangesTask, emailTask);
            }
            catch
            {
                ModelState.AddModelError(nameof(PwdResetErrorMessage), LanguageProvider.Errors[lang, "AN_ERROR_OCCURRED_TRY_AGAIN"]);
                ShowPwdResetOptions = true;
                Mode = LoginMode.PasswordReset;
                return(Page());
            }

            return(RedirectToPage("Confirm", "NewPassword"));
        }
Exemplo n.º 7
0
        public async Task Add(Forum forum)
        {
            try
            {
                await _context.Forums.AddAsync(forum);

                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Exemplo n.º 8
0
        public async Task <(string Message, bool?IsSuccess)> DeleteUsersWithEmailNotConfirmed(int[] userIds, int adminUserId)
        {
            var lang = GetLanguage();

            if (!(userIds?.Any() ?? false))
            {
                return(LanguageProvider.Admin[lang, "NO_USER_SELECTED"], null);
            }

            async Task Log(IEnumerable <PhpbbUsers> users)
            {
                foreach (var user in users)
                {
                    await _operationLogService.LogAdminUserAction(AdminUserActions.Delete_KeepMessages, adminUserId, user, "Batch removing inactive users with unconfirmed email.");
                }
            }

            try
            {
                var users = await(
                    from u in _context.PhpbbUsers
                    where userIds.Contains(u.UserId) && u.UserInactiveReason == UserInactiveReason.NewlyRegisteredNotConfirmed
                    select u
                    ).ToListAsync();

                _context.PhpbbUsers.RemoveRange(users);
                await _context.SaveChangesAsync();

                if (users.Count == userIds.Length)
                {
                    await Log(users);

                    return(LanguageProvider.Admin[lang, "USERS_DELETED_SUCCESSFULLY"], true);
                }

                var dbUserIds     = users.Select(u => u.UserId).ToList();
                var changedStatus = userIds.Where(u => !dbUserIds.Contains(u));

                await Log(users.Where(u => dbUserIds.Contains(u.UserId)));

                return(
                    string.Format(
                        LanguageProvider.Admin[lang, "USERS_DELETED_PARTIALLY_FORMAT"],
                        string.Join(", ", dbUserIds),
                        LanguageProvider.Enums[lang, UserInactiveReason.NewlyRegisteredNotConfirmed],
                        string.Join(", ", changedStatus)
                        ),
                    null
                    );
            }
            catch (Exception ex)
            {
                var id = Utils.HandleError(ex);
                return(string.Format(LanguageProvider.Errors[lang, "AN_ERROR_OCCURRED_TRY_AGAIN_ID_FORMAT"], id), false);
            }
        }
Exemplo n.º 9
0
        public async Task <IActionResult> Create(Forum model)
        {
            if (!ModelState.IsValid)
            {
                throw new Exception("Invalid forum information.");
            }

            model.OwnerId        = _dbContext.User.SingleOrDefault(u => u.Name == User.Identity.Name).Id;
            model.CreateDateTime = DateTime.Now;
            await _dbContext.Forum.AddAsync(model);

            await _dbContext.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
Exemplo n.º 10
0
        public async Task AddForum(ForumViewModel model)
        {
            var newForum = new Forums
            {
                ForumName  = model.ForumName,
                AuthorName = model.AuthorName,
                UserId     = model.UserId
            };

            forumDbContext.Forums.Add(newForum);
            await forumDbContext.SaveChangesAsync();
        }
Exemplo n.º 11
0
        public async Task EditMethodShouldChangeDescriptionAndModifiedOn(string creationDescription, string editedDescription)
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);
            var usersServiceMock     = new Mock <IUsersService>();
            var dateTimeProviderMock = new Mock <IDateTimeProvider>();

            dateTimeProviderMock.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            await db.Replies.AddAsync(new Reply
            {
                Description = creationDescription,
                CreatedOn   = dateTimeProviderMock.Object.Now()
            });

            await db.SaveChangesAsync();

            var repliesService = new RepliesService(db, null, usersServiceMock.Object, dateTimeProviderMock.Object);
            await repliesService.EditAsync(1, editedDescription);

            var expected = new Reply
            {
                Description = editedDescription,
                ModifiedOn  = dateTimeProviderMock.Object.Now()
            };

            var actual = await db.Replies.FirstOrDefaultAsync();

            expected.Description.Should().BeSameAs(actual.Description);
            expected.ModifiedOn.Should().Be(actual.ModifiedOn);
        }
Exemplo n.º 12
0
        public async Task IsExistingMethodShouldReturnTrueIfPostExists()
        {
            var guid = Guid.NewGuid().ToString();

            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(guid)
                          .Options;

            var db = new ForumDbContext(options);
            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            var post = new Post
            {
                Id          = 1,
                Title       = "Test title",
                Description = "Test description",
                Type        = PostType.Discussion,
                CategoryId  = 1,
                AuthorId    = guid,
                CreatedOn   = dateTimeProvider.Object.Now()
            };

            await db.Posts.AddAsync(post);

            await db.SaveChangesAsync();

            var postsService = new PostsService(db, null, null, dateTimeProvider.Object);

            var isExisting = await postsService.IsExistingAsync(1);

            isExisting.Should().BeTrue();
        }
Exemplo n.º 13
0
        public async Task GetAuthorIdByIdMethodShouldReturnCorrectId()
        {
            var guid = Guid.NewGuid().ToString();

            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(guid)
                          .Options;

            var db = new ForumDbContext(options);
            var usersServiceMock     = new Mock <IUsersService>();
            var dateTimeProviderMock = new Mock <IDateTimeProvider>();

            dateTimeProviderMock.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            await db.Replies.AddAsync(new Reply
            {
                Description = "Test",
                AuthorId    = guid,
                CreatedOn   = dateTimeProviderMock.Object.Now()
            });

            await db.SaveChangesAsync();

            var repliesService = new RepliesService(db, null, usersServiceMock.Object, dateTimeProviderMock.Object);
            var authorId       = await repliesService.GetAuthorIdByIdAsync(1);

            authorId.Should().BeSameAs(guid);
        }
Exemplo n.º 14
0
        protected override async Task Handle(UpdateLastLoginDateCommand request, CancellationToken cancellationToken)
        {
            var profile = await _forumDbContext.Profiles.SingleAsync(p => p.UserId == request.UserId);

            profile.LastLoginDate = DateTime.UtcNow;
            await _forumDbContext.SaveChangesAsync();
        }
Exemplo n.º 15
0
        public async Task GetAuthorIdByIdMethodShouldReturnNullIfPostIsDeleted()
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);
            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            var post = new Post
            {
                Id          = 1,
                Title       = "Test title 1",
                Description = "Test description 1",
                Type        = PostType.Discussion,
                CategoryId  = 1,
                AuthorId    = "Test author id",
                IsDeleted   = true,
                CreatedOn   = dateTimeProvider.Object.Now(),
                DeletedOn   = dateTimeProvider.Object.Now()
            };

            await db.Posts.AddAsync(post);

            await db.SaveChangesAsync();

            var postsService = new PostsService(db, null, null, dateTimeProvider.Object);

            var authorId = await postsService.GetAuthorIdByIdAsync(1);

            authorId.Should().BeNull();
        }
Exemplo n.º 16
0
        public async Task GetByIdMethodShouldReturnNullWhenCategoryIsDeleted()
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);

            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <Category, Category>();
            });

            var mapper = config.CreateMapper();

            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            await db.Categories.AddAsync(new Category
            {
                Name      = "Test",
                CreatedOn = dateTimeProvider.Object.Now(),
                IsDeleted = true,
                DeletedOn = dateTimeProvider.Object.Now()
            });

            await db.SaveChangesAsync();

            var categoriesService = new CategoriesService(db, mapper, dateTimeProvider.Object);
            var actual            = await categoriesService.GetByIdAsync <Category>(1);

            actual.Should().BeNull();
        }
Exemplo n.º 17
0
        public async Task GetAllMethodShouldNotReturnDeleted()
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);

            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <Tag, Tag>();
            });

            var mapper = config.CreateMapper();

            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            for (int i = 0; i < 3; i++)
            {
                await db.Tags.AddAsync(new Tag
                {
                    Name      = $"Test {i}",
                    IsDeleted = true,
                    CreatedOn = dateTimeProvider.Object.Now()
                });
            }
            await db.SaveChangesAsync();

            var tagsService = new TagsService(db, mapper, dateTimeProvider.Object);
            var actual      = await tagsService.GetAllAsync <Tag>();

            actual.Should().BeEmpty();
        }
Exemplo n.º 18
0
        public async Task AreExistingMethodShouldReturnFalseIfIdNotExists()
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);
            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            for (int i = 0; i < 3; i++)
            {
                await db.Tags.AddAsync(new Tag
                {
                    Name      = $"Test {i}",
                    CreatedOn = dateTimeProvider.Object.Now()
                });
            }

            await db.SaveChangesAsync();

            var ids = new[] { 1, 2, 3, 4, 5 };

            var tagsService = new TagsService(db, null, dateTimeProvider.Object);
            var areExisting = await tagsService.AreExistingAsync(ids);

            areExisting.Should().BeFalse();
        }
Exemplo n.º 19
0
        public async Task GetCountMethodShouldNotCountDeleted()
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);
            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            for (int i = 0; i < 3; i++)
            {
                await db.Tags.AddAsync(new Tag
                {
                    Name      = $"Test {i}",
                    IsDeleted = true,
                    CreatedOn = dateTimeProvider.Object.Now(),
                    DeletedOn = dateTimeProvider.Object.Now()
                });
            }

            await db.SaveChangesAsync();

            var tagsService = new TagsService(db, null, dateTimeProvider.Object);
            var count       = await tagsService.GetCountAsync();

            count.Should().Be(0);
        }
Exemplo n.º 20
0
        public async Task IsExistingMethodShouldReturnTrueIfExists()
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);
            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            await db.PostReports.AddAsync(new PostReport
            {
                Description = "Test",
                PostId      = 1,
                AuthorId    = Guid.NewGuid().ToString(),
                CreatedOn   = dateTimeProvider.Object.Now()
            });

            await db.SaveChangesAsync();

            var postReportsService = new PostReportsService(db, null, dateTimeProvider.Object);
            var isExisting         = await postReportsService.IsExistingAsync(1);

            isExisting.Should().BeTrue();
        }
Exemplo n.º 21
0
        public async Task EditMethodShouldChangeCategoryNameAndModifiedOn(string creationName, string editedName)
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);
            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            await db.Categories.AddAsync(new Category
            {
                Name      = creationName,
                CreatedOn = dateTimeProvider.Object.Now()
            });

            await db.SaveChangesAsync();

            var categoriesService = new CategoriesService(db, null, dateTimeProvider.Object);
            await categoriesService.EditAsync(1, editedName);

            var expected = new Category
            {
                Name       = editedName,
                ModifiedOn = dateTimeProvider.Object.Now()
            };

            var actual = await db.Categories.FirstOrDefaultAsync();

            actual.Name.Should().BeSameAs(expected.Name);
            actual.ModifiedOn.Should().Be(expected.ModifiedOn);
        }
Exemplo n.º 22
0
        public async Task SeedAsync(ForumDbContext dbContext, IServiceProvider serviceProvider)
        {
            if (dbContext == null)
            {
                throw new ArgumentNullException(nameof(dbContext));
            }

            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            var seeders = new List <ISeeder>
            {
                new RolesSeeder(),
                new AdminSeeder(),
                new TestUserSeeder(),
                new TagsSeeder(),
                new CategoriesSeeder(),
                new PostsSeeder()
            };

            foreach (var seeder in seeders)
            {
                await seeder.SeedAsync(dbContext, serviceProvider);

                await dbContext.SaveChangesAsync();
            }
        }
Exemplo n.º 23
0
        public async Task DeleteMethodShouldChangeIsDeletedAndDeletedOn(string name)
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);
            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            await db.Categories.AddAsync(new Category
            {
                Name      = name,
                CreatedOn = dateTimeProvider.Object.Now()
            });

            await db.SaveChangesAsync();

            var categoriesService = new CategoriesService(db, null, dateTimeProvider.Object);
            await categoriesService.DeleteAsync(1);

            var actual = await db.Categories.FirstOrDefaultAsync();

            actual.IsDeleted.Should().BeTrue();
            actual.DeletedOn.Should().BeSameDateAs(dateTimeProvider.Object.Now());
        }
Exemplo n.º 24
0
        public async Task GetLatestActivityByIdMethodShouldReturnPostLatestActivity()
        {
            var guid = Guid.NewGuid().ToString();

            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(guid)
                          .Options;

            var db = new ForumDbContext(options);
            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            var post = new Post
            {
                Id          = 1,
                Title       = "Test title 1",
                Description = "Test description 1",
                Type        = PostType.Discussion,
                CategoryId  = 1,
                AuthorId    = guid,
                CreatedOn   = dateTimeProvider.Object.Now(),
            };

            await db.Posts.AddAsync(post);

            await db.SaveChangesAsync();

            var postsService = new PostsService(db, null, null, dateTimeProvider.Object);

            var latestActivity = await postsService.GetLatestActivityByIdAsync(1);

            latestActivity.Should().Be("0m");
        }
Exemplo n.º 25
0
        public async Task DeleteMethodShouldReturnTrueIfReportIsDeleted(string description, int replyId)
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);
            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            await db.ReplyReports.AddAsync(new ReplyReport
            {
                Description = description,
                ReplyId     = replyId,
                AuthorId    = Guid.NewGuid().ToString(),
                CreatedOn   = dateTimeProvider.Object.Now()
            });

            await db.SaveChangesAsync();

            var replyReportsService = new ReplyReportsService(db, null, dateTimeProvider.Object);
            var deleted             = await replyReportsService.DeleteAsync(1);

            deleted.Should().BeTrue();
        }
Exemplo n.º 26
0
        public async Task GetByIdMethodShouldReturnCorrectModel()
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);

            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <Tag, Tag>();
            });

            var mapper = config.CreateMapper();

            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            await db.Tags.AddAsync(new Tag
            {
                Name      = "Test",
                CreatedOn = dateTimeProvider.Object.Now()
            });

            await db.SaveChangesAsync();

            var tagsService = new TagsService(db, mapper, dateTimeProvider.Object);
            var actual      = await tagsService.GetByIdAsync <Tag>(1);

            var expected = await db.Tags.FirstOrDefaultAsync();

            actual.Should().BeEquivalentTo(expected);
        }
Exemplo n.º 27
0
        public async Task SeedAsync(ForumDbContext dbContext, IServiceProvider serviceProvider)
        {
            if (dbContext == null)
            {
                throw new ArgumentNullException(nameof(dbContext));
            }

            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            var logger = serviceProvider.GetService <ILoggerFactory>().CreateLogger(typeof(ForumDbContextSeeder));

            var seeders = new List <ISeeder>
            {
                new RolesSeeder(),
                new CategoriesSeeder(),
            };

            foreach (var seeder in seeders)
            {
                await seeder.SeedAsync(dbContext, serviceProvider);

                await dbContext.SaveChangesAsync();

                logger.LogInformation($"Seeder {seeder.GetType().Name} done.");
            }
        }
Exemplo n.º 28
0
        public async Task <Result <object> > Handle(AddLikeToPostRequest request, CancellationToken cancellationToken)
        {
            var post = await _forumDbContext.Posts.FindAsync(request.PostId);

            if (post == null)
            {
                return(Result <object> .Failure(nameof(request.PostId), "Post doesn't exist"));
            }

            var like = await _forumDbContext.PostLikes
                       .SingleOrDefaultAsync(pl => pl.PostId == request.PostId && pl.UserId == request.UserId);

            if (like != null)
            {
                return(Result <object> .Failure(nameof(request.PostId), "This post was liked"));
            }

            var postLike = new PostLike {
                PostId = post.Id, UserId = request.UserId
            };
            await _forumDbContext.PostLikes.AddAsync(postLike);

            await _forumDbContext.SaveChangesAsync();

            return(Result <object> .Success());
        }
Exemplo n.º 29
0
        public async Task DeleteMethodShouldChangeIsDeletedAndDeletedOn(string description, int postId)
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);
            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            await db.PostReports.AddAsync(new PostReport
            {
                Description = description,
                PostId      = postId,
                AuthorId    = Guid.NewGuid().ToString(),
                CreatedOn   = dateTimeProvider.Object.Now()
            });

            await db.SaveChangesAsync();

            var postReportsService = new PostReportsService(db, null, dateTimeProvider.Object);
            await postReportsService.DeleteAsync(1);

            var actual = await db.PostReports.FirstOrDefaultAsync();

            actual.IsDeleted.Should().BeTrue();
            actual.DeletedOn.Should().Be(dateTimeProvider.Object.Now());
        }
Exemplo n.º 30
0
        public async Task IsExistingMethodShouldReturnTrueIfExists()
        {
            var options = new DbContextOptionsBuilder <ForumDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new ForumDbContext(options);
            var usersServiceMock     = new Mock <IUsersService>();
            var dateTimeProviderMock = new Mock <IDateTimeProvider>();

            dateTimeProviderMock.Setup(dtp => dtp.Now()).Returns(new DateTime(2020, 3, 27));

            await db.Replies.AddAsync(new Reply
            {
                Description = "Test",
                CreatedOn   = dateTimeProviderMock.Object.Now()
            });

            await db.SaveChangesAsync();

            var repliesService = new RepliesService(db, null, usersServiceMock.Object, dateTimeProviderMock.Object);
            var isExisting     = await repliesService.IsExistingAsync(1);

            isExisting.Should().BeTrue();
        }