I'm developing an application wich needs to access a "simple database" (google spreadsheet) with users IDs.
I try with Oauth2.0 But that's not what I need.
I'm using this code to get access to the sheet:
private static SheetsService AuthorizeGoogleApp()
{
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);
}
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
return service;
}
But with this code the C# application open a browser to ask the user to login in his google account.
I need to have access via API, so it will be transparent to the user.
I already have the api key, but I don't know how to use and I don't find any documentation on Google sites.
Can you help me with some kind of example to read a simple column?
Thanks in advance!
Here is the documentation for the API.
It also covers authorization.
Related
When i run my local MVC project show me error like this
Access blocked: GoogleDriveRestAPI_v3’s request is invalid
my code MVC code is here use in Models folder
`
public static DriveService GetService()
{
//get Credentials from client_secret.json file
UserCredential credential;
using (var stream = new FileStream(#"D:\client_secret.json", FileMode.Open, FileAccess.Read))
{
String FolderPath = #"D:\";
String FilePath = Path.Combine(FolderPath, "DriveServiceCredentials.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(FilePath, true)).Result;
}
//create Drive API service.
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "GoogleDriveRestAPI-v3",
});
return service;
}
`
when run credential its show error like mention in image
i use google cloud side generated secret client file like this
show allow access google drive to uploading file.
I'm using Google Sheet API V4 in C#.
My source will create new Excel file, write data to that file.
When execute, Google API will open a new OAuth tab on the browser, User will choose/login to an email on this tab, and grant Read/Write/All permission for my App.
My question is: How can I get Logged/permitted email address in C# source?
I want to know, what email did the user log in to create myfile.xlsx.
Thanks in advance.
Code snippet:
string[] Scopes = { SheetsService.Scope.DriveFile };
string ApplicationName = "Google Sheets API";
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,
"UserName",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
var fileName = "myfile.xlsx";
var myNewSheet = new Spreadsheet();
myNewSheet.Properties = new SpreadsheetProperties();
myNewSheet.Properties.Title = fileName;
var sheet = new Sheet();
sheet.Properties = new SheetProperties();
sheet.Properties.Title = $"data";
myNewSheet.Sheets = new List<Sheet>() { sheet };
var newSheet = service.Spreadsheets.Create(myNewSheet).Execute();
var spreadSheetId = newSheet.SpreadsheetId;
...........
// Write data to file source
Google Indentiy platform describes the procedure of how to authenticate a user to obtain user information and more specifically user profile information
The documentation does not specify how exactly to do it in C#, but basically
Make a GET request to https://www.googleapis.com/oauth2/v3/userinfo
Provide the scopes https://www.googleapis.com/auth/userinfo.profile and https://www.googleapis.com/auth/userinfo.email
There is a good sample on Stackoverflow how to do it in PHP - I hope it helps you with the implementation in C#
There is also a workaround authenticating users with Gmail
I was trying to implement google calender event sync functionality to schedule event from my local application to google calendar. its working fine in local system but whenever I deployed it on server, it throws the following error.
System.UnauthorizedAccessException: Access to the path 'Google.Apis.Auth' is denied
Below is the code which I am using for same.
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "xxx-9khdjsqifkj2amsji2jce37p8lfn0166.apps.googleusercontent.com",
ClientSecret = "ZdsrCa-uwG3GmpVLTfYDli-S",
},
new[] { CalendarService.Scope.Calendar },
"user",
CancellationToken.None).Result;
// Create the service.
var service = new CalendarService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = Summary,
});
By default the Google .Net client library uses FileDatastore() file datastore by default stores the credentials in %appData%. When you run your application under what ever user it is you are running you don't apperntly have access to %appData%
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "xxx4671204-9khdjsqifkj2amsji2jce37p8lfn0166.apps.googleusercontent.com",
ClientSecret = "ZdsrCa-uwG3GmpVLTfYDli-S",
},
new[] { CalendarService.Scope.Calendar },
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Make sure that credPath is some place that you have access to write to. I have a sample on GitHub for Google calendar Oauth2 and I have a tutorial on how filedatastore works FileDatastore demystified
I have created an Alexa skill and enabled account linking. Setup my skills configuration to point to googles authorization and token servers, the skill successfully links. Then alexa sends POST Requests to my service that include the access token and state from Google. I use this to validate the token and what I want to do is use the token to access gmail api and begin calling actions.
However, the only examples online I can find include re-building the gmailservice by using the client secret and client id again. I figure since I have the access token already, why do I need to include the secret and ID again? How can i make gmail api calls with the access token I already have, or is this not possible? Here's the code I'm trying to use:
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);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");
// List labels.
IList<Label> labels= request.Execute().Labels;
Console.WriteLine("Labels:");
if (labels != null && labels.Count > 0)
{
foreach (var labelItem in labels)
{
Console.WriteLine("{0}", labelItem.Name);
}
}
else
{
Console.WriteLine("No labels found.");
}
Console.Read();
I don't want to include the client_secret.json file because I already was authorized by google's oauth process in the alexa skill's account linking. Help ?
I've seen;
Accessing Google Spreadsheets with C# using Google Data API
and
http://code.google.com/apis/spreadsheets/data/2.0/developers_guide_dotnet.html#CreatingRows
However i'm still having trouble inserting a new row in to an existing google spread sheet. Does anyone have a canned example which inserts a List<string> for example in to new row in a spreadsheet workbook.
Many thanks,
Use GDataDB http://github.com/mausch/GDataDB
GDataDB provides a simple way to insert .net POCO entities in to a google spread sheet.
public void AddToGoogle()
{
var client = new DatabaseClient(Settings.Default.GmailAccount, Settings.Default.GmailPassword);
string dbName = Settings.Default.WorkBook;
var db = client.GetDatabase(dbName) ?? client.CreateDatabase(dbName);
string tableName = Settings.Default.WorkSheet;
var t = db.GetTable<ActivityLog>(tableName) ?? db.CreateTable<ActivityLog>(tableName);
var all = t.FindAll();
t.Add(this);
}
This Services from Google are discontinued and now they came up with another one named Google.Apis.Sheets.v4 services.
so the above code will not work now a days, I have already tried.
And find something that worked out for me.
I have written a blog and shared the whole source code there. Check it out.
private static SheetsService AuthorizeGoogleApp()
{
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);
}
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
return service;
}
For the entire source code check it out. Insert new row to Google Sheet using Google.Apis.Sheets.V4 Services