public IncrementalLoadingCollection(ItemChildrenCollectionPage files)
 {
     if (files != null)
     {
         foreach (Item i in files)
         {
             Add(i);
         }
     }
     lastFiles = files;
 }
 public IAsyncOperation <LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
 {
     return(AsyncInfo.Run(async cancelToken =>
     {
         if (lastFiles == null)
         {
             return new LoadMoreItemsResult {
                 Count = 0
             };
         }
         try
         {
             var nextPage = lastFiles.NextPageRequest;
             if (nextPage != null)
             {
                 System.Diagnostics.Debug.WriteLine("Listing additional files.");
                 ItemChildrenCollectionPage newFiles = (ItemChildrenCollectionPage)await nextPage.GetAsync();
                 foreach (Item i in newFiles)
                 {
                     Add(i);
                     System.Diagnostics.Debug.WriteLine("Adding file " + i.Name + " for more files.");
                 }
                 // NOTE: currently, there is no break - it just keeps fetching new items
                 System.Diagnostics.Debug.WriteLine("Got " + newFiles.Count() + " additional files");
                 lastFiles = newFiles;
                 return new LoadMoreItemsResult {
                     Count = Convert.ToUInt32(newFiles.Count())
                 };
             }
             else
             {
                 return new LoadMoreItemsResult {
                     Count = 0
                 };
             }
         }
         catch (Exception e)
         {
             Crashes.TrackError(e, new Dictionary <string, string>
             {
                 { "On", "List Additional Files" },
                 { "Where", "MainPage.xaml:LoadMoreItemsAsync" },
                 { "DueTo", e.Message }
             });
             return new LoadMoreItemsResult {
                 Count = 0
             };
         }
     }));
 }
        public async Task GetAsync_InitializeCollectionProperties()
        {
            using (var httpResponseMessage = new HttpResponseMessage())
                using (var responseStream = new MemoryStream())
                    using (var streamContent = new StreamContent(responseStream))
                    {
                        httpResponseMessage.Content = streamContent;

                        var requestUrl = "https://api.onedrive.com/v1.0/drive/items/id";
                        this.httpProvider.Setup(
                            provider => provider.SendAsync(
                                It.Is <HttpRequestMessage>(
                                    request => request.RequestUri.ToString().Equals(requestUrl)),
                                HttpCompletionOption.ResponseContentRead,
                                CancellationToken.None))
                        .Returns(Task.FromResult <HttpResponseMessage>(httpResponseMessage));

                        var expectedChildrenPage = new ItemChildrenCollectionPage
                        {
                            new Item {
                                Id = "id"
                            }
                        };

                        var expectedItemResponse = new Item
                        {
                            AdditionalData = new Dictionary <string, object>
                            {
                                { "*****@*****.**", requestUrl + "/next" }
                            },
                            Children = expectedChildrenPage,
                        };

                        this.serializer.Setup(
                            serializer => serializer.DeserializeObject <Item>(It.IsAny <string>()))
                        .Returns(expectedItemResponse);

                        var item = await this.oneDriveClient.Drive.Items["id"].Request().GetAsync();

                        Assert.IsNotNull(item, "Item not returned.");
                        Assert.IsNotNull(item.Children, "Item children not returned.");
                        Assert.AreEqual(1, item.Children.CurrentPage.Count, "Unexpected number of children in page.");
                        Assert.AreEqual("id", item.Children.CurrentPage[0].Id, "Unexpected child ID in page.");
                        Assert.AreEqual(expectedItemResponse.AdditionalData, item.Children.AdditionalData, "Additional data not initialized correctly.");
                        var nextPageRequest = item.Children.NextPageRequest as ItemChildrenCollectionRequest;
                        Assert.IsNotNull(nextPageRequest, "Children next page request not initialized correctly.");
                        Assert.AreEqual(new Uri(requestUrl + "/next"), new Uri(nextPageRequest.RequestUrl), "Unexpected request URL for next page request.");
                    }
        }
        public async Task GetAsync_InitializeCollectionProperties()
        {
            using (var httpResponseMessage = new HttpResponseMessage())
            using (var responseStream = new MemoryStream())
            using (var streamContent = new StreamContent(responseStream))
            {
                httpResponseMessage.Content = streamContent;

                var requestUrl = "https://api.onedrive.com/v1.0/drive/items/id";
                this.httpProvider.Setup(
                    provider => provider.SendAsync(
                        It.Is<HttpRequestMessage>(
                            request => request.RequestUri.ToString().Equals(requestUrl)),
                        HttpCompletionOption.ResponseContentRead,
                        CancellationToken.None))
                    .Returns(Task.FromResult<HttpResponseMessage>(httpResponseMessage));

                var expectedChildrenPage = new ItemChildrenCollectionPage
                {
                    new Item { Id = "id" }
                };

                var expectedItemResponse = new Item
                {
                    AdditionalData = new Dictionary<string, object>
                    {
                        { "*****@*****.**", requestUrl + "/next" }
                    },
                    Children = expectedChildrenPage,
                };

                this.serializer.Setup(
                    serializer => serializer.DeserializeObject<Item>(It.IsAny<string>()))
                    .Returns(expectedItemResponse);

                var item = await this.oneDriveClient.Drive.Items["id"].Request().GetAsync();

                Assert.IsNotNull(item, "Item not returned.");
                Assert.IsNotNull(item.Children, "Item children not returned.");
                Assert.AreEqual(1, item.Children.CurrentPage.Count, "Unexpected number of children in page.");
                Assert.AreEqual("id", item.Children.CurrentPage[0].Id, "Unexpected child ID in page.");
                Assert.AreEqual(expectedItemResponse.AdditionalData, item.Children.AdditionalData, "Additional data not initialized correctly.");
                var nextPageRequest = item.Children.NextPageRequest as ItemChildrenCollectionRequest;
                Assert.IsNotNull(nextPageRequest, "Children next page request not initialized correctly.");
                Assert.AreEqual(new Uri(requestUrl + "/next"), new Uri(nextPageRequest.RequestUrl), "Unexpected request URL for next page request.");
            }
        }
        private async Task ListFilesFolders(string path)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                // update the title path
                if (path == "/")
                {
                    pathText.Text = "CloudStreamer";
                }
                else
                {
                    pathText.Text = path;
                }
                fileScrollViewer.Visibility = Visibility.Collapsed;
                progressRing.Visibility     = Visibility.Visible;
                progressRing.IsActive       = true;
            });

            // handle login
            try
            {
                await UpdateOrInitOneDriveAuthIfNecessary();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e, "error");
                try
                {
                    await ExitOrRetryWithMessage("Failed to authenticate with OneDrive. Error: " + e.ToString());
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex, new Dictionary <string, string>
                    {
                        { "On", "Call Error Dialog" },
                        { "Where", "MainPage.xaml:InitOneDrive" },
                        { "DueTo", e.Message }
                    });
                }
                return;
            }


            if (oneDriveClient == null)
            {
                return;
            }

            try
            {
                IItemChildrenCollectionRequest request;
                if (path == "/")
                {
                    request = oneDriveClient.Drive.Root.Children.Request();
                }
                else
                {
                    request = oneDriveClient.Drive.Root.ItemWithPath(path).Children.Request();
                }
                IItemChildrenCollectionRequest sortedRequest = request.OrderBy(currentSortBy + " " + currentSortByDir);
                sortedRequest = sortedRequest.Expand("thumbnails");
                files         = (ItemChildrenCollectionPage)await sortedRequest.GetAsync();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e, "error");
                try
                {
                    await ExitOrRetryWithMessage("Failed to load Files from OneDrive. Error: " + e.ToString());
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex, new Dictionary <string, string>
                    {
                        { "On", "Call Error Dialog" },
                        { "Where", "MainPage.xaml:ListFilesFolders" },
                        { "DueTo", e.Message }
                    });
                }
            }
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                fileItems = new IncrementalLoadingCollection(files);
                fileScrollViewer.ItemsSource = fileItems;
                loading = false;
                progressRing.IsActive       = false;
                progressRing.Visibility     = Visibility.Collapsed;
                fileScrollViewer.Visibility = Visibility.Visible;
            });

            System.Diagnostics.Debug.WriteLine("Got " + fileItems.Count() + " files");
        }