{"id":32819,"date":"2017-08-14T12:33:52","date_gmt":"2017-08-14T19:33:52","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=32819"},"modified":"2017-08-14T12:33:52","modified_gmt":"2017-08-14T19:33:52","slug":"adding-storage-mobile-apps-onedrive-business","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/adding-storage-mobile-apps-onedrive-business\/","title":{"rendered":"Adding Storage to Mobile Apps with OneDrive for Business"},"content":{"rendered":"<p>\t\t\t\tEvery app needs storage, whether it&#8217;s for storing a collection of the same type of records in Azure Mobile Service with <a href=\"https:\/\/blog.xamarin.com\/getting-started-azure-mobile-apps-easy-tables\/\" target=\"_blank\">Easy Tables<\/a>,\u00a0or a SQL Database exposed via <a href=\"https:\/\/blog.xamarin.com\/add-a-backend-to-your-app-in-10-minutes\/\" target=\"_blank\">Web Services<\/a>. When the data is unstructured, NoSQL with Azure DocumentDB can be used. For scalability and high availability, <a href=\"https:\/\/blog.xamarin.com\/going-global-xamarin-azure-cosmos-db\/\" target=\"_blank\">Azure CosmosDb<\/a> can be used in both the cases. In enterprise situations, however, where different types of documents need to be stored and shared with colleagues, the best solution is OneDrive for Business. OneDrive for Business is part of Office 365 and provides easy access across multiple Office 365 services. We learned previously how to <a href=\"https:\/\/blog.xamarin.com\/add-storage-to-your-apps-with-office-365\/\" target=\"_blank\">integrate OneDrive for Business<\/a> in mobile apps developed using Xamarin.<\/p>\n<p>Since then, there have been changes to APIs and SDKs that have made this integration simpler. We&#8217;ll take a look at those changes in this blog post. You can find the repo for this post on <a href=\"https:\/\/github.com\/mayur-tendulkar\/\" target=\"_blank\">GitHub<\/a>.<\/p>\n<h2>Step 1: App Registration<\/h2>\n<p>To integrate OneDrive for Business with mobile apps, the app needs to be registered with the Azure Active Directory service. This will authenticate and authorize users while providing access to the resources. The process is the same as registering any other app with Azure Active Directory.<\/p>\n<p>Visit <a href=\"https:\/\/apps.dev.microsoft.com\/\" target=\"_blank\">https:\/\/apps.dev.microsoft.com\/<\/a> and click on <em>Add an app<\/em> to get started. Name your app and continue, making sure you note the Application Id. Click on <em>Add Platorm<\/em> and select <em>Native Application<\/em>.<\/p>\n<p>Ensure you define Delegated Permissions for the application to be able to access files stored on OneDrive for Business:<\/p>\n<ul>\n<li><code>Files.Read<\/code><\/li>\n<li><code>Files.Read.All<\/code><\/li>\n<li><code>Files.Read.Selected<\/code><\/li>\n<li><code>Files.ReadWrite<\/code><\/li>\n<li><code>Files.ReadWrite.All<\/code><\/li>\n<li><code>User.Read<\/code><\/li>\n<\/ul>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-32822\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/xamarin-onedrive-app-permissions-02.png\" alt=\"\" width=\"750\" \/><\/p>\n<h2>Step 2: Calling APIs<\/h2>\n<p>Once the app is registered, create a Blank Xamarin.Forms application with the PCL code sharing strategy. Make sure that the profile selected for PCL is set to <em>Profile7<\/em> by right-clicking the PCL project and selecting Properties &gt; Build &gt; General. Add two NuGet packages: <code>Microsoft.Identity.Client<\/code> and <code>Microsoft.Graph<\/code>.<\/p>\n<p>Use the Microsoft Authentication Library (MSAL) to authenticate the user in the code-behind in <code>App.xaml.cs<\/code>.<\/p>\n<pre class=\"EnlighterJSRAW\">using Microsoft.Identity.Client;\n...\npublic static PublicClientApplication IdentityClientApp = null;\npublic static string ClientID = \"4f91166f-c946-438f-8d07-33792251026d\";\npublic static string[] Scopes = { \"User.Read\", \"User.ReadBasic.All\", \"Files.Read\", \"Files.Read.All\", \"Files.ReadWrite\", \"Files.ReadWrite.All\" };\npublic static UIParent UiParent = null;\npublic App()\n{\n   InitializeComponent();\n   MainPage = new XamarinDrive.MainPage();\n   IdentityClientApp = new PublicClientApplication(ClientID);\n   MainPage = new NavigationPage(new MainPage());\n}<\/pre>\n<p>After the authentication process is complete, create a <code>GraphServiceClient<\/code> object which will be responsible for further requests in the code-behind for <code>MainPage.xaml.cs<\/code>.<\/p>\n<pre class=\"EnlighterJSRAW\">using Microsoft.Graph;\nusing Microsoft.Identity.Client;\n...\nprivate async Task CreateGraphClientAsync()\n{\n   try {\n      Client = new GraphServiceClient(\"https:\/\/graph.microsoft.com\/v1.0\",\n               new DelegateAuthenticationProvider(\n               async (requestMessage) =&gt; {\n                         var tokenRequest = await App.IdentityClientApp.AcquireTokenAsync(App.Scopes, App.UiParent).ConfigureAwait(false);\n                         requestMessage.Headers.Authorization = new AuthenticationHeaderValue(\"bearer\", tokenRequest.AccessToken);\n                }));\n                Me = await Client.Me.Request().GetAsync();\n                Username.Text = $\"Welcome {((User)Me).DisplayName}\";\n                return true;\n       }\n       catch (MsalException ex){\n            await DisplayAlert(\"Error\", ex.Message, \"OK\", \"Cancel\");\n            return false;\n       }\n}<\/pre>\n<p>Using this <code>GraphServiceClient<\/code> and <code>Graph<\/code> Model, traverse through the Drive and get a list of items (files and folders) within the drive. Assign this list of items to the listview control in <code>ListPage.xaml.cs<\/code>.<\/p>\n<pre class=\"EnlighterJSRAW\">using Microsoft.Graph;\n...\nvar client = new GraphServiceClient(\"https:\/\/graph.microsoft.com\/v1.0\",\n                new DelegateAuthenticationProvider(\n                async (requestMessage) =&gt;\n                {\n                   var tokenRequest = await App.IdentityClientApp.AcquireTokenSilentAsync(App.Scopes, App.IdentityClientApp.Users.FirstOrDefault());\n                   requestMessage.Headers.Authorization = new AuthenticationHeaderValue(\"bearer\", tokenRequest.AccessToken);\n                }));\nvar data = await client.Me.Drive.Root.Children.Request().GetAsync();\nvar list = data.ToList();\nFileList.ItemsSource = list;<\/pre>\n<p>This list of DriveItems\u00a0will then be displayed on <code>ListPage<\/code> using the binding with <code>ListView<\/code>. When a user clicks on an item inside List, the file will be opened as requested. This can be achieved with the <code>OnItemTapped<\/code> event.<\/p>\n<pre class=\"EnlighterJSRAW\">var item = ((DriveItem) e.Item);\n   if (item.Folder != null)\n      await DisplayAlert(\"Type\", \"Selected Item is a Folder!\", \"Ok\");\n   else\n      Xamarin.Forms.Device.OpenUri(new Uri(item.WebUrl));<\/pre>\n<p>Just like any Xamarin.Forms app is required to implement platform-specific functionality differently, follow the guide for each individual platform to implement authentication from <a href=\"https:\/\/blog.xamarin.com\/enterprise-apps-made-easy-updated-libraries-apis\/\" target=\"_blank\">here<\/a>.<\/p>\n<h2>Step 3: Running the App<\/h2>\n<p>Run the app on a device or simulator and log in with your Office 365 credentials. The app will ask for appropriate permissions. Once those permissions are granted, the app will display the list of files.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-32830\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/xamarin-onedrive-app-running-03.gif\" alt=\"\" width=\"750\" \/><\/p>\n<h2>Wrapping Up<\/h2>\n<p>OneDrive for Business, which is part of Office 365, allows users to store, share, and collaborate with different types of documents.\u00a0Using Microsoft Graph Client Libraries and Microsoft Authentication Library, it&#8217;s easy to integrate various Office 365 services such as OneDrive. As usual, you can find the sample used in this blog post on <a href=\"https:\/\/github.com\/mayur-tendulkar\/\" target=\"_blank\">GitHub<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Every app needs storage, whether it&#8217;s for storing a collection of the same type of records in Azure Mobile Service with Easy Tables,\u00a0or a SQL Database exposed via Web Services. When the data is unstructured, NoSQL with Azure DocumentDB can be used. For scalability and high availability, Azure CosmosDb can be used in both the [&hellip;]<\/p>\n","protected":false},"author":549,"featured_media":39167,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[4,16],"class_list":["post-32819","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-xamarin-platform","tag-xamarin-forms"],"acf":[],"blog_post_summary":"<p>Every app needs storage, whether it&#8217;s for storing a collection of the same type of records in Azure Mobile Service with Easy Tables,\u00a0or a SQL Database exposed via Web Services. When the data is unstructured, NoSQL with Azure DocumentDB can be used. For scalability and high availability, Azure CosmosDb can be used in both the [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/32819","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/users\/549"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=32819"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/32819\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media\/39167"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=32819"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=32819"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=32819"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}