2

I have successfully connected to my Google Sheet with my C# application using the Google Apps Script API. The connection works, but if I add the following lines:

PropertiesService.getScriptProperties().setProperty('projectName', pName);
PropertiesService.getScriptProperties().setProperty('projectManager', pManager);

To my Google Script, I get a 401 unauthorized error. What do I need to add to my scopes in order to set properties in the PropertiesService?

My current scope is:

static string[] Scopes = { "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets" };

C# code:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Script.v1;
using Google.Apis.Script.v1.Data;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.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 PPR
{
    class googleAPI
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/script-dotnet-quickstart.json
        static string[] Scopes = { "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets" };
        static string ApplicationName = "Google Apps Script Execution API .NET Quickstart";

        public googleAPI()
        {

    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 = "MPD2B-0a8Q2KsDHoHVPh1HVhXBvIk9FTo";
                var service = new ScriptService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });
     ExecutionRequest request = new ExecutionRequest();
                //request.Function = "updateGlobals";
                request.Function = "updateCells";
                //request.Function = "callWeeklyHours";
                request.DevMode = true;

                IList<object> values = new List<object>();
                values.Add("tempProj");
                values.Add("Brett");
                request.Parameters = values;

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

                try
                {
                    // Make the API request.
                    runReq.Execute();
                }
                catch (Google.GoogleApiException e)
                {
                    // The API encountered a problem before the script
                    // started executing.
                    Console.WriteLine("Error calling API:\n{0}", e);
                }
            }
        }
    }

Google Apps Script:

    function updateCells(projectName, projectManager)
    {    
      Logger.log(projectName + ', ' + projectManager);
      PropertiesService.getScriptProperties().setProperty('projectName', pName);
      PropertiesService.getScriptProperties().setProperty('projectManager', pManager);
}
abielita
  • 13,147
  • 2
  • 17
  • 59

2 Answers2

1

I had a problem using the PropertiesService myself, it was solved by adding the undocumented (!!!) scope: "https://www.googleapis.com/auth/script.storage". I wish they had documentation for all of these (I have seen this list, but it is far from complete, and is usually missing the scopes I actually need).

wulftone
  • 1,628
  • 1
  • 18
  • 34
0

One possible reason why you're getting this error is if you are using a deprecated authentication method for Google APIs.

Here's an example on how to save the data.

// Set multiple script properties in one call.
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperties({
  'cow': 'moo',
  'sheep': 'baa',
  'chicken': 'cluck'
});

This related thread might also help:

abielita
  • 13,147
  • 2
  • 17
  • 59