Articles, Blog

Google Drive SDK: Writing your first Drive app in .NET

November 2, 2019


[MUSIC PLAYING] BILL LUAN: Shanghai
GDG is a very interesting developer community. FEMALE SPEAKER: I’m
glad somebody has asked this question. MALE SPEAKER: This is where
the magic happens. FEMALE SPEAKER: This is
primarily a question and answer show. So if any of you out there would
like to ask questions. ALAIN VONGSOUVANH:
Hello, everyone. Welcome to Google
Developers Live. Today, Claudio and I, Alain,
are going to talk about writing your first
.NET application using Google Drive. CLAUDIO CHERUBINO: Cool. So you probably know already
because we had these videos in the past two weeks. We added a new Quickstart page
to the Google Drive SDK documentation. It’s developers.googl
e.com/drive/quickstart. On that page, you can find
step-by-step instructions on how to write your first command
line application for five support languages. ALAIN VONGSOUVANH: Six
languages now. CLAUDIO CHERUBINO:
Actually six. We Just added Go. So we have Java, Python, PHP,
.NET, Ruby, and Go. And we have videos covering
the Quickstart guide for Python and PHP. If you are interested in those,
you can find them in our video library. But today, we’re going
to focus on .NET. And you’re going to see that
most of the introductory steps are the same. So if we go to the documentation
page at developers.googl
e.com/drive/quickstart, we’ll see that we have five
steps to follow. The first one is enabling
the Drive API. So to do that, we have to
go to the APIs console. ALAIN VONGSOUVANH:
That’s correct. This has to be done with most
of our Google APIs. So new developers or existing
developers who already have an API project need to go to the
APIs console and enable the APIs we want to use. In our case, that would
be the Drive API. CLAUDIO CHERUBINO: So we
go to the APIs console. And if you have never created a
project before, you will see this screen with a big blue
button saying Create Project, which is what we’re doing. We need to create a project
to get credentials, right? ALAIN VONGSOUVANH:
That’s correct. CLAUDIO CHERUBINO: So we
do Create Project. We wait for a project
to be created. And then we have a list of
services we want to enable. The only one we need
is the Drive API. So we scroll down to Drive, and
click on it to enable it. So now your Drive API is enabled
for this project. And we have a limit of 500,000
requests per day, which should be more than enough for
today’s example. ALAIN VONGSOUVANH: For a
first application, yes. But if you ever run out of
quota, there is a form on the API console that you can fill,
and we will review the quota requests and grant more quota or
get back to you to get more information. CLAUDIO CHERUBINO: So once we
enable the Drive API, we have to generate our credentials,
client ID, and client secret for the OAuth 2.0 flow. So we have to go to the
API Access tab. In the API Access tab, we have
a big blue button that says Create an OAuth 2.0 client ID. It’s pretty easy. We just click on that. We have to specify
our product name. We can call it Drive
Quickstart. It’s up to you, adjust
the name. And if you want, you can
add a product logo. This is just a sample. We don’t have a logo, but you
can add it later if you want. So I’m going to click Next. And then you have to select if
you want a web application, a service account application, or
an installed application. So what we’re going to write
today is a command line application, right? ALAIN VONGSOUVANH:
That’s correct. So in– [NO AUDIO]. CLAUDIO CHERUBINO: –iOS
or other, which is everything else. And ours is going to be other. It’s going to be a command
line application on .NET. So you click on Create Client
ID, and you get your credentials, which are the
client ID and the client secret, which we’re going to
need in our application. They can be considered as
username and password. ALAIN VONGSOUVANH:
Yes, but for– [NO AUDIO] CLAUDIO CHERUBINO: –client
ID can be, let’s say, distributed around. Other people can know about
your client ID. Client ID of your application,
that’s not secret. But a client secret is
actually secret. So if it happens that other
people get hold of your client secret, you have to revoke
it and get a new one. You can do that at any time by
going to the same page here and clicking on Reset
Client Secret. ALAIN VONGSOUVANH:
That’s correct. CLAUDIO CHERUBINO: So let’s say
at the end of this talk, that’s what I’m going to do. ALAIN VONGSOUVANH: Yes. And if you ever reset your– [NO AUDIO] CLAUDIO CHERUBINO: If you reset
your client secret and you still have it in your code,
the application will just break. The credentials would
not be accepted. So let’s go back to the Docs,
and we see that we’ve done the first step. It was very easy
and very quick. So we enabled the Drive API
and we generated our credentials for an installed
application. The second step, it’s
specific to the language of your choice. Because it’s the step on how to
install the client library for the language of a choice. In our case, this is
going to be .NET. There are similar instructions
for other languages. The .NET one requires you to
download a zip with the library and then reference
some of those into your project. So there’s a link to the
core .NET library. We can just follow the link. It takes you to the
download page. ALAIN VONGSOUVANH: The Drive
API is a simple REST API. So if you already have an HTTP
client and you want to go through the process for writing
your own HTTP client, you can easily use the API. But we do have supported client
libraries in many languages, and it’s so much
easier to use those. And our documentations are
written together on those client libraries. So we recommend you using
those client libraries. In case there are bugs, they’ll
be easily fixed by us, and they’ll always be
up to date with our most recent APIs. CLAUDIO CHERUBINO: Perfect. So we’re brought to the Google
API .NET client library page, and what we want is the
latest stable release. So we click on it, and we have
the option to download the binary release, which includes
the DLLs, the source files, or the samples. What we need here is
the binary release. So we just click on this and
we’re going to download. The file. And it’s done. These ZIP files, which I’m
going to open now, will include two folders, one for the
library, the core library, and the other one
for the service. So let me instruct this on my
desktop just to be used later. So I’ll copy this to
my desktop here. You can obviously put the
files wherever you want. And this will include many DLLs
you won’t need because we’re only going to use Drive. But if you check inside
Services, you will see a folder for each API you can
use with this library. So what we’re going to
need is just Drive. And if you check Lib, instead
you will see there’s a number of libraries we’re going to
include in the next step. So let’s go back to
the documentation. And we’re done with
the second step. So the third step is to
set up the sample. Those instructions are also
specific for the language of your choice. So in .NET, we’re going
to set up– we’re going to create a new
solution inside Visual Studio. And then we’re going to use
the code that’s here. So let’s start with creating a
new solution in Visual Studio. So I have Visual Studio
2010 open. I can do New Project and select
Console Application. Let’s call this DriveQuickstart. Obviously you can call
it as you want to. I create a solution for this. And it’s an empty solution,
as you know. What we’re going to do here to
set up this is that we are going to make sure we target
.NET Framework 3.5 or 4, not Client Profile. So we do right click on the
project and go to Properties. The default framework for the
solution was .NET Framework 4 Client Profile. We are going to change it
to .NET Framework 4. 3.5 is also valid. ALAIN VONGSOUVANH: Yes. And I think the client library
also supports 2.5. CLAUDIO CHERUBINO: Yes,
with some caveats. ALAIN VONGSOUVANH: Yes. CLAUDIO CHERUBINO: So then we
need to add references to the DLLs we want. So we can do Add Reference
and select some of the DLLs we want. So let me browse the Lib
directory first. So they were on my desktop. So I can go to my desktop. In here, there’s a folder
called Lib. What we need is DotNetOpenAuth. We need Google.Apis.Auth
entication.OAuth2. We need Google.Apis. So we can start adding those. We also need a reference
to the Drive service. ALAIN VONGSOUVANH:
That’s correct. ALAIN VONGSOUVANH: So we do
add another reference. This is not here. It’s in the Service folder. So we go back here, go to
Services, and we need Drive. In the DriveService folder,
you will find two DLLs for v1 and v2. This sample is for v2, which
is mostly backward compatible to v1. There’s just minor changes. But now you should always use v2
if you start a new project. ALAIN VONGSOUVANH: v2 is a
separate set of v1 and has much more functionalities
than v1. And if you already have
code working on v1, it’s easy to migrate. And we do have a migration
guide on the documentation page. CLAUDIO CHERUBINO: Yeah, I think
the migration from v1 to v2 is just two very
easy steps. ALAIN VONGSOUVANH: Yes, changing
some attribute’s names and arguments. CLAUDIO CHERUBINO: So let’s
go back to the code. So we have this empty page. But we can start from the
code we have here. So we can take all of this
and then we will explain it line by line. So let me copy it. I will copy this and replace the
content in my Program.cs standard file. This is that. ALAIN VONGSOUVANH: All set. CLAUDIO CHERUBINO: We can
build a solution. Build succeeded. We can run it. Let’s just add another
line here. We’re going to add it to
the documentation. So you know, this is going to be
a command line application. So when you run, it will
authenticate and then upload a file to Drive. ALAIN VONGSOUVANH: And close. CLAUDIO CHERUBINO: And close. So if you want to see the
result, it’s probably better if we do a console.readline here
so that we just wait for the user to press Enter. And we need to add a file
to be uploaded to Drive. So we’re going to read
from the folder that the executable is– ALAIN VONGSOUVANH:
Running from. CLAUDIO CHERUBINO: –in. So we can either manually add
the file to the debug directory or wherever. But it’s probably better if we
add file from here and make sure we copy it to the
content folder. So we do Add. We do Add New Item and search
for a text file. This file is called
Document.txt. If you want to use another
file, of course, you can change it in the code. But if we want to use the code
as it is, and we want to follow the instructions step
by step, the file has to be called Document.txt. So we add it. And we could write something
like this is a test document, Save. And then remember to make sure
this file is copied to the output directory. So you can change this– ALAIN VONGSOUVANH: Build rule. CLAUDIO CHERUBINO: –the build
rule to copy always. So now if we run this
application, this file will be there. We just need another
exercise– ALAIN VONGSOUVANH:
That’s right. CLAUDIO CHERUBINO: –which is
to set the credentials we generated from the Google
APIs Console. ALAIN VONGSOUVANH: Right now,
if you run the application– CLAUDIO CHERUBINO: It will just
fail the authorization. ALAIN VONGSOUVANH: Yes. CLAUDIO CHERUBINO: Because the
credentials are not valid. We have two placeholders
here for client ID and client secret. So we can go back to the APIs
Console and copy those values we generated. So we take the client ID and
we replace this right here. And then we take the client
secret and we replace that too. Now– ALAIN VONGSOUVANH: We’re
ready to go. CLAUDIO CHERUBINO: Yeah. So this will run a command
line application. See what happens. So I run and debug. The first thing we do is the
authorization process. So the application tries to
start a browser in your computer to allow the user to
approve the application. ALAIN VONGSOUVANH:
That’s correct. CLAUDIO CHERUBINO: So this
application is requesting permission to view and manage
the files and documents I have on Google Drive. If you want to know more details
about what we’re allowing the application to do,
you can expand it and see a more detailed description. The name you see here is the
name of the application, the project we created in
the APIs Console. So it’s definitely my project. I can allow access to it. ALAIN VONGSOUVANH: And this
is what the users of our application will see when
they go through the authorization flow. CLAUDIO CHERUBINO: Yes. So since this is a command line
application this is not a web application. The flow is not the best for the
user as the users have to copy this code from here and
pass it to the command line application. So I’m going to copy it from
here, go back to my shell. As you can see, the application
is running here and is waiting for me to provide
an authorization code, which is the code we just
got from the flow. So I can put the code here. And what is going to happen
next, assuming the authorization went well, and
I’m pretty sure it did, the Document.txt file is going to
be uploaded to Google Drive. And the application will
print the file ID. So whenever you upload a file to
Google Drive, you get back some metadata, including the
file ID, which is a unique ID. And the file upload was
successful, and we got our file ID, which is a long string,
and that’s unique. So now the application
is waiting for me to press Enter to quit. That’s it. The application worked. And if I go to my Drive, I
should have a new document called My Document, which
was just created. And if I open it, it contains
the text I put, this is a test document. So it worked. But you might wonder why this
is called My Document. I mean, the file was called
Document.txt. So, let’s go back to the
code and check the code line by line. So in the code we have two
things to do, first, authorization, second, use the
Drive API to upload a file. The authorization
can be complex. The OAuth flow can look
complex if you don’t know the details. But the library hides all
the complexity from you. So it’s basically these
two lines here. You need to instantiate
a provider and then authenticator. ALAIN VONGSOUVANH: Yes, and
the library is also using DotNetOpenAuth, which is an open
source library supporting many types of authorization
mechanisms, including OAuth 2.0 OAuth 1.0 AuthSub,
and other protocols. CLAUDIO CHERUBINO: Yeah, so that
library is basically the de-facto standard for OAuth
authorization in .NET. And so we decided not to
reinvent the wheel and instead we use a standard library that
almost everyone else uses. So we use this library. We extended it with our own
Google specific things. And so you need to do
instantiate a new native application client with your
client ID and secret. And that’s where the credentials
are used. And then you have to instantiate
an OAuth authenticator. One of the parameter you pass to
the OAuth authenticator is a function, in our case, called
GetAuthorization, which is the function that the library
will automatically call when the flow has
to be started. So if we go down, here is the
GetAuthorization method, which generates the authorization URL,
spawns the browser, and waits for the user to– ALAIN VONGSOUVANH:
Enter the code. CLAUDIO CHERUBINO:
–enter the code. When that is done, it just
works on processing the authorization with the code in
the client ID and secret and all the other credentials
you have. And that will return an object
which implements the authorization state interface,
which is what we need to instantiate the service. So in fact, if we go back to
our main code, we can then instantiate a DriveService using
the OAuth object we just got from the authentication. We’re done with authorization. Second part, we have to upload
a file to drive. ALAIN VONGSOUVANH: Yes. CLAUDIO CHERUBINO: How
do we do that? Uploading a file requires
two parts, right? ALAIN VONGSOUVANH: Yes. So a file in Drive, as Claudio
mentioned, has two parts, the metadata and the content. There are two types of files
actually, files that only contain metadata for
applications who already has a database and wants to sort the
content on the database. We can simply create a shortcut
on Drive, and the user would be able to see the
files on Drive and click and be redirected to the
other applications. Otherwise, the other form is
saving both metadata and content on Drive. And this will use the
user’s quota. CLAUDIO CHERUBINO: And that is
exactly what we’re doing here. So we are setting some metadata
first, and then we are setting the content. As this is a sample,
we basically hard-coded some metadata. So the title would always
be My Document. The description will always be
A Test Document, and the MimeType will always
be text/plain. ALAIN VONGSOUVANH: And
this is actually what we saw on your Drive. CLAUDIO CHERUBINO:
Yes, exactly. Of course, if you want to
generalize this and make a real application, you will
have to set the title according to the real title or
give a user an option to select a title and provide a
description, if any, and, obviously, set the correct
mime type. So this application will always
upload a text file to Drive or assume that we’re
trying to upload a text file to Drive. But if you want, let’s say, to
upload a PDF, you have to replace the mime type to
application PDF instead of text/plain. And this is all we need
for metadata and then read the content. So we use standard system.io
methods to read the content of a file from our file system. And here’s where we see that
the application uses Document.txt. So if you want to obviously
give the user an option to select a file, you have
to make this dynamic. So instead of hard-coding the
name of the file, you give the user an option to
select a file, and with that a byteArray. And then, it is just a single
line of code to insert a file on Drive. So we have this
InsertMediaUpload request object which takes the
metadata and the– ALAIN VONGSOUVANH: Content. CLAUDIO CHERUBINO: –content as
a byte stream in the file type, and then you can
call upload on it. The upload, when that returns,
you will have a response body property. And the response body property
will include all the metadata that is returned from Drive. And that includes the file
title, the ID, the modified data, a lot of information. You can check what a file object
is to see what you get. And eventually, before closing
the application, we just print the file ID to show that the
application worked and we got some metadata back. And that’s it. We just wait for a user to
close and we’re done. So this main application, this
command line application, it probably took 10 to 15
minutes to write. ALAIN VONGSOUVANH: Yes. CLAUDIO CHERUBINO: It does
everything from scratch, then it does authorization and
uploading a file to Drive. But, of course, you
can do more now. ALAIN VONGSOUVANH: Yes. So the Drive API has many
functionalities. So inserting files, as we just
did, getting a list of files from the user according to
those codes you choose to approve your application with,
you get either the entire user’s drive or only the files
that the user has granted access to your application. You can also update a file’s
content, delete files, trash files, get revisions
from files. CLAUDIO CHERUBINO: And a lot
more things are in the documentation. Before we wrap up, let’s just
get back to the Doc. So we explained how to build
this application and how to run the sample, and
we tried that. And what Alain is saying is
covered in the next section, which is the last section
of the Quickstart. So you might want to expand
this sample to do a lot more things. And another next step we might
recommend is for you to check the real sample applications
we have. So this is a very simple
basic application. With this, you get started in
five minutes, and you have a working application. But if you want to do any more
and you still need help on that, in the documentation we
have a section for example applications. So if you click on that, you
will see that we have a sample application that is called
DrEdit or DoctorEdit. We will eventually decide
what the right name is. It’s a text editor that uses
Drive to store files. And we have a tutorial
for five languages. Well, it’s still six now. Well, Go is coming. ALAIN VONGSOUVANH:
Go is coming. CLAUDIO CHERUBINO: And so, for
instance, if you’re still using .NET, you might want
to check DrEdit for .NET. And that is going to be a more
complex application. It’s an ASP.NET MVC
application. So it’s a web application that
takes care of everything, all the edge cases in
authorization. ALAIN VONGSOUVANH: Integration
with the Drive UI. CLAUDIO CHERUBINO: Integration
with the Drive UI. And it’s a more complex
sample. But if you get started with
the Quickstart, then this should be very easy
to understand. And all the code is here, the
project can be downloaded from the repository. And it is basically explained
line by line. So it should be very
easy to understand. And of course, you might
still have questions. ALAIN VONGSOUVANH: Yes. So if you have questions, we
will be looking for them on Stack Overflow under the
google-drive-sdk tag. CLAUDIO CHERUBINO:
OK, perfect. I think that’s it for today. I hope you liked learning how
to build your first Drive application with .NET. And we’ll see you next time. ALAIN VONGSOUVANH: Yes,
but it was easy. CLAUDIO CHERUBINO: Yeah. Thank you. ALAIN VONGSOUVANH: Bye. [MUSIC PLAYING]

5 Comments

  • Reply Nathan Owen July 11, 2014 at 6:13 am

    Hmm the code seems to be out of date…  I get a "A first chance exception of type 'System.AggregateException' occurred in mscorlib.dll" error when running the provided code.  I'm guessing this method of authentication is no longer supported…

  • Reply Manuel Luces July 14, 2015 at 7:46 am

    Hello, I'm trying to Upload a File through my ASP website using Service Account but there is an error I don't understand..

    An unhandled exception of type 'System.InvalidOperationException' occurred in Google.Apis.Auth.dll

    Additional information: At least one client secrets (Installed or Web) should be set

  • Reply Mohamed Nasser-allah November 20, 2016 at 2:36 pm

    What about read or download files (PDF files) from Google Drive to our Application (WFA) ?

  • Reply Sanoj Ayinikkal Vasudevan June 22, 2017 at 9:17 pm

    Instead you switching the view frequently from the computer screen to show your own faces next time try keeping the view fixed in the screen after you gave the introduction. It would have been a great video otherwise.

  • Reply sukhen dass December 1, 2017 at 1:53 am

    I am not able to use google drive in VS2010 with 4.0 framework error coming while calling GoogleWebAuthorizationBroker.AuthorizeAsync. Error message is One or more errors occurred.

  • Leave a Reply