Beispiel #1
0
        public void TestAPIUsers()
        {
            var users    = new GetUsers();
            var response = users.GetUsersList();

            Assert.AreEqual(2, response.Page);
        }
 public UserController(GetUsers getFets, AuthenticateUser authenticateUser, UpdateDeviceId updateDeviceId, AddUser addUser)
 {
     _getUsers         = getFets;
     _authenticateUser = authenticateUser;
     _updateDeviceId   = updateDeviceId;
     _addUser          = addUser;
 }
        public IApiResult Update(UpdateUser operation)
        {
            GetUsers loadUser = new GetUsers();

            loadUser.LangID = 1;
            loadUser.ID     = operation.ID;
            var         loadUserResult = loadUser.QueryAsync().Result;
            List <User> users          = (List <User>)loadUserResult;

            if (users.Count > 0)
            {
                var result = operation.ExecuteAsync().Result;
                if (result is ValidationsOutput)
                {
                    return(new ApiResult <List <ValidationItem> >()
                    {
                        Data = ((ValidationsOutput)result).Errors
                    });
                }
                else
                {
                    return(new ApiResult <object>()
                    {
                        Status = ApiResult <object> .ApiStatus.Success
                    });
                }
            }
            else
            {
                return(new ApiResult <object>()
                {
                    ErrorMessageEn = ApiResult <object> .ApiMessage.notExist
                });
            }
        }
Beispiel #4
0
        public async Task <IReadOnlyCollection <UserListEntryDto> > HandleAsync(GetUsers query)
        {
            var users = new List <UserListEntryDto>
            {
                new UserListEntryDto
                {
                    Id        = new Guid("00000000-0000-0000-0000-000000000001"), // Just for testing, usually, we would generate the Guid when creating the user with Guid.NewGuid().
                    Email     = "*****@*****.**",
                    FirstName = "Sherlock",
                    LastName  = "Holmes"
                },
                new UserListEntryDto
                {
                    Id        = new Guid("00000000-0000-0000-0000-000000000002"), // Just for testing, usually, we would generate the Guid when creating the user with Guid.NewGuid().
                    Email     = "*****@*****.**",
                    FirstName = "John",
                    LastName  = "Watson"
                },
                new UserListEntryDto
                {
                    Id        = new Guid("00000000-0000-0000-0000-000000000003"), // Just for testing, usually, we would generate the Guid when creating the user with Guid.NewGuid().
                    FirstName = "James",
                    Email     = "*****@*****.**",
                    LastName  = "Moriarty"
                }
            };

            return(users);
        }
Beispiel #5
0
        public async Task <IActionResult> Index(int page = 1, string searchTerm = null)
        {
            GetUsers getUsersQuery = new GetUsers()
            {
                PageInfo   = new PageInfo(page, DefaultPageSize),
                SearchInfo = new SearchInfo(searchTerm)
            };

            IEnumerable <User> users = await this.getUsers.ExecuteAsync(getUsersQuery);

            GetUsersCount getUsersCountQuery = new GetUsersCount()
            {
                SearchInfo = new SearchInfo(searchTerm)
            };

            int usersCount = await this.getUsersCount.ExecuteAsync(getUsersCountQuery);

            IEnumerable <UserListingViewModel> usersModel =
                Mapper.Map <IEnumerable <UserListingViewModel> >(users);

            SearchViewModel <PaginatedViewModel <UserListingViewModel> > model =
                ViewModelFactory.CreateSearchPaginatedViewModel <UserListingViewModel>(
                    usersModel,
                    page,
                    DefaultPageSize,
                    usersCount,
                    searchTerm,
                    "users");

            return(View(model));
        }
Beispiel #6
0
        public void Test1()
        {
            GetUsers users = new GetUsers();

            users.FirstName = "suraj";
            Assert.AreEqual(users.FirstName, "suraj");
        }
        public IActionResult Load(Int64?userID, Int64?langId)
        {
            GetUsers operation = new GetUsers();

            operation.ID = userID;
            if (langId.HasValue)
            {
                operation.LangID = langId;
            }
            else
            {
                operation.LangID = 1;
            }

            var result = operation.QueryAsync().Result;

            if (result is ValidationsOutput)
            {
                return(Ok(new ApiResult <List <ValidationItem> >()
                {
                    Data = ((ValidationsOutput)result).Errors
                }));
            }
            else
            {
                return(Ok((List <User>)result));
            }
        }
        public async Task <IEnumerable <User> > HandleAsync(GetUsers query, CancellationToken ct)
        {
            var result = await UserRepository.GetAllAsync();



            return(result);
        }
Beispiel #9
0
        public async Task ReturnTheCorrectSongsWhenThePassedQueryContainsNonEmptySearchTerm()
        {
            var expectedUsers = new[]
            {
                new User()
                {
                    UserName = "******"
                },
                new User()
                {
                    UserName = "******"
                }
            };

            var users = new List <User>()
            {
                new User()
                {
                    UserName = "******"
                },
                new User()
                {
                    UserName = "******"
                }
            };

            users.AddRange(expectedUsers);

            var usersStub = users.AsQueryable()
                            .BuildMock();

            var userRepositoryStub = new Mock <IEfRepository <User> >();

            userRepositoryStub
            .Setup(x => x.All(It.IsAny <bool>()))
            .Returns(usersStub.Object);

            GetUsers query = new GetUsers()
            {
                PageInfo   = new PageInfo(1, 5),
                SearchInfo = new SearchInfo("eu")
            };

            // Arrange
            GetUsersQueryService sut =
                new GetUsersQueryService(userRepositoryStub.Object);

            // Act
            IEnumerable <User> actualUsers = await sut.ExecuteAsync(query);

            // Assert
            Assert.AreEqual(2, actualUsers.Count());
            CollectionAssert.AreEqual(expectedUsers, actualUsers);
        }
 /* Take commands as dependencies.
  * This may get awkward once a constructor
  * takes lots of commands... and you may want to consider
  * using a command dispatcher.
  *
  * Good thing is, we get rid of Service classes,
  * which are basically logic dumpsters.
  *
  * Let the controller actions follow an Accept-Delegate-Reply pattern.
  */
 public UsersController(
     GetUsers getUsers,
     ChangeEmail changeEmail,
     ChangeUsername changeUsername,
     IDistributedCache cache
     )
 {
     this.getUsers       = getUsers;
     this.changeEmail    = changeEmail;
     this.changeUsername = changeUsername;
     this.cache          = cache;
 }
        public async Task <IEnumerable <UserDto> > HandleAsync(GetUsers query)
        {
            if (string.IsNullOrEmpty(query.SearchTerm))
            {
                var allUsers = (List <UserDocument>) await _repository.FindAsync(c => true);

                return(allUsers?.Select(u => u.AsDto()));
            }

            var filteredUsers = await _repository.FindAsync(u => u.NORMALIZED_FULLNAME.Contains(query.SearchTerm.ToUpperInvariant()));

            return(filteredUsers?.Select(u => u.AsDto()));
        }
        public ActionResult AddUser([FromBody] GetUsers data)
        {
            var userlist = db.Users.Where(x => x.User == data.Users).Select(x => x.User).FirstOrDefault();

            if (userlist != data.Users && data.Users != null)
            {
                userService.AddUser(data.Users, data.Password);
                return(Ok());
            }
            else
            {
                return(BadRequest());
            }
        }
Beispiel #13
0
        public async Task get_users_query_should_return_empty_when_no_users_exist()
        {
            var query = new GetUsers();

            // Check if exception is thrown

            var requestResult = _queryHandler
                                .Awaiting(c => c.HandleAsync(query));

            requestResult.Should().NotThrow();

            var result = await requestResult();

            result.Should().BeEmpty();
        }
        public IApiResult Create(CreateUser operation)
        {
            //check if userName and email exist
            GetUsers loadUser = new GetUsers();

            loadUser.LangID = 1;

            var         loadUserResult = loadUser.QueryAsync().Result;
            List <User> users          = (List <User>)loadUserResult;
            bool        emailExist     = users.Exists(user => user.Email == operation.Email);

            if (emailExist)
            {
                return new ApiResult <object>()
                       {
                           ErrorMessageEn = ApiResult <object> .ApiMessage.exist
                       }
            }
            ;
            bool userNameExist = users.Exists(user => user.UserName == operation.UserName);

            if (userNameExist)
            {
                return new ApiResult <object>()
                       {
                           ErrorMessageEn = ApiResult <object> .ApiMessage.exist
                       }
            }
            ;


            var result = operation.ExecuteAsync().Result;

            if (result is ValidationsOutput)
            {
                return(new ApiResult <List <ValidationItem> >()
                {
                    Data = ((ValidationsOutput)result).Errors
                });
            }
            else
            {
                return(new ApiResult <object>()
                {
                    Status = ApiResult <object> .ApiStatus.Success
                });
            }
        }
Beispiel #15
0
        public async Task <IEnumerable <QueriedUsers> > Handle(GetUsers request, CancellationToken cancellationToken)
        {
            using (var con = new SqlConnection(
                       "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Procurement;Integrated Security=True"))
            {
                var query = @"SELECT AspNetUsers.UserName, AspNetUsers.Email, AspNetUsers.PhoneNumber, 
                            AspNetUsers.CompanyName, AspNetUsers.FirstName, AspNetUsers.LastName, 
                            AspNetUsers.Id, AspNetRoles.Name AS Role
                            FROM AspNetRoles INNER JOIN
                            AspNetUserRoles ON AspNetRoles.Id = AspNetUserRoles.RoleId RIGHT OUTER JOIN
                            AspNetUsers ON AspNetUserRoles.UserId = AspNetUsers.Id";

                var result = await con.QueryAsync <QueriedUsers>(query);

                return(result);
            }
        }
        public async Task get_users_endpoint_should_return_ok_but_no_content()
        {
            var query = new GetUsers();

            // Check if exception is thrown

            var response = await Act(query);

            response.Should().NotBeNull();
            response.StatusCode.Should().Be(HttpStatusCode.OK);

            var content = await response.Content.ReadAsStringAsync();

            var userDto = JsonConvert.DeserializeObject <UserDto[]>(content);

            userDto.Should().BeEmpty();
        }
 public void login(string Account, string Password)
 {
     try
     {
         var PasswordMD5 = CreateMD5.EncryptWithMD5(Password);  //加密
         var Get         = new GetUsers();
         var u           = Get.GetUser(Account, PasswordMD5);
         if (u == null)
         {
             throw new Exception("用户名或密码错误!");
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Beispiel #18
0
        private void getUserList()
        {
            //FOR LISTING AUTHORISED MACHINES
            Console.WriteLine("clearing all view list data");
            listView2.Clear();


            //GET DATA
            string   apiUrl       = "https://craig.im/infosec.php";
            string   apiMethod    = "getUsers";
            GetUsers thisGetUsers = new GetUsers()
            {
            };


            //Make http post request
            string response = Http.Post(apiUrl, new NameValueCollection()
            {
                { "api_method", apiMethod },
                { "api_data", JsonConvert.SerializeObject(thisGetUsers) }
            });

            //Deserialise
            API_Response r = JsonConvert.DeserializeObject <API_Response>(response);

            //MessageBox.Show("" + r.ResponseData[0].commonName);

            // Set to details view.
            listView2.View = View.Details;
            // Add both columns.
            listView2.Columns.Add("User ID", 50, HorizontalAlignment.Left);
            listView2.Columns.Add("Username", 330, HorizontalAlignment.Left);

            //fill with data
            int lim = r.ResponseData.Length;

            for (int i = 0; i <= (lim - 1); i++)
            {
                Console.WriteLine("This is loop number " + i);
                string[] row          = { r.ResponseData[i].userID, r.ResponseData[i].username };
                var      listViewItem = new ListViewItem(row);
                listView2.Items.Add(listViewItem);
                row = null;
            }
        }
        public GetUsersResponse Any(GetUsers request)
        {
            var users = new List <User>();

            if (request.UserIds != null && request.UserIds.Count > 0)
            {
                users.AddRange(Db.SelectByIds <User>(request.UserIds));
            }

            if (request.UserNames != null && request.UserNames.Count > 0)
            {
                users.AddRange(Db.Select <User>(q => request.UserNames.Contains(q.UserName)));
            }

            return(new GetUsersResponse {
                Users = new ArrayOfUser(users)
            });
        }
Beispiel #20
0
        public async Task <IActionResult> FilteredUsersAjax(string searchTerm = null)
        {
            IEnumerable <User> users = null;

            GetUsers query = new GetUsers()
            {
                PageInfo   = new PageInfo(1, DefaultPageSize),
                SearchInfo = new SearchInfo(searchTerm)
            };

            string message = await this.CallServiceAsync(
                async() => users = await this.getUsers.ExecuteAsync(query));


            IEnumerable <UserListingViewModel> model =
                Mapper.Map <IEnumerable <UserListingViewModel> >(users);

            return(PartialView("_UserListing", model));
        }
        public GetUsersResponse Any(GetUsers request)
        {
            var users = new List <User>();

            if (request.UserIds != null && request.UserIds.Count > 0)
            {
                users.AddRange(Db.SelectByIds <User>(request.UserIds));
            }

            if (request.UserNames != null && request.UserNames.Count > 0)
            {
                users.AddRange(Db.Select <User>(
                                   "UserName IN ({0})", request.UserNames.SqlInValues()));
            }

            return(new GetUsersResponse {
                Users = new ArrayOfUser(users)
            });
        }
Beispiel #22
0
        public async Task <PagedResultDto <UserDto> > GetAllUser(GetUsers input)
        {
            //Total Record
            var countQuery = _repository.GetAll()
                             .WhereIf(!string.IsNullOrEmpty(input.Filter),
                                      p => p.UserName.Contains(input.Filter));
            var totalRecord = countQuery.Count();
            //Record with filter & pager
            var result = _repository
                         .GetAll()
                         .WhereIf(!string.IsNullOrEmpty(input.Filter), p => p.UserName.Contains(input.Filter))
                         .OrderBy(p => p.UserName)
                         .ToList();

            return(new PagedResultDto <UserDto>(
                       totalRecord,
                       result.MapTo <List <UserDto> >()
                       ));
        }
        public IActionResult Login([FromBody] Auth auth)
        {
            GetUsers loginOperation = new GetUsers();

            if (loginOperation.LangID == null)
            {
                auth.langId = 1;
            }
            var     operation   = loginOperation.Login(auth).Result;
            Company userCompany = new Company();
            var     userList    = (List <User>)operation;

            if (userList.Count > 0)
            {
                var        user    = userList[0];
                GetCompany company = new GetCompany();
                company.ID = user.CompanyID;
                var companies = ((List <Company>)company.QueryAsync().Result);
                userCompany = companies[0];
                var tokenHandler    = new JwtSecurityTokenHandler();
                var key             = Encoding.ASCII.GetBytes(configuration.GetSection("AppSettings:Token").Value);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, user.ID.ToString()),
                        new Claim(ClaimTypes.Name, user.Email)
                    }),
                    Expires            = DateTime.Now.AddDays(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                                SecurityAlgorithms.HmacSha512Signature)
                };
                var token       = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                user.Password = "";
                return(Ok(new { tokenString, user, userCompany }));
            }
            else
            {
                return(Unauthorized());
            }
        }
Beispiel #24
0
        public async Task get_users_query_can_filter_based_on_fullname_when_a_user_exists()
        {
            var id             = Guid.NewGuid();
            var id1            = Guid.NewGuid();
            var email          = "*****@*****.**";
            var email1         = "*****@*****.**";
            var fullname       = "fullname";
            var filterFullname = "filter";
            var password       = "******";
            var pic            = "test.nl/image";
            var role           = Role.User;
            var securityStamp  = new Guid().ToString();

            // Add users
            var user = new User(id, email, fullname, pic, password, role, securityStamp, 0, DateTime.MinValue, DateTime.UtcNow,
                                new string[] { });
            var user1 = new User(id1, email1, filterFullname, pic, password, role, securityStamp, 0, DateTime.MinValue, DateTime.UtcNow,
                                 new string[] { });

            await _mongoDbFixture.InsertAsync(user.AsDocument());

            await _mongoDbFixture.InsertAsync(user1.AsDocument());

            var query = new GetUsers(filterFullname);

            // Check if exception is thrown

            var requestResult = _queryHandler
                                .Awaiting(c => c.HandleAsync(query));

            requestResult.Should().NotThrow();

            var result = await requestResult();

            var userDtos = result as UserDto[] ?? result.ToArray();

            userDtos.First().Should().NotBeNull();
            userDtos.First().Id.Should().Be(user1.Id);
            userDtos.First().Email.Should().Be(user1.Email);
            userDtos.First().Fullname.Should().Be(user1.Fullname);
            userDtos.First().Pic.Should().Be(user1.Pic);
            userDtos.First().Role.Should().Be(user1.Role);
        }
        public object Get(GetUsers request)
        {
            var dbUsers = _userRepo.GetAll();
            var dbRoles = _roleRepo.GetAll();
            var users = dbUsers.ConvertAll(user =>
            {
                var dbUserRole = dbRoles.FirstOrDefault(x => x.Id == user.RoleId);
                return new UserDTO
                {
                    FullName = user.FullName,
                    Id = user.Id,
                    UserName = user.UserName,
                    RoleId = user.RoleId,
                    RoleName = dbUserRole.RoleName
                };
            });

            return users;
        }
Beispiel #26
0
        public object Get(GetUsers request)
        {
            var dbUsers = _userRepo.GetAll();
            var dbRoles = _roleRepo.GetAll();
            var users   = dbUsers.ConvertAll(user =>
            {
                var dbUserRole = dbRoles.FirstOrDefault(x => x.Id == user.RoleId);
                return(new UserDTO
                {
                    FullName = user.FullName,
                    Id = user.Id,
                    UserName = user.UserName,
                    RoleId = user.RoleId,
                    RoleName = dbUserRole.RoleName
                });
            });

            return(users);
        }
        public async Task get_users_endpoint_should_return_http_status_code_ok_and_user_dtos()
        {
            var id            = Guid.NewGuid();
            var id1           = Guid.NewGuid();
            var email         = "*****@*****.**";
            var email1        = "*****@*****.**";
            var fullname      = "fullname";
            var password      = "******";
            var pic           = "test.nl/image";
            var role          = Role.User;
            var securityStamp = new Guid().ToString();

            // Add users
            var user = new User(id, email, fullname, pic, password, role, securityStamp, 0, DateTime.MinValue, DateTime.UtcNow,
                                new string[] { });
            var user1 = new User(id1, email1, fullname, pic, password, role, securityStamp, 0, DateTime.MinValue, DateTime.UtcNow,
                                 new string[] { });

            await _mongoDbFixture.InsertAsync(user.AsDocument());

            await _mongoDbFixture.InsertAsync(user1.AsDocument());


            var query = new GetUsers();

            // Check if exception is thrown
            var response = await Act(query);

            response.Should().NotBeNull();
            response.StatusCode.Should().Be(HttpStatusCode.OK);

            var content = await response.Content.ReadAsStringAsync();

            var userDto = JsonConvert.DeserializeObject <UserDto[]>(content);

            userDto.Should().NotBeNull();
            userDto.First().Id.Should().Be(user.Id);
            userDto.First().Email.Should().Be(user.Email);
            userDto.First().Fullname.Should().Be(user.Fullname);
            userDto.First().Pic.Should().Be(user.Pic);
            userDto.First().Role.Should().Be(user.Role);
        }
Beispiel #28
0
        public async Task <IActionResult> GetAllStaticData()
        {
            var user = await userManager.GetUserAsync(HttpContext.User);

            IEnumerable <GetUserDecksWithHeapsAndTags.ResultModel> decksWithHeapsAndTags;

            if (user == null)
            {
                decksWithHeapsAndTags = new GetUserDecksWithHeapsAndTags.ResultModel[0];
            }
            else
            {
                decksWithHeapsAndTags = await new GetUserDecksWithHeapsAndTags(dbContext).RunAsync(user.Id);
            }
            var allTags  = new GetAllAvailableTags(dbContext).Run();
            var allUsers = new GetUsers(dbContext).Run();
            GetAllStaticDataViewModel value = new GetAllStaticDataViewModel(decksWithHeapsAndTags, allTags, allUsers, localizer, decksControllerLocalizer, user);

            return(base.Ok(value));
        }
Beispiel #29
0
        public void ReceiveGetUsers(GetUsers getUsers)
        {
            Console.WriteLine("GetUsers");

            for (int i = 0; i < getUsers.users.Length; i++)
            {
                Packets.Types.Data.UserData data = getUsers.users[i];

                ClientUser user;
                if (Users.TryGetValue(data.userID, out user))
                {
                    user.SetName(data.name);

                    OnUserUpdated?.Invoke(user);
                }
                else
                {
                    AddUser(data.userID, data.name);
                }
            }
        }
        public async Task WhenGettingExistingUsers()
        {
            var cancellationToken = new CancellationToken();

            var users = new[]
            {
                new User(), new User(), new User(),
            };

            var database   = Substitute.For <IMongoDatabase>();
            var collection = Substitute.For <IMongoCollection <User> >();
            var cursor     = Substitute.For <IAsyncCursor <User> >();

            cursor.Current.Returns(users);
            cursor.MoveNextAsync(cancellationToken).Returns(true, false);
            collection.FindAsync <User>(Arg.Any <Expression <Func <User, bool> > >(), null, cancellationToken).ReturnsForAnyArgs(cursor);
            database.GetCollection <User>("users").Returns(collection);

            var handler = new GetUsers(database);

            _result = await handler.Handle(new GetUsers.Query(), cancellationToken);
        }
Beispiel #31
0
        public object Get(GetUsers getUsers)
        {
            var authSession   = this.SessionAs <AuthUserSession>();
            var documentStore = this.ResolveService <IDocumentStore>();

            User[] userList;
            using (var session = documentStore.OpenSession())
            {
                // Trim down the data sent since this is
                // just to show the user names and the basic states.
                userList = (from users in session.Query <User>()
                            where users.Deleted == false
                            select new User
                {
                    FirstName = users.FirstName,
                    LastName = users.LastName,
                    Active = users.Active,
                    Locked = users.Locked
                }).ToArray();
            }

            return(userList);
        }
Beispiel #32
0
 public object Post(GetUsers request)
 {
     var query = AutoQuery.CreateQuery(request, Request.GetRequestParams());
     return AutoQuery.Execute(request, query);
 }
		public BLResponse<User> Get(GetUsers request)
		{
			return Post (request);
		}
		public BLResponse<User> Post(GetUsers request)
		{
			return Controller.GetUsers( BLRequest);
		}