public async Task <ActionResult <int> > GetUserId()
        {
            _logger.LogInformation("Getting user id");
            var userId = _userResolverService.GetUserId();

            return(Ok(userId));
        }
Esempio n. 2
0
 public IQueryable <T> AsQueryableForUser(string userId = null)
 {
     if (userId == null)
     {
         return(_dbSet.AsNoTracking().Where(p => p.IdentityId == userService.GetUserId()));
     }
     return(_dbSet.AsNoTracking().Where(p => p.IdentityId == userId));
 }
        public async Task <bool> UpdateAsync(BookPutDto bookDto)
        {
            var book    = _mapper.Map <Book>(bookDto);
            var oldBook = await _bookRepository.GetAll().AsNoTracking().FirstOrDefaultAsync(a => a.Id == book.Id);

            if (oldBook == null)
            {
                return(false);
            }
            if (bookDto.FieldMasks.Contains("Image"))
            {
                string imagePath;
                bookDto.FieldMasks.Remove("Image");
                bookDto.FieldMasks.Add("ImagePath");
                if (oldBook.ImagePath != null)
                {
                    _imageService.DeleteImage(oldBook.ImagePath);
                }
                if (bookDto.Image != null)
                {
                    imagePath = await _imageService.UploadImage(bookDto.Image);
                }
                else
                {
                    imagePath = null;
                }
                book.ImagePath = imagePath;
            }
            await _bookRepository.Update(book, bookDto.FieldMasks);

            if (bookDto.UserId != oldBook.UserId)
            {
                var user = await _userLocationRepository.FindByIdAsync(oldBook.UserId.Value);

                string emailMessageForUser = $" Administrator has successfully received your book '{oldBook.Name}'";
                SendMailForOwnership(book, user, emailMessageForUser);
                SendNotificationToUser(oldBook.UserId.Value, book.Id, emailMessageForUser);

                var userId = _userResolverService.GetUserId();
                var admin  = await _userLocationRepository.FindByIdAsync(userId);

                string emailMessageForAdmin = $"You became the current owner of the book '{oldBook.Name}'";
                SendMailForOwnership(book, admin, emailMessageForAdmin);
                SendNotificationToUser(userId, book.Id, emailMessageForAdmin);
            }
            var affectedRows = await _bookRepository.SaveChangesAsync();

            var isDatabaseUpdated = affectedRows > 0;

            if (isDatabaseUpdated &&
                bookDto.FieldMasks.Contains("State") &&
                bookDto.State == BookState.Available)
            {
                await _wishListService.NotifyAboutAvailableBookAsync(book.Id);
            }
            return(true);
        }
        public async Task <ActionResult <int> > Put([FromBody] RootUpdateDto updateDto)
        {
            if (updateDto.OwnerId != _userResolverService.GetUserId())
            {
                return(Forbid());
            }
            int number = await _rootBookCommentService.Update(updateDto);

            if (number == 0)
            {
                return(NotFound(number));
            }
            return(Ok(number));
        }
        public async Task <PaginationDto <BookGetDto> > GetWishesOfCurrentUserAsync(PageableParams pageableParams)
        {
            var currentUserId = _userResolverService.GetUserId();

            var wishesQuery = _wishRepository.GetAll()
                              .Include(wish => wish.Book.Language)
                              .Include(wish => wish.Book.BookAuthor).ThenInclude(bookAuthor => bookAuthor.Author)
                              .Include(wish => wish.Book.BookGenre).ThenInclude(bookGenre => bookGenre.Genre)
                              .Include(wish => wish.Book.User.UserRoom.Location)
                              .Where(wish => wish.UserId == currentUserId)
                              .Select(wish => wish.Book);
            var wishesPaginated =
                await _paginationService.GetPageAsync <BookGetDto, Book>(wishesQuery, pageableParams);

            return(wishesPaginated);
        }
Esempio n. 6
0
        public async Task <ActionResult <RequestDto> > Make([FromRoute] int bookId)
        {
            try
            {
                var userId  = _userResolverService.GetUserId();
                var request = await _requestService.MakeAsync(userId, bookId);

                if (request == null)
                {
                    return(NotFound());
                }

                return(Ok(request));
            }
            catch (InvalidOperationException ex)
            {
                return(StatusCode((int)HttpStatusCode.Forbidden, ex.Message));
            }
        }
        public async Task <IEnumerable <NotificationDto> > GetAllForCurrentUserAsync()
        {
            var currentUserId = _userResolverService.GetUserId();

            var notifications = _notificationsRepository.GetAll()
                                .Where(notification => notification.UserId == currentUserId)
                                .OrderByDescending(notification => notification.CreatedAt);

            return(_mapper.Map <IEnumerable <NotificationDto> >(await notifications.ToListAsync()));
        }
        public async Task RemoveUser(int userId)
        {
            await using var transaction = await _context.Database.BeginTransactionAsync();

            var user = _userRepository.GetAll().Include(user => user.Book).Include(user => user.RequestUser).ThenInclude(requesr => requesr.Book).FirstOrDefault(user => user.Id == userId);

            if (user == null)
            {
                throw new ObjectNotFoundException($"There is no user with id = {userId} in database");
            }

            if (user.Book.Any(p => p.State != BookState.InActive))
            {
                throw new InvalidOperationException();
            }
            var requestsIds = user.RequestUser.Where(request => request.ReceiveDate == null).Select(request => request.Id);

            foreach (var requestId in requestsIds)
            {
                await _requestService.RemoveAsync(requestId);
            }
            user.IsDeleted = true;
            var affectedRows = await _userRepository.SaveChangesAsync();

            if (affectedRows == 0)
            {
                throw new DbUpdateException();
            }

            await transaction.CommitAsync();

            SendMail(user, "�Your account was deleted from Bookcrossing app.");

            var userIdAdmin = _userResolverService.GetUserId();
            var userAdmin   = await _userRepository.FindByIdAsync(userIdAdmin);

            SendMail(userAdmin, $"The user '{user.FirstName}' was successfully deleted from the user's list");

            SendNotificationToUser(userIdAdmin, $"The user {user.FirstName} was successfully deleted from the user's list");
        }
Esempio n. 9
0
        public async Task <ActionResult <CountersSetDto> > GetCounters()
        {
            var userId      = _userResolverService.GetUserId();
            var wishedCount = await _wishListService.GetNumberOfWishedBooksAsync(userId);

            var requestedCount = await _requestService.GetNumberOfRequestedBooksAsync(userId);

            var readCount = await _bookService.GetNumberOfBooksInReadStatusAsync(userId);

            var numberOfTimesRegisteredBooksWereRead = await _bookService.GetNumberOfTimesRegisteredBooksWereReadAsync(userId);

            var countersDto = new CountersSetDto()
            {
                WishedBooksCount             = wishedCount,
                RequestedBooksCount          = requestedCount,
                ReadBooksCount               = readCount,
                RegisteredBooksWereReadCount = numberOfTimesRegisteredBooksWereRead
            };

            return(countersDto);
        }
 public async Task <IActionResult> SendFriendRequestAsync([FromBody] int receiverId)
 {
     return(this.ConvertResult(
                await friendRequestService.AddFriendRequestAsync(receiverId, userResolverService.GetUserId())));
 }
Esempio n. 11
0
 public async Task <IActionResult> GetTrainingTemplatesAsync([FromQuery] SortedPaginationModel model)
 {
     return(this.ConvertResult(
                await trainingTemplateService.GetTrainingTemplatesByUserIdAsync(model, userResolverService.GetUserId())));
 }
Esempio n. 12
0
 public async Task <IActionResult> AddFollowingAsync([FromBody] int userToFollow)
 {
     return(this.ConvertResult(await followingService.AddFollowingAsync(userToFollow, userResolverService.GetUserId())));
 }
Esempio n. 13
0
 public async Task <IActionResult> GetActiveTrainingAsync()
 {
     return(this.ConvertResult(await activeTrainingService.GetActiveTrainingAsync(userResolverService.GetUserId())));
 }
Esempio n. 14
0
        #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        public async Task <Routine2NoticeOutput> SendNoticeAsync(
        #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
            int routineId
            , int entityId
            , string userIdsSqlQuery
            , string modelSqlQuery
            , string body
            , string bodySms
            , string bodyEmail
            , bool realSend = true)
        {
            var noticeOutput = new Routine2NoticeOutput();

            // پیغام را باید به چه کسانی بفرستیم؟
            var userIds = _connection.Query <int>(userIdsSqlQuery, new { EntityId = entityId }).ToList();

            // اگر هیچ کاربری پیدا نشد، سراغ پیغام بعدی میرویم
            if (userIds.Count == 0)
            {
                return(noticeOutput);
            }

            noticeOutput.UserIds = userIds;

            // پیغامی که باید برای تک تک کاربران ارسال شود را میسازیم
            foreach (var userId in userIds)
            {
                var userNoticeOutput = new Routine2NoticeSpecificUser {
                    UserId = userId
                };

                // اگر مدل باید بگیریم، کوئری را اجرا میکنیم
                body      = body ?? "";
                bodySms   = bodySms ?? "";
                bodyEmail = bodyEmail ?? "";

                if (!string.IsNullOrWhiteSpace(modelSqlQuery))
                {
                    var model = _connection.QueryFirstOrDefault(modelSqlQuery,
                                                                new { EntityId = entityId, UserId = userId });

                    if (model != null)
                    {
                        // مدل را تبدیل به دیکشنری میکنیم
                        var jsonString = JsonConvert.SerializeObject(model);
                        var dictionary = JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonString);

                        userNoticeOutput.Model = dictionary;

                        // convert dictionary to dynamic
                        var eo     = new ExpandoObject();
                        var eoColl = (ICollection <KeyValuePair <string, object> >)eo;
                        foreach (var kvp in dictionary)
                        {
                            eoColl.Add(kvp);
                        }

                        dynamic dynamicModel = eo;

                        if (!string.IsNullOrWhiteSpace(body))
                        {
                            body = StringExtensions.CompileRazor(body, dynamicModel);
                        }

                        if (!string.IsNullOrWhiteSpace(bodySms))
                        {
                            bodySms = StringExtensions.CompileRazor(bodySms, dynamicModel);
                        }

                        if (!string.IsNullOrWhiteSpace(bodyEmail))
                        {
                            bodyEmail = StringExtensions.CompileRazor(bodyEmail, dynamicModel);
                        }
                    }
                }

                userNoticeOutput.BodyCompiled      = body;
                userNoticeOutput.BodySmsCompiled   = bodySms;
                userNoticeOutput.BodyEmailCompiled = bodyEmail;

                if (!string.IsNullOrWhiteSpace(body))
                {
                    try
                    {
                        // پیغام را میفرستیم
                        _context.Notice2.Add(new Notice2
                        {
                            CreateDate    = DateTime.Now,
                            EntityId      = entityId,
                            RoutineId     = routineId,
                            Body          = body,
                            IsRead        = false,
                            CreatorUserId = _userResolverService.GetUserId(),
                            ToUserId      = userId,
                        });

                        _context.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        throw;
                    }
                }


                if (!string.IsNullOrWhiteSpace(bodySms) || !string.IsNullOrWhiteSpace(bodyEmail))
                {
                    // برای ارسال اس ام اس و ایمیل باید کاربر را از دیتابیس بگیریم
                    var targetUser = _connection.QuerySingle <UserSummary>("SELECT * FROM [Users] WHERE [Id] = @UserId",
                                                                           new { UserId = userId });

                    userNoticeOutput.User = targetUser;

                    if (!string.IsNullOrWhiteSpace(bodySms))
                    {
                        // ارسال SMS
                        try
                        {
                            // اگر موبایل درست بود
                            if (targetUser.PhoneNumber.IsValidIranianMobileNumber())
                            {
                                // اس ام اس را ارسال میکنیم
                                if (realSend)
                                {
                                    #pragma warning disable 4014
                                    //_smsService.SendSmsAsync(targetUser.PhoneNumber, bodySms);
                                    #pragma warning restore 4014
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(bodyEmail))
                    {
                        // ارسال ایمیل
                        try
                        {
                            // اگر ایمیل درست بود
                            if (targetUser.Email.IsValidEmail())
                            {
                                // ایمیل را ارسال میکنیم
                                if (realSend)
                                {
                                    //_emailService.SendEmail(new EmailBody<int>
                                    //{
                                    //    To = targetUser.Email,
                                    //    Subject = "ارسال ایمیل از طریق سامانه شهر پژوهش : " + DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds,
                                    //    Body = "<div dir='rtl'>" + bodyEmail + "</div>"
                                    //});
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }

                noticeOutput.Notices.Add(userNoticeOutput);
            }

            return(noticeOutput);
        }
Esempio n. 15
0
 public SiteDbContext(
     DbContextOptions options,
     IUserResolverService userResolverService) : base(options)
 {
     _userId = userResolverService.GetUserId();
 }
Esempio n. 16
0
 public async Task <IActionResult> GetUserByNameAsync(string name)
 {
     return(this.ConvertResult(await userService.GetUserByNameAsync(name, userResolverService.GetUserId())));
 }
 public EquipmentContext(DbContextOptions <EquipmentContext> options, IUserResolverService userService)
     : base(options)
 {
     _userId   = userService.GetUserId();
     _userName = userService.GetUserName();
 }
Esempio n. 18
0
        public async Task <ServiceResult <Routine2ChangeStepResult> > ChangeStep(int RoutineId, int EntityId, Routine2Actions Action, string Description)
        {
            try
            {
                // گرفتن رکورد مورد نظر
                var entity = table.Find(EntityId);


                // درصورتی که رکورد مورد نظر وجود نداشت باید خطا برگردانده شود
                if (entity == null)
                {
                    throw new Exception($"داده‌ای با شناسه {EntityId} یافت نشد");
                }


                // مرحله بعدی فرآیند دراین قسمت به دست می‌آید
                var nextStep = GetNextStep(Action, entity, RoutineId);

                // درصورتی که مرحله بعدی -1 باشد باید خطا نمایش داده شود
                if (nextStep == -1)
                {
                    throw new Exception("Something went wrong, next dashboard couldn't be -1");
                }


                //=========================================================
                int userId   = _userResolverService.GetUserId();
                var fromStep = entity.RoutineStep;
                //=========================================================


                // ثبت لاگ جدید برای این کاربر که رکورد مورد را از یک مرحله به مرحله دیگر انتقال داده است
                _routine2Repository.CreateLog(new CreateRoutine2LogViewModel
                {
                    RoutineId        = RoutineId,
                    EntityId         = EntityId,
                    Description      = Description,
                    Action           = _routine2Repository.GetActionTitle(RoutineId, fromStep, Action),
                    Step             = fromStep,
                    ToStep           = nextStep,
                    UserId           = userId,
                    CreatorUserId    = userId,
                    RoutineRoleTitle = _routine2Repository.GetRoutineRoleTitle(RoutineId, entity.RoutineStep),
                });


                var routineVm = new EditRoutine2ViewModel(nextStep, entity.RoutineFlownDate);

                // اگر در مرحله آخر باشیم، باید به روال برچست تمام شده بزنیم
                if (entity.DoneSteps.Contains(nextStep))
                {
                    routineVm.RoutineIsDone = true;
                }

                // به صورت پیش‌فرض طرح رد شده است، مگر اینکه در مراحل تایید باشیم
                if (entity.SucceededSteps.Contains(nextStep))
                {
                    routineVm.RoutineIsSucceeded = true;
                }


                entity.RoutineStep           = nextStep;
                entity.RoutineFlownDate      = DateTime.Now;
                entity.RoutineStepChangeDate = DateTime.Now;

                _context.SaveChanges();

                var changeStepResult = new Routine2ChangeStepResult
                {
                    Action      = Action,
                    Description = Description,
                    UserId      = userId,
                    ToStep      = nextStep,
                    FromStep    = fromStep,
                    EntityId    = EntityId,
                    RoutineId   = RoutineId,
                };

                try { await _routine2Repository.SendNoticeAsync(changeStepResult); } catch (Exception) { }

                return(ServiceResult <Routine2ChangeStepResult> .Okay(changeStepResult));
            }
            catch (Exception ex)
            {
                return(ServiceResult <Routine2ChangeStepResult> .Exception(ex));
            }
        }
Esempio n. 19
0
 public async Task <IActionResult> AddTrainingSchedule([FromBody] ScheduledTrainingModel model)
 {
     return(this.ConvertResult(
                await scheduledTrainingService.AddScheduledTraining(model, userResolverService.GetUserId())));
 }
Esempio n. 20
0
 protected SiteDbContext(IUserResolverService userResolverService)
 {
     _userId = userResolverService.GetUserId();
 }
Esempio n. 21
0
 public async Task <IActionResult> RemoveFriendAsync([FromBody] int id)
 {
     return(this.ConvertResult(await friendService.RemoveFriendAsync(id, userResolverService.GetUserId())));
 }
 public async Task <IActionResult> GetExercisePropertyAsync(int id)
 {
     return(this.ConvertResult(
                await exercisePropertyService.GetExercisePropertyAsync(id, userResolverService.GetUserId())));
 }
 public async Task <IActionResult> AddPublicTemplateAsync([FromBody] int templateId)
 {
     return(this.ConvertResult(
                await publicTraningService.AddPublicTemplateAsync(templateId, userResolverService.GetUserId())));
 }