.NET Quickstart

Complete the steps described in the rest of this page to create a simple .NET console application that makes requests to the Google Drive Activity API.

Prerequisites

To run this quickstart, you need the following prerequisites:

  • Visual Studio 2013 or later
  • A G Suite account with Google Drive enabled.

Step 1: Turn on the Google Drive Activity API

Click this button to create a new console project and automatically enable the Google Drive Activity API:

Enable the Google Drive Activity API

This opens a new dialog. In the dialog, do the following:

  1. Select + Create a new project.
  2. Download the configuration file.
  3. Move the downloaded file to your working directory and ensure it is named credentials.json.

Step 2: Prepare the project

  1. Create a new Visual C# Console Application project in Visual Studio.
  2. Open the NuGet Package Manager Console, select the package source nuget.org, and run the following command:
Install-Package Google.Apis.Appsactivity.v1

Step 3: Set up the sample

  1. Drag credentials.json (downloaded in Step 1) into your Visual Studio Solution Explorer.
  2. Select credentials.json, and then go to the Properties window and set the Copy to Output Directory field to Copy always.
  3. Replace the contents of Program.cs with the following code:

drive/activity/DriveActivityQuickstart/DriveActivityQuickstart.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Appsactivity.v1;
using Google.Apis.Appsactivity.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;

namespace DriveActivityQuickstart
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // in token.json
        static string[] Scopes = { AppsactivityService.Scope.Activity };
        static string ApplicationName = "Drive API .NET Quickstart";

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Drive Activity API service.
            var service = new AppsactivityService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            // Define parameters of request.
            ActivitiesResource.ListRequest listRequest = service.Activities.List();
            listRequest.Source = "drive.google.com";
            listRequest.DriveAncestorId = "root";
            listRequest.PageSize = 10;

            // List activities.
            IList<Google.Apis.Appsactivity.v1.Data.Activity> activities = listRequest.Execute().Activities;
            Console.WriteLine("Activities:");
            if (activities != null && activities.Count > 0)
            {
                foreach (var activity in activities)
                {
                    Event activityEvent = activity.CombinedEvent;
                    User user = activityEvent.User;
                    Target target = activityEvent.Target;
                    if (user != null && target != null)
                    {
                        var epoc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                        DateTime date = epoc.AddMilliseconds(
                            (long)activityEvent.EventTimeMillis).ToLocalTime();
                        Console.WriteLine("{0}: {1} {2} {3} {4}", date, user.Name,
                            activityEvent.PrimaryEventType, target.Name, target.MimeType);
                    }
                }
            }
            else
            {
                Console.WriteLine("No recent activity.");
            }
            Console.Read();
        }
    }
}

Step 4: Run the sample

Build and run the sample by clicking Start in the Visual Studio toolbar.

The first time you run the sample, it will prompt you to authorize access:

  1. The sample will attempt to open a new window or tab in your default browser. If this fails, copy the URL from the console and manually open it in your browser.

    If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.

  2. Click the Accept button.
  3. The sample will proceed automatically, and you may close the window/tab.

Notes

  • Authorization information is stored on the file system, so subsequent executions will not prompt for authorization.
  • The authorization flow in this example is designed for a command-line application. For information on how to perform authorization in a web application, see the web applications section of the library's OAuth 2.0 guide.

Further reading

Troubleshooting

Could not load file or assembly 'Microsoft.Threading.Tasks'

This error can occur when using an outdated or incorrectly installed version of the Microsoft.Bcl.Async package. Reinstall the package using the following command in the NuGet Package Manager Console:

Update-Package Microsoft.Bcl.Async -reinstall

You will be prompted to restart Visual Studio to complete the installation.

Send feedback about...

Google Drive Activity
Need help? Visit our support page.