Example #1
0
        public async Task CreateItemAsync(KudosShopItemDto dto)
        {
            var alreadyExists = await _kudosShopItemsDbSet
                                .AnyAsync(t => t.Name == dto.Name && t.OrganizationId == dto.OrganizationId);

            if (alreadyExists)
            {
                throw new ValidationException(PremiumErrorCodes.KudosShopItemAlreadyExist, "Kudos shop item already exists");
            }

            var modified = DateTime.UtcNow;

            var newItem = new KudosShopItem
            {
                Name           = dto.Name,
                Price          = dto.Price,
                Description    = dto.Description,
                CreatedBy      = dto.UserId,
                Created        = modified,
                Modified       = modified,
                ModifiedBy     = dto.UserId,
                OrganizationId = dto.OrganizationId,
                PictureId      = dto.PictureId
            };

            _kudosShopItemsDbSet.Add(newItem);

            await _uow.SaveChangesAsync(dto.UserId);
        }
Example #2
0
        /// <summary>
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public async Task <bool> IsBanByEmailAsync(string email)
        {
            // Process
            var result = await _users.AnyAsync(user => user.Email == email.ToLower() && user.IsBan == true);

            // Result
            return(result);
        }
Example #3
0
        public async Task NewProject(NewProjectDto dto)
        {
            var owningUserExists = await _usersDbSet
                                   .AnyAsync(u => u.Id == dto.OwningUserId && u.OrganizationId == dto.OrganizationId);

            if (!owningUserExists)
            {
                throw new ValidationException(ErrorCodes.ContentDoesNotExist, "Incorrect user");
            }

            var members = await _usersDbSet
                          .Where(u => dto.MembersIds.Contains(u.Id))
                          .ToListAsync();

            var completeListOfAttributes = await ManageProjectAttributes(dto.Attributes);

            var project = new Project
            {
                Name           = dto.Title,
                Desc           = dto.Description,
                OwnerId        = dto.OwningUserId,
                OrganizationId = dto.OrganizationId,
                Logo           = dto.Logo,
                Attributes     = completeListOfAttributes.ToList(),
                Members        = members
            };

            var wall = new CreateWallDto
            {
                Name           = dto.Title,
                UserId         = dto.OwningUserId,
                OrganizationId = dto.OrganizationId,
                Type           = WallType.Project,
                Description    = dto.Description,
                Logo           = dto.Logo,
                Access         = WallAccess.Public,
                MembersIds     = members.Select(m => m.Id).Concat(new List <string> {
                    dto.OwningUserId
                }),
                ModeratorsIds = new List <string> {
                    dto.OwningUserId
                }
            };

            _projectsDbSet.Add(project);
            await _wallService.CreateNewWall(wall);

            await _uow.SaveChangesAsync(dto.UserId);
        }
Example #4
0
        public async Task <int> CreateNewWallAsync(CreateWallDto newWallDto)
        {
            var alreadyExists = await _wallsDbSet
                                .AnyAsync(w =>
                                          w.OrganizationId == newWallDto.OrganizationId &&
                                          w.Name == newWallDto.Name &&
                                          (w.Type == WallType.UserCreated ||
                                           w.Type == WallType.Main));

            if (alreadyExists)
            {
                throw new ValidationException(ErrorCodes.WallNameAlreadyExists, "Wall name already exists");
            }

            if (newWallDto.MembersIds == null || newWallDto.MembersIds.Any())
            {
                newWallDto.MembersIds = newWallDto.ModeratorsIds;
            }
            else
            {
                newWallDto.MembersIds = newWallDto.MembersIds.Union(newWallDto.ModeratorsIds);
            }

            var wall = new MultiwallWall
            {
                Access         = newWallDto.Access,
                Type           = newWallDto.Type == WallType.Main ? WallType.UserCreated : newWallDto.Type,
                OrganizationId = newWallDto.OrganizationId,
                Name           = newWallDto.Name,
                Logo           = newWallDto.Logo,
                Description    = newWallDto.Description,
                Moderators     = newWallDto.ModeratorsIds.Select(x => new WallModerator
                {
                    UserId = x
                }).ToList(),
                IsHiddenFromAllWalls = newWallDto.IsHiddenFromAllWalls,
                Members = newWallDto.MembersIds.Select(x => new WallMember
                {
                    UserId = x,
                    AppNotificationsEnabled   = true,
                    EmailNotificationsEnabled = true
                }).ToList()
            };

            _wallsDbSet.Add(wall);
            await _uow.SaveChangesAsync(newWallDto.UserId);

            return(wall.Id);
        }
        public async Task <bool> updateNegotiationplanrouteCF(GetNegotiationplanrouteCFDto getNegotiationplanrouteCFDto)
        {
            try
            {
                NegotiationplanrouteCF oNegotiationplanrouteCF = await _NegotiationplanrouteCFs.SingleAsync(i => i.id == getNegotiationplanrouteCFDto.id);

                if (!oNegotiationplanrouteCF.isAccepted && oNegotiationplanrouteCF.isAccepted)
                {
                    if (await _NegotiationplanrouteCFs.AnyAsync(i => i.negotiationplanrouteId == getNegotiationplanrouteCFDto.negotiationplanrouteId && i.isAccepted == true))
                    {
                        return(true);
                    }
                }

                if (getNegotiationplanrouteCFDto.carrierId != 0)
                {
                    oNegotiationplanrouteCF.agentId = getNegotiationplanrouteCFDto.agentCarriers.Where(i => i.id == getNegotiationplanrouteCFDto.carrierId).Select(i => i.parentId).Single();
                }

                oNegotiationplanrouteCF.carrierId     = getNegotiationplanrouteCFDto.carrierId;
                oNegotiationplanrouteCF.forwarderId   = getNegotiationplanrouteCFDto.forwarderId;
                oNegotiationplanrouteCF.netPrice      = getNegotiationplanrouteCFDto.netPrice;
                oNegotiationplanrouteCF.modiferUserId = getNegotiationplanrouteCFDto.userId;

                await _uow.SaveChangesAsync();

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Example #6
0
        public async Task <bool> updateNegotiationplan(GetNegotiationplanDto getNegotiationplanDto)
        {
            try
            {
                Negotiationplan oNegotiationplan = await _Negotiationplans.SingleAsync(i => i.id == getNegotiationplanDto.id);

                if (!oNegotiationplan.isAccepted && getNegotiationplanDto.isAccepted)
                {
                    if (await _Negotiationplans.AnyAsync(i => i.negotiationId == getNegotiationplanDto.negotiationId && i.isAccepted == true))
                    {
                        return(true);
                    }
                }

                if (getNegotiationplanDto.isAccepted)
                {
                    Negotiation ONegotiation = await _Negotiation.SingleAsync(i => i.id == getNegotiationplanDto.negotiationId);

                    ONegotiation.state = NegotiationStates.ConfirmedbyCustomer;
                }

                oNegotiationplan.planName      = getNegotiationplanDto.planName;
                oNegotiationplan.isAccepted    = getNegotiationplanDto.isAccepted;
                oNegotiationplan.modiferUserId = getNegotiationplanDto.userId;

                await _uow.SaveChangesAsync();

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #7
0
        public async Task AddBookAsync(NewBookDto bookDto)
        {
            await _newBookLock.WaitAsync();

            try
            {
                var bookAlreadyExists = await _booksDbSet
                                        .AnyAsync(book =>
                                                  (bookDto.Isbn != null && book.Code == bookDto.Isbn && book.OrganizationId == bookDto.OrganizationId) ||
                                                  (bookDto.Isbn == null && book.OrganizationId == bookDto.OrganizationId && book.Title == bookDto.Title));

                _bookServiceValidator.CheckIfBookAlreadyExists(bookAlreadyExists);
                await ValidateQuantifiedOfficesAsync(bookDto.QuantityByOffice.Select(o => o.OfficeId));

                ValidateQuantitiesValues(bookDto.QuantityByOffice.Select(o => o.BookQuantity));

                var newBook = MapNewBookToEntity(bookDto);
                _booksDbSet.Add(newBook);

                bookDto.QuantityByOffice
                .Where(office => office.BookQuantity > BookQuantityZero)
                .ForEach(office => _bookOfficesDbSet.Add(MapBookDtoToBookOfficeEntity(newBook, office, bookDto.UserId)));

                await _uow.SaveChangesAsync(false);
            }
            finally
            {
                _newBookLock.Release();
            }
        }
Example #8
0
        public async Task CreateAsync(JoinIdentityUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var hasAnyUser = await UserSet.AnyAsync();

            var dbUser = new DbUser()
            {
                UserName = user.UserName,
                Email    = user.UserName,
                Auth     = new UserAuthDetails()
                {
                    RegisterDate = DateTime.UtcNow,
                },
            };

            if (!hasAnyUser)
            {
                dbUser.Auth.EmailConfirmed = true;
                dbUser.Auth.IsAdmin        = true;
            }

            _ctx.UserSet.Add(dbUser);
            await _ctx.SaveChangesAsync();

            user.Id = dbUser.UserId;
        }
        private async Task CreateImpl(JoinIdentityUser user, CancellationToken ct = default)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var hasAnyUser = await UserSet.AnyAsync(ct);

            var dbUser = new DbUser()
            {
                UserName = user.UserName,
                Email    = user.UserName,
                Auth     = new UserAuthDetails()
                {
                    RegisterDate        = DateTime.UtcNow,
                    AspNetSecurityStamp = "",
                },
            };

            if (!hasAnyUser)
            {
                dbUser.Auth.EmailConfirmed = true;
                dbUser.Auth.IsAdmin        = true;
            }

            _ctx.UserSet.Add(dbUser);
            await _ctx.SaveChangesAsync(ct);

            user.Id = dbUser.UserId;
        }
 public async Task <bool> AnyEventsThisWeekByTypeAsync(IEnumerable <int> eventTypeIds)
 {
     return(await _eventsDbSet
            .AnyAsync(x => SqlFunctions.DatePart("wk", x.StartDate) == SqlFunctions.DatePart("wk", DateTime.UtcNow) &&
                      eventTypeIds.Contains(x.EventType.Id) &&
                      x.RegistrationDeadline > DateTime.UtcNow));
 }
Example #11
0
        public virtual async Task <bool> HasPermissionAsync(TPermission permission, string roleName)
        {
            #region Contracts

            if (permission == null)
            {
                throw new ArgumentNullException("permission");
            }
            if (string.IsNullOrEmpty(roleName) == true)
            {
                throw new ArgumentNullException("roleName");
            }

            #endregion

            // Require
            this.ThrowIfDisposed();

            // RoleEntity
            var roleEntity = await _roleStore.DbEntitySet.SingleOrDefaultAsync(r => r.Name.ToUpper() == roleName.ToUpper()).WithCurrentCulture();

            if (roleEntity == null)
            {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, IdentityResources.RoleNotFound, roleName));
            }

            // HasPermission
            return(await _permissionRoles.AnyAsync(pr => pr.RoleId.Equals(roleEntity.Id) && pr.PermissionId.Equals(permission.Id)).WithCurrentCulture());
        }
Example #12
0
 private async Task ValidateQuantifiedOfficesAsync(IEnumerable <int> officesIds)
 {
     foreach (var officeId in officesIds)
     {
         _bookServiceValidator.CheckIfRequestedOfficesExist(await _officesDbSet.AnyAsync(o => o.Id == officeId));
     }
 }
Example #13
0
        private async Task ValidateServiceRequestForCreateAsync(ServiceRequestDto newServiceRequest)
        {
            var isServiceRequestPriorityIdCorrect = await _serviceRequestPriorityDbSet.AnyAsync(x => x.Id == newServiceRequest.PriorityId);

            if (!isServiceRequestPriorityIdCorrect)
            {
                throw new ValidationException(ErrorCodes.ContentDoesNotExist, "Service request priority does not exist");
            }
        }
Example #14
0
        private async Task ValidateCategoryNameAsync(string categoryName, int id = 0)
        {
            var isNameAlreadyUsed = await _serviceRequestCategoryDbSet.AnyAsync(x => x.Name == categoryName && x.Id != id);

            if (isNameAlreadyUsed)
            {
                throw new ValidationException(ErrorCodes.DuplicatesIntolerable, "category name already exists");
            }
        }
Example #15
0
 public async Task <bool> CanAddTemColor(int participationId, int representativeUserId)
 {
     return
         (await
          _teamColors.AnyAsync(
              t =>
              t.ParticipationId == participationId &&
              t.Participation.RepresentativeUserId == representativeUserId));
 }
        private async Task ValidateEventTypeNameAsync(string eventTypeName, int organizationId)
        {
            var nameAlreadyExists = await _eventTypesDbSet
                                    .AnyAsync(x => x.OrganizationId == organizationId && x.Name == eventTypeName);

            if (nameAlreadyExists)
            {
                throw new ValidationException(PremiumErrorCodes.EventTypeNameAlreadyExists, "Event type name should be unique");
            }
        }
Example #17
0
        public Task <bool> CheckAccess(Guid conversationId)
        {
            var userId = _userManager.GetCurrentUserId();

            return
                (_conversations.AnyAsync(
                     a =>
                     (a.SenderId == userId && a.Id == conversationId) ||
                     ((a.ReceiverId == userId && a.Id == conversationId))));
        }
Example #18
0
        private async Task ValidatePostBookAsync(BookMobilePostDto bookDto, Book book)
        {
            var bookExistsInChosenOffice = book
                                           .BookOffices
                                           .Any((l => l.OfficeId == bookDto.OfficeId));

            _serviceValidator.ThrowIfBookExist(bookExistsInChosenOffice);

            var officeExists = await _officeDbSet.AnyAsync(o => o.Id == bookDto.OfficeId);

            _serviceValidator.ThrowIfOfficeDoesNotExist(officeExists);
        }
Example #19
0
        public async Task CreateJobType(JobTypeDTO jobTypeDTO)
        {
            var alreadyExists = await _jobTypesDbSet
                                .AnyAsync(t => t.Title == jobTypeDTO.Title && t.OrganizationId == jobTypeDTO.OrganizationId);

            if (alreadyExists)
            {
                throw new ValidationException(ErrorCodes.DuplicatesIntolerable, "Job position with that title already exists");
            }

            var newType = new JobPosition
            {
                Title          = jobTypeDTO.Title,
                CreatedBy      = jobTypeDTO.UserId,
                OrganizationId = jobTypeDTO.OrganizationId
            };

            _jobTypesDbSet.Add(newType);

            await _uow.SaveChangesAsync(jobTypeDTO.UserId);
        }
Example #20
0
        public async Task <bool> CanUserReadiness(int competitionId, int representativeUserId)
        {
            var currentDate = DateTime.Now;

            return
                (await
                 _competitionRepresentativeUsers.AnyAsync(
                     cru =>
                     cru.CompetitionId == competitionId && cru.RepresentativeUserId == representativeUserId &&
                     (cru.Competition.IsReadyActive &&
                      cru.Competition.ReadyStartDate.Value <= currentDate &&
                      currentDate <= cru.Competition.ReadyEndDate.Value)));
        }
Example #21
0
        public async Task CreateMonitorAsync(MonitorDto newMonitor, UserAndOrganizationDto userAndOrganizationDto)
        {
            if (await _monitorsDbSet.AnyAsync(x => x.Name == newMonitor.Name &&
                                              x.OrganizationId == userAndOrganizationDto.OrganizationId))
            {
                throw new ValidationException(ErrorCodes.DuplicatesIntolerable, "Monitor names should be unique");
            }

            var timestamp = DateTime.UtcNow;
            var monitor   = new Monitor
            {
                Created        = timestamp,
                Modified       = timestamp,
                CreatedBy      = userAndOrganizationDto.UserId,
                ModifiedBy     = userAndOrganizationDto.UserId,
                Name           = newMonitor.Name,
                OrganizationId = userAndOrganizationDto.OrganizationId
            };

            _monitorsDbSet.Add(monitor);
            await _uow.SaveChangesAsync(false);
        }
Example #22
0
        public async Task EditPostAsync(EditPostDto editPostDto)
        {
            await _postDeleteLock.WaitAsync();

            try
            {
                var post = await _postsDbSet
                           .Include(x => x.Wall)
                           .FirstOrDefaultAsync(x =>
                                                x.Id == editPostDto.Id &&
                                                x.Wall.OrganizationId == editPostDto.OrganizationId);

                if (post == null)
                {
                    throw new ValidationException(ErrorCodes.ContentDoesNotExist, "Post not found");
                }

                var isWallModerator = await _moderatorsDbSet.AnyAsync(x => x.UserId == editPostDto.UserId && x.WallId == post.WallId) || post.CreatedBy == editPostDto.UserId;

                var isAdministrator = await _permissionService.UserHasPermissionAsync(editPostDto, AdministrationPermissions.Post);

                if (!isAdministrator && !isWallModerator)
                {
                    throw new UnauthorizedException();
                }

                post.MessageBody = editPostDto.MessageBody;
                post.PictureId   = editPostDto.PictureId;
                post.LastEdit    = DateTime.UtcNow;

                await _uow.SaveChangesAsync(editPostDto.UserId);
            }
            finally
            {
                _postDeleteLock.Release();
            }
        }
Example #23
0
        public async Task <bool> insertUser(UserDto userDto)
        {
            try
            {
                var blnIsExistsUsername = await _Users.AnyAsync(r => r.username == userDto.username);

                if (blnIsExistsUsername == true)
                {
                    return(false);  //Repetetive Username
                }
                var oUser = new User
                {
                    address       = userDto.address,
                    email         = userDto.email,
                    fullName      = userDto.fullName,
                    isItemAdmin   = userDto.isItemAdmin,
                    mobile        = userDto.mobile,
                    nationalCode  = userDto.nationalCode,
                    password      = userDto.password,
                    telephone     = userDto.telephone,
                    username      = userDto.username,
                    isActive      = userDto.isActive,
                    companyId     = userDto.companyId,
                    isDataAdmin   = userDto.isDataAdmin,
                    createdUserId = userDto.userId,
                };

                foreach (var oAccessgroupDto in userDto.accessgroupsDto)
                {
                    if (oAccessgroupDto.isChecked == true)
                    {
                        var oAccessgroupUser = new AccessgroupUser();
                        oAccessgroupUser.accessgroupId = oAccessgroupDto.id;
                        oUser.accessgroupUsers.Add(oAccessgroupUser);
                    }
                }


                _Users.Add(oUser);
                await _uow.SaveChangesAsync();

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #24
0
        /// <summary>
        /// Adds a domain to the given host.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="domainName">Name of the domain.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException"></exception>
        public virtual async Task AddDomainAsync(THost host, string domainName)
        {
            Helpers.ThrowIfNull(host != null, "host");
            Helpers.ThrowIfNull(!domainName.IsNullOrWhiteSpace(), "domainName");

            ThrowIfDisposed();

            // check if domain exists
            if (await hostDomains.AnyAsync(d => d.DomainName.ToUpper() == domainName.ToUpper()))
            {
                throw new ArgumentException(string.Format("Domain '{0}' already exists.", domainName));
            }

            host.Domains.Add(new THostDomain()
            {
                DomainName = domainName
            });
        }
Example #25
0
        /// <summary>
        ///     Returns true if the user is in the named role
        /// </summary>
        /// <param name="user"></param>
        /// <param name="roleName"></param>
        /// <returns></returns>
        public virtual async Task <bool> IsInRoleAsync(TUser user, string roleName)
        {
            ThrowIfDisposed();
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (String.IsNullOrWhiteSpace(roleName))
            {
                throw new ArgumentException(IdentityResources.ValueCannotBeNullOrEmpty, "roleName");
            }
            var role = await _roleStore.DbEntitySet.SingleOrDefaultAsync(r => r.Name.ToUpper() == roleName.ToUpper());

            if (role != null)
            {
                var userId = user.Id;
                var roleId = role.Id;
                return(await _userRoles.AnyAsync(ur => ur.RoleId.Equals(roleId) && ur.UserId.Equals(userId)));
            }
            return(false);
        }
Example #26
0
        public async Task AddBadgeCategoryToKudosTypeAsync(int badgeCategoryId, int kudosTypeId, BadgeCalculationPolicyType calculationPolicy)
        {
            var alreadyExists = await _badgeCategoryKudosTypesDbSet
                                .AnyAsync(x => x.BadgeCategoryId == badgeCategoryId && x.KudosTypeId == kudosTypeId);

            if (alreadyExists)
            {
                throw new ValidationException(ErrorCodes.DuplicatesIntolerable,
                                              $"Badge category (ID {badgeCategoryId}) and kudos type (ID {kudosTypeId}) relationship already exists");
            }

            var entity = new BadgeCategoryKudosType
            {
                BadgeCategoryId       = badgeCategoryId,
                KudosTypeId           = kudosTypeId,
                CalculationPolicyType = calculationPolicy
            };

            _badgeCategoryKudosTypesDbSet.Add(entity);

            await SaveChangesAsync();
        }
Example #27
0
        public async Task CreateKudosType(NewKudosTypeDto dto)
        {
            var alreadyExists = await _kudosTypesDbSet
                                .AnyAsync(t => t.Name == dto.Name);

            if (alreadyExists)
            {
                throw new ValidationException(444, "Kudos type already exists");
            }

            var newType = new KudosType
            {
                Name        = dto.Name,
                Value       = dto.Multiplier,
                Type        = ConstBusinessLayer.KudosTypeEnum.Ordinary,
                Description = dto.Description
            };

            _kudosTypesDbSet.Add(newType);

            await _uow.SaveChangesAsync(dto.UserId);
        }
Example #28
0
        public async Task AddBadgeToUserAsync(int badgeTypeId, string employeeId, int organizationId)
        {
            var alreadyExists = await _badgeLogsDbSet
                                .AnyAsync(x => x.BadgeTypeId == badgeTypeId && x.OrganizationId == organizationId && x.EmployeeId == employeeId);

            if (alreadyExists)
            {
                throw new ValidationException(ErrorCodes.DuplicatesIntolerable,
                                              $"Badge type (ID {badgeTypeId}), employee (ID {employeeId}) and organization (ID {organizationId}) relationship already exists");
            }

            var entity = new BadgeLog
            {
                BadgeTypeId    = badgeTypeId,
                EmployeeId     = employeeId,
                OrganizationId = organizationId
            };

            _badgeLogsDbSet.Add(entity);

            await SaveChangesAsync();
        }
        /// <summary>
        /// Adds a role to the given group.
        /// </summary>
        /// <param name="group">The group.</param>
        /// <param name="role">The role.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException"></exception>
        public virtual async Task AddRoleAsync(TRoleGroup group, TRole role)
        {
            Helpers.ThrowIfNull(group != null, "group");
            Helpers.ThrowIfNull(role != null, "role");

            ThrowIfDisabled();
            ThrowIfDisposed();

            var groupId = group.Id;
            var roleId  = role.Id;

            // check if it already exists
            if (await groupRoles.AnyAsync(gr => gr.RoleGroupId.Equals(groupId) && gr.RoleId.Equals(roleId)))
            {
                throw new ArgumentException(string.Format("Group '{0}' already contains Role {1}.", group.Name, role.Name));
            }
            // global groups can only contain global roles; if they are assignable by host, then the host will be applied when user is assigned to the group
            if (group.IsGlobal && !role.IsGlobal)
            {
                throw new ArgumentException(string.Format("Global group '{0}' can only contain global roles.", group.Name));
            }
            // group can only contain roles from same host or global
            if (!group.IsGlobal && !(role.IsGlobal || role.HostId.Equals(group.HostId)))
            {
                throw new ArgumentException(string.Format("Group '{0}' can only contain roles from the same host or global roles.", group.Name));
            }


            var groupRole = new TRoleGroupRole();

            groupRole.RoleGroupId = groupId;
            groupRole.RoleId      = roleId;

            groupRoles.Add(groupRole);

            // update all users in this group to have the new role if they don't already
            RefreshAllUsresInGroup(group.Id);
        }
Example #30
0
 public async Task <bool> AnyAsync(Expression <Func <T, bool> > predicate)
 {
     return(await _dbset.AnyAsync(predicate));
 }