Ejemplo n.º 1
0
		public ListUsersResponse ListUsers(ListUsersRequest request)
		{
			var criteria = new UserSearchCriteria();
			criteria.UserName.SortAsc(0);

			// create the criteria, depending on whether matches should be "exact" or "like"
			if (request.ExactMatchOnly)
			{
				if (!string.IsNullOrEmpty(request.UserName))
					criteria.UserName.EqualTo(request.UserName);
				if (!string.IsNullOrEmpty(request.DisplayName))
					criteria.DisplayName.EqualTo(request.DisplayName);
			}
			else
			{
				if (!string.IsNullOrEmpty(request.UserName))
					criteria.UserName.StartsWith(request.UserName);
				if (!string.IsNullOrEmpty(request.DisplayName))
					criteria.DisplayName.Like(string.Format("%{0}%", request.DisplayName));
			}

			var assembler = new UserAssembler();
			var userSummaries = CollectionUtils.Map(
				PersistenceContext.GetBroker<IUserBroker>().Find(criteria, request.Page),
				(User user) => assembler.GetUserSummary(user));

			return new ListUsersResponse(userSummaries);
		}
Ejemplo n.º 2
0
        public static bool IsMatch(this User user, UserSearchCriteria searchCriteria)
        {
            var result = false;

            if (!string.IsNullOrEmpty(searchCriteria.FirstName))
            {
                result = user.FirstName.ToLower() == searchCriteria.FirstName.ToLower();
            }

            if (!string.IsNullOrEmpty(searchCriteria.LastName))
            {
                result = user.LastName.ToLower() == searchCriteria.LastName.ToLower();
            }

            if (searchCriteria.DateOfBirth != null)
            {
                result = user.DateOfBirth == searchCriteria.DateOfBirth;
            }

            if (!string.IsNullOrEmpty(searchCriteria.Email))
            {
                result = user.Email.ToLower() == searchCriteria.Email.ToLower();
            }

            if (!string.IsNullOrEmpty(searchCriteria.PhoneNumber))
            {
                result = user.PhoneNumber == searchCriteria.PhoneNumber;
            }

            return(result);
        }
        public UserSearchCriteria GetSearchCriteria()
        {
            var allCriteria = new UserSearchCriteria();

            allCriteria.UserSearchGroups.Add(UserSearchGroup.Others);
            switch (lpOrderBy.SelectedIndex)
            {
            case 0:
                allCriteria.SortOrder = UsersSortOrder.ByLastLoginDate;
                break;

            case 1:
                allCriteria.SortOrder = UsersSortOrder.ByTrainingDaysCount;
                break;

            case 2:
                allCriteria.SortOrder = UsersSortOrder.ByName;
                break;
            }

            if (lpGender.SelectedIndex == 0 || lpGender.SelectedIndex == 1)
            {
                allCriteria.Genders.Add(Gender.Male);
            }
            if (lpGender.SelectedIndex == 0 || lpGender.SelectedIndex == 2)
            {
                allCriteria.Genders.Add(Gender.Female);
            }
            return(allCriteria);
        }
Ejemplo n.º 4
0
        public ActionResult List(UserSearchCriteria criteria, PageRequest request)
        {
            var service = Ioc.Get <IUserService>();
            var list    = service.Search(criteria, request);

            return(Json(list, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 5
0
        private static void CreateSysAdminUser(AuthorityGroup adminGroup, SetupCommandLine cmdLine, IPersistenceContext context, TextWriter log)
        {
            try
            {
                // create the sa user, if doesn't already exist
                IUserBroker userBroker = context.GetBroker<IUserBroker>();
                UserSearchCriteria where = new UserSearchCriteria();
				where.UserName.EqualTo(cmdLine.SysAdminUserName);
                userBroker.FindOne(where);

				log.WriteLine(string.Format("User '{0}' already exists.", cmdLine.SysAdminUserName));
            }
            catch (EntityNotFoundException)
            {
                HashedSet<AuthorityGroup> groups = new HashedSet<AuthorityGroup>
                                                       {
                                                           adminGroup
                                                       };

                // create sa user using initial password, set to expire never
                User saUser = User.CreateNewUser(
					new UserInfo(cmdLine.SysAdminUserName, cmdLine.SysAdminDisplayName, null, null, null),
					Password.CreatePassword(cmdLine.SysAdminInitialPassword, null),
                    groups);
                context.Lock(saUser, DirtyState.New);
            }
        }
Ejemplo n.º 6
0
        //public SupplementCycleDefinitionDTO VoteSupplementCycleDefinition(Token token, SupplementCycleDefinitionDTO definition)
        //{
        //    var securityInfo = SecurityManager.EnsureAuthentication(token);
        //    VoteService service = new VoteService(Session, securityInfo, Configuration, PushNotificationService);
        //    return service.VoteSupplementCycleDefinition(definition);
        //}

        public PagedResult <UserSearchDTO> GetUsers(Token token, UserSearchCriteria searchCriteria, PartialRetrievingInfo pagerInfo)
        {
            var            securityInfo   = SecurityManager.EnsureAuthentication(token);
            ProfileService profileService = new ProfileService(Session, securityInfo, Configuration, SecurityManager, PushNotificationService, EMailService);

            return(profileService.GetUsers(searchCriteria, pagerInfo));
        }
Ejemplo n.º 7
0
        private static void CreateSysAdminUser(AuthorityGroup adminGroup, SetupCommandLine cmdLine, IPersistenceContext context, TextWriter log)
        {
            try
            {
                // create the sa user, if doesn't already exist
                IUserBroker userBroker = context.GetBroker <IUserBroker>();
                UserSearchCriteria where = new UserSearchCriteria();
                where.UserName.EqualTo(cmdLine.SysAdminUserName);
                userBroker.FindOne(where);

                log.WriteLine(string.Format("User '{0}' already exists.", cmdLine.SysAdminUserName));
            }
            catch (EntityNotFoundException)
            {
                HashedSet <AuthorityGroup> groups = new HashedSet <AuthorityGroup>
                {
                    adminGroup
                };

                // create sa user using initial password, set to expire never
                User saUser = User.CreateNewUser(
                    new UserInfo(cmdLine.SysAdminUserName, cmdLine.SysAdminDisplayName, null, null, null),
                    Password.CreatePassword(cmdLine.SysAdminInitialPassword, null),
                    groups);
                context.Lock(saUser, DirtyState.New);
            }
        }
Ejemplo n.º 8
0
        private PageViewModel <User> SearchAndGetPage(UserSearchCriteria criteria)
        {
            //this.db.Configuration.LazyLoadingEnabled = false;
            var page = this.db.Users.Search(criteria).GetPage(criteria);

            return(page);
        }
Ejemplo n.º 9
0
        private UserSearchCriteria GetSearchCriteria()
        {
            // BUILD THE SEARCH CRITERIA
            UserSearchCriteria criteria = new UserSearchCriteria();

            criteria.UserName  = SearchUserName.Text;
            criteria.Email     = SearchEmail.Text;
            criteria.FirstName = SearchFirstName.Text;
            criteria.LastName  = SearchLastName.Text;
            criteria.Company   = SearchCompany.Text;
            criteria.Phone     = SearchPhone.Text;
            criteria.GroupId   = AlwaysConvert.ToInt(SearchGroup.SelectedValue);

            if (ShowAssignFilter.SelectedValue == "0")
            {
                criteria.GroupId = 0;

                // UPDATE SEARCH FORM AND RESET GROUP SELECTION
                SearchGroup.SelectedIndex = 0;
            }
            else
            {
                criteria.ShowAssignedToGroup = ShowAssignFilter.SelectedValue == "1";
            }
            criteria.IncludeAnonymous = SearchIncludeAnonymous.Checked;
            return(criteria);
        }
 public IQueryable <UserAuthenticated> FindUsers(UserSearchCriteria criteria)
 {
     return
         (from u in context.oxite_Users
          where u.Status == (byte)EntityState.Normal && (u.Username.Contains(criteria.Name) || u.DisplayName.Contains(criteria.Name))
          select new UserAuthenticated(u.UserID, u.Username, u.DisplayName));
 }
        public async Task GetUserByCriteriaTest()
        {
            var searchCrit = new UserSearchCriteria
            {
                EmployeeID = "EP001",
                FirstName  = "F1",
                LastName   = "L2"
            };
            var pmUser = new PMUser
            {
                EmployeeId = "EP001",
                FirstName  = "F1",
                LastName   = "L2",
                Id         = "Usr/1"
            };
            var mockUserRepo        = new Mock <IUserRepo>();
            var mockProjectTaskRepo = new Mock <IProjectTaskRepo>();
            var mockMapper          = new Mock <IMapper>();
            var logger = createUserLogger();

            mockUserRepo.Setup(usrRepo => usrRepo.GetAllUserMatchAnyCriteria(It.IsAny <UserSearchCriteria>()))
            .Returns(Task.FromResult(new List <PMUser> {
                pmUser
            }));
            var userService = new UserService(mockUserRepo.Object, mockProjectTaskRepo.Object, logger,
                                              mockMapper.Object);
            var result = await userService.GetUserByCriteria(searchCrit);

            Assert.NotEmpty(result);
        }
        private IQueryable <User> resolveQuery(UserSearchCriteria criteria)
        {
            var query = _userRepository.GetQuery();

            if (criteria.ActiveOnly)
            {
                query = query.Where(x => x.DeactivatedAt == null);
            }
            if (criteria.IdList != null && criteria.IdList.Any())
            {
                int[] IdArray = criteria.IdList.ToArray();
                query = query.Where(x => IdArray.Contains(x.Id));
            }
            if (!String.IsNullOrWhiteSpace(criteria.Name))
            {
                query = query.Where(x => (x.FirstName + " " + x.LastName).Contains(criteria.Name) || x.Username.Contains(criteria.Name));
            }
            if (!String.IsNullOrWhiteSpace(criteria.Username))
            {
                query = query.Where(x => x.Username == criteria.Username);
            }
            if (!String.IsNullOrWhiteSpace(criteria.Email))
            {
                query = query.Where(x => x.Email == criteria.Email);
            }
            if (criteria.MemberOfRole.HasValue)
            {
                query = query.Where(x => x.RoleList.Any(y => y.TypeOfUserRole == criteria.MemberOfRole.Value));
            }
            return(query);
        }
Ejemplo n.º 13
0
 public StandardJsonResult SendWeixin(UserSearchCriteria criteria, string htmlContent, string text, string[] types)
 {
     return(base.Try(() =>
     {
         throw new KnownException("This method is not implemented for the demo");
     }));
 }
Ejemplo n.º 14
0
        public PartialViewResult List(UserSearchCriteria criteria, PageRequest request)
        {
            var service = Ioc.Get <Services.Admin.IUserService>();
            var list    = service.Search(criteria, request);

            return(AreaPartialView("user/list.cshtml", list));
        }
Ejemplo n.º 15
0
        public void TestIsOnlineAfterLogout()
        {
            var testData = CreateNewSession((ProfileDTO)profiles[1].Tag, ClientInformation);

            RunServiceMethod(delegate(InternalBodyArchitectService service)
            {
                service.Logout(testData.Token);
            });

            var criteria = UserSearchCriteria.CreateAllCriteria();

            criteria.UserName = profiles[1].UserName;

            var                   profile  = (ProfileDTO)profiles[0].Tag;
            SessionData           data     = CreateNewSession(profile, ClientInformation);
            PartialRetrievingInfo pageInfo = new PartialRetrievingInfo();

            PagedResult <UserSearchDTO> result = null;

            RunServiceMethod(delegate(InternalBodyArchitectService service)
            {
                result = service.GetUsers(data.Token, criteria, pageInfo);
            });
            Assert.IsFalse(result.Items[0].IsOnline);
        }
Ejemplo n.º 16
0
        protected void UserDs_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            UserSearchCriteria criteria = GetSearchCriteria();

            Session["ManageUserSearchCriteria"] = criteria;
            e.InputParameters["criteria"]       = criteria;
        }
Ejemplo n.º 17
0
		public ListUsersResponse ListUsers(ListUsersRequest request)
		{
			var criteria = new UserSearchCriteria();
			criteria.UserName.SortAsc(0);
			criteria.AccountType.EqualTo(UserAccountType.U); // only regular user accounts are visible through this service

			// create the criteria, depending on whether matches should be "exact" or "like"
			if (request.ExactMatchOnly)
			{
				if (!string.IsNullOrEmpty(request.UserName))
					criteria.UserName.EqualTo(request.UserName);
				if (!string.IsNullOrEmpty(request.DisplayName))
					criteria.DisplayName.EqualTo(request.DisplayName);
			}
			else
			{
				if (!string.IsNullOrEmpty(request.UserName))
					criteria.UserName.StartsWith(request.UserName);
				if (!string.IsNullOrEmpty(request.DisplayName))
					criteria.DisplayName.Like(string.Format("%{0}%", request.DisplayName));
			}

			var assembler = new UserAssembler();
			var broker = PersistenceContext.GetBroker<IUserBroker>();
			var userSummaries = CollectionUtils.Map(
				broker.Find(criteria, request.Page),
				(User user) => assembler.GetUserSummaryMinimal(user));
			var total = broker.Count(criteria);

			return new ListUsersResponse(userSummaries, (int)total);
		}
Ejemplo n.º 18
0
        public void TestSearchAccuracy1()
        {
            var criteria = new UserSearchCriteria();

            SearchResult <User> result = instance.Search(criteria);

            AssertResult(result);
        }
Ejemplo n.º 19
0
 public IEnumerable <User> FindUsers(UserSearchCriteria criteria)
 {
     return((
                from u in context.oxite_Users
                where u.Status == (byte)EntityState.Normal && (u.Username.Contains(criteria.Name) || u.DisplayName.Contains(criteria.Name))
                select new User(u.UserID, u.Username, u.DisplayName)
                ).ToArray());
 }
Ejemplo n.º 20
0
        public async Task <IActionResult> GetAll([FromQuery] UserSearchCriteria criteria, [FromQuery] Pager pager)
        {
            var users = await userRepository.GetPagedList(criteria, pager);

            var pages = users.ToPagedDTO <User, UserDTO>(_mapper);

            return(Ok(pages));
        }
Ejemplo n.º 21
0
 public static PagedResult <UserSearchDTO> GetUsers(UserSearchCriteria searchCriteria, PartialRetrievingInfo pagerInfo)
 {
     return(exceptionHandling(delegate
     {
         pagerInfo.PageSize = GetPageSize(40);
         return Instance.GetUsers(Token, searchCriteria, pagerInfo);
     }));
 }
Ejemplo n.º 22
0
        private Expression <Func <User, bool> > FilterUsers(UserSearchCriteria filterParams)
        {
            Expression <Func <User, bool> > filter = c => (string.IsNullOrEmpty(filterParams.UserName) || c.UserName.Trim().ToLower().Contains(filterParams.UserName.Trim().ToLower())) &&
                                                     (!filterParams.DepartmentId.HasValue || c.DepartmentId == filterParams.DepartmentId.Value) &&
                                                     (!filterParams.LocationId.HasValue || c.LocationId == filterParams.LocationId) &&
                                                     (!filterParams.RoleId.HasValue || c.RoleId == filterParams.RoleId);

            return(filter);
        }
Ejemplo n.º 23
0
        public IQueryResult <User> Find(UserSearchCriteria userSearchCriteria)
        {
            if (userSearchCriteria == null)
            {
                throw new ArgumentNullException("userSearchCriteria", "must not be null.");
            }

            var constraints = new QueryConstraints <User>()
                              .IncludePath(u => u.Roles)
                              .Page(userSearchCriteria.PageNumber, userSearchCriteria.PageSize)
                              .Where(c => true);

            if (userSearchCriteria.IsActive.HasValue)
            {
                constraints.AndAlso(c => c.IsActive == userSearchCriteria.IsActive.Value);
            }

            if (!string.IsNullOrEmpty(userSearchCriteria.FullName))
            {
                constraints.AndAlso(c => c.FullName.Contains(userSearchCriteria.FullName));
            }

            if (!string.IsNullOrEmpty(userSearchCriteria.Mobile))
            {
                constraints.AndAlso(c => c.Mobile.Contains(userSearchCriteria.Mobile));
            }

            if (!string.IsNullOrEmpty(userSearchCriteria.RoleName))
            {
                constraints.AndAlso(c => c.Roles.Any(r => r.Name == userSearchCriteria.RoleName));
            }

            if (!string.IsNullOrEmpty(userSearchCriteria.UserName))
            {
                constraints.AndAlso(c => c.UserName.Contains(userSearchCriteria.UserName));
            }

            if (!string.IsNullOrEmpty(userSearchCriteria.Email))
            {
                constraints.AndAlso(c => c.Email.Contains(userSearchCriteria.Email));
            }

            if (string.IsNullOrEmpty(userSearchCriteria.Sort))
            {
                constraints.SortByDescending(c => c.CreatedAt);
            }
            //else if (userSearchCriteria.SortDirection == WebGridSortOrder.Ascending)
            //    constraints.SortBy(userSearchCriteria.Sort);
            else
            {
                constraints.SortByDescending(userSearchCriteria.Sort);
            }


            return(queryRepository.Find(constraints));
        }
        public IHttpActionResult Get([FromUri] UserSearchCriteria criteria)
        {
            var user = userService.Get(criteria);

            if (user == null)
            {
                return(NotFound());
            }
            return(Ok(user));
        }
Ejemplo n.º 25
0
 /// <summary>
 /// <para>
 /// Search users in Active Directory and mapping info in database.
 /// </para>
 /// </summary>
 ///
 /// <param name="criteria">The user search criteria.</param>
 ///
 /// <returns>The search result.</returns>
 ///
 /// <exception cref="ArgumentNullException">If <paramref name="criteria"/> is null.</exception>
 /// <exception cref="ArgumentException">If the <paramref name="criteria"/> is incorrect,
 /// e.g. PageNumber is negative, or PageNumber is positive and PageSize is not positive.</exception>
 /// <exception cref="PersistenceException">If error occurred during access the persistence.
 /// </exception>
 /// <exception cref="ServiceException"> If any other error occurred. </exception>
 public SearchResult <User> Search(UserSearchCriteria criteria)
 {
     return(Logger.Process(() =>
     {
         CommonHelper.CheckSearchCriteria(criteria);
         return SearchUser(criteria, true);
     },
                           "searching users",
                           parameters: criteria));
 }
Ejemplo n.º 26
0
        public async Task <IActionResult> ProfilePicture()
        {
            var user = await userManagerExtended.GetUserAsync(this.User);

            var userSearchCriteria = new UserSearchCriteria {
                Id = user.Id
            };
            var viewModel = profilePictureManager.GetViewModel(searchCriteria: userSearchCriteria);

            return(PartialView(viewModel));
        }
Ejemplo n.º 27
0
        private UserSearchCriteria DeserializeFilter()
        {
            UserSearchCriteria criteria = new UserSearchCriteria();

            if (!string.IsNullOrEmpty(Request.QueryString["filter"]))
            {
                var serializer = new JavaScriptSerializer();
                criteria = serializer.Deserialize(Request.QueryString["filter"], typeof(UserSearchCriteria)) as UserSearchCriteria;
            }
            return(criteria);
        }
Ejemplo n.º 28
0
        public void TestSearchAccuracy2()
        {
            var criteria = new UserSearchCriteria
            {
                Username = "******"
            };

            SearchResult <User> result = instance.Search(criteria);

            AssertResult(result);
        }
Ejemplo n.º 29
0
        private UserSearchCriteria GetSearchCriteria()
        {
            // BUILD THE SEARCH CRITERIA
            UserSearchCriteria criteria = new UserSearchCriteria();

            criteria.Email            = FixSearchString(SearchEmail.Text);
            criteria.FirstName        = FixSearchString(SearchFirstName.Text);
            criteria.LastName         = FixSearchString(SearchLastName.Text);
            criteria.IncludeAnonymous = false;
            return(criteria);
        }
Ejemplo n.º 30
0
        public IHttpActionResult GetUserByName(string name)
        {
            var searchCriteris = new UserSearchCriteria();

            searchCriteris.Name = name;

            var searchSpecification = new UserSpecificationForSearch(searchCriteris);


            return(Ok(GetUserList_DTO(_tenantRepo.Find(searchSpecification))));
        }
Ejemplo n.º 31
0
        public async Task <ApiPageResult> GetUsers([FromBody] UserSearchCriteria criteria)
        {
            var result = new ApiPageResult();
            var page   = await _userService.GetPageAsync(criteria);

            result.Code    = 200;
            result.Message = "获取用户列表成功";
            result.Page    = page;

            return(result);
        }
Ejemplo n.º 32
0
        public OxiteViewModelItems <User> FindQuery(UserSearchCriteria searchCriteria)
        {
            //TODO: (erikpo) Check permissions

            IEnumerable <User> foundUsers = userService.FindUsers(searchCriteria);
            //TODO: (erikpo) Before the list is set into the model, filter it from the AuthorizationManager class (like make sure anonymous doesn't ever get sent down, etc)
            OxiteViewModelItems <User> model = new OxiteViewModelItems <User>(foundUsers);

            model.AddModelItem(searchCriteria);

            return(model);
        }
Ejemplo n.º 33
0
        public JsonList <UserGridModel> GetAll([FromUri] PaginationOptions pagingOptions,
                                               [FromUri] UserSearchCriteria searchCriteria)
        {
            var pagingUsers = _userService.GetAllUsers(pagingOptions, searchCriteria, _workContext.User, true);
            var users       = pagingUsers.ToList().ToModelList <User, UserGridModel>();

            return(new JsonList <UserGridModel>
            {
                Data = users,
                TotalItems = pagingUsers.TotalCount
            });
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Gets the user specified by the user name, or null if no such user exists.
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="persistenceContext"
        /// <returns></returns>
        private User GetUser(string userName, IPersistenceContext persistenceContext)
        {
            var criteria = new UserSearchCriteria();
            criteria.UserName.EqualTo(userName);

            // use query caching here to make this fast (assuming the user table is not often updated)
            var users = persistenceContext.GetBroker<IUserBroker>().Find(
                criteria, new SearchResultPage(0, 1), new EntityFindOptions { Cache = true });

            // bug #3701: to ensure the username match is case-sensitive, we need to compare the stored name to the supplied name
            // returns null if no match
            return CollectionUtils.SelectFirst(users, u => u.UserName == userName);
        }
Ejemplo n.º 35
0
        public bool AssertUserHasToken(string userName, string token)
        {
            UserSearchCriteria whereUser = new UserSearchCriteria();
            whereUser.UserName.EqualTo(userName);

            AuthorityTokenSearchCriteria whereToken = new AuthorityTokenSearchCriteria();
            whereToken.Name.EqualTo(token);

            // want this to be as fast as possible - use joins and only select the count
            HqlQuery query = new HqlQuery("select count(*) from User u join u.AuthorityGroups g join g.AuthorityTokens t");
            query.Conditions.AddRange(HqlCondition.FromSearchCriteria("u", whereUser));
            query.Conditions.AddRange(HqlCondition.FromSearchCriteria("t", whereToken));

            // expect exactly one integer result
            return ExecuteHqlUnique<long>(query) > 0;
        }
Ejemplo n.º 36
0
        public string[] FindTokensByUserName(string userName)
        {
            UserSearchCriteria where = new UserSearchCriteria();
            where.UserName.EqualTo(userName);

            // want this to be as fast as possible - use joins and only select the AuthorityToken names
            HqlQuery query = new HqlQuery("select distinct t.Name from User u join u.AuthorityGroups g join g.AuthorityTokens t");
            query.Conditions.AddRange(HqlCondition.FromSearchCriteria("u", where));

            // take advantage of query caching if possible
            query.Cacheable = true;

            IList<string> tokens = this.ExecuteHql<string>(query);
            string[] result = new string[tokens.Count];
            tokens.CopyTo(result, 0);
            return result;
        }
Ejemplo n.º 37
0
        public Guid[] FindDataGroupsByUserName(string userName)
        {
            UserSearchCriteria where = new UserSearchCriteria();
            where.UserName.EqualTo(userName);

            AuthorityGroupSearchCriteria groupWhere = new AuthorityGroupSearchCriteria();
            groupWhere.DataGroup.EqualTo(true);

            // want this to be as fast as possible - use joins and only select the AuthorityToken names
            HqlQuery query = new HqlQuery("select distinct g.OID from User u join u.AuthorityGroups g");
            query.Conditions.AddRange(HqlCondition.FromSearchCriteria("u", where));
            query.Conditions.AddRange(HqlCondition.FromSearchCriteria("g", groupWhere));

            // take advantage of query caching if possible
            query.Cacheable = true;

            IList<Guid> oids = ExecuteHql<Guid>(query);
            var result = new Guid[oids.Count];
            oids.CopyTo(result, 0);
            return result;
        }
Ejemplo n.º 38
0
		public ListUsersResponse ListUsers(ListUsersRequest request)
		{
			// establish which account types this user is entitled to see
			var visibleAccountTypes = GetAccountTypesAuthorizedToManage(request.IncludeGroupAccounts, request.IncludeSystemAccounts).ToList();
			if (!visibleAccountTypes.Any())
				throw new SecurityException(SR.MessageUserNotAuthorized);

			var criteria = new UserSearchCriteria();
			criteria.AccountType.In(visibleAccountTypes);
			criteria.UserName.SortAsc(0);

			// create the criteria, depending on whether matches should be "exact" or "like"
			if (request.ExactMatchOnly)
			{
				if (!string.IsNullOrEmpty(request.UserName))
					criteria.UserName.EqualTo(request.UserName);
				if (!string.IsNullOrEmpty(request.DisplayName))
					criteria.DisplayName.EqualTo(request.DisplayName);
			}
			else
			{
				if (!string.IsNullOrEmpty(request.UserName))
					criteria.UserName.StartsWith(request.UserName);
				if (!string.IsNullOrEmpty(request.DisplayName))
					criteria.DisplayName.Like(string.Format("%{0}%", request.DisplayName));
			}

			var broker = PersistenceContext.GetBroker<IUserBroker>();
			var assembler = new UserAssembler();
			var userSummaries = CollectionUtils.Map(
				broker.Find(criteria, request.Page),
				(User user) => assembler.GetUserSummary(user));
			var total = broker.Count(criteria);

			return new ListUsersResponse(userSummaries, (int)total);
		}
Ejemplo n.º 39
0
		private User FindUserByName(string name)
		{
			try
			{
				var where = new UserSearchCriteria();
				where.UserName.EqualTo(name);

				return PersistenceContext.GetBroker<IUserBroker>().FindOne(where);
			}
			catch (EntityNotFoundException)
			{
				throw new RequestValidationException(string.Format("{0} is not a valid account name.", name));
			}
		}
 /// <summary>
 /// Search for a user
 /// </summary>
 /// <param name="oHostSecurityToken">HostSecurityToken obtained when security provider of IWS is called</param>
 /// <param name="collectionRequest"></param>
 /// <param name="criteria"></param>
 /// <returns></returns>
 public UserSearchReturnValue UserSearch(HostSecurityToken oHostSecurityToken, CollectionRequest collectionRequest,
     UserSearchCriteria criteria)
 {
     UserSearchReturnValue returnValue = null;
     if (Functions.ValidateIWSToken(oHostSecurityToken))
     {
         oUtilitiesService = new UtilitiesService();
         returnValue = oUtilitiesService.UserSearch(Functions.GetLogonIdFromToken(oHostSecurityToken), collectionRequest, criteria);
     }
     else
     {
         returnValue = new UserSearchReturnValue();
         returnValue.Success = false;
         returnValue.Message = "Invalid Token";
     }
     return returnValue;
 }
Ejemplo n.º 41
0
        /// <summary>
        /// Gets the users.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="userName">The username.</param>
        /// <returns>
        /// The manager response where a list of users is returned in the response.
        /// </returns>
        public virtual ManagerResponse<GetUsersResult, IList<CommerceUser>> GetUsers([NotNull] CommerceStorefront storefront, string userName)
        {
            Assert.ArgumentNotNullOrEmpty(userName, "userName");

            var criteria = new UserSearchCriteria { UserName = userName, ShopName = storefront.ShopName };
            var request = new GetUsersRequest(criteria);
            var result = this.CustomerServiceProvider.GetUsers(request);
            if (!result.Success || result.CommerceUsers == null)
            {
                var message = StorefrontManager.GetSystemMessage("UserNotFoundError");
                result.SystemMessages.Add(new SystemMessage { Message = message });
            }

            Helpers.LogSystemMessages(result.SystemMessages, result);
            return new ManagerResponse<GetUsersResult, IList<CommerceUser>>(result, result.CommerceUsers);
        }
        /// <summary>
        /// Searches for users that match the search criteria.
        /// </summary>
        public UserSearchItem[] SearchUser(int startRow, int pageSize, string sortBy, string name,  bool forceRefresh)
        {
            UtilitiesServiceClient userService = null;
            UserSearchItem[] users = null;
            try
            {
                if (HttpContext.Current.Session[SessionName.LogonSettings] != null)
                {
                    if (name == null || name.Trim() == string.Empty)
                        throw new Exception("Please enter search criteria");

                    if (!IsReset)
                    {
                        // LSC - Insert Wildcards - 28/08/2010
                        if (!name.Contains('%')) { name = "%" + name.Trim() + "%"; }

                        Guid _logonId = ((LogonReturnValue)HttpContext.Current.Session[SessionName.LogonSettings]).LogonId;
                        CollectionRequest collectionRequest = new CollectionRequest();
                        collectionRequest.ForceRefresh = forceRefresh;
                        collectionRequest.StartRow = startRow;
                        collectionRequest.RowCount = pageSize;

                        UserSearchCriteria criteria = new UserSearchCriteria();
                        criteria.UserType = 1;
                        criteria.Name = name;

                        userService = new UtilitiesServiceClient();
                        UserSearchReturnValue returnValue = userService.UserSearch(_logonId, collectionRequest, criteria);

                        //int idx =0;
                        //while (idx < returnValue.Users.Rows.Count())
                        //{

                        //    idx++;
                        //}

                        if (returnValue.Success)
                        {
                            _userRowCount = returnValue.Users.TotalRowCount;
                            users = returnValue.Users.Rows;

                            //users[0].UserId;
                        }
                        else
                        {
                            if (returnValue.Message == "SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.")
                                throw new Exception("Date is invalid");
                            else
                                throw new Exception(returnValue.Message);

                        }
                    }
                }
                return users;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (userService != null)
                {
                    if (userService.State != System.ServiceModel.CommunicationState.Faulted)
                        userService.Close();
                }
            }
        }
        /// <summary>
        /// Get the options for <paramref name="source"/>.
        /// </summary>
        /// <param name="source">Defines the method for retrieving options.</param>
        /// <returns>The options for <paramref name="source"/>.</returns>
        public ControlValueOptionList GetOptions(IOptionSource source)
        {
            ControlValueOptionList optionList = new ControlValueOptionList();
            SystemOptionSource systemSource = source as SystemOptionSource;

            UserSearchCriteria criteria = new UserSearchCriteria
                                          {
                                              IncludeServiceUsers = false,
                                              IncludeNoOrganisationUsers = false,
                                              OrganisationIds = new List<string> { this.organisationId }
                                          };

            if (!string.IsNullOrWhiteSpace(systemSource.FilterRoleId))
            {
                criteria.RoleIds = new List<string> { systemSource.FilterRoleId };
            }

            IEnumerable<OptionSourceUser> usersWithRole = this.findUsersFn(criteria);
            MappedField categoryMap = systemSource.ResponseFieldMap.FirstOrDefault(m => m.Target == CATEGORY);
            string categoryKey = categoryMap != null ? categoryMap.Source : string.Empty;

            string descriptionKey = string.Empty;
            var description = systemSource.ResponseFieldMap.FirstOrDefault(m => m.Target == DESCRIPTION);
            if (description != null)
            {
                descriptionKey = description.Source;
            }

            string valueKey = string.Empty;
            var value = systemSource.ResponseFieldMap.FirstOrDefault(m => m.Target == VALUE);
            if (value != null)
            {
                valueKey = value.Source;
            }

            optionList.AddRange(usersWithRole.Select(item => new ControlValueOption
            {
                Category = !string.IsNullOrWhiteSpace(categoryKey) && item.GetType().GetProperty(categoryKey).GetValue(item) != null ? item.GetType().GetProperty(categoryKey).GetValue(item).ToString() : string.Empty,
                Description = !string.IsNullOrWhiteSpace(descriptionKey) && item.GetType().GetProperty(descriptionKey).GetValue(item) != null ? item.GetType().GetProperty(descriptionKey).GetValue(item).ToString() : string.Empty,
                Value = !string.IsNullOrWhiteSpace(valueKey) && item.GetType().GetProperty(valueKey).GetValue(item) != null ? item.GetType().GetProperty(valueKey).GetValue(item).ToString() : string.Empty
            }));

            return optionList;
        }
Ejemplo n.º 44
0
        private User GetUser(string userName, IList<User> importedUsers)
        {
            User user = null;

            user = CollectionUtils.SelectFirst(importedUsers,
                delegate(User u) { return u.UserName == userName; });

            if (user == null)
            {
                UserSearchCriteria criteria = new UserSearchCriteria();
                criteria.UserName.EqualTo(userName);

                IUserBroker broker = _context.GetBroker<IUserBroker>();
                user = CollectionUtils.FirstElement(broker.Find(criteria));
            }

            return user;
        }