Beispiel #1
0
        /// <summary>
        /// Creates a new subfolder in the current folder.
        /// </summary>
        /// <param name="desiredName">The name of the new subfolder to create in the current folder.</param>
        /// <param name="options">>One of the enumeration values that determines how to handle the collision if a file with the specified desiredName already exists in the current folder.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
        /// <returns>When this method completes, it returns a MicrosoftGraphOneDriveFolder that represents the new subfolder.</returns>
        public async Task <OneDriveStorageFolder> CreateFolderAsync(string desiredName, CreationCollisionOption options = CreationCollisionOption.FailIfExists, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (string.IsNullOrEmpty(desiredName))
            {
                throw new ArgumentNullException(nameof(desiredName));
            }

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

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
            OneDriveItem       item    = new OneDriveItem {
                Name = desiredName, Folder = new Microsoft.OneDrive.Sdk.Folder {
                }, ConflictBehavior = options.ToString()
            };
            var jsonOptions = item.SerializeToJson();

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

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

            return(InitializeOneDriveStorageFolder(createdFolder));
        }
Beispiel #2
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));
        }
Beispiel #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));
        }
Beispiel #4
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));
        }