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.
Step 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.
Step 4: Finally, provide a name for your application and click Create 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.
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.
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.
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.
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).
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 forum, Direct-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:
- [eBook] PDF Succinctly
- [Blog] Why Waste Memory Saving Annotated PDFs When You Can Export Them Using the Xamarin PDF Viewer?
- [Blog] Adding a Custom Stamp to a PDF Using Xamarin PDF Viewer
- [Blog] Digitally Sign and Verify signature in PDF File Using C#: A Complete Guide
The post Easy Steps to Access Files in Dropbox and Use Them in a Xamarin App appeared first on Syncfusion Blogs.
Top comments (0)