Repository: OneDrive/onedrive-sdk-csharp Branch: master Commit: 3594584535a4 Files: 226 Total size: 564.4 KB Directory structure: gitextract_f6t6dqdk/ ├── .gitignore ├── Common/ │ └── Microsoft.OneDriveSDK.nuspec ├── LICENSE.txt ├── OneDriveSdk.sln ├── README.md ├── docs/ │ ├── auth.md │ ├── chunked-uploads.md │ ├── collections.md │ ├── errors.md │ ├── items.md │ └── overview.md ├── src/ │ └── OneDriveSdk/ │ ├── Constants.cs │ ├── Enums/ │ │ └── OneDriveErrorCode.cs │ ├── Helpers/ │ │ └── ChunkedUploadProvider.cs │ ├── Microsoft.OneDrive.Sdk.csproj │ ├── Models/ │ │ └── Generated/ │ │ ├── Audio.cs │ │ ├── ChunkedUploadSessionDescriptor.cs │ │ ├── Deleted.cs │ │ ├── Drive.cs │ │ ├── File.cs │ │ ├── FileSystemInfo.cs │ │ ├── Folder.cs │ │ ├── Hashes.cs │ │ ├── Identity.cs │ │ ├── IdentitySet.cs │ │ ├── Image.cs │ │ ├── Item.cs │ │ ├── ItemCopyRequestBody.cs │ │ ├── ItemCreateLinkRequestBody.cs │ │ ├── ItemCreateSessionRequestBody.cs │ │ ├── ItemInviteRequestBody.cs │ │ ├── ItemReference.cs │ │ ├── Location.cs │ │ ├── OpenWithApp.cs │ │ ├── OpenWithSet.cs │ │ ├── Permission.cs │ │ ├── Photo.cs │ │ ├── Quota.cs │ │ ├── Recipient.cs │ │ ├── SearchResult.cs │ │ ├── Share.cs │ │ ├── Shared.cs │ │ ├── SharingInvitation.cs │ │ ├── SharingLink.cs │ │ ├── SpecialFolder.cs │ │ ├── Thumbnail.cs │ │ ├── ThumbnailSet.cs │ │ ├── UploadSession.cs │ │ └── Video.cs │ ├── Properties/ │ │ └── AssemblyInfo.cs │ ├── Requests/ │ │ ├── Extensions/ │ │ │ ├── DriveRequestBuilderExtensions.cs │ │ │ ├── DriveSpecialCollectionRequestBuilderExtensions.cs │ │ │ ├── IDriveRequestBuilderExtensions.cs │ │ │ ├── IDriveSpecialCollectionRequestBuilderExtensions.cs │ │ │ ├── IItemRequestBuilderExtensions.cs │ │ │ ├── IOneDriveClientExtensions.cs │ │ │ ├── IShareRequestBuilderExtensions.cs │ │ │ ├── IThumbnailSetRequestBuilderExtensions.cs │ │ │ ├── ItemRequestBuilderExtensions.cs │ │ │ ├── OneDriveClientExtensions.cs │ │ │ ├── ShareRequestBuilderExtensions.cs │ │ │ ├── ThumbnailSetExtensions.cs │ │ │ └── ThumbnailSetRequestBuilderExtensions.cs │ │ ├── Generated/ │ │ │ ├── DriveItemsCollectionPage.cs │ │ │ ├── DriveItemsCollectionRequest.cs │ │ │ ├── DriveItemsCollectionRequestBuilder.cs │ │ │ ├── DriveItemsCollectionResponse.cs │ │ │ ├── DriveRecentCollectionPage.cs │ │ │ ├── DriveRecentCollectionResponse.cs │ │ │ ├── DriveRecentRequest.cs │ │ │ ├── DriveRecentRequestBuilder.cs │ │ │ ├── DriveRequest.cs │ │ │ ├── DriveRequestBuilder.cs │ │ │ ├── DriveSharedCollectionPage.cs │ │ │ ├── DriveSharedCollectionRequest.cs │ │ │ ├── DriveSharedCollectionRequestBuilder.cs │ │ │ ├── DriveSharedCollectionResponse.cs │ │ │ ├── DriveSpecialCollectionPage.cs │ │ │ ├── DriveSpecialCollectionRequest.cs │ │ │ ├── DriveSpecialCollectionRequestBuilder.cs │ │ │ ├── DriveSpecialCollectionResponse.cs │ │ │ ├── IDriveItemsCollectionPage.cs │ │ │ ├── IDriveItemsCollectionRequest.cs │ │ │ ├── IDriveItemsCollectionRequestBuilder.cs │ │ │ ├── IDriveRecentCollectionPage.cs │ │ │ ├── IDriveRecentRequest.cs │ │ │ ├── IDriveRecentRequestBuilder.cs │ │ │ ├── IDriveRequest.cs │ │ │ ├── IDriveRequestBuilder.cs │ │ │ ├── IDriveSharedCollectionPage.cs │ │ │ ├── IDriveSharedCollectionRequest.cs │ │ │ ├── IDriveSharedCollectionRequestBuilder.cs │ │ │ ├── IDriveSpecialCollectionPage.cs │ │ │ ├── IDriveSpecialCollectionRequest.cs │ │ │ ├── IDriveSpecialCollectionRequestBuilder.cs │ │ │ ├── IItemChildrenCollectionPage.cs │ │ │ ├── IItemChildrenCollectionRequest.cs │ │ │ ├── IItemChildrenCollectionRequestBuilder.cs │ │ │ ├── IItemContentRequest.cs │ │ │ ├── IItemContentRequestBuilder.cs │ │ │ ├── IItemCopyRequest.cs │ │ │ ├── IItemCopyRequestBuilder.cs │ │ │ ├── IItemCreateLinkRequest.cs │ │ │ ├── IItemCreateLinkRequestBuilder.cs │ │ │ ├── IItemCreateSessionRequest.cs │ │ │ ├── IItemCreateSessionRequestBuilder.cs │ │ │ ├── IItemDeltaCollectionPage.cs │ │ │ ├── IItemDeltaRequest.cs │ │ │ ├── IItemDeltaRequestBuilder.cs │ │ │ ├── IItemInviteRequest.cs │ │ │ ├── IItemInviteRequestBuilder.cs │ │ │ ├── IItemPermissionsCollectionPage.cs │ │ │ ├── IItemPermissionsCollectionRequest.cs │ │ │ ├── IItemPermissionsCollectionRequestBuilder.cs │ │ │ ├── IItemRequest.cs │ │ │ ├── IItemRequestBuilder.cs │ │ │ ├── IItemSearchCollectionPage.cs │ │ │ ├── IItemSearchRequest.cs │ │ │ ├── IItemSearchRequestBuilder.cs │ │ │ ├── IItemThumbnailsCollectionPage.cs │ │ │ ├── IItemThumbnailsCollectionRequest.cs │ │ │ ├── IItemThumbnailsCollectionRequestBuilder.cs │ │ │ ├── IItemVersionsCollectionPage.cs │ │ │ ├── IItemVersionsCollectionRequest.cs │ │ │ ├── IItemVersionsCollectionRequestBuilder.cs │ │ │ ├── IOneDriveClient.cs │ │ │ ├── IOneDriveDrivesCollectionPage.cs │ │ │ ├── IOneDriveDrivesCollectionRequest.cs │ │ │ ├── IOneDriveDrivesCollectionRequestBuilder.cs │ │ │ ├── IOneDriveSharesCollectionPage.cs │ │ │ ├── IOneDriveSharesCollectionRequest.cs │ │ │ ├── IOneDriveSharesCollectionRequestBuilder.cs │ │ │ ├── IPermissionRequest.cs │ │ │ ├── IPermissionRequestBuilder.cs │ │ │ ├── IShareItemsCollectionPage.cs │ │ │ ├── IShareItemsCollectionRequest.cs │ │ │ ├── IShareItemsCollectionRequestBuilder.cs │ │ │ ├── IShareRequest.cs │ │ │ ├── IShareRequestBuilder.cs │ │ │ ├── IThumbnailContentRequest.cs │ │ │ ├── IThumbnailContentRequestBuilder.cs │ │ │ ├── IThumbnailSetRequest.cs │ │ │ ├── IThumbnailSetRequestBuilder.cs │ │ │ ├── ItemChildrenCollectionPage.cs │ │ │ ├── ItemChildrenCollectionRequest.cs │ │ │ ├── ItemChildrenCollectionRequestBuilder.cs │ │ │ ├── ItemChildrenCollectionResponse.cs │ │ │ ├── ItemContentRequest.cs │ │ │ ├── ItemContentRequestBuilder.cs │ │ │ ├── ItemCopyRequest.cs │ │ │ ├── ItemCopyRequestBuilder.cs │ │ │ ├── ItemCreateLinkRequest.cs │ │ │ ├── ItemCreateLinkRequestBuilder.cs │ │ │ ├── ItemCreateSessionRequest.cs │ │ │ ├── ItemCreateSessionRequestBuilder.cs │ │ │ ├── ItemDeltaCollectionPage.cs │ │ │ ├── ItemDeltaCollectionResponse.cs │ │ │ ├── ItemDeltaRequest.cs │ │ │ ├── ItemDeltaRequestBuilder.cs │ │ │ ├── ItemInviteRequest.cs │ │ │ ├── ItemInviteRequestBuilder.cs │ │ │ ├── ItemPermissionsCollectionPage.cs │ │ │ ├── ItemPermissionsCollectionRequest.cs │ │ │ ├── ItemPermissionsCollectionRequestBuilder.cs │ │ │ ├── ItemPermissionsCollectionResponse.cs │ │ │ ├── ItemRequest.cs │ │ │ ├── ItemRequestBuilder.cs │ │ │ ├── ItemSearchCollectionPage.cs │ │ │ ├── ItemSearchCollectionResponse.cs │ │ │ ├── ItemSearchRequest.cs │ │ │ ├── ItemSearchRequestBuilder.cs │ │ │ ├── ItemThumbnailsCollectionPage.cs │ │ │ ├── ItemThumbnailsCollectionRequest.cs │ │ │ ├── ItemThumbnailsCollectionRequestBuilder.cs │ │ │ ├── ItemThumbnailsCollectionResponse.cs │ │ │ ├── ItemVersionsCollectionPage.cs │ │ │ ├── ItemVersionsCollectionRequest.cs │ │ │ ├── ItemVersionsCollectionRequestBuilder.cs │ │ │ ├── ItemVersionsCollectionResponse.cs │ │ │ ├── OneDriveClient.cs │ │ │ ├── OneDriveDrivesCollectionPage.cs │ │ │ ├── OneDriveDrivesCollectionRequest.cs │ │ │ ├── OneDriveDrivesCollectionRequestBuilder.cs │ │ │ ├── OneDriveDrivesCollectionResponse.cs │ │ │ ├── OneDriveSharesCollectionPage.cs │ │ │ ├── OneDriveSharesCollectionRequest.cs │ │ │ ├── OneDriveSharesCollectionRequestBuilder.cs │ │ │ ├── OneDriveSharesCollectionResponse.cs │ │ │ ├── PermissionRequest.cs │ │ │ ├── PermissionRequestBuilder.cs │ │ │ ├── ShareItemsCollectionPage.cs │ │ │ ├── ShareItemsCollectionRequest.cs │ │ │ ├── ShareItemsCollectionRequestBuilder.cs │ │ │ ├── ShareItemsCollectionResponse.cs │ │ │ ├── ShareRequest.cs │ │ │ ├── ShareRequestBuilder.cs │ │ │ ├── ThumbnailContentRequest.cs │ │ │ ├── ThumbnailContentRequestBuilder.cs │ │ │ ├── ThumbnailSetRequest.cs │ │ │ └── ThumbnailSetRequestBuilder.cs │ │ ├── IThumbnailRequest.cs │ │ ├── IThumbnailRequestBuilder.cs │ │ ├── IUploadChunkRequest.cs │ │ ├── ThumbnailRequest.cs │ │ ├── ThumbnailRequestBuilder.cs │ │ ├── UploadChunkRequest.cs │ │ └── UploadSessionRequest.cs │ ├── app.config │ └── packages.config └── tests/ └── Test.OneDriveSdk/ ├── 35MSSharedLib1024.snk ├── ChunkedUploadProviderTests.cs ├── Mocks/ │ ├── ExceptionHttpMessageHandler.cs │ ├── MockAuthenticationProvider.cs │ ├── MockHttpProvider.cs │ ├── MockSerializer.cs │ ├── TestChunkedUploadProvider.cs │ └── TestHttpMessageHandler.cs ├── Properties/ │ └── AssemblyInfo.cs ├── Requests/ │ ├── ItemRequestTests.cs │ ├── MethodRequestTests.cs │ ├── RequestTestBase.cs │ ├── ThumbnailRequestTests.cs │ └── UploadChunkRequestTest.cs ├── Test.OneDrive.Sdk.csproj ├── app.config └── packages.config ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.sln.docstates *.suo *.user *.userosscache *.sln.ide TestResults/* .vs/* # UWP project files project.lock.json *StoreKey.pfx Package.StoreAssociation.xml # Build results **/[Dd]ebug/ **/[Dd]ebugPublic/ **/[Rr]elease/ **/[Rr]eleases/ **/x64/ **/x86/ **/build/ **/bld/ **/[Bb]in/ **/[Oo]bj/ /lib # NuGet *.nupkg **/packages/* !**/packages/build/ # VS project upgrade files _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm ================================================ FILE: Common/Microsoft.OneDriveSDK.nuspec ================================================  Microsoft.OneDriveSDK 2.0.7 OneDrive .NET SDK Microsoft Microsoft false Integrate the OneDrive API into your .NET App! Copyright 2016 Microsoft Corporation https://github.com/OneDrive/onedrive-sdk-csharp http://msdn.microsoft.com/en-US/cc300389 https://dev.onedrive.com/images/OneDriveCloud.png onedrive sharepoint files livesdk liveconnect cloud storage microsoftaccount windowsliveid microsoftid windowsphone windowsstore metro xaml html ================================================ FILE: LICENSE.txt ================================================ OneDrive SDK for CSharp Copyright 2015 Microsoft Corporation All right reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: OneDriveSdk.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.25123.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{2EFD6E75-C1E0-4600-88D6-BFEDAD24A50A}" ProjectSection(SolutionItems) = preProject Common\Microsoft.OneDriveSDK.nuspec = Common\Microsoft.OneDriveSDK.nuspec EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.OneDrive.Sdk", "src\OneDriveSdk\Microsoft.OneDrive.Sdk.csproj", "{1368527B-D7B2-46AD-893D-6DC8C073D819}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{369050EF-15AF-4B0E-98DF-085B91E1B68D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test.OneDrive.Sdk", "tests\Test.OneDriveSdk\Test.OneDrive.Sdk.csproj", "{E3A990AA-5628-42AA-A8D4-1C599602DD96}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|ARM = Debug|ARM Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|ARM = Release|ARM Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {1368527B-D7B2-46AD-893D-6DC8C073D819}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Debug|Any CPU.Build.0 = Debug|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Debug|ARM.ActiveCfg = Debug|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Debug|ARM.Build.0 = Debug|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Debug|x64.ActiveCfg = Debug|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Debug|x64.Build.0 = Debug|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Debug|x86.ActiveCfg = Debug|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Debug|x86.Build.0 = Debug|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Release|Any CPU.ActiveCfg = Release|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Release|Any CPU.Build.0 = Release|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Release|ARM.ActiveCfg = Release|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Release|ARM.Build.0 = Release|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Release|x64.ActiveCfg = Release|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Release|x64.Build.0 = Release|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Release|x86.ActiveCfg = Release|Any CPU {1368527B-D7B2-46AD-893D-6DC8C073D819}.Release|x86.Build.0 = Release|Any CPU {E3A990AA-5628-42AA-A8D4-1C599602DD96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E3A990AA-5628-42AA-A8D4-1C599602DD96}.Debug|Any CPU.Build.0 = Debug|Any CPU {E3A990AA-5628-42AA-A8D4-1C599602DD96}.Debug|ARM.ActiveCfg = Debug|Any CPU {E3A990AA-5628-42AA-A8D4-1C599602DD96}.Debug|ARM.Build.0 = Debug|Any CPU {E3A990AA-5628-42AA-A8D4-1C599602DD96}.Debug|x64.ActiveCfg = Debug|Any CPU {E3A990AA-5628-42AA-A8D4-1C599602DD96}.Debug|x64.Build.0 = Debug|Any CPU {E3A990AA-5628-42AA-A8D4-1C599602DD96}.Debug|x86.ActiveCfg = Debug|Any CPU {E3A990AA-5628-42AA-A8D4-1C599602DD96}.Debug|x86.Build.0 = Debug|Any CPU {E3A990AA-5628-42AA-A8D4-1C599602DD96}.Release|Any CPU.ActiveCfg = Release|Any CPU {E3A990AA-5628-42AA-A8D4-1C599602DD96}.Release|ARM.ActiveCfg = Release|Any CPU {E3A990AA-5628-42AA-A8D4-1C599602DD96}.Release|x64.ActiveCfg = Release|Any CPU {E3A990AA-5628-42AA-A8D4-1C599602DD96}.Release|x86.ActiveCfg = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {1368527B-D7B2-46AD-893D-6DC8C073D819} = {2EFD6E75-C1E0-4600-88D6-BFEDAD24A50A} {E3A990AA-5628-42AA-A8D4-1C599602DD96} = {369050EF-15AF-4B0E-98DF-085B91E1B68D} EndGlobalSection EndGlobal ================================================ FILE: README.md ================================================ # OneDrive SDK for CSharp [![Build status](https://ci.appveyor.com/api/projects/status/fs9ddrmdev37v012/branch/master?svg=true)](https://ci.appveyor.com/project/OneDrive/onedrive-sdk-csharp/branch/master) Integrate the [OneDrive API](https://dev.onedrive.com/README.htm) into your C# project! The OneDrive SDK is built as a Portable Class Library and targets the following frameworks: * .NET 4.5.1 * .NET for Windows Store apps * Windows Phone 8.1 and higher Azure Active Directory authentication is available for: * Windows Forms apps * UWP apps * Windows 8.1 apps ## Installation via Nuget To install the OneDrive SDK via NuGet * Search for `Microsoft.OneDriveSDK` in the NuGet Library, or * Type `Install-Package Microsoft.OneDriveSDK` into the Package Manager Console. ## Getting started ### 1. Register your application Register your application for OneDrive by following [these](https://dev.onedrive.com/app-registration.htm) steps. ### 2. Setting your application Id and scopes Your app must requests permissions in order to access a user's OneDrive. To do this, specify your app ID and scopes, or permission level. For more information, see [Authentication scopes](https://dev.onedrive.com/auth/msa_oauth.htm#authentication-scopes). ### 3. Getting an authenticated OneDriveClient object You must get a **OneDriveClient** object in order for your app to make requests to the service, but first you must have an instance of an object that implements `IAuthenticationProvider` in Microsoft.Graph.Core. An example of such an imlementation can be found [MSA Auth Adapter repository](https://github.com/OneDrive/onedrive-sdk-dotnet-msa-auth-adapter). You should create the `IAuthenticationProvider`, authenticate using `AuthenticateUserAsync()`, and then create a `OneDriveClient` using the auth provider as a constructor argument. You must also provide the ClientId of your app, the return URL you have specified for your app, and the base URL for the API. Below is a sample of that pattern for authentication on the OneDrive service. ```csharp var msaAuthProvider = new myAuthProvider( myClientId, "https://login.live.com/oauth20_desktop.srf", { "onedrive.readonly", "wl.signin" }); await msaAuthProvider.AuthenticateUserAsync(); var oneDriveClient = new OneDriveClient("https://api.onedrive.com/v1.0", msaAuthProvider); ``` After that, you will be able to use the `oneDriveClient` object to make calls to the service. For more information, see [Authenticate your C# app for OneDrive](docs/auth.md). ### 4. Making requests to the service Once you have a OneDriveClient that is authenticated you can begin to make calls against the service. The requests against the service look like OneDrive's [REST API](https://dev.onedrive.com/README.htm). To retrieve a user's drive: ```csharp var drive = await oneDriveClient .Drive .Request() .GetAsync(); ``` `GetAsync` will return a `Drive` object on success and throw a `Microsoft.Graph.ServiceException` on error. To get the current user's root folder of their drive: ```csharp var rootItem = await oneDriveClient .Drive .Root .Request() .GetAsync(); ``` `GetAsync` will return an `Item` object on success and throw a `Microsoft.Graph.ServiceException` on error. For a general overview of how the SDK is designed, see [overview](docs/overview.md). The following sample applications are also available: * [OneDrive API Browser](https://github.com/OneDrive/onedrive-sample-apibrowser-dotnet) - Windows Forms app * [OneDrive Photo Browser](https://github.com/OneDrive/onedrive-sample-photobrowser-uwp) - Windows Universal app * [OneDrive Webhooks](https://github.com/OneDrive/onedrive-webhooks-aspnet) - ASP.NET MVC app To run the OneDrivePhotoBrowser sample app your machine will need to be configured for [UWP app development](https://msdn.microsoft.com/en-us/library/windows/apps/dn609832.aspx) and the project must be associated with the Windows Store. ## Documentation and resources * [Overview](docs/overview.md) * [Auth](docs/auth.md) * [Items](docs/items.md) * [Chunked uploads](docs/chunked-uploads.md) * [Collections](docs/collections.md) * [Errors](docs/errors.md) * [OneDrive API](http://dev.onedrive.com) ## Issues To view or log issues, see [issues](https://github.com/OneDrive/onedrive-sdk-csharp/issues). ## Other resources * NuGet Package: [https://www.nuget.org/packages/Microsoft.OneDriveSDK](https://www.nuget.org/packages/Microsoft.OneDriveSDK) ## License [License](LICENSE.txt) This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. ================================================ FILE: docs/auth.md ================================================ Authenticate your C# app for OneDrive ===== To authenticate your app to use OneDrive, you need to instantiate an object that implements `IAuthenticationProvider` from Microsoft.Graph and call `AuthenticateAsync` on it. Then, you must create a `OneDriveClient` object and pass in your auth provider as an argument. Note that if the user changes their password, your app must re-authenticate. If you see `401` error codes, this is most likely the case. See [Error codes for the OneDrive C# SDK](errors.md) for more info. **Note** This topic assumes that you are familiar with app authentication. For more info about authentication in OneDrive, see [Authentication for the OneDrive API](https://dev.onedrive.com/auth/readme.htm). ## Standard authentication components When implementing `IAuthenticationProvider`, a standard set of parameters will be required: | Parameter | Description | |:----------|:------------| | _clientId_ | The client ID of the app. Required. | | _returnUrl_ | A redirect URL. Required. | | _baseUrl_ | URL where the target OneDrive service is found. Required. | | _scopes_ | Permissions that your app requires from the user. Required. | | _client\_secret_ | The client secret created for your app. Optional. Not available for Windows Store 8.1, Windows Phone 8.1, and Universal Windows Platform (UWP) apps. | In addition to _clientId_, _returnURL_, _scopes_, and _client\_secret_ the method takes in implementations for a client type, credential cache, HTTP provider, and a service info provider or web authentication UI. If not provided, the default implementations of each item will be used. ### ClientType A single client can only call OneDrive for Consumer or OneDrive for Business, not both. The target service is configured implicitly by the `IAuthenticationProvider` and the _baseUrl_ passed into the `OneDriveClient` constructor. If the application would like to interact with both OneDrive for Consumer and OneDrive for Business, a client should be created for each. ## More Information More information, and a fuller example of authentication, can be found at the [MSA Auth Adapter repository](https://github.com/OneDrive/onedrive-sdk-dotnet-msa-auth-adapter). ================================================ FILE: docs/chunked-uploads.md ================================================ # Chunked Uploads ## Uploading large files and pausing/resuming uploads Chunked uploads are easy using `Helpers.ChunkedUploadProvider`. The easiest way to upload a large file looks like this: ```csharp var session = await oneDriveClient.ItemWithPath(uploadPath).CreateSession().Request().PostAsync(); var provider = new ChunkedUploadProvider(session, oneDriveClient, fileStream); var uploadedItem = await provider.UploadAsync(); ``` Your file will upload in default-sized chunks (5MiB). You can also adjust chunk size by adding a parameter to the `ChunkedUploadProvider` constructor: `new ChunkedUploadProvider(session, oneDriveClient, fileStream, 1024*1024); // 1 MiB`. ## Controlling and Monitoring Large Uploads You may want to monitor the progress of an upload (perhaps to show a progress bar to the user). You can get finer control of uploading each chunk using the skeleton below. You will certainly need to make a few modifications. Also, you can check out how the [ChunkedUploadProvider](../src/OneDriveSdk/Helpers/ChunkedUploadProvider.cs) ```csharp // Get the provider var myMaxChunkSize = 5*1024*1024; // 5MB var session = await oneDriveClient.ItemWithPath(uploadPath).CreateSession().Request().PostAsync(); var provider = new ChunkedUploadProvider(session, oneDriveClient, fileStream, myMaxChunkSize); // Setup the chunk request necessities var chunkRequests = provider.GetUploadChunkRequests(); var readBuffer = new byte[myMaxChunkSize]; var trackedExceptions = new List(); Item itemResult = null; //upload the chunks foreach(var request in chunkRequests) { // Do your updates here: update progress bar, etc. // ... // Send chunk request var result = await provider.GetChunkRequestResponseAsync(request, readBuffer, trackedExceptions); if(result.UploadSucceeded) { itemResult = result.ItemResponse; } } // Check that upload succeeded if (itemResult == null) { // Retry the upload // ... } ``` ================================================ FILE: docs/collections.md ================================================ Collections in the OneDrive SDK for C# ===== You can use the OneDrive SDK for C# to work with item collections in OneDrive. ## Getting a collection To retrieve a collection, like a folder's children, you call `GetAsync`: ```csharp await oneDriveClient .Drive .Items[itemId] .Children .Request() .GetAsync(); ``` `GetAsync` returns an `ICollectionPage` implementation on success and throws a `OneDriveException` on error. For children collections, the type returned is `IChildrenCollectionPage`, which inherits `ICollectionPage`. `IChildrenCollectionPage` contains three properties: |Name |Description | |--------------------|---------------------------------------------------------------------------------------------------------------------------------------------| |**CurrentPage** |An `IList`. | |**NextPageRequest** |An `IChildrenPageRequest` used to get to the next page of items, if another page exists. This value will be null if there is not a next page.| |**AdditionData** |An `IDictionary` to any additional values returned by the service. In this case, none. | ## Adding to a collection Some collections, like the children of a folder, can be changed. To add a folder to the children of an item, you can call the `AddAsync` method: ```csharp var folderToCreate = new Item { Name = "New folder", Folder = new Folder() }; var newFolder = await oneDriveClient .Drive .Items[itemId] .Children .Request() .AddAsync(folderToCreate); ``` `AddAsync` returns the created item on success and throws a `OneDriveException` on error. ## Expanding a collection To expand a collection, you call `Expand` on the collection request object with the string value of the expand: ```csharp var children = await oneDriveClient .Drive .Items[itemId] .Children .Request() .Expand("thumbnails") .GetAsync(); ``` ## Special collections Some API calls will return collections with added properties. These properties will always be in the additional data dictionary. These collections are also their own objects (subclasses of `ICollectionPage`) that will have these properties attached to them. To get the delta of an item you call: ```csharp var deltaCollectionPage = await oneDriveClient .Drive .Items[itemId] .Delta(deltaToken) .Request() .GetAsync(); ``` `IItemDeltaCollectionPage` is an `ICollectionPage` object with a `Token` property and a `DeltaLink` property. The token link can be used to pass into `Delta:` when you want to check for more changes. You can also construct a delta request with the `DeltaLink` property. The `NextPageRequest` is an `IItemDeltaRequest` to be used for paging purposes and will be null when there are no more changes. ================================================ FILE: docs/errors.md ================================================ Handling errors in the OneDrive SDK for C# ===== Errors in the OneDrive SDK for C# behave just like errors returned from the OneDrive service. You can read more about them [here](https://github.com/OneDrive/onedrive-api-docs/blob/master/misc/errors.md). Anytime you make a request against the service there is the potential for an error. You will see that all requests to the service can return an error. In the case of an error, the request will throw a `OneDriveException` object with an inner `Error` object that contains the service error details. ## Checking the error There are a few different types of errors that can occur during a network call. These error codes are defined in [OneDriveErrorCodes.cs](../src/OneDriveSdk/Enums/OneDriveErrorCodes.cs). ### Checking the error code You can easily check if an error has a specific code by calling `IsMatch` on the error code value. `IsMatch` is not case sensitive: ```csharp if (exception.IsMatch(OneDriveErrorCode.AccessDenied.ToString()) { // Handle access denied error } ``` Each error object has a `Message` property as well as code. This message is for debugging purposes and is not be meant to be displayed to the user. Common error codes are defined in [OneDriveErrorCodes.cs](../src/OneDriveSdk/Enums/OneDriveErrorCodes.cs). ### Authentication errors There can be errors during the authentication process. Authentication errors will have the code `AuthenticationFailed`. Authentication cancelled errors will have the code `AuthenticationCancelled`. ```csharp if (exception.IsMatch(OneDriveErrorCode.AuthenticationFailure.ToString()) { // Handle auth error } ``` The `Message` property will contain more detailed error information if available. ================================================ FILE: docs/items.md ================================================ Items in the OneDrive SDK for C# ===== Items in the OneDrive SDK for C# behave just like items through the OneDrive API. All actions on items described in the OneDrive API are available through the SDK. For more information, see the [Items Reference](https://dev.onedrive.com/README.htm#item-resource). The examples below assume that you have [Authenticated](/docs/auth.md) your app with a **OneDriveClient** object. * [Get an Item](#get-an-item) * [Delete an Item](#delete-an-item) * [Get Children for an Item](#get-children-for-an-item) * [Create a folder](#create-a-folder) * [Uploading contents](#uploading-contents) * [Downloading contents](#downloading-contents) * [Moving and updating an Item](#moving-and-updating-an-item) * [Copy an Item](#copy-an-item) Get an Item --------------- ### 1. By ID ```csharp var item = await oneDriveClient .Items[itemId] .Request() .GetAsync(); ``` ### 2. By path ```csharp var item = await oneDriveClient .Drive .Root .ItemWithPath("path/to/file/txt") .Request() .GetAsync(); ``` Access an item by parent reference path: ```csharp var item = await oneDriveClient .ItemWithPath(parentItem.ParentReference.Path + "/" + parentItem.Name + "/relative/path") .Request() .GetAsync(); ``` Delete an Item --------------- ```csharp await oneDriveClient .Drive .Items[itemId] .Request() .DeleteAsync(); ``` Get children for an Item ------------------------- More info about collections [here](/docs/collections.md). ```csharp await oneDriveClient .Drive .Items[itemId] .Children .Request() .GetAsync(); ``` Create a folder ------------------------- ### 1. By POST to a known folder ID ```csharp var folderToCreate = new Item { Folder = new Folder(), Name = "folder name" }; var createdFolder = await oneDriveClient .Drive .Items[itemId] .Children .Request() .AddAsync(folderToCreate); ``` ### 2. By PUT to a known folder ID ```csharp var folderToCreate = new Item { Folder = new Folder() }; var createdFolder = await oneDriveClient .Drive .Items[itemId] .ItemWithPath("folder name") .Request() .CreateAsync(folderToCreate); ``` ### 3. By PUT with a given path ```csharp var folderToCreate = new Item { Folder = new Folder() }; var createdFolder = await oneDriveClient .Drive .Root .ItemWithPath("folder/subfolder") .Request() .CreateAsync(folderToCreate); ``` Note: If the specified path does not exist, every folder name in the path will also be created. Uploading contents ------------------------------ ```csharp using (contentStream) { var uploadedItem = await oneDriveClient .Drive .Root .ItemWithPath("path/to/file.txt") .Content .Request() .PutAsync(contentStream); } ``` Downloading contents ------------------------------ ```csharp var contentStream = await oneDriveClient .Drive .Items[itemId] .Content .Request() .GetAsync(); ``` Moving and updating an Item -------------- To [move](https://dev.onedrive.com/items/move.htm) an item you must update its parent reference. ```csharp var updateItem = new Item { ParentReference = new ItemReference { Id = newParentId } }; var itemWithUpdates = await oneDriveClient .Drive .Items[itemId] .Request() .UpdateAsync(updateItem); ``` To change an item's name you could: ```csharp var updateItem = new Item { Name = "New name!" }; var itemWithUpdates = await oneDriveClient .Drive .Items[itemId] .Request() .UpdateAsync(updateItem); ``` Copy an Item --------------- Copying an item is an async action described [here](https://dev.onedrive.com/items/copy.htm). ```csharp var asyncStatus = await oneDriveClient .Drive .Items[itemId] .Copy(newItemName, new ItemReference { Id = copyLocationId }) .Request() .PostAsync(); ``` The `Copy` action returns an `IItemCopyAsyncMonitor` instance that has a method to poll the monitor URL for completion. The poll method returns the created item on completion. To poll until the copy action completes: ```csharp var newItem = await asyncStatus.CompleteOperationAsync(null, CancellationToken.None); ``` `CompleteOperationAsync` takes in an `IProgress` for reporting back progress status and a `CancellationToken` for action cancellation. The method will poll until completion unless cancelled. ================================================ FILE: docs/overview.md ================================================ OneDrive SDK for CSharp overview ===== The OneDrive C# SDK is designed to look just like the [OneDrive API](https://github.com/onedrive/onedrive-api-docs/). ## OneDriveClient When accessing the OneDrive APIs, all requests will be made through a **OneDriveClient** object. For a more detailed explanation, see [Authentication](/docs/auth.md). ## Resource model Resources, like [items](/docs/items.md) or drives, are represented by `Item` and `Drive`. These objects contain properties that represent the properties of a resource. These objects are property bags and cannot make calls against the service. To get the name of an item you would address the `Name` property. It is possible for any of these properties to be null at any time. To check if an item is a folder you can address the `Folder` property of the item. If the item is a folder, a `Folder` object that contains all of the properties described by the [folder](https://github.com/OneDrive/onedrive-api-docs/blob/master/facets/folder_facet.md) facet will be returned. See [Resource model](https://github.com/onedrive/onedrive-api-docs/#resource-model) for more information. ## Requests To make requests against the service, you construct request objects using a request builder object. The type of the request builder will depend on the type of the object you are addressing. This is meant to mimic creating the URL for any of the OneDrive APIs. ### 1. Request builders To generate a request you chain together calls on request builder objects. You get the first request builder from the `OneDriveClient` object. To get a drive request builder you call: |Task | SDK | URL | |:---------------|:---------------------:|:--------------------------------| |Get a drive | oneDriveClient.Drive | GET api.onedrive.com/v1.0/drive/| The call will return an `IDriveRequestBuilder` object. From drive you can continue to chain the requests to get everything else in the API, like an item. |Task | SDK | URL | |:---------------|:------------------------------------:|:------------------------------------------| |Get an item | oneDriveClient.Drive.Items["1234"] | GET api.onedrive.com/v1.0/drive/items/1234| Here `oneDriveClient.Drive` returns an `IDriveRequestBuilder` that contains a property `Items` of type `IItemsCollectionRequestBuilder`. That builder has an accessor for the item ID and Items["1234"] returns an `IItemRequestBuilder`. Similarly to get thumbnails: |Task | SDK | URL | |----------------|--------------------------------|--------------------------| | Get thumbnails | ... Items["1234"].Thumbnails | .../items/1234/thumbnails| Here, `oneDriveClient.Drive.Items["1234"]` returns an `IItemRequestBuilder` that contains the property Thumbnails of type `IThumbnailsCollectionRequestBuilder`. This returns a collection of [thumbnail sets](https://github.com/OneDrive/onedrive-api-docs/blob/master/resources/thumbnailSet.md). To index the collection directly you can call: |Task | SDK | URL | |-------------------|-------------------------------------|----------------------------| | Get thumbnail Set | ... Items["1234"].Thumbnails["0"] | ...items/1234/thumbnails/0 | To return a thumbnail set, and to get a specific [thumbnail](https://github.com/OneDrive/onedrive-api-docs/blob/master/resources/thumbnail.md), you can add the name of the thumbnail to the URL like this: |Task | SDK | URL | |-----------------|-----------------------------|------------------------| | Get a thumbnail | ... Thumbnails["0"].Small | .../thumbnails/0/small | ### 2. Request calls After you build the request you call the `Request` method on the request builder. This will construct the request object needed to make calls against the service. For an item you call: ```csharp var itemRequest = oneDriveClient .Drive .Items[itemId] .Request(); ``` All request builders have a `Request` method that can generate a request object. Request objects may have different methods on them depending on the type of request. To get an item you call: ```csharp var item = await oneDriveClient .Drive .Items[itemId] .Request() .GetAsync(); ``` For more info, see [items](/docs/items.md) and [errors](/docs/errors.md). ## Query options If you only want to retrieve certain properties of a resource you can select them. Here's how to get only the names and IDs of an item: ```csharp var item = await oneDriveClient .Drive .Items[itemId] .Request() .Select("name,id") .GetAsync(); ``` All properties other than `Name` and `Id` will be null on the item. To expand certain properties on resources you can call a similar expand method, like this: ```csharp var item = await oneDriveClient .Drive .Items[itemId] .Request() .Expand("thumbnails,children(expand=thumbnails)") .GetAsync(); ``` The above call will expand thumbnails and children for the item, as well as thumbnails for all of the children. ================================================ FILE: src/OneDriveSdk/Constants.cs ================================================ // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ namespace Microsoft.OneDrive.Sdk { public static class Constants { public const int PollingIntervalInMs = 5000; public static class Headers { public const string SdkVersionHeaderPrefix = "onedrive"; } public static class Url { public const string Drive = "drive"; public const string Root = "root"; public const string AppRoot = "approot"; public const string Documents = "documents"; public const string Photos = "photos"; public const string CameraRoll = "cameraroll"; public const string Music = "music"; } } } ================================================ FILE: src/OneDriveSdk/Enums/OneDriveErrorCode.cs ================================================ // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ namespace Microsoft.OneDrive.Sdk { public enum OneDriveErrorCode { AccessDenied, ActivityLimitReached, GeneralException, InvalidRange, InvalidRequest, ItemNotFound, MalwareDetected, NameAlreadyExists, NotAllowed, NotSupported, ResourceModified, ResyncRequired, ServiceNotAvailable, Timeout, TooManyRedirects, QuotaLimitReached, Unauthenticated, } } ================================================ FILE: src/OneDriveSdk/Helpers/ChunkedUploadProvider.cs ================================================ // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ namespace Microsoft.OneDrive.Sdk.Helpers { using Microsoft.Graph; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; /// /// Use this class to make resumable uploads or to upload large files. This /// class allows the client to control the size of chunks uploaded (for example, can be useful /// to use small chunks if the connection is slow). Also allows the client to /// pause an upload and resume later. /// public class ChunkedUploadProvider { private const int DefaultMaxChunkSize = 5 * 1024 * 1024; private const int RequiredChunkSizeIncrement = 320 * 1024; public UploadSession Session { get; private set; } private IBaseClient client; private Stream uploadStream; private readonly int maxChunkSize; private List> rangesRemaining; private long totalUploadLength => uploadStream.Length; /// /// Helps with resumable uploads. Generates chunk requests based on /// information, and can control uploading of requests using /// /// Session information. /// Client used to upload chunks. /// Readable, seekable stream to be uploaded. Length of session is determined via uploadStream.Length /// Max size of each chunk to be uploaded. Multiple of 320 KiB (320 * 1024) is required. /// If less than 0, default value of 5 MiB is used. . public ChunkedUploadProvider(UploadSession session, IBaseClient client, Stream uploadStream, int maxChunkSize = -1) { if (!uploadStream.CanRead || !uploadStream.CanSeek) { throw new ArgumentException("Must provide stream that can read and seek"); } this.Session = session; this.client = client; this.uploadStream = uploadStream; this.rangesRemaining = this.GetRangesRemaining(session); this.maxChunkSize = maxChunkSize < 0 ? DefaultMaxChunkSize : maxChunkSize; if (this.maxChunkSize % RequiredChunkSizeIncrement != 0) { throw new ArgumentException("Max chunk size must be a multiple of 320 KiB", nameof(maxChunkSize)); } } /// /// Get the series of requests needed to complete the upload session. Call /// first to update the internal session information. /// /// Options to be applied to each request. /// All requests currently needed to complete the upload session. public virtual IEnumerable GetUploadChunkRequests(IEnumerable