GithubHelp home page GithubHelp logo

onedrive-sdk-csharp's Introduction

OneDrive SDK for CSharp

Build status

Integrate the OneDrive API 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 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.

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. 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.

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.

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.

To retrieve a user's drive:

    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:

    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.

The following sample applications are also available:

To run the OneDrivePhotoBrowser sample app your machine will need to be configured for UWP app development and the project must be associated with the Windows Store.

Documentation and resources

Issues

To view or log issues, see issues.

Other resources

License

License

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

onedrive-sdk-csharp's People

Contributors

cdmayer avatar daboxu avatar damirlisak avatar ginach avatar gitasaurus avatar jimic avatar mimisasouvanh avatar rgregg avatar shahmalav avatar steve-bitmight avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

onedrive-sdk-csharp's Issues

Trying to access empty Shared With Me throws

If there is nothing Shared With Me and I try to access the Shared With Me 'folder', I get an exception saying the item wasn't found. It would be more convenient if this function returned an empty Enumeration instead of throwing.

SDK version = 1.1.15
C# console app on Win 10-64

To reproduce:

// Use a 'home consumer' OneDrive account that has nothing shared with it.
OD.IDriveSharedWithMeRequestBuilder swmRequestBuilder = OneDrive.client.Drive.SharedWithMe();
OD.IDriveSharedWithMeCollectionPage result = swmRequestBuilder.Request().GetAsync().Result; // throws

Unable to create folder

I am trying to authenticate and create a folder. I have tried below 2 approaches, but both giving error ("An error occurred sending the request.") at
var newFolder = await this.oneDriveClientNew.Drive.Items["root"].Children.Request().AddAsync(folderToCreate); line.

Could you please help?

Scopes used : { "onedrive.readwrite", "wl.offline_access", "wl.signin" };

Approach 1

this.oneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
FormBrowser.MsaClientId,
FormBrowser.MsaReturnUrl,
FormBrowser.Scopes,
webAuthenticationUi: new FormsWebAuthenticationUi());

if (!this.oneDriveClient.IsAuthenticated)
{
var session = await this.oneDriveClient.AuthenticateAsync();
var folderToCreate = new Item { Name = "My folder1", Folder = new Folder() };
var newFolder = await this.oneDriveClient.Drive.Items["root"].Children.Request().AddAsync(folderToCreate);
}

Approach 2

this.oneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
FormBrowser.MsaClientId,
FormBrowser.MsaReturnUrl,
FormBrowser.Scopes,
webAuthenticationUi: new FormsWebAuthenticationUi());

if (!this.oneDriveClient.IsAuthenticated)
{
var session = await this.oneDriveClient.AuthenticateAsync();

this.oneDriveClientNew = await OneDriveClient.GetSilentlyAuthenticatedMicrosoftAccountClient(
     FormBrowser.MsaClientId,
     FormBrowser.MsaReturnUrl,
     FormBrowser.Scopes,
     session.RefreshToken);

await this.oneDriveClientNew.AuthenticateAsync();

var folderToCreate = new Item { Name = "My folder1", Folder = new Folder() };
var newFolder = await this.oneDriveClientNew.Drive.Items["root"].Children.Request().AddAsync(folderToCreate);

}

Don't show splash screen on sign out

I have noticed that when signing out the FormsWebDialogs is shown briefly. Although it's not an issue per say, it would satisfy my OCD, it it wasn't shown.

@ginach
In case you agree to that I can provide a PR to deal with that.
Experimentally I have done so by adding a switch at line 60 of FormsWebDialog.GetAuthenticationResponseValues. The switcher also requires a new boolean parameter on the method.
Thoughts?

How to Authenticate in ASP.NET with Business Account using SDK

Do you have a guide on how to do this?

I tried to use the simple authentication below
var oneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
clientId,
returnUrl,
scopes);

await oneDriveClient.AuthenticateAsync();

I noticed that after creating the client, the ClientType is set as "Consumer"

I read in this Issue
#23

That I might to create a class that implements IWebAuthenticationUi
Do you have a sample for that?

many thanks
Philip

authentication_failed

Cant login, error message:
An error occurred during active directory authentication. Error: authentication_failed. Description: Stream does not support seeking.

AuthenticationFailure after upgraded from 1.1.20 to 1.1.29

I think there is some authentication issue in 1.1.29. Everything seems to work well until I call
client.Drive.Request().GetAsync() which throws AuthenticationFailure. I could not find release notes to check if this is related to some planned change. I reverted back to 1.1.20 which solved the issue. Code sample to reproduce the issue:
var client = OneDriveClientExtensions.GetUniversalClient("wl.signin", "wl.offline_access", "onedrive.readwrite", "onedrive.appfolder");
var session = await client.AuthenticateAsync();
var drive = await client.Drive.Request().GetAsync();

Authenticate without any user interaction in C# windows forms

How do get authenticated without any user interaction from C# windows forms? Tried below code, but its asking for the confirmation.

this.oneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
FormBrowser.MsaClientId,
FormBrowser.MsaReturnUrl,
FormBrowser.Scopes,
webAuthenticationUi: new FormsWebAuthenticationUi());

Can't get shared collections

One user shared with me a folder with a couple files inside.
I have added the folder to my OneDrive.
I can see the folder listed in it's parent's IChildrenCollectionPage, but cannot retrieve the items inside of it. The next code returns an empty IChildrenCollectionPage:
await this.OneDriveClient.Drive.Items[folderId].Children.Request().GetAsync();

Is it possible get the files in that folder?

Xamarin Android Project not buildable with onedrive sdk referenced

I use MVVM Cross in a project which includes a UWP, Android and IOS Project.
When add the onedrive sdk to the portable core I can no longer build the android project. The following error is thrown:

Severity    Code    Description Project File    Line    Source
Error   CS0246  The type or namespace name 'IOneDriveClient' could not be found (are you  missing a using directive or an assembly reference?)  MoneyManager.Core        C:\Users\padruttn\Documents\GitHub\MoneyManager\Src\MoneyManager.Core\Manager\OneDriveManager.cs   31  Build

As far as I know xamarin should be supported by the c# sdk or did I get that wrong?

Uploading Content results in zero length item

This example is from a Windows 10 Mobile UWP app that is attempting to create/update a small XML file in the OneDrive root. The result is no errors and a zero length file in OneDrive. It doesn't matter if the file exists or not. The stream definitely has data when PutAsync is executed. I also tried using XmlSerializer. Any Ideas on the issue?

async private void Save_Click(object sender, RoutedEventArgs e)
        {
            string OneDrive_XMLFILENAME = "a_file_name.xml";
            string[] scopes = { "wl.signin", "wl.offline_access", "onedrive.readwrite" };
            var oneDriveClient = OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator(scopes);
            await oneDriveClient.AuthenticateAsync();

            // serialize card data then create new OneDrive Item (XML File)
            var serializer = new DataContractSerializer(typeof(List<Card>));

            using (System.IO.Stream contentStream = new System.IO.MemoryStream())
            {
                serializer.WriteObject(contentStream, App.CardList);
                await contentStream.FlushAsync();
                var uploadedItem = await oneDriveClient
                                             .Drive
                                             .Root
                                             .ItemWithPath(OneDrive_XMLFILENAME)
                                             .Content
                                             .Request()
                                             .PutAsync<Item>(contentStream);

            }
        }

requesturi missing access_token

i would expect the command

OneDrive.Drive.Items["id"].Content.Request().GetHttpRequestMessage().RequestUri

include the access_token but thats not the case, it "only" provides the full uri but thats senseless without the access_token as we need the access_token to fullfill the request...

i try to connect a mediaelement to the music stored on onedrive

 MediaElement.Source = OneDrive.Drive.Items["id"].Content.Request().GetHttpRequestMessage().RequestUri;

because the access_token is missing i would need to extend that command to include

OneDrive.AuthenticationProvider.CurrentAccountSession.AccessToken

to build a working url but why should i need to build an uri outside of the sdk

or is there a better way to connect a mediaelement with music located on onedrive by use of the onedrive csharp sdk?

Pagination - Bug

Hi,

The following pagination code is not working. The second call will not get the next set of items instead it returns the same set of items as the first one.

var page = await oneDriveClient.Drive.Items[item.Id].Children.Request().Top(100).Select("name").GetAsync();
var nextPage = await page.NextPageRequest.GetAsync();

By inspecting the fiddler log, The URL generated for the second request is strange,
URL for the first request :
https://abccompany-my.sharepoint.com/_api/v2.0/me/drive/items/01LZHNAUECBE37DBUFN5GLCRHQNCZVXBUX/children?top=100&select=name

URL for the second request :
https://abccompany-my.sharepoint.com/_api/v2.0/me/drive/items('01LZHNAUECBE37DBUFN5GLCRHQNCZVXBUX')/children?$skiptoken=Paged=TRUE&p_SortBehavior=0&p_FileRef=personal%2fprakash_abccompany_onmicrosoft_com%2fDocuments%2fLots%20Of%20Data%2fText%20Data-19.txt&p_ID=25&RootFolder=%2fpersonal%2fprakash_abccompany_onmicrosoft_com%2fDocuments%2fLots%20Of%20Data&$top=100&$select=name

The second request resulted in same set of results as the first one.

FYI
Response for the first Request
As per the one drive for business API documentation, The response will have a @odata.nextLink if there are large number of items then the requested items. Below is the @odata.nextlink,

https://abccompany-my.sharepoint.com/_api/v2.0/me/drive/items('01LZHNAUECBE37DBUFN5GLCRHQNCZVXBUX')/children?%24skiptoken=Paged%3dTRUE%26p_SortBehavior%3d0%26p_FileRef%3dpersonal%252fprakash%255fabccompany%255fonmicrosoft%255fcom%252fDocuments%252fLots%2520Of%2520Data%252fText%2520Data%252d19%252etxt%26p_ID%3d25%26RootFolder%3d%252fpersonal%252fprakash%255fabccompany%255fonmicrosoft%255fcom%252fDocuments%252fLots%2520Of%2520Data&%24top=100&%24select=name

There is difference in the query string. The "@odata.nextLink" have only three "&" indicating three query string parameters. But the sdk generated url contains six "&" which resulted in six query string parameters.

The first skiptoken querystring somewhat missing all of it's token because of that thats why the second request returns the same set of results.

Looks like there is a bug in the BaseRequest.InitializeUrl(),
var queryOptions = queryString.Split('&').Select( queryValue => { var segments = queryValue.Split('='); return new QueryOption( WebUtility.UrlDecode(segments[0]), segments.Length > 1 ? WebUtility.UrlDecode(segments[1]) : string.Empty); });
The UrlDecode of segments[1] resulted in adding some additional query string params which resulted in this issue. Once I removed the WebUtility.UrlDecode() for the segments[1] I am able to get the right results. I am not sure whether it is right fix or not but this information may helpful to you.

Is there any workaround for this?

Bad Exception Error

When uploading a file, I used to encounter an Error:
{System.UriFormatException: Invalid URI: The format of the URI could not be determined. at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind) at System.Uri..ctor(String uriString) at Microsoft.OneDrive.Sdk.BaseRequest.InitializeUrl(String requestUrl) at Microsoft.OneDrive.Sdk.BaseRequest..ctor(String requestUrl, IBaseClient client, IEnumerable' 1 options) at Microsoft.OneDrive.Sdk.ItemContentRequestBuilder.Request() at OneDriveClass.myOneDrive.<uploadFile>d__8.MoveNext()}

This was a System.Exception and not a Microsoft.OneDrive.Sdk.OneDriveException. The issue was, that I forgot to check, if I'm authenticated to upload:

if (!this.oneDriveClient.IsAuthenticated) { await this.oneDriveClient.AuthenticateAsync(); }

Adding these lines prevented the error.

Maybe you can make this an Error, that get's triggered in Microsoft.OneDrive.Sdk.OneDriveException when one forgot to authenticate and give the Exception a better description (so I as a dev know, what's really wrong).

Cached Account Session

I'm developing a UWP app and I'm using OneDriveClientExtensions.GetAuthenticatedClientUsingWebAuthenticationBroker to log in. I am able to login successfully and log out as well. Although, let's say I login, the app closes completely and I relaunch the app. Now I no longer have the previous account session to log out. If I try calling "GetAuthenticatedClientUsingWebAuthenticationBroker" again, the "Connecting to service" dialog comes up again to login which is not what I would expect since I have a previous session. I've seen the function "GetSilentlyAuthenticatedMicrosoftAccountClient" but I don't receive a refresh token back from the initial login. Any suggestions for this use case?

Api returning wrong lastModifiedDateTime value

While querying for the lastModifiedDateTime, the api returns a date time offset that is 1 hour behind the actual last modified time.

Steps to reproduce:

  1. Launch your internet browser and navigate to your one drive portal.
  2. Select a file and notice its time stamp in one drive site.
  3. Launch the OneDriveApiBrowser.
  4. Select the same file and notice the time stamp.

Expected Result:
Both step 2 and step 4 should return the same values.

Actual Result:
Result of step 2 != step 4. Step 2 always returns the value as actual - TimeSpan.FromHours(1).
api-timestamp
one-drive-timestamp

Exception Handling

The only error message returned is "Exception of type 'Microsoft.OneDrive.Sdk.OneDriveException' was thrown.". No detail is given as per why the request raised this exception which makes it hard to handle the exceptions on the client side. The exceptions raised need more details.

Folder creation

Hello! How can I create a folder in root via Onedrive SDK in uwp app?
I tried in different ways but I did not succeed.
Thank you

OneDrive for Business Support

Is there anyway to utilize this SDK for OneDrive for Business? The authentication seems to assume consumer OneDrive, is there a way to way to change this behavior so I can login to a business account? If not, can authentication be done separately but still use the SDK for the API calls afterwards?

SilentlyAuthenticatedMicrosoftAccountClient can not sign out

If you create a client with an account session from the cache (SilentlyAuthenticatedMicrosoftAccountClient) the CanSignOut is not set to true, therefore the client can't revoke the access.

This can be resolved by adding at line 193 in AuthenticationProvider.ProcessCachedAccountSessionAsync the following code:

accountSession.CanSignOut = true;

CredentialsCache, System.Collections.Concurrent and Windows Phone 8.1?

I noticed references to using the SDK for Phone 8.1. In my attempt to mock up a basic prototype of this, I noticed the use of System.Collections.Concurrent, which isn't available in the Windows Phone 8.1 runtime as far as I can tell. Even a simple repro like var cache = new CredentialsCache(); within a WP8.1 project results in:

Additional information: Could not load file or assembly 'System.Collections.Concurrent, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

Is this an issue in the implementation of the SDK or something that can be resolved within my project?

Can't authenticate, UserCancel always returned....

I've been following the instructions from https://github.com/OneDrive/onedrive-sdk-csharp/blob/master/docs/auth.md

I do have my app registered to the store with his proper Client id. I've been trying those three examples:

Attempt #1
var client = OneDriveClientExtensions.GetUniversalClient(this.oneDriveScopes) as OneDriveClient;

Attempt #2
IWebAuthenticationUi webAuthenticationUi = new WebAuthenticationBrokerWebAuthenticationUi();
var client = OneDriveClient.GetMicrosoftAccountClient(
appId: ClientId,
returnUrl: "https://login.live.com/oauth20_desktop.srf",
scopes: oneDriveScopes ,
clientSecret: ClientSecret,
credentialCache: null,
httpProvider: null,
serviceInfoProvider: new ServiceInfoProvider(webAuthenticationUi));
Atempt #3
var client = await OneDriveClientExtensions.GetAuthenticatedClientUsingWebAuthenticationBroker(appId: ClientId, scopes: oneDriveScopes);
try
{
await client.AuthenticateAsync();
}

All those attempts fails at : the call to
result = await this.AuthenticateAsync(requestUri, callbackUri, WebAuthenticationOptions.None);

inside
C:\development\onedrive-sdk-csharp-master\src\OneDriveSdk.WinStore\Authentication\WebAuthenticationBrokerWebAuthenticationUi.cs#Line 61

The response status is always ResponseStatus : UserCancel.

What gives?

Automatic handling of backoff?

Does the API automatically handle backoff in case the OneDrive service feels it's being hit too hard? If not, is there any plan to?

Large file download - Performance Issue

Hi,
The one drive api is really good and easy to use. And it has lot of customization points where I can easily change some of the behavior.

I am trying to download a large file > 80MB from one drive using the test application. The process memory is shooting up.

Is there a way to fix this?

Note:
Upon further investigation, the call "this.oneDriveClient.Drive.Items[item.Id]. Content.Request().GetAsync() " buffers the file content as MemoryStream. Which was the reason for this issue.

The GetAsync() internally uses HttpClient.SendAsync() which has overload to specify HttpCompletionOption where the download buffering can be skipped. Unfortunately I really don't know how to override that behavior.

WebAuthenticationUI

I tried to implement an WebAuthenticationUI for Android using Xamarin Auth to display the browser with the login. I can login and get the IDictionary<string, string> in the response (who also contains an entry with the access token). But on the further processing I get this error: "Failed to retrieve a valid authentication token for the user."

Any idea what’s this is causing?

StackTrace:

at Microsoft.OneDrive.Sdk.AuthenticationProvider+<AuthenticateAsync>d__10.MoveNext () [0x001eb] in <filename unknown>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:201 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:170 
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:142 
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:372 
  at Microsoft.OneDrive.Sdk.BaseClient+<AuthenticateAsync>d__24.MoveNext () [0x00130] in <filename unknown>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:201 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:170 
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:142 
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:372 
  at MoneyManager.Droid.OneDriveAuthenticator+<LoginAsync>d__6.MoveNext () [0x00083] in C:\Users\ninop\Documents\GitHub\MoneyManager\Src\MoneyManager.Droid\Src\OneDriveAuthenticator.cs:32 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:201 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:170 
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:142 
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:372 
  at MoneyManager.Core.OneDriveService+<Login>d__11.MoveNext () [0x00030] in C:\Users\ninop\Documents\GitHub\MoneyManager\Src\MoneyManager.Core\OneDriveService.cs:30 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:201 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:170 
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:142 
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in /Users/builder/data/lanes/2512/d3008455/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:124 
  at MoneyManager.Core.ViewModels.BackupViewModel+<Login>d__16.MoveNext () [0x0005b] in C:\Users\ninop\Documents\GitHub\MoneyManager\Src\MoneyManager.Core\ViewModels\BackupViewModel.cs:88 

Add support for Task<T>.Result usage

Currently the SDK doesn't support the use of the Result property of an async Task<T>.
When used it results to a deadlock.
Consider the use of ConfigureAwait(false) where applicable (mainly everywhere).

P.S.: When I used ConfigureAwait(false) in all steps of a GetAsync() call it worked. I know this isn't an easy undertaking but it should be done eventually.

Justification: https://youtu.be/H4EmfpsYcfs?t=3966

OneDriveSdk assembly strong name issue

An unhandled exception of type 'System.IO.FileLoadException' occurred in OneDriveSdkTest.exe

Additional information: could Not load file or Assembly "OneDriveSdk, Version=1.1.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" or one of its dependencies. Failure to verify that strong name. (Exception from HRESULT: 0x8013141A)

Windows 7
.NET 4.5.2
Visual Studio 2013

Can't upload a file

Hello, i'm creating a aplication that syncs some data between devices, but i don't know how to make a upload of the file, cause i always get the NullReferenceException. Code below(Code edited, but still don't work):

string[] lines = { selecaoBlock.Text };
string appFolder = ApplicationData.Current.LocalFolder.Path;
System.IO.File.WriteAllLines(@appfolder + "\Shared.txt", lines);
Stream file = System.IO.File.Open(@appfolder + "\Shared.txt", FileMode.Open);
using (file)
{
var item = await OneDriveClient
.Drive
.Special
.AppRoot
.Children["Shared.txt"]
.Content
.Request()
.PutAsync(file);
}

Unable to authenticate from ASP.Net (OneDrive Personal) using token flow

I am using below code to get authenticated for OneDrive Personal from ASP.NET application.

Task oneDriveClient = OD.OneDriveClient.GetSilentlyAuthenticatedMicrosoftAccountClient(
"{client id}",
"https://login.live.com/oauth20_desktop.srf",
new[] { "onedrive.readwrite" },
"{client secret}",
serviceInfoProvider: new OD.ServiceInfoProvider(new AuthenticationProvider("{client secret}"))
);

        IOneDriveClient client = oneDriveClient.Result;
        AccountSession session = await client.AuthenticateAsync();

--> AccessToken comes as NULL here. What could be the issue here?


public class AuthenticationProvider : OD.IAuthenticationProvider
{
OD.AccountSession m_session;

    public AuthenticationProvider(string refreshToken)
    {
        m_session = new OD.AccountSession()
        {  
            RefreshToken = refreshToken,
            ExpiresOnUtc = DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc),
            ClientId = "{client id}",
            Scopes = new[] { "onedrive.readwrite" },
            AccountType = OD.AccountType.MicrosoftAccount
        };
    }

    public OD.AccountSession CurrentAccountSession
    {
        get
        {
            return m_session;
        }

        set
        {
            m_session = value;
        }
    }

    public Task AppendAuthHeaderAsync(HttpRequestMessage request)
    {
        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(OD.Constants.Headers.Bearer, m_session.AccessToken);
        return Task.WhenAll(); // == Task.CompletedTask
    }

    public Task<OD.AccountSession> AuthenticateAsync()
    {
        return Task<OD.AccountSession>.FromResult(m_session);
    }

    public Task SignOutAsync()
    {
        throw new NotImplementedException();
    }
}

Request to support an OData $skip option to support virtual data lists on clients

Though the current server paging capability can support an incremental loading capability, this doesn't support at all the case of user quickly scrolling through their photos or data in a virtual list, because scrolling can be done so quickly that any incremental loading queue can get saturated.

Random access data virtualization is what is required to support the quick scrolling scenario. Unfortunately, it looks as if the SDK and the OneDrive API don't support the OData query options (namely $skip) which would enable that.

Hopefully $skip is in the near range plan, so that we'll be able to create awesome third party apps that use the OneDrive API.
The concepts I'm describing can be found here:
https://msdn.microsoft.com/en-us/library/windows/apps/mt574120.aspx

To illustrate, let's say that a list or grid is used to show picture thumbnails. We start with a query to get the camera roll by date descending, but we only get just a few of the thousands of pictures' metadata with the first call. In fact, to remain responsive, we may want the call to get even fewer than 100 items.

https://api.onedrive.com/v1.0/drives('me')/items('cameraroll_id')/children?$top=100&$orderby=lastModifiedDateTime%20desc

Now the user scrolls very quickly to item 200, but we're still loading the previous items into the control. This might be reported to the app by the IItemsRangeInfo interface for a list and overriding the RangesChanged method..

What we need is this:

https://api.onedrive.com/v1.0/drives('me')/items('cameraroll_id')/children?$top=100&$orderby=lastModifiedDateTime%20desc&skip=200

If there is a way to enable this scenario, please let me know.
-THANKS
-e

How to authenticate in an ASP.NET app?

How to authenticate in an ASP.NET app with OneDrive API?
I tried to use Live SDK for ASP.NET to discover it's not working anymore, and that I should use the new OneDrive API.
A bit confusing, any help would be great...
For authentication, I know I could use JavaScript like in the sample, but it would be great to have .NET support for ASP.NET, as I intend to upload / download files to/from OneDrive.

Another question:
In ASP.NET I can use OWIN's built in MicrosoftAccountAuthenticationExtensions::UseMicrosoftAccountAuthentication
Would it be possible to use this identity to login to OneDrive and upload\download files?
It would be useful to use the ASP.NET identity support which already manages and saves the authentication in database.

Thanks!

View changes for a OneDrive Item and its children

reference https://dev.onedrive.com/items/view_delta.htm
based on available documentation its unclear how we can/should build the request ?
for var r = Client.Drive.Special["Music"].Delta("latest").Request().GetAsync();
the response is: Id = 89, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"

i assume we have to use "latest" as token value for the initial request... and @delta.token for every following sync ...

Upload to SpecialFolder

Hi,
I can upload files successfully via
item = await oneDriveClient.Drive.Root.ItemWithPath(itemPath).Content.Request().PutAsync<Item>(memStream);
to the OneDrive directory. However, when I want to upload to SpecialFolder Approot both:
var specialFolder = await this.oneDriveClient.Drive.Special.AppRoot.Request().GetAsync(); if(specialFolder != null) { item = await oneDriveClient.Drive.Items[specialFolder.Id].Content.Request().PutAsync<Item>(memStream); }
and
item = await oneDriveClient.Drive.Special.AppRoot.ItemWithPath(itemPath).Content.Request().PutAsync<Item>(memStream);
fail.
I do get an Error saying "Exception of type 'Microsoft.OneDrive.Sdk.OneDriveException' was thrown." with Stacktrace:

" at Microsoft.OneDrive.Sdk.HttpProvider.d__16.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.OneDrive.Sdk.HttpProvider.d__14.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.OneDrive.Sdk.BaseRequest.d__29.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.OneDrive.Sdk.BaseRequest.d__271.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()\r\n at OneDriveClass.myOneDrive.d__8`1.MoveNext()"

Authentication using Refresh Token

Hello. It is possible to authenticate in client by using refresh token, taken in previous session? And if it possible, please write an example how to authenticate. Thank you in advance.

Cancellation support?

Unless I'm missing something, there doesn't seem to be any way to cancel a request to the server. It would be better if all methods that call the server accepted a CancellationToken.

'Sign in with different User' option

Hello world,

Have been using the C# Winforms SDK to create an Uploader and have found issue with cached credentials. When I log in with user X, it seems IE will cache that in some live login cookies so each subsequent run of the application will load user X and only has options on consent screen for "Yes or No" to allow user X. Id like the option at this point to 'select a different user', said link could perhaps perform the logout operation for the cached user.

Many thanks in advance!

Mitch.

Fail to request item content into stream after updating to 1.1.29

Same code works with 1.1.20 but throws exception on 1.1.29. syncFileItem.Id can be fetched correctly. Is there API change or is this a bug?

    var contentStream = await oneDriveClient.Drive
                .Items[syncFileItem.Id]
                .Content
                .Request()
                .GetAsync();

Exception:
Message "The request is not supported. (Exception from HRESULT: 0x80070032)" string
StackTrace " at Windows.Security.Authentication.OnlineId.OnlineIdAuthenticator.AuthenticateUserAsync(OnlineIdServiceTicketRequest request)\r\n at Microsoft.OneDrive.Sdk.OnlineIdAuthenticationProvider.d__4.MoveNext()" string

Authentication related code:

        return OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator(new string[] {
            "wl.signin", "onedrive.appfolder", "onedrive.readwrite"
        });

Please help take a look.

Authentication Question for Single Sign On

I am currently developing a cross-platform app using Xamarin, that targets Windows Phone 8.1, Android, and iOS. I am using a PCL to handle all of the OneDrive specific code, and have an object in each platform project that acts as an adapter for the OneDriveClient.

In my WP project, I am able to sign in using this client:

_client = OneDriveClient.GetMicrosoftAccountClient(
    appId: Resources.MicrosoftOneDriveClientId,
    returnUrl: Resources.MicrosoftOneDriveReturnUrl,
    scopes: new[] {"wl.signin", "wl.offline_access", "onedrive.readwrite"},
    clientSecret: Resources.MicrosoftOneDriveClientSecret,
    credentialCache: credentialCache,
    httpProvider: null,
    serviceInfoProvider: new ServiceInfoProvider(webAuthenticationUi));

I am instantiating credentialCache as follows:

CredentialCache credentialCache;
if (!_resourceService.TryLoadOneDriveCredentialCache(out credentialCache))
{
    credentialCache = new CredentialCache();
}

The TryLoad method reads the byte[] from CredentialCache::GetCacheBlob() that I have written to app resources, after the CredentialCache::AfterAccess delegate fires. In app resources it would look like

{ OneDriveCredentialCacheKey, byte[] }

This all works great, and after calling _client.AuthenticateAsync() I am able to query my OneDrive drive. However, on subsequent sessions of the app, when I call AuthenticateAsync() with the loaded credentialCache, I am still being presented with the webAuthenticationUi.

I assume this comes down to how I'm instantiating the OneDriveClient or the CredentialCache. Is there a different signature I should use when I have a valid CredentialCache vs. not? Do I need to implement any of the other Interfaces and use them instead of the defaults?

My goal is to enable single sign on across the different platforms. Thanks for any feedback / pointers in the right direction.

No examples for large file upload

The previous project (onedrive-explorer-win) had support in its API for large file upload, and the example applications had the ability to use this support.

However, in this newer version of the API, I see neither documentation nor examples that cover the process of doing a large file upload (as described here).

The closest I've seen is a call wrapping the CreateSession request. However, I have not seen anything that covers the actual uploading of file contents, nor a clean way of wrapping up the whole process.

How to get link to see the original image

I want upload an Image and get a link which never expires to access the original image (this feature is available in Google Drive). Any one with this link should be able to see the original image.

Background Task Authentication

Hello.
I'm writing a Windows 10 UWP and I want to authenticate the user into background task to sync some small files.

In foreground I do this and it works:
var oneDriveClient = await OneDriveClientExtensions.GetAuthenticatedClientUsingOnlineIdAuthenticator(scopes);

If I try to do it inside the Background task it doesn't works.

Thanks for your help

Can't sign out acc

When I call OneDriveClient.SignOutAsync(); but OneDriveClient.IsAuthenticated value is still true. So how to sign out account

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.