// GET: Manage/DirectoryMembers
        public ActionResult Index(int? page, long? filter, string search, string theme)
        {
            long f = (filter == null) ? 0 : filter.Value;

            List<DirectoryMember> members =  this._contextManager.DirectoryContext.DirectoryMembers.GetByFilter(f, search);

            ViewBag.Filter = f;

            if (theme != null)
                Session["Theme"] = theme;

            List<DirectoryMember> dd = new List<DirectoryMember>();

            foreach (DirectoryMember d in members)
            {
                dd.Add(new DirectoryMember(d));
            }

            page = (page == null) ? 1 : page;

            ViewBag.Page = page.Value;

            ViewBag.Total = dd.Count();

            PagedList<DirectoryMember> pg = new PagedList<DirectoryMember>(dd, page.Value, 12);

            return View(pg);
        }
Beispiel #2
0
        // GET: BestSales
        public ActionResult Index(string attractionName, int? SelectedAttraction, int? LocationID, int page = 1)
        {
            int pageSize = 15;
            if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["PageSize"]))
            {
                if (!int.TryParse(ConfigurationManager.AppSettings["PageSize"], out pageSize))
                {
                    pageSize = 15;
                }
            }

            var tempAttractions = db.Attractions.OrderBy(q => q.AttractionName)
                                .Select(s => new { s.AttractionID, s.AttractionName }).Distinct().ToList();
            ViewBag.SelectedAttraction = new SelectList(tempAttractions, "AttractionID", "AttractionName", SelectedAttraction);
            PopulateLocationsDropDownList();

            var attractions = db.Attractions.OrderBy(o => o.AttractionName).Distinct().ToList();

            //IQueryable<Attractions> list = db.Attractions
            //    .Where(c => (string.IsNullOrEmpty(attractionName) || c.AttractionName.Contains(attractionName)) &&
            //                (!SelectedAttraction.HasValue || c.AttractionID == SelectedAttraction) &&
            //                (!LocationID.HasValue || c.LocationID == LocationID))

            //    .OrderBy(d => d.AttractionPrice)
            //    .Include(d => d.Locations)
            //    .Include(d => d.Sites);

            IQueryable<Attractions> list = db.Attractions.GroupBy(p => p.AttractionID)
                  .Select(g => g.OrderBy(p => p.Price)
                                .FirstOrDefault()
                   );

            PagedList<Attractions> model = new PagedList<Attractions>(list.ToList(), page, pageSize);
            return View(model);
        }
        /// <summary>
        /// Gets all contactUs items
        /// </summary>
        /// <param name="fromUtc">ContactUs item creation from; null to load all records</param>
        /// <param name="toUtc">ContactUs item creation to; null to load all records</param>
        /// <param name="email">email</param>
        /// <param name="vendorId">vendorId; null to load all records</param>
        /// <param name="customerId">customerId; null to load all records</param>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        /// <returns>ContactUs items</returns>
        public virtual IPagedList<ContactUs> GetAllContactUs(DateTime? fromUtc = null, DateTime? toUtc = null,
            string email = "", int vendorId = 0, int customerId = 0, int storeId = 0,
            int pageIndex = 0, int pageSize = int.MaxValue)
        {
            var builder = Builders<ContactUs>.Filter;
            var filter = builder.Where(c => true);

            if (fromUtc.HasValue)
                filter = filter & builder.Where(l => fromUtc.Value <= l.CreatedOnUtc);
            if (toUtc.HasValue)
                filter = filter & builder.Where(l => toUtc.Value >= l.CreatedOnUtc);
            if (vendorId > 0)
                filter = filter & builder.Where(l => vendorId == l.VendorId);
            if (customerId > 0)
                filter = filter & builder.Where(l => customerId == l.CustomerId);
            if (storeId > 0)
                filter = filter & builder.Where(l => storeId == l.StoreId);

            if (!String.IsNullOrEmpty(email))
                filter = filter & builder.Where(l => l.Email.ToLower().Contains(email.ToLower()));

            var builderSort = Builders<ContactUs>.Sort.Descending(x => x.CreatedOnUtc);
            var query = _contactusRepository.Collection;
            var contactus = new PagedList<ContactUs>(query, filter, builderSort, pageIndex, pageSize);

            return contactus;


        }
 public ActionResult List(int? id)
 {
     int PageNo = id ?? 1;
     Dictionary<string, string> sitemaster = GetSiteMaster();
     ViewData["SiteMaster"] = sitemaster;
     if (Int32.Parse(sitemaster["isadmin"]) == 2 || Int32.Parse(sitemaster["isadmin"]) == 5)
     {
         IList<IDictionary> bidAnounceList;
         Hashtable htparm = new Hashtable();
         htparm["start"] = PageSizeList * (PageNo - 1) + 1;   //记录开始数
         htparm["end"] = PageNo * PageSizeList;    //记录结束数
         bidAnounceList = EmedAppraiseMapper.Get().QueryForList<IDictionary>("QualityGroup.QueryAll", htparm);
         foreach (IDictionary b in bidAnounceList)
         {
             b["ProjectOid"] = EmedAppraiseMapper.Get().QueryForObject<string>("AuctionProject.getprojectname", Int32.Parse(b["ProjectOid"].ToString()));
         }
         IList<IDictionary> projects = EmedAppraiseMapper.Get().QueryForList<IDictionary>("AuctionProject.forgroup", "");
         int count = EmedAppraiseMapper.Get().QueryForObject<int>("QualityGroup.QueryAllCount", "");
         PagedList<IDictionary> list = new PagedList<IDictionary>(bidAnounceList, PageNo, PageSizeList, count);
         ViewData["ProvincebidAnounceListByUser"] = list;
         ViewData["Count"] = count;
         string selecthtml = string.Empty;
         foreach (IDictionary p in projects)
         {
             selecthtml += "<option value='" + p["OID"].ToString() + "'>" + p["NewProjectName"].ToString() + "</option>";
         }
         ViewData["projects"] = selecthtml;
         return View(list);
     }
     else
         return RedirectToAction("MemberLevelError", "Base");
     return View();
 }
Beispiel #5
0
 //从SelectCityView中得到CityPinYin     2012/3/29
 public ViewResult Tour(string id, int? pi)
 {
     ViewBag.pinyin = id;
     //定义了一个可变化的intPi =1
     var intPi = 1;
     //如果没有的话即表示在当前页
     if (pi == null)
     {
         pi = 1;
     }
     //将pi赋值给intPi
     intPi = (int)pi;
     if (id == "")
     {
         throw new ArgumentNullException("id is null");
     }
     var cityInfo = cityInfoService.GetCityByPinYin(id);
     if (cityInfo.city == "")
     {
         throw new ArgumentNullException("cityInfo is null");
     }
     else
     {
         id = cityInfo.city;
         IQueryable<Miaow.Application.dj.Dto.ListTypeMidTourPlanDto> data = null;
         int total = 0;    //总条数
         data = listService.GetTourListByCity(id, intPi, pageSize, ref total);
         PagedList<Miaow.Application.dj.Dto.ListTypeMidTourPlanDto> model = new PagedList<Miaow.Application.dj.Dto.ListTypeMidTourPlanDto>(data, intPi, pageSize, total);
         return View(model);
     }
 }
Beispiel #6
0
        //
        // GET: /Home/
        public ActionResult Index(string Id, int? page)
        {
            string where = null;
            IList<nav> navList = Daxu.BLL.navBll.GetEntityList<nav>(new SearchEntityList()
            {
                ModelEqual = "nav"

            }, null);
            ViewBag.Id = Id;
            ViewBag.navList = navList;
            nav thisnav = navList.Where(c => c.id == 511).FirstOrDefault();
            ViewBag.lmtp = thisnav.LmImg;
            //获取所有产品信息

            int pageIndex = page.HasValue && page.Value > 1 ? page.Value : 1;
            int pageSize = 16;
            int recordCount = 0;
            if (Id == "511")
            {

                where = "  DengJI like '%511%'";
            }
            else
            {
                where = " fenlei=" + Convert.ToString(Id);
            }
            IList<down> ImginfoList = Daxu.BLL.downBll.IGetPageListDataTable<down>("down", "*", "id", "", pageSize, pageIndex, 1, where, out recordCount);
            PagedList<down> pagedList = new PagedList<down>(ImginfoList, pageIndex, pageSize, recordCount);

            return View(pagedList);
        }
        /// <summary>
        /// 获取未删除的所有products
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PagedList<ProductModel> GetProducts(int pageIndex, int pageSize)
        {
            var data = new List<ProductModel>();
            var count = 0;
            using (var cmd = DataCommandManager.GetDataCommand("GetProducts"))
            {
                cmd.SetParameterValue("@PageIndex", pageIndex);
                cmd.SetParameterValue("@PageSize", pageSize);

                using (var ds = cmd.ExecuteDataSet())
                {
                   if(ds.Tables.Count>=2)
                   {
                       foreach (DataRow dr in ds.Tables[0].Rows)
                       {
                           data.Add(DataRowToProductModel(dr));
                       }
                       var drCount = ds.Tables[1].Rows[0][0];
                       count = !Convert.IsDBNull(drCount) ? Convert.ToInt32(drCount) : 0;
                   }

                }
            }

            var result = new PagedList<ProductModel>(data, pageIndex, pageSize, count);
            //总记录数量
            return result;
        }
		/// <summary>
        /// Find Enties Async
        /// </summary>
        /// <param name="pageIndex">pageIndex</param>
        /// <param name="pageSize">pageSize</param>
        /// <returns>Enties</returns>
        public async Task<PagedList<EmployeePayHistoryDto>> FindEntiesAsync(int? pageIndex, int pageSize)
        {
            var entities = await entiesrepository.Repository.FindAsync(p => p.EmployeeID!=null, p => p.EmployeeID, pageIndex, pageSize);
            var listDtos = new PagedList<EmployeePayHistoryDto>() { TotalCount = entities.TotalCount, PageIndex=pageIndex.Value,PageSize=pageSize  };
            entities.ForEach(entity => { listDtos.Add(typeAdapter.ConvertEntitiesToDto(entity)); });
            return listDtos;
        }
        /// <summary>
        /// Gets sorted list of all Business Locations in the dataset by filter 
        /// </summary>
        /// <param name="SearchQuery">Query to filter on</param>
        /// <param name="PageNumber">Current page number</param>
        /// <param name="PageSize">Number of items per page</param>
        /// <param name="OrderBy">Column name to sequence the list by</param>
        /// <param name="OrderByAscDesc">Sort direction</param> 
        /// <returns>object PagedList</returns>
        public static PagedList<BusinessLocation> GetBusinessLocations(string SearchQuery, int PageNumber, int PageSize, string OrderBy, bool OrderByAscDesc)
        {
            //Create client to talk to OpenDat API Endpoint
            var client = new SodaClient(_APIEndPointHost, _AppToken);

            //get a reference to the resource itself the result (a Resouce object) is a generic type
            //the type parameter represents the underlying rows of the resource
            var dataset = client.GetResource <PagedList<BusinessLocation>>(_APIEndPoint4x4);

            //Build the select list of columns for the SoQL call
            string[] columns = new[] { "legal_name", "doing_business_as_name", "date_issued", "city", "state", "zip_code", "latitude", "longitude"  };
            
            //Column alias must not collide with input column name, i.e. don't alias 'city' as 'city'
            string[] aliases = new[] { "LegalName", "DBA", "IssuedOn" };

            //using SoQL and a fluent query building syntax
            var soql = new SoqlQuery().Select(columns)
                .As(aliases)
                .Order((OrderByAscDesc) ? SoqlOrderDirection.ASC: SoqlOrderDirection.DESC,  new[] { OrderBy });

            if(!string.IsNullOrEmpty(SearchQuery))
            {
                soql = new SoqlQuery().FullTextSearch(SearchQuery);
            }

            var results = dataset.Query<BusinessLocation>(soql);

            //page'em cause there might be quite a few
            PagedList<BusinessLocation> pagedResults = new PagedList<BusinessLocation>(results.ToList(), PageNumber, PageSize);

            return pagedResults;
        }
        public virtual IPagedList<Vendor> GetAllVendorsOrderByDate(string name = "",
            bool isDecendin=true, int pageIndex = 0, int pageSize = int.MaxValue, 
            bool showHidden = false)
        {
            var query = (from v in _vendorRepository.TableNoTracking
                         join c in _customerRepository.TableNoTracking on v.Id equals c.VendorId
                         where v.Active && !v.Deleted
                         orderby c.CreatedOnUtc descending
                         select v
                 );

            if(!isDecendin)
            {
                query = (from v in _vendorRepository.TableNoTracking
                         join c in _customerRepository.TableNoTracking on v.Id equals c.VendorId
                         where v.Active && !v.Deleted
                         orderby c.CreatedOnUtc
                         select v
                 );
            }
            if(!string.IsNullOrWhiteSpace(name))
                query = query.Where(v => v.Name.ToLower().Contains(name.ToLower()));

            var vendors = new PagedList<Vendor>(query, pageIndex, pageSize);
            return vendors;
        }
 /// <summary>
 /// Find Enties 
 /// </summary>
 /// <param name="pageIndex">pageIndex</param>
 /// <param name="pageSize">pageSize</param>
 /// <returns>Enties</returns>
 public PagedList<EmployeePayHistoryDto> FindEnties(int? pageIndex, int pageSize)
 {
     var entities=entiesrepository.Repository.Find(p => p.EmployeeID!=null, p => p.EmployeeID, pageIndex, pageSize);
     var listDtos=new PagedList<EmployeePayHistoryDto>() { TotalCount = entities.TotalCount };
      entities.ForEach(entity => { listDtos.Add(typeAdapter.ConvertEntitiesToDto(entity)); });
      return listDtos;
 }
         /// <summary>
        /// Get the List ofAddressdto.
        /// </summary>
        /// <param name="_AddressDto">The Address dto.</param>
        /// <example><code> HTTP GET: api/Address/?pageindex=1&pagesize=10&....</code></example>
        /// <returns>DatagridData List of AddressDto</returns>
        public EasyuiDatagridData<AddressDto> Get([FromUri] AddressDto _AddressDtos, int pageIndex =1, int pageSize =10)
        {
		    var pagedlist = new PagedList<AddressDto>  {_AddressDtos };
            pagedlist.PageIndex = pageIndex;
            pagedlist.PageSize = pageSize;
            return _AddressBO.FindAll(pagedlist);
        }
        // GET: Zapis
        public ActionResult Index(string SilowniaID, int page = 1, int pageSize = 10, AkcjaZapisEnum akcja = AkcjaZapisEnum.Brak)
        {
            if (Session["Auth"] != null)
            {
                if (Session["Auth"].ToString() == "Klient")
                {
                    ViewBag.SilowniaID = new SelectList(db.Silownie.DistinctBy(a => new { a.Nazwa }), "Nazwa", "Nazwa");

                    var zajeciaGrup = from ZajeciaGrupowe in db.ZajeciaGrup select ZajeciaGrupowe;

                    zajeciaGrup = zajeciaGrup.Search(SilowniaID, i => i.Sala.Silownia.Nazwa);

                    var final = zajeciaGrup.OrderBy(p => p.Instruktor.Nazwisko);
                    var ileWynikow = zajeciaGrup.Count();
                    if ((ileWynikow / page) <= 1)
                    {
                        page = 1;
                    }
                    var kk = ileWynikow / page;

                    PagedList<ZajeciaGrupowe> model = new PagedList<ZajeciaGrupowe>(final, page, pageSize);

                    if (akcja != AkcjaZapisEnum.Brak)
                    {
                        ViewBag.Akcja = akcja;
                    }

                    return View(model);
                }
            }
            return HttpNotFound();
        }
         /// <summary>
        /// Get the List ofContactdto.
        /// </summary>
        /// <param name="_ContactDto">The Contact dto.</param>
        /// <example><code> HTTP GET: api/Contact/?pageindex=1&pagesize=10&....</code></example>
        /// <returns>DatagridData List of ContactDto</returns>
        public EasyuiDatagridData<ContactDto> Get([FromUri] ContactDto _ContactDtos, int pageIndex =1, int pageSize =10)
        {
		    var pagedlist = new PagedList<ContactDto>  {_ContactDtos };
            pagedlist.PageIndex = pageIndex;
            pagedlist.PageSize = pageSize;
            return _ContactBO.FindAll(pagedlist);
        }
 public PagedList<MessageModel> GetMessages(int userId, int pageIndex, int pageSize)
 {
     var data = new List<MessageModel>();
     
     using (var cmd = DataCommandManager.GetDataCommand("GetMessages"))
     {
         cmd.SetParameterValue("@UserId", userId);
         cmd.SetParameterValue("@PageIndex", pageIndex);
         cmd.SetParameterValue("@PageSize", pageSize);
         var total = 0;
         using (var dr=cmd.ExecuteDataReader())
         {
             while (dr.Read())
             {
                 var messageModel = new MessageModel();
                 if (total == 0)
                 {
                     total = !Convert.IsDBNull(dr["Total"]) ? Convert.ToInt32(dr["Total"]) : 0;
                 }
                 messageModel.MessageId = !Convert.IsDBNull(dr["Id"]) ? Convert.ToInt32(dr["Id"]) : 0;
                 messageModel.UserId = !Convert.IsDBNull(dr["UserId"]) ? Convert.ToInt32(dr["UserId"]) : 0;
                 messageModel.Content = !Convert.IsDBNull(dr["MsgContent"]) ? dr["MsgContent"].ToString() : string.Empty;
                 messageModel.CreateTime = !Convert.IsDBNull(dr["CreateTime"]) ? Convert.ToDateTime(dr["CreateTime"]) : DateTime.MinValue;
                 messageModel.Status = !Convert.IsDBNull(dr["Status"]) ? Convert.ToInt32(dr["Status"]) : 0;
                 if (messageModel.MessageId > 0)
                 {
                     data.Add(messageModel);
                 }
             }
         }
         var result = new PagedList<MessageModel>(data, pageIndex, pageSize, total);
         return result;
     }
     
 }
 /// <summary>
 /// 同步一次性加载
 /// </summary>
 /// <param name="query"></param>
 /// <returns></returns>
 private ActionResult SyncQueryLoad(QueryModel query)
 {
     List<ParameterViewModel> parameterTreeNodes = ParameterRepository.FindByQuery(Sql.Builder.OrderBy("SortId ASC")).Select(parameter => parameter.ToDto()).ToList();
     //CommonHelper.SetState(parameterTreeNodes, ParameterLoadMode);//返回treegrid数据时会进行处理
     PagedList<ParameterViewModel> result =new PagedList<ParameterViewModel>(parameterTreeNodes, query.Page, query.Rows);
     return new TreeGridResult(result, ParameterLoadMode != LoadMode.Sync, result.TotalItemCount).GetResult();
 }
Beispiel #17
0
        public void PagedList_BuildPagingLastPage_Valid()
        {
            const int page = 3;
            const int pageSize = 1;
            const int shownEitherSide = 1;
            const string url = "url";

            List<string> source = new List<string> { "one", "two", "three" };

            var pagedList = new PagedList<string>(source.AsEnumerable(), page, pageSize);

            var actual = pagedList.BuildPagingLinks(shownEitherSide, url);

            const string expected = "<div class=\"pagination\">" +
                                        "<span class=\"page\"></span>" +
                                        "<ul>" +
                                            "<li><a href=\"url?page=1\">First</a></li>" +
                                            "<li><a href=\"url?page=2\">Prev</a></li>" +
                                            "<li><a href=\"url?page=1\">... </a></li>" +
                                            "<li><a href=\"url?page=2\">2</a></li>" +
                                            "<li class=\"current\"><a href=\"url?page=3\">3</a></li>" +
                                            "<li><a href=\"url?page=3\">Next</a></li>" +
                                            "<li><a href=\"url?page=3\">Last</a></li>" +
                                        "</ul>" +
                                    "</div>";

            Assert.AreEqual(expected, actual);
        }
         /// <summary>
        /// Get the List ofEmployeedto.
        /// </summary>
        /// <param name="_EmployeeDto">The Employee dto.</param>
        /// <example><code> HTTP GET: api/Employee/?pageindex=1&pagesize=10&....</code></example>
        /// <returns>DatagridData List of EmployeeDto</returns>
        public object Get([FromUri] EmployeeDto _EmployeeDtos, int pageIndex =1, int pageSize =10)
        {
		    var pagedlist = new PagedList<EmployeeDto>  {_EmployeeDtos };
            pagedlist.PageIndex = pageIndex;
            pagedlist.PageSize = pageSize;
            return _EmployeeBO.FindAll(pagedlist);
        }
 public async static Task<PagedList<Article>> FindAllAsync(string type, string query = null, IEnumerable<string> fields = null, int page = 1, int pageSize = 20, string orderBy = null, SortOrder sortOrder = SortOrder.Descending )
 {
     var service = ObjectFactory.Build<IArticleService>();
     var request = new FindAllArticleRequest()
     {
         Type = type,
         Query = query,
         PageNumber = page,
         PageSize = pageSize,
         OrderBy = orderBy,
         SortOrder = sortOrder
     };
     var response = await service.FindAllAsync(request);
     if (response.Status.IsSuccessful == false)
         throw response.Status.ToFault();
     var articles = new PagedList<Article>()
     {
         PageNumber = response.PagingInfo.PageNumber,
         PageSize = response.PagingInfo.PageSize,
         TotalRecords = response.PagingInfo.TotalRecords,
         GetNextPage = async skip => await FindAllAsync(type, query, fields, page+skip+1, pageSize)
     };
     articles.AddRange(response.Articles);
     return articles;
     
 }
        /// <summary>
        /// Searches for lessons based on input parameters. Lessons are paginated and a single paged is returned
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<PagedList<Lesson>> Search(LessonViewModel model) 
        {
            PagedList<Lesson> page = new PagedList<Lesson>();

            IQueryable<Lesson> lessons = SearchedLesson(
                model.Keyword,
                model.InContent,
                model.Discipline,
                model.School,
                model.Classroom,
                model.Rate,
                model.Tags,
                model.PublishedOn,
                model.PublishedBy
            );

            page.Count = lessons.Count();
            page.StartRow = model.StartRow;
            page.PageSize = model.PageSize;

            lessons = lessons.OrderBy(model.OrderBy + " " + model.OrderDir).Skip(model.StartRow).Take(model.PageSize);
            page.Records = await lessons.ToListAsync<Lesson>();

            return page;
        }
        //
        // GET: /InformationBrokerConsole/Labor/
        public ActionResult Index(int id = 1)
        {
            int pageIndex = id;
            int pageSize = SystemConst.CountPerPage;
            int startIndex = (pageIndex - 1) * pageSize + 1;
            string whereClause = " 1=1 ";

            //--数据权限----------------------------------------------------------------------
            string informationBrokerGuid = BusinessUserBLL.CurrentUser.EnterpriseKey;
            if (string.IsNullOrWhiteSpace(informationBrokerGuid))
            {
                whereClause += " AND 1=2 ";
            }
            else
            {
                whereClause += string.Format(" AND [InformationBrokerUserGuid]= '{0}' ", informationBrokerGuid);
            }
            //--end--------------------------------------------------------------------------

            string orderClause = "LaborID DESC";

            PagedEntityCollection<LaborEntity> entityList = LaborBLL.Instance.GetPagedCollection(startIndex, pageSize, whereClause, orderClause);
            PagedList<LaborEntity> pagedExList = new PagedList<LaborEntity>(entityList.Records, entityList.PageIndex, entityList.PageSize, entityList.TotalCount);

            return View(pagedExList);
        }
 public TransactionsViewModel(IEnumerable<Transaction> transactions, int pageNumber, int pageSize)
 {
     PageNumber = pageNumber;
     PageSize = pageSize;
     Transactions = transactions;
     PagedTransactions = new PagedList<Transaction>(transactions, pageNumber,pageSize);
 }
Beispiel #23
0
        public void GivenThatPageIsFirstOne_WhenCreatingPagedList_ThenPreviousPageNumberIsNull()
        {
            var superset = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            var pagedList = new PagedList<int>(superset.AsQueryable(), 1, 1);

            Assert.IsNull(pagedList.PreviousPageNumber);
        }
 /// <summary>
 /// 同步一次性加载
 /// </summary>
 /// <param name="query"></param>
 /// <returns></returns>
 private ActionResult SyncQueryLoad(QueryModel query)
 {
     List<MenuViewModel> treeNodes = MenuRepository.FindByQuery(Sql.Builder.OrderBy("SortId ASC")).Select(menu => menu.ToDto()).ToList();
     CommonHelper.SetState(treeNodes,MenuLoadMode);
     PagedList<MenuViewModel> result = new PagedList<MenuViewModel>(treeNodes, query.Page, query.Rows);
     return new TreeGridResult(result, true, result.TotalItemCount).GetResult();
 }
        public PartialViewResult RenderFlickrSetList(int? id)
        {
            IEnumerable<FlickrSets> flickrSets = _flickrImageService.GetList();
            PagedList<FlickrSets> fs = new PagedList<FlickrSets>(flickrSets, id ?? 1, 5, flickrSets.Count());

            return PartialView("_FlickrSets", fs);
        }
 public ActionResult Article(int? id, string keywords, int? page)
 {
     ((dynamic) base.ViewBag).Keywords = Globals.HtmlDecode(keywords);
     if (this.WebSiteSet != null)
     {
         ((dynamic) base.ViewBag).Title = Globals.HtmlDecode(this.WebSiteSet.WebTitle) + "-" + Globals.HtmlDecode(this.WebSiteSet.WebName);
         ((dynamic) base.ViewBag).Description = Globals.HtmlDecode(this.WebSiteSet.Description);
     }
     ((dynamic) base.ViewBag).Domain = this.WebSiteSet.BaseHost;
     ((dynamic) base.ViewBag).WebName = this.WebSiteSet.WebName;
     ((dynamic) base.ViewBag).HotWordss = keywords;
     if (keywords == null)
     {
         return base.View();
     }
     if (keywords.Length > 0x19)
     {
         return base.View();
     }
     Maticsoft.BLL.CMS.Content content = new Maticsoft.BLL.CMS.Content();
     int pageSize = 10;
     page = new int?((page.HasValue && (page.Value > 1)) ? page.Value : 1);
     int startIndex = (page.Value > 1) ? (((page.Value - 1) * pageSize) + 1) : 0;
     int endIndex = page.Value * pageSize;
     int recordCount = content.GetRecordCount(id, keywords);
     PagedList<Maticsoft.Model.CMS.Content> model = null;
     List<Maticsoft.Model.CMS.Content> list2 = content.GetList(id, startIndex, endIndex, keywords);
     string valueByCache = ConfigSystem.GetValueByCache("ArticleIsStatic");
     List<Maticsoft.Model.CMS.Content> items = new List<Maticsoft.Model.CMS.Content>();
     string str2 = ConfigSystem.GetValueByCache("MainArea");
     if ((list2 != null) && (list2.Count > 0))
     {
         foreach (Maticsoft.Model.CMS.Content content2 in list2)
         {
             if (valueByCache == "true")
             {
                 content2.SeoUrl = PageSetting.GetCMSUrl(content2.ContentID, "CMS", ApplicationKeyType.CMS);
             }
             else if (str2 == "CMS")
             {
                 content2.SeoUrl = "/Article/Details/" + content2.ContentID;
             }
             else
             {
                 content2.SeoUrl = "/CMS/Article/Details/" + content2.ContentID;
             }
             items.Add(content2);
         }
     }
     if ((items != null) && (items.Count > 0))
     {
         int? nullable = page;
         model = new PagedList<Maticsoft.Model.CMS.Content>(items, nullable.HasValue ? nullable.GetValueOrDefault() : 1, pageSize, recordCount);
     }
     if (base.Request.IsAjaxRequest())
     {
         return this.PartialView("~/Areas/CMS/Themes/Default/Views/Partial/UCjQuerySearchList.cshtml", model);
     }
     return base.View(model);
 }
        public ActionResult  Search(string query, int page = 1)
        {
            var modelContent = RuntimeContext.Instance.ContentService.GetContent(System.Web.HttpContext.Current);
            var newModel = Mapper.Map<SearchResultsModel>(modelContent);
            
            var results = RuntimeContext.Instance.SearchService.Search(query);
            
            var searchResults = new List<SearchResultModel>();

            foreach (var result in results)
            {
                var content = RuntimeContext.Instance.ContentService.GetContent(result.Url);

                if (content == null || content.Type == "BlogComment") continue;

                result.Content = content;
                searchResults.Add(result);
            }

            var paged = new PagedList<SearchResultModel>(searchResults.AsQueryable(), page, 10);

            newModel.Query = query;
            newModel.SearchResults = paged;

            return View(newModel);
        }
Beispiel #28
0
        public void GivenThatPageIsSecondOne_WhenCreatingPagedList_ThenPreviousPageNumberIsOne()
        {
            var superset = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            var pagedList = new PagedList<int>(superset.AsQueryable(), 2, 1);

            Assert.AreEqual(1, pagedList.PreviousPageNumber.Value);
        }
Beispiel #29
0
 public IndexModel(PagedList<News> news)
     : this()
 {
     if (news == null)
         throw new ArgumentNullException("the news is null!!!");
     this.news = news;
 }
        /// <summary>
        /// Returns a PagedList of items.
        /// </summary>
        /// <param name="pageIndex">Zero-based index for lookup.</param>
        /// <param name="pageSize">Number of items to return in a page.</param>
        /// <returns></returns>
        public PagedList<HtmlContent> Get(int pageIndex, int pageSize, out int totalCount)
        {
            var resultSet = new PagedList<HtmlContent>(Get(), pageIndex, pageSize);
            totalCount = resultSet.TotalCount;

            return resultSet;
        }
Beispiel #31
0
        public async Task <IActionResult> GetDepartmentADs([FromQuery] Params parameters)
        {
            if (!(parameters.AccountId > 0))
            {
                var allDepartments = await _context.DomainDepartments
                                     .Include(d => d.Department)
                                     .ToListAsync();

                var toReturn = _mapper.Map <IEnumerable <DomainDepartmentForListDto> >(allDepartments);
                return(Ok(toReturn));
            }
            var source = _context.DomainDepartments
                         .Include(d => d.Department)
                         .AsQueryable();

            if (!string.IsNullOrEmpty(parameters.Order))
            {
                if (parameters.OrderAsc)
                {
                    switch (parameters.Order)
                    {
                    case "adName":
                        source = source.OrderBy(s => s.Name);
                        break;

                    case "dbName":
                        source = source.OrderBy(s => s.Department.Name);
                        break;
                    }
                }
                else
                {
                    switch (parameters.Order)
                    {
                    case "domainName":
                        source = source.OrderByDescending(s => s.Name);
                        break;

                    case "dbName":
                        source = source.OrderByDescending(s => s.Department.Name);
                        break;
                    }
                }
            }
            else
            {
                source = source.OrderBy(s => s.Name);
            }
            if (!string.IsNullOrEmpty(parameters.Filter))
            {
                var f = parameters.Filter.ToLower();
                source = source.Where(s => s.Name.ToLower().Contains(f) ||
                                      s.Department.Name.ToLower().Contains(f)
                                      );
            }
            var result = await PagedList <DomainDepartment> .CreateAsync(source, parameters.PageNumber, parameters.PageSize);

            var departments = _mapper.Map <IEnumerable <DomainDepartmentForListDto> >(result);

            Response.AddPagination(result.CurrentPage, result.PageSize, result.TotalCount, result.TotalPages);
            return(Ok(departments));
        }
Beispiel #32
0
 public static LogsDto ToModel(this PagedList <Log> logs)
 {
     return(Mapper.Map <LogsDto>(logs));
 }
 public PagedList<TDestinationElement> MapToViewModelPagedList<TSourceElement, TDestinationElement>(PagedList<TSourceElement> model)
 {
     var mappedList = MapPagedListElements<TSourceElement, TDestinationElement>(model);
     var index = model.PagerInfo.PageIndex;
     var pageSize = model.PagerInfo.PageSize;
     var totalCount = model.PagerInfo.TotalCount;
     return new PagedList<TDestinationElement>(mappedList, index, pageSize, totalCount);
 }
        /// <summary>
        /// Gets the paged result.
        /// </summary>
        /// <typeparam name="T">The Base Model</typeparam>
        /// <param name="routeName">Name of the route.</param>
        /// <param name="routeValues">The route values.</param>
        /// <param name="obj">The object.</param>
        /// <returns>
        /// The paged result.
        /// </returns>
        private PagedResult <T> GetPagedResult <T>(string routeName, object routeValues, PagedList <T> obj) where T : BaseModel
        {
            PagedResult <T> result = new PagedResult <T>(obj);

            if (!(result.Items == null || result.Items.Count == 0))
            {
                this.SetHateoasLinks <T>(result.Items);
            }

            if (!(string.IsNullOrWhiteSpace(routeName) || routeValues == null))
            {
                this.SetPageLinks <T>(routeName, routeValues, result, obj);
            }

            return(result);
        }
        /// <summary>
        /// Gets the search result.
        /// </summary>
        /// <typeparam name="T">The Base Model</typeparam>
        /// <param name="routeName">Name of the route.</param>
        /// <param name="routeValues">The route values.</param>
        /// <param name="obj">The object.</param>
        /// <returns>The http result.</returns>
        protected IHttpActionResult GetSearchResult <T>(string routeName, IDictionary <string, object> routeValues, PagedList <T> obj) where T : BaseModel
        {
            PagedResult <T> result = this.GetPagedResult <T>(routeName, routeValues, obj);

            return(this.Ok <PagedResult <T> >(result));
        }
        /// <summary>
        /// Gets the result.
        /// </summary>
        /// <typeparam name="T">The Base Model</typeparam>
        /// <param name="routeName">Name of the route.</param>
        /// <param name="routeValues">The route values.</param>
        /// <param name="obj">The object.</param>
        /// <returns>The http result.</returns>
        protected IHttpActionResult GetResult <T>(string routeName, IDictionary <string, object> routeValues, PagedList <T> obj) where T : BaseModel
        {
            if (obj == null || obj.Values == null || obj.Values.Count == 0)
            {
                return(this.NotFound());
            }

            return(this.GetSearchResult <T>(routeName, routeValues, obj));
        }
Beispiel #37
0
        //Lấy danh sách Brand và phân trang
        public async Task <PagedList <MaterialDto> > GetWithPaginations(PaginationParams param)
        {
            var lists = _repoLine.FindAll().ProjectTo <MaterialDto>(_configMapper).OrderByDescending(x => x.ID);

            return(await PagedList <MaterialDto> .CreateAsync(lists, param.PageNumber, param.PageSize));
        }
        /// <summary>
        /// Gets the newsletter subscription list
        /// </summary>
        /// <param name="email">Email to search or string. Empty to load all records.</param>
        /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>
        /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>
        /// <param name="userRoleId">User role identifier. Used to filter subscribers by user role. 0 to load all records.</param>
        /// <param name="isActive">Value indicating whether subscriber record should be active or not; null to load all records</param>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        /// <returns>NewsLetterSubscription entities</returns>
        public virtual IPagedList <NewsLetterSubscription> GetAllNewsLetterSubscriptions(string email            = null,
                                                                                         DateTime?createdFromUtc = null, DateTime?createdToUtc = null,
                                                                                         bool?isActive           = null, int userRoleId = 0,
                                                                                         int pageIndex           = 0, int pageSize      = int.MaxValue)
        {
            if (userRoleId == 0)
            {
                //do not filter by user role
                var query = _subscriptionRepository.Table;
                if (!string.IsNullOrEmpty(email))
                {
                    query = query.Where(nls => nls.Email.Contains(email));
                }
                if (createdFromUtc.HasValue)
                {
                    query = query.Where(nls => nls.CreatedOnUtc >= createdFromUtc.Value);
                }
                if (createdToUtc.HasValue)
                {
                    query = query.Where(nls => nls.CreatedOnUtc <= createdToUtc.Value);
                }
                if (isActive.HasValue)
                {
                    query = query.Where(nls => nls.Active == isActive.Value);
                }
                query = query.OrderBy(nls => nls.Email);

                var subscriptions = new PagedList <NewsLetterSubscription>(query, pageIndex, pageSize);
                return(subscriptions);
            }

            //filter by user role
            var guestRole = _userService.GetUserRoleBySystemName(NopUserDefaults.GuestsRoleName);

            if (guestRole == null)
            {
                throw new NopException("'Guests' role could not be loaded");
            }

            if (guestRole.Id == userRoleId)
            {
                //guests
                var query = _subscriptionRepository.Table;
                if (!string.IsNullOrEmpty(email))
                {
                    query = query.Where(nls => nls.Email.Contains(email));
                }
                if (createdFromUtc.HasValue)
                {
                    query = query.Where(nls => nls.CreatedOnUtc >= createdFromUtc.Value);
                }
                if (createdToUtc.HasValue)
                {
                    query = query.Where(nls => nls.CreatedOnUtc <= createdToUtc.Value);
                }
                if (isActive.HasValue)
                {
                    query = query.Where(nls => nls.Active == isActive.Value);
                }
                query = query.Where(nls => !_userRepository.Table.Any(c => c.Email == nls.Email));
                query = query.OrderBy(nls => nls.Email);

                var subscriptions = new PagedList <NewsLetterSubscription>(query, pageIndex, pageSize);
                return(subscriptions);
            }
            else
            {
                //other user roles (not guests)
                var query = _subscriptionRepository.Table.Join(_userRepository.Table,
                                                               nls => nls.Email,
                                                               c => c.Email,
                                                               (nls, c) => new
                {
                    NewsletterSubscribers = nls,
                    User = c
                });

                if (!string.IsNullOrEmpty(email))
                {
                    query = query.Where(x => x.NewsletterSubscribers.Email.Contains(email));
                }
                if (createdFromUtc.HasValue)
                {
                    query = query.Where(x => x.NewsletterSubscribers.CreatedOnUtc >= createdFromUtc.Value);
                }
                if (createdToUtc.HasValue)
                {
                    query = query.Where(x => x.NewsletterSubscribers.CreatedOnUtc <= createdToUtc.Value);
                }
                if (isActive.HasValue)
                {
                    query = query.Where(x => x.NewsletterSubscribers.Active == isActive.Value);
                }
                query = query.OrderBy(x => x.NewsletterSubscribers.Email);

                var subscriptions = new PagedList <NewsLetterSubscription>(query.Select(x => x.NewsletterSubscribers), pageIndex, pageSize);
                return(subscriptions);
            }
        }
Beispiel #39
0
        /// <summary>
        /// Get best sellers report
        /// </summary>
        /// <param name="storeId">Store identifier (orders placed in a specific store); 0 to load all records</param>
        /// <param name="vendorId">Vendor identifier; 0 to load all records</param>
        /// <param name="categoryId">Category identifier; 0 to load all records</param>
        /// <param name="manufacturerId">Manufacturer identifier; 0 to load all records</param>
        /// <param name="createdFromUtc">Order created date from (UTC); null to load all records</param>
        /// <param name="createdToUtc">Order created date to (UTC); null to load all records</param>
        /// <param name="os">Order status; null to load all records</param>
        /// <param name="ps">Order payment status; null to load all records</param>
        /// <param name="ss">Shipping status; null to load all records</param>
        /// <param name="billingCountryId">Billing country identifier; 0 to load all records</param>
        /// <param name="orderBy">1 - order by quantity, 2 - order by total amount</param>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Result</returns>
        public virtual IPagedList <BestsellersReportLine> BestSellersReport(
            int categoryId          = 0, int manufacturerId = 0,
            int storeId             = 0, int vendorId       = 0,
            DateTime?createdFromUtc = null, DateTime?createdToUtc = null,
            OrderStatus?os          = null, PaymentStatus?ps = null, ShippingStatus?ss = null,
            int billingCountryId    = 0,
            int orderBy             = 1,
            int pageIndex           = 0, int pageSize = int.MaxValue,
            bool showHidden         = false)
        {
            #region Extensions by QuanNH
            var _storeMappingService = Nop.Core.Infrastructure.EngineContext.Current.Resolve <Nop.Services.Stores.IStoreMappingService>();
            storeId = _storeMappingService.CurrentStore();

            #endregion

            int?orderStatusId = null;
            if (os.HasValue)
            {
                orderStatusId = (int)os.Value;
            }

            int?paymentStatusId = null;
            if (ps.HasValue)
            {
                paymentStatusId = (int)ps.Value;
            }

            int?shippingStatusId = null;
            if (ss.HasValue)
            {
                shippingStatusId = (int)ss.Value;
            }

            var query1 = from orderItem in _orderItemRepository.Table
                         join o in _orderRepository.Table on orderItem.OrderId equals o.Id
                         join p in _productRepository.Table on orderItem.ProductId equals p.Id
                         //join pc in _productCategoryRepository.Table on p.Id equals pc.ProductId into p_pc from pc in p_pc.DefaultIfEmpty()
                         //join pm in _productManufacturerRepository.Table on p.Id equals pm.ProductId into p_pm from pm in p_pm.DefaultIfEmpty()
                         where (storeId == 0 || storeId == o.StoreId) &&
                         (!createdFromUtc.HasValue || createdFromUtc.Value <= o.CreatedOnUtc) &&
                         (!createdToUtc.HasValue || createdToUtc.Value >= o.CreatedOnUtc) &&
                         (!orderStatusId.HasValue || orderStatusId == o.OrderStatusId) &&
                         (!paymentStatusId.HasValue || paymentStatusId == o.PaymentStatusId) &&
                         (!shippingStatusId.HasValue || shippingStatusId == o.ShippingStatusId) &&
                         (!o.Deleted) &&
                         (!p.Deleted) &&
                         (vendorId == 0 || p.VendorId == vendorId) &&
                         //(categoryId == 0 || pc.CategoryId == categoryId) &&
                         //(manufacturerId == 0 || pm.ManufacturerId == manufacturerId) &&
                         (categoryId == 0 || p.ProductCategories.Count(pc => pc.CategoryId == categoryId) > 0) &&
                         (manufacturerId == 0 || p.ProductManufacturers.Count(pm => pm.ManufacturerId == manufacturerId) > 0) &&
                         (billingCountryId == 0 || o.BillingAddress.CountryId == billingCountryId) &&
                         (showHidden || p.Published)
                         select orderItem;

            IQueryable <BestsellersReportLine> query2 =
                //group by products
                from orderItem in query1
                group orderItem by orderItem.ProductId into g
                select new BestsellersReportLine
            {
                ProductId     = g.Key,
                TotalAmount   = g.Sum(x => x.PriceExclTax),
                TotalQuantity = g.Sum(x => x.Quantity),
            }
            ;

            switch (orderBy)
            {
            case 1:
            {
                query2 = query2.OrderByDescending(x => x.TotalQuantity);
            }
            break;

            case 2:
            {
                query2 = query2.OrderByDescending(x => x.TotalAmount);
            }
            break;

            default:
                throw new ArgumentException("Wrong orderBy parameter", "orderBy");
            }

            var result = new PagedList <BestsellersReportLine>(query2, pageIndex, pageSize);
            return(result);
        }
Beispiel #40
0
        public async Task <IActionResult> GetDbUsers([FromQuery] Params parameters)
        {
            var allAccounts = await _context.Accounts
                              .Include(a => a.AccountRoles).ThenInclude(r => r.Role)
                              .Include(d => d.Department).ThenInclude(d => d.DomainDepartments)
                              .ToListAsync();

            var source = _mapper.Map <IEnumerable <AccountForListDto> >(allAccounts);

            if (!(parameters.AccountId > 0))
            {
                return(Ok(source));
            }
            if (!string.IsNullOrEmpty(parameters.Order))
            {
                if (parameters.OrderAsc)
                {
                    switch (parameters.Order)
                    {
                    case "name":
                        source = source.OrderBy(s => s.Name);
                        break;

                    case "fullname":
                        source = source.OrderBy(s => s.Fullname);
                        break;

                    case "department":
                        source = source.OrderBy(s => s.Department.Name);
                        break;
                    }
                }
                else
                {
                    switch (parameters.Order)
                    {
                    case "name":
                        source = source.OrderByDescending(s => s.Name);
                        break;

                    case "fullname":
                        source = source.OrderByDescending(s => s.Fullname);
                        break;

                    case "department":
                        source = source.OrderByDescending(s => s.Department.Name);
                        break;
                    }
                }
            }
            else
            {
                source = source.OrderBy(s => s.Name);
            }
            if (!string.IsNullOrEmpty(parameters.Filter))
            {
                var f = parameters.Filter.ToLower();
                source = source.Where(s => s.Name.ToLower().Contains(f) ||
                                      s.Fullname.ToLower().Contains(f) ||
                                      s.Department.Name.ToLower().Contains(f) ||
                                      s.AccountRoles.Any(r => r.Name.ToLower().Contains(f))
                                      );
            }
            var result = PagedList <AccountForListDto> .Create(source, parameters.PageNumber, parameters.PageSize);

            //var accounts = _mapper.Map<IEnumerable<AccountForListDto>>(result);
            Response.AddPagination(result.CurrentPage, result.PageSize, result.TotalCount, result.TotalPages);
            return(Ok(result));
        }
Beispiel #41
0
        public virtual IPagedList <Customer> GetAllCustomers(DateTime?registrationFrom,
                                                             DateTime?registrationTo, int[] customerRoleIds, string email, string username,
                                                             string firstName, string lastName, int dayOfBirth, int monthOfBirth,
                                                             string company, string phone, string zipPostalCode,
                                                             bool loadOnlyWithShoppingCart, ShoppingCartType?sct, int pageIndex, int pageSize)
        {
            var query = _customerRepository.Table;

            if (registrationFrom.HasValue)
            {
                query = query.Where(c => registrationFrom.Value <= c.CreatedOnUtc);
            }
            if (registrationTo.HasValue)
            {
                query = query.Where(c => registrationTo.Value >= c.CreatedOnUtc);
            }
            query = query.Where(c => !c.Deleted);
            if (customerRoleIds != null && customerRoleIds.Length > 0)
            {
                query = query.Where(c => c.CustomerRoles.Select(cr => cr.Id).Intersect(customerRoleIds).Count() > 0);
            }
            if (!String.IsNullOrWhiteSpace(email))
            {
                query = query.Where(c => c.Email.Contains(email));
            }
            if (!String.IsNullOrWhiteSpace(username))
            {
                query = query.Where(c => c.Username.Contains(username));
            }
            if (!String.IsNullOrWhiteSpace(firstName))
            {
                query = query
                        .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y })
                        .Where((z => z.Attribute.KeyGroup == "Customer" &&
                                z.Attribute.Key == SystemCustomerAttributeNames.FirstName &&
                                z.Attribute.Value.Contains(firstName)))
                        .Select(z => z.Customer);
            }
            if (!String.IsNullOrWhiteSpace(lastName))
            {
                query = query
                        .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y })
                        .Where((z => z.Attribute.KeyGroup == "Customer" &&
                                z.Attribute.Key == SystemCustomerAttributeNames.LastName &&
                                z.Attribute.Value.Contains(lastName)))
                        .Select(z => z.Customer);
            }
            //date of birth is stored as a string into database.
            //we also know that date of birth is stored in the following format YYYY-MM-DD (for example, 1983-02-18).
            //so let's search it as a string
            if (dayOfBirth > 0 && monthOfBirth > 0)
            {
                //both are specified
                string dateOfBirthStr = monthOfBirth.ToString("00", CultureInfo.InvariantCulture) + "-" + dayOfBirth.ToString("00", CultureInfo.InvariantCulture);
                //EndsWith is not supported by SQL Server Compact
                //so let's use the following workaround http://social.msdn.microsoft.com/Forums/is/sqlce/thread/0f810be1-2132-4c59-b9ae-8f7013c0cc00

                //we also cannot use Length function in SQL Server Compact (not supported in this context)
                //z.Attribute.Value.Length - dateOfBirthStr.Length = 5
                //dateOfBirthStr.Length = 5
                query = query
                        .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y })
                        .Where((z => z.Attribute.KeyGroup == "Customer" &&
                                z.Attribute.Key == SystemCustomerAttributeNames.DateOfBirth &&
                                z.Attribute.Value.Substring(5, 5) == dateOfBirthStr))
                        .Select(z => z.Customer);
            }
            else if (dayOfBirth > 0)
            {
                //only day is specified
                string dateOfBirthStr = dayOfBirth.ToString("00", CultureInfo.InvariantCulture);
                //EndsWith is not supported by SQL Server Compact
                //so let's use the following workaround http://social.msdn.microsoft.com/Forums/is/sqlce/thread/0f810be1-2132-4c59-b9ae-8f7013c0cc00

                //we also cannot use Length function in SQL Server Compact (not supported in this context)
                //z.Attribute.Value.Length - dateOfBirthStr.Length = 8
                //dateOfBirthStr.Length = 2
                query = query
                        .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y })
                        .Where((z => z.Attribute.KeyGroup == "Customer" &&
                                z.Attribute.Key == SystemCustomerAttributeNames.DateOfBirth &&
                                z.Attribute.Value.Substring(8, 2) == dateOfBirthStr))
                        .Select(z => z.Customer);
            }
            else if (monthOfBirth > 0)
            {
                //only month is specified
                string dateOfBirthStr = "-" + monthOfBirth.ToString("00", CultureInfo.InvariantCulture) + "-";
                query = query
                        .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y })
                        .Where((z => z.Attribute.KeyGroup == "Customer" &&
                                z.Attribute.Key == SystemCustomerAttributeNames.DateOfBirth &&
                                z.Attribute.Value.Contains(dateOfBirthStr)))
                        .Select(z => z.Customer);
            }
            //search by company
            if (!String.IsNullOrWhiteSpace(company))
            {
                query = query
                        .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y })
                        .Where((z => z.Attribute.KeyGroup == "Customer" &&
                                z.Attribute.Key == SystemCustomerAttributeNames.Company &&
                                z.Attribute.Value.Contains(company)))
                        .Select(z => z.Customer);
            }
            //search by phone
            if (!String.IsNullOrWhiteSpace(phone))
            {
                query = query
                        .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y })
                        .Where((z => z.Attribute.KeyGroup == "Customer" &&
                                z.Attribute.Key == SystemCustomerAttributeNames.Phone &&
                                z.Attribute.Value.Contains(phone)))
                        .Select(z => z.Customer);
            }
            //search by zip
            if (!String.IsNullOrWhiteSpace(zipPostalCode))
            {
                query = query
                        .Join(_gaRepository.Table, x => x.Id, y => y.EntityId, (x, y) => new { Customer = x, Attribute = y })
                        .Where((z => z.Attribute.KeyGroup == "Customer" &&
                                z.Attribute.Key == SystemCustomerAttributeNames.ZipPostalCode &&
                                z.Attribute.Value.Contains(zipPostalCode)))
                        .Select(z => z.Customer);
            }

            if (loadOnlyWithShoppingCart)
            {
                int?sctId = null;
                if (sct.HasValue)
                {
                    sctId = (int)sct.Value;
                }

                query = sct.HasValue ?
                        query.Where(c => c.ShoppingCartItems.Where(x => x.ShoppingCartTypeId == sctId).Count() > 0) :
                        query.Where(c => c.ShoppingCartItems.Count() > 0);
            }

            query = query.OrderByDescending(c => c.CreatedOnUtc);

            var customers = new PagedList <Customer>(query, pageIndex, pageSize);

            return(customers);
        }
Beispiel #42
0
        public static void AddPaginationHeader <T>(this IPaginationController controller, PaginationRequest request, PagedList <T> list, string action, Guid?entityId = null, string filter = null, IEnumerable <string> fields = null)
        {
            string previousPageLink = list.HasPreviousPage ? controller.CreatePageUri(request, PaginationUriType.PreviousPage, action, entityId, filter, fields) : null;
            string nextPageLink     = list.HasNextPage ? controller.CreatePageUri(request, PaginationUriType.NextPage, action, entityId, filter, fields) : null;

            var paginationMetadata = new
            {
                totalCount  = list.TotalCount,
                pageSize    = list.PageSize,
                totalPages  = list.TotalPages,
                currentPage = list.CurrentPage,
                nextPageLink,
                previousPageLink
            };

            controller.Response.Headers.Add("Access-Control-Expose-Headers", "X-Pagination");
            controller.Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationMetadata));
        }
Beispiel #43
0
        public async Task <PagedList <VehicleModel> > ReadVehicleModels(IReadVehicleModelsParams readParams)
        {
            var vehicleModelsJoinQuery = dbSet
                                         .Join(dbContext.Set <VehicleMakeEntity>(),
                                               model => model.MakeId,
                                               make => make.Id,
                                               (model, make) => new VehicleModel
            {
                Id   = model.Id,
                Name = model.Name,
                Abrv = model.Abrv,
                Make = new VehicleMake {
                    Id = make.Id, Name = make.Name, Abrv = make.Abrv
                }
            });

            var nameFilter     = !string.IsNullOrWhiteSpace(readParams.Name) ? readParams.Name.Trim() : null;
            var abrvFilter     = !string.IsNullOrWhiteSpace(readParams.Abrv) ? readParams.Abrv.Trim() : null;
            var makeNameFilter = !string.IsNullOrWhiteSpace(readParams.MakeName) ? readParams.MakeName.Trim() : null;
            var makeFilter     = !string.IsNullOrWhiteSpace(readParams.MakeName) ? readParams.MakeName.Trim() : null;

            if (nameFilter != null)
            {
                vehicleModelsJoinQuery =
                    vehicleModelsJoinQuery.Where(n => n.Name == nameFilter);
            }
            if (abrvFilter != null)
            {
                vehicleModelsJoinQuery =
                    vehicleModelsJoinQuery.Where(n => n.Abrv == abrvFilter);
            }
            if (makeNameFilter != null)
            {
                vehicleModelsJoinQuery =
                    vehicleModelsJoinQuery.Where(n => n.Make.Name == makeNameFilter);
            }

            var orderBy = !string.IsNullOrWhiteSpace(readParams.OrderBy) ? readParams.OrderBy.Trim().ToLowerInvariant() : null;

            if (orderBy != null)
            {
                vehicleModelsJoinQuery = orderBy switch
                {
                    string value when value == "name" || value == "name_desc" => value == "name_desc" ?
                    vehicleModelsJoinQuery.OrderByDescending(s => s.Name)
                                               : vehicleModelsJoinQuery.OrderBy(s => s.Name),
                    string value when value == "abrv" || value == "abrv_desc" => value == "abrv_desc" ?
                    vehicleModelsJoinQuery.OrderByDescending(s => s.Abrv)
                                                : vehicleModelsJoinQuery.OrderBy(s => s.Abrv),
                    string value when value == "makename" || value == "makename_desc" => value == "name_desc" ?
                    vehicleModelsJoinQuery.OrderByDescending(s => s.Make.Name)
                                                : vehicleModelsJoinQuery.OrderBy(s => s.Make.Name),
                    _ => vehicleModelsJoinQuery.OrderBy(s => s.Name),
                };
            }

            var pagedVehicleModels = await PagedList <VehicleModel>
                                     .CreateAsync(vehicleModelsJoinQuery, readParams.PageSize, readParams.PageNumber);

            return(pagedVehicleModels);
        }
Beispiel #44
0
        public virtual IPagedList <CSCZJ.Core.Domain.Properties.PropertyEdit> GetAllEditRecords(IList <int> governmentIds, string checkState = "", string search = "", int pageIndex = 0, int pageSize = int.MaxValue, params PropertySortCondition[] sortConditions)
        {
            var query       = _propertyEditRepository.Table.AsNoTracking();
            var currentUser = _workContext.CurrentAccountUser;

            //query = GetAllProperties(governmentId, includeChildren);

            Expression <Func <CSCZJ.Core.Domain.Properties.PropertyEdit, bool> > expression = p => !p.Deleted;

            if (governmentIds != null && governmentIds.Count > 0)
            {
                expression = expression.And(p => governmentIds.Contains(p.SuggestGovernmentId));
            }

            //字符串查询
            if (!string.IsNullOrEmpty(search))
            {
                expression = expression.And(p => p.Title.Contains(search) || p.ASuggestion.Contains(search) || p.DSuggestion.Contains(search));
            }

            switch (checkState)
            {
            case "unchecked":
                if (currentUser.IsGovAuditor() || currentUser.IsStateOwnerAuditor())
                {
                    expression = expression.And(p => p.State == PropertyApproveState.AdminApprove);
                }
                else if (currentUser.Government.ParentGovernmentId == 0)
                {
                    expression = expression.And(p => p.State == PropertyApproveState.DepartmentApprove || (p.State == PropertyApproveState.Start & p.SuggestGovernmentId == currentUser.Government.Id));
                }
                else
                {
                    expression = expression.And(p => p.State == PropertyApproveState.Start);
                }
                break;

            case "checked":
                if (currentUser.IsGovAuditor() || currentUser.IsStateOwnerAuditor())
                {
                    expression = expression.And(p => p.State == PropertyApproveState.Finish);
                }
                else if (currentUser.Government.ParentGovernmentId == 0)
                {
                    expression = expression.And(p => p.State == PropertyApproveState.Finish || p.State == PropertyApproveState.AdminApprove);
                }
                else
                {
                    expression = expression.And(p => p.State == PropertyApproveState.Finish);
                }
                break;

            case "all":
                //expression = expression.And(p => p.State != PropertyApproveState.Start);
                break;
            }

            query = query.Where(expression);

            if (sortConditions != null && sortConditions.Length != 0)
            {
                query = query.Sort(sortConditions);
            }
            else
            {
                query = query.Sort(new PropertySortCondition[1] {
                    new PropertySortCondition("DisplayOrder", System.ComponentModel.ListSortDirection.Ascending)
                });
            }

            var propertiesNewCreateRecords = new PagedList <CSCZJ.Core.Domain.Properties.PropertyEdit>(query, pageIndex, pageSize);

            return(propertiesNewCreateRecords);
        }
Beispiel #45
0
        public ActionResult Show(int id, string name, string order_by, int?page)
        {
            var user = !Current.User.IsAnonymous && Current.User.Id == id ? Current.User : Current.DB.Users.Get(id);

            if (user == null)
            {
                return(PageNotFound());
            }

            // if this user has a display name, and the title is missing or does not match, permanently redirect to it
            if (user.UrlTitle.HasValue() && (string.IsNullOrEmpty(name) || name != user.UrlTitle))
            {
                return(PageMovedPermanentlyTo($"/users/{user.ProfilePath}{Request.Url.Query}"));
            }

            SetHeader(user.Login);
            SelectMenuItem("Users");

            var profileTabs = new SubHeader
            {
                Selected = order_by,
                Items    = new List <SubHeaderViewData>
                {
                    new SubHeaderViewData
                    {
                        Description = "edited",
                        Title       = "Recently edited queries",
                        Href        = "/users/" + user.ProfilePath + "?order_by=edited",
                        Default     = true,
                    },
                    new SubHeaderViewData
                    {
                        Description = "favorite",
                        Title       = "Favorite queries",
                        Href        = "/users/" + user.ProfilePath + "?order_by=favorite"
                    },
                    new SubHeaderViewData
                    {
                        Description = "recent",
                        Title       = "Recently executed queries",
                        Href        = "/users/" + user.ProfilePath + "?order_by=recent"
                    }
                }
            };

            ViewData["UserQueryHeaders"] = profileTabs;

            page = Math.Max(page ?? 1, 1);
            int?pagesize = 15;  // In case we decide to make this a query param

            int    start  = ((page.Value - 1) * pagesize.Value) + 1;
            int    finish = page.Value * pagesize.Value;
            string message;
            var    builder = new SqlBuilder();
            var    pager   = builder.AddTemplate(@"
                SELECT *
                FROM (SELECT /**select**/, ROW_NUMBER() OVER(/**orderby**/) AS RowNumber
                        FROM Queries q
                             /**join**/
                             /**leftjoin**/
                             /**where**/
                    ) AS results
                WHERE RowNumber BETWEEN @start AND @finish
             ORDER BY RowNumber",
                                                 new { start, finish }
                                                 );
            var counter = builder.AddTemplate("SELECT COUNT(*) FROM Queries q /**join**/ /**leftjoin**/ /**where**/");

            if (order_by == "recent")
            {
                builder.Select("re.RevisionId AS Id");
                builder.Select("re.LastRun");
                builder.Select("s.TinyName AS SiteName");
                builder.Where("re.UserId = @user", new { user = id });
                builder.Join("Revisions r ON r.QueryId = q.Id");
                builder.Join("RevisionExecutions re ON re.RevisionId = r.Id");
                builder.Join("Sites s ON s.Id = re.SiteId");
                builder.Join(@"QuerySets qs ON qs.Id = r.OriginalQuerySetId");
                builder.OrderBy("re.LastRun DESC");

                message = user.Id == CurrentUser.Id ?
                          "You have never ran any queries" : "No queries ran recently";
            }
            else
            {
                builder.Select("qs.CurrentRevisionId AS Id");
                builder.Select("qs.LastActivity AS LastRun");
                builder.Join("Revisions r on r.QueryId = q.Id");
                builder.Join("QuerySets qs on qs.CurrentRevisionId = r.Id");

                if (order_by == "favorite")
                {
                    builder.Join(@"
                        Votes v ON
                        v.QuerySetId = qs.Id AND
                        v.UserId = @user AND
                        v.VoteTypeId = @vote",
                                 new { user = id, vote = (int)VoteType.Favorite }
                                 );
                    builder.OrderBy("v.Id DESC");
                    message = user.Id == CurrentUser.Id ?
                              "You have no favorite queries, click the star icon on a query to favorite it" : "No favorites";
                }
                else
                {
                    builder.Where("qs.OwnerId = @user", new { user = id });
                    builder.Where("qs.Hidden = 0");
                    builder.OrderBy("qs.LastActivity DESC");

                    message = user.Id == CurrentUser.Id ?
                              "You haven't edited any queries" : "No queries";
                }
            }

            builder.Select("qs.Id as QuerySetId");
            builder.Select("u.Id as CreatorId");
            builder.Select("u.Login as CreatorLogin");
            builder.Select("qs.Title AS Name");
            builder.Select("qs.[Description] AS [Description]");
            builder.Select("qs.Votes AS FavoriteCount");
            builder.Select("qs.Views AS Views");
            builder.Select("q.QueryBody AS [SQL]");
            builder.LeftJoin("Users u ON u.Id = qs.OwnerId");

            var queries = Current.DB.Query <QueryExecutionViewData>(
                pager.RawSql,
                pager.Parameters
                ).Select(
                view =>
            {
                view.SiteName = (view.SiteName ?? Site.TinyName).ToLower();
                return(view);
            }
                );
            int total = Current.DB.Query <int>(counter.RawSql, counter.Parameters).First();

            ViewData["Href"]    = $"/users/{user.ProfilePath}?order_by={profileTabs.Selected}";
            ViewData["Queries"] = new PagedList <QueryExecutionViewData>(queries, page.Value, pagesize.Value, false, total);

            if (!queries.Any())
            {
                ViewData["EmptyMessage"] = message;
            }

            return(View(user));
        }
Beispiel #46
0
 public async Task <PagedList <Categoria> > GetCategorias(CategoriasParameters categoriasParameters)
 {
     return(await PagedList <Categoria> .ToPagedList(Get().OrderBy(on => on.CategoriaId),
                                                     categoriasParameters.PageNumber, categoriasParameters.PageSize));
 }
Beispiel #47
0
        public ActionResult MpProvide()
        {
            PagedList <Ocean.Entity.MpCenter> list = MpCenterService.GetPageList(PageIndex, PageSize);

            return(JsonList <MpCenter>(list, list.TotalItemCount));
        }
Beispiel #48
0
        private PagedList <User> GetUserList(string selected, int?page, string search)
        {
            int perPage     = 36;
            int currentPage = Math.Max(page ?? 1, 1);
            var builder     = new SqlBuilder();
            var pager       = builder.AddTemplate(@"
                SELECT *,
                    (SELECT COUNT(*) FROM QuerySets WHERE OwnerId = Y.Id) SavedQueriesCount,
                    (SELECT COUNT(*) FROM RevisionExecutions WHERE UserId = Y.Id) QueryExecutionsCount
                FROM
                (
                    SELECT * FROM
                    (
                        SELECT ROW_NUMBER() OVER (/**orderby**/) AS Row, Users.Id, Users.Login, Users.Email,
                               Users.IPAddress, Users.IsAdmin, Users.CreationDate /**select**/
                          FROM Users /**join**/ /**where**/
                    ) AS X
                    WHERE Row > @start AND Row <= @finish
                ) AS Y
                ORDER BY Row ASC",
                                                  new { start = (currentPage - 1) * perPage, finish = currentPage * perPage }
                                                  );
            var counter = builder.AddTemplate("SELECT COUNT(*) FROM Users /**join**/ /**where**/");

            if (selected == "all")
            {
                builder.OrderBy("Login ASC");
            }
            else
            {
                var activePeriod = 30; // Last 30 days

                // We should probably just be...actually recording the user's LastActivityDate,
                // instead of performing this join all the time
                builder.Select(", LastRun AS LastActivityDate");
                builder.Join(@"(
                    SELECT UserId, MAX(LastRun) AS LastRun FROM RevisionExecutions GROUP BY UserId
                ) AS LastExecutions ON LastExecutions.UserId = Users.Id");
                builder.OrderBy("LastRun DESC");
                builder.Where("LastRun >= @since", new { since = DateTime.UtcNow.AddDays(-activePeriod).Date });
            }

            var url = "/users?order_by=" + selected;

            ViewData["SearchHref"] = "/users/search?order_by=" + selected;

            if (search.HasValue() && search.Length > 2)
            {
                url += "&search=" + HtmlUtilities.UrlEncode(search);
                ViewData["UserSearch"] = search;

                builder.Where("Login LIKE @search", new { search = '%' + search + '%' });
            }

            ViewData["Href"] = url;

            var rows  = Current.DB.Query <User>(pager.RawSql, pager.Parameters);
            var total = Current.DB.Query <int>(counter.RawSql, counter.Parameters).First();
            var users = new PagedList <User>(rows, currentPage, perPage, false, total);

            return(users);
        }
        /// <summary>
        /// Prepare the sitemap model
        /// </summary>
        /// <param name="pageModel">Sitemap page model</param>
        /// <returns>Sitemap model</returns>
        public virtual SitemapModel PrepareSitemapModel(SitemapPageModel pageModel)
        {
            var cacheKey = string.Format(NopModelCacheDefaults.SitemapPageModelKey,
                                         _workContext.WorkingLanguage.Id,
                                         string.Join(",", _customerService.GetCustomerRoleIds(_workContext.CurrentCustomer)),
                                         _storeContext.CurrentStore.Id);

            var cachedModel = _cacheManager.Get(cacheKey, () =>
            {
                //get URL helper
                var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);

                var model = new SitemapModel();

                //prepare common items
                var commonGroupTitle = _localizationService.GetResource("Sitemap.General");

                //home page
                model.Items.Add(new SitemapModel.SitemapItemModel
                {
                    GroupTitle = commonGroupTitle,
                    Name       = _localizationService.GetResource("Homepage"),
                    Url        = urlHelper.RouteUrl("Homepage")
                });

                //search
                model.Items.Add(new SitemapModel.SitemapItemModel
                {
                    GroupTitle = commonGroupTitle,
                    Name       = _localizationService.GetResource("Search"),
                    Url        = urlHelper.RouteUrl("ProductSearch")
                });

                //news
                if (_newsSettings.Enabled)
                {
                    model.Items.Add(new SitemapModel.SitemapItemModel
                    {
                        GroupTitle = commonGroupTitle,
                        Name       = _localizationService.GetResource("News"),
                        Url        = urlHelper.RouteUrl("NewsArchive")
                    });
                }

                //blog
                if (_blogSettings.Enabled)
                {
                    model.Items.Add(new SitemapModel.SitemapItemModel
                    {
                        GroupTitle = commonGroupTitle,
                        Name       = _localizationService.GetResource("Blog"),
                        Url        = urlHelper.RouteUrl("Blog")
                    });
                }

                //forums
                if (_forumSettings.ForumsEnabled)
                {
                    model.Items.Add(new SitemapModel.SitemapItemModel
                    {
                        GroupTitle = commonGroupTitle,
                        Name       = _localizationService.GetResource("Forum.Forums"),
                        Url        = urlHelper.RouteUrl("Boards")
                    });
                }

                //contact us
                model.Items.Add(new SitemapModel.SitemapItemModel
                {
                    GroupTitle = commonGroupTitle,
                    Name       = _localizationService.GetResource("ContactUs"),
                    Url        = urlHelper.RouteUrl("ContactUs")
                });

                //customer info
                model.Items.Add(new SitemapModel.SitemapItemModel
                {
                    GroupTitle = commonGroupTitle,
                    Name       = _localizationService.GetResource("Account.MyAccount"),
                    Url        = urlHelper.RouteUrl("CustomerInfo")
                });

                //at the moment topics are in general category too
                if (_sitemapSettings.SitemapIncludeTopics)
                {
                    var topics = _topicService.GetAllTopics(storeId: _storeContext.CurrentStore.Id)
                                 .Where(topic => topic.IncludeInSitemap);

                    model.Items.AddRange(topics.Select(topic => new SitemapModel.SitemapItemModel
                    {
                        GroupTitle = commonGroupTitle,
                        Name       = _localizationService.GetLocalized(topic, x => x.Title),
                        Url        = urlHelper.RouteUrl("Topic", new { SeName = _urlRecordService.GetSeName(topic) })
                    }));
                }

                //blog posts
                if (_sitemapSettings.SitemapIncludeBlogPosts && _blogSettings.Enabled)
                {
                    var blogPostsGroupTitle = _localizationService.GetResource("Sitemap.BlogPosts");
                    var blogPosts           = _blogService.GetAllBlogPosts(storeId: _storeContext.CurrentStore.Id)
                                              .Where(p => p.IncludeInSitemap);

                    model.Items.AddRange(blogPosts.Select(post => new SitemapModel.SitemapItemModel
                    {
                        GroupTitle = blogPostsGroupTitle,
                        Name       = post.Title,
                        Url        = urlHelper.RouteUrl("BlogPost", new { SeName = _urlRecordService.GetSeName(post) })
                    }));
                }

                //news
                if (_sitemapSettings.SitemapIncludeNews && _newsSettings.Enabled)
                {
                    var newsGroupTitle = _localizationService.GetResource("Sitemap.News");
                    var news           = _newsService.GetAllNews(storeId: _storeContext.CurrentStore.Id);
                    model.Items.AddRange(news.Select(newsItem => new SitemapModel.SitemapItemModel
                    {
                        GroupTitle = newsGroupTitle,
                        Name       = newsItem.Title,
                        Url        = urlHelper.RouteUrl("NewsItem", new { SeName = _urlRecordService.GetSeName(newsItem) })
                    }));
                }

                //categories
                if (_sitemapSettings.SitemapIncludeCategories)
                {
                    var categoriesGroupTitle = _localizationService.GetResource("Sitemap.Categories");
                    var categories           = _categoryService.GetAllCategories(storeId: _storeContext.CurrentStore.Id);
                    model.Items.AddRange(categories.Select(category => new SitemapModel.SitemapItemModel
                    {
                        GroupTitle = categoriesGroupTitle,
                        Name       = _localizationService.GetLocalized(category, x => x.Name),
                        Url        = urlHelper.RouteUrl("Category", new { SeName = _urlRecordService.GetSeName(category) })
                    }));
                }

                //manufacturers
                if (_sitemapSettings.SitemapIncludeManufacturers)
                {
                    var manufacturersGroupTitle = _localizationService.GetResource("Sitemap.Manufacturers");
                    var manufacturers           = _manufacturerService.GetAllManufacturers(storeId: _storeContext.CurrentStore.Id);
                    model.Items.AddRange(manufacturers.Select(manufacturer => new SitemapModel.SitemapItemModel
                    {
                        GroupTitle = manufacturersGroupTitle,
                        Name       = _localizationService.GetLocalized(manufacturer, x => x.Name),
                        Url        = urlHelper.RouteUrl("Manufacturer", new { SeName = _urlRecordService.GetSeName(manufacturer) })
                    }));
                }

                //products
                if (_sitemapSettings.SitemapIncludeProducts)
                {
                    var productsGroupTitle = _localizationService.GetResource("Sitemap.Products");
                    var products           = _productService.SearchProducts(storeId: _storeContext.CurrentStore.Id, visibleIndividuallyOnly: true);
                    model.Items.AddRange(products.Select(product => new SitemapModel.SitemapItemModel
                    {
                        GroupTitle = productsGroupTitle,
                        Name       = _localizationService.GetLocalized(product, x => x.Name),
                        Url        = urlHelper.RouteUrl("Product", new { SeName = _urlRecordService.GetSeName(product) })
                    }));
                }

                //product tags
                if (_sitemapSettings.SitemapIncludeProductTags)
                {
                    var productTagsGroupTitle = _localizationService.GetResource("Sitemap.ProductTags");
                    var productTags           = _productTagService.GetAllProductTags();
                    model.Items.AddRange(productTags.Select(productTag => new SitemapModel.SitemapItemModel
                    {
                        GroupTitle = productTagsGroupTitle,
                        Name       = _localizationService.GetLocalized(productTag, x => x.Name),
                        Url        = urlHelper.RouteUrl("ProductsByTag", new { SeName = _urlRecordService.GetSeName(productTag) })
                    }));
                }

                return(model);
            });

            //prepare model with pagination
            pageModel.PageSize   = Math.Max(pageModel.PageSize, _sitemapSettings.SitemapPageSize);
            pageModel.PageNumber = Math.Max(pageModel.PageNumber, 1);

            var pagedItems   = new PagedList <SitemapModel.SitemapItemModel>(cachedModel.Items, pageModel.PageNumber - 1, pageModel.PageSize);
            var sitemapModel = new SitemapModel {
                Items = pagedItems
            };

            sitemapModel.PageModel.LoadPagedList(pagedItems);

            return(sitemapModel);
        }
Beispiel #50
0
        public ActionResult Set(Int32 id = 1)
        {
            PagedList <ProblemEntity> list = ProblemManager.GetProblemSet(id);

            return(ViewWithPager(list, id));
        }
 public ReceivingExpenseListViewModel()
 {
     FilterModel  = new ReceivingExpenseListFilterModel();
     PagedList    = new PagedList <ReceivingExpenseModel>();
     SearchWheres = new List <SelectListItem>();
 }
Beispiel #52
0
        public void SetupMeetingMock()
        {
            var meetingsDto = new List <MeetingDto> {
                new MeetingDto {
                    MeetingId   = 1,
                    AdminId     = 1,
                    Description = "meeting mock 1, ya pasó",
                    Date        = DateTime.Now.AddDays(-10),
                    MaxPeople   = 10,
                    City        = new CityDto {
                        CityId    = 1,
                        Name      = "La Plata",
                        Latitude  = -34.9214,
                        Longitude = -57.9544
                    }
                }, new MeetingDto {
                    MeetingId   = 2,
                    AdminId     = 1,
                    Description = "meeting mock 2, es mañana",
                    Date        = new DateTime(2021, 1, 20, 20, 0, 0, 0),
                    MaxPeople   = 10,
                    City        = new CityDto {
                        CityId    = 1,
                        Name      = "La Plata",
                        Latitude  = -34.9214,
                        Longitude = -57.9544
                    }
                }, new MeetingDto {
                    MeetingId   = 3,
                    AdminId     = 1,
                    Description = "meeting mock 3, dentro de 10 dias",
                    Date        = DateTime.Now.AddDays(10),
                    MaxPeople   = 10,
                    City        = new CityDto {
                        CityId    = 1,
                        Name      = "La Plata",
                        Latitude  = -34.9214,
                        Longitude = -57.9544
                    }
                }, new MeetingDto {
                    MeetingId   = 4,
                    AdminId     = 1,
                    Description = "meeting mock 1, dentro de 4 dias",
                    Date        = DateTime.Now.AddDays(4),
                    MaxPeople   = 10,
                    City        = new CityDto {
                        CityId    = 1,
                        Name      = "La Plata",
                        Latitude  = -34.9214,
                        Longitude = -57.9544
                    }
                },
            };

            var pagedList = PagedList <MeetingDto> .Create(meetingsDto, 1, 2);// son 2 paginas de 2 elementos

            var mock = new Mock <IMeetingService>();

            mock.Setup(m => m.GetMeetings(null)).ReturnsAsync(pagedList);
            mock.Setup(m => m.GetMeeting(2)).ReturnsAsync(meetingsDto.Where(
                                                              x => x.MeetingId == 2).FirstOrDefault());
            mock.Setup(m => m.GetAttendedCount(2)).ReturnsAsync(10);
            _meetingService = mock.Object;
        }
        public PagedList <ValueSetConcept> GetValueSetConcepts(ValueSetConceptPaginationParameters parameters)
        {
            var collection = _context.ValueSetConcepts
                             .Join(_context.ValueSetVersions,
                                   vsc => vsc.ValueSetVersionID,
                                   vsv => vsv.ValueSetVersionID,
                                   (vsc, vsv) => new ValueSetConcept()
            {
                ValueSetConceptID             = vsc.ValueSetConceptID,
                CodeSystemConceptName         = vsc.CodeSystemConceptName,
                ValueSetConceptStatusCode     = vsc.ValueSetConceptStatusCode,
                ValueSetConceptStatusDate     = vsc.ValueSetConceptStatusDate,
                ValueSetConceptDefinitionText = vsc.ValueSetConceptDefinitionText != "NULL" ? vsc.ValueSetConceptDefinitionText : string.Empty,
                CDCPreferredDesignation       = vsc.CDCPreferredDesignation,
                ScopeNoteText         = vsc.ScopeNoteText,
                ValueSetVersionID     = vsc.ValueSetVersionID,
                CodeSystemOID         = vsc.CodeSystemOID,
                ConceptCode           = vsc.ConceptCode,
                Sequence              = vsc.Sequence,
                ValueSetOID           = vsv.ValueSetOID,
                ValueSetVersionNumber = vsv.ValueSetVersionNumber
            })
                             .Join(_context.ValueSets,
                                   vsc => vsc.ValueSetOID,
                                   vs => vs.ValueSetOID,
                                   (vsc, vs) => new ValueSetConcept()
            {
                ValueSetConceptID             = vsc.ValueSetConceptID,
                CodeSystemConceptName         = vsc.CodeSystemConceptName,
                ValueSetConceptStatusCode     = vsc.ValueSetConceptStatusCode,
                ValueSetConceptStatusDate     = vsc.ValueSetConceptStatusDate,
                ValueSetConceptDefinitionText = vsc.ValueSetConceptDefinitionText,
                CDCPreferredDesignation       = vsc.CDCPreferredDesignation,
                ScopeNoteText         = vsc.ScopeNoteText,
                ValueSetVersionID     = vsc.ValueSetVersionID,
                CodeSystemOID         = vsc.CodeSystemOID,
                ConceptCode           = vsc.ConceptCode,
                Sequence              = vsc.Sequence,
                ValueSetOID           = vsc.ValueSetOID,
                ValueSetVersionNumber = vsc.ValueSetVersionNumber,
                ValueSetCode          = vs.ValueSetCode
            })
                             .Join(_context.CodeSystems,
                                   vsc => vsc.CodeSystemOID,
                                   cs => cs.CodeSystemOID,
                                   (vsc, cs) => new ValueSetConcept()
            {
                ValueSetConceptID             = vsc.ValueSetConceptID,
                CodeSystemConceptName         = vsc.CodeSystemConceptName,
                ValueSetConceptStatusCode     = vsc.ValueSetConceptStatusCode,
                ValueSetConceptStatusDate     = vsc.ValueSetConceptStatusDate,
                ValueSetConceptDefinitionText = vsc.ValueSetConceptDefinitionText,
                CDCPreferredDesignation       = vsc.CDCPreferredDesignation,
                ScopeNoteText         = vsc.ScopeNoteText,
                ValueSetVersionID     = vsc.ValueSetVersionID,
                CodeSystemOID         = vsc.CodeSystemOID,
                ConceptCode           = vsc.ConceptCode,
                Sequence              = vsc.Sequence,
                ValueSetOID           = vsc.ValueSetOID,
                ValueSetVersionNumber = vsc.ValueSetVersionNumber,
                ValueSetCode          = vsc.ValueSetCode,
                HL70396Identifier     = cs.HL70396Identifier
            });

            if (!string.IsNullOrWhiteSpace(parameters.ValueSetCode))
            {
                collection = collection.Where(c =>
                                              c.ValueSetCode != null ?
                                              c.ValueSetCode.Equals(parameters.ValueSetCode, StringComparison.OrdinalIgnoreCase) :
                                              true
                                              );
            }
            if (!string.IsNullOrWhiteSpace(parameters.ValueSetOid))
            {
                collection = collection.Where(c =>
                                              c.ValueSetOID != null ?
                                              c.ValueSetOID.Equals(parameters.ValueSetOid) :
                                              true
                                              );
            }
            if (!string.IsNullOrWhiteSpace(parameters.ConceptCode))
            {
                collection = collection.Where(c =>
                                              c.ConceptCode != null ?
                                              c.ConceptCode.Equals(parameters.ConceptCode) :
                                              true
                                              );
            }
            if (parameters.ValueSetVersionId != null)
            {
                collection = collection.Where(c =>
                                              c.ValueSetVersionID != null ?
                                              c.ValueSetVersionID == parameters.ValueSetVersionId :
                                              true
                                              );
            }
            if (!string.IsNullOrWhiteSpace(parameters.SearchQuery))
            {
                var searchQueryStringForWhereClause = string.Empty;
                searchQueryStringForWhereClause = parameters.SearchQuery.Trim().ToLowerInvariant();

                if (parameters.SearchType == MatchType.Contains)
                {
                    collection = collection.Where(v =>
                                                  v.ValueSetConceptDefinitionText.ToLowerInvariant().Contains(searchQueryStringForWhereClause) ||
                                                  v.CDCPreferredDesignation.ToLowerInvariant().Contains(searchQueryStringForWhereClause)
                                                  );
                }
                else if (parameters.SearchType == MatchType.StartsWith)
                {
                    collection = collection.Where(v =>
                                                  v.ValueSetConceptDefinitionText.ToLowerInvariant().StartsWith(searchQueryStringForWhereClause) ||
                                                  v.CDCPreferredDesignation.ToLowerInvariant().StartsWith(searchQueryStringForWhereClause)
                                                  );
                }
            }

            if (parameters.ValueSetVersionNumber != null)
            {
                int versionNumber = 1;

                if (parameters.ValueSetVersionNumber.Equals("latest", StringComparison.OrdinalIgnoreCase))
                {
                    var max = collection.Max(v => v.ValueSetVersionNumber);
                    if (max.HasValue)
                    {
                        versionNumber = max.Value;
                    }
                }
                else
                {
                    int.TryParse(parameters.ValueSetVersionNumber, out versionNumber);
                }

                collection = collection.Where(c =>
                                              c.ValueSetVersionNumber != null ?
                                              c.ValueSetVersionNumber == versionNumber :
                                              true
                                              );
            }

            return(PagedList <ValueSetConcept> .Create(collection,
                                                       parameters.PageNumber,
                                                       parameters.PageSize));
        }
Beispiel #54
0
        protected override async Task <IEnumerable <RuleDescriptor> > LoadDescriptorsAsync()
        {
            var language   = _services.WorkContext.WorkingLanguage;
            var oneStarStr = T("Search.Facet.1StarAndMore").Value;
            var xStarsStr  = T("Search.Facet.XStarsAndMore").Value;

            var stores = _services.StoreContext.GetAllStores()
                         .Select(x => new RuleValueSelectListOption {
                Value = x.Id.ToString(), Text = x.Name
            })
                         .ToArray();

            var visibilities = ((ProductVisibility[])Enum.GetValues(typeof(ProductVisibility)))
                               .Select(x => new RuleValueSelectListOption {
                Value = ((int)x).ToString(), Text = _localizedEntityHelper.GetLocalizedEnum(x)
            })
                               .ToArray();

            var productTypes = ((ProductType[])Enum.GetValues(typeof(ProductType)))
                               .Select(x => new RuleValueSelectListOption {
                Value = ((int)x).ToString(), Text = _localizedEntityHelper.GetLocalizedEnum(x)
            })
                               .ToArray();

            var ratings = FacetUtility.GetRatings()
                          .Reverse()
                          .Skip(1)
                          .Select(x => new RuleValueSelectListOption
            {
                Value = ((double)x.Value).ToString(CultureInfo.InvariantCulture),
                Text  = (double)x.Value == 1 ? oneStarStr : xStarsStr.FormatInvariant(x.Value)
            })
                          .ToArray();

            var categoryTree = _catalogSettings.ShowProductsFromSubcategories
                ? await _categoryService.GetCategoryTreeAsync(includeHidden : true)
                : null;

            #region Special filters

            CatalogSearchQuery categoryFilter(SearchFilterContext ctx, int[] x)
            {
                if (x?.Any() ?? false)
                {
                    var ids = new HashSet <int>(x);

                    if (_catalogSettings.ShowProductsFromSubcategories)
                    {
                        foreach (var id in x)
                        {
                            var node = categoryTree.SelectNodeById(id);
                            if (node != null)
                            {
                                ids.AddRange(node.Flatten(false).Select(y => y.Id));
                            }
                        }
                    }

                    return(ctx.Query.WithCategoryIds(_catalogSettings.IncludeFeaturedProductsInNormalLists ? (bool?)null : false, ids.ToArray()));
                }

                return(ctx.Query);
            };

            CatalogSearchQuery stockQuantityFilter(SearchFilterContext ctx, int x)
            {
                if (ctx.Expression.Operator == RuleOperator.IsEqualTo || ctx.Expression.Operator == RuleOperator.IsNotEqualTo)
                {
                    return(ctx.Query.WithStockQuantity(x, x, ctx.Expression.Operator == RuleOperator.IsEqualTo, ctx.Expression.Operator == RuleOperator.IsEqualTo));
                }
                else if (ctx.Expression.Operator == RuleOperator.GreaterThanOrEqualTo || ctx.Expression.Operator == RuleOperator.GreaterThan)
                {
                    return(ctx.Query.WithStockQuantity(x, null, ctx.Expression.Operator == RuleOperator.GreaterThanOrEqualTo, null));
                }
                else if (ctx.Expression.Operator == RuleOperator.LessThanOrEqualTo || ctx.Expression.Operator == RuleOperator.LessThan)
                {
                    return(ctx.Query.WithStockQuantity(null, x, null, ctx.Expression.Operator == RuleOperator.LessThanOrEqualTo));
                }

                return(ctx.Query);
            };

            CatalogSearchQuery priceFilter(SearchFilterContext ctx, decimal x)
            {
                if (ctx.Expression.Operator == RuleOperator.IsEqualTo || ctx.Expression.Operator == RuleOperator.IsNotEqualTo)
                {
                    return(ctx.Query.PriceBetween(x, x, ctx.Expression.Operator == RuleOperator.IsEqualTo, ctx.Expression.Operator == RuleOperator.IsEqualTo));
                }
                else if (ctx.Expression.Operator == RuleOperator.GreaterThanOrEqualTo || ctx.Expression.Operator == RuleOperator.GreaterThan)
                {
                    return(ctx.Query.PriceBetween(x, null, ctx.Expression.Operator == RuleOperator.GreaterThanOrEqualTo, null));
                }
                else if (ctx.Expression.Operator == RuleOperator.LessThanOrEqualTo || ctx.Expression.Operator == RuleOperator.LessThan)
                {
                    return(ctx.Query.PriceBetween(null, x, null, ctx.Expression.Operator == RuleOperator.LessThanOrEqualTo));
                }

                return(ctx.Query);
            };

            CatalogSearchQuery createdFilter(SearchFilterContext ctx, DateTime x)
            {
                if (ctx.Expression.Operator == RuleOperator.IsEqualTo || ctx.Expression.Operator == RuleOperator.IsNotEqualTo)
                {
                    return(ctx.Query.CreatedBetween(x, x, ctx.Expression.Operator == RuleOperator.IsEqualTo, ctx.Expression.Operator == RuleOperator.IsEqualTo));
                }
                else if (ctx.Expression.Operator == RuleOperator.GreaterThanOrEqualTo || ctx.Expression.Operator == RuleOperator.GreaterThan)
                {
                    return(ctx.Query.CreatedBetween(x, null, ctx.Expression.Operator == RuleOperator.GreaterThanOrEqualTo, null));
                }
                else if (ctx.Expression.Operator == RuleOperator.LessThanOrEqualTo || ctx.Expression.Operator == RuleOperator.LessThan)
                {
                    return(ctx.Query.CreatedBetween(null, x, null, ctx.Expression.Operator == RuleOperator.LessThanOrEqualTo));
                }

                return(ctx.Query);
            };

            #endregion

            var descriptors = new List <SearchFilterDescriptor>
            {
                new SearchFilterDescriptor <int>((ctx, x) => ctx.Query.HasStoreId(x))
                {
                    Name        = "Store",
                    DisplayName = T("Admin.Rules.FilterDescriptor.Store"),
                    RuleType    = RuleType.Int,
                    SelectList  = new LocalRuleValueSelectList(stores),
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <int[]>((ctx, x) => ctx.Query.AllowedCustomerRoles(x))
                {
                    Name        = "CustomerRole",
                    DisplayName = T("Admin.Rules.FilterDescriptor.IsInCustomerRole"),
                    RuleType    = RuleType.IntArray,
                    SelectList  = new RemoteRuleValueSelectList("CustomerRole")
                    {
                        Multiple = true
                    },
                    Operators = new RuleOperator[] { RuleOperator.In }
                },
                new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.PublishedOnly(x))
                {
                    Name        = "Published",
                    DisplayName = T("Admin.Catalog.Products.Fields.Published"),
                    RuleType    = RuleType.Boolean,
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.AvailableOnly(x))
                {
                    Name        = "AvailableByStock",
                    DisplayName = T("Products.Availability.InStock"),
                    RuleType    = RuleType.Boolean,
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.AvailableByDate(x))
                {
                    Name        = "AvailableByDate",
                    DisplayName = T("Admin.Rules.FilterDescriptor.AvailableByDate"),
                    RuleType    = RuleType.Boolean,
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <int>((ctx, x) => ctx.Query.WithVisibility((ProductVisibility)x))
                {
                    Name        = "Visibility",
                    DisplayName = T("Admin.Catalog.Products.Fields.Visibility"),
                    RuleType    = RuleType.Int,
                    SelectList  = new LocalRuleValueSelectList(visibilities),
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <int[]>((ctx, x) => ctx.Query.WithProductIds(x))
                {
                    Name        = "Product",
                    DisplayName = T("Common.Entity.Product"),
                    RuleType    = RuleType.IntArray,
                    SelectList  = new RemoteRuleValueSelectList("Product")
                    {
                        Multiple = true
                    },
                    Operators = new RuleOperator[] { RuleOperator.In }
                },
                new SearchFilterDescriptor <int>((ctx, x) => ctx.Query.IsProductType((ProductType)x))
                {
                    Name        = "ProductType",
                    DisplayName = T("Admin.Catalog.Products.Fields.ProductType"),
                    RuleType    = RuleType.Int,
                    SelectList  = new LocalRuleValueSelectList(productTypes),
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <int[]>(categoryFilter)
                {
                    Name        = "Category",
                    DisplayName = T("Common.Entity.Category"),
                    RuleType    = RuleType.IntArray,
                    SelectList  = new RemoteRuleValueSelectList("Category")
                    {
                        Multiple = true
                    },
                    Operators = new RuleOperator[] { RuleOperator.In }
                },
                new SearchFilterDescriptor <int[]>((ctx, x) => ctx.Query.WithManufacturerIds(null, x))
                {
                    Name        = "Manufacturer",
                    DisplayName = T("Common.Entity.Manufacturer"),
                    RuleType    = RuleType.IntArray,
                    SelectList  = new RemoteRuleValueSelectList("Manufacturer")
                    {
                        Multiple = true
                    },
                    Operators = new RuleOperator[] { RuleOperator.In }
                },
                // Same logic as the filter above product list.
                new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.HasAnyCategory(!x))
                {
                    Name        = "WithoutCategory",
                    DisplayName = T("Admin.Catalog.Products.List.SearchWithoutCategories"),
                    RuleType    = RuleType.Boolean,
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.HasAnyManufacturer(!x))
                {
                    Name        = "WithoutManufacturer",
                    DisplayName = T("Admin.Catalog.Products.List.SearchWithoutManufacturers"),
                    RuleType    = RuleType.Boolean,
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <int[]>((ctx, x) => ctx.Query.WithProductTagIds(x))
                {
                    Name        = "ProductTag",
                    DisplayName = T("Admin.Catalog.Products.Fields.ProductTags"),
                    RuleType    = RuleType.IntArray,
                    SelectList  = new RemoteRuleValueSelectList("ProductTag")
                    {
                        Multiple = true
                    },
                    Operators = new RuleOperator[] { RuleOperator.In }
                },
                new SearchFilterDescriptor <int[]>((ctx, x) => ctx.Query.WithDeliveryTimeIds(x))
                {
                    Name        = "DeliveryTime",
                    DisplayName = T("Admin.Catalog.Products.Fields.DeliveryTime"),
                    RuleType    = RuleType.IntArray,
                    Operators   = new RuleOperator[] { RuleOperator.In },
                    SelectList  = new RemoteRuleValueSelectList("DeliveryTime")
                    {
                        Multiple = true
                    }
                },
                new SearchFilterDescriptor <int>(stockQuantityFilter)
                {
                    Name        = "StockQuantity",
                    DisplayName = T("Admin.Catalog.Products.Fields.StockQuantity"),
                    RuleType    = RuleType.Int
                },
                new SearchFilterDescriptor <decimal>(priceFilter)
                {
                    Name        = "Price",
                    DisplayName = T("Admin.Catalog.Products.Fields.Price"),
                    RuleType    = RuleType.Money
                },
                new SearchFilterDescriptor <DateTime>(createdFilter)
                {
                    Name        = "CreatedOn",
                    DisplayName = T("Common.CreatedOn"),
                    RuleType    = RuleType.DateTime
                },
                new SearchFilterDescriptor <double>((ctx, x) => ctx.Query.WithRating(x, null))
                {
                    Name        = "Rating",
                    DisplayName = T("Admin.Catalog.ProductReviews.Fields.Rating"),
                    RuleType    = RuleType.Float,
                    Operators   = new RuleOperator[] { RuleOperator.GreaterThanOrEqualTo },
                    SelectList  = new LocalRuleValueSelectList(ratings)
                },
                new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.HomePageProductsOnly(x))
                {
                    Name        = "HomepageProduct",
                    DisplayName = T("Admin.Catalog.Products.Fields.ShowOnHomePage"),
                    RuleType    = RuleType.Boolean,
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.DownloadOnly(x))
                {
                    Name        = "Download",
                    DisplayName = T("Admin.Catalog.Products.Fields.IsDownload"),
                    RuleType    = RuleType.Boolean,
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.RecurringOnly(x))
                {
                    Name        = "Recurring",
                    DisplayName = T("Admin.Catalog.Products.Fields.IsRecurring"),
                    RuleType    = RuleType.Boolean,
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.ShipEnabledOnly(x))
                {
                    Name        = "ShipEnabled",
                    DisplayName = T("Admin.Catalog.Products.Fields.IsShipEnabled"),
                    RuleType    = RuleType.Boolean,
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.FreeShippingOnly(x))
                {
                    Name        = "FreeShipping",
                    DisplayName = T("Admin.Catalog.Products.Fields.IsFreeShipping"),
                    RuleType    = RuleType.Boolean,
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.TaxExemptOnly(x))
                {
                    Name        = "TaxExempt",
                    DisplayName = T("Admin.Catalog.Products.Fields.IsTaxExempt"),
                    RuleType    = RuleType.Boolean,
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.EsdOnly(x))
                {
                    Name        = "Esd",
                    DisplayName = T("Admin.Catalog.Products.Fields.IsEsd"),
                    RuleType    = RuleType.Boolean,
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                },
                new SearchFilterDescriptor <bool>((ctx, x) => ctx.Query.HasDiscount(x))
                {
                    Name        = "Discount",
                    DisplayName = T("Admin.Catalog.Products.Fields.HasDiscountsApplied"),
                    RuleType    = RuleType.Boolean,
                    Operators   = new RuleOperator[] { RuleOperator.IsEqualTo }
                }
            };

            if (_services.ApplicationContext.ModuleCatalog.GetModuleByName("SmartStore.MegaSearchPlus") != null)
            {
                ISearchFilter[] filters(string fieldName, int parentId, int[] valueIds)
                {
                    return(valueIds.Select(id => SearchFilter.ByField(fieldName, id).ExactMatch().NotAnalyzed().HasParent(parentId)).ToArray());
                }

                // Sort by display order!
                var pageIndex     = -1;
                var variantsQuery = _services.DbContext.ProductAttributes
                                    .AsNoTracking()
                                    .Where(x => x.AllowFiltering)
                                    .OrderBy(x => x.DisplayOrder);

                while (true)
                {
                    var variants = await PagedList.Create(variantsQuery, ++pageIndex, 1000).LoadAsync();

                    foreach (var variant in variants)
                    {
                        var descriptor = new SearchFilterDescriptor <int[]>((ctx, x) => ctx.Query.WithFilter(SearchFilter.Combined(filters("variantvalueid", variant.Id, x))))
                        {
                            Name        = $"Variant{variant.Id}",
                            DisplayName = variant.GetLocalized(x => x.Name, language, true, false),
                            GroupKey    = "Admin.Catalog.Attributes.ProductAttributes",
                            RuleType    = RuleType.IntArray,
                            SelectList  = new RemoteRuleValueSelectList("VariantValue")
                            {
                                Multiple = true
                            },
                            Operators = new RuleOperator[] { RuleOperator.In }
                        };
                        descriptor.Metadata["ParentId"] = variant.Id;

                        descriptors.Add(descriptor);
                    }
                    if (!variants.HasNextPage)
                    {
                        break;
                    }
                }

                pageIndex = -1;
                var attributesQuery = _services.DbContext.SpecificationAttributes
                                      .AsNoTracking()
                                      .Where(x => x.AllowFiltering)
                                      .OrderBy(x => x.DisplayOrder);

                while (true)
                {
                    var attributes = await PagedList.Create(attributesQuery, ++pageIndex, 1000).LoadAsync();

                    foreach (var attribute in attributes)
                    {
                        var descriptor = new SearchFilterDescriptor <int[]>((ctx, x) => ctx.Query.WithFilter(SearchFilter.Combined(filters("attrvalueid", attribute.Id, x))))
                        {
                            Name        = $"Attribute{attribute.Id}",
                            DisplayName = attribute.GetLocalized(x => x.Name, language, true, false),
                            GroupKey    = "Admin.Catalog.Attributes.SpecificationAttributes",
                            RuleType    = RuleType.IntArray,
                            SelectList  = new RemoteRuleValueSelectList("AttributeOption")
                            {
                                Multiple = true
                            },
                            Operators = new RuleOperator[] { RuleOperator.In }
                        };
                        descriptor.Metadata["ParentId"] = attribute.Id;

                        descriptors.Add(descriptor);
                    }
                    if (!attributes.HasNextPage)
                    {
                        break;
                    }
                }
            }

            descriptors
            .Where(x => x.RuleType == RuleType.Money)
            .Each(x => x.Metadata["postfix"] = _services.StoreContext.CurrentStore.PrimaryStoreCurrency.CurrencyCode);

            return(descriptors.Cast <RuleDescriptor>());
        }
        public async Task OnGetAsync(string sortOrder, string searchString, int?transactorTypeFilter, int?pageIndex, int?pageSize)
        {
            LoadFilters();

            PageSize = (int)((pageSize == null || pageSize == 0) ? 20 : pageSize);
            // CurrentPageSize = PageSize;
            CurrentSort = sortOrder;
            NameSort    = sortOrder == "Name" ? "name_desc" : "Name";
            DateSort    = sortOrder == "Date" ? "date_desc" : "Date";

            if (searchString != null)
            {
                pageIndex = 1;
            }
            else
            {
                searchString = CurrentFilter;
            }
            CurrentFilter = searchString;
            if (transactorTypeFilter == null)
            {
                transactorTypeFilter = 0;
            }
            CurrentTransactorTypeFilter = (int)(transactorTypeFilter ?? 0);
            await LoadDiarysAsync();

            IQueryable <Transactor> fullListIq = from s in _context.Transactors
                                                 select s;

            if (!String.IsNullOrEmpty(searchString))
            {
                fullListIq = fullListIq.Where(s => s.Name.Contains(searchString));
            }

            if (transactorTypeFilter > 0)
            {
                fullListIq = fullListIq.Where(p => p.TransactorTypeId == transactorTypeFilter);
            }
            switch (sortOrder)
            {
            case "Name":
                fullListIq   = fullListIq.OrderBy(p => p.Name);
                NameSortIcon = "fas fa-sort-alpha-up ";
                DateSortIcon = "invisible";
                break;

            case "name_desc":
                fullListIq   = fullListIq.OrderByDescending(p => p.Name);
                NameSortIcon = "fas fa-sort-alpha-down ";
                DateSortIcon = "invisible";
                break;

            default:
                fullListIq = fullListIq.OrderBy(p => p.Id);
                break;
            }

            var t = fullListIq.ProjectTo <TransactorListDto>(_mapper.ConfigurationProvider);


            ListItems = await PagedList <TransactorListDto> .CreateAsync(
                t, pageIndex ?? 1, PageSize);
        }
Beispiel #56
0
        public ActionResult SearchAll(FormCollection f)
        {
            SearchInfoDto data      = new SearchInfoDto();
            string        sorter    = "def";
            int           min       = -1;
            int           max       = -1;
            int           day       = 0;
            List <string> hotelList = new List <string>();

            #region sorter

            if (f["sorter"] != null)
            {
                sorter = f["sorter"].ToString();
            }
            #endregion

            #region price

            if (f["priceFilter1"] != null)
            {
                min = 0;
                max = 200;
            }
            if (f["priceFilter2"] != null)
            {
                min = 201;
                max = 400;
            }
            if (f["priceFilter3"] != null)
            {
                min = 401;
                max = 600;
            }
            if (f["priceFilter4"] != null)
            {
                min = 601;
                max = 0;
            }
            #endregion

            #region day

            if (f["daysFilter2"] != null)
            {
                day = 2;
            }
            if (f["daysFilter4"] != null)
            {
                day = 4;
            }
            if (f["daysFilter6"] != null)
            {
                day = 6;
            }
            if (f["daysFilter8"] != null)
            {
                day = -1;
            }
            #endregion

            #region hotelList
            if (f["hotelFilter1"] != null)
            {
                hotelList.Add("招待所");
            }
            if (f["hotelFilter2"] != null)
            {
                hotelList.Add("度假村");
            }
            if (f["hotelFilter3"] != null)
            {
                hotelList.Add("农家乐");
            }
            if (f["hotelFilter4"] != null)
            {
                hotelList.Add("三星级");
            }

            if (f["hotelFilter5"] != null)
            {
                hotelList.Add("四星级");
            }
            if (f["hotelFilter6"] != null)
            {
                hotelList.Add("五星级");
            }
            if (f["hotelFilter7"] != null)
            {
                hotelList.Add("经济型酒店");
            }
            if (f["hotelFilter8"] != null)
            {
                hotelList.Add("酒店式公寓");
            }

            #endregion

            #region bide

            if (f["txtBide"] != null)
            {
                data.Bide = f["txtBide"];
            }
            #endregion

            int total = 0;
            IQueryable <SearchTourDto> iq    = null;
            PagedList <SearchTourDto>  model = null;
            if (!string.IsNullOrEmpty(data.Bide))
            {
                iq    = searchService.GetSearchTourModelAdvanced(data.Bide, sorter, min, max, day, hotelList, 1, pageSize, ref total);
                model = new PagedList <SearchTourDto>(iq, 1, pageSize, total);
            }
            data.Bide = Server.UrlEncode(data.Bide);
            string typeList = string.Empty;
            foreach (var item in hotelList)
            {
                typeList += item + "|";
            }
            if (typeList.Length > 1)
            {
                typeList = typeList.Remove(typeList.Length - 1, 1);
            }
            ViewBag.para  = data;
            ViewBag.sort  = sorter;
            ViewBag.day   = day;
            ViewBag.min   = min;
            ViewBag.max   = max;
            ViewBag.hotel = Server.UrlEncode(typeList);
            return(View(model));
        }
        public async Task <PagedList <PhanBienDoAn> > GetAll(PhanBienDoAnParams userParams)
        {
            var result                 = _context.DanhSachPhanBienDoAn.Include(x => x.DoAn).Include(x => x.GiangVien).AsQueryable();
            var sortField              = userParams.SortField;
            var sortOrder              = userParams.SortOrder;
            var maDoAn                 = userParams.MaDoAn;
            var maGiangVien            = userParams.MaGiangVien;
            var thoiGianTaoBatDau      = userParams.ThoiGianTaoBatDau;
            var thoiGianTaoKetThuc     = userParams.ThoiGianTaoKetThuc;
            var thoiGianCapNhatBatDau  = userParams.ThoiGianCapNhatBatDau;
            var thoiGianCapNhatKetThuc = userParams.ThoiGianCapNhatKetThuc;
            var trangThai              = userParams.TrangThai;

            if (!string.IsNullOrEmpty(maGiangVien))
            {
                result = result.Where(x => x.MaGiangVien.ToLower().Contains(maGiangVien.ToLower()));
            }

            if (maDoAn > -1)
            {
                result = result.Where(x => x.MaDoAn == maDoAn);
            }

            if (thoiGianTaoBatDau.GetHashCode() != 0 && thoiGianTaoKetThuc.GetHashCode() != 0)
            {
                result = result.Where(x => x.ThoiGianTao >= thoiGianTaoBatDau && x.ThoiGianTao <= thoiGianTaoKetThuc);
            }

            if (thoiGianCapNhatBatDau.GetHashCode() != 0 && thoiGianCapNhatKetThuc.GetHashCode() != 0)
            {
                result = result.Where(x => x.ThoiGianCapNhat >= thoiGianCapNhatBatDau && x.ThoiGianCapNhat <= thoiGianCapNhatKetThuc);
            }

            if (trangThai > -1)
            {
                result = result.Where(x => x.TrangThai == trangThai);
            }

            if (!string.IsNullOrEmpty(sortField) && !string.IsNullOrEmpty(sortOrder))
            {
                switch (sortField)
                {
                case "MaDoAn":
                    if (string.Equals(sortOrder, "ASC", StringComparison.OrdinalIgnoreCase))
                    {
                        result = result.OrderBy(x => x.MaDoAn);
                    }
                    else
                    {
                        result = result.OrderByDescending(x => x.MaDoAn);
                    }
                    break;

                case "MaGiangVien":
                    if (string.Equals(sortOrder, "ASC", StringComparison.OrdinalIgnoreCase))
                    {
                        result = result.OrderBy(x => x.MaGiangVien);
                    }
                    else
                    {
                        result = result.OrderByDescending(x => x.MaGiangVien);
                    }
                    break;

                case "ThoiGianTao":
                    if (string.Equals(sortOrder, "ASC", StringComparison.OrdinalIgnoreCase))
                    {
                        result = result.OrderBy(x => x.ThoiGianTao);
                    }
                    else
                    {
                        result = result.OrderByDescending(x => x.ThoiGianTao);
                    }
                    break;

                case "ThoiGianCapNhat":
                    if (string.Equals(sortOrder, "ASC", StringComparison.OrdinalIgnoreCase))
                    {
                        result = result.OrderBy(x => x.ThoiGianCapNhat);
                    }
                    else
                    {
                        result = result.OrderByDescending(x => x.ThoiGianCapNhat);
                    }
                    break;

                case "TrangThai":
                    if (string.Equals(sortOrder, "ASC", StringComparison.OrdinalIgnoreCase))
                    {
                        result = result.OrderBy(x => x.TrangThai);
                    }
                    else
                    {
                        result = result.OrderByDescending(x => x.TrangThai);
                    }
                    break;

                default:
                    result = result.OrderByDescending(x => x.ThoiGianTao);
                    break;
                }
            }
            _total = result.Count();

            var totalPages  = (_total / userParams.PageSize) + 1;
            var hasNextPage = userParams.PageNumber < totalPages ? true : false;

            _hasNextPage = hasNextPage;
            return(await PagedList <PhanBienDoAn> .CreateAsync(result, userParams.PageNumber, userParams.PageSize));
        }
Beispiel #58
0
 // Get all orders for user.
 public async Task <PagedList <OrdUser> > GetOrdUsersAsync(
     ResourceParameters resourceParameters)
 => await PagedList <OrdUser> .CreateAsync(_userRepo.EntityDbSet,
                                           resourceParameters.PageNumber,
                                           resourceParameters.PageSize);
Beispiel #59
0
        public void BindGrid(int paramPageIndex, int paramPageSize)
        {

            //根据项目店铺查询广告费用 项目说明
            string min = this.DateTimeMin.ToString();
            string max = DateTime.Parse(this.DateTimeMax).AddDays(1).AddSeconds(-1).ToString();
            string pid = this.ProjectId.ToString();
            string nid = this.NickId.ToString();
            TimeSpan ts = DateTime.Parse(this.DateTimeMax) -  DateTime.Parse(this.DateTimeMin);
            //店铺集合
            List<int> nickIdList = new List<int>();
            #region 店铺条件查询集合 处理
            //选择某项目  
            if (pid != "-1")
            {
                if (nid == "-1")//项目下的所有店铺
                {
                    var nickList = base.XMNickService.GetXMNickListByProjectId(Convert.ToInt32(pid), 362);

                    // var NickListNew = nickList.Where(p => p.nick_id != 16 && p.nick_id != 17 && p.nick_id != 18).ToList();

                    if (nickList.Count > 0)
                    {
                        nickIdList = nickList.Select(p => p.nick_id).ToList();
                    }
                }
                else
                {

                    nickIdList.Add(Convert.ToInt32(nid));
                }
            }
            else
            {
                if (nid == "-1")
                {
                    var NickList = base.XMNickService.GetXMNickListByProjectId(Convert.ToInt32(pid), 362);

                    //var NickListNew = NickList.Where(p => p.nick_id != 16 && p.nick_id != 17 && p.nick_id != 18).ToList();

                    nickIdList = NickList.Select(a => a.nick_id).ToList();
                }
                else
                {
                    nickIdList.Add(Convert.ToInt32(nid));
                }

            }
            #endregion
            var XMAdvertisingFeeList = base.XMAdvertisingFeeService.GetXMXMAdvertisingFeeByDetails(nickIdList, DateTime.Parse(min), DateTime.Parse(max));

            if (XMAdvertisingFeeList.Count == 0 || (ts.Days * nickIdList.Count) > XMAdvertisingFeeList.Count)
            {
                foreach (var b in nickIdList)
                {
                    var imin = min;
                    while (DateTime.Parse(imin) <= DateTime.Parse(max))
                    {
                        var tj2 = base.XMAdvertisingFeeService.GetXMByIdmin(0, DateTime.Parse(imin));
                        if (tj2.Count != nickIdList.Count)
                        {
                            var tj = base.XMAdvertisingFeeService.GetXMByIdmin(b, DateTime.Parse(imin));
                            if (tj.Count == 0)
                            {
                                XMAdvertisingFee ps = new XMAdvertisingFee();
                                ps.NickId = Convert.ToInt32(b);
                                ps.Feedate = DateTime.Parse(imin);
                                ps.Fee = 0;
                                ps.CreatorID = HozestERPContext.Current.User.CustomerID;
                                ps.CreatorTime = DateTime.Now;
                                ps.UpdatorID = HozestERPContext.Current.User.CustomerID;
                                ps.UpdateTime = DateTime.Now;
                                base.XMAdvertisingFeeService.InsertXMAdvertisingFee(ps);
                            }
                        }
                        imin = DateTime.Parse(imin).AddDays(1).ToString();
                    }

                }
                XMAdvertisingFeeList = base.XMAdvertisingFeeService.GetXMXMAdvertisingFeeByDetails(nickIdList, DateTime.Parse(min), DateTime.Parse(max));
            }
            var pageList = new PagedList<XMAdvertisingFee>(XMAdvertisingFeeList, paramPageIndex, paramPageSize, this.Master.GridViewSortField, this.Master.GridViewSortDir.ToString());

            this.Master.BindData(this.grdvCWPlatformSpendingDetails, pageList);
        }
Beispiel #60
0
        public async Task <PagedList <Course> > GetCourses(CourseParam courseParams, int studentId)
        {
            var courses = _context.Courses.Where(course => course.StudentCourses.Any(sc => sc.StudentId == studentId));

            return(await PagedList <Course> .CreateAsync(courses, courseParams.PageNumber, courseParams.PageSize));
        }