Exemple #1
0
        public async Task <IEnumerable <TutorDto> > GetTutors(int moduleId)
        {
            var userId = _currentUserService.GetUserId();
            var tutors = await _userManager.Users
                         .Include(u => u.TutoredSessions)
                         .Include(u => u.TutorStudents)
                         .Where(u => u.TutorModules.Any(tm => tm.ModuleId == moduleId))
                         .Where(u => u.IgnoresToStudents.All(its => its.StudentId != userId))
                         .Where(u => u.Id != userId)
                         .OrderByDescending(u => u.TutoredSessions.Count)
                         .ToListAsync();

            var tutorDtos = tutors.Select(t => new TutorDto
            {
                Id                   = t.Id,
                Name                 = $"{t.FirstName} {t.LastName}",
                StudentCycle         = t.StudentCycle,
                StudentYear          = t.StudentYear,
                Faculty              = t.Faculty,
                StudyBranch          = t.StudyBranch,
                TutoringSessionCount = t.TutoredSessions.Count(ts => ts.Status == TutoringSessionStatusEnum.Finished),
                IsAddable            = t.TutorStudents.All(st => st.ModuleId != moduleId || st.StudentId != userId),
                AverageScore         = Math.Round(
                    t.TutoredSessions
                    .Where(ts => ts.Evaluation != null)
                    .Select(ts => (double)ts.Evaluation.GetValueOrDefault())
                    .DefaultIfEmpty(0.0)
                    .Average(),
                    1
                    )
            });

            return(tutorDtos);
        }
Exemple #2
0
        public async Task PostChatMessage(string receiverId, ChatMessageNewDto chatMessageNew)
        {
            await ValidateMessagePosting(receiverId, chatMessageNew);

            var senderId = _currentUserService.GetUserId();

            var chatMessage = new ChatMessage
            {
                ReceiverId = receiverId,
                SenderId   = senderId,
                Timestamp  = _timeService.GetCurrentTime(),
                Content    = chatMessageNew.Content,
                ModuleId   = chatMessageNew.ModuleId
            };

            await _chatMessagesRepository.Create(chatMessage);

            var sender = await _userManager.FindByIdAsync(senderId);

            var chatMessageDto = new ChatMessageDto
            {
                SenderId   = chatMessage.SenderId,
                Timestamp  = chatMessage.Timestamp,
                SenderName = $"{sender.FirstName} {sender.LastName}",
                Content    = chatMessage.Content
            };

            await _hubsService.SendChatNotificationToUser(senderId, chatMessageDto);

            await _hubsService.SendChatNotificationToUser(receiverId, chatMessageDto);
        }
Exemple #3
0
        public async Task <IActionResult> Index(int id)
        {
            var post = await _postService.GetPostById(id);

            var userId = await _currentUserService.GetUserId();

            ViewData["currentUser"] = userId;

            return(View(post));
        }
Exemple #4
0
        public async Task ApplyForTutoring(int moduleId, TutoringApplicationNewDto tutoringApplicationNew)
        {
            var currentUserId = _currentUserService.GetUserId();
            var currentUser   = await _userManager.Users
                                .Include(u => u.TutorModules)
                                .Include(u => u.TutoringApplications)
                                .FirstOrDefaultAsync(u => u.Id == currentUserId);

            if (currentUser.TutorModules.Any(tm => tm.ModuleId == moduleId))
            {
                throw new InvalidOperationException($"Could not apply for tutoring: user (id='{currentUser.Id}') is already a tutor in this module.");
            }

            var tutoringApplication = new TutoringApplication
            {
                ModuleId           = moduleId,
                StudentId          = currentUserId,
                RequestDate        = _timeService.GetCurrentTime(),
                MotivationalLetter = tutoringApplicationNew.MotivationalLetter
            };

            currentUser.TutoringApplications.Add(tutoringApplication);

            await _userManager.UpdateAsync(currentUser);
        }
        public async Task <Unit> Handle(DeleteRecipe request, CancellationToken cancellationToken)
        {
            var @event = _mapper.Map(request, _dateTime.GetCurrentTime(), _currentUser.GetUserId());
            await _eventStore.AddEvent(@event);

            return(Unit.Value);
        }
        public async Task <Unit> Handle(UpdateAccountCommand request, CancellationToken cancellationToken)
        {
            var id = int.Parse(_userService.GetUserId());

            var entity = await _context.Users.FindAsync(id);

            if (entity == null)
            {
                throw new NotFoundException(nameof(User), id);
            }

            if (request.Avatar != null)
            {
                string fileName = _imageService.SaveImage(request.Avatar);
                //await request.Avatar.CopyToAsync(new FileStream(filePath, FileMode.Create));

                if (entity.AvatarPath != null)
                {
                    _imageService.DeleteImage(entity.AvatarPath);
                }

                entity.AvatarPath = fileName;
            }

            _mapper.Map(request, entity);

            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
Exemple #7
0
        public async Task <PictureDTO> AddPicture(CreatePictureDTO data)
        {
            string fileName = GenerateRandomFileName(data.Extension);
            await _storageService.AddAsync(fileName, data.Picture);

            Picture picData = new Picture()
            {
                Date        = DateTime.UtcNow,
                Description = data.Description,
                PicIdentity = fileName,
                UserId      = _userService.GetUserId()
            };

            await _pictureRepository.AddAsync(picData);

            return(_mapper.Map <Picture, PictureDTO>(picData));
        }
 private void Audit()
 {
     foreach (var entity in ChangeTracker.Entries <AuditEntity>())
     {
         if (entity.State == EntityState.Added)
         {
             entity.Entity.Created    = DateTime.Now;
             entity.Entity.CreatedBy  = currentUserService.GetUserId();
             entity.Entity.Identifier = Guid.NewGuid();
         }
         else if (entity.State == EntityState.Modified)
         {
             entity.Entity.Modified   = DateTime.Now;
             entity.Entity.ModifiedBy = currentUserService.GetUserId();
         }
     }
 }
        public Task Process(TRequest request, CancellationToken cancellationToken)
        {
            var name = typeof(TRequest).Name;

            _logger.LogInformation("SSWConsulting Request: {Name} {@UserId} {@Request}",
                                   name, _currentUserService.GetUserId(), request);

            return(Task.CompletedTask);
        }
Exemple #10
0
        public override Task <int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
        {
            ChangeTracker.DetectChanges();

            foreach (var entry in ChangeTracker.Entries <BaseEntity>())
            {
                if (entry.State == EntityState.Added)
                {
                    entry.Entity.CreatedBy = _currentUserService.GetUserId();
                    entry.Entity.Created   = DateTime.Now;
                }
                else if (entry.State == EntityState.Modified)
                {
                    entry.Entity.LastModifiedBy = _currentUserService.GetUserId();
                    entry.Entity.LastModified   = DateTime.Now;
                }
            }

            return(base.SaveChangesAsync(cancellationToken));
        }
Exemple #11
0
        public async Task <Unit> Handle(CreateCommentReportCommand request, CancellationToken cancellationToken)
        {
            var entity = _mapper.Map <CommentReport>(request);

            entity.AccuserId = int.Parse(_userService.GetUserId());

            _context.CommentReports.Add(entity);
            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
Exemple #12
0
        public override Task <int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
        {
            foreach (var entry in ChangeTracker.Entries <AuditableEntity>())
            {
                switch (entry.State)
                {
                case EntityState.Added:
                    entry.Entity.CreatedBy = _currentUserService.GetUserId();
                    entry.Entity.Created   = SystemClock.Now;
                    break;

                case EntityState.Modified:
                    entry.Entity.LastModifiedBy = _currentUserService.GetUserId();
                    entry.Entity.LastModified   = SystemClock.Now;
                    break;
                }
            }

            return(base.SaveChangesAsync(cancellationToken));
        }
        public async Task <SuggestedUserListVm> Handle(GetSuggestedUserListQuery request, CancellationToken cancellationToken)
        {
            var id = _userService.GetUserId();

            var model = new SuggestedUserListVm();

            using (var connection = new SqlConnection(_configuration.GetConnectionString("DieteticSNSDatabase")))
            {
                var friendIds = await connection.QueryAsync <int>($@"
                    SELECT Id
                    FROM AspNetUsers LEFT OUTER JOIN Followings ON AspNetUsers.Id = Followings.UserId
                    WHERE FollowerId = { id }
                    AND SYSDATETIME() > IIF(LockoutEnd IS NULL, DATEADD(minute, -1, SYSDATETIME()), LockoutEnd);
                ");

                if (friendIds.Count() != 0)
                {
                    string friendIdSet = $"({ id },";

                    foreach (var friendId in friendIds)
                    {
                        friendIdSet += friendId + ", ";
                    }

                    friendIdSet = friendIdSet.Remove(friendIdSet.Length - 2) + ")";

                    var suggestedUsers = await connection.QueryAsync <SuggestedUserDto>($@"
                        SELECT TOP 4 Id, FirstName, LastName, AvatarPath, COUNT(Id) FollowersCount
                        FROM AspNetUsers LEFT OUTER JOIN Followings ON AspNetUsers.Id = Followings.UserId
                        WHERE Id NOT IN { friendIdSet }
                        AND SYSDATETIME() > IIF(LockoutEnd IS NULL, DATEADD(minute, -1, SYSDATETIME()), LockoutEnd)
                        GROUP BY Id, FirstName, LastName, AvatarPath
                        ORDER BY FollowersCount DESC;
                    ");

                    model.Users = suggestedUsers.ToList();
                }
                else
                {
                    var suggestedUsers = await connection.QueryAsync <SuggestedUserDto>($@"
                        SELECT TOP 4 Id, FirstName, LastName, AvatarPath, COUNT(Id) FollowersCount
                        FROM AspNetUsers LEFT OUTER JOIN Followings ON AspNetUsers.Id = Followings.UserId
                        WHERE Id != { id }
                        AND SYSDATETIME() > IIF(LockoutEnd IS NULL, DATEADD(minute, -1, SYSDATETIME()), LockoutEnd)
                        GROUP BY Id, FirstName, LastName, AvatarPath
                        ORDER BY FollowersCount DESC;
                    ");

                    model.Users = suggestedUsers.ToList();
                }
            }

            return(model);
        }
        public async Task AddStudentTutor(string tutorId, int moduleId)
        {
            var currentUserId = _currentUserService.GetUserId();

            if (currentUserId == tutorId)
            {
                throw new InvalidOperationException($"Could not add tutor (id='{tutorId}'): you can't add yourself.");
            }

            var tutorExists = await _moduleTutorsRepository.Exists(moduleId, tutorId);

            if (!tutorExists)
            {
                throw new InvalidOperationException($"Could not add tutor (id='{tutorId}'): not found.");
            }

            var tutorIgnoresStudent = await _studentTutorIgnoresRepository.Exists(sti => sti.TutorId == tutorId && sti.StudentId == currentUserId);

            if (tutorIgnoresStudent)
            {
                throw new InvalidOperationException($"Could not add tutor (id='{tutorId}'): he has ignored you.");
            }

            var studentTutor = new StudentTutor
            {
                StudentId = currentUserId,
                TutorId   = tutorId,
                ModuleId  = moduleId
            };

            await _studentTutorsRepository.Create(studentTutor);
        }
Exemple #15
0
        public async Task UploadAssignments(int moduleId, string studentId, IFormFileCollection formFiles)
        {
            var tutorId = _currentUserService.GetUserId();

            await ValidateAssignmentsUpload(moduleId, studentId, formFiles);

            _filesService.CreateDirectory($"{AssignmentsRoot}{moduleId}");
            _filesService.CreateDirectory($"{AssignmentsRoot}{moduleId}/{tutorId}");
            _filesService.CreateDirectory($"{AssignmentsRoot}{moduleId}/{tutorId}/{studentId}");

            var assignmentEntities = new List <Assignment>();

            foreach (var formFile in formFiles)
            {
                await _filesService.UploadFile(formFile, $"{AssignmentsRoot}{moduleId}/{tutorId}/{studentId}/{formFile.FileName}");

                assignmentEntities.Add(new Assignment
                {
                    AssignmentFileName = formFile.FileName,
                    StudentId          = studentId,
                    TutorId            = tutorId,
                    ModuleId           = moduleId
                });
            }

            await _assignmentsRepository.CreateMany(assignmentEntities);
        }
Exemple #16
0
        public async Task <int> Handle(CreateIssueCommand request, CancellationToken cancellationToken)
        {
            var userId       = _currentUserService.GetUserId();
            var defaultState = await _issueStateRepository.GetDefaultState();

            var issue = new Issue(request.Summary, request.IssueTypeId, userId, defaultState);

            _issueRepository.Add(issue);

            await _issueRepository.Commit(cancellationToken);

            return(issue.Id);
        }
        public async Task <Unit> Handle(DeleteAllNotificationsCommand request, CancellationToken cancellationToken)
        {
            var id = int.Parse(_userService.GetUserId());

            var entities = _context.Notifications
                           .Where(x => x.RecipientId == id).ToList();

            _context.Notifications.RemoveRange(entities);

            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
Exemple #18
0
        public async Task <UserModuleMetadataDto> GetUserModuleMetadata(int moduleId)
        {
            var userId = _currentUserService.GetUserId();
            var module = await _modulesRepository.GetById(moduleId);

            var canResignFromTutoring = module.ModuleTutors.Any(mt => mt.TutorId == userId);
            var metadata = new UserModuleMetadataDto
            {
                CanApplyForTutoring   = !canResignFromTutoring && module.TutoringApplications.All(mt => mt.StudentId != userId),
                CanResignFromTutoring = canResignFromTutoring
            };

            return(metadata);
        }
        public override Task <int> SaveChangesAsync(CancellationToken cancellationToken)
        {
            ChangeTracker.DetectChanges();

            foreach (var entry in ChangeTracker.Entries <AuditableEntity>())
            {
                if (entry.State == EntityState.Modified)
                {
                    entry.Entity.UpdatedBy   = _currentUserService.GetUserId();
                    entry.Entity.UpdatedDate = _dateTime.Now;
                }
            }

            return(base.SaveChangesAsync(cancellationToken));
        }
Exemple #20
0
        public async Task <Unit> Handle(ReadNotificationsCommand request, CancellationToken cancellationToken)
        {
            var id = int.Parse(_userService.GetUserId());

            var entities = _context.Notifications
                           .Where(x => x.RecipientId == id && x.IsRead == false).ToList();

            foreach (var entity in entities)
            {
                entity.IsRead = true;
            }

            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
Exemple #21
0
        public async Task <UnreadNotificationListVm> Handle(GetUnreadNotificationListQuery request, CancellationToken cancellationToken)
        {
            var id = _userService.GetUserId();

            var model = new UnreadNotificationListVm();

            using (var connection = new SqlConnection(_configuration.GetConnectionString("DieteticSNSDatabase")))
            {
                var roles = await connection.QueryAsync <UnreadNotificationDto>($@"
                    SELECT UserId, RecipientId, NotificationType, CreatedAt, FirstName, LastName, AvatarPath
                    FROM Notifications LEFT OUTER JOIN AspNetUsers ON Notifications.UserId = AspNetUsers.Id
                    WHERE RecipientId = { id }
                    AND IsRead = 0
                    ORDER BY CreatedAt DESC;
                ");

                foreach (var role in roles)
                {
                    switch (role.NotificationType)
                    {
                    case NotificationType.PostComment:
                        role.NotificationText = "commented on your post.";
                        break;

                    case NotificationType.PostLike:
                        role.NotificationText = "liked your post.";
                        break;

                    case NotificationType.CommentLike:
                        role.NotificationText = "liked your comment.";
                        break;

                    case NotificationType.UserFollowing:
                        role.NotificationText = "is now following you.";
                        break;

                    case NotificationType.UserUnfollowing:
                        role.NotificationText = "stopped following you.";
                        break;
                    }
                }

                model.Notifications = roles.ToList();
            }

            return(model);
        }
Exemple #22
0
        public async Task <Unit> Handle(CreatePostCommand request, CancellationToken cancellationToken)
        {
            var entity = _mapper.Map <Post>(request);

            entity.UserId = int.Parse(_userService.GetUserId());

            if (request.Photo != null)
            {
                string fileName = _imageService.SaveImage(request.Photo);
                entity.PhotoPath = fileName;
            }

            _context.Posts.Add(entity);
            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
Exemple #23
0
        public async Task <Unit> Handle(DeleteAccountCommand request, CancellationToken cancellationToken)
        {
            var id = int.Parse(_userService.GetUserId());

            var entity = await _context.Users
                         .Include(x => x.Comments)
                         .Include(x => x.Posts)
                         .ThenInclude(x => x.PostComments)
                         .Include(x => x.Posts)
                         .ThenInclude(x => x.PostReports)
                         .Include(x => x.Posts)
                         .ThenInclude(x => x.PostLikes)
                         .Include(x => x.Followings)
                         .Include(x => x.NotificationsTo)
                         .FirstOrDefaultAsync(x => x.Id == id);

            if (entity == null)
            {
                throw new NotFoundException(nameof(User), id);
            }

            if (entity.AvatarPath != null)
            {
                _imageService.DeleteImage(entity.AvatarPath);
            }

            foreach (var post in entity.Posts)
            {
                _imageService.DeleteImage(post.PhotoPath);

                _context.Comments.RemoveRange(post.PostComments);
                _context.Reports.RemoveRange(post.PostReports);
                _context.Likes.RemoveRange(post.PostLikes);
            }

            _context.Comments.RemoveRange(entity.Comments);
            _context.Followings.RemoveRange(entity.Followings);
            _context.Notifications.RemoveRange(entity.NotificationsTo);

            _context.Users.Remove(entity);

            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
Exemple #24
0
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            _timer.Start();

            var response = await next();

            _timer.Stop();

            if (_timer.ElapsedMilliseconds > 500)
            {
                var name = typeof(TRequest).Name;

                _logger.LogWarning("Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@UserId} {@Request}",
                                   name, _timer.ElapsedMilliseconds, _currentUserService.GetUserId(), request);
            }

            return(response);
        }
Exemple #25
0
        public async Task <Unit> Handle(CreateCommentLikeCommand request, CancellationToken cancellationToken)
        {
            var entity = _mapper.Map <CommentLike>(request);

            entity.UserId = int.Parse(_userService.GetUserId());

            _context.CommentLikes.Add(entity);

            if (await _context.SaveChangesAsync(cancellationToken) > 0)
            {
                var item = _context.CommentLikes
                           .Where(x => x.CommentId == entity.CommentId && x.UserId == entity.UserId)
                           .FirstOrDefault();

                await _wallService.SendCommentLike(entity.UserId, item.Id, item.CommentId);

                var recipientId = _context.Comments.Find(entity.CommentId)?.UserId;

                if (recipientId != null)
                {
                    var setting = _context.UserNotificationSettings
                                  .Where(x => x.UserId == recipientId)
                                  .FirstOrDefault()
                                  .CommentLikes;

                    if (setting)
                    {
                        if (entity.UserId != recipientId)
                        {
                            var command = new CreateNotificationCommand
                            {
                                UserId           = entity.UserId,
                                RecipientId      = recipientId.Value,
                                NotificationType = NotificationType.CommentLike
                            };

                            await _mediator.Send(command);
                        }
                    }
                }
            }

            return(Unit.Value);
        }
Exemple #26
0
        public async Task <Unit> Handle(UpdateNotificationsCommand request, CancellationToken cancellationToken)
        {
            var id = int.Parse(_userService.GetUserId());

            var entity = _context.UserNotificationSettings
                         .Where(x => x.UserId == id)
                         .FirstOrDefault();

            if (entity == null)
            {
                throw new NotFoundException(nameof(UserNotificationSettings), id);
            }

            _mapper.Map(request, entity);

            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }
        public async Task <IEnumerable <TutoringSessionDto> > GetTutoringSessions()
        {
            var currentUserId    = _currentUserService.GetUserId();
            var tutoringSessions = await _tutoringSessionsRepository.GetFiltered(ts => ts.TutorId == currentUserId);

            return(tutoringSessions
                   .Select(ts => new TutoringSessionDto
            {
                Id = ts.Id,
                CreationDate = ts.CreationDate,
                Evaluation = ts.Evaluation,
                IsSubscribed = ts.IsSubscribed,
                ModuleName = ts.Module.Name,
                ParticipantName = ts.Student.FirstName + " " + ts.Student.LastName,
                SessionDate = ts.SessionDate,
                Status = ts.Status,
                StatusChangeDate = ts.StatusChangeDate,
                CancellationReason = ts.CancellationReason
            })
                   .OrderByDescending(ts => ts.SessionDate));
        }
        public async Task <UserNotificationSettingsVm> Handle(GetUserNotificationSettingsQuery request, CancellationToken cancellationToken)
        {
            var id = _userService.GetUserId();

            using (var connection = new SqlConnection(_configuration.GetConnectionString("DieteticSNSDatabase")))
            {
                var model = await connection.QueryFirstOrDefaultAsync <UserNotificationSettingsVm>($@"
                    SELECT PostComments, PostLikes, CommentLikes, UserFollowings, UserUnfollowings
                    FROM UserNotificationSettings
                    WHERE UserId = { id }
                ");

                if (model == null)
                {
                    throw new NotFoundException(nameof(User), id);
                }

                return(model);
            }
        }
        public async Task <AccountDetailsVm> Handle(GetAccountDetailsQuery request, CancellationToken cancellationToken)
        {
            var id = _userService.GetUserId();

            using (var connection = new SqlConnection(_configuration.GetConnectionString("DieteticSNSDatabase")))
            {
                var model = await connection.QueryFirstOrDefaultAsync <AccountDetailsVm>($@"
                    SELECT * 
                    FROM AspNetUsers
                    WHERE id = { id }
                ");

                if (model == null)
                {
                    throw new NotFoundException(nameof(User), id);
                }

                return(model);
            }
        }
        public async Task <Unit> Handle(DeleteAvatarCommand request, CancellationToken cancellationToken)
        {
            var id = int.Parse(_userService.GetUserId());

            var entity = await _context.Users.FindAsync(id);

            if (entity == null)
            {
                throw new NotFoundException(nameof(User), id);
            }

            if (entity.AvatarPath != null)
            {
                _imageService.DeleteImage(entity.AvatarPath);
                entity.AvatarPath = null;
            }

            await _context.SaveChangesAsync(cancellationToken);

            return(Unit.Value);
        }