public void ListGroupMembers()
        {
            // Snippet: ListGroupMembers(string,string,int?,CallSettings)
            // Create client
            GroupServiceClient groupServiceClient = GroupServiceClient.Create();
            // Initialize request argument(s)
            string formattedName = GroupServiceClient.FormatGroupName("[PROJECT]", "[GROUP]");
            // Make the request
            IPagedEnumerable <ListGroupMembersResponse, MonitoredResource> response =
                groupServiceClient.ListGroupMembers(formattedName);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (MonitoredResource item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over fixed-sized pages, lazily performing RPCs as required
            int pageSize = 10;

            foreach (FixedSizePage <MonitoredResource> page in response.AsPages().WithFixedSize(pageSize))
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (MonitoredResource item in page)
                {
                    Console.WriteLine(item);
                }
            }
            // End snippet
        }
Пример #2
0
        public void ListGroupStats()
        {
            // Snippet: ListGroupStats(string,QueryTimeRange,string,int?,CallSettings)
            // Create client
            ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.Create();
            // Initialize request argument(s)
            string         formattedProjectName = ErrorStatsServiceClient.FormatProjectName("[PROJECT]");
            QueryTimeRange timeRange            = new QueryTimeRange();
            // Make the request
            IPagedEnumerable <ListGroupStatsResponse, ErrorGroupStats> response =
                errorStatsServiceClient.ListGroupStats(formattedProjectName, timeRange);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (ErrorGroupStats item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over fixed-sized pages, lazily performing RPCs as required
            int pageSize = 10;

            foreach (FixedSizePage <ErrorGroupStats> page in response.AsPages().WithFixedSize(pageSize))
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (ErrorGroupStats item in page)
                {
                    Console.WriteLine(item);
                }
            }
            // End snippet
        }
Пример #3
0
        public void WithFixedSize()
        {
            string projectId            = _fixture.ProjectId;
            string pageTokenFromRequest = "";

            // Sample: WithFixedSize
            PublisherClient client      = PublisherClient.Create();
            string          projectName = PublisherClient.FormatProjectName(projectId);
            IPagedEnumerable <ListTopicsResponse, Topic> topics = client.ListTopics(projectName, pageTokenFromRequest);

            IEnumerable <FixedSizePage <Topic> > fixedSizePages = topics.AsPages().WithFixedSize(3);
            // With fixed size pages, if there are no more resources, there are no more pages.
            FixedSizePage <Topic> nextPage = fixedSizePages.FirstOrDefault();

            if (nextPage != null)
            {
                // In a web application, this would be a matter of including the topics in the web page.
                foreach (Topic topic in nextPage)
                {
                    Console.WriteLine(topic.Name);
                }
                // ... and embedding the next page token into a "next page" link.
                Console.WriteLine($"Next page token: {nextPage.NextPageToken}");
            }
            // End sample
        }
Пример #4
0
        /// <summary>
        /// Lists the subtasks matching the specified filter options.
        /// </summary>
        /// <param name="options">The options to use when querying for subtasks.</param>
        /// <returns>The subtasks matching the specified filter options.</returns>
        public IEnumerable <PSSubtaskInformation> ListSubtasks(ListSubtaskOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            string taskId           = options.Task == null ? options.TaskId : options.Task.Id;
            string verboseLogString = string.Format(Resources.GetSubtaskNoFilter, taskId);

            WriteVerbose(verboseLogString);

            IPagedEnumerable <SubtaskInformation> subtasks = null;

            if (options.Task != null)
            {
                subtasks = options.Task.omObject.ListSubtasks(additionalBehaviors: options.AdditionalBehaviors);
            }
            else
            {
                JobOperations jobOperations = options.Context.BatchOMClient.JobOperations;
                subtasks = jobOperations.ListSubtasks(options.JobId, options.TaskId, additionalBehaviors: options.AdditionalBehaviors);
            }
            Func <SubtaskInformation, PSSubtaskInformation> mappingFunction = s => { return(new PSSubtaskInformation(s)); };

            return(PSPagedEnumerable <PSSubtaskInformation, SubtaskInformation> .CreateWithMaxCount(
                       subtasks, mappingFunction, options.MaxCount, () => WriteVerbose(string.Format(Resources.MaxCount, options.MaxCount))));
        }
Пример #5
0
        public async Task ListJobSchedulesWithRetry()
        {
            TimeSpan  deltaBackoff = TimeSpan.FromSeconds(1);
            const int maxRetries   = 3;

            int callCount = 0;

            using (var client = BatchClient.Open(this.credentials))
            {
                client.JobScheduleOperations.CustomBehaviors.Add(new RequestInterceptor(
                                                                     (req) =>
                {
                    //I wish I didn't have to cast here
                    var stronglyTypedRequest = (BatchRequest <
                                                    JobScheduleListOptions,
                                                    AzureOperationResponse <IPage <ProxyModels.CloudJobSchedule>, JobScheduleListHeaders> >)req;

                    stronglyTypedRequest.ServiceRequestFunc = (token) =>
                    {
                        ++callCount;
                        throw new TimeoutException();
                    };
                }));

                client.JobScheduleOperations.CustomBehaviors.Add(new RetryPolicyProvider(new LinearRetry(deltaBackoff, maxRetries)));

                await Assert.ThrowsAsync <TimeoutException>(async() =>
                {
                    IPagedEnumerable <CloudJobSchedule> schedules = client.JobScheduleOperations.ListJobSchedules();
                    await schedules.GetPagedEnumerator().MoveNextAsync();
                });

                Assert.Equal(maxRetries + 1, callCount);
            }
        }
        static CloudJob AddCloudJob(BatchClient client, string code)
        {
            var poolId = "applicationpool" + code;
            var jobId  = "cloudjob" + code;
            IPagedEnumerable <CloudJob> jobs = client.JobOperations.ListJobs();

            foreach (CloudJob job in jobs)
            {
                if (job.Id.Equals(jobId))
                {
                    Console.WriteLine("Job already available for id : " + job.Id);
                    return(job);
                }
            }

            CloudJob newJob = client.JobOperations.CreateJob();

            newJob.Id = jobId;
            newJob.PoolInformation = new PoolInformation()
            {
                PoolId = poolId
            };
            newJob.Commit();
            Console.WriteLine("Created the Cloud job for Code : " + code);

            return(newJob);
        }
        public void ListSubscriptions()
        {
            // Snippet: ListSubscriptions(string,string,int?,CallSettings)
            // Create client
            SubscriberClient subscriberClient = SubscriberClient.Create();
            // Initialize request argument(s)
            string formattedProject = SubscriberClient.FormatProjectName("[PROJECT]");
            // Make the request
            IPagedEnumerable <ListSubscriptionsResponse, Subscription> response =
                subscriberClient.ListSubscriptions(formattedProject);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Subscription item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over fixed-sized pages, lazily performing RPCs as required
            int pageSize = 10;

            foreach (FixedSizePage <Subscription> page in response.AsPages().WithFixedSize(pageSize))
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Subscription item in page)
                {
                    Console.WriteLine(item);
                }
            }
            // End snippet
        }
Пример #8
0
        public void ListOperations()
        {
            // Snippet: ListOperations(string,string,string,int?,CallSettings)
            // Create client
            OperationsClient operationsClient = OperationsClient.Create();
            // Initialize request argument(s)
            string name   = "";
            string filter = "";
            // Make the request
            IPagedEnumerable <ListOperationsResponse, Operation> response =
                operationsClient.ListOperations(name, filter);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Operation item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over fixed-sized pages, lazily performing RPCs as required
            int pageSize = 10;

            foreach (FixedSizePage <Operation> page in response.AsPages().WithFixedSize(pageSize))
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Operation item in page)
                {
                    Console.WriteLine(item);
                }
            }
            // End snippet
        }
Пример #9
0
        public void GetPoolsListTest()
        {
            using (var client = FakeBatchClient.ConnectWithFakeCredentials(ClientUnitTestCommon.DummyBaseUrl))
            {
                client.FakeProtocolLayer.ListPoolsHandler = (skipToken, behaviors) => Task.FromResult(
                    new AzureOperationResponse <IPage <ProxyModels.CloudPool>, ProxyModels.PoolListHeaders>()
                {
                    Body = new FakePage <ProxyModels.CloudPool>(new List <ProxyModels.CloudPool>()
                    {
                        new ProxyModels.CloudPool {
                            DisplayName = "batch-test"
                        },
                        new ProxyModels.CloudPool {
                            DisplayName = "foobar", CurrentOSVersion = "3", AllocationState = ProxyModels.AllocationState.Steady
                        },
                    })
                });

                IPagedEnumerable <Microsoft.Azure.Batch.CloudPool> asyncPools = client.PoolOperations.ListPools();
                var pools = new List <Microsoft.Azure.Batch.CloudPool>(asyncPools);


                Assert.Equal(2, pools.Count);
                Assert.Equal("batch-test", pools[0].DisplayName);

                Assert.Equal("foobar", pools[1].DisplayName);

                // enums are in the same namespace.
                Assert.Equal(AllocationState.Steady, pools[1].AllocationState);
            }
        }
        public void ListLogMetrics()
        {
            // Snippet: ListLogMetrics(string,string,int?,CallSettings)
            // Create client
            MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create();
            // Initialize request argument(s)
            string formattedParent = MetricsServiceV2Client.FormatParentName("[PROJECT]");
            // Make the request
            IPagedEnumerable <ListLogMetricsResponse, LogMetric> response =
                metricsServiceV2Client.ListLogMetrics(formattedParent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (LogMetric item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over fixed-sized pages, lazily performing RPCs as required
            int pageSize = 10;

            foreach (FixedSizePage <LogMetric> page in response.AsPages().WithFixedSize(pageSize))
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (LogMetric item in page)
                {
                    Console.WriteLine(item);
                }
            }
            // End snippet
        }
        public void ListTraces()
        {
            // Snippet: ListTraces(string,string,int?,CallSettings)
            // Create client
            TraceServiceClient traceServiceClient = TraceServiceClient.Create();
            // Initialize request argument(s)
            string projectId = "";
            // Make the request
            IPagedEnumerable <ListTracesResponse, Trace> response =
                traceServiceClient.ListTraces(projectId);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Trace item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over fixed-sized pages, lazily performing RPCs as required
            int pageSize = 10;

            foreach (FixedSizePage <Trace> page in response.AsPages().WithFixedSize(pageSize))
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Trace item in page)
                {
                    Console.WriteLine(item);
                }
            }
            // End snippet
        }
Пример #12
0
        /// <summary>
        /// Lists the pool node counts matching the specified filter options.
        /// </summary>
        /// <param name="options">The options to use when listing pool node counts.</param>
        /// <returns>The pool node counts matching the specified filter.</returns>
        public IEnumerable <PSPoolNodeCounts> ListPoolNodeCounts(ListPoolNodeCountsOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            ODATADetailLevel detailLevel = null;

            const string filterStringFormat = "(poolId eq '{0}')";

            if (!string.IsNullOrEmpty(options.PoolId))
            {
                detailLevel = new ODATADetailLevel(string.Format(filterStringFormat, options.PoolId));
            }
            else if (options.Pool != null)
            {
                detailLevel = new ODATADetailLevel(string.Format(filterStringFormat, options.Pool.Id));
            }

            IPagedEnumerable <PoolNodeCounts> poolNodeCounts = options.Context.BatchOMClient.PoolOperations.ListPoolNodeCounts(
                detailLevel, options.AdditionalBehaviors);

            Func <PoolNodeCounts, PSPoolNodeCounts> mappingFunction = p => { return(new PSPoolNodeCounts(p)); };

            return(PSPagedEnumerable <PSPoolNodeCounts, PoolNodeCounts> .CreateWithMaxCount(poolNodeCounts, mappingFunction,
                                                                                            options.MaxCount, () => WriteVerbose(string.Format(Resources.MaxCount, options.MaxCount))));
        }
Пример #13
0
        public static MvcHtmlString PagerStats(this HtmlHelper htmlHelper, IPagedEnumerable list, string singular)
        {
            var plural = Inflector.Pluralize(singular);
            var output = string.Empty;

            switch (list.TotalRecords)
            {
                case 0 :
                    output = string.Format("There are <strong>0</strong> {0}.", plural);
                    break;
                case 1 :
                    output = string.Format("There is <strong>1</strong> {0}.", singular);
                    break;
                default :
                    output = string.Format(
                        "There are <strong>{0}</strong> {1}. Displaying {2} <strong>{3}</strong> to <strong>{4}</strong>.",
                        list.TotalRecords,
                        plural,
                        singular,
                        (list.PageSize * list.Page) - (list.PageSize - 1),
                        (list.PageSize * list.Page) > list.TotalRecords ? list.TotalRecords : list.PageSize * list.Page);
                    break;
            }

            return MvcHtmlString.Create(output);
        }
        public void ListLogEntries()
        {
            // Snippet: ListLogEntries(IEnumerable<string>,string,string,string,int?,CallSettings)
            // Create client
            LoggingServiceV2Client loggingServiceV2Client = LoggingServiceV2Client.Create();
            // Initialize request argument(s)
            IEnumerable <string> projectIds = new List <string>();
            string filter  = "";
            string orderBy = "";
            // Make the request
            IPagedEnumerable <ListLogEntriesResponse, LogEntry> response =
                loggingServiceV2Client.ListLogEntries(projectIds, filter, orderBy);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (LogEntry item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over fixed-sized pages, lazily performing RPCs as required
            int pageSize = 10;

            foreach (FixedSizePage <LogEntry> page in response.AsPages().WithFixedSize(pageSize))
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (LogEntry item in page)
                {
                    Console.WriteLine(item);
                }
            }
            // End snippet
        }
Пример #15
0
        public static async Task PrintNodeTasksAsync(BatchClient batchClient, string poolId)
        {
            Console.WriteLine("Listing Node Tasks");
            Console.WriteLine("==================");

            ODATADetailLevel nodeDetail          = new ODATADetailLevel(selectClause: "id,recentTasks");
            IPagedEnumerable <ComputeNode> nodes = batchClient.PoolOperations.ListComputeNodes(poolId, nodeDetail);

            await nodes.ForEachAsync(node =>
            {
                Console.WriteLine();
                Console.WriteLine(node.Id + " tasks:");

                if (node.RecentTasks != null && node.RecentTasks.Any())
                {
                    foreach (TaskInformation task in node.RecentTasks)
                    {
                        Console.WriteLine("\t{0}: {1}", task.TaskId, task.TaskState);
                    }
                }
                else
                {
                    // No tasks found for the node
                    Console.WriteLine("\tNone");
                }
            }).ConfigureAwait(continueOnCapturedContext: false);

            Console.WriteLine("==================");
        }
Пример #16
0
        /// <summary>
        /// Lists the job prep and release status matching the specified filter options.
        /// </summary>
        /// <param name="options">The Batch account context.</param>
        public IEnumerable <PSJobPreparationAndReleaseTaskExecutionInformation> ListJobPreparationAndReleaseStatus(ListJobPreparationAndReleaseStatusOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            string jobId = options.JobId ?? options.Job.Id;

            if (jobId == null)
            {
                throw new ArgumentNullException(nameof(jobId));
            }

            WriteVerbose(string.Format(Resources.GetJobPreparationAndReleaseStatus, jobId));
            JobOperations    jobOperations  = options.Context.BatchOMClient.JobOperations;
            ODATADetailLevel getDetailLevel = new ODATADetailLevel(filterClause: options.Filter, selectClause: options.Select, expandClause: options.Expand);
            IPagedEnumerable <JobPreparationAndReleaseTaskExecutionInformation> jobPrepAndReleaseDetails =
                jobOperations.ListJobPreparationAndReleaseTaskStatus(jobId, getDetailLevel, additionalBehaviors: options.AdditionalBehaviors);

            Func <JobPreparationAndReleaseTaskExecutionInformation, PSJobPreparationAndReleaseTaskExecutionInformation> mappingFunction =
                j => new PSJobPreparationAndReleaseTaskExecutionInformation(j);

            return(PSPagedEnumerable <PSJobPreparationAndReleaseTaskExecutionInformation, JobPreparationAndReleaseTaskExecutionInformation> .CreateWithMaxCount(
                       jobPrepAndReleaseDetails, mappingFunction, options.MaxCount, () => WriteVerbose(string.Format(Resources.MaxCount, options.MaxCount))));
        }
        public async Task IfSequenceIsNull_ThenForEachAsyncThrowsArgumentNullException_SyncDelegateOverload()
        {
            IPagedEnumerable <string> seq = null;

            var ex = await Assert.ThrowsAsync <ArgumentNullException>(() => seq.ForEachAsync(_ => { }));

            Assert.Equal("source", ex.ParamName);
        }
Пример #18
0
        public static PageResult <TDestination> ToPageResult <TSource, TDestination>(this IPagedEnumerable <TSource> source)
            where TSource : class
            where TDestination : class
        {
            var items = Mapper.Map <IEnumerable <TSource>, IEnumerable <TDestination> >(source);

            return(new PageResult <TDestination>(items, source.TotalCount));
        }
Пример #19
0
        /// <summary>
        /// Lists the task files associated with this task
        /// </summary>
        /// <returns></returns>
        private async System.Threading.Tasks.Task <List <NodeFile> > ListTaskFilesAsync()
        {
            IPagedEnumerable <NodeFile> vmFiles = this.Task.ListNodeFiles(recursive: true);

            List <NodeFile> results = await vmFiles.ToListAsync();

            return(results);
        }
        public async Task IfSequenceIsNull_ThenToListAsyncThrowsArgumentNullException()
        {
            IPagedEnumerable <string> seq = null;

            var ex = await Assert.ThrowsAsync <ArgumentNullException>(() => seq.ToListAsync());

            Assert.Equal("source", ex.ParamName);
        }
Пример #21
0
        /// <summary>
        /// Lists the files on this ComputeNode.
        /// </summary>
        /// <returns></returns>
        private async Task <List <NodeFile> > ListFilesAsync()
        {
            IPagedEnumerable <NodeFile> vmFiles = this.ComputeNode.ListNodeFiles(recursive: true);

            List <NodeFile> results = await vmFiles.ToListAsync();

            return(results);
        }
        public async Task <IList <NodeAgentSku> > ListNodeAgentSkusAsync()
        {
            IPagedEnumerable <NodeAgentSku> nodeAgentSkus = this.Service.ListNodeAgentSkus();

            IList <NodeAgentSku> results = await nodeAgentSkus.ToListAsync();

            return(results);
        }
        public PagedListResultBuilder <TItem> WithPagedItems(IPagedEnumerable <TItem> items)
        {
            this.result.Items      = items.ToList();
            this.result.PageIndex  = items.PageIndex;
            this.result.PageSize   = items.PageSize;
            this.result.TotalCount = items.TotalCount;

            return(this);
        }
Пример #24
0
        /// <summary>
        /// Enumerates the <see cref="CloudJob">jobs</see> created under the specified job schedule.
        /// </summary>
        /// <param name="jobScheduleId">The id of the job schedule.</param>
        /// <param name="detailLevel">A <see cref="DetailLevel"/> used for filtering the list and for controlling which properties are retrieved from the service.</param>
        /// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/> and <paramref name="detailLevel"/>.</param>
        /// <returns>An <see cref="IPagedEnumerable{CloudJob}"/> that can be used to enumerate jobs asynchronously or synchronously.</returns>
        /// <remarks>This method returns immediately; the jobs are retrieved from the Batch service only when the collection is enumerated.
        /// Retrieval is non-atomic; jobs are retrieved in pages during enumeration of the collection.</remarks>
        public IPagedEnumerable <CloudJob> ListJobs(string jobScheduleId, DetailLevel detailLevel = null, IEnumerable <BatchClientBehavior> additionalBehaviors = null)
        {
            // set up behavior manager
            BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);

            IPagedEnumerable <CloudJob> enumerable = ListJobsImpl(jobScheduleId, bhMgr, detailLevel);

            return(enumerable);
        }
        public async Task <IList <CertificateModel> > GetCertificatesCollectionAsync()
        {
            IPagedEnumerable <Certificate> certificates      = this.Service.ListCertificates(null);
            IList <CertificateModel>       certificateModels = new List <CertificateModel>();

            await certificates.ForEachAsync(item => certificateModels.Add(new CertificateModel(item)));

            return(certificateModels);
        }
        public async Task <IList <PoolModel> > GetPoolCollectionAsync()
        {
            IPagedEnumerable <CloudPool> pools      = this.Service.ListPools(OptionsModel.Instance.ListDetailLevel);
            IList <PoolModel>            poolModels = new List <PoolModel>();

            await pools.ForEachAsync(item => poolModels.Add(new PoolModel(item)));

            return(poolModels);
        }
        public async Task <IList <JobModel> > GetJobCollectionAsync()
        {
            IPagedEnumerable <CloudJob> jobs      = this.Service.ListJobs(OptionsModel.Instance.ListDetailLevel);
            List <JobModel>             jobModels = new List <JobModel>();

            await jobs.ForEachAsync(item => jobModels.Add(new JobModel(item)));

            return(jobModels);
        }
Пример #28
0
        private async Task <List <ComputeNodeModel> > ListComputeNodesAsync()
        {
            List <ComputeNodeModel>        results = new List <ComputeNodeModel>();
            IPagedEnumerable <ComputeNode> jobList = this.Pool.ListComputeNodes();

            await jobList.ForEachAsync(item => results.Add(new ComputeNodeModel(this, item)));

            return(results);
        }
Пример #29
0
        /// <summary>
        /// Exposes synchronous and asynchronous enumeration of the files for the node.
        /// </summary>
        /// <param name="recursive">If true, performs a recursive list of all files of the node. If false, returns only the files at the node directory root.</param>
        /// <param name="detailLevel">Controls the detail level of the data returned by a call to the Azure Batch Service.</param>
        /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object and after the behavior implementing the DetailLevel.</param>
        /// <returns>An instance of IPagedEnumerable that can be used to enumerate objects using either synchronous or asynchronous patterns.</returns>
        public IPagedEnumerable <NodeFile> ListNodeFiles(bool?recursive = null, DetailLevel detailLevel = null, IEnumerable <BatchClientBehavior> additionalBehaviors = null)
        {
            // craft the behavior manager for this call
            BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors);

            IPagedEnumerable <NodeFile> enumerator = this.parentBatchClient.PoolOperations.ListNodeFilesImpl(this.parentPoolId, this.Id, recursive, bhMgr, detailLevel);

            return(enumerator);
        }
Пример #30
0
 public object GetMeta(IPagedEnumerable instance)
 {
     return new
     {
         instance.Page,
         instance.TotalPages,
         instance.ItemsPerPage
     };
 }
Пример #31
0
        private async System.Threading.Tasks.Task <List <TaskModel> > ListTasksAsync()
        {
            List <TaskModel>             results  = new List <TaskModel>();
            IPagedEnumerable <CloudTask> taskList = this.Job.ListTasks(OptionsModel.Instance.ListDetailLevel);

            await taskList.ForEachAsync(item => results.Add(new TaskModel(this, item)));

            return(results);
        }
Пример #32
0
 public object GetMeta(IPagedEnumerable instance)
 {
     return(new
     {
         instance.Page,
         instance.TotalPages,
         instance.ItemsPerPage
     });
 }
Пример #33
0
        public static MvcHtmlString Pager(this HtmlHelper htmlHelper, IPagedEnumerable list, int maximumNumericLinks, string pagerPreviousClass, string pagerNextClass, string pagerDisabledClass, string pagingNumberClass, string pagingNumberCurrentClass)
        {
            if (maximumNumericLinks % 2 != 1)
                throw new ArgumentException("Value must be an odd number.", "maximumNumericLinks");

            var url = new UrlHelper(htmlHelper.ViewContext.RequestContext);

            #region Previous Link

            var prev = new TagBuilder("div");
            prev.AddCssClass("pagerPreviousHolder");

            var prevLink = new TagBuilder("a");
            prevLink.SetInnerText("<< Prev");
            if (list.Page > 1)
                prevLink.MergeAttribute("href", url.StateUrl(new { page = list.Page - 1 }));
            else
                prevLink.AddCssClass(pagerDisabledClass);
            prevLink.AddCssClass(pagerPreviousClass);

            prev.InnerHtml = prevLink.ToString(TagRenderMode.Normal);

            #endregion
            #region Numeric Links

            var numerics = new TagBuilder("div");
            numerics.AddCssClass("pagerNumberHolder");

            if (list.TotalPages > 0)
            {

                int pagingStartNumber = -1;
                int pagingEndNumber = -1;

                if ((list.TotalPages >= maximumNumericLinks) && (list.Page > (int)Math.Ceiling((double)maximumNumericLinks / 2D)))
                    pagingStartNumber = list.Page - (int)Math.Floor((double)maximumNumericLinks / 2D);
                else
                    pagingStartNumber = 1;

                if (list.TotalPages >= (pagingStartNumber + maximumNumericLinks))
                    pagingEndNumber = pagingStartNumber + (maximumNumericLinks - 1);
                else
                {
                    if (list.TotalPages >= maximumNumericLinks)
                        pagingStartNumber = list.TotalPages - (maximumNumericLinks - 1);

                    pagingEndNumber = list.TotalPages;
                }

                //for (int i = pagingStartNumber; i <= pagingEndNumber; i++)
                for (int i = pagingEndNumber; i >= pagingStartNumber; i--)
                {
                    var numberTag = new TagBuilder("a");
                    numberTag.SetInnerText(i.ToString());
                    if (i == list.Page) 
                        numberTag.AddCssClass(pagingNumberCurrentClass);
                    else
                        numberTag.MergeAttribute("href", url.StateUrl(new { page = i }));
                    numberTag.AddCssClass(pagingNumberClass);                    
                    numerics.InnerHtml = numerics.InnerHtml + numberTag.ToString();
                }

            }
            else
            {
                //numerics.InnerHtml = "&nbsp;"; // Stops div colapsing
            }

            #endregion
            #region Next Link

            var next = new TagBuilder("div");
            next.AddCssClass("pagerNextHolder");

            var nextLink = new TagBuilder("a");
            nextLink.SetInnerText("Next >>");
            if (list.Page < list.TotalPages)
                nextLink.MergeAttribute("href", url.StateUrl(new { page = list.Page + 1 }));
            else
                nextLink.AddCssClass(pagerDisabledClass);
            nextLink.AddCssClass(pagerNextClass);

            next.InnerHtml = nextLink.ToString();

            #endregion
            
            return MvcHtmlString.Create(string.Format("<div class=\"pagerHolder\">{0}{3}{0}{2}{0}{1}</div>", Environment.NewLine, prev, numerics, next));
        }
Пример #34
0
 public static MvcHtmlString Pager(this HtmlHelper htmlHelper, IPagedEnumerable list)
 {
     return htmlHelper.Pager(list, 9);
 }
Пример #35
0
 public static MvcHtmlString Pager(this HtmlHelper htmlHelper, IPagedEnumerable list, int maximumNumericLinks)
 {
     return htmlHelper.Pager(list, maximumNumericLinks, "pagerPreviousLink", "pagerNextLink", "disabled", "pagerNumberLink", "current");
 }
Пример #36
0
 public static MvcHtmlString PagerStats(this HtmlHelper htmlHelper, IPagedEnumerable list)
 {
     return htmlHelper.PagerStats(list, "record");
 }