4

I have two methods. One is to read data from Google Sheets and the other is to add a value to a single cell (But I actually want to append data to the last row but, I'm gonna start with just 1 record first). The btnLoadAttendance works perfectly but when I input something in the textbox1.Text, in the "UpdateValuesResponse result2 = update.Execute();" I get an error like so:

Request had insufficient authentication scopes. [403]

I found an answer here "Request had insufficient authentication scopes [403] when update cell spreadsheet" that says about commenting some lines. I tried commenting that line but it doesn't work for me. I still get the same error. Below is my code:

WORKING

private void btnLoadAttendance_Click(object sender, EventArgs e)
    {
            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/sheets.googleapis.com-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);
            }

            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            String spreadsheetId = "1b64mhUgdeRzGyJF4NfAPhkFY7br3c0o9rJ9mMnDBTR8";
            String range = "Sheet1!A2:D";
            SpreadsheetsResource.ValuesResource.GetRequest request =
                    service.Spreadsheets.Values.Get(spreadsheetId, range);

            ValueRange response = request.Execute();
            IList<IList<Object>> values = response.Values;
            if (values != null && values.Count > 0)
            {
                foreach (var x in values)
                {

                    dgvAttendance.Rows.Add(x[0], x[1], x[2], x[3]);
                }
            }
            else
            {
                MessageBox.Show("No data found.");
            }
        }

NOT WORKING

private void btnAddData_Click(object sender, System.EventArgs e)
        {
            string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
            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/sheets.googleapis.com-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);
            }

            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            String spreadsheetId = "1b64mhUgdeRzGyJF4NfAPhkFY7br3c0o9rJ9mMnDBTR8/edit";
            String range = "Sheet1!F5"; // update the F5 cell

            //ValueRange response = request.Execute();
            ValueRange valueRange = new ValueRange();
            valueRange.MajorDimension = "COLUMNS"; //Rows or Columns

            var oblist = new List<object>() { textBox1.Text };
            valueRange.Values = new List<IList<object>> { oblist };

            SpreadsheetsResource.ValuesResource.UpdateRequest update =
                service.Spreadsheets.Values.Update(valueRange, spreadsheetId, range);
            update.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
            UpdateValuesResponse result2 = update.Execute();
        }

You help is very much appreciated.

Community
  • 1
  • 1
Ibanez1408
  • 4,550
  • 10
  • 59
  • 110

2 Answers2

5
  1. Firstly delete the credentials files .credentials/sheets.googleapis.com-dotnet-quickstart.json stored at c:\user\Documents.credentials.
  2. Change the scope variable used for reading cells from Google Spreadsheets from

    string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly }; to

    static string[] Scopes = { SheetsService.Scope.Spreadsheets };

  3. After execution of code, API will authenticate again and then issue will be resolved.
Fahad Naeem
  • 515
  • 7
  • 15
3

I just needed to change:

string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };

to

static string[] Scopes = { SheetsService.Scope.Spreadsheets };

and it took me all day!

Ishaan Javali
  • 1,711
  • 3
  • 13
  • 23
Ibanez1408
  • 4,550
  • 10
  • 59
  • 110