{"id":18844,"date":"2015-06-04T16:23:05","date_gmt":"2015-06-04T20:23:05","guid":{"rendered":"http:\/\/blog.xamarin.com\/?p=18844"},"modified":"2015-06-04T16:23:05","modified_gmt":"2015-06-04T20:23:05","slug":"add-collaboration-to-your-mobile-apps-with-sharepoint","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/add-collaboration-to-your-mobile-apps-with-sharepoint\/","title":{"rendered":"Add Collaboration To Your Mobile Apps with SharePoint"},"content":{"rendered":"<p>\t\t\t\tMicrosoft SharePoint is one of the most widely used, powerful\u00a0collaboration tools in the workplace, providing countless features and seamless integration with other products in the Microsoft ecosystem. Now that SharePoint is provided as a cloud solution with <a href=\"https:\/\/dev.office.com\/\">Office 365<\/a>, integrating Office 365 into your apps with Xamarin is a breeze.\u00a0In recent blog posts, we covered adding\u00a0<a href=\"\/authenticate-xamarin-mobile-apps-using-azure-active-directory\/\" title=\"Authenticate Xamarin Mobile Apps Using Azure Active Directory\" target=\"_blank\">Azure Active Directory Authentication<\/a>, <a href=\"\/put-some-office-365-into-your-apps\/\" title=\"Put Some Office 365 in Your Apps\" target=\"_blank\">Outlook for Email<\/a>, and\u00a0<a href=\"\/add-storage-to-your-apps-with-office-365\/\" title=\"Add Storage to Your Apps with Office 365\" target=\"_blank\">OneDrive for Storage<\/a>\u00a0to your apps.<\/p>\n<p><img decoding=\"async\" class=\" size-medium wp-image-19034 aligncenter\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/0001-SP-2013-Logo-300x95.png\" alt=\"0001 SP 2013 Logo\" width=\"300\" height=\"95\" \/><\/p>\n<p>In this blog post,\u00a0we&#8217;ll see how easy it is to add SharePoint functionality to your mobile apps using the SharePoint APIs.<\/p>\n<h2>Step 1: Register Native Mobile App<\/h2>\n<p>Before SharePoint can be integrated into your app, you must <a href=\"https:\/\/developer.xamarin.com\/guides\/cross-platform\/azure\/active-directory\/getting-started\/register\/\" target=\"_blank\">register it using the Azure Active Directory<\/a>.<\/p>\n<h2>Step 2: Provide Access to SharePoint APIs<\/h2>\n<p>Once you register the app, click on the &#8216;Configure&#8217; tab. On this tab, you should see a green button with the text &#8216;Add application&#8217;. Click on it to access the SharePoint APIs.<\/p>\n<p><img decoding=\"async\" class=\"alignnone wp-image-18845 size-large\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/Screen-Shot-2015-05-28-at-10.36.16-1024x325.png\" alt=\"Providing access to SharePoint Services\" width=\"1024\" height=\"325\" \/>On the next screen, select &#8216;Office 365 SharePoint Online&#8217; and click on the check mark button.<\/p>\n<p><img decoding=\"async\" class=\"alignnone size-large wp-image-18846\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/Screen-Shot-2015-05-28-at-10.39.41-1024x640.png\" alt=\"Providing access to SharePoint Services Pt. 2.\" width=\"1024\" height=\"640\" \/>After this, give the\u00a0appropriate permissions to the SharePoint services, so users can access them from your mobile app.<\/p>\n<p><img decoding=\"async\" class=\"alignnone size-large wp-image-18848\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/Screen-Shot-2015-05-28-at-11.05.40-1024x554.png\" alt=\"Providing access to SharePoint Services Pt. 3\" width=\"1024\" height=\"554\" \/>Save the changes. Now it&#8217;s time to integrate SharePoint with our app. Make sure to copy the\u00a0&#8216;Client Id&#8217; and &#8216;Redirect URI&#8217;, which will be required in future steps.<\/p>\n<h2>Step 3: Authenticating to Azure Active Directory<\/h2>\n<p>With the latest Azure Active Directory Authentication Library (Azure ADAL) preview, the code from our <a href=\"\/authenticate-xamarin-mobile-apps-using-azure-active-directory\/\" target=\"_blank\">previous blog post on\u00a0ADAL<\/a> changes slightly.\u00a0As of the latest release, AuthorizationParameters has been renamed PlatformParameters, which govern the authentication mechanism on individual platforms. For Android, this is what the code to fetch access tokens should look like now:<\/p>\n<pre class=\"lang:csharp decode:true\">\npublic static async Task&lt;AuthenticationResult&gt; GetAccessToken(string serviceResourceId, PlatformParameters param)\n{\n    authContext = new AuthenticationContext(Authority);\n    if (authContext.TokenCache.ReadItems ().Any ()) {\n        authContext = new AuthenticationContext (authContext.TokenCache.ReadItems ().First ().Authority);\n\n        var authResult = await authContext.AcquireTokenAsync(serviceResourceId, clientId, returnUri, param);\n        return authResult;\n    }\n}\n<\/pre>\n<p>Here, serviceResourceId is your top-level SharePoint URL. For example, in my case it&#8217;s &#8220;http:\/\/mayurtendulkar.sharepoint.com\/&#8221;, and once authenticated, the app can access any resources below that level.\u00a0You can call this method from OnCreate, so whenever the app is launched, it will check for tokens (or launch the sign in process).<\/p>\n<pre class=\"lang:csharp decode:true\">\nvar authResult = await AuthenticationHelper.GetAccessToken (AuthenticationHelper.SharePointURL, new PlatformParameters (this));\n<\/pre>\n<p>Now, you can use this token from authResult to call the SharePoint APIs.<\/p>\n<h2>Step 4: Calling SharePoint APIs<\/h2>\n<p>Unlike objects like OutlookClient (which is responsible for Mail, Contacts, and Calendar) or SharePointClient (which is responsible for handling files in OneDrive), SharePoint APIs are REST APIs. Instead of using objects from the SDK, you will use HttpClient to call the SharePoint APIs.<\/p>\n<p>Before discussing how to call the SharePoint APIs from your app,\u00a0I want to revisit some SharePoint fundamentals. SharePoint contains SiteCollections, which can have sites and the sites can have sub-sites. Sites can be individual apps (e.g. HR Portal, Leave Portal, etc.) that contain libraries (for storing documents) as well as lists (task list, custom lists of data, etc.). Tasks can be shared with colleagues and marked as not started\/started\/complete\/etc. Here, we&#8217;re going to create a Task List and add some items to it.<\/p>\n<h3>Step 4.a: Create a List in SharePoint Site<\/h3>\n<p>The\u00a0code below will show you how to create a list within a SharePoint site. You can find detailed REST API documentation on SharePoint via <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/office\/dn292552.aspx\" target=\"_blank\">MSDN<\/a>.<\/p>\n<pre class=\"lang:csharp decode:true\">\n\nprotected async Task&lt;bool&gt; CreateList(string token)\n{\n    var client = new HttpClient();\n    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(&quot;Bearer&quot;, token);\n\n    var mediaType = new MediaTypeWithQualityHeaderValue (&quot;application\/json&quot;);\n    mediaType.Parameters.Add (new NameValueHeaderValue (&quot;odata&quot;, &quot;verbose&quot;));\n    client.DefaultRequestHeaders.Accept.Add (mediaType);\n\n    var body = &quot;{\\&quot;__metadata\\&quot;:{\\&quot;type\\&quot;:\\&quot;SP.List\\&quot;},\\&quot;AllowContentTypes\\&quot;:true,\\&quot;BaseTemplate\\&quot;:107,\\\n        &quot;ContentTypesEnabled\\&quot;:true,\\&quot;Description\\&quot;:\\&quot;Tasks by Xamarin.Android\\&quot;,\n        \\&quot;Title\\&quot;:\\&quot;TasksByAndroid\\&quot;}&quot;;\n\n    var contents = new StringContent (body);\n    contents.Headers.ContentType = MediaTypeHeaderValue.Parse( &quot;application\/json;odata=verbose&quot;);\n\n    try {\n        var postResult = await client.PostAsync (&quot;https:\/\/mayurtendulkar.sharepoint.com\/_api\/web\/lists\/&quot;, contents);\n        var result = postResult.EnsureSuccessStatusCode();\n        Toast.MakeText (this, &quot;List created successfully! Seeding tasks.&quot;, ToastLength.Long).Show();\n\n        return true;\n    } catch (Exception ex) {\n        Toast.MakeText (this, &quot;List already exists! Fetching tasks.&quot;, ToastLength.Long).Show();\n        return false;\n    }\n}\n<\/pre>\n<p>As you can see from the above code, the body of the request defines what needs to be done on the SharePoint side. In our case, we&#8217;re asking SharePoint to create a SP.List (list with template 107,) which is nothing but a Task List, and giving this list a title and description.<\/p>\n<h3>Step 4.b: Add Items to the List<\/h3>\n<p>Once the list is created, the same code shown above can be used to create &#8216;List Item&#8217;. To do so, changes need to be made in the request url and body. The following code can add a new task in &#8216;Task List&#8217;, which was just created above.<\/p>\n<pre class=\"lang:csharp decode:true\">\n\nprotected async Task&lt;bool&gt; CreateItems(string token)\n{\n    var client = new HttpClient();\n    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(&quot;Bearer&quot;, token);\n    var mediaType = new MediaTypeWithQualityHeaderValue (&quot;application\/json&quot;);\n    mediaType.Parameters.Add (new NameValueHeaderValue (&quot;odata&quot;, &quot;verbose&quot;));\n    client.DefaultRequestHeaders.Accept.Add (mediaType);\n\n    var itemToCreateTitle = &quot;Item created on: &quot; + DateTime.Now.ToString(&quot;dd\/MM HH:mm&quot;);\n    var body = &quot;{\\&quot;__metadata\\&quot;:{\\&quot;type\\&quot;:\\&quot;SP.Data.TasksByAndroidListItem\\&quot;},\\&quot;Title\\&quot;:\\&quot;&quot; + itemToCreateTitle + &quot;\\&quot;,\\&quot;Status\\&quot;: \\&quot;Not Started\\&quot;}&quot;;\n    var contents = new StringContent (body);\n    contents.Headers.ContentType = MediaTypeHeaderValue.Parse( &quot;application\/json;odata=verbose&quot;);\n\n    try {\n        var postResult = await client.PostAsync (&quot;https:\/\/mayurtendulkar.sharepoint.com\/_api\/web\/lists\/GetByTitle('TasksByAndroid')\/items&quot;, contents);\n        var result = postResult.EnsureSuccessStatusCode();\n        if (result.IsSuccessStatusCode) {\n            Toast.MakeText (this, &quot;List item created successfully!&quot;, ToastLength.Long).Show();\n            return true;\n        }\n    } catch (Exception ex) {\n        var msg = &quot;Unable to create list item. &quot; + ex.Message;\n        Toast.MakeText (this, msg, ToastLength.Long).Show();\n        return false;\n}\n\n<\/pre>\n<h3>Step 4.c: Fetch &amp; Display List Items<\/h3>\n<p>Getting records from list requires nothing beyond calling a &#8216;GET&#8217; request on list endpoint. Displaying these items in a list within your mobile app is easy: the request returns JSON data, which you can parse to objects using <a href=\"https:\/\/components.xamarin.com\/view\/json.net\">Json.NET<\/a> and then you can create a custom adapter (in my case ListItemModels) and display it in a ListActivity.<\/p>\n<pre class=\"lang:csharp decode:true\">\n\nprotected async Task&lt;bool&gt; FetchListItems(string token)\n{\n    var client = new HttpClient();\n    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(&quot;Bearer&quot;, token);\n    var mediaType = new MediaTypeWithQualityHeaderValue (&quot;application\/json&quot;);\nmediaType.Parameters.Add (new NameValueHeaderValue (&quot;odata&quot;, &quot;verbose&quot;));\nclient.DefaultRequestHeaders.Accept.Add (mediaType);\n    try {\n        var result = await client.GetStringAsync(&quot;https:\/\/mayurtendulkar.sharepoint.com\/_api\/web\/lists\/GetByTitle('TasksByAndroid')\/items&quot;);\n        var data = JsonConvert.DeserializeObject&lt;O365SharePoint.Models.ListItemModels&gt;(result);\n        ListAdapter = new ListItemAdapter(this, data.D.Results);\n        ListView.ItemClick += async (sender, e) =&gt; {\n            var _status = (e.View as CheckedTextView).Checked;\n            var _id = (e.View).Tag.ToString();\n            await ChangeStatus(token, _id, _status);\n        };\n\n        for (int item = 0; item &lt; data.D.Results.Length; item++) {\n            if(data.D.Results[item].Status == &quot;Completed&quot;)\n                ListView.SetItemChecked(item, true);\n        }\n\n    } catch (Exception ex) {\n        var msg = &quot;Unable to fetch list items. &quot; + ex.Message;\n        Toast.MakeText (this, msg, ToastLength.Long).Show();\n    }\n\n    return true;\n}\n\n<\/pre>\n<h3>Step 5: Run the App<\/h3>\n<p>Run this app using either the <a href=\"https:\/\/xamarin.com\/android-player\">Xamarin Android Player<\/a> or a physical device. If all of the steps above are executed correctly, you should see the same items from the list created in SharePoint in the Android\u00a0app we built.<\/p>\n<p><img decoding=\"async\" class=\"alignnone size-large wp-image-18857\" src=\"\/wp-content\/uploads\/sites\/44\/2019\/04\/Screenshot-2015-05-29-14.54.58-1024x585.png\" alt=\"SharePoint List and List in a Mobile App\" width=\"1024\" height=\"585\" \/><\/p>\n<h2>Conclusion<\/h2>\n<p>Once you understand the basics of the SharePoint REST APIs and how to call them from mobile apps, the possibilities are endless. Integrating existing SharePoint sites into your iOS and Android apps is easy with Xamarin.<\/p>\n<p>To get started, <a href=\"https:\/\/github.com\/mayur-tendulkar\/\" target=\"_blank\">download the SharePoint sample<\/a> from GitHub and be sure to replace the client ID, redirect URI, and your resource URI with the ones\u00a0you created in the tutorial before running the app.\t\t<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Microsoft SharePoint is one of the most widely used, powerful\u00a0collaboration tools in the workplace, providing countless features and seamless integration with other products in the Microsoft ecosystem. Now that SharePoint is provided as a cloud solution with Office 365, integrating Office 365 into your apps with Xamarin is a breeze.\u00a0In recent blog posts, we covered [&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],"class_list":["post-18844","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-xamarin-platform"],"acf":[],"blog_post_summary":"<p>Microsoft SharePoint is one of the most widely used, powerful\u00a0collaboration tools in the workplace, providing countless features and seamless integration with other products in the Microsoft ecosystem. Now that SharePoint is provided as a cloud solution with Office 365, integrating Office 365 into your apps with Xamarin is a breeze.\u00a0In recent blog posts, we covered [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/18844","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=18844"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/18844\/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=18844"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=18844"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=18844"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}