Exemple #1
0
        public static async Task<PagingList<T>> CreateAsync(IOrderedQueryable<T> qry, int pageSize, int pageIndex)
        {
            var pageCount = (int)Math.Ceiling(await qry.CountAsync() / (double)pageSize);

            return new PagingList<T>(await qry.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(),
                                        pageSize, pageIndex, pageCount);
        }
Exemple #2
0
        public async Task <ActionResult> GetAlertsTable([System.Web.Http.FromBody] DataTableParameters dataTableParameters)
        {
            var userId = User.Identity.GetUserId();

            if (userId == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            using (var db = new ZapContext())
            {
                var sorts = dataTableParameters.Order;

                var pageUserAlertsQS = db.Users
                                       .Where(u => u.AppId == userId)
                                       .SelectMany(u => u.Alerts)
                                       .Include(m => m.PostLink)
                                       .Include(m => m.CommentLink)
                                       .Where(m => !m.IsDeleted);

                // Build our query and ensure default sort order
                IOrderedQueryable <UserAlert> pageUserAlertsQ = pageUserAlertsQS.OrderByDescending(m => m.TimeStamp);

                foreach (var s in sorts)
                {
                    if (s.Dir == "asc")
                    {
                        if (dataTableParameters.Columns[s.Column].Name == "Date")
                        {
                            pageUserAlertsQ = pageUserAlertsQS.OrderBy(q => q.TimeStamp ?? DateTime.UtcNow);
                        }
                    }
                    else
                    {
                        if (dataTableParameters.Columns[s.Column].Name == "Date")
                        {
                            pageUserAlertsQ = pageUserAlertsQS.OrderByDescending(q => q.TimeStamp ?? DateTime.UtcNow);
                        }
                    }
                }

                var pageUserAlerts = await pageUserAlertsQ
                                     .Skip(dataTableParameters.Start)
                                     .Take(dataTableParameters.Length)
                                     .ToListAsync();

                List <AlertDataItem> values = GetAlertDataItems(pageUserAlerts);

                int numrec = await pageUserAlertsQ.CountAsync();

                return(Json(new
                {
                    draw = dataTableParameters.Draw,
                    recordsTotal = numrec,
                    recordsFiltered = numrec,
                    data = values
                }));
            }
        }
Exemple #3
0
        public static async Task <PagedList <T> > CreateAsync(IOrderedQueryable <T> source, int pageNumber, int pageSize)
        {
            var count = await source.CountAsync();

            var items = await source.Skip((pageNumber - 1) *pageSize).Take(pageSize).ToListAsync();

            return(new PagedList <T>(items, count, pageNumber, pageSize));
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="orderedResult">已排序集合对象</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <returns>实体对象列表</returns>
        public static async Task<Page<T>> ToPageAsync<T>(this IOrderedQueryable<T> orderedResult, int pageIndex, int pageSize)
        {
            int rowCount = await orderedResult.CountAsync();
            int pageCount = (int)Math.Ceiling(rowCount * 1.0 / pageSize);
            IList<T> pagedResult = await orderedResult.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();

            return new Page<T>(pagedResult, pageIndex, pageSize, pageCount, rowCount);
        }
Exemple #5
0
        public static async Task <PagedList <T> > PaginateAsync(int pageNumber, int pageSize, IOrderedQueryable <T> collection)
        {
            int totalCount = await collection.CountAsync();

            List <T> pagedList = await collection.Skip((pageNumber - 1) *pageSize).Take(pageSize).ToListAsync();

            return(new PagedList <T>(pagedList, totalCount));
        }
Exemple #6
0
        public static async Task <PagingList <T> > CreateAsync <T>(IOrderedQueryable <T> qry, string action, string controller, int pageSize, int pageIndex) where T : class
        {
            var totalRecordCount = await qry.CountAsync();

            var pageCount = (int)Math.Ceiling(totalRecordCount / (double)pageSize);

            return(new PagingList <T>(await qry.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(), action, controller,
                                      pageSize, pageIndex, pageCount, totalRecordCount));
        }
Exemple #7
0
        public async IAsyncEnumerable <List <T> > BatchAsync <T>(IOrderedQueryable <T> collection, int size)
        {
            var batches = (double)await collection.CountAsync() / size;

            for (var i = 0; i < batches; i++)
            {
                yield return(await collection.Skip(i *size).Take(size).ToListAsync());
            }
        }
Exemple #8
0
        /// <summary>
        /// Create a paging list based on the EntityFramework ordered query
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="qry">Entity Framework ordered query</param>
        /// <param name="pageSize">The size of the Page</param>
        /// <param name="pageIndex">The index of the Page (1 based, not zero)</param>
        /// <returns>The PagingListOfT</returns>
        public static async Task <PagingList <T> > CreateAsync <T>(IOrderedQueryable <T> qry, int pageSize, int pageIndex) where T : class
        {
            var totalRecordCount = await qry.CountAsync().ConfigureAwait(false);

            var pageCount = (int)Math.Ceiling(totalRecordCount / (double)pageSize);

            return(new PagingList <T>(await qry.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync().ConfigureAwait(false),
                                      pageIndex, pageCount, totalRecordCount));
        }
Exemple #9
0
        public static async Task <Pagination <TResult> > GetPageAsync <TSource, TProjection, TResult>(this IOrderedQueryable <TSource> query, int pageNumber, int pageSize, Expression <Func <TSource, TProjection> > serverProjection, Func <TProjection, TResult> clientProjection)
        {
            var totalCount = await query.CountAsync();

            var items = await query
                        .Select(serverProjection)
                        .Skip((pageNumber - 1) * pageSize)
                        .Take(pageSize)
                        .ToListAsync();

            return(new Pagination <TResult>(items.Select(clientProjection), totalCount, pageSize, pageNumber));
        }
Exemple #10
0
        protected async Task <PaginatedResult <T> > Paginate <T>
        (
            IQueryable <T> data,
            PaginationData paginationData,
            params Expression <Func <T, object> >[] keys
        )
        {
            var skipRows = (paginationData.CurrentPage - 1) * paginationData.RowsPerPage;

            IOrderedQueryable <T> orderedData = null;

            for (int i = 0; i < keys.Count(); ++i)
            {
                if (i == 0)
                {
                    orderedData = data.OrderBy(keys[i]);
                }
                else
                {
                    orderedData = orderedData.ThenBy(keys[i]);
                }
            }

            var paginated = orderedData.Skip(skipRows).Take(paginationData.RowsPerPage);

            var result = new PaginatedResult <T>
            {
                Result         = await paginated.ToListAsync(),
                PaginationData = new PaginationDataResult()
            };

            var dataCount = await orderedData.CountAsync();

            var pages = dataCount % paginationData.RowsPerPage > 0 ?
                        (dataCount / paginationData.RowsPerPage) + 1 :
                        dataCount / paginationData.RowsPerPage;

            result.PaginationData.PageCount   = pages;
            result.PaginationData.CurrentPage = paginationData.CurrentPage;
            result.PaginationData.RowsPerPage = paginationData.RowsPerPage;
            result.PaginationData.RowCount    = dataCount;

            if (result.PaginationData.CurrentPage > result.PaginationData.PageCount && result.PaginationData.PageCount != 0)
            {
                result.PaginationData.CurrentPage = result.PaginationData.PageCount;
            }

            return(result);
        }
Exemple #11
0
        public static async Task <int> CountNoLockAsync <T>(this IOrderedQueryable <T> query)
        {
            using (
                var scope = new TransactionScope(TransactionScopeOption.Required,
                                                 new TransactionOptions()
            {
                IsolationLevel = IsolationLevel.ReadUncommitted
            },
                                                 TransactionScopeAsyncFlowOption.Enabled))
            {
                int toReturn = await query.CountAsync();

                scope.Complete();
                return(toReturn);
            }
        }
Exemple #12
0
        public static async Task <PagingList <T> > CreateAsync <T>(IOrderedQueryable <T> qry, int pageSize, int pageIndex,
                                                                   Func <T, int?> totalCount = null,
                                                                   string action             = "Index") where T : class
        {
            var list = await qry.Skip((pageIndex - 1) *pageSize).Take(pageSize).ToListAsync();

            var totalRecordCountInvoke = (totalCount != null && list.Count > 0) ? totalCount(list.First()) : null;
            var totalRecordCount       = totalRecordCountInvoke ?? await qry.CountAsync();

            var pageCount = (int)Math.Ceiling(totalRecordCount / (double)pageSize);

            return(new PagingList <T>(list, pageSize, pageIndex, pageCount, totalRecordCount)
            {
                Action = action
            });
        }
Exemple #13
0
        public static async Task <PagedResponse <T> > GetPagedResponse <T>(IOrderedQueryable <T> query, PaginationQuery paginationQuery, CancellationToken cancellationToken)
        {
            var result = await query
                         .Skip(paginationQuery.Skip)
                         .Take(paginationQuery.Count)
                         .ToListAsync(cancellationToken);

            var totalCount = await query.CountAsync(cancellationToken);

            return(new PagedResponse <T>(result)
            {
                Count = result.Count,
                Data = result,
                Skipped = paginationQuery.Skip,
                TotalCount = totalCount
            });
        }
        public static async Task <AiurPagedCollection <T> > BuildAsync <T>(
            IOrderedQueryable <T> query,
            IPageable pager,
            ErrorType code,
            string message)
        {
            var items = await query.Page(pager).ToListAsync();

            return(new AiurPagedCollection <T>(items)
            {
                TotalCount = await query.CountAsync(),
                CurrentPage = pager.PageNumber,
                CurrentPageSize = pager.PageSize,
                Code = code,
                Message = message
            });
        }
        public static async Task <PaginatedList <T> > CreateAsync(IOrderedQueryable <T> source, FilterGas filter)
        {
            //кількість елементів
            int count = await source.CountAsync();

            filter.TotalPages = (int)Math.Ceiling(count / (double)filter.PageSize);
            //якщо поле "поточна сторінка" більше ніж кількість сторінок після зміни фільтру:
            while (filter.PageIndex > filter.TotalPages)
            {
                filter.PageIndex--;
            }

            //вибірка потрібної сторінки
            items = await source.Skip((filter.PageIndex - 1) *filter.PageSize).Take(filter.PageSize).ToListAsync();

            return(new PaginatedList <T>(count, filter));
        }
Exemple #16
0
        public static async Task <PageInfo <T> > ToPageAsync <T>(this IOrderedQueryable <T> source, int pageIndex, int pageSize) where T : class
        {
            int total = await source.CountAsync();

            var inc          = total % pageSize > 0 ? 0 : -1;
            var maxPageIndex = (int)Math.Floor((double)total / pageSize) + inc;

            pageIndex = Math.Max(0, Math.Min(pageIndex, maxPageIndex));

            var data = await source.Skip(pageIndex *pageSize).Take(pageSize).AsNoTracking().ToListAsync();

            var page = new PageInfo <T>(total, data)
            {
                PageIndex = pageIndex, PageSize = pageSize
            };

            return(page);
        }
Exemple #17
0
        /// <summary>
        /// 生成分页集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TDto"></typeparam>
        /// <param name="query"></param>
        /// <param name="page">当前页</param>
        /// <param name="size">页大小</param>
        /// <param name="mapper"></param>
        /// <returns></returns>
        public static async Task <PagedList <TDto> > ToPagedListAsync <T, TDto>(this IOrderedQueryable <T> query, int page, int size, MapperConfiguration mapper)
        {
            var totalCount = await query.CountAsync();

            if (page * size > totalCount)
            {
                page = (int)Math.Ceiling(totalCount / (size * 1.0));
            }

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

            var list = await query.Skip(size *(page - 1)).Take(size).ProjectTo <TDto>(mapper).NotCacheable().ToListAsync();

            return(new PagedList <TDto>(list, page, size, totalCount));
        }
        /// <summary>
        /// 生成分页集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="page">当前页</param>
        /// <param name="size">页大小</param>
        /// <returns></returns>
        public static async Task <PagedList <T> > ToPagedListAsync <T>(this IOrderedQueryable <T> query, int page, int size)
        {
            var totalCount = await query.CountAsync();

            if (page * size > totalCount)
            {
                page = (int)Math.Ceiling(totalCount / (size * 1.0));
            }

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

            var list = await query.Skip(size *(page - 1)).Take(size).ToListAsync();

            return(new PagedList <T>(list, page, size, totalCount));
        }
Exemple #19
0
        public static async Task <Page <TResult> > ToPageAsync <TSource, TResult>(this IOrderedQueryable <TSource> queryable, int index, int size, Expression <Func <TSource, TResult> > resultSelector)
        {
            if (queryable == null)
            {
                throw new ArgumentNullException(nameof(queryable));
            }
            if (index < 0)
            {
                throw new ArgumentException("Index must be greater than or equal to 0.", nameof(index));
            }
            if (size <= 0)
            {
                throw new ArgumentException("Size must be greater than 0.", nameof(size));
            }

            var count = queryable.CountAsync();
            var items = queryable.Skip(index * size).Take(size).Select(resultSelector).ToListAsync();

            return(new Page <TResult>(index, size, await count, await items));
        }
Exemple #20
0
        public async Task <PagedResult <TResult> > GetPageAsync <TResult>(IOrderedQueryable <TResult> source,
                                                                          int pageNo,
                                                                          int pageSize, Expression <Func <TSource, TResult> > converter)
        {
            if (pageNo < 1)
            {
                pageNo = 1;
            }

            var total = await source.CountAsync();

            var result = await source
                         .Skip(pageSize *(pageNo - 1))
                         .Take(pageSize)
                         .ToListAsync();

            return(new PagedResult <TResult>
            {
                Total = total,
                Result = result
            });
        }
Exemple #21
0
        public async Task QueryableExtentionFunctionsTest()
        {
            //Creating items for query.
            IList <ToDoActivity> itemList = await ToDoActivity.CreateRandomItems(container : this.Container, pkCount : 10, perPKItemCount : 1, randomPartitionKey : true);

            QueryRequestOptions queryRequestOptions        = new QueryRequestOptions();
            IOrderedQueryable <ToDoActivity> linqQueryable = this.Container.GetItemLinqQueryable <ToDoActivity>(
                requestOptions: queryRequestOptions);

            int count = await linqQueryable.CountAsync();

            Assert.AreEqual(10, count);

            Response <int> intSum = await linqQueryable.Select(item => item.taskNum).SumAsync();

            this.VerifyResponse(intSum, 420, queryRequestOptions);

            Response <int?> intNullableSum = await linqQueryable.Select(item => (int?)item.taskNum).SumAsync();

            this.VerifyResponse(intNullableSum, 420, queryRequestOptions);

            Response <float> floatSum = await linqQueryable.Select(item => (float)item.taskNum).SumAsync();

            this.VerifyResponse(floatSum, 420, queryRequestOptions);

            Response <float?> floatNullableSum = await linqQueryable.Select(item => (float?)item.taskNum).SumAsync();

            this.VerifyResponse(floatNullableSum, 420, queryRequestOptions);

            Response <double> doubleSum = await linqQueryable.Select(item => (double)item.taskNum).SumAsync();

            this.VerifyResponse(doubleSum, 420, queryRequestOptions);

            Response <double?> doubleNullableSum = await linqQueryable.Select(item => (double?)item.taskNum).SumAsync();

            this.VerifyResponse(doubleNullableSum, 420, queryRequestOptions);

            Response <long> longSum = await linqQueryable.Select(item => (long)item.taskNum).SumAsync();

            this.VerifyResponse(longSum, 420, queryRequestOptions);

            Response <long?> longNullableSum = await linqQueryable.Select(item => (long?)item.taskNum).SumAsync();

            this.VerifyResponse(longNullableSum, 420, queryRequestOptions);

            Response <decimal> decimalSum = await linqQueryable.Select(item => (decimal)item.taskNum).SumAsync();

            this.VerifyResponse(decimalSum, 420, queryRequestOptions);

            Response <decimal?> decimalNullableSum = await linqQueryable.Select(item => (decimal?)item.taskNum).SumAsync();

            this.VerifyResponse(decimalNullableSum, 420, queryRequestOptions);

            Response <double> intToDoubleAvg = await linqQueryable.Select(item => item.taskNum).AverageAsync();

            this.VerifyResponse(intToDoubleAvg, 42, queryRequestOptions);

            Response <double?> intToDoubleNulableAvg = await linqQueryable.Select(item => (double?)item.taskNum).AverageAsync();

            this.VerifyResponse(intToDoubleNulableAvg, 42, queryRequestOptions);

            Response <float> floatAvg = await linqQueryable.Select(item => (float)item.taskNum).AverageAsync();

            this.VerifyResponse(floatAvg, 42, queryRequestOptions);

            Response <float?> floatNullableAvg = await linqQueryable.Select(item => (float?)item.taskNum).AverageAsync();

            this.VerifyResponse(floatNullableAvg, 42, queryRequestOptions);

            Response <double> doubleAvg = await linqQueryable.Select(item => (double)item.taskNum).AverageAsync();

            this.VerifyResponse(doubleAvg, 42, queryRequestOptions);

            Response <double?> doubleNullableAvg = await linqQueryable.Select(item => (double?)item.taskNum).AverageAsync();

            this.VerifyResponse(doubleNullableAvg, 42, queryRequestOptions);

            Response <double> longToDoubleAvg = await linqQueryable.Select(item => (long)item.taskNum).AverageAsync();

            this.VerifyResponse(longToDoubleAvg, 42, queryRequestOptions);

            Response <double?> longToNullableDoubleAvg = await linqQueryable.Select(item => (long?)item.taskNum).AverageAsync();

            this.VerifyResponse(longToNullableDoubleAvg, 42, queryRequestOptions);

            Response <decimal> decimalAvg = await linqQueryable.Select(item => (decimal)item.taskNum).AverageAsync();

            this.VerifyResponse(decimalAvg, 42, queryRequestOptions);

            Response <decimal?> decimalNullableAvg = await linqQueryable.Select(item => (decimal?)item.taskNum).AverageAsync();

            this.VerifyResponse(decimalNullableAvg, 42, queryRequestOptions);

            //Adding more items to test min and max function
            ToDoActivity toDoActivity = ToDoActivity.CreateRandomToDoActivity();

            toDoActivity.taskNum = 20;
            toDoActivity.id      = "minTaskNum";
            await this.Container.CreateItemAsync(toDoActivity, new PartitionKey(toDoActivity.pk));

            toDoActivity.taskNum = 100;
            toDoActivity.id      = "maxTaskNum";
            await this.Container.CreateItemAsync(toDoActivity, new PartitionKey(toDoActivity.pk));

            Response <int> minTaskNum = await linqQueryable.Select(item => item.taskNum).MinAsync();

            Assert.AreEqual(20, minTaskNum);

            Response <int> maxTaskNum = await linqQueryable.Select(item => item.taskNum).MaxAsync();

            Assert.AreEqual(100, maxTaskNum);
        }
Exemple #22
0
        public async Task <ActionResult> GetMessagesTable([System.Web.Http.FromBody] DataTableParameters dataTableParameters)
        {
            var userId = User.Identity.GetUserId();

            if (userId == null || dataTableParameters == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            using (var db = new ZapContext())
            {
                var sorts = dataTableParameters.Order;

                var pageUserMessagesQS = db.Users
                                         .Where(u => u.AppId == userId)
                                         .SelectMany(u => u.Messages)
                                         .Include(m => m.From)
                                         .Include(m => m.PostLink)
                                         .Include(m => m.CommentLink)
                                         .Where(m => !m.IsDeleted)
                                         .Where(m => m.CommentLink != null);

                // Build our query
                IOrderedQueryable <UserMessage> pageUserMessagesQ = null;

                foreach (var s in sorts)
                {
                    if (s.Dir == "asc")
                    {
                        if (dataTableParameters.Columns[s.Column].Name == "Date")
                        {
                            pageUserMessagesQ = pageUserMessagesQS.OrderBy(q => q.TimeStamp ?? DateTime.UtcNow);
                        }
                        else if (dataTableParameters.Columns[s.Column].Name == "From")
                        {
                            pageUserMessagesQ = pageUserMessagesQS.OrderBy(q => q.From != null ? q.From.Name : "");
                        }
                    }
                    else
                    {
                        if (dataTableParameters.Columns[s.Column].Name == "Date")
                        {
                            pageUserMessagesQ = pageUserMessagesQS.OrderByDescending(q => q.TimeStamp);
                        }
                        else if (dataTableParameters.Columns[s.Column].Name == "From")
                        {
                            pageUserMessagesQ = pageUserMessagesQS.OrderByDescending(q => q.From != null ? q.From.Name : "");
                        }
                    }
                }

                // Ensure default sort order
                if (pageUserMessagesQ == null)
                {
                    pageUserMessagesQ = pageUserMessagesQS.OrderByDescending(m => m.TimeStamp);
                }

                var pageUserMessages = await pageUserMessagesQ
                                       .Skip(dataTableParameters.Start)
                                       .Take(dataTableParameters.Length)
                                       .ToListAsync().ConfigureAwait(true);

                var values = pageUserMessages.AsParallel()
                             .Select(u => new MessageDataItem()
                {
                    Id      = u.Id,
                    Type    = u.IsPrivateMessage ? "Private Message" : u.CommentLink != null ? "Comment" : "?",
                    Date    = u.TimeStamp != null ? u.TimeStamp.Value.ToString("o", CultureInfo.InvariantCulture) : "?",
                    From    = u.From != null ? u.From.Name : "?",
                    FromID  = u.From != null ? u.From.AppId : "?",
                    Message = u.Content,
                    Status  = u.IsRead ? "Read" : "Unread",
                    Link    = u.PostLink != null ? u.PostLink.PostId.ToString(CultureInfo.InvariantCulture) : "",
                    Anchor  = u.CommentLink != null ? u.CommentLink.CommentId.ToString(CultureInfo.InvariantCulture) : "",
                }).ToList();

                int numrec = await pageUserMessagesQ.CountAsync().ConfigureAwait(true);

                var ret = new
                {
                    draw            = dataTableParameters.Draw,
                    recordsTotal    = numrec,
                    recordsFiltered = numrec,
                    data            = values
                };
                return(Json(ret));
            }
        }
Exemple #23
0
 public async Task <int> CountAsync(IOrderedQueryable <T> queryable) => await queryable.CountAsync();
        public async Task <int> GetCount <T>(IOrderedQueryable <T> query)
        {
            var response = await query.CountAsync();

            return(response);
        }
        public async Task QueryableExtentionFunctionsTest()
        {
            //Creating items for query.
            IList <ToDoActivity> itemList = await ToDoActivity.CreateRandomItems(container : this.Container, pkCount : 10, perPKItemCount : 1, randomPartitionKey : true);

            IOrderedQueryable <ToDoActivity> linqQueryable = this.Container.GetItemLinqQueryable <ToDoActivity>();

            int count = await linqQueryable.CountAsync();

            Assert.AreEqual(10, count);

            int intSum = await linqQueryable.Select(item => item.taskNum).SumAsync();

            Assert.AreEqual(420, intSum);

            int?intNullableSum = await linqQueryable.Select(item => item.taskNum).SumAsync();

            Assert.AreEqual(420, intNullableSum);

            float floatSum = await linqQueryable.Select(item => (float)item.taskNum).SumAsync();

            Assert.AreEqual(420, intSum);

            float?floatNullableSum = await linqQueryable.Select(item => (float?)item.taskNum).SumAsync();

            Assert.AreEqual(420, intNullableSum);

            double doubleSum = await linqQueryable.Select(item => (double)item.taskNum).SumAsync();

            Assert.AreEqual(420, doubleSum);

            double?doubleNullableSum = await linqQueryable.Select(item => (double?)item.taskNum).SumAsync();

            Assert.AreEqual(420, doubleNullableSum);

            long longSum = await linqQueryable.Select(item => (long)item.taskNum).SumAsync();

            Assert.AreEqual(420, longSum);

            long?longNullableSum = await linqQueryable.Select(item => (long?)item.taskNum).SumAsync();

            Assert.AreEqual(420, longNullableSum);

            decimal decimalSum = await linqQueryable.Select(item => (decimal)item.taskNum).SumAsync();

            Assert.AreEqual(420, decimalSum);

            decimal?decimalNullableSum = await linqQueryable.Select(item => (decimal?)item.taskNum).SumAsync();

            Assert.AreEqual(420, decimalNullableSum);

            double intToDoubleAvg = await linqQueryable.Select(item => item.taskNum).AverageAsync();

            Assert.AreEqual(42, intToDoubleAvg);

            double?intToDoubleNulableAvg = await linqQueryable.Select(item => item.taskNum).AverageAsync();

            Assert.AreEqual(42, intToDoubleNulableAvg);

            float floatAvg = await linqQueryable.Select(item => (float)item.taskNum).AverageAsync();

            Assert.AreEqual(42, floatAvg);

            float?floatNullableAvg = await linqQueryable.Select(item => (float?)item.taskNum).AverageAsync();

            Assert.AreEqual(42, floatNullableAvg);

            double doubleAvg = await linqQueryable.Select(item => (double)item.taskNum).AverageAsync();

            Assert.AreEqual(42, doubleAvg);

            double?doubleNullableAvg = await linqQueryable.Select(item => (double?)item.taskNum).AverageAsync();

            Assert.AreEqual(42, doubleNullableAvg);

            double longToDoubleAvg = await linqQueryable.Select(item => (long)item.taskNum).AverageAsync();

            Assert.AreEqual(42, longToDoubleAvg);

            double?longToNullableDoubleAvg = await linqQueryable.Select(item => (long?)item.taskNum).AverageAsync();

            Assert.AreEqual(42, longToNullableDoubleAvg);

            decimal decimalAvg = await linqQueryable.Select(item => (decimal)item.taskNum).AverageAsync();

            Assert.AreEqual(42, decimalAvg);

            decimal?decimalNullableAvg = await linqQueryable.Select(item => (decimal?)item.taskNum).AverageAsync();

            Assert.AreEqual(42, decimalNullableAvg);

            //Adding more items to test min and max function
            ToDoActivity toDoActivity = ToDoActivity.CreateRandomToDoActivity();

            toDoActivity.taskNum = 20;
            toDoActivity.id      = "minTaskNum";
            await this.Container.CreateItemAsync(toDoActivity, new PartitionKey(toDoActivity.status));

            toDoActivity.taskNum = 100;
            toDoActivity.id      = "maxTaskNum";
            await this.Container.CreateItemAsync(toDoActivity, new PartitionKey(toDoActivity.status));

            int minTaskNum = await linqQueryable.Select(item => item.taskNum).MinAsync();

            Assert.AreEqual(20, minTaskNum);

            int maxTaskNum = await linqQueryable.Select(item => item.taskNum).MaxAsync();

            Assert.AreEqual(100, maxTaskNum);
        }
Exemple #26
0
        public async Task QueryableExtentionFunctionsTest()
        {
            //Creating items for query.
            IList <ToDoActivity> itemList = await ToDoActivity.CreateRandomItems(container : this.Container, pkCount : 10, perPKItemCount : 1, randomPartitionKey : true);

            IOrderedQueryable <ToDoActivity> linqQueryable = this.Container.GetItemLinqQueryable <ToDoActivity>();

            int count = await linqQueryable.CountAsync();

            Assert.AreEqual(10, count);

            Response <int> intSum = await linqQueryable.Select(item => item.taskNum).SumAsync();

            Assert.AreEqual(420, intSum.Resource);
            Assert.IsTrue(intSum.RequestCharge > 0);
            string diagnostics = intSum.Diagnostics.ToString();

            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <int?> intNullableSum = await linqQueryable.Select(item => (int?)item.taskNum).SumAsync();

            Assert.AreEqual <int?>(420, intNullableSum);
            Assert.IsTrue(intNullableSum.RequestCharge > 0);
            diagnostics = intNullableSum.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <float> floatSum = await linqQueryable.Select(item => (float)item.taskNum).SumAsync();

            Assert.AreEqual(420, intSum);
            Assert.IsTrue(floatSum.RequestCharge > 0);
            diagnostics = floatSum.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <float?> floatNullableSum = await linqQueryable.Select(item => (float?)item.taskNum).SumAsync();

            Assert.AreEqual <float?>(420, intNullableSum);
            Assert.IsTrue(intSum.RequestCharge > 0);
            diagnostics = intSum.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <double> doubleSum = await linqQueryable.Select(item => (double)item.taskNum).SumAsync();

            Assert.AreEqual(420.0, doubleSum);
            Assert.IsTrue(intSum.RequestCharge > 0);
            diagnostics = intSum.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <double?> doubleNullableSum = await linqQueryable.Select(item => (double?)item.taskNum).SumAsync();

            Assert.AreEqual <double?>(420.0, doubleNullableSum);
            Assert.IsTrue(intSum.RequestCharge > 0);
            diagnostics = intSum.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <long> longSum = await linqQueryable.Select(item => (long)item.taskNum).SumAsync();

            Assert.AreEqual <long>(420, longSum);
            Assert.IsTrue(intSum.RequestCharge > 0);
            diagnostics = intSum.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <long?> longNullableSum = await linqQueryable.Select(item => (long?)item.taskNum).SumAsync();

            Assert.AreEqual <long?>(420, longNullableSum);
            Assert.IsTrue(intSum.RequestCharge > 0);
            diagnostics = intSum.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <decimal> decimalSum = await linqQueryable.Select(item => (decimal)item.taskNum).SumAsync();

            Assert.AreEqual <decimal>(420, decimalSum);
            Assert.IsTrue(intSum.RequestCharge > 0);
            diagnostics = intSum.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <decimal?> decimalNullableSum = await linqQueryable.Select(item => (decimal?)item.taskNum).SumAsync();

            Assert.AreEqual <decimal?>(420, decimalNullableSum);
            Assert.IsTrue(intSum.RequestCharge > 0);
            diagnostics = intSum.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <double> intToDoubleAvg = await linqQueryable.Select(item => item.taskNum).AverageAsync();

            Assert.AreEqual <double>(42, intToDoubleAvg);
            Assert.IsTrue(intSum.RequestCharge > 0);
            diagnostics = intSum.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <double?> intToDoubleNulableAvg = await linqQueryable.Select(item => (double?)item.taskNum).AverageAsync();

            Assert.AreEqual <double?>(42, intToDoubleNulableAvg);
            Assert.IsTrue(intToDoubleNulableAvg.RequestCharge > 0);
            diagnostics = intToDoubleNulableAvg.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <float> floatAvg = await linqQueryable.Select(item => (float)item.taskNum).AverageAsync();

            Assert.AreEqual <float>(42, floatAvg);
            Assert.IsTrue(floatAvg.RequestCharge > 0);
            diagnostics = floatAvg.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <float?> floatNullableAvg = await linqQueryable.Select(item => (float?)item.taskNum).AverageAsync();

            Assert.AreEqual <float?>(42, floatNullableAvg);
            Assert.IsTrue(floatNullableAvg.RequestCharge > 0);
            diagnostics = floatNullableAvg.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <double> doubleAvg = await linqQueryable.Select(item => (double)item.taskNum).AverageAsync();

            Assert.AreEqual <double>(42, doubleAvg);
            Assert.IsTrue(doubleAvg.RequestCharge > 0);
            diagnostics = doubleAvg.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <double?> doubleNullableAvg = await linqQueryable.Select(item => (double?)item.taskNum).AverageAsync();

            Assert.AreEqual <double?>(42, doubleNullableAvg);
            Assert.IsTrue(doubleNullableAvg.RequestCharge > 0);
            diagnostics = doubleNullableAvg.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <double> longToDoubleAvg = await linqQueryable.Select(item => (long)item.taskNum).AverageAsync();

            Assert.AreEqual <double>(42, longToDoubleAvg);
            Assert.IsTrue(longToDoubleAvg.RequestCharge > 0);
            diagnostics = longToDoubleAvg.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <double?> longToNullableDoubleAvg = await linqQueryable.Select(item => (long?)item.taskNum).AverageAsync();

            Assert.AreEqual <double?>(42, longToNullableDoubleAvg);
            Assert.IsTrue(longToNullableDoubleAvg.RequestCharge > 0);
            diagnostics = longToNullableDoubleAvg.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <decimal> decimalAvg = await linqQueryable.Select(item => (decimal)item.taskNum).AverageAsync();

            Assert.AreEqual <decimal>(42, decimalAvg);
            Assert.IsTrue(decimalAvg.RequestCharge > 0);
            diagnostics = decimalAvg.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            Response <decimal?> decimalNullableAvg = await linqQueryable.Select(item => (decimal?)item.taskNum).AverageAsync();

            Assert.AreEqual <decimal?>(42, decimalNullableAvg);
            Assert.IsTrue(decimalNullableAvg.RequestCharge > 0);
            diagnostics = decimalNullableAvg.Diagnostics.ToString();
            Assert.IsTrue(diagnostics.Contains("queryMetrics"));

            //Adding more items to test min and max function
            ToDoActivity toDoActivity = ToDoActivity.CreateRandomToDoActivity();

            toDoActivity.taskNum = 20;
            toDoActivity.id      = "minTaskNum";
            await this.Container.CreateItemAsync(toDoActivity, new PartitionKey(toDoActivity.status));

            toDoActivity.taskNum = 100;
            toDoActivity.id      = "maxTaskNum";
            await this.Container.CreateItemAsync(toDoActivity, new PartitionKey(toDoActivity.status));

            Response <int> minTaskNum = await linqQueryable.Select(item => item.taskNum).MinAsync();

            Assert.AreEqual(20, minTaskNum);

            Response <int> maxTaskNum = await linqQueryable.Select(item => item.taskNum).MaxAsync();

            Assert.AreEqual(100, maxTaskNum);
        }
Exemple #27
0
        public async Task <IActionResult> OnGet(Int32?index)
        {
            Console.WriteLine($"/community/assetBrowser/singleDownload{Request.QueryString}");

            BrowseType        = Request.Query["browseType"];
            FilterView        = Request.Query["filterView"];
            ShowBigBackground = false;
            PageSize          = 8;

            // parse AppResolution header
            var resolution = Request.Headers["AppResolution"].FirstOrDefault();

            if (!String.IsNullOrEmpty(resolution))
            {
                // make sure it's in the right format
                var splitResolution = resolution.Split('x');

                if (splitResolution.Length == 2)
                {
                    // the official server
                    // only checks the width,
                    // so let's do the same here
                    if (Int32.TryParse(splitResolution[0], out int width))
                    {
                        // show big background
                        // and increase page size
                        // when the resolution width
                        // is large enough
                        if (width >= 1024)
                        {
                            ShowBigBackground = true;
                            PageSize          = 15;
                        }
                    }
                }
            }

            // parse 'action' query
            // and perform action
            var requestQuery = Request.Query["action"];
            IOrderedQueryable <SporeServerAsset> orderedAssets = null;

            if (requestQuery == "SEARCH")
            {
                orderedAssets = PerformSearch();
            }
            else if (requestQuery == "BROWSE")
            {
                orderedAssets = PerformBrowse();
            }

            // when the action was performed,
            // set page information
            if (orderedAssets != null)
            {
                CurrentIndex  = index ?? 0;
                NextIndex     = CurrentIndex + PageSize;
                PreviousIndex = CurrentIndex - PageSize;
                SearchCount   = await orderedAssets
                                .CountAsync();

                Assets = await orderedAssets
                         .Skip(CurrentIndex)
                         .Take(PageSize)
                         .ToArrayAsync();

                AssetCount      = Assets.Length;
                PerformedAction = true;
            }

            return(Page());
        }