Ejemplo n.º 1
0
        public async static Task <string> DownloadFileAsync(this LiveConnectClient client, string directory, string fileName)
        {
            string skyDriveFolder = await OneDriveHelper.CreateOrGetDirectoryAsync(client, directory, "me/skydrive");

            var result = await client.DownloadAsync(skyDriveFolder);

            var operation = await client.GetAsync(skyDriveFolder + "/files");

            var    items = operation.Result["data"] as List <object>;
            string id    = string.Empty;

            // Search for the file - add handling here if File Not Found
            foreach (object item in items)
            {
                IDictionary <string, object> file = item as IDictionary <string, object>;
                if (file["name"].ToString() == fileName)
                {
                    id = file["id"].ToString();
                    break;
                }
            }

            var downloadResult = await client.DownloadAsync(string.Format("{0}/content", id));

            var    reader = new StreamReader(downloadResult.Stream);
            string text   = await reader.ReadToEndAsync();

            return(text);
        }
Ejemplo n.º 2
0
 public OneDriveHandler(ITracer tracer,
                        IDeploymentStatusManager status,
                        IDeploymentSettingsManager settings,
                        IEnvironment environment)
 {
     _settings       = settings;
     _oneDriveHelper = new OneDriveHelper(tracer, status, settings, environment);
 }
Ejemplo n.º 3
0
        private async Task <OneDriveStorageFile> UploadFileInternalAsync(string desiredName, IRandomAccessStream content, CreationCollisionOption options = CreationCollisionOption.FailIfExists, int maxChunkSize = -1)
        {
            int currentChunkSize = maxChunkSize < 0 ? OneDriveUploadConstants.DefaultMaxChunkSizeForUploadSession : maxChunkSize;

            if (currentChunkSize % OneDriveUploadConstants.RequiredChunkSizeIncrementForUploadSession != 0)
            {
                throw new ArgumentException("Max chunk size must be a multiple of 320 KiB", nameof(maxChunkSize));
            }

            if (string.IsNullOrEmpty(desiredName))
            {
                throw new ArgumentNullException(nameof(desiredName));
            }

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

            var uploadSessionUri = $"{_service.Provider.GraphProvider.BaseUrl}/drive/items/{_oneDriveStorageFolder.OneDriveItem.Id}:/{desiredName}:/createUploadSession";

            var conflictBehavior = new OneDriveItemConflictBehavior {
                Item = new OneDriveConflictItem {
                    ConflictBehavior = OneDriveHelper.TransformCollisionOptionToConflictBehavior(options.ToString())
                }
            };

            var jsonConflictBehavior   = JsonConvert.SerializeObject(conflictBehavior);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uploadSessionUri)
            {
                Content = new StringContent(jsonConflictBehavior, Encoding.UTF8, "application/json")
            };
            await _service.Provider.GraphProvider.AuthenticationProvider.AuthenticateRequestAsync(request).ConfigureAwait(false);

            var response = await _service.Provider.GraphProvider.HttpProvider.SendAsync(request).ConfigureAwait(false);

            if (!response.IsSuccessStatusCode)
            {
                throw new ServiceException(new Error {
                    Message = "Could not create an UploadSession", Code = "NoUploadSession", ThrowSite = "Windows Community Toolkit"
                });
            }

            _oneDriveStorageFolder.IsUploadCompleted = false;
            var jsonData = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            _oneDriveStorageFolder.UploadSession = JsonConvert.DeserializeObject <UploadSession>(jsonData);

            var streamToUpload = content.AsStreamForRead();

            _oneDriveStorageFolder.UploadProvider = new ChunkedUploadProvider(_oneDriveStorageFolder.UploadSession, _service.Provider.GraphProvider, streamToUpload, maxChunkSize);

            var uploadedItem = await _oneDriveStorageFolder.UploadProvider.UploadAsync().ConfigureAwait(false);

            _oneDriveStorageFolder.IsUploadCompleted = true;
            return(_oneDriveStorageFolder.InitializeOneDriveStorageFile(uploadedItem));
        }
Ejemplo n.º 4
0
 public OneDriveHandler(ITracer tracer,
                        IDeploymentStatusManager status,
                        IDeploymentSettingsManager settings,
                        IEnvironment environment,
                        IRepositoryFactory repositoryFactory)
 {
     _settings          = settings;
     _repositoryFactory = repositoryFactory;
     _oneDriveHelper    = new OneDriveHelper(tracer, status, settings, environment);
 }
Ejemplo n.º 5
0
        public void TestConsumerOneDrivePath()
        {
            string basePath = System.Environment.GetEnvironmentVariable("OneDriveConsumer");
            string testPath = "https://d.docs.live.net/98546e1b65a78a74/Documents/test.xlsx";
            string actual   = OneDriveHelper.ConvertToLocalPath(testPath);

            string expected = Path.Combine(basePath, "Documents\\test.xlsx");

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 6
0
        private async Task <OneDriveStorageFile> CreateFileInternalAsync(string desiredName, CreationCollisionOption options = CreationCollisionOption.FailIfExists, IRandomAccessStream content = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Stream streamContent = null;

            if (string.IsNullOrEmpty(desiredName))
            {
                throw new ArgumentNullException(nameof(desiredName));
            }

            if (content == null)
            {
                // Because OneDrive (Not OneDrive For business) don't allow to create a file with no content
                // Put a single byte, then the caller can call Item.WriteAsync() to put the real content in the file
                byte[] buffer = new byte[1];
                buffer[0]     = 0x00;
                streamContent = new MemoryStream(buffer);
            }
            else
            {
                if (content.Size > OneDriveUploadConstants.SimpleUploadMaxSize)
                {
                    throw new ServiceException(new Error {
                        Message = "The file size cannot exceed 4MB, use UploadFileAsync instead ", Code = "MaxSizeExceeded", ThrowSite = "Windows Community Toolkit"
                    });
                }

                streamContent = content.AsStreamForRead();
            }

            var                childrenRequest = ((IDriveItemRequestBuilder)_oneDriveStorageFolder.RequestBuilder).Children.Request();
            string             requestUri      = $"{childrenRequest.RequestUrl}/{desiredName}/[email protected]={OneDriveHelper.TransformCollisionOptionToConflictBehavior(options.ToString())}";
            HttpRequestMessage request         = new HttpRequestMessage(HttpMethod.Put, requestUri)
            {
                Content = new StreamContent(streamContent)
            };
            var createdFile = await((IGraphServiceClient)_service.Provider.GraphProvider).SendAuthenticatedRequestAsync(request, cancellationToken);

            return(_oneDriveStorageFolder.InitializeOneDriveStorageFile(createdFile));
        }
Ejemplo n.º 7
0
        private async Task <OneDriveStorageFolder> CreateFolderInternalAsync(string desiredName, CreationCollisionOption options = CreationCollisionOption.FailIfExists, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (string.IsNullOrEmpty(desiredName))
            {
                throw new ArgumentNullException(nameof(desiredName));
            }

            var childrenRequest = ((IDriveItemRequestBuilder)_oneDriveStorageFolder.RequestBuilder).Children.Request();
            var requestUri      = childrenRequest.RequestUrl;

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
            DriveItem          item    = new DriveItem {
                Name = desiredName, Folder = new Graph.Folder {
                }
            };

            item.AdditionalData = new Dictionary <string, object>();
            item.AdditionalData.Add(new KeyValuePair <string, object>("@microsoft.graph.conflictBehavior", OneDriveHelper.TransformCollisionOptionToConflictBehavior(options.ToString())));

            var jsonOptions = JsonConvert.SerializeObject(item);

            request.Content = new StringContent(jsonOptions, Encoding.UTF8, "application/json");

            var createdFolder = await((IGraphServiceClient)_service.Provider.GraphProvider).SendAuthenticatedRequestAsync(request, cancellationToken).ConfigureAwait(false);

            return(_oneDriveStorageFolder.InitializeOneDriveStorageFolder(createdFolder));
        }
Ejemplo n.º 8
0
        public async Task SyncBasicTests()
        {
            var mockTracer = new Mock <ITracer>();

            mockTracer
            .Setup(m => m.Trace(It.IsAny <string>(), It.IsAny <IDictionary <string, string> >()));

            var repository      = Mock.Of <IRepository>();
            var fileSystem      = new Mock <IFileSystem>();
            var fileBase        = new Mock <FileBase>();
            var fileInfoFactory = new Mock <IFileInfoFactory>();
            var fileInfo        = new Mock <FileInfoBase>();
            var dirBase         = new Mock <DirectoryBase>();
            var dirInfoFactory  = new Mock <IDirectoryInfoFactory>(); // mock dirInfo to make FileSystemHelpers.DeleteDirectorySafe not throw exception
            var dirInfoBase     = new Mock <DirectoryInfoBase>();

            fileSystem.Setup(f => f.File).Returns(fileBase.Object);
            fileSystem.Setup(f => f.FileInfo).Returns(fileInfoFactory.Object);
            fileInfoFactory.Setup(f => f.FromFileName(It.IsAny <string>()))
            .Returns(() => fileInfo.Object);
            fileSystem.Setup(f => f.Directory).Returns(dirBase.Object);
            fileSystem.Setup(f => f.DirectoryInfo).Returns(dirInfoFactory.Object);
            dirInfoFactory.Setup(d => d.FromDirectoryName(It.IsAny <string>())).Returns(dirInfoBase.Object);
            fileBase.Setup(fb => fb.Exists(It.IsAny <string>())).Returns((string path) =>
            {
                return(path != null && (path.EndsWith("f-delete") || path.EndsWith("bar.txt")));
            });
            fileBase.Setup(fb => fb.SetLastWriteTimeUtc(It.IsAny <string>(), It.IsAny <DateTime>()));

            dirBase.Setup(d => d.Exists(It.IsAny <string>())).Returns((string path) =>
            {
                return(path != null && (path.EndsWith("f-delete-dir") || path.EndsWith("f2")));
            });
            FileSystemHelpers.Instance = fileSystem.Object;

            // prepare change from OneDrive
            OneDriveModel.OneDriveChange change = new OneDriveModel.OneDriveChange();
            change.IsDeleted = false;

            // prepare OneDriveInfo
            var info = new OneDriveInfo();

            info.AccessToken     = "fake-token";
            info.RepositoryUrl   = "https://api.onedrive.com/v1.0/drive/special/approot:/fake-folder";
            info.TargetChangeset = new ChangeSet("id", "authorName", "authorEmail", "message", DateTime.UtcNow);

            // prepare http handler
            var handler = new TestMessageHandler((HttpRequestMessage message) =>
            {
                StringContent content = null;
                if (message != null && message.RequestUri != null)
                {
                    if (message.RequestUri.AbsoluteUri.Equals(info.RepositoryUrl))
                    {
                        content = new StringContent(@"{ 'id': 'fake-id'}", Encoding.UTF8, "application/json");
                        return(new HttpResponseMessage {
                            Content = content
                        });
                    }
                    else if (message.RequestUri.AbsoluteUri.Equals("https://api.onedrive.com/v1.0/drive/items/fake-id/view.changes"))
                    {
                        content = new StringContent(ViewChangePayload, Encoding.UTF8, "application/json");
                        return(new HttpResponseMessage {
                            Content = content
                        });
                    }
                    else if (message.RequestUri.AbsoluteUri.EndsWith("items/A6034FFBC93398FD!331") ||
                             message.RequestUri.AbsoluteUri.EndsWith("items/A6034FFBC93398FD!330"))
                    {
                        content = new StringContent(@"{ '@content.downloadUrl': 'http://site-does-not-exist.microsoft.com'}", Encoding.UTF8, "application/json");
                        return(new HttpResponseMessage {
                            Content = content
                        });
                    }
                }

                content = new StringContent("test file content", Encoding.UTF8, "application/json");
                return(new HttpResponseMessage {
                    Content = content
                });
            });

            // perform action
            OneDriveHelper helper = CreateMockOneDriveHelper(handler: handler, tracer: mockTracer.Object);
            await helper.Sync(info, repository);

            // verification

            /*
             * Sycing f2 to wwwroot:
             *
             *   There are 6 changes
             *      2 deletion
             *        f2\f-delete       (existed as file)
             *        f2\f-delete-dir   (existed as folder)
             *
             *      2 file changes
             *        f2\foo.txt        (not existed)
             *        f2\f22\bar.txt    (existed)
             *
             *      2 folder chagnes
             *        f2                (existed)
             *        f2\f22            (not existed)
             */

            // deletion
            mockTracer.Verify(t => t.Trace(@"Deleted file D:\home\site\wwwroot\f-delete", It.Is <IDictionary <string, string> >(d => d.Count == 0)));
            mockTracer.Verify(t => t.Trace(@"Deleted directory D:\home\site\wwwroot\f-delete-dir", It.Is <IDictionary <string, string> >(d => d.Count == 0)));

            // file changes
            mockTracer.Verify(t => t.Trace(@"Creating file D:\home\site\wwwroot\foo.txt ...", It.Is <IDictionary <string, string> >(d => d.Count == 0)));
            mockTracer.Verify(t => t.Trace(@"Updating file D:\home\site\wwwroot\f22\bar.txt ...", It.Is <IDictionary <string, string> >(d => d.Count == 0)));

            mockTracer.Verify(t => t.Trace(@"Deleted file D:\home\site\wwwroot\f-delete", It.Is <IDictionary <string, string> >(d => d.Count == 0)));
            mockTracer.Verify(t => t.Trace(@"Deleted directory D:\home\site\wwwroot\f-delete-dir", It.Is <IDictionary <string, string> >(d => d.Count == 0)));

            // directory changes
            mockTracer.Verify(t => t.Trace(@"Ignore folder f2", It.Is <IDictionary <string, string> >(d => d.Count == 0)));
            mockTracer.Verify(t => t.Trace(@"Creating directory D:\home\site\wwwroot\f22 ...", It.Is <IDictionary <string, string> >(d => d.Count == 0)));
        }
Ejemplo n.º 9
-1
 public OneDriveHandler(ITracer tracer,
                        IDeploymentStatusManager status,
                        IDeploymentSettingsManager settings,
                        IEnvironment environment)
 {
     _settings = settings;
     _oneDriveHelper = new OneDriveHelper(tracer, status, settings, environment);
 }