コード例 #1
0
ファイル: Sample.cs プロジェクト: iorilan/AzureGraphApiLab
        public IHttpActionResult GetAllUsers([FromBody] UserPagingRequest request)
        {
            try
            {
                var tryGetToken = IdTokenFromSession;
                if (string.IsNullOrWhiteSpace(tryGetToken))
                {
                    tryGetToken = RefreshTokenWithAdminLogin();
                    UpdateToken(tryGetToken);
                }

                return(DoUserPaging(request, tryGetToken));
            }
            catch (Exception ex)
            {
                // assume that token has been expired
                try
                {
                    var idtoken = RefreshTokenWithAdminLogin();
                    UpdateToken(idtoken);

                    return(DoUserPaging(request, idtoken));
                }
                catch (Exception ex2)
                {
                    _log.Error(ex2);
                    return(InternalServerError());
                }
            }
        }
コード例 #2
0
        // Get user paging
        public async Task <PageResult <UserViewModel> > GetUserPaging(UserPagingRequest request)
        {
            // b1 create query
            var query = (from u in  _userManager.Users
                         select new UserViewModel()
            {
                Id = u.Id,
                Email = u.Email,
                FirstName = u.FristName,
                LastName = u.LastName,
                DOB = u.BOD,
                PhoneNumber = u.PhoneNumber,
                UserName = u.UserName
            });

            // b2 select user by keyword
            if (!string.IsNullOrEmpty(request.keyword))
            {
                query = query.Where(x => x.LastName.Contains(request.keyword) || x.UserName.Contains(request.keyword));
            }
            // b3 count record
            var totalRecord = await query.CountAsync();

            // b4 paging
            var data = await query.Skip((request.PageIndex - 1) *request.PageSize).Take(request.PageSize).ToListAsync();

            PageResult <UserViewModel> pageResult = new PageResult <UserViewModel>()
            {
                TotalRecord = totalRecord,
                Items       = data
            };

            return(pageResult);
        }
コード例 #3
0
        public async Task <IActionResult> Index(string keyword, Status?status, string roleId, int pageIndex = 1, int pageSize = 10)
        {
            var request = new UserPagingRequest()
            {
                Keyword   = keyword,
                PageIndex = pageIndex,
                PageSize  = pageSize,
                RoleId    = roleId,
                Status    = status
            };

            List <SelectListItem> roles = new List <SelectListItem>();

            roles.Add(new SelectListItem()
            {
                Text = "Tất cả", Value = ""
            });
            var listRoles = (await _roleApiClient.GetRolesAsync())
                            .Select(x => new SelectListItem()
            {
                Text     = x.Name,
                Value    = x.Id.ToString(),
                Selected = (!string.IsNullOrWhiteSpace(roleId)) && roleId == x.Id.ToString()
            }).ToList().OrderBy(x => x.Text);

            roles.AddRange(listRoles);
            ViewBag.Roles = roles;


            ViewBag.KeyWord = keyword;
            var result = await _userApiClient.GetUserPagingAsync(request);

            return(View(result.ResultObj));
        }
コード例 #4
0
        public async Task <UserPagingResponse> GetUsers(IOperation operation, UserPagingRequest request)
        {
            var(total, users) = await userDataStore.GetUsers(operation, request);

            return(new UserPagingResponse
            {
                Total = total,
                Items = users
            });
        }
コード例 #5
0
ファイル: Sample.cs プロジェクト: iorilan/AzureGraphApiLab
        private IHttpActionResult DoUserPaging(UserPagingRequest request, string tryGetToken)
        {
            string directoryName         = AzureADAppConstants.TenantName;
            string clientId              = AzureADAppConstants.ClientId;
            var    credentials           = new UserAssertion(tryGetToken);
            var    authenticationContext = new AuthenticationContext(AzureADGlobalConstants.AuthString + directoryName);
            var    loginResult           = authenticationContext.AcquireTokenAsync(AzureADGlobalConstants.GraphUrl, clientId, credentials)
                                           .Result;

            var token = loginResult.AccessToken;


            ProfileResultWrapper result = null;
            string skipToken            = "";

            using (var httpClient = new HttpClient())
            {
                var baseUrl = "https://graph.microsoft.com/v1.0/users?";

                var filterString = string.Format("$top={0}", request.PageSize);

                // sample :
                //https://graph.microsoft.com/v1.0/users?$top=10&$skiptoken=X%274453707
                //

                if (!string.IsNullOrWhiteSpace(request.AzureToken))
                {
                    filterString += "&$skiptoken=" + request.AzureToken;
                }

                httpClient.BaseAddress = new Uri(baseUrl + filterString);
                httpClient.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse("Bearer " + token);
                var graphRet = httpClient.GetAsync("").Result;
                var json     = graphRet.Content.ReadAsStringAsync().Result;

                result = JsonConvert.DeserializeObject <ProfileResultWrapper>(json);

                var i  = result.SkipToken.IndexOf("skiptoken=");
                var st = "skiptoken=";
                skipToken = result.SkipToken.Substring(i + st.Length, result.SkipToken.Length - i - st.Length);
            }
            foreach (var profile in result.Value)
            {
                var photo = GetUserPhoto(token, profile.Id);
                profile.Photo = photo;
            }

            return(Ok(new PagingQueryResponse()
            {
                IsSuccess = true,
                ErrorMessage = "",
                Data = result.Value,
                SkipToken = skipToken
            }));
        }
コード例 #6
0
        public async Task <ApiResult <PageResult <UserVMD> > > GetUserPagingAsync(UserPagingRequest request)
        {
            var users = _context.Users.Select(x => x);

            if (!string.IsNullOrWhiteSpace(request.RoleId))
            {
                users = users.Join(_context.AppUserRoles,
                                   u => u.Id,
                                   ur => ur.UserId,
                                   (u, ur) => new { u, ur }).Where(x => request.RoleId == x.ur.RoleId.ToString()).Select(x => x.u);
            }


            if (request.Status != null)
            {
                users = users.Where(x => x.Status == request.Status);
            }

            if (!string.IsNullOrWhiteSpace(request.Keyword))
            {
                users = users.Where(x => x.UserName.Contains(request.Keyword) ||
                                    x.PhoneNumber.Contains(request.Keyword) ||
                                    x.FirstName.Contains(request.Keyword) ||
                                    x.LastName.Contains(request.Keyword) ||
                                    x.Email.Contains(request.Keyword) ||
                                    x.Dob.ToString().Contains(request.Keyword));
            }

            int totalRow = await users.CountAsync();

            var item = users.OrderBy(x => x.UserName).Skip((request.PageIndex - 1) * request.PageSize)
                       .Take(request.PageSize).Select(x => new UserVMD()
            {
                Id          = x.Id,
                Dob         = x.Dob,
                Email       = x.Email,
                FirstName   = x.FirstName,
                LastName    = x.LastName,
                PhoneNumber = x.PhoneNumber,
                UserName    = x.UserName,
                Status      = x.Status
            }).ToList();

            var pageResult = new PageResult <UserVMD>()
            {
                TotalRecord = totalRow,
                PageIndex   = request.PageIndex,
                PageSize    = request.PageSize,
                Item        = item,
            };

            return(new ApiSuccessResult <PageResult <UserVMD> >(pageResult));
        }
コード例 #7
0
        public async Task <IActionResult> GetUserPaging([FromBody] UserPagingRequest request)
        {
            var result = await _userService.GetUserPaging(request);

            if (request == null)
            {
                return(BadRequest());
            }
            else
            {
                return(new OkObjectResult(new {
                    StatusCode = HttpStatusCode.OK,
                    Data = result
                }));
            }
        }
コード例 #8
0
        public async Task <IActionResult> GetUsersPaged(UserPagingRequest model)
        {
            var result = await _userService.GetListUserPaged(model);

            if (result == null)
            {
                return(Ok(new ResponseBase <PagedResult <UserViewModel> >()
                {
                    msg = "Out of index"
                }));
            }
            return(Ok(new ResponseBase <PagedResult <UserViewModel> >()
            {
                data = result
            }));
        }
コード例 #9
0
        public async Task <PageResult <UserViewModel> > UserPagingRequest(UserPagingRequest request, string token)
        {
            var json = JsonConvert.SerializeObject(request); // convert from object to json
            // new request
            var httpcontent = new StringContent(json, Encoding.UTF8, "application/json");
            var client      = _httClientFactory.CreateClient();

            client.BaseAddress = new Uri("http://apieshop.somee.com");
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            var response = await client.PostAsync("/api/User/GetUserPaging", httpcontent);

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

            var users = JsonConvert.DeserializeObject <ResultApiGetUserPaging>(data);

            return(users.data);
        }
コード例 #10
0
        public async Task <IActionResult> Index(UserPagingRequest request)
        {
            request.PageIndex = request.PageIndex == 0?1:request.PageIndex;
            request.PageSize  = 1;
            request.keyword   = "";
            var token = HttpContext.Session.GetString("Token");
            var users = await _userApiClient.UserPagingRequest(request, token);

            var statusMessage = TempData["Result"];

            if (statusMessage != null)
            {
                ViewBag.statusMessage = statusMessage;
            }
            ViewBag.Data        = users.Items;
            ViewBag.TotalRecord = users.TotalRecord;
            return(View(request));
        }
コード例 #11
0
        public async Task <PagedResult <UserViewModel> > GetListUserPaged(UserPagingRequest model)
        {
            //throw new NotImplementedException();
            // Query tat ca user hien co
            var allUser = await _dbContext.Users.ToListAsync();

            // check keyword de xem co dang tim kiem hay phan loai ko
            // sau do gan vao Query o tren
            if (!string.IsNullOrEmpty(model.keyword))
            {
                allUser = allUser.Where(u => u.UserName.Contains(model.keyword) ||
                                        u.Email.Contains(model.keyword) ||
                                        u.PhoneNumber.Contains(model.keyword) ||
                                        u.Name.Contains(model.keyword)
                                        ).ToList();
            }
            // get total row from query
            int totalrecord = allUser.Count;
            // get so trang
            int soTrang = (totalrecord % model.PageSize == 0) ? (totalrecord / model.PageSize) : (totalrecord / model.PageSize + 1);
            // get data and paging
            var data = allUser.Skip((model.PageIndex - 1) * model.PageSize)
                       .Take(model.PageSize)
                       .Select(u => new UserViewModel()
            {
                Id          = u.Id,
                Name        = u.Name,
                Email       = u.Email,
                DoB         = u.DoB,
                PhoneNumber = u.PhoneNumber,
                UserName    = u.UserName,
                isActive    = u.isActive,
                AvatarURL   = u.Avatar
            })
                       .ToList();

            // return
            return(new PagedResult <UserViewModel>()
            {
                Items = data, TotalRecords = totalrecord, TotalPages = soTrang, PageIndex = model.PageIndex, PageSize = model.PageSize
            });
        }
コード例 #12
0
        // GET: Users
        public async Task <ActionResult> Index(string keyword, int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                //List<UserViewModel> lstAllUser = new List<UserViewModel>();
                var model = new UserPagingRequest()
                {
                    keyword   = keyword,
                    PageIndex = pageIndex,
                    PageSize  = pageSize
                };
                var token          = CookieEncoder.DecodeToken(Request.Cookies["access_token_cookie"]);
                var listUserResult = await _userManage.GetListUserPaged(model, token);

                return(View(listUserResult.data));
            }
            catch (Exception)
            {
                return(RedirectToAction("Index", "Home"));
            }
        }
コード例 #13
0
        public async Task <ResponseBase <PagedResult <UserViewModel> > > GetListUserPaged(UserPagingRequest model, string access_token)
        {
            if (access_token != null)
            {
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token);
            }
            var json        = JsonConvert.SerializeObject(model);
            var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
            var response    = await _httpClient.PostAsync("/api/users/paged/", httpContent);

            if (response.IsSuccessStatusCode)
            {
                var body = await response.Content.ReadAsStringAsync();

                ResponseBase <PagedResult <UserViewModel> > pagedResult = JsonConvert.DeserializeObject <ResponseBase <PagedResult <UserViewModel> > >(body);
                return(pagedResult);
            }
            else
            {
                return(null);
            }
        }
コード例 #14
0
        public async Task <ApiResult <PageResult <UserVMD> > > GetUserPagingAsync(UserPagingRequest request)
        {
            var result = await _userService.GetUserPagingAsync(request);

            return(result);
        }
コード例 #15
0
 public async Task <ApiResult <PageResult <UserVMD> > > GetUserPagingAsync(UserPagingRequest request)
 {
     return(await PostAsync <ApiResult <PageResult <UserVMD> > >("/api/User/GetUserPaging", request));
 }