public long GetUsersCount(UserFilter filterData)
        {
            var mongo = MongoDb.OpenConnection();

            var query = GetUserQuery(filterData) ?? new BsonDocument();

            var collection = mongo.GetCollection<BsonDocument>(CollectionsEnum.users.ToString());
            var usersCount = collection
                .Count(query);

            return usersCount;
        }
        public void Delete(UserFilter filterData)
        {
            if (filterData == null || !filterData.HasFilter())
                throw new ArgumentException("Invalid filter data");

            var query = GetUserQuery(filterData) ?? new BsonDocument();

            var mongoDb = MongoDb.OpenConnection();

            var collection = mongoDb.GetCollection<BsonDocument>(CollectionsEnum.users.ToString());
            var result = collection.DeleteMany(query);
            if (result.DeletedCount == 0)
                throw new Exception("There aren't any users with the criteria provided");

        }
        public IList<User> GetUsers(UserFilter filterData, int take, int skip)
        {
            var mongo = MongoDb.OpenConnection();

            var query = GetUserQuery(filterData) ?? new BsonDocument();

            var collection = mongo.GetCollection<BsonDocument>(CollectionsEnum.users.ToString());
            var users = collection
                .Find(query)
                .Skip(skip)
                .Limit(take)
                .ToList()
                .Select(u => BsonSerializer.Deserialize<UserMongoMap>(u).GetUserModel())
                .ToList();

            return users;
        }
        private static FilterDefinition<BsonDocument> GetUserQuery(UserFilter filterData)
        {
            if (filterData == null)
                return null;

            //https://docs.mongodb.org/getting-started/csharp/query/

            var builder = Builders<BsonDocument>.Filter;
            FilterDefinition<BsonDocument> filter = null;

            #region ids
            if (filterData.Ids != null && filterData.Ids.Any())
            {
                var arrayIds = filterData.Ids.Select(i => new BsonObjectId(new ObjectId(i))).ToArray();
                filter = builder.Eq("_id", new BsonDocument("$in", new BsonArray(arrayIds)));
            }
            #endregion

            #region email
            if (!string.IsNullOrEmpty(filterData.Email))
            {
                filter = filter == null
                    ? builder.Eq("email", new BsonString(filterData.Email))
                    : filter & builder.Eq("email", new BsonString(filterData.Email));
            }
            #endregion

            #region status
            if (filterData.StatusList != null && filterData.StatusList.Any())
            {
                var arrayStatus = filterData.StatusList.Select(i => i.GetUserStatusEnumStringValue()).ToArray();
                filter = filter == null
                    ? builder.Eq("status", new BsonDocument("$in", new BsonArray(arrayStatus)))
                    : filter & builder.Eq("status", new BsonDocument("$in", new BsonArray(arrayStatus)));
            }
            #endregion

            return filter;
        }
        public IndexViewModel Create(HttpContext httpContext, UserFilter filter, IEnumerable <User> users, string orderBy, int skip, int take, int total)
        {
            IStringLocalizer <IndexViewModelFactory> localizer = httpContext.GetStringLocalizer <IndexViewModelFactory>();

            return(new IndexViewModel()
            {
                Grid = new GridViewModelFactory().Create(
                    httpContext,
                    new[] {
                    new FilterViewModelFactory().Create(httpContext, "Name.Contains", localizer["Name"]),
                    new FilterViewModelFactory().Create(httpContext, "Credential.Identifier.Contains", localizer["Credential identifier"])
                },
                    orderBy, skip, take, total,
                    new[] {
                    new GridColumnViewModelFactory().Create(localizer["Name"], "Name"),
                    new GridColumnViewModelFactory().Create(localizer["Credentials"]),
                    new GridColumnViewModelFactory().Create(localizer["Created"], "Created"),
                    new GridColumnViewModelFactory().CreateEmpty()
                },
                    users.Select(u => new UserViewModelFactory().Create(u)),
                    "_User"
                    )
            });
        }
        public bool Deposit(Guid userId, BankAccountType bankAccountType, Guid bankAccountId, decimal money)
        {
            var res    = false;
            var filter = new UserFilter();

            filter.Id = userId;
            var details = _UserCollection.Get(filter);

            if (details.Any())
            {
                var detail = details.FirstOrDefault();
                if (bankAccountType == BankAccountType.CheckingAccount)
                {
                    detail.CheckingAccount.AccountBalance += money;
                    res = _UserCollection.UpdateCheckingAccount(new UserFilter()
                    {
                        Id = userId
                    }, detail.CheckingAccount) >= 0;
                }
                else
                {
                    var bankDetail = detail.SavingsAccounts.FirstOrDefault(x => x.Id == bankAccountId);

                    if (bankDetail != null)
                    {
                        bankDetail.AccountBalance += money;
                        res = _UserCollection.UpdateSavingsAccount(new UserFilter()
                        {
                            Id = userId
                        }, bankDetail) >= 0;
                    }
                }
            }

            return(res);
        }
Example #7
0
 public static IQueryable <User> Filter(this IQueryable <User> queryable, UserFilter filter)
 {
     if (!string.IsNullOrEmpty(filter?.Text))
     {
         queryable = queryable.Where(e => e.UserName.Contains(filter.Text) || e.Email.Contains(filter.Text) || e.FirstName.Contains(filter.Text) || e.LastName.Contains(filter.Text));
     }
     if (!string.IsNullOrEmpty(filter?.UserName))
     {
         queryable = queryable.Where(e => e.UserName.Contains(filter.UserName));
     }
     if (!string.IsNullOrEmpty(filter?.Email))
     {
         queryable = queryable.Where(e => e.Email.Contains(filter.Email));
     }
     if (!string.IsNullOrEmpty(filter?.FirstName))
     {
         queryable = queryable.Where(e => e.FirstName.Contains(filter.FirstName));
     }
     if (!string.IsNullOrEmpty(filter?.LastName))
     {
         queryable = queryable.Where(e => e.LastName.Contains(filter.LastName));
     }
     return(queryable);
 }
Example #8
0
        public int UpdateUser(UserFilter UFilt)
        {
            int result = 0;

            try
            {
                SqlCommand sqlCommand = ProjectConnection.CreateCommand();
                sqlCommand.CommandText = UPDATE_USER_SP;
                sqlCommand.CommandType = CommandType.StoredProcedure;
                sqlCommand.Parameters.Add(new SqlParameter(USER_USERID_PARAM, SqlDbType.Int)).Value           = UFilt.User.UserID;
                sqlCommand.Parameters.Add(new SqlParameter(USER_FIRSTNAME_PARAM, SqlDbType.NVarChar)).Value   = UFilt.User.Firstname;
                sqlCommand.Parameters.Add(new SqlParameter(USER_FAMILYNAME_PARAM, SqlDbType.NVarChar)).Value  = UFilt.User.Familyname;
                sqlCommand.Parameters.Add(new SqlParameter(USER_PHONENUMBER_PARAM, SqlDbType.NVarChar)).Value = UFilt.User.Phonenumber;
                sqlCommand.Parameters.Add(new SqlParameter(USER_EMAIL_PARAM, SqlDbType.NVarChar)).Value       = UFilt.User.Email;
                sqlCommand.Parameters.Add(new SqlParameter(USER_ADDRESS_PARAM, SqlDbType.NVarChar)).Value     = UFilt.User.Address;
                sqlCommand.Parameters.Add(new SqlParameter(USER_PRIVILAGE_PARAM, SqlDbType.Int)).Value        = UFilt.User.Privilage;
                sqlCommand.Parameters.Add(new SqlParameter(USER_WEBPAGE_PARAM, SqlDbType.Xml)).Value          = UFilt.User.WebPageXML;
                sqlCommand.Parameters.Add(new SqlParameter(USER_USERNAME_PARAM, SqlDbType.NVarChar)).Value    = UFilt.User.Username;
                sqlCommand.Parameters.Add(new SqlParameter(USER_PASSWORD_PARAM, SqlDbType.NVarChar)).Value    = UFilt.User.Password;
                ProjectConnection.Open();
                result = sqlCommand.ExecuteNonQuery();
                ProjectConnection.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("USER", ex);
            }
            finally
            {
                if (ProjectConnection.State == ConnectionState.Open)
                {
                    ProjectConnection.Close();
                }
            }
            return(result);
        }
Example #9
0
        public void Get_Users_Filter(UserFilter filter, int expectedCount)
        {
            // Arrange
            var helper = new TestHelper();
            var user   = PrincipalHelper.CreateForPermission(Permissions.AdminUsers);
            var euser  = EntityHelper.CreateUser("Tester");

            euser.FirstName   = "Test";
            euser.LastName    = "McTest";
            euser.DisplayName = "ttester";
            euser.Email       = "*****@*****.**";
            euser.IsDisabled  = false;
            helper.CreatePimsContext(user, true).AddAndSaveChanges(euser);

            var service = helper.CreateService <UserService>(user);

            // Act
            var result = service.Get(filter);

            // Assert
            Assert.NotNull(result);
            Assert.IsAssignableFrom <Paged <Entity.User> >(result);
            Assert.Equal(expectedCount, result.Items.Count());
        }
Example #10
0
        public async Task <bool> ForgotPassword(UserFilter userFilter)
        {
            //Quên mật khẩu
            //Nếu thí sinh nhập đúng Identify và Email, hệ thống sẽ generate lại mật khẩu và gửi về email
            User user = await UOW.UserRepository.Get(userFilter);

            if (user == null)
            {
                throw new BadRequestException("Id không tồn tại");
            }
            if (!userFilter.Email.Equals(user.Email))
            {
                throw new BadRequestException("Email không đúng!");
            }
            user.Password = CryptographyExtentions.GeneratePassword();
            user.Salt     = null;
            await UOW.UserRepository.ChangePassword(user);

            MailSenderService mailSender     = new MailSenderService(user);
            Thread            sendMailThread = new Thread(new ThreadStart(mailSender.RecoveryPasswordMail));

            sendMailThread.Start();
            return(true);
        }
Example #11
0
        public async Task <ListResponse <UserResponse> > RunAsync(UserFilter filter, ListOptions options)
        {
            IQueryable <UserResponse> query = _context.Users
                                              .ProjectTo <UserResponse>();

            query = ApplyFilter(query, filter);
            int totalCount = await query.CountAsync();

            if (options.Sort == null)
            {
                options.Sort = "Id";
            }

            query = options.ApplySort(query);
            query = options.ApplyPaging(query);
            return(new ListResponse <UserResponse>
            {
                Items = await query.ToListAsync(),
                Page = options.Page,
                PageSize = options.PageSize ?? -1,
                Sort = options.Sort ?? "-Id",
                TotalItemsCount = totalCount
            });
        }
        public async Task <User> Get(UserFilter filter)
        {
            if (filter == null)
            {
                return(null);
            }

            IQueryable <UserDAO> users = examRegContext.User.AsNoTracking();

            users = DynamicFilter(users, filter);

            List <User> list = await users.Select(u => new User
            {
                Id               = u.Id,
                Password         = u.Password,
                Username         = u.Username,
                IsAdmin          = u.IsAdmin,
                StudentId        = u.StudentId,
                StudentGivenName = u.Student.GivenName,
                StudentLastName  = u.Student.LastName
            }).ToListAsync();

            return(list.FirstOrDefault());
        }
 private IQueryable <UserDAO> DynamicFilter(IQueryable <UserDAO> query, UserFilter filter)
 {
     if (filter == null)
     {
         return(query.Where(q => 1 == 0));
     }
     if (filter.Username != null)
     {
         query = query.Where(u => u.Username.Equals(filter.Username));
     }
     if (filter.Password != null)
     {
         query = query.Where(u => u.Password.Equals(filter.Password));
     }
     if (filter.StudentLastName != null)
     {
         query = query.Where(u => u.Student.LastName.Equals(filter.StudentLastName));
     }
     if (filter.StudentGivenName != null)
     {
         query = query.Where(u => u.Student.GivenName.Equals(filter.StudentGivenName));
     }
     return(query);
 }
Example #14
0
        public async Task <IActionResult> Stores(int page, UserFilter filter)
        {
            filter.StoreAccess     = StoreAccess.Approved;
            filter.StoreSetup      = true;
            filter.StorePlanActive = true;

            var users = await _userService.GetQuery(filter)
                        .ToPageableAsync(page, _appSettings.PageDefaultSize);

            var model = new UserListModel
            {
                Filter = filter
            };

            await _appService.PrepareModelAsync(model, users,
                                                prepareChildModel : async(userModel, user) =>
            {
                userModel.ReviewEvaluation = await _reviewService.EvaluateAsync(new ReviewFilter {
                    SellerId = user.Id, Approved = true,
                });
            });

            return(View(nameof(Stores), model));
        }
Example #15
0
 public async Task <IEnumerable <User> > GetUsersAsync([FromQuery] UserFilter filter)
 {
     return(await pipelineService.Query <UsersQueries>().With(q => q.GetUsersAsync(filter)));
 }
Example #16
0
 public async Task <IActionResult> Search([FromBody] UserFilter request)
 {
     return(Ok(await UserManager.GetUsersByFilterAsync(request)));
 }
 /// <summary>
 /// Returns a list of all existing users within the account along with the last recorded login time.
 /// </summary>
 /// <returns></returns>
 public List <User> ShowUsers(UserFilter userFilter = null)
 {
     return(ShowUsersAsync(userFilter).Result);
 }
        /// <summary>
        /// Returns a list of all existing users within the account along with the last recorded login time.
        /// </summary>
        /// <returns></returns>
        public async Task <List <User> > ShowUsersAsync(UserFilter userFilter = null)
        {
            var parameters = new ApiParameters(OperationParameters.UserManagement.ShowUsers, userFilter);

            return(await _httpClient.Get <List <User> >("showUsers", parameters));
        }
Example #19
0
 public User GetUser(UserFilter filter)
 {
     return(Session.Get <UserDto>(filter.Id));
 }
Example #20
0
        private async Task ManageUser()
        {
            UserFilter userFilter = null;
            JObject    user       = null;
            string     name       = null;

            async Task askForUser()
            {
                userFilter = ConsoleOptions.GetInput("Which user? (objectId || signInName || displayName)", mutate: r =>
                {
                    var id = r.ParseGuid();

                    if (id.HasValue)
                    {
                        return(new UserFilter(id.Value, null));
                    }

                    try
                    {
                        var mailAddress = new MailAddress(r);

                        return(new UserFilter(null, $"$filter=signInNames / any(x: x / value eq '{r}')"));
                    }
                    catch (Exception)
                    {
                        return(new UserFilter(null, $"$filter=displayName eq '{r}'"));
                    }
                });
            }

            async Task search()
            {
                if (userFilter == null)
                {
                    return;
                }

                user = await QueryUser(userFilter);

                if (user == null)
                {
                    return;
                }

                name = user["displayName"].ToString();

                if (ConsoleOptions.YesNo($"Found {name}. Print user details?"))
                {
                    Log.PrintJson(user);
                }
            }

            await askForUser();

            do
            {
                await search();

                if (user == null && !ConsoleOptions.YesNo("Search again?"))
                {
                    return;
                }
            } while (user == null);


            var options = new ConsoleOptions <Func <JObject, Task> >($"What would you like to do with {name}?", new[]
            {
                new Option <Func <JObject, Task> >("Update", j => Update(j).Then(search)),
                new Option <Func <JObject, Task> >("Print user details", async j => Log.PrintJson(j)),
                new Option <Func <JObject, Task> >("Get another user", async j => await askForUser().Then(search))
            });

            Func <JObject, Task> f = null;

            while (userFilter != null)
            {
                try
                {
                    f = options.Ask()?.Value;
                    if (f == null)
                    {
                        break;
                    }

                    await f.Invoke(user);
                }
                catch (Exception e)
                {
                    Log.Error(e.UnwrapForLog());
                }
            }
        }
Example #21
0
        public virtual Task <PaginateResult <User> > GetByFiltersPaging(UserFilter filters)
        {
            var queryBase = this._rep.GetBySimplefilters(filters);

            return(this._rep.PagingAndDefineFields(filters, queryBase));
        }
Example #22
0
 public virtual async Task <User> GetOne(UserFilter filters)
 {
     return(await this._rep.GetById(filters));
 }
		public override void GetHeatmapData(int screenId, int screenWidth, int screenHeight, UserFilter filter, System.Action<HeatmapResult> onResult) {

		}
Example #24
0
 public async Task <SearchResponse> GetUsersByFilterAsync(UserFilter userFilter)
 {
     return(await UserRepository.GetUsersByFilterAsync(userFilter));
 }
Example #25
0
 public Task <List <ApplicationUser> > FindAsync(UserFilter userFilter) => _userRepository.FindAsync(userFilter);
Example #26
0
 public override void GetHeatmapData(int screenId, int screenWidth, int screenHeight, UserFilter filter, System.Action <HeatmapResult> onResult)
 {
 }
Example #27
0
        private async Task <JObject> QueryUser(UserFilter filter)
        {
            string json = null;

            try
            {
                var url = _graph.BuildUrl($"{ApiPath}/{filter.Id?.ToString()}", filter.Filter);

                json = await _graph.SendGraphRequest(HttpMethod.Get, url, null);

                var jt = Json.TryParse(json);

                if (jt is JObject jo)
                {
                    if (!(jo["value"] is JArray ja))
                    {
                        return(jo);
                    }

                    var details = ja.Cast <JObject>()
                                  .Select(u => new
                    {
                        user    = u,
                        display = JObject.FromObject(new
                        {
                            displayName = u["displayName"],
                            signInNames = (u["signInNames"] as JArray)?.Select(s => s["value"].ToString())
                        }).ToString(Formatting.Indented)
                    });

                    if (!details.Any())
                    {
                        Log.Error("No users found");
                        return(null);
                    }

                    return(new ConsoleOptions <JObject>("Multiple users found", details.Select(u => new Option <JObject>(u.display, u.user))).Ask()?.Value);
                }

                if (jt != null)
                {
                    Log.Error($"Invalid response {jt.ToString(Formatting.Indented)}");
                }
                else
                {
                    Log.Error($"Invalid response {json}");
                }

                return(null);
            }
            catch (Exception e)
            {
                Log.Error(
                    $@"Failed to retrieve user.
Response:
{json ?? "null"}

Exception:
{e.UnwrapForLog()}");

                return(null);
            }
        }
Example #28
0
 public UserListRequestBuilder(UserFilter filter, FilterPager pager)
     : this()
 {
     this.Filter = filter;
     this.Pager  = pager;
 }
        public JsonResult Filter(UserFilter filter)
        {
            var response = _userService.Filter(filter);

            return(new JsonFactory().Success(response.Users, response.TotalRecords));
        }
        public void GetUsers_Returns_List_Of_Users()
        {
            // Arrange
            var foundUser = new User { Email = "*****@*****.**" };
            var userList = new List<User> { foundUser, foundUser }.AsQueryable();
            const int currentPage = 1;
            const int numPerPage = 10;
            int total = 0;
            var filter = new UserFilter();
            var userRepository = new Mock<IUserRepository>();
            userRepository.Setup(u => u.Search(filter, currentPage, numPerPage, ref total)).Returns(userList);

            var userService = ServiceMiniMart.CreateUserService(userRepository);

            // Act
            var returnedList = userService.GetUsers(filter, currentPage, numPerPage);

            // Assert
            Assert.AreEqual(userList.Count(), returnedList.Items.Count);
        }
Example #31
0
        public virtual async Task <IEnumerable <User> > GetByFilters(UserFilter filters)
        {
            var queryBase = this._rep.GetBySimplefilters(filters);

            return(await this._rep.ToListAsync(queryBase));
        }
Example #32
0
        public async Task <PagedResult <UserDto> > GetUsersAsync(UserFilter filter = null)
        {
            if (filter == null)
            {
                filter = new UserFilter();
            }

            if (filter?.PageSize < 0)
            {
                filter.PageSize = null;
            }
            if (filter?.PageNumber < 0)
            {
                filter.PageNumber = null;
            }

            IQueryable <User> users;

            if (!await _roleManager.RoleExistsAsync(filter.RoleName))
            {
                users = _userManager.Users;
            }
            else
            {
                var userList = await _userManager.GetUsersInRoleAsync(filter.RoleName);

                users = userList.AsQueryable();
            }

            switch (filter.userOrder)
            {
            case UserFilter.UserOrder.IdAscending:
                users = users.OrderBy(u => u.Id);
                break;

            case UserFilter.UserOrder.IdDescending:
                users = users.OrderByDescending(u => u.Id);
                break;

            case UserFilter.UserOrder.NameAscending:
                users = users.OrderBy(u => u.Name);
                break;

            case UserFilter.UserOrder.NameDescending:
                users = users.OrderByDescending(u => u.Name);
                break;

            case UserFilter.UserOrder.EmailAscending:
                users = users.OrderBy(u => u.Email);
                break;

            case UserFilter.UserOrder.EmailDescending:
                users = users.OrderByDescending(u => u.Email);
                break;

            default:
                break;
            }

            int?Total = null;

            if (((filter?.PageSize) ?? 0) != 0)
            {
                filter.PageNumber = filter.PageNumber ?? 0;
                Total             = users.Count();
                users             = users.Skip(filter.PageNumber.Value * filter.PageSize.Value).Take(filter.PageSize.Value);
            }

            var results = users.Select(UserDtoSelector).ToList();

            return(new PagedResult <UserDto>
            {
                Total = Total,
                PageNumber = filter?.PageNumber,
                PageSize = filter?.PageSize,
                Results = results
            });
        }
Example #33
0
        public async Task <IHttpActionResult> GetUsers(UserFilter filter)
        {
            var users = await userManager.GetUsersAsync(filter);

            return(Ok(users));
        }
Example #34
0
 public static UserExportToCsvRequestBuilder ExportToCsv(UserFilter filter = null, int metadataProfileId = Int32.MinValue, IList <CsvAdditionalFieldInfo> additionalFields = null)
 {
     return(new UserExportToCsvRequestBuilder(filter, metadataProfileId, additionalFields));
 }
        static Expression <Func <Entities.Entities.User, bool> > PredicateBuilderFunction(UserFilter filter)
        {
            var predicate = PredicateBuilder.New <Entities.Entities.User>(true);

            if (!string.IsNullOrWhiteSpace(filter.NameAr))
            {
                predicate = predicate.And(b => b.NameAr.ToLower().Contains(filter.NameAr.ToLower()));
            }
            if (!string.IsNullOrWhiteSpace(filter.NameEn))
            {
                predicate = predicate.And(b => b.NameEn.ToLower().Contains(filter.NameEn.ToLower()));
            }
            return(predicate);
        }
Example #36
0
 public static UserListRequestBuilder List(UserFilter filter = null, FilterPager pager = null)
 {
     return(new UserListRequestBuilder(filter, pager));
 }