Giter Site home page Giter Site logo

onedrive-sample-apibrowser-dotnet's Introduction

page_type products languages extensions
sample
office-onedrive
ms-graph
csharp
contentType technologies services createdDate
samples
Microsoft Graph
OneDrive
7/6/2016 11:47:49 AM

OneDrive API Browser Sample

The OneDriveAPIBrowser sample is a Windows Forms app sample that uses the Microsoft Graph .NET Client Library for C#/.NET. In this sample, users can browse files and folders that are stored on OneDrive, and view metadata.

Register and configure the application

  1. Sign into the App Registration Portal using either your personal or work or school account.
  2. Select Add an app.
  3. Enter a name for the app, and select Create application. The registration page displays, listing the properties of your app.
  4. Under Platforms, select Add platform.
  5. Select Mobile application.
  6. Copy the Client Id (App Id) value to the clipboard. You'll need to use it in the sample app. The app id is a unique identifier for your app.
  7. Select Save.

Set up

  1. Install Visual Studio and all available updates, if you don't already have it.
  2. Download the OneDriveAPIBrowser sample from GitHub or create your own fork of the repository.
  3. From Visual Studio, open the OneDriveApiBrowser.sln solution.
  4. Go to the OneDriveApiBrowser project in the solution and view the code for FormBrowser.cs.
  5. Configure the sample to use the Client Id (App Id) that you registered by making it the value of the MsaClientId variable:
        private const string MsaClientId = "Insert your client ID here";

Run the sample

In Visual Studio, select the sample OneDriveAPIBrowser from the Startup project list, and then press F5 or click Start to run the sample. The sample looks like this:

OneDriveAPIBrowser sample

Sign-in

When the OneDrive API Browser app opens, choose File | Sign in... to sign in to a personal OneDrive account or to a business OneDrive account. Once you have signed in to your Microsoft account, a dialog will appear, asking for permissions to access OneDrive files.

Let this app access your info

Click Yes.

After sign-in

Your OneDrive items will appear on the left pane, with each item represented by a thumbnail. On the right pane, the selected item's properties are displayed. You can choose how the item properties are displayed, whether its JSON or Tree View.

To upload a file, choose Upload from the menu and then choose Simple - Path-based to upload by path, or Simple - ID-based to upload by item id.

To download a file, select a file, and then choose Download from the menu.

API features

Retrieving an authenticated client

This sample gets a Microsoft Graph GraphServiceClient instance and signs in the user using the GetAuthenticatedClient method in the AuthenticationHelper.cs file.

public static string[] Scopes = { "Files.ReadWrite.All" };
...
        public static GraphServiceClient GetAuthenticatedClient()
        {
            if (graphClient == null)
            {
                // Create Microsoft Graph client.
                try
                {
                    graphClient = new GraphServiceClient(
                        "https://graph.microsoft.com/v1.0",
                        new DelegateAuthenticationProvider(
                            async (requestMessage) =>
                            {
                                var token = await GetTokenForUserAsync();
                                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
                                // This header has been added to identify our sample in the Microsoft Graph service.  If extracting this code for your project please remove.
                                requestMessage.Headers.Add("SampleID", "uwp-csharp-apibrowser-sample");

                            }));
                    return graphClient;
                }

                catch (Exception ex)
                {
                    Debug.WriteLine("Could not create a graph client: " + ex.Message);
                }
            }

            return graphClient;
        } 
...

The AuthenticationHelper.cs file also provides a SignOutAsync method to easily sign the user out:

        public static void SignOut()
        {
            foreach (var user in IdentityClientApp.Users)
            {
                user.SignOut();
            }
            graphClient = null;
            TokenForUser = null;

        }

Get item properties

This sample demonstrates how to get an item's properties, by calling the GetAsync method of the GraphServiceClient object:

folder = await this.graphClient.Drive.Root.Request().Expand(expandValue).GetAsync();

Simple item upload

This sample makes use of Microsoft Graph's ability to upload items by path or by id. Here, you upload an item by path:

// Since the ItemWithPath method is available only at Drive.Root, we need to strip
// /drive/root: (12 characters) from the parent path string.
string folderPath = targetFolder.ParentReference == null
	? ""
	: targetFolder.ParentReference.Path.Remove(0, 12) + "/" + Uri.EscapeUriString(targetFolder.Name);
	var uploadPath = folderPath + "/" + Uri.EscapeUriString(System.IO.Path.GetFileName(filename)); 

// Use the Microsoft Graph SDK to upload the item by path.
var uploadedItem =
	await
	this.graphClient.Drive.Root.ItemWithPath(uploadPath).Content.Request().PutAsync<DriveItem>(stream); 

This example shows how to upload an item by id:

var uploadedItem =
	await
	this.graphClient.Drive.Items[targetFolder.Id].ItemWithPath(filename).Content.Request()
                                    .PutAsync<DriveItem>(stream); 

More resources

You can continue to explore this sample and the rest of its features by using GitHub or Visual Studio. To view a Windows Universal app sample that uses the Microsoft Graph SDK for CSharp/.NET, see OneDrivePhotoBrowser. Make sure to also check out the Microsoft Graph API's official documentation at https://developer.microsoft.com/en-us/graph/.

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-sample-apibrowser-dotnet's People

Contributors

cdmayer avatar ginach avatar nokafor avatar

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.