Trying to write to google sheets from .NET .
Got exception:
An unhandled exception of type 'Google.GoogleApiException' occurred in mscorlib.dll
Additional information: Google.Apis.Requests.RequestError
Request had insufficient authentication scopes. [403]
Errors [
Message[Request had insufficient authentication scopes.] Location[ - ] Reason[forbidden] Domain[global]
]
Analog function with read works fine. Credentials are created and google sheets API is enabled. I don't see any settings while create credentials regarding read/write. Spreadsheet is shared for everyone read/write. How to solve this problem?
static void UpdateEntry()
{
string spreadsheetId = "1IAD2okAWZD7anbt5L4ybgD2dxHBGmsY6IkNIWHBQkBM";
string ApplicationName = "myapp";
UserCredential credential;
using (var stream = new FileStream("credentials_1.json", FileMode.Open, FileAccess.Read))
{
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 Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
String range = "new first sheet!A1";
//var range = "{sheet}!D543";
var valueRange = new ValueRange();
var oblist = new List<object>() { "updated" };
valueRange.Values = new List<IList<object>> { oblist };
var updateRequest = service.Spreadsheets.Values.Update(valueRange, spreadsheetId, range);
updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
var appendReponse = updateRequest.Execute();
}
Related
I wanna get all playlists of a channel
all settings works on API explorer but when I try it in the client it not working
other things of youtube data api3 like channel and playlistitems working, my problem is just with playlist.list
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows for full read/write access to the
// authenticated user's account.
new[] { YouTubeService.Scope.Youtube },
"user",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
var channelVids = youtubeService.Playlists.List("snippet");
channelVids.Id = "UCIabPXjvT5BVTxRDPCBBOOQ";
//channelVids.Fields = "items(id,snippet(description,publishedAt,thumbnails/default/url,title)),nextPageToken";
channelVids.MaxResults = 25;
var results = await channelVids.ExecuteAsync();
Console.WriteLine(results.Items.Count + " lists");
I found my solution
it was just a typo
channelVids.Id = "UCIabPXjvT5BVTxRDPCBBOOQ";
to
channelVids.ChannelId = "UCIabPXjvT5BVTxRDPCBBOOQ";
Below is the code I use to obtain the data from my spreadsheet. This works if I am logged into google+, but that isn't the intention, as I want users to access the data through this application.
When I build and provide the files to a user on another PC, it doesn't even start the application, on my own, it can at least start
String myUrl =
"http://nofile.io/g/[REDACTED]/client_secret.json";
WebClient client = new WebClient(); {
client.DownloadFile(myUrl, "\\client_secret.json");
}
UserCredential credential;
using (var stream =
new FileStream("\\client_secret.json", FileMode.Open, FileAccess.Read)) {
string credPath = Environment.GetFolderPath(
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);
}
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer {
HttpClientInitializer = credential,
ApplicationName = ApplicationName
});
// Define request parameters.
String spreadsheetId = "1uLxm0jvmL1_FJNYUJp6YqIezzqrZdjPf2xQGOWYd6ao";
String range = "TestSheet!A1:F";
SpreadsheetsResource.ValuesResource.GetRequest request =
service.Spreadsheets.Values.Get(spreadsheetId, range);
File.Delete("\\client_secret.json");
I'm trying to send emails based on Gmail API. I have created a project in Google Develover Console.
I referred to GmailService instance: https://developers.google.com/gmail/api/quickstart/dotnet
And here’s the code that sent an email:
var msg = new AE.Net.Mail.MailMessage { Subject = "Your Subject", Body = "Hello, World, from Gmail API!", From = new MailAddress("[you]#qq.com") }; msg.To.Add(new MailAddress("yourbuddy#qq.com"));
msg.ReplyTo.Add(msg.From); // Bounces without this!!
var msgStr = new StringWriter();
msg.Save(msgStr);
string[] Scopes = { GmailService.Scope.GmailSend };
string ApplicationName = "Gmail API .NET Quickstart";
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/gmail-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 gmail = new GmailService(new Google.Apis.Services.BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, });
var result = gmail.Users.Messages.Send(new Google.Apis.Gmail.v1.Data.Message { Raw = Base64UrlEncode(msgStr.ToString()) }, "user").Execute();
But I'm only getting this:
An unhandled exception of type 'Google.GoogleApiException' occurred in
Google.Apis.dll Additional information:
Google.Apis.Requests.RequestError Bad Request [400]
Errors [
Message[Bad Request] Location[ - ] Reason[failedPrecondition]
Domain[global]
]
Any idea what is wrong? Thanks!
I am trying to create new folder MY_FOLDER in Google Drive using Drive API, using the quick starter example and adding more to it as I read through the https://developers.google.com/drive/v3/web/quickstart/dotnet.
My scope is set as:
static string[] Scopes = { DriveService.Scope.DriveFile };
And I create service like this
private static void CreateService()
{
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.ReadWrite))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/drive-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 Drive API service.
service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
As per example on this page [https://developers.google.com/drive/v3/web/folder], 2, I am creating new folder
var fileMetadata = new File()
{
Name = "MY_FOLDER",
MimeType = "application/vnd.google-apps.folder"
};
var request = driveService.Files.Create(fileMetadata);
request.Fields = "id";
var file = request.Execute();
Console.WriteLine("Folder ID: " + file.Id);
The error I get reads "Insufficient Permissions [403]"
UPDATE
I created credentials as described in same Google tutorial at https://developers.google.com/drive/v3/web/quickstart/dotnet
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.
Firstly delete the credentials files .credentials/sheets.googleapis.com-dotnet-quickstart.json stored at c:\user\Documents.credentials.
Change the scope variable used for reading cells from Google Spreadsheets from
string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
to
static string[] Scopes = { SheetsService.Scope.Spreadsheets };
After execution of code, API will authenticate again and then issue will be resolved.
I just needed to change:
string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
to
static string[] Scopes = { SheetsService.Scope.Spreadsheets };
and it took me all day!