Example #1
0
                public async Task <ResultModel <ListResponseModel <ProductDto> > > Handle(Query request,
                                                                                          CancellationToken cancellationToken)
                {
                    if (request == null)
                    {
                        throw new ArgumentNullException(nameof(request));
                    }

                    var spec = new ProductListQuerySpec(request);

                    var products = await _productRepository.FindAsync(spec);

                    var productModels = products.Select(x => new ProductDto
                    {
                        Id              = x.Id,
                        ProductCodeId   = x.ProductCodeId,
                        Active          = x.Active,
                        Cost            = x.Cost,
                        Name            = x.Name,
                        Quantity        = x.Quantity,
                        ProductCodeName = x.Code.Name,
                        Created         = x.Created,
                        Modified        = x.Updated
                    });

                    var totalProducts = await _productRepository.CountAsync(spec);

                    var resultModel =
                        new ListResponseModel <ProductDto>(productModels.ToList(), totalProducts, request.Page,
                                                           request.PageSize);

                    return(new ResultModel <ListResponseModel <ProductDto> >(resultModel));
                }
Example #2
0
        /// <summary>
        /// 在controller action result执行之前调用
        /// 统一数据返回类型
        /// </summary>
        /// <param name="context"></param>
        ///
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            var result = context.Result as ObjectResult;
            ListResponseModel <object> responseData = ResponseHandler.ListResponse <object>(result.Value);

            result.Value = responseData;
        }
Example #3
0
        public async Task <JsonResult> ListAsync(FullPath path, IEnumerable <string> intersect, IEnumerable <string> mimeTypes)
        {
            var response = new ListResponseModel();

            foreach (var item in await path.Directory.GetFilesAsync(mimeTypes))
            {
                if (!item.Attributes.HasFlag(FileAttributes.Hidden))
                {
                    response.List.Add(item.Name);
                }
            }

            foreach (var item in await path.Directory.GetDirectoriesAsync())
            {
                if (!item.Attributes.HasFlag(FileAttributes.Hidden))
                {
                    response.List.Add(item.Name);
                }
            }

            if (intersect.Any())
            {
                response.List.RemoveAll(x => !intersect.Contains(x));
            }

            return(await Json(response));
        }
Example #4
0
        public async Task <JsonResult> ListAsync(FullPath path, IEnumerable <string> intersect)
        {
            var response = new ListResponseModel();

            // Get all files and directories
            var items = await AzureStorageAPI.ListFilesAndDirectoriesAsync(path.Directory.FullName);

            // Add visible files
            foreach (var file in items.Where(i => i is CloudFile))
            {
                var f = new AzureStorageFile(file as CloudFile);
                if (!f.Attributes.HasFlag(FileAttributes.Hidden))
                {
                    response.List.Add(f.Name);
                }
            }

            // Add visible directories
            foreach (var dir in items.Where(i => i is CloudFileDirectory))
            {
                var d = new AzureStorageDirectory(dir as CloudFileDirectory);
                if (!d.Attributes.HasFlag(FileAttributes.Hidden))
                {
                    response.List.Add(d.Name);
                }
            }

            if (intersect.Any())
            {
                response.List.RemoveAll(l => !intersect.Contains(l));
            }

            return(await Json(response));
        }
Example #5
0
        public async Task <IActionResult> List([FromQuery] EventFilterRequestModel request)
        {
            var dateRange = request.ToDateRange();
            var result    = new PagedResult <IEvent>();

            if (request.ActingUserId.HasValue)
            {
                result = await _eventRepository.GetManyByOrganizationActingUserAsync(
                    _currentContext.OrganizationId.Value, request.ActingUserId.Value, dateRange.Item1, dateRange.Item2,
                    new PageOptions { ContinuationToken = request.ContinuationToken });
            }
            else if (request.ItemId.HasValue)
            {
                var cipher = await _cipherRepository.GetByIdAsync(request.ItemId.Value);

                if (cipher != null && cipher.OrganizationId == _currentContext.OrganizationId.Value)
                {
                    result = await _eventRepository.GetManyByCipherAsync(
                        cipher, dateRange.Item1, dateRange.Item2,
                        new PageOptions { ContinuationToken = request.ContinuationToken });
                }
            }
            else
            {
                result = await _eventRepository.GetManyByOrganizationAsync(
                    _currentContext.OrganizationId.Value, dateRange.Item1, dateRange.Item2,
                    new PageOptions { ContinuationToken = request.ContinuationToken });
            }

            var eventResponses = result.Data.Select(e => new EventResponseModel(e));
            var response       = new ListResponseModel <EventResponseModel>(eventResponses, result.ContinuationToken);

            return(new JsonResult(response));
        }
Example #6
0
        public async Task <ListResponseModel <TModel> > GetListRoleAsync <TModel>()
        {
            #region Validation
            var userInfo       = contextProvider.BusinessContext.PrincipalInfo;
            var validationData = new ValidationData(resultLocalizer);

            // validation logic here

            if (!validationData.IsValid)
            {
                throw validationData.BuildException();
            }
            #endregion

            var query = dbContext.Roles.AsNoTracking().OrderBy(o => o.Name);

            var responseModels = await query.DefaultProjectTo <TModel>().ToArrayAsync();

            var response = new ListResponseModel <TModel>
            {
                List       = responseModels,
                TotalCount = await query.CountAsync()
            };

            return(response);
        }
Example #7
0
        /// <summary>
        /// 返回数据是List的消息构造
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static ListResponseModel <T> ListResponse <T>(T data)
        {
            ListResponseModel <T> responseData = new ListResponseModel <T>();

            responseData.data = data;

            return(responseData);
        }
Example #8
0
 public async Task<IActionResult> List()
 {
     var collections = await _collectionRepository.GetManyByOrganizationIdAsync(
         _currentContext.OrganizationId.Value);
     // TODO: Get all CollectionGroup associations for the organization and marry them up here for the response.
     var collectionResponses = collections.Select(c => new CollectionResponseModel(c, null));
     var response = new ListResponseModel<CollectionResponseModel>(collectionResponses);
     return new JsonResult(response);
 }
        public async Task <IActionResult> List()
        {
            var groups = await _groupRepository.GetManyByOrganizationIdAsync(_currentContext.OrganizationId.Value);

            var groupResponses = groups.Select(g => new GroupResponseModel(g));
            var response       = new ListResponseModel <GroupResponseModel>(groupResponses);

            return(new JsonResult(response));
        }
Example #10
0
        public async Task <IActionResult> List()
        {
            var policies = await _policyRepository.GetManyByOrganizationIdAsync(_currentContext.OrganizationId.Value);

            var policyResponses = policies.Select(p => new PolicyResponseModel(p));
            var response        = new ListResponseModel <PolicyResponseModel>(policyResponses);

            return(new JsonResult(response));
        }
Example #11
0
        public async Task <IActionResult> List()
        {
            var users = await _organizationUserRepository.GetManyDetailsByOrganizationAsync(
                _currentContext.OrganizationId.Value);

            // TODO: Get all CollectionUser associations for the organization and marry them up here for the response.
            var memberResponses = users.Select(u => new MemberResponseModel(u, null));
            var response        = new ListResponseModel <MemberResponseModel>(memberResponses);

            return(new JsonResult(response));
        }
Example #12
0
        public async Task <JsonResult> List(string target)
        {
            FullPath          fullPath = ParsePath(target);
            ListResponseModel answer   = new ListResponseModel();

            foreach (var item in fullPath.Directory.GetFileSystemInfos())
            {
                answer.List.Add(item.Name);
            }
            return(await Json(answer));
        }
        public async Task GetList()
        {
            var query    = new ListQueryModel <PartnerDto>();
            var response = new ListResponseModel <PartnerDto>(query, 100, new List <PartnerDto>());

            _mockMediator.Setup(x => x.Send(query, It.IsAny <CancellationToken>()))
            .ReturnsAsync(response);

            var result = await _sut.GetList(query);

            Assert.IsAssignableFrom <OkObjectResult>(result.Result);
            Assert.AreEqual(response, ((OkObjectResult)result.Result).Value);
        }
Example #14
0
        public Task <ListResponseModel <TimeZoneOption> > GetTimeZoneOptionsAsync()
        {
            var timeZoneOptions = _memoryCache.GetOrCreate(CachingKeys.ListTimeZoneInfo,
                                                           (entry) => TimeZoneHelper.GetAllTimeZones().MapTo <TimeZoneOption>().ToArray());

            var response = new ListResponseModel <TimeZoneOption>()
            {
                List       = timeZoneOptions,
                TotalCount = timeZoneOptions.Length
            };

            return(Task.FromResult(response));
        }
Example #15
0
        public Task <ListResponseModel <RegionOption> > GetRegionOptionsAsync()
        {
            var countryOptions = _memoryCache.GetOrCreate(CachingKeys.ListRegionOptions,
                                                          (entry) => CultureHelper.GetDistinctRegions().MapTo <RegionOption>().ToArray());

            var response = new ListResponseModel <RegionOption>()
            {
                List       = countryOptions,
                TotalCount = countryOptions.Length
            };

            return(Task.FromResult(response));
        }
Example #16
0
        public async Task <ListResponseModel <TModel> > GetListDeletedAppUserAsync <TModel>()
        {
            var responseModels = await dbContext.QueryDeleted <AppUserEntity>()
                                 .AsNoTracking().DefaultProjectTo <TModel>().ToArrayAsync();

            var response = new ListResponseModel <TModel>
            {
                List       = responseModels,
                TotalCount = responseModels.Length
            };

            return(response);
        }
Example #17
0
        public async Task <JsonResult> ListAsync(FullPath path, IEnumerable <string> intersect, IEnumerable <string> mimeTypes)
        {
            var response = new ListResponseModel();

            // Get all files and directories
            var items    = AzureBlobStorageApi.ListFilesAndDirectoriesAsync(path.Directory.FullName);
            var itemList = items.ToList();

            var mimeTypesList = mimeTypes.ToList();

            // Add visible files
            foreach (var file in itemList.Where(i => !i.Name.EndsWith("/")))
            {
                var f = new AzureBlobFile(file);

                if (f.Attributes.HasFlag(FileAttributes.Hidden))
                {
                    continue;
                }

                if (mimeTypesList.Any() && !mimeTypesList.Contains(f.MimeType) && !mimeTypesList.Contains(f.MimeType.Type))
                {
                    continue;
                }

                response.List.Add(f.Name);
            }

            // Add visible directories
            foreach (var file in itemList.Where(i => i.Name.EndsWith("/")))
            {
                var d = new AzureBlobFile(file);

                if (!d.Attributes.HasFlag(FileAttributes.Hidden))
                {
                    response.List.Add(d.Name);
                }
            }

            var intersectList = intersect.ToList();

            if (intersectList.Any())
            {
                response.List.RemoveAll(l => !intersectList.Contains(l));
            }

            return(await Json(response));
        }
Example #18
0
        public Task <ListResponseModel <CurrencyOption> > GetCurrencyOptionsAsync()
        {
            var currencyOptions = _memoryCache.GetOrCreate(CachingKeys.ListCurrencyOptions,
                                                           (entry) =>
            {
                entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(CacheDurationInHours);
                return(Settings.Get <AppSettings>().SupportedRegionInfos.MapTo <CurrencyOption>().ToArray());
            });

            var response = new ListResponseModel <CurrencyOption>()
            {
                List       = currencyOptions,
                TotalCount = currencyOptions.Length
            };

            return(Task.FromResult(response));
        }
        public static IActionResult ToHttpResponse <TModel>(this ListResponseModel <TModel> response)
        {
            var statusCode = HttpStatusCode.OK;

            if (response.Model == null)
            {
                statusCode = HttpStatusCode.NotFound;
            }
            else if (response.DidError)
            {
                statusCode = HttpStatusCode.InternalServerError;
            }

            return(new ObjectResult(response)
            {
                StatusCode = (int)statusCode
            });
        }
Example #20
0
        public async Task <IActionResult> List()
        {
            var response = new ListResponseModel <Person>();

            try
            {
                var entity = await _servicePeople.Find(FilterDefinition <Person> .Empty);

                response.Model = entity;
            }
            catch (Exception ex)
            {
                response.DidError     = true;
                response.ErrorMessage = ex.Message;
            }

            return(response.ToHttpResponse());
        }
Example #21
0
        public IActionResult GetAll()
        {
            var response = new ListResponseModel <UserModel>();

            try
            {
                var users = _userRepository.GetAll();
                response.Model = UserModel.ToModels(users);
            }
            catch (Exception exception)
            {
                response.DidError = true;
                response.Message  = exception.Message;

                _logger.LogError(exception.Message);
            }

            return(response.ToHttpResponse());
        }
Example #22
0
        private async Task <IPAddress> GetDnsIpAsync()
        {
            DnsApiProcessor   api           = new(_apiKey);
            ListResponseModel responseModel = await api.ListRecords();

            if (responseModel.Reason != null)
            {
                throw new Exception("stub"); // TODO throw more specific exception
            }
            _editableEntries.Data = responseModel.Data.Where(entry => entry.Editable == 1 && entry.Record == _domain && entry.Type == _recordType).ToList();

            if (_editableEntries.Data.Count == 1)
            {
                return(IPAddress.Parse(_editableEntries.Data[0].Value));
            }
            else
            {
                throw new Exception("stub"); // TODO throw more specific exception
            }
        }
        public async Task <JsonResult> ListAsync(FullPath path)
        {
            var response = new ListResponseModel();

            foreach (var item in await path.Directory.GetFilesAsync())
            {
                if (!item.Attributes.HasFlag(FileAttributes.Hidden))
                {
                    response.List.Add(item.Name);
                }
            }
            foreach (var item in await path.Directory.GetDirectoriesAsync())
            {
                if (!item.Attributes.HasFlag(FileAttributes.Hidden))
                {
                    response.List.Add(item.Name);
                }
            }
            return(await Json(response));
        }
Example #24
0
 public ResultMessage <ListResponseModel <ClientLogResponseModel> > GetLogs(ClientLogListRequestModel model)
 {
     try
     {
         var dtos     = _LogService.GetAlLogs(model.PageIndex, model.PageSize, model.AppkeyId);
         var list     = dtos.Select(x => new ClientLogResponseModel(x)).ToList();
         var response = new ListResponseModel <ClientLogResponseModel>(list)
         {
             PageIndex       = dtos.PageIndex,
             PageSize        = dtos.PageSize,
             TotalRecord     = dtos.TotalCount,
             TotalPages      = dtos.TotalPages,
             HasPreviousPage = dtos.HasPreviousPage,
             HasNextPage     = dtos.HasNextPage
         };
         return(new ResultMessage <ListResponseModel <ClientLogResponseModel> >(response));
     }
     catch (NeedToShowFrontException e)
     {
         return(new ResultMessage <ListResponseModel <ClientLogResponseModel> >(StateCode.Fail, e.Message));
     }
 }
        public async Task <ListResponseModel <TModel> > GetListPostCategoryAsync <TModel>(
            ListPostCategoryRequestModel requestModel, ParsingConfig parsingConfig = null)
        {
            #region Validation
            var userInfo       = contextProvider.BusinessContext.PrincipalInfo;
            var validationData = new ValidationData(resultLocalizer);

            // validation logic here

            if (!validationData.IsValid)
            {
                throw validationData.BuildException();
            }
            #endregion

            IQueryable <PostCategoryEntity>        query = dbContext.PostCategory.AsNoTracking();
            IQueryable <ListPostCategoryJoinModel> joinedQuery;

            #region Filter
            if (requestModel.Ids?.Any() == true)
            {
                query = query.ByIds(requestModel.Ids);
            }

            string lang   = requestModel.Lang;
            string region = requestModel.Region;
            if (string.IsNullOrEmpty(lang))
            {
                lang = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            }

            var locQuery = dbContext.PostCategoryLocalization.ByCulture(lang, region);

            joinedQuery = from pc in query
                          from pcl in locQuery.Where(o => o.EntityId == pc.Id).Take(1).DefaultIfEmpty()
                          select new ListPostCategoryJoinModel
            {
                CreatedTime = pc.CreatedTime,
                Description = pcl.Description,
                Id          = pc.Id,
                Lang        = pcl.Lang,
                Region      = pcl.Region,
                Title       = pcl.Title
            };

            if (!string.IsNullOrWhiteSpace(requestModel.SearchTerm))
            {
                joinedQuery = joinedQuery.BySearchTerm(requestModel.SearchTerm);
            }
            #endregion

            var orgQuery = joinedQuery;

            #region Sorting
            var sortByArr = requestModel.GetSortByArr();
            if (!sortByArr.IsNullOrEmpty())
            {
                foreach (var field in sortByArr)
                {
                    var asc       = field[0] == QueryConsts.SortAscPrefix;
                    var fieldName = field.Remove(0, 1);

                    switch (fieldName)
                    {
                    case ListPostCategoryRequestModel.SortByTitle:
                    {
                        if (asc)
                        {
                            joinedQuery = joinedQuery.SequentialOrderBy(o => o.Title);
                        }
                        else
                        {
                            joinedQuery = joinedQuery.SequentialOrderByDesc(o => o.Title);
                        }
                    }
                    break;

                    default:
                        throw AppValidationException.From(resultLocalizer, ResultCode.InvalidPagingRequest);
                    }
                }
            }
            #endregion

            if (requestModel.Page > 0)
            {
                joinedQuery = joinedQuery.Limit(requestModel.Page, requestModel.PageLimit);
            }

            #region Projection
            var projectionArr = requestModel.GetFieldsArr().Select(o => ListPostCategoryRequestModel.Projections[o]).ToArray();
            var projectionStr = string.Join(',', projectionArr);

            var projectedQuery = joinedQuery.Select <TModel>(
                parsingConfig ?? DynamicLinqConsts.DefaultParsingConfig,
                $"new {typeof(TModel).FullName}({projectionStr})");
            #endregion

            var responseModels = await projectedQuery.ToArrayAsync();

            var response = new ListResponseModel <TModel>
            {
                List = responseModels,
            };

            if (requestModel.CountTotal)
            {
                response.TotalCount = await orgQuery.CountAsync();
            }

            return(response);
        }
Example #26
0
        public async Task <ListResponseModel <TModel> > GetListAppUserAsync <TModel>(
            ListAppUserRequestModel requestModel, ParsingConfig parsingConfig = null)
        {
            #region Validation
            var userInfo       = contextProvider.BusinessContext.PrincipalInfo;
            var validationData = new ValidationData(resultLocalizer);

            // validation logic here

            if (!validationData.IsValid)
            {
                throw validationData.BuildException();
            }
            #endregion

            IQueryable <AppUserEntity> query = dbContext.Users.AsNoTracking();

            #region Filter
            if (requestModel.Ids?.Any() == true)
            {
                query = query.ByIds(requestModel.Ids);
            }

            if (requestModel.UserName != null)
            {
                query = query.ByUsername(requestModel.UserName);
            }

            if (!string.IsNullOrWhiteSpace(requestModel.SearchTerm))
            {
                query = query.BySearchTerm(requestModel.SearchTerm);
            }

            if (requestModel.RegisteredFromDate != null)
            {
                query = query.CreatedFrom(requestModel.RegisteredFromDate.Value);
            }

            if (requestModel.RegisteredToDate != null)
            {
                query = query.CreatedTo(requestModel.RegisteredToDate.Value);
            }
            #endregion

            var orgQuery = query;

            #region Sorting
            var sortByArr = requestModel.GetSortByArr();
            if (!sortByArr.IsNullOrEmpty())
            {
                foreach (var field in sortByArr)
                {
                    var asc       = field[0] == QueryConsts.SortAscPrefix;
                    var fieldName = field.Remove(0, 1);

                    switch (fieldName)
                    {
                    case ListAppUserRequestModel.SortByUsername:
                    {
                        if (asc)
                        {
                            query = query.SequentialOrderBy(o => o.UserName);
                        }
                        else
                        {
                            query = query.SequentialOrderByDesc(o => o.UserName);
                        }
                    }
                    break;

                    default:
                        throw AppValidationException.From(resultLocalizer, ResultCode.InvalidPagingRequest);
                    }
                }
            }
            #endregion

            if (requestModel.Page > 0)
            {
                query = query.Limit(requestModel.Page, requestModel.PageLimit);
            }

            #region Projection
            var projectionArr = requestModel.GetFieldsArr().Select(o => ListAppUserRequestModel.Projections[o]).ToArray();
            var projectionStr = string.Join(',', projectionArr);

            var projectedQuery = query.Select <TModel>(
                parsingConfig ?? DynamicLinqConsts.DefaultParsingConfig,
                $"new {typeof(TModel).FullName}({projectionStr})");
            #endregion

            var responseModels = await projectedQuery.ToArrayAsync();

            var response = new ListResponseModel <TModel>
            {
                List = responseModels,
            };

            if (requestModel.CountTotal)
            {
                response.TotalCount = await orgQuery.CountAsync();
            }

            return(response);
        }