Ejemplo n.º 1
0
        public async Task <IActionResult> Details(Guid id, FilterType filter = FilterType.New, int page = 1)
        {
            Topic topic = await topicService.GetByIdAsync(id);

            if (topic == null || topic.IsHide)
            {
                return(NotFound());
            }
            if (page <= 0)
            {
                return(NotFound());
            }
            PagingResult <PostView> result = await this.postService.GetPagingResultAsync(id, PostResultType.All, page, filter);

            if (result.PageCount > 1 && page > result.PageCount)
            {
                return(NotFound());
            }
            TopicDetailsModel model = new TopicDetailsModel
            {
                Topic        = topic,
                PagingResult = result
            };

            return(View(model));
        }
Ejemplo n.º 2
0
        public static async Task <PagingResult <T> > PagingAsync <T>(this string sql, string connectionName, string orderByFields, int pageIndex = 1, int pageSize = 15, object param = null)
        {
            if (pageIndex <= 0)
            {
                pageIndex = 1;
            }

            if (pageSize <= 0)
            {
                pageSize = 15;
            }

            try
            {
                PagingResult <T> result = new PagingResult <T>
                {
                    PageIndex = pageIndex,
                    PageSize  = pageSize
                };
                var pagingSql = string.Format(DapperContext.PAGING_SQL_SCRIPT_TEMPLATE, sql, orderByFields, (pageIndex - 1) * pageSize + 1, pageIndex * pageSize);
                using (var conn = DapperContext.GetMySqlConnection(connectionName))
                {
                    result.Items = (await conn.ReadUncommitted().QueryAsync <T, long, T>(pagingSql,
                                                                                         (a, b) => { result.TotalCount = b; return(a); },
                                                                                         param,
                                                                                         splitOn: "TotalCount")).AsList();
                    return(result);
                }
            }
            catch (Exception ex)
            {
                throw ex.GetBaseException();
            }
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CosmosDbArgs"/> class.
 /// </summary>
 /// <param name="containerId">The <see cref="Container"/> identifier.</param>
 /// <param name="partitionKey">The optional <see cref="PartitionKey"/>.</param>
 /// <param name="paging">The <see cref="PagingResult"/>.</param>
 /// <param name="requestOptions">The optional <see cref="FeedOptions"/>.</param>
 public CosmosDbArgs(string containerId, PartitionKey partitionKey, PagingResult paging, QueryRequestOptions requestOptions = null)
 {
     ContainerId         = Check.NotEmpty(containerId, nameof(containerId));
     PartitionKey        = partitionKey;
     Paging              = Check.NotNull(paging, nameof(paging));
     QueryRequestOptions = requestOptions;
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Gets the entries.
        /// </summary>
        /// <param name="logFileName">Name of the log file.</param>
        /// <param name="page">The page.</param>
        /// <param name="searchQuery">The search query.</param>
        /// <returns></returns>
        public PagingResult <LogEntry> GetEntries(string logFileName, int?page = null, string searchQuery = null)
        {
            string location  = ApplicationSettings.Current.AlternateLogLocation;
            bool   showError = !string.IsNullOrWhiteSpace(location);
            PagingResult <LogEntry> entries = new PagingResult <LogEntry>();
            int pagingSize = ApplicationSettings.Current.DefaultPagingSize;

            this.TryExecute(
                () =>
            {
                ILogsClient client = this.factory.Create <ILogsClient>();
                entries            = client.GetLogEntries(logFileName, page, searchQuery, pagingSize);
            },
                () =>
            {
                if (!string.IsNullOrWhiteSpace(location))
                {
                    var logs = new List <LogEntry>();
                    logLoader.LoadLogs(logs, Path.Combine(ApplicationSettings.Current.AlternateLogLocation, logFileName));
                    entries = LogLoader.FilterLogs(logs, page, searchQuery, pagingSize);
                }
            },
                showError);

            return(entries);
        }
Ejemplo n.º 5
0
        public async Task <PagingResult <T> > ToPageListAsync(int pageIndex, int pageSize)
        {
            var fields = GetFields();
            var from   = GetFrom();

            var sqlBuilder = new SqlServerBuilder();
            var sql        = sqlBuilder.PagingSelect(from, fields, _where, _orderBy, pageIndex, pageSize);

            var command = new SqlCommand(sql);

            command.Parameters.AddRange(_parameters.Parameters);
            var param = new SqlParameter("@RecordCount", SqlDbType.Int)
            {
                Direction = ParameterDirection.Output
            };

            command.Parameters.Add(param);

            var result = new PagingResult <T>();

            using (var conn = new SqlConnection(_connectionString))
            {
                conn.Open();
                command.Connection = conn;
                using (var sdr = await command.ExecuteReaderAsync())
                {
                    var handler = new SqlDataReaderConverter <T>(_includeProperties.Select(p => p.PropertyName).ToArray());
                    result.Items = handler.ConvertToEntityList(sdr);
                }
            }

            result.RecordCount = (int)param.Value;
            return(result);
        }
Ejemplo n.º 6
0
 public UserManageModel(PagingResult <PersonView> pagingResult, string search, RoleFilterType roleFilter)
 {
     PagingResult         = pagingResult;
     Search               = search;
     RoleFilter           = roleFilter;
     this.SelectListItems = EnumUitls.ToSelectListItems <RoleFilterType>(false);
 }
Ejemplo n.º 7
0
    public void QueryProductINOut()
    {
        string rows        = Context.Request.Form["rows"];
        string page        = Context.Request.Form["page"];
        string workorder   = Context.Request.Form["workOrder"];
        string productname = Context.Request.Form["productName"];
        string batchnumber = Context.Request.Form["batch"];
        string status      = Context.Request.Form["status"];
        string starttime   = Context.Request.Form["startTime"];
        string endtime     = Context.Request.Form["endTime"];

        if (status == "4")
        {
            status = "";
        }
        PagingResult <ProductStockHistory> objs = _bal.FindProductStockHistory(status, workorder, productname, batchnumber, starttime, endtime, rows, page);

        if (objs != null && objs.ResultSet.Count > 0)
        {
            for (int i = 0; i < objs.ResultSet.Count; i++)
            {
                objs.ResultSet[i].StockHouse  = _bal.FindNameBySubCode(objs.ResultSet[i].StockHouse) == null ? objs.ResultSet[i].StockHouse : _bal.FindNameBySubCode(objs.ResultSet[i].StockHouse).SubName;
                objs.ResultSet[i].MANUFACTURE = _bal.FindNameBySubCode(objs.ResultSet[i].MANUFACTURE) == null ? objs.ResultSet[i].MANUFACTURE : _bal.FindNameBySubCode(objs.ResultSet[i].MANUFACTURE).SubName;
                objs.ResultSet[i].UNIT        = _bal.FindNameBySubCode(objs.ResultSet[i].UNIT) == null ? objs.ResultSet[i].UNIT : _bal.FindNameBySubCode(objs.ResultSet[i].UNIT).SubName;
                objs.ResultSet[i].UpdatedBy   = _bal.FindUserNameByCode(objs.ResultSet[i].UpdatedBy) == null ? objs.ResultSet[i].UpdatedBy : _bal.FindUserNameByCode(objs.ResultSet[i].UpdatedBy).UserName;
                objs.ResultSet[i].FromBy      = _bal.FindUserNameByCode(objs.ResultSet[i].FromBy) == null ? objs.ResultSet[i].FromBy : _bal.FindUserNameByCode(objs.ResultSet[i].FromBy).UserName;
            }
        }
        Dictionary <String, Object> map = new Dictionary <String, Object>();

        map.Add("total", objs.ResultCount);
        map.Add("rows", objs.ResultSet);
        Context.Response.Write(JsonConvert.SerializeObject(map));
    }
Ejemplo n.º 8
0
        /// <summary>
        /// 转换成dic
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static object ConvertToDictionary(object obj)
        {
            Dictionary <string, object> dic = obj as Dictionary <string, object>;

            //如果有分页就转换分页对象
            if (dic.ContainsKey("PageSize"))
            {
                PagingResult pagingResult = new PagingResult()
                {
                    PageSize   = Utils.ToInt(dic["PageSize"]),
                    PageIndex  = Utils.ToInt(dic["PageIndex"]),
                    TotalCount = Utils.ToInt(dic["TotalCount"])
                };
                if (dic["Data"].GetType().Name == "Object[]")
                {
                    pagingResult.Data = ConvertToDataTable(dic["Data"] as object[]);
                }
                return(pagingResult);
            }
            foreach (var key in dic.Keys)
            {
                if (dic[key].GetType().Name == "Object[]")
                {
                    dic[key] = ConvertToDataTable(dic[key] as object[]);
                    break;
                }
            }
            return(dic);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates a <see cref="CosmosDbArgs"/> with an <i>AutoMapper</i> <paramref name="mapper"/>.
        /// </summary>
        /// <param name="mapper">The <i>AutoMapper</i> <see cref="IMapper"/>.</param>
        /// <param name="containerId">The <see cref="Container"/> identifier.</param>
        /// <param name="partitionKey">The <see cref="Microsoft.Azure.Cosmos.PartitionKey"/>.</param>
        /// <param name="paging">The <see cref="PagingResult"/>.</param>
        /// <param name="requestOptions">The optional <see cref="FeedOptions"/>.</param>
        /// <param name="onCreate">Optional action to perform additional processing.</param>
        /// <returns>The <see cref="CosmosDbArgs"/>.</returns>
        public static CosmosDbArgs Create(IMapper mapper, string containerId, PagingResult paging, PartitionKey?partitionKey = null, QueryRequestOptions?requestOptions = null, Action <CosmosDbArgs>?onCreate = null)
        {
            var dbArgs = new CosmosDbArgs(mapper, containerId, paging, partitionKey, requestOptions);

            onCreate?.Invoke(dbArgs);
            return(dbArgs);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 获取所有按钮(分页)
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public PagingResult <GetPagingButtonsResponse> GetPagingButtons(GetPagingButtonsRequest request)
        {
            PagingResult <GetPagingButtonsResponse> result = null;
            var totalCount = 0;
            var startIndex = (request.PageIndex - 1) * request.PageSize + 1;
            var endIndex   = request.PageIndex * request.PageSize;

            using (var conn = DapperHelper.CreateConnection())
            {
                var multi  = conn.QueryMultiple(@"--获取所有按钮(分页)
                    SELECT rs.* FROM
                    (SELECT ROW_NUMBER() OVER (ORDER BY btn.created_time DESC) AS RowNum, btn.created_time AS CreatedTime, btn.last_updated_time AS LastUpdatedTIme,* 
                    FROM dbo.t_rights_button AS btn) AS rs
                    WHERE rs.RowNum BETWEEN @Start AND @End;

                    --获取所有按钮total
                    SELECT COUNT(btn.id) FROM dbo.t_rights_button AS btn;", new { @Start = startIndex, @End = endIndex });
                var query1 = multi.Read <GetPagingButtonsResponse>();
                var query2 = multi.Read <int>();
                totalCount = query2.First();

                result = new PagingResult <GetPagingButtonsResponse>(totalCount, request.PageIndex, request.PageSize, query1);
            }

            return(result);
        }
Ejemplo n.º 11
0
        public async Task <PagingResult <SdkReleaseHistory> > ReleaseHistory([FromRoute] long id, [FromQuery] PagingRequest <ReleaseHistoryGetRequest> value)
        {
            if (!ModelState.IsValid)
            {
                return(new PagingResult <SdkReleaseHistory>()
                {
                    code = (int)BasicControllerEnums.UnprocessableEntity,
                    message = ModelErrors()
                });
            }

            var query = sdkDB.ReleaseHistories.Where(x => x.SdkPackageId == id && x.UserID == UserId).AsQueryable();

            #region filter
            if (!string.IsNullOrWhiteSpace(value.q.remark))
            {
                query = query.Where(x => x.Remark.Contains(value.q.remark));
            }
            if (!string.IsNullOrWhiteSpace(value.q.tags))
            {
                query = query.Where(x => x.Tags.Contains(value.q.tags));
            }
            #endregion

            #region total
            var result = new PagingResult <SdkReleaseHistory>()
            {
                skip  = value.skip.Value,
                take  = value.take.Value,
                total = await query.CountAsync()
            };
            #endregion

            if (result.total > 0)
            {
                #region orderby
                if (!string.IsNullOrWhiteSpace(value.orderby))
                {
                    if (value.asc.Value)
                    {
                        query = query.OrderBy(value.orderby);
                    }
                    else
                    {
                        query = query.OrderByDescending(value.orderby);
                    }
                }
                #endregion

                #region pagingWithData
                var data = await query.Skip(value.skip.Value).Take(value.take.Value)
                           .ToListAsync();

                #endregion

                result.data = data;
            }

            return(result);
        }
Ejemplo n.º 12
0
        PagingResult <BlogModel> IBlogManager.GetBlogPageList(PagingModel model)
        {
            var result = new PagingResult <BlogModel>();
            var query  = Context.BlogDetails.Where(x => x.IsDeleted != true).OrderBy(model.SortBy + " " + model.SortOrder);

            if (!string.IsNullOrEmpty(model.Search))
            {
                query = query.Where(z => z.Title.Contains(model.Search) || z.Name.Contains(model.Search) || z.Description.Contains(model.Search));
            }

            if (model.Checked)
            {
                query = query.Where(x => x.IsFeaturedArticle == true);
            }

            var list = query
                       .Skip((model.PageNo - 1) * model.RecordsPerPage).Take(model.RecordsPerPage)
                       .ToList().Select(x => new BlogModel(x)).ToList();

            result.List       = list;
            result.Status     = ActionStatus.Successfull;
            result.Message    = "Blog List";
            result.TotalCount = query.Count();
            return(result);
        }
Ejemplo n.º 13
0
        public async Task OnGetAsync(string slug, string currentPage)
        {
            var tags = await _tagRepository.GetTags(slug);

            if (tags == null || !tags.Any())
            {
                Redirect("/");
            }

            var page = 1;

            if (!string.IsNullOrWhiteSpace(currentPage))
            {
                int.TryParse(currentPage.ToLower().Replace("page-", ""), out page);
            }

            if (page < 1)
            {
                page = 1;
            }

            PagingResult = await _matchRepository.GetMatchsByTag(page, tags.Select(x => x.Id.Value).ToArray());

            PagingResult.PageUrl   = $"/tag/{slug}";
            PagingResult.PageTitle = $"{tags.First().Name} - Latest Highlights and Full Matches";
        }
        public async Task <PagingResult <MasterKeyValue> > GetAllMastersAsync(string masterFor, int pageIndex, int pageSize)
        {
            //int pageNum = Convert.ToInt32(newPage);
            int totalCount = 0, totalPage = 0;

            pageIndex += 1;

            totalCount = _appDbContext.MasterKeyValue
                         .Where(m => m.Type.Equals(masterFor))
                         .ToList()
                         .Count();

            var data = await _appDbContext.MasterKeyValue
                       .Where(m => m.Type.Equals(masterFor))
                       .OrderBy(o => o.Value)
                       .Skip((pageIndex - 1) * pageSize)
                       .Take(pageSize)
                       .ToListAsync().ConfigureAwait(false);

            totalPage = (totalCount / pageSize) + ((totalCount % pageSize) > 0 ? 1 : 0);

            var pagingData = new PagingResult <MasterKeyValue>
            {
                Items      = data.AsEnumerable(),
                TotalCount = totalCount,
                TotalPage  = totalPage
            };

            return(await Task.FromResult(pagingData));
        }
        public override bool ProcessSource()
        {
            var metadata = DefineMetadata;

            Invocation.Proceed();
            ICache queryCache = RepositoryFramework.GetCacherForQuery(metadata);
            ICache cache      = RepositoryFramework.GetCacher(metadata);

            //IList接口
            PagingResult <TEntity> paging = (PagingResult <TEntity>)Invocation.ReturnValue;

            var ta       = TypeAccessor.GetAccessor(metadata.EntityType);
            var idGetter = ta.GetPropertyGetter(metadata.IdMember.Name);

            var spec = (ISpecification <TEntity>)Invocation.Arguments[0];

            if (spec == null)
            {
                throw new ArgumentException("第一个参数类型必须为 ISpecification<TEntity>");
            }

            //加入缓存
            cache.SetBatch(paging.Items.Cast <object>().Select(o => new CacheItem <object>(metadata.GetCacheKey(o), metadata.CloneEntity(o))), 1200);
            queryCache.Set(CacheKey, new PagingCacheData(paging.Items.Select(o => idGetter(o)))
            {
                ShardParams = spec.ShardParams,
                TotalCount  = paging.TotalCount
            });
            return(true);
        }
Ejemplo n.º 16
0
        public ServiceResponse GetUserGroupInStepSetting(Paging paging, string[] includes = null)
        {
            ServiceResponse         res   = new ServiceResponse();
            IEnumerable <UserGroup> query = null;
            PagingResult            data  = new PagingResult();

            if (!String.IsNullOrEmpty(paging.FilterString))
            {
                query = _userGrpRepository.GetMulti(x => x.UserGroupName.ToUpper().Contains(paging.FilterString.ToUpper()), includes);


                if (query == null)
                {
                    res.OnSuccess(data);
                    return(res);
                }
            }
            else
            {
                query = _userGrpRepository.GetAll(includes);
            }
            query = query.OrderBy(x => x.UserGroupName);

            data.TotalRecord = query.Count();
            data.PageData    = query.Skip((paging.CurrentPage - 1) * paging.PageSize).Take(paging.PageSize);
            res.OnSuccess(data);
            return(res);
        }
Ejemplo n.º 17
0
        PagingResult <CategoryListingModel> ICategoryManager.GetCategoriesPagedList(PagingModel model)
        {
            var result = new PagingResult <CategoryListingModel>();

            model.SortBy    = model.SortBy == null ? "CreatedOn" : model.SortBy;
            model.SortOrder = model.SortOrder == null ? "Desc" : model.SortOrder;

            var query = Context.Categories.Where(a => a.IsDeleted == false).AsEnumerable().OrderBy(model.SortBy + " " + model.SortOrder);

            if (!string.IsNullOrEmpty(model.Search))
            {
                query = query.Where(z =>
                                    ((z.Description != null && z.Description.ToLower().Contains(model.Search.ToLower())) ||
                                     (z.Name != null && (z.Name.ToLower()).Contains(model.Search.ToLower()))));
            }
            var list = query
                       .Skip((model.PageNo - 1) * model.RecordsPerPage).Take(model.RecordsPerPage)
                       .ToList().Select(x => new CategoryListingModel(x)).ToList();

            result.List       = list;
            result.Status     = ActionStatus.Successfull;
            result.Message    = "Category List";
            result.TotalCount = query.Count();
            return(result);
        }
Ejemplo n.º 18
0
        public static async Task <PagingResult <Game> > PagingAsync(this IRepository <Game> repository, PagingByIdModel model)
        {
            var userCollection = repository.Collection.Database.GetCollection <User>("User");
            var user           = await userCollection.Find(Builders <User> .Filter.Eq(e => e.Id, model.Id)).FirstOrDefaultAsync();

            if (user == null)
            {
                return(null);
            }
            var keys            = user.Logins?.Select(e => e.ProviderKey);
            var availableFilter = Builders <Game> .Filter.Where(e => e.IsRemoved != true);

            var statusFilter = Builders <Game> .Filter.Where(e => e.Status != GameStatus.Ended || e.Status != GameStatus.Rejected);

            var belongsToUserFilter =
                Builders <Game> .Filter.Where(e => e.CreatedBy == model.Id || e.OpponentId == model.Id);

            var socialInviteFilter = Builders <Game> .Filter.And(Builders <Game> .Filter.Where(e => e.OpponentExtInfo != null),
                                                                 Builders <Game> .Filter.In(e => e.OpponentExtInfo.Key, keys));

            var queryable    = repository.Collection.Find(Builders <Game> .Filter.And(availableFilter, statusFilter, Builders <Game> .Filter.Or(belongsToUserFilter, socialInviteFilter)));
            var pagingResult = new PagingResult <Game>
            {
                Total = await queryable.CountAsync(),
                Items = await queryable.Sort(Builders <Game> .Sort.Descending(e => e.CreatedAt)).Skip(model.Skip).Limit(model.Take).ToListAsync() ?? new List <Game>()
            };

            pagingResult.CanLoadMore = pagingResult.Total > model.Skip + model.Take;
            return(pagingResult);
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> Details(Guid id, FilterType filter = FilterType.New, int page = 1)
        {
            Tag tag = await tagService.SingleByIdAsync(id);

            if (tag == null)
            {
                return(NotFound());
            }
            if (page <= 0)
            {
                return(NotFound());
            }
            PagingResult <PostView> result = await this.postService.GetPagingResultAsync(tag, page, filter);

            if (result.PageCount > 1 && page > result.PageCount)
            {
                return(NotFound());
            }
            TagDetailsModel model = new TagDetailsModel
            {
                Tag          = tag,
                PagingResult = result
            };

            return(View(model));
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 分页
        /// </summary>
        /// <typeparam name="TDto">查询对象</typeparam>
        /// <param name="paging">分页对象</param>
        /// <param name="specification">查询对象</param>
        /// <param name="pagingBefore">分页前</param>
        /// <param name="pagingAfter">分页后</param>
        /// <returns></returns>
        public virtual IPagingResult <TDto> Paging <TDto>(IPaging paging,
                                                          ISpecification <TDto> specification,
                                                          Func <IQueryable <TDto>, IQueryable <TDto> > pagingBefore = null,
                                                          Func <IQueryable <TDto>, IQueryable <TDto> > pagingAfter  = null)
        {
            var query = this._storage.AsQueryable <TDto>();

            if (specification != null && specification.Expression != null)
            {
                query = query.Where(specification.Expression);
            }

            paging.TotalNumber = query.Count();

            if (pagingBefore != null)
            {
                query = pagingBefore(query);
            }

            query = query.Skip((paging.PageIndex - 1) * paging.PageSize)
                    .Take(paging.PageSize);
            if (pagingAfter != null)
            {
                query = pagingAfter(query);
            }
            return(PagingResult.Build(paging, query.ToList()));
        }
Ejemplo n.º 21
0
        public async Task <PagingResult <dynamic> > ToPageListAsync(int pageIndex, int pageSize)
        {
            var sqlBuilder = new SqlServerBuilder();
            var sql        = sqlBuilder.PagingSelect2008(_table, _fields, _where, _orderBy, pageIndex, pageSize);

            var command = new SqlCommand(sql);

            command.Parameters.AddRange(_parameters.Parameters);
            var param = new SqlParameter("@RecordCount", SqlDbType.Int)
            {
                Direction = ParameterDirection.Output
            };

            command.Parameters.Add(param);

            var result = new PagingResult <dynamic>();

            using (var conn = new SqlConnection(_connectionString))
            {
                conn.Open();
                command.Connection = conn;
                using (var sdr = await command.ExecuteReaderAsync())
                {
                    var handler = new SqlDataReaderSelectConverter();
                    result.Items = handler.ConvertToDynamicList(sdr);
                }
            }

            result.RecordCount = (int)param.Value;
            return(result);
        }
Ejemplo n.º 22
0
        private async Task <PagingResult <IRestaurantWithLinks> > GetPagingWithLinksInternal(
            PagingResult <IRestaurant> paging)
        {
            var cuisineTypes =
                await GetLink <RestaurantCuisineType>(paging.Items,
                                                      opt => paging.Items.Select(t => t.Id).Contains(opt.RestaurantId));

            var denyTypes =
                await GetLink <RestaurantDenyType>(paging.Items,
                                                   opt => paging.Items.Select(t => t.Id).Contains(opt.RestaurantId));


            return(new PagingResult <IRestaurantWithLinks>()
            {
                Total = paging.Total,
                Items = paging.Items.Select(t => new RestaurantWithLinks()
                {
                    Restaurant = t,
                    CuisineTypeIds = cuisineTypes.Where(w => w.RestaurantId == t.Id)
                                     .Select(s => s.CuisineTypeId)
                                     .ToArray(),
                    DenyTypeIds = denyTypes.Where(w => w.RestaurantId == t.Id)
                                  .Select(s => s.DenyTypeId).ToArray(),
                }).ToArray()
            });
        }
Ejemplo n.º 23
0
        public async Task <PagingResult <T> > PagingAsync(Expression <Func <T, bool> > filter, Expression <Func <IEnumerable <T>, dynamic> > orderBy, int pageIndex = 1, int pageSize = 20)
        {
            var result = new PagingResult <T> {
                PageIndex = pageIndex, PageSize = pageSize
            };

            result.TotalCount = await this.Collection.CountDocumentsAsync(filter);

            if (result.TotalCount == 0)
            {
                return(result);
            }

            if (orderBy == null)
            {
                orderBy = (i) => i.OrderBy(j => j.Id);
            }
            //T1: query type; T2: return type (select f1, f2, f3 ...)
            result.Items = await(await this.Collection.FindAsync(filter, new FindOptions <T, T>
            {
                Skip  = (pageIndex - 1) * pageSize,
                Limit = pageSize,
                Sort  = GetSortDefinition(orderBy),
            })).ToListAsync();
            return(result);
        }
Ejemplo n.º 24
0
        public async Task OnGetAsync(string slug, string currentPage)
        {
            var category = await _categoryRepository.GetCategory(slug);

            if (category == null)
            {
                Redirect("/");
            }

            var page = 1;

            if (!string.IsNullOrWhiteSpace(currentPage))
            {
                int.TryParse(currentPage.ToLower().Replace("page-", ""), out page);
            }

            if (page < 1)
            {
                page = 1;
            }

            PagingResult = await _matchRepository.GetMatchsByCategory(category.Id, page);

            PagingResult.PageUrl   = $"/league/{slug}";
            PagingResult.PageTitle = $"{category.Name} - Highlights and Full Matches";
        }
Ejemplo n.º 25
0
        public async Task <IActionResult> Get(int?pageIndex = 0, int?pageSize = 3, string nom = null)
        {
            Task <Model.Shop[]> getShopsTask = _context.Shops
                                               .Where(shop => nom == null || shop.Name.Contains(nom))
                                               .OrderBy(shop => shop.Id)
                                               .Skip(pageIndex.Value * pageSize.Value)
                                               .Take(pageSize.Value)
                                               .ToArrayAsync();

            Task <int> countShopsTask = _context.Shops.CountAsync(shop => nom == null || shop.Name.Contains(nom));

            await Task.WhenAll(getShopsTask, countShopsTask);

            //IEnumerable<Model.Shop> entities = await

            //int totalCount = await _context.Shops.CountAsync(shop => nom == null || shop.Name.Contains(nom));

            PagingResult <DTO.Shop> resultsPage = new PagingResult <DTO.Shop>()
            {
                Items      = getShopsTask.Result.Select(CreateDTOFromEntity),
                PageSize   = pageSize.Value,
                PageIndex  = pageIndex.Value,
                TotalCount = countShopsTask.Result
            };

            return(Ok(resultsPage));
        }
Ejemplo n.º 26
0
    public void QueryOutMaterial()
    {
        string rows         = Context.Request.Form["rows"];
        string page         = Context.Request.Form["page"];
        string msn          = Context.Request.Form["msn"];
        string materialCode = Context.Request.Form["materialCode"];
        string batch        = Context.Request.Form["batch"];
        string custName     = Context.Request.Form["custName"];
        string startTime    = Context.Request.Form["startTime"];
        string endTime      = Context.Request.Form["endTime"];


        PagingResult <MaterialStockHistory> objs = _bal.FindMaterialHistory("", "1^3", msn, materialCode, batch, custName, startTime, endTime, rows, page);

        if (objs != null && objs.ResultSet.Count > 0)
        {
            for (int i = 0; i < objs.ResultSet.Count; i++)
            {
                objs.ResultSet[i].StockHouse      = _bal.FindNameBySubCode(objs.ResultSet[i].StockHouse) == null ? objs.ResultSet[i].StockHouse : _bal.FindNameBySubCode(objs.ResultSet[i].StockHouse).SubName;
                objs.ResultSet[i].CustName        = _bal.FindCustNameByCode(objs.ResultSet[i].CustName) == null ? objs.ResultSet[i].CustName : _bal.FindCustNameByCode(objs.ResultSet[i].CustName).NAME;
                objs.ResultSet[i].UpdatedBy       = _bal.FindUserNameByCode(objs.ResultSet[i].UpdatedBy) == null ? objs.ResultSet[i].UpdatedBy : _bal.FindUserNameByCode(objs.ResultSet[i].UpdatedBy).UserName;
                objs.ResultSet[i].MaterialHandler = _bal.FindUserNameByCode(objs.ResultSet[i].MaterialHandler) == null ? objs.ResultSet[i].MaterialHandler : _bal.FindUserNameByCode(objs.ResultSet[i].MaterialHandler).UserName;
            }
        }
        Dictionary <String, Object> map = new Dictionary <String, Object>();

        map.Add("total", objs.ResultCount);
        map.Add("rows", objs.ResultSet);
        Context.Response.Write(JsonConvert.SerializeObject(map));
    }
Ejemplo n.º 27
0
        /// <summary>
        /// Sets the <see cref="HttpResponse.Headers"/> for the <see cref="PagingResult"/>.
        /// </summary>
        /// <param name="response">The <see cref="HttpResponse"/> to update.</param>
        /// <param name="paging">The <see cref="PagingResult"/> value to be added to the headers; <c>null</c> indicates to remove.</param>
        public static void SetPaging(HttpResponse response, PagingResult paging)
        {
            if (response == null)
            {
                throw new ArgumentNullException(nameof(response));
            }

            if (paging == null)
            {
                return;
            }

            if (paging.IsSkipTake)
            {
                response.Headers[WebApiConsts.PagingSkipHeaderName] = paging.Skip.ToString(System.Globalization.CultureInfo.InvariantCulture);
                response.Headers[WebApiConsts.PagingTakeHeaderName] = paging.Take.ToString(System.Globalization.CultureInfo.InvariantCulture);
            }
            else
            {
                response.Headers[WebApiConsts.PagingPageNumberHeaderName] = paging.Page.Value.ToString(System.Globalization.CultureInfo.InvariantCulture);
                response.Headers[WebApiConsts.PagingPageSizeHeaderName]   = paging.Take.ToString(System.Globalization.CultureInfo.InvariantCulture);
            }

            if (paging.TotalCount.HasValue)
            {
                response.Headers[WebApiConsts.PagingTotalCountHeaderName] = paging.TotalCount.Value.ToString(System.Globalization.CultureInfo.InvariantCulture);
            }

            if (paging.TotalPages.HasValue)
            {
                response.Headers[WebApiConsts.PagingTotalPagesHeaderName] = paging.TotalPages.Value.ToString(System.Globalization.CultureInfo.InvariantCulture);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// 个人提问
        /// </summary>
        public async Task <IActionResult> Question(Guid id, int page = 1)
        {
            if (page < 1)
            {
                return(NotFound());
            }
            PersonView person = await this.personService.GetPersonViewAsync(id);

            if (person == null || person.IsDelete)
            {
                return(NotFound());
            }
            else
            {
                Person p = ObjectMapper.Map <PersonView, Person>(person);
                PagingResult <PostView> pagingResult = await this.postService.GetPagingResultAsync(person, Library.Enums.PostResultType.Question, page);

                if (pagingResult.PageCount > 1 && page > pagingResult.PageCount)
                {
                    return(NotFound());
                }
                UserQuestionViewModel model = new UserQuestionViewModel(pagingResult, person);
                return(View(model));
            }
        }
Ejemplo n.º 29
0
        public static async Task <PagingResult <Friend> > PagingFriendsAsync(this IRepository <User> repository, PagingByIdModel model)
        {
            FilterDefinition <User> filter = Builders <User> .Filter.Where(e => e.Id == model.Id && !e.IsDelete);

            var searchFilter = !string.IsNullOrEmpty(model.SearchTextFormated) ?
                               Builders <UnwindUserFriend> .Filter.Where(e => e.Friends.Name.ToLower().Contains(model.SearchTextFormated)) :
                               Builders <UnwindUserFriend> .Filter.Empty;

            var queryable = repository.Collection.Aggregate()
                            .Match(filter)
                            .Unwind <User, UnwindUserFriend>(e => e.Friends)
                            .Match(searchFilter);
            var total = (await queryable.Group <UnwindUserFriend, string, TotalResult>(e => null, e => new TotalResult()
            {
                Result = e.Count()
            }).FirstOrDefaultAsync())?.Result ?? 0;
            var result = new PagingResult <Friend>
            {
                Items       = (await queryable.Skip(model.Skip).Limit(model.Take).ToListAsync())?.Select(e => e.Friends).ToList() ?? new List <Friend>(),
                CanLoadMore = total > model.Skip + model.Take,
                Total       = total
            };

            return(result);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Paging (just support version >= mysql 8.0)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="querySql"></param>
        /// <param name="orderByFields"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task <PagingResult <T> > PagingAsync <T>(string querySql, string orderByFields, int pageIndex = 1, int pageSize = 15, object param = null)
        {
            if (pageIndex <= 0)
            {
                pageIndex = 1;
            }

            if (pageSize <= 0)
            {
                pageSize = 15;
            }

            try
            {
                var result = new PagingResult <T>
                {
                    PageIndex = pageIndex,
                    PageSize  = pageSize
                };
                var pagingSql = string.Format(DapperContext.PAGING_SQL_SCRIPT_TEMPLATE, querySql, orderByFields, (pageIndex - 1) * pageSize + 1, pageIndex * pageSize);
                result.Items = (await Connection.QueryAsync <T, long, T>(pagingSql,
                                                                         (a, b) => { result.TotalCount = b; return(a); },
                                                                         param,
                                                                         splitOn: "TotalCount")).AsList();
                return(result);
            }
            catch (Exception ex)
            {
                throw ex.GetBaseException();
            }
        }
Ejemplo n.º 31
0
 public PagingResult<UploadFileItem> GetAll(int pageIndex, int pageSize)
 {
     var response = _client.GetAll(pageIndex, pageSize, _fileDir);
     var result = CommandResult.Create(response);
     var total = 0;
     var list = new List<UploadFileItem>();
     if (result.StatusCode == StatusCodes.Success)
     {
         total = int.Parse(result.Results["total"]);
         var items = result.Results["items"];
         if (!String.IsNullOrEmpty(items))
         {
             var fileKeys = items.Split(',');
             list.AddRange(fileKeys.Select(CreateUploadFileItem));
         }
     }
     var results = new PagingResult<UploadFileItem>(list)
                       {
                           CurrentPage = pageIndex,
                           PageSize = pageSize,
                           TotalItems = total
                       };
     return results;
 }
        public Task<PagingResult<User>> QueryUsers(string username, string claimType, string claimValue, Paging paging)
        {
            var users =
                this.userManager.Users
                    .WhereIf(() => !string.IsNullOrWhiteSpace(username), u => u.Id.Contains(username))
                    .WhereIf(() => !string.IsNullOrWhiteSpace(claimType) && !string.IsNullOrWhiteSpace(claimValue), 
                                u => u.Claims.Any(c => c.ClaimType == claimType && c.ClaimValue.Contains(claimValue)))
                    .Select(u => u.ToDomainModel());
            
            var pagedUsers = users.ToPagedList(paging.Page, paging.PageSize);
            var pagingResult = new PagingResult<User>(
                new PageDetails(pagedUsers.PageNumber, pagedUsers.PageSize, pagedUsers.Count, pagedUsers.PageCount, pagedUsers.TotalItemCount),
                pagedUsers);

            return Task.FromResult(pagingResult);
        }