コード例 #1
0
        /// <summary>
        /// Create children http request with specific options
        /// </summary>
        /// <param name="requestBuilder">request builder</param>
        /// <param name="top">The number of items to return in a result set.</param>
        /// <param name="orderBy">Sort the order of items in the response collection</param>
        /// <param name="filter">Filters the response based on a set of criteria.</param>
        /// <returns>Returns the http request</returns>
        public static IItemChildrenCollectionRequest CreateChildrenRequest(this IItemRequestBuilder requestBuilder, int top, OrderBy orderBy = OrderBy.None, string filter = null)
        {
            IItemChildrenCollectionRequest oneDriveitemsRequest = null;

            if (orderBy == OrderBy.None && string.IsNullOrEmpty(filter))
            {
                return(requestBuilder.Children.Request().Top(top));
            }

            if (orderBy == OrderBy.None)
            {
                return(requestBuilder.Children.Request().Top(top).Filter(filter));
            }

            string order = OneDriveHelper.TransformOrderByToODataString(orderBy);

            if (string.IsNullOrEmpty(filter))
            {
                oneDriveitemsRequest = requestBuilder.Children.Request().Top(top).OrderBy(order);
            }
            else
            {
                oneDriveitemsRequest = requestBuilder.Children.Request().Top(top).OrderBy(order).Filter(filter);
            }

            return(oneDriveitemsRequest);
        }
コード例 #2
0
        /// <inheritdoc/>
        public async Task <IOneDriveStorageFile> UploadFileAsync(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 = $"{Provider.BaseUrl}/drive/items/{OneDriveItem.Id}:/{desiredName}:/oneDrive.createSession";

            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 Provider.AuthenticationProvider.AuthenticateRequestAsync(request).ConfigureAwait(false);

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

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

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

            _uploadSession = JsonConvert.DeserializeObject <Microsoft.OneDrive.Sdk.UploadSession>(jsonData);

            var streamToUpload = content.AsStreamForRead();

            _uploadProvider = new Microsoft.OneDrive.Sdk.Helpers.ChunkedUploadProvider(_uploadSession, Provider, streamToUpload, maxChunkSize);

            var uploadedItem = await _uploadProvider.UploadAsync().ConfigureAwait(false);

            IsUploadCompleted = true;

            return(InitializeOneDriveStorageFile(uploadedItem.CopyToDriveItem()));
        }
コード例 #3
0
        /// <summary>
        /// Initialize OneDrive service
        /// </summary>
        /// <param name="appClientId">Application Id Client. Could be null if AccountProviderType.OnlineId is used</param>
        /// <param name="accountProviderType">Account Provider type.
        /// <para>AccountProviderType.OnlineId: If the user is signed into a Windows system with a Microsoft Account, this user will be used for authentication request. Need to associate the App to the store</para>
        /// <para>AccountProviderType.Msa: Authenticate the user with a Microsoft Account. You need to register your app https://apps.dev.microsoft.com in the SDK Live section</para>
        /// <para>AccountProviderType.Adal: Authenticate the user with a Office 365 Account. You need to register your in Azure Active Directory</para></param>
        /// <param name="scopes">Scopes represent various permission levels that an app can request from a user. Could be null if AccountProviderType.Adal is used </param>
        /// <remarks>If AccountProvider</remarks>
        /// <returns>Success or failure.</returns>
        public bool Initialize(string appClientId, AccountProviderType accountProviderType = AccountProviderType.OnlineId, OneDriveScopes scopes = OneDriveScopes.ReadWrite | OneDriveScopes.OfflineAccess)
        {
            if (accountProviderType != AccountProviderType.OnlineId && string.IsNullOrEmpty(appClientId))
            {
                throw new ArgumentNullException(nameof(appClientId));
            }

            AppClientId = appClientId;

            if (accountProviderType != AccountProviderType.Adal)
            {
                Scopes = OneDriveHelper.TransformScopes(scopes);
            }

            IsInitialized        = true;
            _accountProviderType = accountProviderType;
            return(true);
        }
コード例 #4
0
        /// <inheritdoc/>
        public bool Initialize(string appClientId, AccountProviderType accountProviderType = AccountProviderType.OnlineId, OneDriveScopes scopes = OneDriveScopes.OfflineAccess | OneDriveScopes.ReadWrite)
        {
            if (accountProviderType == AccountProviderType.Adal || accountProviderType == AccountProviderType.Msal)
            {
                _instance = new GraphOneDriveService();
                return(_instance.Initialize(appClientId, accountProviderType, scopes));
            }

            if (accountProviderType != AccountProviderType.OnlineId && string.IsNullOrEmpty(appClientId))
            {
                throw new ArgumentNullException(nameof(appClientId));
            }

            _appClientId = appClientId;

            if (accountProviderType == AccountProviderType.Msa)
            {
                _scopes = OneDriveHelper.TransformScopes(scopes);
            }

            _isInitialized       = true;
            _accountProviderType = accountProviderType;
            return(true);
        }
コード例 #5
0
        /// <inheritdoc/>
        public async Task <IOneDriveStorageFile> CreateFileAsync(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 = "UWP Community Toolkit"
                    });
                }

                streamContent = content.AsStreamForRead();
            }

            var                childrenRequest = ((IItemRequestBuilder)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((IOneDriveClient)Provider).SendAuthenticatedRequestAsync(request, cancellationToken);

            return(InitializeOneDriveStorageFile(createdFile.CopyToDriveItem()));
        }
コード例 #6
0
        /// <inheritdoc/>
        public async Task <IOneDriveStorageFolder> CreateFolderAsync(string desiredName, CreationCollisionOption options = CreationCollisionOption.FailIfExists, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (string.IsNullOrEmpty(desiredName))
            {
                throw new ArgumentNullException(nameof(desiredName));
            }

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

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
            Item item = new Item {
                Name = desiredName, Folder = new Microsoft.OneDrive.Sdk.Folder()
                {
                }
            };

            item.AdditionalData = new Dictionary <string, object>();
            item.AdditionalData.Add(new KeyValuePair <string, object>("@name.conflictBehavior", OneDriveHelper.TransformCollisionOptionToConflictBehavior(options.ToString())));
            var jsonOptions = JsonConvert.SerializeObject(item);

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

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

            return(InitializeOneDriveStorageFolder(createdFolder.CopyToDriveItem()));
        }