public static LazyLoadedResult <T> GetPart <T>(this IQueryable <T> query, LazyLoadParameters parameters) where T : class { int count = query.Count(); if (parameters == null) { return(new LazyLoadedResult <T> { Result = query, Total = query.Count() }); } var result = query.Skip(parameters.Offset.HasValue ? parameters.Offset.Value : 0); result = parameters.Limit.HasValue? result.Take(parameters.Limit.Value): result; return(new LazyLoadedResult <T> { Result = result, Total = query.Count(), Offset = parameters.Offset, Limit = parameters.Limit }); }
public async Task <IActionResult> GetHistory(Guid deviceId, [FromQuery] LazyLoadParameters filters) { try { var deviceHistory = await _deviceHistoryService.GetHistoryByDeviceId(Token, deviceId, filters); _logger.LogInformation($"[GetHistory], deviceId = {deviceId}, status code = {StatusCodes.Status200OK}", deviceId, filters); return(Ok(deviceHistory)); } catch (ArgumentNullException ex) { _logger.LogInformation($"[GetHistory], deviceId = {deviceId}, status code = {StatusCodes.Status400BadRequest}, error = ex.Message", deviceId, filters); return(BadRequest(ex.Message)); } catch (KeyNotFoundException ex) { _logger.LogInformation($"[GetHistory], deviceId = {deviceId}, status code = {StatusCodes.Status404NotFound}, error = ex.Message", deviceId, filters); return(NotFound(ex.Message)); } catch (AccessException ex) { _logger.LogInformation($"[GetHistory], deviceId = {deviceId}, status code = {StatusCodes.Status403Forbidden}, error = ex.Message", deviceId, filters); return(new ContentResult { StatusCode = 403, Content = ex.Message }); } }
public async Task <IActionResult> GetAll([FromQuery] FilteringModel filter, [FromQuery] LazyLoadParameters lazyLoadFilters, [FromQuery] Sorting sorting) { try { var devices = await _deviceService.GetAll(filter, lazyLoadFilters, sorting, Token); return(Ok(devices)); } catch (ArgumentNullException ex) { return(BadRequest($"{ex.ParamName} ---- {ex.Message}")); } catch (ApplicationException ex) { return(BadRequest(ex.Message)); } }
public async Task ShouldReturnCommentsLazyLoadResult() { // Arrange Guid deviceId = _baseTest.Fixture.Create <Guid>(); string comment = _baseTest.Fixture.Create <string>(); Guid userId = _baseTest.Fixture.Create <Guid>(); string userName = _baseTest.Fixture.Create <string>(); string userNameNewForAssert = _baseTest.Fixture.Create <string>(); LazyLoadParameters filter = new LazyLoadParameters() { Limit = 1, Offset = 2 }; var commentList = _baseTest.Fixture.Build <Comment>() .With(x => x.Message, comment) .With(x => x.CreateOn, DateTime.UtcNow) .With(x => x.DeviceId, deviceId) .With(x => x.UserId, userId) .With(x => x.UserName, userName) .Without(x => x.Device) .CreateMany(4); var userStubList = _baseTest.Fixture.Build <UserModel>() .With(x => x.CompanyId, 2222) .With(x => x.DisplayName, userNameNewForAssert) .With(x => x.Id, userId) .CreateMany(1).ToList(); await _commrepository.AddRangeAsync(commentList); _httpServiceMock.Setup(x => x.GetUsersByIdTrustedAsync(It.IsAny <string>())).ReturnsAsync(userStubList); // Act var result = await _commentService.GetAllByDeviceIdAsync(It.IsAny <string>(), deviceId, filter); //Assert var commentsresult = result.Result.FirstOrDefault(); commentsresult.UserName.Should().Be(userNameNewForAssert); result.Result.Count().Should().Be(1); result.Total.Should().Be(4); }
public async Task ShouldReturnSuccsessWhithLazyLoadingWhenGetHistoryByDeviceId(int skip, int take) { // Arrange var request = _baseTest.Fixture.Create <BaseDeviceRequest>(); int firstCompanyId = 10; int secondCompanyId = 20; int deviceHistoryWhithUserCompanyCount = 3; int deviceHistoryWithAnotherCompanyCount = 7; var token = _baseTest.Fixture.Create <string>(); var device = _baseTest.Fixture.Build <Device>() .With(x => x.Id, Guid.NewGuid()) .With(x => x.CompanyId, firstCompanyId) .Without(x => x.DeviceHistory) .Create(); var deviceHistoryList = _baseTest.Fixture.Build <DeviceHistory>().With(x => x.DeviceId, device.Id) .With(x => x.CompanyId, firstCompanyId) .Without(x => x.Device) .CreateMany(deviceHistoryWhithUserCompanyCount).ToList(); deviceHistoryList.AddRange(_baseTest.Fixture.Build <DeviceHistory>().With(x => x.DeviceId, device.Id) .With(x => x.CompanyId, secondCompanyId) .Without(x => x.Device) .CreateMany(deviceHistoryWithAnotherCompanyCount)); _baseTest.DbContext.Devices.Add(device); _baseTest.DbContext.DeviceHistory.AddRange(deviceHistoryList); _baseTest.DbContext.SaveChanges(); var filters = new LazyLoadParameters { Offset = skip, Limit = take }; _validationHelperMock.Setup(x => x.GetCompanyIdByPermission(token, It.IsAny <string[]>(), null)).ReturnsAsync((int?)null); // Act var result = await _deviceHistoryService.GetHistoryByDeviceId(token, device.Id, filters); //Assert result.Total.Should().Be(_baseTest.DbContext.DeviceHistory.Count()); _baseTest.DbContext.DeviceHistory.Skip(skip).Take(take).Count().Should().Be(result.Result.Count()); result.Offset.Should().Be(skip); result.Limit.Should().Be(take); }
public async Task <IActionResult> Get(Guid deviceId, [FromQuery] LazyLoadParameters filters) { try { var comments = await _commentService.GetAllByDeviceIdAsync(Token, deviceId, filters); return(Ok(comments)); } catch (ArgumentNullException ex) { _logger.LogError(ex.Message); return(BadRequest(ex.Message)); } catch (AccessException ex) { _logger.LogError(ex.Message); return(new ContentResult { StatusCode = 403, Content = ex.Message }); } }
public async Task ShouldReturnSuccsessWhithLazyLoadingWhenGetAllDevice(int skip, int take) { // Arrange var request = _baseTest.Fixture.Create <BaseDeviceRequest>(); int firstCompanyId = 10; var token = _baseTest.Fixture.Create <string>(); CreateDevicesAndSetupMockWithParams(); var device = _baseTest.Fixture.Build <Device>().With(x => x.CompanyId, firstCompanyId) .CreateMany(10).ToList(); device.ForEach(x => { x.DeviceHistory = _baseTest.Fixture.Build <DeviceHistory>() .With(h => h.DeviceId, x.Id) .CreateMany() .ToList(); }); _baseTest.DbContext.Devices.AddRange(device); _baseTest.DbContext.SaveChanges(); var filters = new LazyLoadParameters { Offset = skip, Limit = take }; // Act var result = await _deviceService.GetAll(new FilteringModel(), filters, new Sorting(), token); //Assert result.Total.Should().Be(_baseTest.DbContext.Devices.Count()); _baseTest.DbContext.Devices.Skip(skip).Take(take).Count().Should().Be(result.Result.Count()); result.Offset.Should().Be(skip); result.Limit.Should().Be(take); }
/// <inheritdoc /> public async Task <LazyLoadedResult <CommentModel> > GetAllByDeviceIdAsync(string token, Guid deviceId, LazyLoadParameters filters = null) { var comments = (await _commentRepository.GetAllAsync(x => x.DeviceId == deviceId, filters)).Adapt <LazyLoadedResult <CommentModel> >(); Filters filter = new Filters(); filter.UsersId = comments.Result.Select(x => x.UserId.ToString()); string query = JsonConvert.SerializeObject(filter); var users = await _httpService.GetUsersByIdTrustedAsync(query); if (comments.Result.Count() > 0) { users.ForEach(x => comments.Result.FirstOrDefault(y => y.UserId == x.Id).UserName = x.DisplayName); } return(comments); }
/// <inheritdoc /> public async Task <LazyLoadedResult <DeviceModel> > GetAll(FilteringModel filter, LazyLoadParameters lazyLoadFilters, Sorting sorting, string token) { var resultLazy = new LazyLoadedResult <DeviceModel>(); var deviceList = new List <DeviceModel>(); var companyId = await _validationHelper.GetCompanyIdByPermission(token, new [] { Const.Permissions.Device.AdminRead }); List <TenantFullModel> tenants = new List <TenantFullModel>(); if (companyId != null) { filter.CompanyIds = new List <int> { companyId.Value }; var tenant = await _httpService.GetTenantSingleByCompanyId(companyId.Value, token); tenants.Add(tenant); } else { if (filter.TenantIds.Any()) { var tenantIdsString = filter.TenantIds.Select(x => x.ToString()).ToList(); tenants = await _httpService.GetTenantsByIds(token, GetQuery("TenantIds", tenantIdsString)); var companyIds = tenants.SelectMany(x => x.Companies).Select(x => x.Id).ToList(); filter.CompanyIds = filter.CompanyIds != null ? companyIds.Count > 0 ? filter.CompanyIds.Intersect(companyIds).ToList() : null : companyIds; } else { tenants = await _httpService.GetTenantsByIds(token); } } var devices = await _deviceRepository.GetWithoutIncludeAsync(GetFilterExpression(filter)); var devicesHistories = await _deviceHistoryRepository.GetAsync(); if (!devices.Any()) { return(resultLazy); } var compIds = (from device in devices select device.CompanyId.ToString()).ToList(); var branchIds = (from device in devices select device.BranchId.ToString()).ToList(); var deviceAndLastHistoryQuery = (from device in devices from history in devicesHistories.Where(x => x.DeviceId == device.Id).OrderByDescending(x => x.CreatedOn).Take(1) select new { Device = device, LastHistory = history }); var usersIds = deviceAndLastHistoryQuery.Where(x => x.LastHistory.LoggedInUserId.HasValue).Select(x => x.LastHistory.LoggedInUserId.ToString().ToLower()).Distinct().ToList(); //var companies = await _httpService.GetCompaniesByIds(GetQuery("CompanyIds", compIds), token); var companyTenant = tenants.SelectMany(tenant => tenant.Companies, (tenant, company) => new { Company = company, Tenant = tenant }); var branches = await _httpService.GetBranchesByIds(GetQuery("BranchIds", branchIds), token); var users = await _httpService.GetUsersByIdsAsync(token, GetQuery("UsersId", usersIds)); var fdeviceList = (from deviceInfo in deviceAndLastHistoryQuery join company in companyTenant on deviceInfo.Device.CompanyId equals company.Company.Id into _c from company in _c.DefaultIfEmpty() join branch in branches on deviceInfo.Device.BranchId equals branch.Id into _b from branch in _b.DefaultIfEmpty() join user in users on deviceInfo.LastHistory.LoggedInUserId equals user.Id into _u from user in _u.DefaultIfEmpty() select new DeviceModel { Id = deviceInfo.Device.Id, Udid = deviceInfo.Device.Udid, CreatedOn = deviceInfo.Device.CreatedOn, HexnodeUdid = deviceInfo.Device.HexnodeUdid, DeviceName = deviceInfo.Device.DeviceName, IsPending = deviceInfo.Device.IsPending, Latitude = deviceInfo.Device.Latitude, Longitude = deviceInfo.Device.Longitude, Radius = deviceInfo.Device.Radius, IsDeleted = deviceInfo.Device.IsDeleted, IsOnline = deviceInfo.LastHistory.IsOnline, IsInLocation = deviceInfo.LastHistory.IsInLocation, StatusSince = deviceInfo.LastHistory.CreatedOn, Branch = branch, Company = company.Company, Tenant = company.Tenant.Adapt <TenantModel>(), LoggedInAs = user, Phone = deviceInfo.Device.Phone, CurrentDeviceLocationLatitude = deviceInfo.LastHistory.CurrentDeviceLocationLatitude, CurrentDeviceLocationLongitude = deviceInfo.LastHistory.CurrentDeviceLocationLongitude, }); resultLazy = GetSorted(fdeviceList, sorting).GetPart(lazyLoadFilters); return(resultLazy); }
public async Task <LazyLoadedResult <Comment> > GetAllAsync(Expression <Func <Comment, bool> > predicate, LazyLoadParameters filters) => await Task.FromResult(Data.Where(predicate).OrderByDescending(x => x.CreateOn).GetPart(filters));
/// <inheritdoc /> public async Task <LazyLoadedResult <DeviceHistoryModel> > GetHistoryByDeviceId(string token, Guid deviceId, LazyLoadParameters filters = null) { if (string.IsNullOrWhiteSpace(token)) { throw new ArgumentNullException(nameof(token)); } var device = await _deviceRepository.GetAsync(deviceId); if (device == null) { throw new KeyNotFoundException($"Device with id: {deviceId} not found"); } IQueryable <DeviceHistory> deviceHistory = await _deviceHistoryRepository.GetAsync(x => x.DeviceId == device.Id); var scopeArray = new[] { Const.Permissions.History.AdminRead }; var companyId = await _validationHelper.GetCompanyIdByPermission(token, scopeArray); if (companyId.HasValue && companyId != device.CompanyId) { throw new AccessException(); } else if (companyId == device.CompanyId) { deviceHistory = deviceHistory.Where(x => x.CompanyId == device.CompanyId); } return(deviceHistory.OrderByDescending(x => x.CreatedOn).GetPart(filters).Adapt <LazyLoadedResult <DeviceHistoryModel> >()); }
public IActionResult GetTotalInCompanies([FromQuery] List <string> companyIds, [FromQuery] UserSortingParameters sorting, [FromQuery] LazyLoadParameters lazyParameters) { try { var userRole = HttpContext.User.Claims.FirstOrDefault(x => x.Type == Consts.RoleClaimType)?.Value; if (!string.IsNullOrEmpty(userRole) && !Consts.Roles.GlobalAdmins.Contains(userRole.ToLower())) { return(new ContentResult { StatusCode = 403 }); } var usersCount = _userService.GetUsersCountInCompanies(companyIds, sorting, lazyParameters); return(Ok(usersCount)); } catch (ArgumentException ex) { return(BadRequest(ex.Message)); } }
/// <inheritdoc /> public Dictionary <string, int> GetUsersCountInCompanies(List <string> companyIds, UserSortingParameters sorting, LazyLoadParameters lazyParameters) { var result = new Dictionary <string, int>(); var usersInCache = _cache.Get <List <AzureUser> >(Consts.Cache.UsersKey); if (companyIds != null && companyIds.Any()) { foreach (var companyId in companyIds) { var usersInCompanyCount = usersInCache.Where(x => x.CompanyId == companyId).Count(); result.Add(companyId, usersInCompanyCount); } return(result); } var grouped = usersInCache.GroupBy(x => x.CompanyId); if (sorting?.By == Consts.UsersSorting.Descending) { grouped = grouped.OrderByDescending(x => x.Count()); } if (sorting?.By == Consts.UsersSorting.Ascending) { grouped = grouped.OrderBy(x => x.Count()); } grouped = grouped.Where(x => x.Key != null) .Skip(lazyParameters?.Offset ?? 0) .Take(lazyParameters?.Limit ?? grouped.Count()); foreach (var value in grouped) { result.Add(value.Key, value.Count()); } return(result); }