.NET Quickstart

Complete the steps described in the rest of this page, and in about five minutes you'll have a simple .NET console application that makes requests to the Google Apps Script Execution API.

Prerequisites

To run this quickstart, you'll need:

  • Visual Studio 2013 or later.
  • Access to the internet and a web browser.
  • A Google account with Google Drive enabled.
  • A target Apps Script to call with the API.

Step 1: Turn on the Google Apps Script Execution API

  1. Open your target Apps Script in the editor and select Resources > Cloud Platform project.
  2. In the dialog that opens, click on the blue link (that starts with your script's name) at the top to open the console project associated with your script.
  3. The left sidebar should say API Manager. If it does not, click the icon in the upper-left to open a side panel and select API Manager. Select Library in the left sidebar.
  4. In the search bar under the Google APIs tab, enter "Google Apps Script Execution API". Click the same name in the list that appears. In the new tab that opens, click Enable API.
  5. Click Credentials in the left sidebar.
  6. Select the Credentials tab, click the Create credentials button and select OAuth client ID.
  7. Select the application type Other, enter the name "Google Apps Script Execution API Quickstart", and click the Create button.
  8. Click OK to dismiss the resulting dialog.
  9. Click the file_download (Download JSON) button to the right of the client ID.
  10. Move this file to your working directory and rename it client_secret.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.Script.v1

Step 3: Set up the sample

  1. Drag client_secret.json (downloaded in Step 1) into your Visual Studio Solution Explorer.
  2. Select client_secret.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:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Script.v1;
using Google.Apis.Script.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ScriptQuickstart
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/script-dotnet-quickstart.json
        static string[] Scopes = { "https://www.googleapis.com/auth/drive" };
        static string ApplicationName = "Google Apps Script Execution API .NET Quickstart";

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

            using (var stream =
                new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/script-dotnet-quickstart.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 Apps Script Execution API service.
            string scriptId = "ENTER_YOUR_SCRIPT_ID_HERE";
            var service = new ScriptService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

            // Create an execution request object.
            ExecutionRequest request = new ExecutionRequest();
            request.Function = "getFoldersUnderRoot";

            ScriptsResource.RunRequest runReq =
                    service.Scripts.Run(request, scriptId);

            try
            {
                // Make the API request.
                Operation op = runReq.Execute();

                if (op.Error != null)
                {
                    // The API executed, but the script returned an error.

                    // Extract the first (and only) set of error details
                    // as a IDictionary. The values of this dictionary are
                    // the script's 'errorMessage' and 'errorType', and an
                    // array of stack trace elements. Casting the array as
                    // a JSON JArray allows the trace elements to be accessed
                    // directly.
                    IDictionary<string, object> error = op.Error.Details[0];
                    Console.WriteLine(
                            "Script error message: {0}", error["errorMessage"]);
                    if (error["scriptStackTraceElements"] != null)
                    {
                        // There may not be a stacktrace if the script didn't
                        // start executing.
                        Console.WriteLine("Script error stacktrace:");
                        Newtonsoft.Json.Linq.JArray st =
                            (Newtonsoft.Json.Linq.JArray)error["scriptStackTraceElements"];
                        foreach (var trace in st)
                        {
                            Console.WriteLine(
                                    "\t{0}: {1}",
                                    trace["function"],
                                    trace["lineNumber"]);
                        }
                    }
                }
                else
                {
                    // The result provided by the API needs to be cast into
                    // the correct type, based upon what types the Apps
                    // Script function returns. Here, the function returns
                    // an Apps Script Object with String keys and values.
                    // It is most convenient to cast the return value as a JSON
                    // JObject (folderSet).
                    Newtonsoft.Json.Linq.JObject folderSet =
                            (Newtonsoft.Json.Linq.JObject)op.Response["result"];
                    if (folderSet.Count == 0)
                    {
                        Console.WriteLine("No folders returned!");
                    }
                    else
                    {
                        Console.WriteLine("Folders under your root folder:");
                        foreach (var folder in folderSet)
                        {
                            Console.WriteLine(
                                "\t{0} ({1})", folder.Value, folder.Key);
                        }
                    }
                }
            }
            catch (Google.GoogleApiException e)
            {
                // The API encountered a problem before the script
                // started executing.
                Console.WriteLine("Error calling API:\n{0}", e);
            }
            Console.Read();
        }
    }
}
Be sure to also replace the placeholder ENTER_YOUR_SCRIPT_ID_HERE with the script ID of your target script.

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...

Apps Script
Apps Script