Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (143).NET Core  (22)Angular  (38)ASP.NET  (47)ASP.NET Core  (52)ASP.NET MVC  (83)Azure  (26)Blazor  (44)DocIO  (18)Essential JS 2  (64)Essential Studio  (159)Flutter  (46)JavaScript  (133)Microsoft  (96)PDF  (47)React  (29)Succinctly series  (118)Syncfusion  (382)TypeScript  (30)Uno Platform  (2)UWP  (4)Vue  (25)Webinar  (13)Windows Forms  (52)WPF  (85)Xamarin  (104)XlsIO  (20)Other CategoriesBarcode  (4)BI  (29)Bold BI  (3)Build conference  (6)Business intelligence  (53)Button  (4)C#  (97)Chart  (38)Cloud  (8)Company  (445)Dashboard  (4)Data Science  (3)Data Validation  (2)DataGrid  (27)Development  (232)Doc  (7)eBook  (89)Enterprise  (22)Entity Framework  (4)Essential Tools  (14)Excel  (11)Extensions  (6)File Manager  (3)Gantt  (6)Gauge  (4)Git  (3)Grid  (24)HTML  (8)Installer  (1)Knockout  (2)LINQPad  (1)Linux  (1)M-Commerce  (1)Metro Studio  (11)Mobile  (133)Mobile MVC  (9)OLAP server  (1)Orubase  (12)Partners  (20)PDF viewer  (15)Performance  (1)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (5)Road Map  (9)Scheduler  (13)SfDataGrid  (7)Silverlight  (21)Sneak Peek  (12)Solution Services  (2)Spreadsheet  (2)SQL  (3)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (8)Tips and Tricks  (12)UI  (55)Uncategorized  (68)Unix  (2)User interface  (42)Visual State Manager  (1)Visual Studio  (12)Visual Studio Code  (6)Web  (84)What's new  (53)Windows 8  (19)Windows App  (1)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
Access PDF files from Dropbox and load them easily using Xamarin PDF Viewer

Easy Steps to Access Files in Dropbox and Use Them in a Xamarin App

We all know that Dropbox is one of the most popular file-hosting services for the cloud. However, at some point, we all have found it hard to access files available in the Dropbox and use them in our Xamarin applications.

In this blog, we will walk you through the steps to access files in Dropbox and use them in a Xamarin.Forms application, with an example of accessing a PDF file and displaying it in our Syncfusion Xamarin PDF Viewer.

Let’s get started!

Register your application in Dropbox

Step 1: To start with, you need to register your application in the Dropbox platform. For that, navigate to the Dropbox developers site and click Create Apps.

Step 2: Next, select the type of API you want to use with your application. The suggested option is to use the free Dropbox API.

Choose-Dropbox-APIStep 3: Then, select the access mode. You can restrict the access to the application to a specific folder or allow access to all the folders.
Choose-the-type-of-access-you-need

Step 4: Finally, provide a name for your application and click Create app.
Name-your-app

Step 5: Then, the following page will be displayed with the application settings information in it. You need to use this App secret key information to generate an OAuth2 access token.
App-secret-key-to-generate-OAuth2-access-token

For a simple C# console application, you can directly generate the access tokens from the developer site and use them in your program. So, you should copy this token and use it in the client application to establish the connection.

Use the Dropbox API class DropboxClient to establish the connection and manage the files. For more details, please refer to this tutorial.

But in our Xamarin application, we are going to generate the access token programmatically to manage the Dropbox files.

Access Dropbox files and use them in a Xamarin application

Please follow these steps to establish the connection, access PDF files in the Dropbox, and view them using our Syncfusion Xamarin PDF Viewer.

Step 1: Create a new Xamarin.Forms project.

Step 2: Install the packages Dropbox.Api in the PCL project and Syncfusion.Xamarin.SfPdfViewer in all the projects.
Choose-Dropbox.Api_

Step 3: Create a ViewModel class and name it DropboxViewModel. Add a binding property PdfDocumentStream of type Stream in the ViewModel class. Then, in the MainPage.xaml, set the binding context as DropboxViewModel and add the SfPdfViewer control. Then bind the InputFileStream property of SfPdfViewer to the PdfDocumentStream property.

Step 4: Create a class named DropboxService and add all the logic to establish the connection and obtain the information from the Dropbox. Here, we use Webview to display the login interface. In its navigation event, add the logic to obtain the Dropbox access token once when the authentication is completed. The ClientId (App secret) and RedirectUri values can be obtained from the Dropbox developers site/console.

Please take a look at the code example.

        private const string ClientId = "Your App secret key";
 
        private const string RedirectUri = "Your Redirect Uri";
 
        /// <summary>
        ///     <para>Runs the Dropbox OAuth authorization process if not yet authenticated.</para>
        ///     <para>Upon completion <seealso cref="OnAuthenticated"/> is called</para>
        /// </summary>
        /// <returns>An asynchronous task.</returns>
        public async Task Authorize()
        {
            Application.Current.Properties.Clear();
 
            if (string.IsNullOrWhiteSpace(this.AccessToken) == false)
            {
                // Already authorized
                this.OnAuthenticated?.Invoke();
                return;
            }
 
            // Run Dropbox authentication
            this.oauth2State = Guid.NewGuid().ToString("N");
            var authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OAuthResponseType.Token, ClientId, new Uri(RedirectUri), this.oauth2State);
            var webView = new WebView { Source = new UrlWebViewSource { Url = authorizeUri.AbsoluteUri } };
            webView.Navigating += this.WebViewOnNavigating;
            var contentPage = new ContentPage { Content = webView };
            await Application.Current.MainPage.Navigation.PushModalAsync(contentPage);
        }

Step 5: Once the user has logged into Dropbox, the URL for the Webview will contain the access token to authenticate all other requests. Please find the code example of the Webview navigation event in the following.

        private async void WebViewOnNavigating(object sender, WebNavigatingEventArgs e)
        {
            if (!e.Url.StartsWith(RedirectUri, StringComparison.OrdinalIgnoreCase))
            {
                // we need to ignore all navigation that isn't to the redirect uri.
                return;
            }
            try
            {
                var result = DropboxOAuth2Helper.ParseTokenFragment(new Uri(e.Url));
                if (result.State != this.oauth2State)
                {
                    return;
                }
                this.AccessToken = result.AccessToken;
                this.OnAuthenticated?.Invoke();
            }
            catch (ArgumentException)
            {
                // There was an error in the URI passed
            }
            finally
            {
                e.Cancel = true;
                await Application.Current.MainPage.Navigation.PopModalAsync();
            }
        }     

Step 6: Now we have obtained the token and with the help of that, we can perform actions like getting the list of files; reading, writing, and saving files.

Please take a look at the code example.

         /// <summary>
        /// Gets the Dropbox file list
        /// </summary>
        /// <returns>An asynchronous task</returns>
        public async Task<IList<Metadata>> ListFiles()
        {
            try
            {
                using (var client = this.GetClient())
                {
                    var list = await client.Files.ListFolderAsync(string.Empty, true);
                    return list?.Entries;
                }
            }
            catch (Exception)
            {                
                return null;
            }
        }
 
        /// <summary>
        /// Reads the file from Dropbox and returns it as byte array
        /// </summary>
        /// <returns>An asynchronous task</returns>
        public async Task<byte[]> ReadFile(string filePath)
        {
            try
            {
                using (var client = this.GetClient())
                {
                    var response = await client.Files.DownloadAsync(filePath);
                    var bytes = response?.GetContentAsByteArrayAsync();
                    return bytes?.Result;
                }
            }
            catch (Exception)
            {                
                return null;
            }
        }
 
        /// <summary>
        /// Writes the file to the Dropbox
        /// </summary>
        /// <returns>An asynchronous task</returns>
        public async Task<FileMetadata> WriteFile(MemoryStream fileContent, string fileName)
        {
            try
            {
                var commitInfo = new CommitInfo(fileName, WriteMode.Overwrite.Instance, false, DateTime.Now);
 
                using (var client = this.GetClient())
                {
                    var metadata = await client.Files.UploadAsync(commitInfo, fileContent);
                    return metadata;
                }
            }
            catch (Exception)
            {                
                return null;
            }
        }

Step 7: To view the PDF file in Dropbox in our Syncfusion Xamarin PDF Viewer, call the ReadFile(string fileName) method and convert the resultant byte array to stream. Then, assign the converted stream to the PdfDocumentStream property in the DropboxViewModel class.

Step 8: Similarly, you can call the WriteFile(MemoryStream fileContent, string fileName) method to write or save the modified PDF back in the Dropbox.

Dropbox sample project

You can find the sample project of loading and saving Dropbox PDF files using Syncfusion Xamarin PDF Viewer in this GitHub location. The following steps describe the procedures involved in working with this sample project.

Step 1: In this sample, initially a Dropbox login interface will be displayed for your Dropbox credentials.

drop box in Xamarin
Step 2:
After entering your credentials, the list of PDF files from the user’s Dropbox account will be displayed in a pop-up list view. You can select any PDF file from the list to view it in the PDF Viewer control. You can also select another file by clicking on the Files option in the top grid section.
choose your desired file

Step 3: Then, you can edit the PDF file loaded using the options in the PDF Viewer control. Also, you can save them to the signed-in Dropbox account by clicking on the save option.

Step 4: Once Save is clicked, a pop-up view to obtain the file name will be displayed. Entering a file name (e.g., PDF_Succinctly.pdf) and clicking OK will save the document in the Dropbox.

Step 5: You could also save the file to a specific folder by providing the file name in this format: folder name/file name (e.g., Syncfusion/PDF_Succinctly2.pdf).
choose save option

enter the file name
Conclusion

I hope you now have a clear idea about how to access files from Dropbox and use them in a Xamarin application. You can also perform various other operations as described in the Dropbox tutorial documentation. I leave them for you to experiment with. Try them and share your feedback in the comments section below.

If you aren’t a customer yet, you can try our 30-day free trial to check out these features. Also, try our other samples from this GitHub location.

If you wish to send us feedback or would like to submit any questions, please feel free to contact us through our support forumDirect-Trac, or feedback portal. We are always happy to assist you!

If you like this post, we think you will also enjoy the following eBook and other articles as well:

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin

Leave a comment

Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top