コード例 #1
0
        public List <SearchUserModel> GetUserList(SqlCommand command)
        {
            List <SearchUserModel> UserList = new List <SearchUserModel>();

            using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
                using (command)
                {
                    command.Connection = conn;

                    conn.Open();

                    using (var DB = command.ExecuteReader())
                    {
                        SearchUserModel User = null;
                        while (DB.Read())
                        {
                            User = new SearchUserModel
                            {
                                UserID     = (long)DB["UserID"],
                                Username   = (string)DB["Username"],
                                NrOfVideos = (int)DB["NrOfVideos"]
                            };
                            UserList.Add(User);
                        }
                    }
                    conn.Close();
                }
            return(UserList);
        }
コード例 #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SearchUser su = new SearchUser(CurrentAdmin, CurrentLanguage.Code);

            model    = su.Model;
            callback = RequestTool.RequestString("callback");
        }
コード例 #3
0
ファイル: UserController.cs プロジェクト: ywscr/Vulcan
        public async Task <IActionResult> QueryUserList(SearchUserModel search)
        {
            if (search.orgCode == rootId)
            {
                search.orgCode = "";
            }

            if (string.IsNullOrEmpty(search.orgCode)) // 权限控制
            {
                string userId = base.UserId;
                var    user   = await base.GetSignedUser();

                string viewCode = user.ViewRootCode;
                bool   admin    = await this._contextService.IsInRole(userId, Constans.SUPPER_ADMIN_ROLE);

                if (!admin)
                {
                    if (!string.IsNullOrEmpty(viewCode))
                    {
                        search.orgCode = viewCode;
                    }
                }
            }

            PageView view = new PageView(search.page, search.rp);
            PagedList <IUserInfo> list = await this._service.QueryUserList(search.orgCode, search.qText, view);

            var ret = JsonQTable.ConvertFromPagedList(list.DataList, list.PageIndex, list.Total, search.colkey, search.colsArray);

            return(Json(ret));
        }
コード例 #4
0
        public async Task <Result <LightUserModel> > Search(SearchUserModel model)
        {
            var result = await _repository.FirstOrDefaultAsNoTrackingAsync <User>(
                u => u.Email == model.Keyword || u.Mobile == model.Keyword
                , u => u.Role);

            if (!result.Success || result.Data == null)
            {
                return(Result <LightUserModel> .Failed(Error.WithData(1000, new[] { "User not found" })));
            }

            var user = result.Data;

            return(Result <LightUserModel> .Successful(new LightUserModel
            {
                Id = user.Id,
                Firstname = user.Firstname,
                Lastname = user.Lastname,
                Username = user.Username,
                Gender = user.Gender,
                Role = new RoleModel
                {
                    Id = user.Role.Id,
                    Name = user.Role.Name,
                    Feature = new List <FeatureModel>()
                }
            }));
        }
コード例 #5
0
        private SearchUserModel MapSearchUserModels(StickMan_Users dbUser, StickMan_FriendRequest friendRequest, int currentUserId)
        {
            var userModel = new SearchUserModel
            {
                ImagePath = dbUser.ImagePath,
                UserName  = dbUser.UserName,
                UserId    = dbUser.UserID,
                FullName  = dbUser.FullName,
                DOB       = dbUser.DOB,
                MobileNo  = dbUser.MobileNo,
                Sex       = dbUser.Sex,
                Email     = dbUser.EmailID,
                DeviceId  = dbUser.DeviceId,
            };

            if (friendRequest == null)
            {
                userModel.FriendStatus = FriendStatus.Stranger;
            }
            else
            {
                userModel.FriendRequestId = friendRequest.FriendRequestID;
                if (friendRequest.FriendRequestStatus == 0)
                {
                    userModel.FriendStatus =
                        friendRequest.UserID == currentUserId ? FriendStatus.InviteSent : FriendStatus.InviteReceived;
                }
                else
                {
                    userModel.FriendStatus = StatusMapping[friendRequest.FriendRequestStatus];
                }
            }

            return(userModel);
        }
コード例 #6
0
        public ActionResult List(DataSourceRequest command, SearchUserModel model)
        {
            var users = _userService.GetAllUsersAsync(searchKeyword: model.SearchKeyword, pageIndex: command.Page - 1, pageSize: command.PageSize);

            var gridModel = new DataSourceResult
            {
                Data = users.Select(u => new User_Model
                {
                    Id          = u.Id,
                    Email       = u.Email,
                    FirstName   = u.FirstName,
                    LastName    = u.LastName,
                    PhoneNumber = u.PhoneNumber,
                    UserName    = u.Username,
                    Active      = u.Active,
                    //Role = GetUserRoleForViewModel(u.UserRoles),
                    Roles = u.UserRoles.Select(ur => new UserRoleViewModel()
                    {
                        Id = ur.Id, Name = ur.Name
                    }).ToList(),
                    ResetPassword = "",
                    Departments   = u.Departments.Select(ud => new DepartmentViewModel()
                    {
                        Id = ud.Id, Name = ud.Name
                    }).ToList()
                }),
                Total = users.TotalCount
            };

            // Return the result as JSON
            return(Json(gridModel));
        }
コード例 #7
0
        public async Task <Result> ForgotPassword(SearchUserModel model)
        {
            var result = (await _membershipServiceApi.MembershipUserApiService.Search(model));

            if (result.Data == null)
            {
                return(Result.Failed(Error.WithData(1000, new[] { "user not found" })));
            }
            var user = result.Data;

            var password = $"{Guid.NewGuid()}".Substring(0, 5);

            await _membershipServiceApi.AuthAuthApiService.ChangePassword(new ChangePasswordModel
            {
                NewPassword = password, UserId = user.Id.Value,
            });

            var profile = await _membershipServiceApi.AuthAuthApiService.Profile(
                new ERP.MembershipService.ApiClient.Models.BaseModel
            {
                Id = user.Id
            });

            _coreSmtpClient.SendChangePassword(profile.Data.Email, user.Firstname + " " + user.Lastname, user.Username,
                                               password);

            return(Result.Successful());
        }
コード例 #8
0
ファイル: Default.aspx.cs プロジェクト: parkpook/MEYER
        protected void GetAllUserByCriteria(string search)
        {
            string URL         = Constants.Constants.GET_ALL_USER_URL;
            string QueryString = "users?q=" + search + "%20in:login";

            URL = URL.Replace("[query]", QueryString);

            HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;

            request.UserAgent = "GitHubAgent";
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader     = new StreamReader(response.GetResponseStream());
                string       JsonString = reader.ReadToEnd();

                SearchUserModel userResult = JsonConvert.DeserializeObject <SearchUserModel>(JsonString);
                //dt = jDt.JsonStringToDataTable(JsonString);

                if (userResult != null && userResult.items.Count > 0)
                {
                    lvResult.DataSource = userResult.items;
                    lvResult.DataBind();
                    dpListView.Visible = true;
                    HttpContext.Current.Session["UserList_" + hdfGUID.Value] = userResult.items;
                }
                else
                {
                    txtSearch.Text      = string.Empty;
                    lvResult.DataSource = null;
                    lvResult.DataBind();
                    dpListView.Visible = false;
                    HttpContext.Current.Session["UserList_" + hdfGUID.Value] = null;
                }
            }
        }
コード例 #9
0
        public ActionResult DeletedUser(int?page, String condition)
        {
            int             pageSize  = Request["rows"] == null ? 10 : int.Parse(Request["rows"]);
            int             pageIndex = page == null ? 1 : page.Value;
            int             total     = 0;
            SearchUserModel su        = null;

            if (condition != null)
            {
                su = JsonConvert.DeserializeObject <SearchUserModel>(condition);
            }


            var data = UserInfoService.LoadPageEntities(pageSize, pageIndex, out total, u => u.IsDeleted == true, true, u => u.Id)
                       .Select(u => new { u.Id, u.UID, u.Name, u.Email, u.Gender, u.HiredTime, u.IsEnabled, roleName = u.Role.Name, positionName = u.Position.Name, groupName = u.Group.Name });

            if (su != null)
            {
                if (su.startTime != null)
                {
                    data = data.Where(u => u.HiredTime >= su.startTime.Value);
                }
                if (su.endTime != null)
                {
                    data = data.Where(u => u.HiredTime <= su.endTime.Value);
                }
                if (su.searchInfo != null)
                {
                    data = data.Where(u => u.Name.Contains(su.searchInfo) || u.Email.Contains(su.searchInfo));
                }
            }
            var result = new { total = Math.Ceiling(Convert.ToDecimal(total / pageSize)), rows = data };

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
コード例 #10
0
        public ActionResult <List <User> > Search(SearchUserModel search)
        {
            var matchingUsers = _usersService.Get();

            if (!string.IsNullOrEmpty(search.name))
            {
                matchingUsers = matchingUsers.Where(k => k.name.Contains(search.name)).ToList();
            }

            if (!string.IsNullOrEmpty(search.username))
            {
                matchingUsers = matchingUsers.Where(k => k.username.Contains(search.username)).ToList();
            }

            if (!string.IsNullOrEmpty(search.companyName))
            {
                matchingUsers = matchingUsers.Where(k => k.company != null && k.company.name.Contains(search.companyName)).ToList();
            }

            if (!string.IsNullOrEmpty(search.addressZipcode))
            {
                matchingUsers = matchingUsers.Where(k => k.address != null && k.address.zipcode.Contains(search.addressZipcode)).ToList();
            }

            return(matchingUsers);
        }
コード例 #11
0
        public ApiPagingListResponse <UserModel> SearchUsers(SearchUserModel model, int pageIndex = 0, int pageSize = 25)
        {
            //查询满足条件的用户
            var query = this.UserService.SearchUsers(model, pageIndex, pageSize);

            //查询结果
            var result = new PaginationModel <UserModel>();

            result.Result = query.Result;

            //分页
            result.Page = new Page()
            {
                PageIndex  = query.PageIndex,
                PageSize   = query.PageSize,
                TotalPages = query.TotalPages,
                TotalCount = query.TotalCount
            };

            return(new ApiPagingListResponse <UserModel>
            {
                Result = query.Result,
                Page = result.Page
            });
        }
コード例 #12
0
 public SearchViewModel()
 {
     SearchTracks    = new SearchTrackModel();
     FanburstTracks  = new FanburstSearchModel();
     SearchPlaylists = new SearchPlaylistModel();
     SearchUsers     = new SearchUserModel();
     YouTubeTracks   = new YouTubeSearchModel();
 }
コード例 #13
0
ファイル: UserController.cs プロジェクト: war-man/YuebonCore
        public async Task <IActionResult> FindWithPagerSearchAsync(SearchUserModel search)
        {
            CommonResult <PageResult <UserOutputDto> > result = new CommonResult <PageResult <UserOutputDto> >();

            result.ResData = await iService.FindWithPagerSearchAsync(search);

            result.ErrCode = ErrCode.successCode;
            return(ToJsonContent(result));
        }
コード例 #14
0
        //[EnableCors("ori, ori2", "headers,...", "GET")]
        public IEnumerable <UserViewModel> SearchUsers(SearchUserModel search)
        {
            // Mapp to backend model
            IEnumerable <UserView>      users  = projectRepository.SearchUsers(search.Text);
            IEnumerable <UserViewModel> models = null;

            if (users != null)
            {
                models = ApplicationMapper.MapUserViewList(users);
            }
            return(models);
        }
コード例 #15
0
ファイル: IssueController.cs プロジェクト: sasha007k/MyKanban
        public async Task <IActionResult> NewIssue(int projectId)
        {
            IssueAndSearchModel issueAndSearchModel = new IssueAndSearchModel();
            SearchUserModel     user = new SearchUserModel
            {
                Users = await this.issueservice.GetUsersForTask(projectId),
            };

            issueAndSearchModel.SearchUserModel = user;
            issueAndSearchModel.ProjectId       = projectId;
            return(this.View(issueAndSearchModel));
        }
コード例 #16
0
        public async Task <IActionResult> New()
        {
            ProjectAndSearchModel projectAndSearchModel = new ProjectAndSearchModel();
            var             currentUserName             = this.User.Identity.Name;
            SearchUserModel user = new SearchUserModel
            {
                Users = await this.projectservice.GetUsers(currentUserName),
            };

            projectAndSearchModel.SearchUserModel = user;
            return(this.View(projectAndSearchModel));
        }
コード例 #17
0
        public ServiceResponse GetUserList(SearchUserModel searchParams, int pageSize = 10, int pageIndex = 1, string sortIndex = "ModifiedDate", string sortDirection = "DESC")
        {
            ServiceResponse response = new ServiceResponse();

            List <SearchValueData> searchData = new List <SearchValueData> {
                new SearchValueData {
                    Name = "searchText", Value = searchParams.SearchText
                }
            };
            var userList = GetEntityPageList <UserListModel>(StoredProcedures.GetUserList, searchData, pageSize, pageIndex, sortIndex, sortDirection);

            response      = Common.GenerateResponse(Resource.Success, true);
            response.Data = new List <UserListModel>();
            return(response);
        }
コード例 #18
0
        public async Task <Result <LightUserModel> > Search(SearchUserModel model)
        {
            var result = await _membershipServiceApi.MembershipUserApiService.Search(model);

            if (result.Success && result.Data != null)
            {
                var userId = new Guid(User.Claims.FirstOrDefault(c => c.Type == "Id").Value);

                if (result.Data.Id == userId)
                {
                    return(Result <LightUserModel> .Failed(Error.WithData(1000, new[] { "user not found" })));
                }
            }

            return(result);
        }
コード例 #19
0
        /// <summary>
        /// Searches for a user and returns a partial view of
        /// potential matches
        /// </summary>
        /// <param name="username">The search string</param>
        /// <param name="groupId">The group id used to filter the search results</param>
        /// <returns></returns>
        public ActionResult SearchUser(string username, int groupId)
        {
            var        members   = groupRepository.GetMembersByGroupId(groupId);
            List <int> memberIds = new List <int>();

            foreach (var member in members)
            {
                memberIds.Add(member.Id);
            }
            var matches = userRepository.SearchUserInvite(username, memberIds);
            var model   = new SearchUserModel
            {
                Users   = matches,
                GroupId = groupId,
                UserId  = Int32.Parse(Session["CurrentUserId"].ToString())
            };

            return(PartialView(model));
        }
コード例 #20
0
        public async Task <PaginatedResult <User> > SearchAsync(SearchUserModel rq)
        {
            // filter
            var queryObject = QueryObject <User> .Empty;

            if (!string.IsNullOrWhiteSpace(rq.Keyword))
            {
                var keyword = rq.Keyword;
                queryObject.And(new UserQueryObjects.ContainsKeyword(keyword));
            }

            // filter lockout status
            switch (rq.IsLockout)
            {
            case UserLockStatusFilters.Lock:
                queryObject.And(new UserQueryObjects.IsLockout(rq.IsLockout));
                break;

            case UserLockStatusFilters.Unlock:
                queryObject.And(new UserQueryObjects.IsUnLockout(rq.IsLockout));
                break;

            default:
                break;
            }

            // orderby
            if (!rq.Sort.Any())
            {
                rq.Sort.Add(new SortItem {
                    FieldName = nameof(User.IdentityKey)
                });
            }

            rq.Sort.ForEach(x => queryObject.AddOrderBy(x.FieldName, x.IsDescending));


            // execute
            var result = await _genericRepo.SearchAsync(queryObject, rq.Pagination);

            return(result);
        }
コード例 #21
0
        public SearchUserModel ConvertSeachUserInfoFromDataTableToList(DataTable dt, int rowNo)
        {
            SearchUserModel userGidHub = new SearchUserModel();

            //userGidHub.items.Id = Convert.ToInt32(dt.Rows[rowNo]["Id"]);
            //userGidHub.UserLogin = dt.Rows[rowNo]["Login"].ToString();
            //userGidHub.avatar_url = dt.Rows[rowNo]["avatar_url"].ToString();
            //userGidHub.url = dt.Rows[rowNo]["url"].ToString();
            //userGidHub.html_url = dt.Rows[rowNo]["html_url"].ToString();
            //userGidHub.following_url = dt.Rows[rowNo]["following_url"].ToString();
            //userGidHub.subscriptions_url = dt.Rows[rowNo]["subscriptions_url"].ToString();
            //userGidHub.organizations_url = dt.Rows[rowNo]["organizations_url"].ToString();
            //userGidHub.repos_url = dt.Rows[rowNo]["repos_url"].ToString();
            //userGidHub.events_url = dt.Rows[rowNo]["events_url"].ToString();
            //userGidHub.received_events_url = dt.Rows[rowNo]["received_events_url"].ToString();
            //userGidHub.type = dt.Rows[rowNo]["type"].ToString();
            //userGidHub.site_admin = dt.Rows[rowNo]["site_admin"].ToString();

            return(userGidHub);
        }
コード例 #22
0
        public async Task <DataResponse <SearchUserResult> > AllCompanyUser(SearchUserModel request)
        {
            var enitityportalApi = await _ioTConnectAPIDiscovery.GetPortalUrl(_envCode, _solutionKey, IoTConnectBaseURLType.UserBaseUrl);

            string enitityAccessTokenUrl = string.Concat(enitityportalApi, UserApi.CompanyUser);
            string enitityFormattedUrl   = String.Format(enitityAccessTokenUrl, Constants.userVersion);

            var result = await enitityFormattedUrl.WithHeaders(new { Content_type = Constants.contentType, Authorization = Constants.bearerTokenType + _token })
                         .SetQueryParams(new
            {
                pageSize   = request.PageSize,
                pageNumber = request.PageNo,
                searchtext = request.SearchText,
                sortBy     = request.SortBy
            }).GetJsonAsync <SearchUserResult>();

            return(new DataResponse <SearchUserResult>(null)
            {
                data = result,
                status = true
            });
        }
コード例 #23
0
 public JsonResult GetUserList(SearchUserModel searchParams, int pageSize = 10, int pageIndex = 1, string sortIndex = "ModifiedDate", string sortDirection = "DESC")
 {
     _userDataProvider = new UserDataProvider();
     return(Json(_userDataProvider.GetUserList(searchParams, pageSize, pageIndex, sortIndex, sortDirection)));
 }
コード例 #24
0
ファイル: UserController.cs プロジェクト: Danissimo13/Faces
        public async Task <IActionResult> Get(int?id, [FromQuery] SearchUserModel searchOptions)
        {
            logger.LogInformation("Get action.");
            var userRepository = storage.GetRepository <IUserRepository>();

            try
            {
                logger.LogInformation("Get user");
                User user = await userRepository.GetAsync((options) =>
                {
                    options.SearchType           = UserSearchTypes.ById;
                    options.UserId               = id.HasValue ? id.Value : int.Parse(User.FindFirst("Id").Value);
                    options.WithRole             = searchOptions.WithRole;
                    options.WithRequests         = searchOptions.WithRequests;
                    options.WithRequestResponses = searchOptions.WithRequestResponses;
                    options.WithRequestImages    = searchOptions.WithRequestImages;
                    options.WithResponseImages   = searchOptions.WithResponseImages;
                    options.FromRequest          = searchOptions.FromRequest;
                    options.RequestsCount        = searchOptions.RequestsCount;
                    options.WithPassword         = false;
                });

                var responseModel = new
                {
                    UserId   = user.UserId,
                    Nickname = user.Nickname,
                    Email    = user.Email,
                    Requests = new ArrayList(),
                    Role     = user.Role?.Name
                };

                foreach (Request request in user.Requests)
                {
                    var requestToModel = new
                    {
                        RequestId   = request.RequestId,
                        RequestType = request.Discriminator,
                        Images      = request.Images?.Select(i => new
                        {
                            ImageSrc = Path.Combine(fileService.LocalRequestImagesPath, i.ImageName)
                        }),
                        Response = new
                        {
                            ResponseId   = request.Response?.ResponseId,
                            ResponseType = request.Response?.Discriminator,
                            Images       = request.Response?.Images?.Select(i => new
                            {
                                ImageSrc = Path.Combine(fileService.LocalResponseImagesPath, i.ImageName)
                            })
                        }
                    };

                    responseModel.Requests.Add(requestToModel);
                }

                logger.LogInformation("Return reposnse.");
                return(Ok(responseModel));
            }
            catch (UserNotFoundException ex)
            {
                logger.LogInformation($"Error: {ex.Message}");
                ModelState.AddModelError("Id", ex.Message);
                return(NotFound(ModelState));
            }
        }
コード例 #25
0
 public async Task <Result <LightUserModel> > Search(SearchUserModel model)
 => await _userBiz.Search(model);
コード例 #26
0
        /// <summary>
        /// Search User.
        /// </summary>
        /// <param name="request">Search filter</param>
        /// <param name="roleGuid">(Optional)User role guid. Required for search by role. Default empty.</param>
        /// <param name="entityGuid">(Optional)Entity guid. Required for search by entity. Default empty.</param>
        /// <returns></returns>
        public async Task <DataResponse <SearchUserResult> > Search(SearchUserModel request, string roleGuid = "", string entityGuid = "")
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(entityGuid))
                {
                    var entityResult = await AllUserEntity(entityGuid);

                    SearchUserResult roleResult = null;
                    if (!string.IsNullOrWhiteSpace(roleGuid))
                    {
                        roleResult = await AllUserRole(roleGuid);
                    }

                    if (roleResult != null)
                    {
                        entityResult.data.AddRange(roleResult.data);
                        entityResult.data         = entityResult.data.GroupBy(x => x.UserId).Select(y => y.First()).ToList();
                        entityResult.invokingUser = roleResult.invokingUser;
                        return(new DataResponse <SearchUserResult>(null)
                        {
                            data = entityResult,
                            status = true
                        });
                    }
                    else
                    {
                        return(new DataResponse <SearchUserResult>(null)
                        {
                            data = entityResult,
                            status = true
                        });
                    }
                }

                else if (!string.IsNullOrWhiteSpace(roleGuid))
                {
                    var result = await AllUserRole(roleGuid);

                    return(new DataResponse <SearchUserResult>(null)
                    {
                        data = result,
                        status = true
                    });
                }

                else
                {
                    var portalApi = await _ioTConnectAPIDiscovery.GetPortalUrl(_envCode, _solutionKey, IoTConnectBaseURLType.UserBaseUrl);

                    string accessTokenUrl = string.Concat(portalApi, UserApi.Search);
                    string formattedUrl   = String.Format(accessTokenUrl, Constants.userVersion);
                    var    result         = await formattedUrl.WithHeaders(new { Content_type = Constants.contentType, Authorization = Constants.bearerTokenType + _token })
                                            .GetJsonAsync <SearchUserResult>();

                    return(new DataResponse <SearchUserResult>(null)
                    {
                        data = result,
                        status = true
                    });
                }
            }
            catch (IoTConnectException ex)
            {
                List <ErrorItemModel> errorItemModels = new List <ErrorItemModel>();
                errorItemModels.AddRange(ex.error);
                return(new DataResponse <SearchUserResult>(null)
                {
                    errorMessages = errorItemModels,
                    message = ex.message,
                    status = false
                });
            }
            catch (Exception ex)
            {
                await _ioTConnectAPIDiscovery.LoggedException(_envCode, ex, "User", "Search()");

                throw ex;
            }
        }
コード例 #27
0
        /// <summary>
        /// 查询用户(员工)
        /// </summary>
        /// <param name="model">查询条件</param>
        /// <returns>满足条件的用户</returns>
        public List <UserModel> GetUserList(SearchUserModel model = null)
        {
            using (var dbContext = new MissionskyOAEntities())
            {
                var query = dbContext.Users.AsEnumerable();

                //关键字查询
                if (model != null && !string.IsNullOrEmpty(model.Keyword))
                {
                    query =
                        query.Where(
                            it => it.ChineseName != null && it.ChineseName.ToLower().Contains(model.Keyword.ToLower())
                            ||
                            (it.EnglishName != null && it.EnglishName.ToLower().Contains(model.Keyword.ToLower())));
                }

                //项目查询
                if (model != null && model.ProjectId.HasValue && model.ProjectId.Value > 0)
                {
                    query = query.Where(it => it.ProjectId.HasValue && it.ProjectId.Value == model.ProjectId.Value);
                }

                //邮箱查询
                if (model != null && !string.IsNullOrEmpty(model.Email))
                {
                    query = query.Where(it => it.Email != null && it.Email.ToLower().Contains(model.Email.ToLower()));
                }

                //电话查询
                if (model != null && !string.IsNullOrEmpty(model.Phone))
                {
                    query = query.Where(it => it.Phone != null && it.Phone.ToLower().Contains(model.Phone.ToLower()));
                }

                //QQID
                if (model != null && !string.IsNullOrEmpty(model.QQID))
                {
                    query = query.Where(it => it.QQID != null && it.QQID.ToLower().Contains(model.QQID.ToLower()));
                }

                //账号状态,在职状态
                if (model != null)
                {
                    query =
                        query.Where(
                            it => (!it.Status.HasValue && model.Status == AccountStatus.Normal) || //字段Status为空,默认为Normal状态
                            (it.Status.HasValue && it.Status.Value == (int)model.Status));
                }

                List <UserModel> result = new List <UserModel>();
                query.ToList().ForEach(entity =>
                {
                    var user     = entity.ToModel();
                    var userRole = dbContext.UserRoles.FirstOrDefault(it => it.UserId == entity.Id) ?? new UserRole();

                    user.Role     = userRole.UserId; //用户角色
                    user.Password = null;            //清除Password
                    result.Add(user);
                });

                return(result);
            }
        }
コード例 #28
0
        /// <summary>
        /// 分页查询用户(员工)
        /// </summary>
        /// <param name="model">查询条件</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <returns>满足条件的用户</returns>
        public IPagedList <UserModel> SearchUsers(SearchUserModel model, int pageIndex, int pageSize)
        {
            using (var dbContext = new MissionskyOAEntities())
            {
                var query = dbContext.Users.Where(it => it.Available);

                //关键字查询
                if (model != null && !string.IsNullOrEmpty(model.Keyword))
                {
                    query =
                        query.Where(
                            it => it.ChineseName != null && it.ChineseName.ToLower().Contains(model.Keyword.ToLower())
                            ||
                            (it.EnglishName != null && it.EnglishName.ToLower().Contains(model.Keyword.ToLower())));
                }

                //项目查询
                if (model != null && model.ProjectId.HasValue && model.ProjectId.Value > 0)
                {
                    query = query.Where(it => it.ProjectId.HasValue && it.ProjectId.Value == model.ProjectId.Value);
                }

                //员工编号
                if (model != null && !string.IsNullOrEmpty(model.No))
                {
                    query = query.Where(it => it.No != null && it.No.ToLower().Contains(model.No.ToLower()));
                }

                //邮箱查询
                if (model != null && !string.IsNullOrEmpty(model.Email))
                {
                    query = query.Where(it => it.Email != null && it.Email.ToLower().Contains(model.Email.ToLower()));
                }

                //电话查询
                if (model != null && !string.IsNullOrEmpty(model.Phone))
                {
                    query = query.Where(it => it.Phone != null && it.Phone.ToLower().Contains(model.Phone.ToLower()));
                }

                //QQID
                if (model != null && !string.IsNullOrEmpty(model.QQID))
                {
                    query = query.Where(it => it.QQID != null && it.QQID.ToLower().Contains(model.QQID.ToLower()));
                }

                //账号状态
                if (model != null)
                {
                    query =
                        query.Where(
                            it =>
                            (model.Status == AccountStatus.Normal &&
                             (!it.Status.HasValue || it.Status == 0 || it.Status == 2)) ||
                            (it.Status.HasValue && it.Status.Value == (int)model.Status));
                }

                //今天工作状态
                if (model != null)
                {
                    query =
                        query.Where(
                            it =>
                            model.TodayStatus == UserTodayStatus.None ||
                            (model.TodayStatus != UserTodayStatus.None && it.TodayStatus == (int)model.TodayStatus));
                }

                List <UserModel> result = new List <UserModel>();
                query.ToList().ForEach(it =>
                {
                    it.Password = null; //清除Password
                    result.Add(it.ToModel());
                });

                return(new PagedList <UserModel>(result, pageIndex, pageSize));
            }
        }
コード例 #29
0
ファイル: UserService.cs プロジェクト: war-man/YuebonCore
        /// <summary>
        /// 根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="search">查询的条件</param>
        /// <returns>指定对象的集合</returns>
        public async Task <PageResult <UserOutputDto> > FindWithPagerSearchAsync(SearchUserModel search)
        {
            bool order = search.Order == "asc" ? false : true;

            string where = GetDataPrivilege(false);

            if (!string.IsNullOrEmpty(search.Keywords))
            {
                where += string.Format(" and (NickName like '%{0}%' or Account like '%{0}%' or RealName  like '%{0}%' or MobilePhone like '%{0}%')", search.Keywords);
            }

            if (!string.IsNullOrEmpty(search.RoleId))
            {
                where += string.Format(" and RoleId like '%{0}%'", search.RoleId);
            }
            if (!string.IsNullOrEmpty(search.CreatorTime1))
            {
                where += " and CreatorTime >='" + search.CreatorTime1 + " 00:00:00'";
            }
            if (!string.IsNullOrEmpty(search.CreatorTime2))
            {
                where += " and CreatorTime <='" + search.CreatorTime2 + " 23:59:59'";
            }
            PagerInfo pagerInfo = new PagerInfo
            {
                CurrenetPageIndex = search.CurrenetPageIndex,
                PageSize          = search.PageSize
            };
            List <User> list = await repository.FindWithPagerAsync(where, pagerInfo, search.Sort, order);

            List <UserOutputDto> resultList = list.MapTo <UserOutputDto>();
            List <UserOutputDto> listResult = new List <UserOutputDto>();

            foreach (UserOutputDto item in resultList)
            {
                if (!string.IsNullOrEmpty(item.OrganizeId))
                {
                    item.OrganizeName = _organizeService.Get(item.OrganizeId).FullName;
                }
                if (!string.IsNullOrEmpty(item.RoleId))
                {
                    item.RoleName = _roleService.GetRoleNameStr(item.RoleId);
                }
                if (!string.IsNullOrEmpty(item.DepartmentId))
                {
                    item.DepartmentName = _organizeService.Get(item.DepartmentId).FullName;
                }
                //if (!string.IsNullOrEmpty(item.DutyId))
                //{
                //    item.DutyName = _roleService.Get(item.DutyId).FullName;
                //}
                listResult.Add(item);
            }
            PageResult <UserOutputDto> pageResult = new PageResult <UserOutputDto>
            {
                CurrentPage  = pagerInfo.CurrenetPageIndex,
                Items        = listResult,
                ItemsPerPage = pagerInfo.PageSize,
                TotalItems   = pagerInfo.RecordCount
            };

            return(pageResult);
        }