public static IHtmlString PagerInfo(this HtmlHelper helper, PageResult page)
 {
     var html = "<input type=\"hidden\" class=\"total-pages\" value=\"" + page.TotalPages +
                "\" /><input type=\"hidden\" class=\"page-index\" value=\"" + page.PageIndex + "\" />"
                + "<input type=\"hidden\" class=\"page-rows\" value=\"" + page.TotalCount + "\" />";
     return helper.Raw(html);
 }
示例#2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["p"] != null)
            PageIndex = Convert.ToInt32(Request["p"]);
        else
            PageIndex = 1;

        //根据categoryid,分类显示列表

        object cache = Cache[TableName + condition];
        if (cache == null)
        {
            _DataSource = DataPager.PageState(TableName, PageSize, condition);
            Cache.Add(TableName + condition, _DataSource, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, 5), System.Web.Caching.CacheItemPriority.Default, null);
        }
        else
        {
            _DataSource = (PageResult)cache;
        }

        _BaseURL = Request.Url.AbsolutePath + '?';
        foreach (var p in Request.QueryString.AllKeys)
        {
            if (p != "p")
                _BaseURL += p + "=" + Request.QueryString[p] + '&';
        }
    }
示例#3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["p"] != null)
            pageIndex = Convert.ToInt32(Request["p"]);
        else
            pageIndex = 1;

        //根据categoryid,分类显示列表

        if (Request["PlanClassifyID"] != null)//&& Request["month"] == "")
        {
            condition = "StationPlan.IsDelete = 0 and PlanClassifyID = " + Convert.ToInt32(Request["PlanClassifyID"]);
        }

        else
        {
            condition = "StationPlan.IsDelete = 0";
        }

        DataPager p = new ExclusiveDataPager();
        result = p.PageData(pageIndex, pageSize, "StationPlan", "*", "StationPlanID", condition, "desc");

        GridView1.DataSource = result.Result;
        GridView1.DataBind();
    }
示例#4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // FAQList.DataSource = FAQ.GetQuestionCategory(false, Cache);

        //   FAQList.DataBind();
        if (Request["p"] != null)
        {
            pageIndex = Convert.ToInt32(Request["p"]);
        }
        else
        {
            pageIndex = 1;

        }
        if (Request["OilProjectDirectionID"] != null)
        {
            condition = "OilProject.IsDelete = 0 and OilProject.Confirm = True and OilProject.OilProjectDirectionID = OilProjectDirection.OilProjectDirectionID and OilProjectDirection.OilProjectDirectionID=" + Convert.ToInt32(Request["OilProjectDirectionID"]);
        }
        else
        {
            condition = "OilProject.IsDelete = 0 and OilProject.Confirm = True and OilProject.OilProjectDirectionID = OilProjectDirection.OilProjectDirectionID ";
        }
        DataPager p = new ExclusiveDataPager();

        result_direction = p.PageData(1, 100, "OilProjectDirection", "*", "OilProjectDirectionID", condition_direction, null);
        result1 = p.PageData(pageIndex, pageSize, "OilProject,OilProjectDirection", "*", "OilProjectID", condition, "desc");
        ProjectList.DataSource = result_direction.Result;
        ProjectList.DataBind();

        GridView1.DataSource = result1.Result;
        GridView1.DataBind();
    }
        public async Task<HttpResponseMessage> GetProduct(ProductSearch Condition, PageCommand Page = null)
        {

            var page = Page ?? new PageCommand();

            var Query = productRepo.Find(t => t.Input_Date >= Condition.Start, t => t.skus);

            if (Condition.Brands != null && Condition.Brands.Count != 0)
                Query = Query.Where(t => Condition.Brands.Contains(t.Brand));

            if (Condition.End.HasValue)
                Query = Query.Where(t => t.Input_Date <= Condition.End.Value);

            try
            {
                var List = await Task.Factory.StartNew(() => Query.OrderBy(t => 1).AsNoTracking().ToPagedList(page.PageIndex, page.PageSize));

                var Result = new PageResult<product>()
                {
                    PageIndex = List.PageNumber,
                    PageSize = List.PageSize,
                    TotalItem = List.TotalItemCount,
                    TotalPage = List.PageCount,
                    PageList = List.Select(t => t.Convert())
                };

                return Request.CreateResponse(HttpStatusCode.OK, Result);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, new OperationResult() { err_code = ErrorEnum.sys_error, err_info = ex.Message });
            }
        }
示例#6
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["p"] != null)
            pageIndex = Convert.ToInt32(Request["p"]);
        else
            pageIndex = 1;

        //根据categoryid,分类显示列表

        if (Request["categoryid"] != null)//&& Request["month"] == "")
        {
            condition = "NewsCategoryID = " + Convert.ToInt32(Request["categoryid"]);
        }

        //      根据年份与月份显示
        if (Request["NewsYear"] != null && Request["month"] == "")
        {
            condition = "NewsYear = " + Convert.ToInt32(Request["NewsYear"]);
        }
        if (Request["NewsYear"] != null && Request["month"] != "")
        {

            condition = "NewsYear = " + Convert.ToInt32(Request["NewsYear"]) + "And NewsMonth= " + Convert.ToInt32(Request["month"]);

        }

        DataPager p = new ExclusiveDataPager();
        result = p.PageData(pageIndex, pageSize, "News", "*", "NewsID", condition, "desc");

        GridView1.DataSource = result.Result;
        GridView1.DataBind();
    }
 public PageResult<string> GetResult(int page, FieldCriteria[] criterias)
 {
     var provider = new DbDataProvider();
     var result = new PageResult<string>();
     result.TotalCount = Convert.ToInt32(provider.Count(criterias));
     result.PageCount = result.TotalCount / pageSize + 1;
     result.Page = page;
     result.Result = provider.GetEntitiesId(page, pageSize, criterias);
     return result;
 }
示例#8
0
        private PageResult GetPageResult(string pagina)
        {
            var date = Regex.Match(pagina, @"<date>(\d+)</date>");
            var number = Regex.Match(pagina, @"<td>Laat</td> <td class=""numeric last"">(\d+,\d+)</td>");

            var pageResult = new PageResult();

            if (date.Groups.Count == 2)
            {
                pageResult.Date = date.Groups[1].Value;
            }

            if (number.Groups.Count == 2)
            {
                pageResult.Price = number.Groups[1].Value;
            }

            return pageResult;
        }
示例#9
0
    protected void Page_Load(object sender, EventArgs e)
    {
        XmlDocument document = new XmlDocument();
        document.Load(Server.MapPath("~/Footer.xml"));
        //    picture = ResolveUrl(document.DocumentElement.SelectSingleNode("picture").InnerText);
        if (Request["newsId"] != null)
        {
            newsFrame = "NewsContent.aspx?newsid=" + Request["newsId"];
        }
        else
        {
            newsFrame = "NewsTempate.aspx";
        }
        //新闻列表更新

        if (Request["p"] != null)
            pageIndex = Convert.ToInt32(Request["p"]);
        else
            pageIndex = 1;

        //根据categoryid,分类显示列表

        if (Request["categoryid"] != null)//&& Request["month"] == "")
        {
            condition += " and NewsCategoryID = " + Convert.ToInt32(Request["categoryid"]);
        }

        //      根据年份与月份显示
        if (Request["NewsYear"] != null && Request["month"] == "")
        {
            condition += " and NewsYear = " + Convert.ToInt32(Request["NewsYear"]);
        }
        if (Request["NewsYear"] != null && Request["month"] != "")
        {
            condition += " and NewsYear = " + Convert.ToInt32(Request["NewsYear"]) + "And NewsMonth= " + Convert.ToInt32(Request["month"]);
        }

        DataPager p = new ExclusiveDataPager();
        result = p.PageData(pageIndex, pageSize, "News", "*", "NewsID", condition, "desc");

        GridView1.DataSource = result.Result;
        GridView1.DataBind();
    }
示例#10
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // FAQList.DataSource = FAQ.GetQuestionCategory(false, Cache);
           //   FAQList.DataBind();
        if (Request["p"] != null)
        {
            pageIndex = Convert.ToInt32(Request["p"]);
            i = (Convert.ToInt32(Request["p"]) - 1) * 7 + 1;
        }
        else
        {
            pageIndex = 1;
            i = 1;
        }
        DataPager p = new ExclusiveDataPager();
        result = p.PageData(pageIndex, pageSize, "FAQ", "*", "FAQID", condition, "desc");

        FAQList.DataSource = result.Result;
        FAQList.DataBind();
    }
        public PageResult<CharterOut> GetByFilter(long companyId, int pageSize, int pageIndex)
        {
            var res = new PageResult<CharterOut>();

            var strategy = new ListFetchStrategy<Charter>(Enums.FetchInUnitOfWorkOption.NoTracking);

            IQueryable<CharterOut> query = this.GetAll(strategy).OfType<CharterOut>().OrderBy(p => p.Id)
                .Where(c => c.OwnerId == companyId && c.CharterType == CharterType.Start).AsQueryable();

            res.Result = query.Skip(pageSize * (pageIndex - 1))
                .Take(pageSize).ToList();

            res.TotalCount = query.Count();

            res.TotalPages = Convert.ToInt32(Math.Ceiling(decimal.Divide(res.TotalCount, pageSize)));

            res.CurrentPage = pageIndex + 1;

            return res;
        }
示例#12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //  XmlDocument document = new XmlDocument();
        //  document.Load(Server.MapPath("~/Footer.xml"));
        //   picture = ResolveUrl(document.DocumentElement.SelectSingleNode("picture").InnerText);
        if (Request["p"] != null)
        {
            pageIndex = Convert.ToInt32(Request["p"]);
        }
        else
        {
            pageIndex = 1;

        }
           if (Request["NewRecruitsCategoryID"] != null)
        {
            condition = "NewRecruits.IsDelete = 0 and NewRecruits.NewRecruitsCategoryID = NewRecruitsCategory.NewRecruitsCategoryID  and NewRecruits.OilProjectDirectionID = OilProjectDirection.OilProjectDirectionID and NewRecruitsCategory.NewRecruitsCategoryID=" + Convert.ToInt32(Request["NewRecruitsCategoryID"]);
        }
           else if (Request["OilProjectDirectionID"] != null)
        {
            condition = "NewRecruits.IsDelete = 0 and NewRecruits.NewRecruitsCategoryID = NewRecruitsCategory.NewRecruitsCategoryID  and NewRecruits.OilProjectDirectionID = OilProjectDirection.OilProjectDirectionID and NewRecruits.OilProjectDirectionID=" + Convert.ToInt32(Request["OilProjectDirectionID"]);
        }else
        {
            condition = "NewRecruits.IsDelete = 0 and NewRecruits.NewRecruitsCategoryID = NewRecruitsCategory.NewRecruitsCategoryID  and NewRecruits.OilProjectDirectionID = OilProjectDirection.OilProjectDirectionID";
        }

        DataPager p = new ExclusiveDataPager();

        result_category = p.PageData(1, 100, "NewRecruitsCategory", "*", "NewRecruitsCategoryID", condition_category, "asc");
         //   result_direction = p.PageData(1, 10, "OilProjectDirectionTitle", "*", "OilProjectDirectionID", condition_direction, "asc");
        result1 = p.PageData(pageIndex, pageSize, "NewRecruits,NewRecruitsCategory,OilProjectDirection", "*", "NewRecruitsID", condition, "asc");
        NewRecruitsList.DataSource = result_category.Result;
         //  OilProjectList.DataSource = result_direction.Result;

        NewRecruitsList.DataBind();
         // OilProjectList.DataBind();

        GridView1.DataSource = result1.Result;
        GridView1.DataBind();
    }
示例#13
0
    //not completed
    /// <summary>
    /// 查询分页状态,如总页数、总记录条数。一般由.net进行缓存优化效率。
    /// </summary>
    /// <param name="table">数据库表</param>
    /// <param name="pageSize">页大小</param>
    /// <param name="condition">附加的查询条件</param>
    /// <returns></returns>
    public static PageResult PageState(string table,int pageSize, string condition)
    {
        PageResult pr = new PageResult()
        {
            PageIndex = -1,
            Result = null,
            PageSize = pageSize,
            TotalPage = 0,
            TotalRow = 0
        };
        string sql = "select count(*) from {0} {1}";
        sql = string.Format(sql,
            table,
            condition == null ? "" : "where " + condition);

        DbDataReader r = DBHelper.INST.ExecuteSqlDR(sql);
        r.Read();
        pr.TotalRow = r.GetInt32(0);
        pr.TotalPage = pr.TotalRow % pr.PageSize == 0 ? pr.TotalRow / pr.PageSize : pr.TotalRow / pr.PageSize + 1;

        return pr;
    }
        public void WriteObjectInline_Sets_InlineCount_OnWriteStart()
        {
            // Arrange
            Mock<ODataEntrySerializer> customerSerializer = new Mock<ODataEntrySerializer>(_customersType.ElementType(), ODataPayloadKind.Entry);
            ODataSerializerProvider provider = ODataTestUtil.GetMockODataSerializerProvider(customerSerializer.Object);
            var mockWriter = new Mock<ODataWriter>();

            Uri expectedNextLink = new Uri("http://nextlink.com");
            long expectedInlineCount = 1000;

            var result = new PageResult<Customer>(_customers, expectedNextLink, expectedInlineCount);
            mockWriter
                .Setup(m => m.WriteStart(It.Is<ODataFeed>(feed => feed.Count == expectedInlineCount)))
                .Verifiable();

            _serializer = new ODataFeedSerializer(_customersType, provider);

            // Act
            _serializer.WriteObjectInline(result, mockWriter.Object, _writeContext);

            // Assert
            mockWriter.Verify();
        }
示例#15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // FAQList.DataSource = FAQ.GetQuestionCategory(false, Cache);
        //   FAQList.DataBind();
        if (Request["p"] != null)
        {
            pageIndex = Convert.ToInt32(Request["p"]);

        }
        else
        {
            pageIndex = 1;

        }
        if (Request["ProjectID"] != null)//&& Request["month"] == "")
        {
            condition = "ProjectID = " + Convert.ToInt32(Request["ProjectID"]);
        }
        DataPager p = new ExclusiveDataPager();
        result = p.PageData(pageIndex, pageSize, "NewRecruits", "*", "NewRecruitsID", condition, "desc");

        NewRecruitsList.DataSource = result.Result;
        NewRecruitsList.DataBind();
    }
        public void Does_replace_bindings()
        {
            var context = new TemplateContext
            {
                Args =
                {
                    ["contextTitle"]   = "The title",
                    ["contextPartial"] = "bind-partial",
                    ["contextTag"]     = "h2",
                    ["a"] = "foo",
                    ["b"] = "bar",
                }
            }.Init();

            context.VirtualFiles.WriteFile("_layout.html", @"
<html>
  <title>{{ title }}</title>
</head>
<body>
{{ contextPartial | partial({ title: contextTitle, tag: contextTag, items: [a,b] }) }}
{{ page }}
</body>");

            context.VirtualFiles.WriteFile("bind-partial.html", @"
<{{ tag }}>{{ title | upper }}</{{ tag }}>
<p>{{ items | join(', ') }}</p>");

            context.VirtualFiles.WriteFile("bind-page.html", @"
<section>
{{ pagePartial | partial({ tag: pageTag, items: items }) }}
</section>
");

            var result = new PageResult(context.GetPage("bind-page"))
            {
                Args =
                {
                    ["title"]       = "Page title",
                    ["pagePartial"] = "bind-partial",
                    ["pageTag"]     = "h3",
                    ["items"]       = new[] { 1, 2, 3 },
                }
            }.Result;

            Assert.That(result.NormalizeNewLines(), Is.EqualTo(@"
<html>
  <title>Page title</title>
</head>
<body>

<h2>THE TITLE</h2>
<p>foo, bar</p>

<section>

<h3>PAGE TITLE</h3>
<p>1, 2, 3</p>
</section>

</body>
".NormalizeNewLines()));
        }
示例#17
0
        /// <summary>
        /// 查询工作联系单
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="authority"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="orderBy"></param>
        /// <param name="keyword"></param>
        /// <param name="ContactDeper"></param>
        /// <param name="ContactName"></param>
        /// <param name="ContactDate"></param>
        /// <returns></returns>
        public PageResult GetWorkContactPageResult(string loginName, string UserName, string authority, int page, int rows, string orderBy, string keyword, string ContactDeper, string ContactConten, string startDate, string EndDate, string Type = "")
        {
            PageResult result = new PageResult();

            try
            {
                PageInfo pageInfo = new PageInfo();
                pageInfo.CurrentPageIndex = page;
                pageInfo.PageSize         = rows;
                pageInfo.QueryFields      = "*";
                pageInfo.Orderby          = orderBy;
                if (Type == "2")
                {
                    pageInfo.TableName = "View_ContactReply";
                }
                else
                {
                    pageInfo.TableName = "TblContact";
                }

                StringBuilder strSql = new StringBuilder("1=1");
                if (!string.IsNullOrEmpty(Type))
                {
                    if (Type == "0")
                    {
                        strSql.AppendFormat(" and (State ='{0}' or State is NULL) and CreateName='{1}'", Type, UserName);
                    }
                    else if (Type == "1")
                    {
                        strSql.AppendFormat(" and State ='{0}' and (CreateName='{1}')", Type, UserName);
                    }
                    else if (Type == "2")
                    {
                        strSql.AppendFormat(" and (LoginName = '{0}')", loginName);
                    }
                }
                //if (!string.IsNullOrEmpty(ContactDeper))
                //{
                //    strSql.AppendFormat(" and CreateNameDeper like '%" + ContactDeper + "%'");
                //}
                if (!string.IsNullOrEmpty(ContactConten))
                {
                    strSql.AppendFormat(" and ContactConten like '%" + ContactConten + "%'");
                }
                if ((!string.IsNullOrEmpty(startDate)))
                {
                    strSql.AppendFormat(" and ContactDate >='{0}' ", startDate);
                }
                if ((!string.IsNullOrEmpty(EndDate)))
                {
                    strSql.AppendFormat(" and ContactDate <='{0}' ", EndDate);
                }
                pageInfo.Where = strSql.ToString();
                //查询数据
                if (Type == "2")
                {
                    result = CommonHelper.ListPageResult <Bitshare.PTMM.Model.View_ContactReply>(pageInfo);
                }
                else
                {
                    result = CommonHelper.ListPageResult <Bitshare.PTMM.Model.TblContact>(pageInfo);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error("GetWorkContactPageResult()", ex);
            }
            return(result);
        }
示例#18
0
    void bindData()
    {
        if (Request["p"] != null)
            pageIndex = Convert.ToInt32(Request["p"]);
        else
            pageIndex = 1;

        DataPager p = new ExclusiveDataPager();
        result = p.PageData(pageIndex, pageSize, "FAQ", "*", "FAQID", null, "desc");
        GridView1.DataSource = result.Result;
        GridView1.DataKeyNames = new string[] { "FAQID" };
        GridView1.DataBind();
    }
        /// <summary>
        /// Search Scheduled Student For Group Drop
        /// </summary>
        /// <param name="scheduleStudentListViewModel"></param>
        /// <returns></returns>
        public ScheduleStudentListViewModel SearchScheduledStudentForGroupDrop(PageResult pageResult)
        {
            ScheduleStudentListViewModel        scheduleStudentListView = new ScheduleStudentListViewModel();
            IQueryable <ScheduleStudentForView> transactionIQ           = null;

            try
            {
                var scheduledStudentData = this.context?.StudentCoursesectionSchedule.
                                           Join(this.context?.StudentMaster,
                                                scs => scs.StudentId, sm => sm.StudentId,
                                                (scs, sm) => new { scs, sm }).Where(c => c.scs.TenantId == pageResult.TenantId && c.scs.SchoolId == pageResult.SchoolId && c.scs.CourseSectionId == pageResult.CourseSectionId && c.sm.SchoolId == pageResult.SchoolId && c.sm.TenantId == pageResult.TenantId).ToList().Select(ssv => new ScheduleStudentForView
                {
                    SchoolId          = ssv.sm.SchoolId,
                    TenantId          = ssv.sm.TenantId,
                    StudentId         = ssv.sm.StudentId,
                    FirstGivenName    = ssv.sm.FirstGivenName,
                    LastFamilyName    = ssv.sm.LastFamilyName,
                    AlternateId       = ssv.sm.AlternateId,
                    StudentInternalId = ssv.sm.StudentInternalId,
                    GradeLevel        = this.context.Gradelevels.FirstOrDefault(c => c.TenantId == ssv.sm.TenantId && c.SchoolId == ssv.sm.SchoolId && c.GradeId == ssv.scs.GradeId)?.Title,
                    Section           = this.context.Sections.FirstOrDefault(c => c.TenantId == ssv.sm.TenantId && c.SchoolId == ssv.sm.SchoolId && c.SectionId == ssv.sm.SectionId)?.Name,
                    PhoneNumber       = ssv.sm.MobilePhone,
                    Action            = ssv.scs.IsDropped,
                    ScheduleDate      = ssv.scs.CreatedOn,
                    StudentPhoto      = (pageResult.ProfilePhoto == true)?ssv.sm.StudentPhoto:null
                }).ToList();

                if (scheduledStudentData.Count > 0)
                {
                    if (pageResult.FilterParams == null || pageResult.FilterParams.Count == 0)
                    {
                        transactionIQ = scheduledStudentData.AsQueryable();
                    }
                    else
                    {
                        if (pageResult.FilterParams != null && pageResult.FilterParams.ElementAt(0).ColumnName == null && pageResult.FilterParams.Count == 1)
                        {
                            string Columnvalue = pageResult.FilterParams.ElementAt(0).FilterValue;

                            transactionIQ = scheduledStudentData.Where(x => x.FirstGivenName.ToLower().Contains(Columnvalue.ToLower()) || x.LastFamilyName.ToLower().Contains(Columnvalue.ToLower()) || x.GradeLevel.ToLower().Contains(Columnvalue.ToLower()) || x.ScheduleDate.ToString() == Columnvalue).AsQueryable();
                        }
                        else
                        {
                            transactionIQ = Utility.FilteredData(pageResult.FilterParams, scheduledStudentData).AsQueryable();
                        }
                        transactionIQ = transactionIQ.Distinct();
                    }
                    if (pageResult.SortingModel != null)
                    {
                        switch (pageResult.SortingModel.SortColumn.ToLower())
                        {
                        default:
                            transactionIQ = Utility.Sort(transactionIQ, pageResult.SortingModel.SortColumn, pageResult.SortingModel.SortDirection.ToLower());
                            break;
                        }
                    }

                    int totalCount = transactionIQ.Count();
                    if (pageResult.PageNumber > 0 && pageResult.PageSize > 0)
                    {
                        transactionIQ = transactionIQ.Skip((pageResult.PageNumber - 1) * pageResult.PageSize).Take(pageResult.PageSize);
                    }
                    scheduleStudentListView.scheduleStudentForView = transactionIQ.ToList();
                    scheduleStudentListView.TotalCount             = totalCount;
                }
                else
                {
                    scheduleStudentListView.scheduleStudentForView = scheduledStudentData;
                    scheduleStudentListView._failure = false;
                    scheduleStudentListView._message = NORECORDFOUND;
                }

                scheduleStudentListView.TenantId        = pageResult.TenantId;
                scheduleStudentListView.SchoolId        = pageResult.SchoolId;
                scheduleStudentListView.CourseSectionId = pageResult.CourseSectionId;
                scheduleStudentListView.PageNumber      = pageResult.PageNumber;
                scheduleStudentListView._pageSize       = pageResult.PageSize;
                scheduleStudentListView._tenantName     = pageResult._tenantName;
                scheduleStudentListView._token          = pageResult._token;
                scheduleStudentListView._failure        = false;
            }
            catch (Exception es)
            {
                scheduleStudentListView._failure = true;
                scheduleStudentListView._message = es.Message;;
            }
            return(scheduleStudentListView);
        }
 //================================================================================
 private PageResultDto<OffhireDto> mapPageResult(PageResult<Offhire> pageResult)
 {
     return new PageResultDto<OffhireDto>()
     {
         CurrentPage = pageResult.CurrentPage,
         PageSize = pageResult.PageSize,
         TotalCount = pageResult.TotalCount,
         TotalPages = pageResult.TotalPages,
         Result = offhireDtoMapper.MapToModel(pageResult.Result, this.setEditProperties).ToList()
     };
 }
        public object Any(FreeDbMatchSearch request)
        {
            var sp = Stopwatch.StartNew();
            var returnValue = new PageResult<List<Disk>>();

            var results =
                Client().Search<Disk>(
                    i =>
                        i.Index("disk")
                            .Skip((request.Offset) * request.Limit)
                            .Take(request.Limit)
                            .Query(q => q.Match(m => m.OnField(p => p.Artist).Query(request.Artist)) && q.Match(m => m.OnField(p => p.Genre).Query(request.Genre)))
                            .Aggregations((a => a.Terms("genre.raw", t => t.Field("genre.raw").Size(20)))));

            returnValue.TimeElapsed = sp.Elapsed.TotalSeconds;
            returnValue.CurrentPage = (request.Offset == 0) ? 1 : request.Offset;
            returnValue.Result = results.Documents.ToList();
            returnValue.ItemCount = results.Documents.Count();
            returnValue.TotalItems = results.Total;
            returnValue.TotalPages = (int)Math.Ceiling((double)results.Total / request.Limit);

            return returnValue;
        }
        public ActionResult <ScheduleStudentListViewModel> SearchScheduledStudentForGroupDrop(PageResult pageResult)
        {
            ScheduleStudentListViewModel ScheduledStudentListView = new ScheduleStudentListViewModel();

            try
            {
                ScheduledStudentListView = _studentScheduleService.SearchScheduledStudentForGroupDrop(pageResult);
            }
            catch (Exception es)
            {
                ScheduledStudentListView._failure = true;
                ScheduledStudentListView._message = es.Message;
            }
            return(ScheduledStudentListView);
        }
示例#23
0
        public void PageModelActionTester_TestPage_should_return_PageResult()
        {
            PageResult PageResult = _pageTester.Action(x => x.OnGet).TestPage();

            Assert.IsNotNull(PageResult);
        }
示例#24
0
        /// <summary>
        /// 获取当前用户的视频列表 用于分页
        /// </summary>
        /// <param name="condtions"></param>
        /// <param name="orderCondtions"></param>
        /// <returns></returns>
        public PageResult GetUserVideoList(int userId, IList <Condtion> condtions, IList <OrderCondtion> orderCondtions)
        {
            var videos = from v in _videoRepository.GetEntityList(CondtionEqualCreateManageId(userId))
                         where v.VideoState == 3
                         select new VideoView()
            {
                IsHot            = v.IsHot,
                IsRecommend      = v.IsRecommend,
                PlayCount        = v.PlayCount,
                About            = v.About,
                BigPicturePath   = v.BigPicturePath,
                CreateTime       = v.CreateTime,
                UpdateTime       = v.UpdateTime ?? v.CreateTime,
                Director         = v.Director,
                Id               = v.Id,
                IsOfficial       = v.IsOfficial,
                SmallPicturePath = v.SmallPicturePath,
                Starring         = v.Starring,
                Tags             = v.Tags,
                Title            = v.Title,
                Filter           = v.Filter
            };

            if (condtions != null && condtions.Count() > 0)
            {
                videos = videos.Query <VideoView>(condtions);
            }
            if (orderCondtions != null && orderCondtions.Count() > 0)
            {
                videos = videos.OrderBy <VideoView>(orderCondtions);
            }

            int totalCount = videos.Count();
            int pageCount  = 0;

            if (this.PageSize > 0)
            {
                pageCount = totalCount % this.PageSize == 0
                  ? (totalCount / this.PageSize)
                  : (totalCount / this.PageSize + 1);
                if (this.PageIndex <= 0)
                {
                    this.PageIndex = 1;
                }
                if (this.PageIndex >= pageCount)
                {
                    this.PageIndex = pageCount;
                }
                videos = videos.Skip <VideoView>((this.PageIndex - 1) * this.PageSize).Take <VideoView>(this.PageSize);
            }
            var result = new PageResult()
            {
                PageSize   = this.PageSize,
                PageIndex  = this.PageIndex,
                TotalCount = totalCount,
                TotalIndex = pageCount,
                Data       = videos.ToList()
            };

            return(result);
        }
示例#25
0
        /// <summary>
        /// Create the <see cref="ODataResourceSet"/> to be written for the given resourceSet instance.
        /// </summary>
        /// <param name="resourceSetInstance">The instance representing the resourceSet being written.</param>
        /// <param name="resourceSetType">The EDM type of the resourceSet being written.</param>
        /// <param name="writeContext">The serializer context.</param>
        /// <returns>The created <see cref="ODataResourceSet"/> object.</returns>
        public virtual ODataResourceSet CreateResourceSet(IEnumerable resourceSetInstance, IEdmCollectionTypeReference resourceSetType,
                                                          ODataSerializerContext writeContext)
        {
            ODataResourceSet resourceSet = new ODataResourceSet
            {
                TypeName = resourceSetType.FullName()
            };

            IEdmStructuredTypeReference structuredType = GetResourceType(resourceSetType).AsStructured();

            if (writeContext.NavigationSource != null && structuredType.IsEntity())
            {
                ResourceSetContext resourceSetContext = new ResourceSetContext
                {
                    Request             = writeContext.Request,
                    Context             = writeContext.Context,
                    EntitySetBase       = writeContext.NavigationSource as IEdmEntitySetBase,
                    Url                 = writeContext.Url,
                    ResourceSetInstance = resourceSetInstance
                };

                IEdmEntityType entityType      = structuredType.AsEntity().EntityDefinition();
                var            operations      = writeContext.Model.GetAvailableOperationsBoundToCollection(entityType);
                var            odataOperations = CreateODataOperations(operations, resourceSetContext, writeContext);
                foreach (var odataOperation in odataOperations)
                {
                    ODataAction action = odataOperation as ODataAction;
                    if (action != null)
                    {
                        resourceSet.AddAction(action);
                    }
                    else
                    {
                        resourceSet.AddFunction((ODataFunction)odataOperation);
                    }
                }
            }

            if (writeContext.ExpandedResource == null)
            {
                // If we have more OData format specific information apply it now, only if we are the root feed.
                PageResult odataResourceSetAnnotations = resourceSetInstance as PageResult;
                if (odataResourceSetAnnotations != null)
                {
                    resourceSet.Count        = odataResourceSetAnnotations.Count;
                    resourceSet.NextPageLink = odataResourceSetAnnotations.NextPageLink;
                }
                else if (writeContext.Request != null)
                {
                    resourceSet.NextPageLink = writeContext.Context.ODataFeature().NextLink;

                    long?countValue = writeContext.Context.ODataFeature().TotalCount;
                    if (countValue.HasValue)
                    {
                        resourceSet.Count = countValue.Value;
                    }
                }
            }
            else
            {
                // nested resourceSet
                ITruncatedCollection truncatedCollection = resourceSetInstance as ITruncatedCollection;
                if (truncatedCollection != null && truncatedCollection.IsTruncated)
                {
                    resourceSet.NextPageLink = GetNestedNextPageLink(writeContext, truncatedCollection.PageSize);
                }

                ICountOptionCollection countOptionCollection = resourceSetInstance as ICountOptionCollection;
                if (countOptionCollection != null && countOptionCollection.TotalCount != null)
                {
                    resourceSet.Count = countOptionCollection.TotalCount;
                }
            }

            return(resourceSet);
        }
示例#26
0
    void bindData()
    {
        if (Request["p"] != null)
            pageIndex = Convert.ToInt32(Request["p"]);
        else
            pageIndex = 1;

        DataPager p = new ExclusiveDataPager();
        result = p.PageData(pageIndex, pageSize, "CooperationEnterprises", "*", "EnterprisesID", null, "asc");
        string dsStr = "select * from CooperationEnterprises where IsDelete=" + 0;
        DataSet ds = DBHelper.INST.ExecuteSqlDS(dsStr);
        GridView1.DataSource = ds;//result1.Result;
        GridView1.DataBind();
        ds.Dispose();
           /*
         GridView1.DataSource = result.Result;
        GridView1.DataKeyNames = new string[] { "EnterprisesID" };
        GridView1.DataBind();
        */
    }
示例#27
0
        public async Task <IActionResult> GetPage(string url)
        {
            PageResult result = await _mediatr.Send(new GetPageQuery(url));

            return(HandleResult(result, result.Page));
        }
示例#28
0
        public PageResult<ProductInfo> ListByCondition(NameValueCollection searchCondtionCollection, NameValueCollection sortCollection, int pageNumber, int pageSize)
        {
            PageResult<ProductInfo> result = new PageResult<ProductInfo>();
            int skip = (pageNumber - 1) * pageSize;
            int take = pageSize;
            List<ProductInfo> list = null;

            using (var DbContext = new MRPDbContext())
            {
                var query = from i in DbContext.Product
                            join p in DbContext.ProductCatalog on i.ProductCatalogId equals p.Id
                            select new ProductInfo()
                            {
                                Id = i.Id,
                                ProductCode = i.ProductCode,
                                ProductName = i.ProductName,
                                ProductCatalogName = p.ProductCatalogName,
                                ProductCatalogId = i.ProductCatalogId,
                                ImageUrl = i.ImageUrl,
                                SearchKey = i.SearchKey,
                                Special = i.Special,
                                Size = i.Size,
                                MinStock = i.MinStock,
                                Stock = i.Stock,
                                MaxStock = i.MaxStock,
                                Texture = i.Texture,
                                Color = i.Color,
                                UnitId = i.UnitId,
                                SYS_IsValid = i.SYS_IsValid,
                                SYS_OrderSeq = i.SYS_OrderSeq,
                                SYS_AppId = i.SYS_AppId,
                                SYS_StaffId = i.SYS_StaffId,
                                SYS_StationId = i.SYS_StationId,
                                SYS_DepartmentId = i.SYS_DepartmentId,
                                SYS_CompanyId = i.SYS_CompanyId,
                                SYS_CreateTime = i.SYS_CreateTime
                            };

                #region 条件
                foreach (string key in searchCondtionCollection)
                {
                    string condition = searchCondtionCollection[key];
                    switch (key.ToLower())
                    {
                        case "productname":
                            query = query.Where(x => x.ProductName.Contains(condition));
                            break;
                        case "productcatalogid":
                            query = query.Where(x => x.ProductCatalogId.Equals(condition));
                            break;
                        case "searchkey":
                            query = query.Where(x => x.SearchKey.Equals(condition));
                            break;
                        case "isvalid":
                            int value = Convert.ToInt32(condition);
                            query = query.Where(x => x.SYS_IsValid.Equals(value));
                            break;
                        default:
                            break;
                    }
                }
                #endregion

                result.TotalRecords = query.Count();

                #region 排序
                foreach (string sort in sortCollection)
                {
                    string direct = sortCollection[sort];
                    switch (sort.ToLower())
                    {
                        case "createtime":
                            if (direct.ToLower().Equals("asc"))
                            {
                                query = query.OrderBy(x => new { x.SYS_CreateTime }).Skip(skip).Take(take);
                            }
                            else
                            {
                                query = query.OrderByDescending(x => new { x.SYS_CreateTime }).Skip(skip).Take(take);
                            }
                            break;
                        case "productname":
                            if (direct.ToLower().Equals("asc"))
                            {
                                query = query.OrderBy(x => x.ProductName).Skip(skip).Take(take);
                            }
                            else
                            {
                                query = query.OrderByDescending(x => x.ProductName).Skip(skip).Take(take);
                            }
                            break;
                        default:
                            query = query.OrderByDescending(x => new { x.SYS_OrderSeq }).Skip(skip).Take(take);
                            break;
                    }
                }
                #endregion
                list = query.ToList();
            }

            result.PageSize = pageSize;
            result.PageNumber = pageNumber;
            result.Data = list;
            return result;
        }
        public async Task <object> Any(ApiPages request)
        {
            if (string.IsNullOrEmpty(request.PageName))
            {
                throw new ArgumentNullException(nameof(request.PageName));
            }

            var parts = string.IsNullOrEmpty(request.PathInfo)
                ? TypeConstants.EmptyStringArray
                : request.PathInfo.SplitOnLast('.');

            var hasPathContentType = parts.Length > 1 && Host.ContentTypes.KnownFormats.Contains(parts[1]);
            var pathInfo           = hasPathContentType
                ? parts[0]
                : request.PathInfo;

            var pathArgs = string.IsNullOrEmpty(pathInfo)
                ? TypeConstants.EmptyStringArray
                : pathInfo.Split('/');

            parts = request.PageName.SplitOnLast('.');
            var hasPageContentType = pathArgs.Length == 0 && parts.Length > 1 && Host.ContentTypes.KnownFormats.Contains(parts[1]);
            var pageName           = hasPageContentType
                ? parts[0]
                : request.PageName;

            // Change .csv download file name
            base.Request.OperationName = pageName + (pathArgs.Length > 0 ? "_" + string.Join("_", pathArgs) : "");

            var feature = HostContext.GetPlugin <TemplatePagesFeature>();

            if (feature.ApiDefaultContentType != null &&
                !hasPathContentType &&
                !hasPageContentType &&
                base.Request.QueryString[TemplateConstants.Format] == null && base.Request.ResponseContentType == MimeTypes.Html)
            {
                base.Request.ResponseContentType = feature.ApiDefaultContentType;
            }

            var pagePath = feature.ApiPath.CombineWith(pageName).TrimStart('/');
            var page     = base.Request.GetPage(pagePath);

            if (page == null)
            {
                throw HttpError.NotFound($"No API Page was found at '{pagePath}'");
            }

            var requestArgs = base.Request.GetTemplateRequestParams();

            requestArgs[TemplateConstants.PathInfo] = request.PathInfo;
            requestArgs[TemplateConstants.PathArgs] = pathArgs;

            var pageResult = new PageResult(page)
            {
                NoLayout          = true,
                RethrowExceptions = true,
                Args = requestArgs
            };

            var discardedOutput = await pageResult.RenderToStringAsync();

            if (!pageResult.Args.TryGetValue(TemplateConstants.Return, out var response))
            {
                throw HttpError.NotFound($"The API Page did not specify a response. Use the 'return' filter to set a return value for the page.");
            }

            if (response is Task <object> responseTask)
            {
                response = await responseTask;
            }
            if (response is IRawString raw)
            {
                response = raw.ToRawString();
            }

            var httpResult = ToHttpResult(pageResult, response);

            return(httpResult);
        }
示例#30
0
        public override async Task <PageResult <CompanyNewsDto> > Handle(GetCompanyNewsCommand request, CancellationToken cancellationToken)
        {
            var sb = new List <string>();


            if (request.Id != 0)
            {
                sb.Add($"Id = {request.Id}");
            }

            if (request.Show.HasValue)
            {
                sb.Add($"Show = " + (request.Show.Value ? 1 : 0));
            }

            if (request.Status != -999)
            {
                sb.Add($"Status = " + request.Status);
            }


            if (request.CompanyId != 0)
            {
                sb.Add($"CompanyId = " + request.CompanyId);
            }


            if (!string.IsNullOrWhiteSpace(request.CompanyTypeId))
            {
                sb.Add($"CompanyTypeId = " + request.CompanyTypeId);
            }

            if (request.LoginUser != null && request.LoginUser.Type == 2)
            {
                sb.Add($"UserId = " + request.LoginUser.Id);
            }


            var where = string.Join(" and ", sb);


            var pageData = await _companyNewsRepository.GetPageDataAsync <Domain.CompanyAggregate.CompanyNews>(
                pageIndex : request.PageIndex,
                pageSize : request.PageSize,
                where : where,
                order : "Status asc,Sort asc,Id desc"
                );

            var count = pageData.Total;

            if (count < 1)
            {
                return(PageResult <CompanyNewsDto> .Success(null, count, request.PageIndex, request.PageSize, request.LinkUrl));
            }

            var types = await _companyTypeRepository.Set().ToListAsync();

            var companyId_arr = pageData.Data.Select(x => x.CompanyId);

            var companys = _companyRepository.Set().Where(x => companyId_arr.Contains(x.Id));

            var data = pageData.Data.Select(x =>

                                            new CompanyNewsDto()
            {
                CompanyId          = x.CompanyId,
                CompanyName        = companys.FirstOrDefault(c => c.Id == x.CompanyId)?.Name,
                Id                 = x.Id,
                CompanyTypeId      = x.CompanyTypeId,
                Contact            = x.Contact,
                CooperationContent = x.CooperationContent,
                Introduce          = x.Introduce,
                IntroduceImage     = x.IntroduceImage,
                MainBusiness       = x.MainBusiness,
                Show               = x.Show,
                Sort               = x.Sort,
                Status             = x.Status,
                Title              = x.Title,
                CreatedTime        = x.CreatedTime,
                UpdatedTime        = x.UpdatedTime
            }
                                            );;

            return(PageResult <CompanyNewsDto> .Success(data, count, request.PageIndex, request.PageSize, request.LinkUrl));
        }
示例#31
0
        public PageResult<StaffInfo> ListByCondition(NameValueCollection searchCondtionCollection, NameValueCollection sortCollection, int pageNumber, int pageSize)
        {
            PageResult<StaffInfo> result = new PageResult<StaffInfo>();
            int skip = (pageNumber - 1) * pageSize;
            int take = pageSize;
            List<StaffInfo> list = null;

            using (var DbContext = new UCDbContext())
            {
                var query = from i in DbContext.Staff
                            join d in DbContext.Department on i.DepartmentId equals d.Id
                            join c in DbContext.Company on d.CompanyId equals c.Id
                            select new StaffInfo()
                            {
                                Id = i.Id,
                                UserCode = i.UserCode,
                                UserName = i.UserName,
                                Sex = i.Sex,
                                Mobile = i.Mobile,
                                DepartmentId = i.DepartmentId,
                                DepartmentName = d.DepartmentName,
                                CompanyId = d.CompanyId,
                                CompanyName = c.CompanyName,
                                SYS_IsValid = i.SYS_IsValid,
                                SYS_OrderSeq = i.SYS_OrderSeq,
                                SYS_AppId = i.SYS_AppId,
                                SYS_StaffId = i.SYS_StaffId,
                                SYS_StationId = i.SYS_StationId,
                                SYS_DepartmentId = i.SYS_DepartmentId,
                                SYS_CompanyId = i.SYS_CompanyId,
                                SYS_CreateTime = i.SYS_CreateTime
                            };

                #region 条件
                foreach (string key in searchCondtionCollection)
                {
                    string condition = searchCondtionCollection[key];
                    switch (key.ToLower())
                    {
                        case "username":
                            query = query.Where(x => x.UserName.Contains(condition));
                            break;
                        case "departmentid":
                            query = query.Where(x => x.DepartmentId.Equals(condition));
                            break;
                        case "companyid":
                            query = query.Where(x => x.CompanyId.Equals(condition));
                            break;
                        case "isvalid":
                            int value = Convert.ToInt32(condition);
                            query = query.Where(x => x.SYS_IsValid.Equals(value));
                            break;
                        default:
                            break;
                    }
                }
                #endregion

                result.TotalRecords = query.Count();

                #region 排序
                foreach (string sort in sortCollection)
                {
                    string direct = sortCollection[sort];
                    switch (sort.ToLower())
                    {
                        case "createtime":
                            if (direct.ToLower().Equals("asc"))
                            {
                                query = query.OrderBy(x => new { x.SYS_CreateTime }).Skip(skip).Take(take);
                            }
                            else
                            {
                                query = query.OrderByDescending(x => new { x.SYS_CreateTime }).Skip(skip).Take(take);
                            }
                            break;
                        case "username":
                            if (direct.ToLower().Equals("asc"))
                            {
                                query = query.OrderBy(x => x.CompanyName).Skip(skip).Take(take);
                            }
                            else
                            {
                                query = query.OrderByDescending(x => x.CompanyName).Skip(skip).Take(take);
                            }
                            break;
                        default:
                            query = query.OrderByDescending(x => new { x.SYS_OrderSeq }).Skip(skip).Take(take);
                            break;
                    }
                }
                #endregion
                list = query.ToList();
            }

            result.PageSize = pageSize;
            result.PageNumber = pageNumber;
            result.Data = list;
            return result;
        }
示例#32
0
 /// <summary>
 /// Ctor: init immutable instance.
 /// </summary>
 public IndexModel(PageResult pr, string gaCode)
 {
     PR     = pr;
     GACode = gaCode;
 }
        public void CreateODataFeed_Sets_NextPageLinkForPageResult()
        {
            // Arrange
            ODataFeedSerializer serializer = new ODataFeedSerializer(new DefaultODataSerializerProvider());
            Uri expectedNextLink = new Uri("http://nextlink.com");
            const long ExpectedCountValue = 1000;

            var result = new PageResult<Customer>(_customers, expectedNextLink, ExpectedCountValue);

            // Act
            ODataFeed feed = serializer.CreateODataFeed(result, _customersType, new ODataSerializerContext());

            // Assert
            Assert.Equal(expectedNextLink, feed.NextPageLink);
        }
示例#34
0
 private PageResult GetPageResultData(PageResult pageParams)
 {
     #region 判断是否进行全部查询
     string deleteFlag = ui.UiData.Crud.DeleteFlag;
     var    formParam  = pdata.GetSelectParamFieldValue(this.Request.Form);
     if (!string.IsNullOrWhiteSpace(deleteFlag))
     {
         if (formParam.ContainsKey(deleteFlag))
         {
             formParam[deleteFlag] = this.hiddenIsSearchAllInfo.Value;
         }
         else
         {
             formParam.Add(deleteFlag, this.hiddenIsSearchAllInfo.Value);
         }
         if (string.IsNullOrWhiteSpace(this.hiddenIsSearchAllInfo.Value.ToString()))
         {
             formParam.Remove(deleteFlag);
         }
     }
     #endregion
     #region 根据URL传递的参数进行查询
     foreach (string name in this.Request.QueryString.AllKeys)
     {
         if (string.IsNullOrWhiteSpace(name))
         {
             continue;
         }
         string value    = this.Request.QueryString[name];
         bool   isExeits = false;
         string key      = string.Empty;
         foreach (KeyValuePair <string, object> keyvalue in formParam)
         {
             if (keyvalue.Key.Equals(name, StringComparison.CurrentCultureIgnoreCase))
             {
                 key            = keyvalue.Key;
                 formParam[key] = value;
                 isExeits       = true;
                 break;
             }
         }
         if (!isExeits)
         {
             key = name;
             formParam.Add(key, value);
         }
         if (string.IsNullOrWhiteSpace(value))
         {
             formParam.Remove(key);
         }
     }
     #endregion
     #region 扩展功能
     var commandParam = getCommandParam(ui.Select, formParam);
     if (ExecuteCommands(commandParam).isBreak)
     {
         return(null);
     }
     #endregion
     pageParams.ParameterObject = formParam;
     return(manager.GetPageDataByReader(pageParams));
 }
示例#35
0
        public PageResult<ArticleVideoInfo> ListByCondition(NameValueCollection searchCondtionCollection, NameValueCollection sortCollection, int pageNumber, int pageSize)
        {
            PageResult<ArticleVideoInfo> result = new PageResult<ArticleVideoInfo>();
            int skip = (pageNumber - 1) * pageSize;
            int take = pageSize;
            List<ArticleVideo> list = null;

            using (var DbContext = new CmsDbContext())
            {
            var query = from i in DbContext.ArticleVideo
                        select i;

            #region 条件
            foreach (string key in searchCondtionCollection)
            {
                string condition = searchCondtionCollection[key];
                switch (key.ToLower())
                {
                    case "isvalid":
                        int value = Convert.ToInt32(condition);
                        query = query.Where(x => x.SYS_IsValid.Equals(value));
                        break;
                    default:
                        break;
                }
            }
            #endregion

            result.TotalRecords = query.Count();

            #region 排序
            foreach (string sort in sortCollection)
            {
                string direct = string.Empty;
                switch (sort.ToLower())
                {
                    case "createtime":
                        if (direct.ToLower().Equals("asc"))
                        {
                            query = query.OrderBy(x => new { x.SYS_CreateTime }).Skip(skip).Take(take);
                        }
                        else
                        {
                            query = query.OrderByDescending(x => new { x.SYS_CreateTime }).Skip(skip).Take(take);
                        }
                        break;
                    default:
                        query = query.OrderByDescending(x => new { x.SYS_OrderSeq }).Skip(skip).Take(take);
                        break;
                }
            }
               list = query.ToList();
            }
            #endregion
            #region linq to entity
            List<ArticleVideoInfo> ilist = new List<ArticleVideoInfo>();
            list.ForEach(x =>
            {
                ArticleVideoInfo info = new ArticleVideoInfo();
                DESwap.ArticleVideoETD(x, info);
                ilist.Add(info);
            });
            #endregion

            result.PageSize = pageSize;
            result.PageNumber = pageNumber;
            result.Data = ilist;
            return result;;
        }
示例#36
0
        public async Task <PageResult <UserDTO> > Handle(GetUsersCommand request, CancellationToken cancellationToken)
        {
            // Func<User, bool> condition = x => true;
            var where = "";
            var userSet = _userRepository.Set().AsQueryable();

            if (!string.IsNullOrWhiteSpace(request.Key))
            {
                userSet = userSet.Where(x => x.UserName.Contains(request.Key));
                //condition = x => x.UserName.Contains(request.Key);
                where = $"UserName like '%{request.Key}%'";
            }

            //  var count = await userSet.CountAsync();

            //if (count < 1) return PageResult<UserDTO>.Success(null, 0, request.PageIndex, request.PageSize, "");
            //var start = (request.PageIndex - 1) * request.PageSize;
            //var end = start + request.PageSize;


            //var query = userSet.OrderByDescending(x => x.Id)
            //    .Skip(start)
            //    .Take(request.PageSize)
            //    .AsQueryable();

            //var data = await userSet.OrderByDescending(x => x.Id)
            //   .Skip(start)
            //   .Take(request.PageSize)
            //   .ToListAsync();
            //var data = query.ToList();


            var pageData = await _userRepository.GetPageDataAsync <User>(
                pageIndex : request.PageIndex,
                pageSize : request.PageSize,
                where : where);

            var count = pageData.Total;

            if (count < 1)
            {
                return(PageResult <UserDTO> .Success(null, 0, request.PageIndex, request.PageSize, ""));
            }

            //_logger.LogInformation(query.ToSql());
            var data = pageData.Data;

            var ids = data.Select(x => x.Id);

            var companyUserids = await _companyUserRepository.Set().Where(x => ids.Contains(x.UserId)).ToListAsync();

            var user_company_arr = companyUserids.Select(x => new { x.CompanyId, x.UserId });

            var cids = user_company_arr.Select(x => x.CompanyId);

            var companys = await _companyRepository.Set().Where(x => cids.Contains(x.Id)).ToListAsync();

            var _data = new List <UserDTO>();

            data.ToList().ForEach(x =>
            {
                var u = new UserDTO
                {
                    CreatedTime   = x.CreatedTime,
                    Id            = x.Id,
                    Type          = x.Type,
                    UserName      = x.UserName,
                    LoginCount    = x.LoginCount,
                    Mobile        = x.Mobile,
                    LastLoginTime = x.LastLoginTime
                };
                var user_company = user_company_arr.FirstOrDefault(y => y.UserId == x.Id);
                if (user_company == null)
                {
                    u.CompanyName = "未绑定";
                }
                else
                {
                    u.CompanyId   = user_company.CompanyId;
                    u.CompanyName = companys.FirstOrDefault(x => x.Id == user_company.CompanyId)?.Name;
                }

                _data.Add(u);
            });

            return(PageResult <UserDTO> .Success(_data, count, request.PageIndex, request.PageSize, $"/user/user/list/?PageIndex=__id__&PageSize={request.PageSize}&key={request.Key}"));
        }
示例#37
0
        /// <summary>
        /// Materialize a page result.
        /// </summary>
        public static async Task <PageResult <T> > MaterializeAsync <T>(this PageResult <T> pageResult)
        {
            pageResult.Results = await pageResult.Results.AsQueryable().ToListAsync();

            return(pageResult);
        }
示例#38
0
 /// <summary>
 /// 将分页数据转换为表格数据格式
 /// </summary>
 public static GridData <TData> ToGridData <TData>(this PageResult <TData> pageResult)
 {
     return(new GridData <TData>(pageResult.Data, pageResult.Total));
 }
示例#39
0
        public static List <PageResult> LoadPageResults(Service service)
        {
            //return new List<PageResult>();
            try
            {
                string filename = service.Name.Replace(" ", "") + ".json";
                string path     = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data", filename);
                string json     = FileSystemHelper.ReadWithoutLock(path);
                if (string.IsNullOrWhiteSpace(json))
                {
                    return(new List <PageResult>());
                }

                List <PageResult> results = new List <PageResult>();

                using (StringReader sr = new StringReader(json))
                    using (JsonTextReader reader = new JsonTextReader(sr))
                    {
                        if (!reader.Read() || reader.TokenType != JsonToken.StartArray)
                        {
                            throw new Exception("Invalid format");
                        }

                        while (reader.Read())
                        {
                            if (reader.TokenType != JsonToken.StartObject)
                            {
                                continue;
                            }

                            PageResult result = new PageResult();

                            while (reader.Read())
                            {
                                if (reader.TokenType == JsonToken.PropertyName)
                                {
                                    string name = reader.Value as string;
                                    reader.Read();
                                    switch (name.ToLowerInvariant())
                                    {
                                    case "friendly-url":
                                        result.FriendlyUrl = reader.Value as string;
                                        break;

                                    case "ip-address":
                                        result.IPAddress = reader.Value as string;
                                        break;

                                    case "site-id":
                                        result.SiteID = Convert.ToInt32(reader.Value);
                                        break;

                                    case "domain-id":
                                        result.DomainID = Convert.ToInt32(reader.Value);
                                        break;

                                    case "result-type":
                                        result.ResultType = (ResultType)Enum.Parse(typeof(ResultType), reader.Value as string);
                                        break;

                                    case "status-code":
                                        result.StatusCode = Convert.ToInt32(reader.Value);
                                        break;
                                    }
                                }
                                else if (reader.TokenType == JsonToken.EndObject)
                                {
                                    results.Add(result);
                                    break;
                                }
                            }
                        }
                    }

                return(results);
            }
            catch
            {
                return(new List <PageResult>());
            }
        }
        public void Can_assign_to_variables_in_partials()
        {
            var context = new TemplateContext
            {
                Args =
                {
                    ["num"] = 1,
                },
            }.Init();

            context.VirtualFiles.WriteFile("_layout.html", @"
<html>
<body>
<header>
layout num = {{ num }}
pageMetaTitle = {{ pageMetaTitle }}
inlinePageTitle = {{ inlinePageTitle }}
pageResultTitle = {{ pageResultTitle }}
</header>
{{ 'add-partial' | partial({ num: 100 }) }} 
{{ page }}
{{ 'add-partial' | partial({ num: 400 }) }} 
<footer>
layout num = {{ num }}
inlinePageTitle = {{ inlinePageTitle }}
</footer>
</body>
</html>
");

            context.VirtualFiles.WriteFile("page.html", @"
<!--
pageMetaTitle: page meta title
-->
<section>
{{ 'page inline title' | upper | assignTo('inlinePageTitle') }}
{{ 'add-partial' | partial({ num: 200 }) }} 
{{ num | add(1) | assignTo('num') }}
<h2>page num = {{ num }}</h2>
{{ 'add-partial' | partial({ num: 300 }) }} 
</section>");

            context.VirtualFiles.WriteFile("add-partial.html", @"
{{ num | add(10) | assignTo('num') }}
<h3>partial num = {{ num }}</h3>");

            var result = new PageResult(context.GetPage("page"))
            {
                Args =
                {
                    ["pageResultTitle"] = "page result title"
                }
            }.Result;

            /* NOTES:
             * 1. Page Args and Page Result Args are *always* visible to Layout as they're known before page is executed
             * 2. Args created during Page execution are *only* visible in Layout after page is rendered (i.e. executed)
             * 3. Args assigned in partials are retained within their scope
             */

            Assert.That(result.RemoveNewLines(), Is.EqualTo(@"
<html>
<body>
<header>
layout num = 1
pageMetaTitle = page meta title
inlinePageTitle = {{ inlinePageTitle }}
pageResultTitle = page result title
</header>
<h3>partial num = 110</h3> 
<section>
<h3>partial num = 210</h3> 
<h2>page num = 2</h2>
<h3>partial num = 310</h3> 
</section>
<h3>partial num = 410</h3> 
<footer>
layout num = 2
inlinePageTitle = PAGE INLINE TITLE
</footer>
</body>
</html>
".RemoveNewLines()));
        }
示例#41
0
        private void btnConfirm_Click(object sender, RoutedEventArgs e)
        {
            _pageVM.StopTimer();

            bool bSameWithHouse = PersonalData170["IsSameWithHouse"] == "Y";

            string[] fundSrcs = GetFundSource();

            string pcFlagadd = "";

            if (PersonalData170["ShowStatementAddr"] == "Y")
            {
                pcFlagadd = PersonalData170["StatementAddrByHouse"] == "Y" ? "A" : "B";
            }

            var model = new
            {
                regzipcode             = PersonalData170["HouseZipCode"],
                regadr                 = PersonalData170["HouseCityName"],
                regtown                = PersonalData170["HouseTownName"],
                reglin                 = PersonalData170["HouseLin"],
                reglee                 = PersonalData170["HouseLi"],
                regaddr                = PersonalData170["HouseAddress"],
                zipcode2               = PersonalData170["CommZipCode"],
                adr2                   = PersonalData170["CommCityName"],
                town2                  = PersonalData170["CommTownName"],
                lee2                   = PersonalData170["CommLi"],
                addr2                  = PersonalData170["CommAddress"],
                zipcode1               = pcFlagadd == "A" ? PersonalData170["HouseZipCode"] : PersonalData170["CommZipCode"],
                adr1                   = pcFlagadd == "A" ? PersonalData170["HouseCityName"] : PersonalData170["CommCityName"],
                town1                  = pcFlagadd == "A" ? PersonalData170["HouseTownName"] : PersonalData170["CommTownName"],
                lee1                   = pcFlagadd == "A" ? PersonalData170["HouseLi"] : PersonalData170["CommLi"],
                addr1                  = pcFlagadd == "A" ? PersonalData170["HouseAddress"] : PersonalData170["CommAddress"],
                hphnc                  = PersonalData170["HomeTelCountry"],
                hpharea                = PersonalData170["HomeTelArea"],
                hphno                  = PersonalData170["HomeTelNumber"],
                ophnc                  = PersonalData170["OfficeTelCountry"],
                opharea                = PersonalData170["OfficeTelArea"],
                ophno                  = PersonalData170["OfficeTelNumber"],
                ophext                 = PersonalData170["OfficeExtNumber"],
                mphnc                  = PersonalData170["MobileCountry"],
                mphno                  = PersonalData170["MobileNumber"].Replace("-", "").Trim(),
                faxnc1                 = PersonalData170["FaxTelCountry"],
                faxarea1               = PersonalData170["FaxTelArea"],
                faxno1                 = PersonalData170["FaxTelNumber"],
                email                  = PersonalData170["Email"],
                pcFlag                 = PersonalData170["StatementCode"],
                statement              = PersonalData170["OldStatementCode"],
                jobTitle               = PersonalData172["JobTitleKey"],
                serveCompany           = PersonalData172["CompanyName"],
                jobBusinessCode        = PersonalData172["SubClassMegaCode"],
                annualIncome           = PersonalData172["AnnualIncomeCode"],
                indviAmtRange          = PersonalData172["MonthlyAvgCode"],
                purpose1               = PersonalData172["PurposeCode1"],
                purpose2               = PersonalData172["PurposeCode2"],
                purpose3               = PersonalData172["PurposeCode3"],
                purpose1Remark         = PersonalData172["OtherPurpose"],
                incomeResource1        = fundSrcs.Length > 0 ? fundSrcs[0] : "",
                incomeResource2        = fundSrcs.Length > 1 ? fundSrcs[1] : "",
                incomeResource3        = fundSrcs.Length > 2 ? fundSrcs[2] : "",
                incomeResourceIncome   = PersonalData175["FundSourceADesc"],
                incomeResourceOther    = PersonalData175["FundSourceBDesc"],
                assetResource1         = PersonalData177["WealthySource1Code"],
                assetResourceSub1      = PersonalData177["WealthySource1SubCode"],
                assetResourceSub1Other = PersonalData177["WealthySource1Other"],
                assetResource2         = PersonalData177["WealthySource2Code"],
                assetResourceSub2      = PersonalData177["WealthySource2SubCode"],
                assetResourceSub2Other = PersonalData177["WealthySource2Other"],
                assetResource3         = PersonalData177["WealthySource3Code"],
                assetResourceSub3      = PersonalData177["WealthySource3SubCode"],
                assetResourceSub3Other = PersonalData177["WealthySource3Other"],
                pbtransf               = PersonalData177["StampRefAccNo"],
                pbatmfg                = PersonalData185["ApplyATMCard"],
                wfCard                 = PersonalData185["ICCATMCard"],
                lkkCard                = PersonalData185["VISAAtomCard"],
                lotusCard              = PersonalData185["VISALotusCard"],
                pb11nofg               = PersonalData185["NonDealTRF"],
                pb11stfg               = PersonalData185["ConsumeDeduct"],
                pb11trfg               = PersonalData185["InternationTrade"],
                appWebbank             = PersonalData186["ApplyEBank"],
                actfNbSsl              = PersonalData186["ApplySSL"] == "Y" ? "1" : "?",
                actfNbToSelf           = PersonalData186["TRFSameNameAccount"] == "Y" ? "1" : "?",
                actfNbFree             = PersonalData186["EBankNonDealTRF"] == "Y" ? "1" : "?",
                actfNbFxFlag           = PersonalData186["ExchangeClaimService"] == "Y" ? "1" : "?",
                actfNbRgFlag           = PersonalData186["OnlineTRFAccount"] == "Y" ? "1" : "?",
                actfNbDvPhid           = PersonalData186["MobileBank"] == "Y" ? "5" : "?",
                ecode                  = PersonalData186["ApplyEMobileService"],
                mobile                 = PersonalData186["eMobile"].Replace("-", "").Trim(),
                appPwd                 = PersonalData185["ApplyUniPayment"],
                twAppPwd               = PersonalData185["ApplyTWDAccountPswd"],
                fappPwd                = PersonalData185["ApplyFGDAccountPswd"],
                commarkterm            = PersonalData187["PromotionTerm"],
                pcFlagadd,
                engAddr = PersonalData170["OldEnglishAddress"],
                engName = PersonalData170["OldEnglishName"],

                PersonalData170 = Json2Base64(_pageVM.Page0170Data),
                PersonalData172 = Json2Base64(_pageVM.Page0172Data),
                PersonalData175 = Json2Base64(_pageVM.Page0175Data),
                PersonalData177 = Json2Base64(_pageVM.Page0177Data),
                PersonalData185 = Json2Base64(_pageVM.Page0185Data),
                PersonalData186 = Json2Base64(_pageVM.Page0186Data),
                PersonalData187 = Json2Base64(_pageVM.Page0187Data)
            };

            string json = JsonConvert.SerializeObject(model);

            _kernelService.TransactionDataCache.Set(KioskDataCacheKey.ApplyConfirmData, json);

            PageResult result = new PageResult("Confirm", KioskDataCacheKey.ApplyConfirmData);

            _kernelService.NextPage(result);
        }
示例#42
0
        public void Can_validate_person_in_code()
        {
            var context = new ScriptContext().Init();

            var code = @"
['Name','Age'] |> to => requiredProps
#each requiredProps
    #if !model[it]
        it.throwArgumentNullException()
    /if
/each

(Age < 13) |> ifThrowArgumentException('Must be 13 or over', 'Age')
";

            try
            {
                var pageResult = new PageResult(context.CodeBlock(code))
                {
                    Model = new Person()
                };
                pageResult.RenderToStream(Stream.Null);
                Assert.Fail("Should throw");
            }
            catch (ScriptException e)
            {
                if (!(e.InnerException is ArgumentNullException ne))
                {
                    throw;
                }

                Assert.That(ne.ParamName, Is.EqualTo(nameof(Person.Name)));
            }

            try
            {
                var pageResult = new PageResult(context.CodeBlock(code))
                {
                    Model = new Person {
                        Name = "A"
                    }
                };
                pageResult.RenderToStream(Stream.Null);
                Assert.Fail("Should throw");
            }
            catch (ScriptException e)
            {
                if (!(e.InnerException is ArgumentNullException ne))
                {
                    throw;
                }

                Assert.That(ne.ParamName, Is.EqualTo(nameof(Person.Age)));
            }

            try
            {
                var pageResult = new PageResult(context.CodeBlock(code))
                {
                    Model = new Person {
                        Name = "A", Age = 1
                    }
                };
                pageResult.RenderToStream(Stream.Null);
                Assert.Fail("Should throw");
            }
            catch (ScriptException e)
            {
                if (!(e.InnerException is ArgumentException ae))
                {
                    throw;
                }

                Assert.That(ae.Message.Replace("\r", ""),
                            Does.StartWith("Must be 13 or over"));
            }
        }
示例#43
0
        public PageResult<ClientTypeInfo> ListByCondition(NameValueCollection searchCondtionCollection, NameValueCollection sortCollection, int pageNumber, int pageSize)
        {
            PageResult<ClientTypeInfo> result = new PageResult<ClientTypeInfo>();
            int skip = (pageNumber - 1) * pageSize;
            int take = pageSize;
            List<ClientTypeInfo> list = null;

            using (var DbContext = new UCDbContext())
            {
                var query = from i in DbContext.ClientType
                            join p in DbContext.ClientType on i.ParentId equals p.Id into parent
                            from tp in parent.DefaultIfEmpty()
                            select new ClientTypeInfo()
                            {
                                Id = i.Id,
                                ClientTypeCode = i.ClientTypeCode,
                                ClientTypeName = i.ClientTypeName,
                                ParentId = i.ParentId,
                                TreeNode = i.TreeNode,
                                SYS_IsValid = i.SYS_IsValid,
                                SYS_OrderSeq = i.SYS_OrderSeq,
                                SYS_AppId = i.SYS_AppId,
                                SYS_StaffId = i.SYS_StaffId,
                                SYS_StationId = i.SYS_StationId,
                                SYS_DepartmentId = i.SYS_DepartmentId,
                                SYS_CompanyId = i.SYS_CompanyId,
                                SYS_CreateTime = i.SYS_CreateTime,
                                ParentName = tp.ClientTypeName == null ? "" : tp.ClientTypeName
                            };

                #region 条件
                foreach (string key in searchCondtionCollection)
                {
                    string condition = searchCondtionCollection[key];
                    switch (key.ToLower())
                    {
                        case "clienttypename":
                            query = query.Where(x => x.ClientTypeName.Contains(condition));
                            break;
                        case "clienttypecode":
                            query = query.Where(x => x.ClientTypeCode.Contains(condition));
                            break;
                        case "parentid":
                            query = query.Where(x => x.ParentId.Equals(condition));
                            break;
                        case "isvalid":
                            int value = Convert.ToInt32(condition);
                            query = query.Where(x => x.SYS_IsValid.Equals(value));
                            break;
                        default:
                            break;
                    }
                }
                #endregion

                result.TotalRecords = query.Count();

                #region 排序
                foreach (string sort in sortCollection)
                {
                    string direct = sortCollection[sort];
                    switch (sort.ToLower())
                    {
                        case "createtime":
                            if (direct.ToLower().Equals("asc"))
                            {
                                query = query.OrderBy(x => new { x.SYS_CreateTime }).Skip(skip).Take(take);
                            }
                            else
                            {
                                query = query.OrderByDescending(x => new { x.SYS_CreateTime }).Skip(skip).Take(take);
                            }
                            break;
                        case "clienttypename":
                            if (direct.ToLower().Equals("asc"))
                            {
                                query = query.OrderBy(x => x.ClientTypeName).Skip(skip).Take(take);
                            }
                            else
                            {
                                query = query.OrderByDescending(x => x.ClientTypeName).Skip(skip).Take(take);
                            }
                            break;
                        default:
                            query = query.OrderByDescending(x => new { x.SYS_OrderSeq }).Skip(skip).Take(take);
                            break;
                    }
                }
                #endregion
                list = query.ToList();
            }

            result.PageSize = pageSize;
            result.PageNumber = pageNumber;
            result.Data = list;
            return result;
        }
示例#44
0
        private static async Task MainAsync()
        {
            // Start

            Console.WriteLine("Jasmin rocks! Let's list the orders attributes using the OData...");

            // Handle errors

            try
            {
                // Create the HTTP client to send the request

                using (HttpClient client = new HttpClient())
                {
                    // Set the authorization header

                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);

                    // URI of the endpoint

                    string endpoint = string.Format(CultureInfo.CurrentCulture, "{0}/{1}/{2}/sales/orders/odata?$inlinecount=allpages&$select=DocumentType,SeriesNumber,Company&$top=10&$orderby=Serie desc", ApiBaseAddress, AccountKey, SubscriptionKey);

                    // Send the request (GET)

                    Console.WriteLine("Kicking the Orders OData endpoint to list the orders attributes...");

                    Uri endpointUri = new Uri(endpoint);

                    using (HttpResponseMessage response = await client.GetAsync(endpointUri))
                    {
                        // Failed?

                        if (!response.IsSuccessStatusCode)
                        {
                            string errorContent = await response.Content.ReadAsStringAsync();

                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine(string.Format(CultureInfo.CurrentCulture, "The requested failed with status code {0} ({1}).", (int)response.StatusCode, response.StatusCode));

                            if (!string.IsNullOrWhiteSpace(errorContent))
                            {
                                sb.Append(string.Format(CultureInfo.CurrentCulture, "Message: {0}.", errorContent));
                            }

                            throw new InvalidOperationException(sb.ToString());
                        }

                        // Succeeded

                        string json = await response.Content.ReadAsStringAsync();

                        JsonSerializerSettings settings = new JsonSerializerSettings()
                        {
                            ContractResolver = new CamelCasePropertyNamesContractResolver(),
                            Formatting       = Formatting.Indented
                        };

                        PageResult <OrderResource> orders = JsonConvert.DeserializeObject <PageResult <OrderResource> >(json);

                        Console.WriteLine("The orders attributes were obtained with success.");

                        foreach (OrderResource order in orders.Items)
                        {
                            Console.WriteLine("Order: {0}.{1}.{2}", order.DocumentType, order.Company, order.SeriesNumber);
                        }
                        Console.WriteLine("Count: {0}", orders.Count);
                    }
                }
            }
            catch (Exception exception)
            {
                ConsoleHelper.WriteErrorLine("Error found!");
                ConsoleHelper.WriteErrorLine(exception.Message);
            }

            // End

            Console.Write("Press any key to end... ");
            Console.ReadKey();
        }
        public override async Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            var args = httpReq.GetTemplateRequestParams();

            if (Args != null)
            {
                foreach (var entry in Args)
                {
                    args[entry.Key] = entry.Value;
                }
            }

            var pageResult = new PageResult(page)
            {
                Args       = args,
                LayoutPage = layoutPage,
                Model      = Model,
            };

            try
            {
                httpRes.ContentType = page.Format.ContentType;
                if (OutputStream != null)
                {
                    await pageResult.WriteToAsync(OutputStream);
                }
                else
                {
                    // Buffering improves perf when running behind a reverse proxy (recommended for .NET Core)
                    using (var ms = MemoryStreamFactory.GetStream())
                    {
                        await pageResult.WriteToAsync(ms);

                        if (pageResult.Args.TryGetValue(TemplateConstants.Return, out var response))
                        {
                            if (response is Task <object> responseTask)
                            {
                                response = await responseTask;
                            }
                            if (response is IRawString raw)
                            {
                                response = raw.ToRawString();
                            }

                            if (response != null)
                            {
                                var httpResult = TemplateApiPagesService.ToHttpResult(pageResult, response);
                                await httpRes.WriteToResponse(httpReq, httpResult);

                                return;
                            }
                        }

                        ms.Position = 0;
                        await ms.WriteToAsync(httpRes.OutputStream);
                    }
                }
            }
            catch (Exception ex)
            {
                await page.Format.OnViewException(pageResult, httpReq, ex);
            }
        }
示例#46
0
        public static PageResult <TResult> Convert <TSource, TResult>(this PageResult <TSource> source, Func <TSource, TResult> selector)
        {
            var data = source.Data.Select(selector);

            return(new PageResult <TResult>(data, source.Request, source.Total));
        }
        public object Any(FreeDb request)
        {
            var sp = Stopwatch.StartNew();
            var returnValue = new PageResult<List<Disk>>();

            var results =
                Client().Search<Disk>(
                    i =>
                        i.Index("disk")
                        .Type("disk")
                            .Skip((request.Offset) * request.Limit)
                            .Take(request.Limit)
                            .Query(
                                q =>
                                    q.QueryString(
                                        qs =>
                                            qs.OnFields(new[] { "artist", "title", "tracks" })
                                                .Query(request.Query))));

            returnValue.TimeElapsed = sp.Elapsed.TotalSeconds;
            returnValue.CurrentPage = (request.Offset == 0) ? 1 : request.Offset;
            returnValue.Result = results.Documents.ToList();
            returnValue.ItemCount = results.Documents.Count();
            returnValue.TotalItems = results.Total;
            returnValue.TotalPages = (int)Math.Ceiling((double)results.Total / request.Limit);

            return returnValue;
        }
 private async Task OnSelectCommandAsync()
 {
     await PageResult.FinishAsync(SelectedItem);
 }
        public void CreateODataFeed_Sets_InlineCountForPageResult()
        {
            // Arrange
            ODataFeedSerializer serializer = new ODataFeedSerializer(new DefaultODataSerializerProvider());
            Uri expectedNextLink = new Uri("http://nextlink.com");
            long expectedInlineCount = 1000;

            var result = new PageResult<Customer>(_customers, expectedNextLink, expectedInlineCount);

            // Act
            ODataFeed feed = serializer.CreateODataFeed(result, _customersType, new ODataSerializerContext());

            // Assert
            Assert.Equal(1000, feed.Count);
        }
 private async Task OnCancelCommandAsync()
 {
     await PageResult.CancelAsync();
 }
示例#51
0
        public PageResult<AppInfo> ListByCondition(NameValueCollection searchCondtionCollection, NameValueCollection sortCollection, int pageNumber, int pageSize)
        {
            PageResult<AppInfo> result = new PageResult<AppInfo>();
            int skip = (pageNumber - 1) * pageSize;
            int take = pageSize;
            List<AppInfo> list = null;

            using (var DbContext = new UCDbContext())
            {
                var query = from i in DbContext.App
                            select new AppInfo()
                            {
                                Id = i.Id,
                                AppCode = i.AppCode,
                                AppName = i.AppName,
                                PublicKey = i.PublicKey,
                                PrivateKey = i.PrivateKey,
                                SYS_IsValid = i.SYS_IsValid,
                                SYS_OrderSeq = i.SYS_OrderSeq,
                                SYS_AppId = i.SYS_AppId,
                                SYS_StaffId = i.SYS_StaffId,
                                SYS_StationId = i.SYS_StationId,
                                SYS_DepartmentId = i.SYS_DepartmentId,
                                SYS_CompanyId = i.SYS_CompanyId,
                                SYS_CreateTime = i.SYS_CreateTime
                            };

                #region 条件
                foreach (string key in searchCondtionCollection)
                {
                    string condition = searchCondtionCollection[key];
                    switch (key.ToLower())
                    {
                        case "appname":
                            query = query.Where(x => x.AppName.Contains(condition));
                            break;
                        case "appcode":
                            query = query.Where(x => x.AppCode.Contains(condition));
                            break;
                        case "isvalid":
                            int value = Convert.ToInt32(condition);
                            query = query.Where(x => x.SYS_IsValid.Equals(value));
                            break;
                        default:
                            break;
                    }
                }
                #endregion

                result.TotalRecords = query.Count();

                #region 排序
                foreach (string sort in sortCollection)
                {
                    string direct = sortCollection[sort];
                    switch (sort.ToLower())
                    {
                        case "createtime":
                            if (direct.ToLower().Equals("asc"))
                            {
                                query = query.OrderBy(x => new { x.SYS_CreateTime }).Skip(skip).Take(take);
                            }
                            else
                            {
                                query = query.OrderByDescending(x => new { x.SYS_CreateTime }).Skip(skip).Take(take);
                            }
                            break;
                        case "appname":
                            if (direct.ToLower().Equals("asc"))
                            {
                                query = query.OrderBy(x => x.AppName).Skip(skip).Take(take);
                            }
                            else
                            {
                                query = query.OrderByDescending(x => x.AppName).Skip(skip).Take(take);
                            }
                            break;
                        default:
                            query = query.OrderByDescending(x => new { x.SYS_OrderSeq }).Skip(skip).Take(take);
                            break;
                    }
                }
                #endregion
                list = query.ToList();
            }

            result.PageSize = pageSize;
            result.PageNumber = pageNumber;
            result.Data = list;
            return result; ;
        }
示例#52
0
 public void WritePageResult(PageResult results)
 {
     _writer.Write(Protocol.FormatDocument(string.Format("{0}\n{1}\n{2}\n", results.Title, results.TestCounts.Description, results.Content)));
 }
示例#53
0
        public PageResult<ArticleInfo> ListByCondition(NameValueCollection searchCondtionCollection, NameValueCollection sortCollection, int pageNumber, int pageSize)
        {
            PageResult<ArticleInfo> result = new PageResult<ArticleInfo>();
            int skip = (pageNumber - 1) * pageSize;
            int take = pageSize;
            List<ArticleInfo> list = null;

            using (var DbContext = new CmsDbContext())
            {
                var query = from i in DbContext.Article
                            join ac in DbContext.ArticleCatalog on i.ArticleCatalogId equals ac.Id
                            select new ArticleInfo()
                            {
                                Id = i.Id,
                                Title = i.Title,
                                FormDate = i.FormDate,
                                ArticleType = i.ArticleType,
                                ArticleCatalogId = i.ArticleCatalogId,
                                SignImage = i.SignImage,
                                SYS_IsValid = i.SYS_IsValid,
                                SYS_OrderSeq = i.SYS_OrderSeq,
                                SYS_AppId = i.SYS_AppId,
                                SYS_StaffId = i.SYS_StaffId,
                                SYS_StationId = i.SYS_StationId,
                                SYS_DepartmentId = i.SYS_DepartmentId,
                                SYS_CompanyId = i.SYS_CompanyId,
                                SYS_CreateTime = i.SYS_CreateTime,
                                ArticleCatalogName = ac.Name
                            };

                #region 条件
                foreach (string key in searchCondtionCollection)
                {
                    string condition = searchCondtionCollection[key];
                    switch (key.ToLower())
                    {
                        case "titile":
                            query = query.Where(x => x.Title.Contains(condition));
                            break;
                        case "articlecatalogid":
                            query = query.Where(x => x.ArticleCatalogId.Equals(condition));
                            break;
                        case "isvalid":
                            int isvalid = Convert.ToInt32(condition);
                            query = query.Where(x => x.SYS_IsValid.Equals(isvalid));
                            break;
                        default:
                            break;
                    }
                }
                #endregion

                result.TotalRecords = query.Count();

                #region 排序
                foreach (string sort in sortCollection)
                {
                    string direct = sortCollection[sort];
                    switch (sort.ToLower())
                    {
                        case "createtime":
                            if (direct.ToLower().Equals("asc"))
                            {
                                query = query.OrderBy(x => new { x.SYS_CreateTime }).Skip(skip).Take(take);
                            }
                            else
                            {
                                query = query.OrderByDescending(x => new { x.SYS_CreateTime }).Skip(skip).Take(take);
                            }
                            break;
                        case "title":
                            if (direct.ToLower().Equals("asc"))
                            {
                                query = query.OrderBy(x => x.Title).Skip(skip).Take(take);
                            }
                            else
                            {
                                query = query.OrderByDescending(x => x.Title).Skip(skip).Take(take);
                            }
                            break;
                        default:
                            query = query.OrderByDescending(x => new { x.SYS_OrderSeq }).Skip(skip).Take(take);
                            break;
                    }
                }
                #endregion
                list = query.ToList();
            }

            result.PageSize = pageSize;
            result.PageNumber = pageNumber;
            result.Data = list;
            return result; ;
        }
        /// <summary>
        /// Create the <see cref="ODataFeed"/> to be written for the given feed instance.
        /// </summary>
        /// <param name="feedInstance">The instance representing the feed being written.</param>
        /// <param name="feedType">The EDM type of the feed being written.</param>
        /// <param name="writeContext">The serializer context.</param>
        /// <returns>The created <see cref="ODataFeed"/> object.</returns>
        public virtual ODataFeed CreateODataFeed(IEnumerable feedInstance, IEdmCollectionTypeReference feedType,
                                                 ODataSerializerContext writeContext)
        {
            ODataFeed feed = new ODataFeed();

            if (writeContext.EntitySet != null)
            {
                IEdmModel model = writeContext.Model;
                EntitySetLinkBuilderAnnotation linkBuilder = model.GetEntitySetLinkBuilder(writeContext.EntitySet);
                FeedContext feedContext = new FeedContext
                {
                    Request        = writeContext.Request,
                    RequestContext = writeContext.RequestContext,
                    EntitySet      = writeContext.EntitySet,
                    Url            = writeContext.Url,
                    FeedInstance   = feedInstance
                };

                Uri feedSelfLink = linkBuilder.BuildFeedSelfLink(feedContext);
                if (feedSelfLink != null)
                {
                    feed.SetAnnotation(new AtomFeedMetadata()
                    {
                        SelfLink = new AtomLinkMetadata()
                        {
                            Relation = "self", Href = feedSelfLink
                        }
                    });
                }
            }

            // TODO: Bug 467590: remove the hardcoded feed id. Get support for it from the model builder ?
            feed.Id = "http://schemas.datacontract.org/2004/07/" + feedType.FullName();

            if (writeContext.ExpandedEntity == null)
            {
                // If we have more OData format specific information apply it now, only if we are the root feed.
                PageResult odataFeedAnnotations = feedInstance as PageResult;
                if (odataFeedAnnotations != null)
                {
                    feed.Count        = odataFeedAnnotations.Count;
                    feed.NextPageLink = odataFeedAnnotations.NextPageLink;
                }
                else if (writeContext.Request != null)
                {
                    feed.NextPageLink = writeContext.Request.ODataProperties().NextLink;

                    long?inlineCount = writeContext.Request.ODataProperties().TotalCount;
                    if (inlineCount.HasValue)
                    {
                        feed.Count = inlineCount.Value;
                    }
                }
            }
            else
            {
                // nested feed
                ITruncatedCollection truncatedCollection = feedInstance as ITruncatedCollection;
                if (truncatedCollection != null && truncatedCollection.IsTruncated)
                {
                    feed.NextPageLink = GetNestedNextPageLink(writeContext, truncatedCollection.PageSize);
                }
            }

            return(feed);
        }
        //================================================================================
        //public OffhireDetailDto AddOffhireDetail(OffhireDetailDto detailDto)
        //{
        //    var result = offhireApplicationService.AddOffhireDetail(
        //        detailDto.Offhire.Id, detailDto.ROB, detailDto.Price, detailDto.Currency.Id, detailDto.Good.Id, detailDto.Unit.Id, detailDto.Tank.Id);
        //    return offhireDetailDtoMapper.MapToModel(result);
        //}
        //================================================================================
        //public OffhireDetailDto UpdateOffhireDetail(OffhireDetailDto detailDto)
        //{
        //    var result = offhireApplicationService.UpdateOffhireDetail(
        //        detailDto.Offhire.Id, detailDto.Id, detailDto.ROB, detailDto.Price, detailDto.Currency.Id, detailDto.Good.Id, detailDto.Unit.Id, detailDto.Tank.Id);
        //    return offhireDetailDtoMapper.MapToModel(result);
        //}
        //================================================================================
        //public void DeleteOffhireDetail(long offhireId, long offhireDetailId)
        //{
        //    offhireApplicationService.DeleteOffhireDetail(offhireId, offhireDetailId);
        //}
        //================================================================================
        public PageResultDto<OffhireManagementSystemDto> GetOffhireManagementSystemPagedDataByFilter(long companyId, long vesselInCompanyId, DateTime? fromDate, DateTime? toDate, int pageSize, int pageIndex)
        {
            var result = offhireManagementSystemDomainService.GetFinalizedOffhires(companyId, vesselInCompanyId, fromDate, toDate);

            var pageResult = new PageResult<OffhireManagementSystemEntity>()
                                    {
                                        CurrentPage = pageIndex,
                                        PageSize = pageSize,
                                        TotalCount = result.Count,
                                        TotalPages = pageSize == 0 ? 0 : (int)Math.Ceiling((double)result.Count / pageSize),
                                        Result = pageSize == 0 ? result : result.Skip(pageSize * pageIndex).Take(pageSize).ToList()
                                    };

            return mapPageResult(pageResult);
        }
        public async Task <IActionResult> Get(int take = 100, int skip = 0)
        {
            PageResult <ApiResourceDto> items = await _apiResourceService.Get(take, skip);

            return(Ok(items));
        }
 //================================================================================
 private PageResultDto<OffhireManagementSystemDto> mapPageResult(PageResult<OffhireManagementSystemEntity> pageResult)
 {
     return new PageResultDto<OffhireManagementSystemDto>()
         {
             CurrentPage = pageResult.CurrentPage,
             PageSize = pageResult.PageSize,
             TotalCount = pageResult.TotalCount,
             TotalPages = pageResult.TotalPages,
             Result = offhireManagementSystemDtoMapper.MapToModel(pageResult.Result).ToList()
         };
 }
示例#58
0
 public MvcPageResult(PageResult pageResult, Stream contents)
 {
     this.pageResult = pageResult;
     this.contents   = contents;
 }
        public async Task <PageResult <GetAllStatisticByDto> > GetAllStatisticBy(StatisticReportFilterByDto input)
        {
            var counts = 0;

            var results = (from category in _categoryRepository.GetAll()

                           join book in _bookRepository.GetAll() on category.Id equals book.CategoryId

                           join brDetail in _borrowBookDetailRepository.GetAll() on book.Id equals brDetail.BookId into TempBrDetail
                           from brDetailTB in TempBrDetail.DefaultIfEmpty()

                           join borrow in _borrowBookRepository.GetAll() on brDetailTB.BorrowBookId equals borrow.Id into TempBr
                           from borrowTB in TempBr.DefaultIfEmpty()

                           join library in _libraryRepository.GetAll() on brDetailTB.LibraryId equals library.Id into TempLib
                           from libraryTB in TempLib.DefaultIfEmpty()

                           join district in _districtRepository.GetAll() on libraryTB.DistrictId equals district.Id into TempDistrict
                           from districtTB in TempDistrict.DefaultIfEmpty()

                           join province in _provinceRepository.GetAll() on districtTB.ProvinceId equals province.Id into TempProvince
                           from provinceTB in TempProvince.DefaultIfEmpty()

                           select new
            {
                CategoryId = category.Id,
                CategoryName = category.Name,
                LibraryId = libraryTB != null ? libraryTB.Id : Guid.Empty,
                LibraryName = libraryTB != null ? libraryTB.Name : null,
                DistrictId = districtTB != null ? districtTB.Id : Guid.Empty,
                DistrictName = districtTB != null ? districtTB.Name : null,
                ProvinceId = provinceTB != null ? provinceTB.Id : Guid.Empty,
                ProvinceName = provinceTB != null ? provinceTB.Name : null,
                Qty = brDetailTB != null ? brDetailTB.Qty : 0,
                DateBorrow = borrowTB.DateBorrow
            })
                          .ToList()
                          .WhereIf(
                input.LibraryId != Guid.Empty || input.ProvinceId != Guid.Empty ||
                input.DistrictId != Guid.Empty || input.FromDate.HasValue && input.ToDate.HasValue ||
                input.Month != null || input.Quarter != null
                ,
                x => x.LibraryId == input.LibraryId || x.ProvinceId == input.ProvinceId ||
                x.DistrictId == input.DistrictId || x.DateBorrow.Date >= input.FromDate && x.DateBorrow.Date <= input.ToDate ||
                x.DateBorrow.Month == input.Month ||
                ((1 <= x.DateBorrow.Month && x.DateBorrow.Month <= 3) ? 1 : ((4 <= x.DateBorrow.Month && x.DateBorrow.Month <= 6) ? 2 : ((7 <= x.DateBorrow.Month && x.DateBorrow.Month <= 9) ? 3 : ((10 <= x.DateBorrow.Month && x.DateBorrow.Month <= 12) ? 4 : 0)))) == input.Quarter
                )
                          .GroupBy(x => x.CategoryId)
                          .Select(data => new GetAllStatisticByDto
            {
                CategoryId   = data.Key,
                CategoryName = data.Select(x => x.CategoryName).FirstOrDefault(),
                LibraryId    = data.Select(x => x.LibraryId).FirstOrDefault(),
                LibraryName  = data.Select(x => x.LibraryName).FirstOrDefault(),
                DistrictId   = data.Select(x => x.DistrictId).FirstOrDefault(),
                DistrictName = data.Select(x => x.DistrictName).FirstOrDefault(),
                ProvinceId   = data.Select(x => x.ProvinceId).FirstOrDefault(),
                ProvinceName = data.Select(x => x.ProvinceName).FirstOrDefault(),
                Quantity     = data.Sum(x => x == null ? 0 : x.Qty),
            }).OrderByDescending(x => x.Quantity);

            counts = results.Count();
            var result = new PageResult <GetAllStatisticByDto>
            {
                Count     = counts,
                PageIndex = input.PageIndex,
                PageSize  = input.PageSize,
                Items     = await Task.FromResult(results.Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList())
            };

            return(result);
        }
示例#60
0
 public PageResult GetPageDataByReader(PageResult pageResult)
 {
     return(this.businessService.GetPageDataByReader(pageResult));
 }