Exemple #1
0
            public async Task <UserEnvelope> Handle(Query message, CancellationToken cancellationToken)
            {
                var person = await _context.Persons.AsNoTracking()
                             .FirstOrDefaultAsync(p => p.PersonId == message.UserId, cancellationToken);

                if (message.UserId == null)
                {
                    throw new RedirectException($"user/{_currentUserAccessor.GetCurrentUserId()}", false);
                }

                if (person == null)
                {
                    throw new RestException(HttpStatusCode.NotFound, "User does not exist");
                }

                var user = _mapper.Map <Person, User>(person);

                if (person.PersonId != _currentUserAccessor.GetCurrentUserId())
                {
                    user.Email = null;
                    user.Token = null;
                }
                else
                {
                    user.Token = await _jwtTokenGenerator.CreateToken(person.PersonId);
                }
                return(new UserEnvelope(user));
            }
            public async Task <QuestionDTOEnvelope> Handle(Request request, CancellationToken cancellationToken)
            {
                var userId   = currentUserAccessor.GetCurrentUserId();
                var question = context.Questions.Where(q => q.Id == request.Id)
                               .Include(q => q.AnswerOptions).FirstOrDefault();

                if (question == null)
                {
                    throw new Exceptions.QuestionNotFoundException();
                }

                var examId = question.ExamId;
                var exam   = context.Exams.NotPublishedByIdAndUserId(examId, userId).FirstOrDefault();

                if (exam == null)
                {
                    throw new Exceptions.ExamNotFoundException();
                }

                context.AnswerOptions.RemoveRange(question.AnswerOptions);
                context.Questions.Remove(question);
                await context.SaveChangesAsync();

                var questionDto = mapper.Map <Domain.Question, QuestionDTO>(question);

                return(new QuestionDTOEnvelope(questionDto));
            }
Exemple #3
0
            public async Task <ExamDTOEnvelope> Handle(Query request, CancellationToken cancellationToken)
            {
                int userId = currentUserAccessor.GetCurrentUserId();

                var queryable = context.Exams.AsNoTracking();

                queryable = queryable.Where(e => e.UserId == userId);


                if (request.IncludeTags)
                {
                    queryable = queryable.IncludeTags();
                }

                if (request.IncludeUser)
                {
                    queryable = queryable.Include(e => e.User);
                }


                var exam = await queryable
                           .FirstOrDefaultAsync(e => e.Id == request.Id, cancellationToken);

                if (exam == null)
                {
                    throw new Exceptions.ExamNotFoundException();
                }

                var examDTO = mapper.Map <Domain.Exam, ExamDTO>(exam);

                return(new ExamDTOEnvelope(examDTO));
            }
            public async Task <UserExamResultDTOEnvelope> Handle(Request request, CancellationToken cancellationToken)
            {
                var userId = currentUserAccessor.GetCurrentUserId();

                var userExam = await this.context.UserExams
                               .Include(e => e.Exam).Where(e => e.Id == request.UserExamId && e.UserId == userId && e.Exam.IsPublished == true).FirstOrDefaultAsync();

                if (userExam == null)
                {
                    throw new Exceptions.UserExamNotFoundException();
                }

                if (!userExam.EndedAt.HasValue)
                {
                    await UserExam.UserExamHelper.EndUserExamIfTimeExpired(context, cancellationToken, userExam);
                }
                if (!userExam.EndedAt.HasValue)
                {
                    throw new Exceptions.UserExamNotFoundException();
                }
                var userExamResult = await context.UserExamResults.FindAsync(userExam.Id);

                if (userExamResult != null)
                {
                    return(MakeEnvelope(userExamResult));
                }
                userExamResult = new Domain.UserExamResult()
                {
                    UserExamId = userExam.Id
                };

                userExamResult.QuestionCount = context.Questions.Where(e => e.ExamId == userExam.ExamId).Count();

                var userExamQuestionAnswers = context.UserExamQuestions.Where(e => e.UserExamId == userExam.Id)
                                              .Include(e => e.UserExamQuestionAnswers).ToArray();

                foreach (var userExamQuestionAnswer in userExamQuestionAnswers)
                {
                    userExamQuestionAnswer.HasRightAnswer = IsRight(userExamQuestionAnswer);
                }

                userExamResult.AnsweredQuestionCount    = userExamQuestionAnswers.Length;
                userExamResult.NotAnsweredQuestionCount = userExamResult.QuestionCount - userExamResult.AnsweredQuestionCount;
                userExamResult.RightAnswerCount         = userExamQuestionAnswers.Where(e => e.HasRightAnswer == true).Count();
                userExamResult.WrongAnswerCount         = userExamQuestionAnswers.Where(e => e.HasRightAnswer == false).Count();
                userExamResult.IsPassed = (float)userExamResult.RightAnswerCount / (float)userExamResult.QuestionCount * 100
                                          >= userExam.Exam.PassPercentage;

                await context.UserExamResults.AddAsync(userExamResult);

                await context.SaveChangesAsync();

                context.Entry(userExamResult).Reload();
                return(MakeEnvelope(userExamResult));
            }
Exemple #5
0
            public async Task <SnippetEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                var author = await _context.Persons.FirstAsync(p =>
                                                               p.PersonId == _currentUserAccessor.GetCurrentUserId(),
                                                               cancellationToken);

                var categories = new List <Category>();

                foreach (var categoryString in message.Snippet.Categories)
                {
                    var category = await _context.Categories.FirstOrDefaultAsync(x =>
                                                                                 x.DisplayName.ToLower() == categoryString.ToLower(),
                                                                                 cancellationToken);

                    if (category == null)
                    {
                        category = new Category()
                        {
                            DisplayName = categoryString,
                            Color       = _settings.AccentColorsList.Random()
                        };

                        await _context.Categories.AddAsync(category, cancellationToken);
                    }

                    categories.Add(category);
                }

                var newSnippet = new Domains.Snippet()
                {
                    Title    = message.Snippet.Title,
                    Author   = author,
                    Content  = message.Snippet.Content,
                    Language = (int)message.Snippet.Language,
                };
                await _context.Snippets.AddAsync(newSnippet, cancellationToken);

                await _context.SnippetCategories.AddRangeAsync(categories.Select(x => new Domains.SnippetCategory()
                {
                    Snippet  = newSnippet,
                    Category = x
                }), cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);

                var snippet = _mapper.Map <Domains.Snippet, Snippet>(newSnippet);

                return(new SnippetEnvelope(snippet));
            }
Exemple #6
0
            public async Task <ExamDTOEnvelope> Handle(Request request, CancellationToken cancellationToken)
            {
                var userId   = currentUserAccessor.GetCurrentUserId();
                var examData = request.Exam;
                var exam     = await context.Exams.NotPublishedByIdAndUserId(request.Id, userId)
                               .IncludeTags()
                               .FirstOrDefaultAsync(cancellationToken);

                if (exam == null)
                {
                    throw new Exceptions.ExamNotFoundException();
                }

                exam.Title          = examData.Title ?? exam.Title;
                exam.Description    = examData.Description ?? exam.Description;
                exam.TimeInMinutes  = examData.TimeInMinutes ?? exam.TimeInMinutes;
                exam.PassPercentage = examData.PassPercentage ?? exam.PassPercentage;
                exam.IsPrivate      = examData.IsPrivate ?? exam.IsPrivate;
                var examTagsToAdd    = Array.Empty <Domain.ExamTag>();
                var examTagsToDelete = Array.Empty <Domain.ExamTag>();

                if (request.Exam.Tags != null)
                {
                    var tags = await context.SaveTagsAsync(request.Exam.Tags ?? Enumerable.Empty <string>(), cancellationToken);

                    var examTags = exam.ExamTags;
                    examTagsToDelete = examTags.Where(et => !tags.Any(t => t.TagId == et.TagId)).ToArray();
                    examTagsToAdd    = tags.Where(t => !examTags.Any(et => et.TagId == t.TagId))
                                       .Select(t => new Domain.ExamTag()
                    {
                        Tag = t, TagId = t.TagId, Exam = exam, ExamId = exam.Id
                    }).ToArray();
                }

                if (context.IsModified(exam) || examTagsToAdd.Length > 0 || examTagsToDelete.Length > 0)
                {
                    exam.UpdatedAt = DateTime.UtcNow;
                }

                await context.ExamTags.AddRangeAsync(examTagsToAdd, cancellationToken);

                context.ExamTags.RemoveRange(examTagsToDelete);

                await context.SaveChangesAsync(cancellationToken);

                var examDto = mapper.Map <Domain.Exam, ExamDTO>(exam);

                return(new ExamDTOEnvelope(examDto));
            }
            public async Task <User> Handle(VerificationCommand request, CancellationToken cancellationToken)
            {
                var userId = currentUserAccessor.GetCurrentUserId();

                if (string.IsNullOrEmpty(userId))
                {
                    throw new RestException(HttpStatusCode.Unauthorized, new { Error = "Unknown User Unauthorized" });
                }

                var user = await userRepository.GetByIdAsync(userId, cancellationToken);

                if (user == null)
                {
                    throw new RestException(HttpStatusCode.Unauthorized, new { Error = $"Invalid UserId {userId}" });
                }

                return(user);
            }
Exemple #8
0
            public async Task <QuestionDTOEnvelope> Handle(Request request, CancellationToken cancellationToken)
            {
                var userId = currentUserAccessor.GetCurrentUserId();

                var question = context.Questions.Where(q => q.Id == request.Question.Id)
                               .Include(q => q.AnswerOptions).FirstOrDefault();

                if (question == null)
                {
                    throw new Exceptions.QuestionNotFoundException();
                }
                var examId = question.ExamId;
                var exam   = context.Exams.NotPublishedByIdAndUserId(examId, userId).FirstOrDefault();

                if (exam == null)
                {
                    throw new Exceptions.ExamNotFoundException();
                }

                var  utcNow            = DateTime.UtcNow;
                var  answers           = request.Question.Answers;
                bool hasAnswersChanged = false;

                if (answers != null && answers.Count() > 0)
                {
                    hasAnswersChanged = await SaveAnswers(question, utcNow, answers, cancellationToken);
                }


                question.Text           = request.Question.Text ?? question.Text;
                question.QuestionTypeId = request.Question.QuestionTypeId;

                if (context.IsModified(question) || hasAnswersChanged)
                {
                    question.UpdatedAt = utcNow;
                }

                await context.SaveChangesAsync();

                var questionDto = mapper.Map <Domain.Question, QuestionDTO>(question);

                return(new QuestionDTOEnvelope(questionDto));
            }
Exemple #9
0
            public async Task <ExamDTOEnvelope> Handle(Request request, CancellationToken cancellationToken)
            {
                var userId = currentUserAccessor.GetCurrentUserId();
                var exam   = await context.Exams.ByIdAndUserId(request.Id, userId).FirstOrDefaultAsync(cancellationToken);

                if (exam == null)
                {
                    throw new Exceptions.ExamNotFoundException();
                }

                exam.IsDeleted = true;
                exam.DeletedAt = DateTime.UtcNow;

                await context.SaveChangesAsync(cancellationToken);

                var examDto = mapper.Map <Domain.Exam, ExamDTO>(exam);

                return(new ExamDTOEnvelope(examDto));
            }
Exemple #10
0
            public async Task<UserExamResultDTOEnvelope> Handle(Query request, CancellationToken cancellationToken)
            {
                var userId = currentUserAccessor.GetCurrentUserId();

                var userExam = await this.context.UserExams
                .Include(e => e.Exam).Where(e => e.Id == request.UserExamId && e.UserId == userId && e.Exam.IsPublished == true).FirstOrDefaultAsync();

                if (userExam == null)
                {
                    throw new Exceptions.UserExamNotFoundException();
                }

                var userExamResult = await context.UserExamResults.FirstOrDefaultAsync(e => e.UserExamId == request.UserExamId);
                if (userExamResult == null)
                {
                    throw new Exceptions.UserExamResultNotFoundException();
                }
                var userExamResultDto = mapper.Map<Domain.UserExamResult, UserExamResultDTO>(userExamResult);
                return new UserExamResultDTOEnvelope(userExamResultDto);
            }
Exemple #11
0
            public async Task <VoteEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                var currentUserId  = _currentUserAccessor.GetCurrentUserId();
                var currentSnippet = await _context.Snippets
                                     .FindAsync(message.Vote.SnippetId, cancellationToken);

                var currentKarma = await _context.Karma.SingleOrDefaultAsync(x =>
                                                                             x.Submitter.PersonId == currentUserId && x.Snippet == currentSnippet,
                                                                             cancellationToken);

                var vote = new Vote
                {
                    Status = VoteStatus.Upvote
                };

                if (currentKarma == null)
                {
                    currentKarma = new Domains.Karma {
                        Upvote    = true,
                        Snippet   = currentSnippet,
                        Submitter = await _context.Persons.FindAsync(currentUserId, cancellationToken)
                    };
                    await _context.Karma.AddAsync(currentKarma, cancellationToken);
                }
                else
                {
                    if (!currentKarma.Upvote)
                    {
                        currentKarma.Upvote = true;
                    }
                    else
                    {
                        _context.Karma.Remove(currentKarma);
                        vote.Status = VoteStatus.Removed;
                    }
                }

                await _context.SaveChangesAsync(cancellationToken);

                return(new VoteEnvelope(vote));
            }
Exemple #12
0
            public async Task <UserExamDTOEnvelope> Handle(Query request, CancellationToken cancellationToken)
            {
                var userId    = currentUserAccessor.GetCurrentUserId();
                var queryable = this.context.UserExams.AsNoTracking().Where(e => e.Id == request.Id && e.UserId == userId);

                if (request.IncludeExam)
                {
                    queryable = queryable.Include(e => e.Exam);
                }

                var userExam = await queryable.FirstOrDefaultAsync();

                if (userExam == null)
                {
                    throw new Exceptions.UserExamNotFoundException();
                }

                var userExamDTO = mapper.Map <Domain.UserExam, UserExamDTO>(userExam);

                return(new UserExamDTOEnvelope(userExamDTO));
            }
Exemple #13
0
            public async Task <UserEnvelope> Handle(Command message, CancellationToken cancellationToken)
            {
                var currentUserId = _currentUserAccessor.GetCurrentUserId();
                var person        = await _context.Persons.Where(p => p.PersonId == currentUserId).FirstOrDefaultAsync(cancellationToken);

                person.Email       = message.User.Email ?? person.Email;
                person.DisplayName = message.User.DisplayName ?? person.DisplayName;

                if (!string.IsNullOrWhiteSpace(message.User.Password))
                {
                    var salt = Guid.NewGuid().ToByteArray();
                    person.PasswordHash = _passwordHasher.Hash(message.User.Password, salt);
                    person.PasswordSalt = salt;
                }

                await _context.SaveChangesAsync(cancellationToken);

                var user = _mapper.Map <Person, User>(person);

                return(new UserEnvelope(user));
            }
            public async Task <QuestionDTOEnvelope> Handle(Query request, CancellationToken cancellationToken)
            {
                var queryable = context.Questions.AsNoTracking();

                queryable = queryable.Where(q => q.Id == request.Id);

                if (request.IncludeAnswerOptions)
                {
                    queryable = queryable.Include(e => e.AnswerOptions);
                }
                var question = await queryable.FirstOrDefaultAsync();

                if (question == null)
                {
                    throw new Exceptions.QuestionNotFoundException();
                }
                var examId = question.ExamId;

                int examCount = 0;

                if (request.IsAuthorized)
                {
                    var userId = currentUserAccessor.GetCurrentUserId();
                    examCount = context.Exams.ByUserIdOrPublishedAndNotPrivate(userId)
                                .Where(e => e.Id == examId).Count();
                }
                else
                {
                    examCount = context.Exams.PublishedAndNotPrivate().Where(e => e.Id == examId).Count();
                }

                if (examCount == 0)
                {
                    throw new Exceptions.ExamNotFoundException();
                }

                var questionDTO = mapper.Map <Domain.Question, QuestionDTO>(question);

                return(new QuestionDTOEnvelope(questionDTO));
            }
Exemple #15
0
            public async Task <QuestionsDTOEnvelope> Handle(Query request, CancellationToken cancellationToken)
            {
                int examCount = 0;

                if (request.IsAuthorized)
                {
                    var userId = currentUserAccessor.GetCurrentUserId();
                    examCount = context.Exams.ByUserIdOrPublishedAndNotPrivate(userId).Where(e => e.Id == request.ExamId).Count();
                }
                else
                {
                    examCount = context.Exams.PublishedAndNotPrivate().Where(e => e.Id == request.ExamId).Count();
                }

                if (examCount == 0)
                {
                    throw new Exceptions.ExamNotFoundException();
                }

                var queryable = context.Questions.AsNoTracking();

                queryable = queryable.Where(e => e.ExamId == request.ExamId);

                if (request.IncludeAnswerOptions)
                {
                    queryable = queryable.Include(e => e.AnswerOptions);
                }

                var questions = await queryable
                                .OrderByDescending(e => e.CreatedAt)
                                .Skip(request.Offset)
                                .Take(request.Limit)
                                .ToListAsync(cancellationToken);

                var questionsCount = await queryable.CountAsync();

                var questionDTOs = mapper.Map <List <Domain.Question>, List <QuestionDTO> >(questions);

                return(new QuestionsDTOEnvelope(questionDTOs, questionsCount));
            }
Exemple #16
0
            public async Task <UserExamsDTOEnvelope> Handle(Query request, CancellationToken cancellationToken)
            {
                var userId    = currentUserAccessor.GetCurrentUserId();
                var queryable = this.context.UserExams.AsNoTracking().Where(e => e.UserId == userId);

                if (request.IncludeExams)
                {
                    queryable = queryable.Include(e => e.Exam);
                }

                var userExams = await queryable
                                .OrderByDescending(e => e.StartedtedAt)
                                .Skip(request.Offset)
                                .Take(request.Limit)
                                .ToListAsync(cancellationToken);

                var userExamsCount = await queryable.CountAsync();

                var userExamDTOs = mapper.Map <List <Domain.UserExam>, List <UserExamDTO> >(userExams);

                return(new UserExamsDTOEnvelope(userExamDTOs, userExamsCount));
            }
            public async Task <QuestionDTOEnvelope> Handle(Request request, CancellationToken cancellationToken)
            {
                var userId = currentUserAccessor.GetCurrentUserId();
                var exam   = context.Exams.NotPublishedByIdAndUserId(request.ExamId, userId).FirstOrDefault();

                if (exam == null)
                {
                    throw new Exceptions.ExamNotFoundException();
                }

                var question = mapper.Map <QuestionData, Domain.Question>(request.Question);

                question.ExamId = exam.Id;
                question.Exam   = exam;
                var utcNow = DateTime.UtcNow;

                question.CreatedAt = utcNow;
                question.UpdatedAt = utcNow;

                question.AnswerOptions.ToList().ForEach(ao =>
                {
                    ao.Question  = question;
                    ao.CreatedAt = utcNow;
                    ao.UpdatedAt = utcNow;
                });
                await this.context.Questions.AddAsync(question);

                await context.SaveChangesAsync();

                context.Entry(question).Reload();
                foreach (var answerOption in question.AnswerOptions)
                {
                    context.Entry(answerOption).Reload();
                }
                var questionDto = mapper.Map <Domain.Question, QuestionDTO>(question);

                return(new QuestionDTOEnvelope(questionDto));
            }
            public async Task <ExamsDTOEnvelope> Handle(Query request, CancellationToken cancellationToken)
            {
                int userId = currentUserAccessor.GetCurrentUserId();

                var queryable = context.Exams.AsNoTracking();

                queryable = queryable.Where(e => e.UserId == userId);

                switch (request.PublishType)
                {
                case PublishType.Published:
                    queryable = queryable.Where(e => e.IsPublished);
                    break;

                case PublishType.NotPublished:
                    queryable = queryable.Where(e => !e.IsPublished);
                    break;

                case PublishType.All:
                default:
                    break;
                }

                switch (request.PrivateType)
                {
                case PrivateType.Private:
                    queryable = queryable.Where(e => e.IsPrivate);
                    break;

                case PrivateType.Public:
                    queryable = queryable.Where(e => !e.IsPrivate);
                    break;

                case PrivateType.All:
                default:
                    break;
                }

                if (request.IncludeTags)
                {
                    queryable = queryable.IncludeTags();
                }

                if (request.IncludeUser)
                {
                    queryable = queryable.Include(e => e.User);
                }


                var exams = await queryable
                            .OrderByDescending(e => e.CreatedAt)
                            .Skip(request.Offset)
                            .Take(request.Limit)
                            .ToListAsync(cancellationToken);

                var examCount = await queryable.CountAsync();

                var examDTOs = mapper.Map <List <Domain.Exam>, List <ExamDTO> >(exams);

                return(new ExamsDTOEnvelope(examDTOs, examCount));
            }