googleworkspace / dotnet-samples Goto Github PK
View Code? Open in Web Editor NEW.NET samples for Google Workspace APIs
License: Apache License 2.0
.NET samples for Google Workspace APIs
License: Apache License 2.0
I have used Dot net WCF service to the read-write event in google calendar. the code works fine when service running in dot net solution. but not read-write event after hosting wcf service.
I have call google calendar API in my service. Please let me know anyone has the idea about issue
I'm trying to create a token using a JSON service account private key file, using the sample code provided to only save the token to a file, but the GoogleWebAuthorizationBroker is looking for a client_secret inside the downloaded JSON file (which isn't included in the JSON).
{
"type": "service_account",
"project_id": "endpoint-a1234567",
"private_key_id": "abc1234567",
"private_key": "-----BEGIN PRIVATE KEY-----\n#####-----END PRIVATE KEY-----\n",
"client_email": "email",
"client_id": "123456789",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/endpointuser%40endpoint-a1234567.iam.gserviceaccount.com"
}
Error:
At least one client secrets (Installed or Web) should be set
Source Code:
using System;
using System.IO;
using System.Threading;
using Google.Apis.Admin.Directory.directory_v1;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/admin-directory_v1-dotnet-quickstart.json
static string[] Scopes = { DirectoryService.Scope.AdminDirectoryDeviceChromeos };
static string ApplicationName = "TokenStore";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "client_secret.json"), FileMode.Open, FileAccess.Read))
{
string credPath = AppDomain.CurrentDomain.BaseDirectory;
credPath = Path.Combine(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);
}
}
}
(Please search existing issues before creating a new one.)
Sample Name:
.NET Quickstart
Run the example
System.AggregateException:
-HttpRequestException: An error occurred while sending the request.
-WebException: Error en el servidor remoto: (407) Se requiere autenticación del proxy.
This happens in line 31 ("credential = GoogleWebAuthorizationBroker.AuthorizeAsync(...")
https://developers.google.com/gmail/api/quickstart/dotnet
request is null on uploading while downloading is ok (so service is also ok) in a code like this
using (var stream = new FileStream(_uploadFile, FileMode.Open))
{
var fileMetadata = new File()
{
Name = "My Report",
MimeType = "application/vnd.google-apps.unknown"
};
request = service.Files.Create(fileMetadata, stream, "text/csv");
request.Fields = "id";
request.Upload(); // "/upload/drive/v3/files"
}
request.ResponseBody.Dump(); // result is null
(Please search existing issues before creating a new one.)
Sample Name:
Trying to run code using "dotnet SheetsMagic.dll"
When running in Visual Studio everything works fine.
When running the build .dll's Commands that do not require Google Authentication work fine. Commands that do require google authentication do not.
The code does not execute anything that requires google authentication.
When moving files around as well I couldn't get it to work, (perhaps I didn't move the authentication stuff to the right area?)
Should read the information from the sheet
Get an invalid URL error - Always crashes at ValueRange response = request.Execute();
An exception of type 'Google.GoogleApiException' occurred in System.Private.CoreLib.dll but was not handled in user code<TITLE>Bad Request</TITLE>
Bad Request - Invalid URL
HTTP Error 400. The request URL is invalid.
` SheetsService service = new(new BaseClientService.Initializer()
{
ApplicationName = ApplicationName,
ApiKey = API_KEY,
HttpClientFactory = new ProxySupportedHttpClientFactory(),
});
String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
String range = "Class Data!A2:E";
SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, range);
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
ValueRange response = request.Execute();
IList<IList<Object>> values = response.Values;
if (values != null && values.Count > 0)
{
Console.WriteLine("Name, Major");
foreach (var row in values)
{
// Print columns A and E, which correspond to indices 0 and 4.
Console.WriteLine("{0}, {1}", row[0], row[4]);
}
}
else
{
Console.WriteLine("No data found.");
}
Console.Read();`
using Google.Apis.Auth.OAuth2;
this and which such it, doesn't work for me!?
how can i add library to it to make it work???
note*
i already have Nuget.org Library in my Visual Studio
Every time I run the console application, the port on the URL that is accessing the Google OAuth page changes.
I get the following error:
The redirect URI in the request, http://127.0.0.1:58639/authorize/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs
How can I keep the port consistent every time I run the app?
I have not a realy problem, but a bug in my head???
I start the Calendar sample ap with my Google "credentials.json" file...
Then i debug die sample via Visual Studio 2019
I bekom the Error/Question/Hint:
Google hat diese App nicht überprüft
Die App möchte auf vertrauliche Daten in Ihrem Google-Konto zugreifen. Verwenden Sie diese App erst, wenn der Entwickler ...
What must i change in my Google Account?
I found no point for this :-(
I think it is very easy...?!?!?!?!
Best Regards
Bernd
How could I verify if an events exists before insert?
(Please search existing issues before creating a new one.)
Sample Name:
Quickstart
Has to sign in through the code
Get the warning
I'm expecting to receive a list of my tasks
**However my console returns the following:
"Credential file saved to: token.json
Task Lists:
My Tasks (MDU5OTgwNTEzMDU3ODkwODAxMjU6MDow)"**
Please help, how to fix this?
Improved error messages.
An exception with a generic message is thrown:
Google.GoogleApiException: 'Google.Apis.Requests.RequestError Invalid resource id value. [400] Errors [Message[Invalid resource id value.] Location[ - ] Reason[invalid] Domain[global]
Sample Name:
https://developers.google.com/drive/api/v3/quickstart/dotnet
foreach (MessagePart p in emailInfoResponse.Payload.Parts)
{
if (p.MimeType == "text/html")
{
byte[] data = FromBase64ForUrlString(p.Body.Data);
string decodedString = Encoding.UTF8.GetString(data);
}
}
Exception:
An unhandled exception of type 'System.NullReferenceException' occurred in Gmail.exe
Additional information: Object reference not set to an instance of an object.
The docs here https://developers.google.com/admin-sdk/reports/v1/quickstart/dotnet say click on "Enable The Reports API" and in a resulting diaglog you can download the Client Confioguration and save it as credentials.json.
When I click on the button it says "Something went wrong. Please try again." with no further information (chomre tools don't show anything extra). The API is enabled already and I have credentials for it. I don't know the schema of the credentials.json file so not sure what to do next.
I don't have another Gsuite account so unable to test in another account.
See screenshot:
https://www.screencast.com/t/UxhrdyBbm5j
i have followed below documentation to create event in google calendar
https://developers.google.com/calendar/quickstart/dotnet
but while click on "Enable the calendar API" button in above url
its asking to create new project.
with already existing project how to DOWNLOAD CLIENT CONFIGURATION
I have created a project in console.developers.google.com to use Google Calendar API. there we need to generate credential and select application type
For Localhost and application type other following is the Json which works fine.
{
"installed": {
"client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
"project_id": "xxxxxx-00000",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "xxxxxxxxxxxx",
"redirect_uris": [ "urn:ietf:wg:oauth:2.0:oob", "http://localhost" ]
}
}
And for Application type Web Application to Host on Server Few parameters has different Values in Json as shown below.
{
"web": {
"client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
"project_id": "xxxxxxxx-99999",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "xxxxxxxxxxxxxxxxxxxxxxx",
"redirect_uris": [ "http://demo.mydemo.com" ],
"javascript_origins": [ "http://demo.mydemo.com" ]
}
}
Can anyone help me to solve this issue?
Error is as follows
System.AggregateException: One or more errors occurred. ---> System.NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=xxxxxxxxxxxx-vqi4faduqgcpt3d2ruv53ltgr0rkgfsb.apps.googleusercontent.com&redirect_uri=http:%2F%2Flocalhost:53998%2Fauthorize%2F&scope=https:%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar" for authorization. See inner exception for details. ---> System.ComponentModel.Win32Exception: Access is denied
at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.d__8.MoveNext()
--- End of inner exception stack trace ---
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.<AuthorizeAsync>d__8.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__4.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__1.MoveNext() --- End of inner exception stack trace --- at System.Threading.Tasks.Task
1.GetResultCore(Boolean waitCompletionNotification)
at KriyaCRM.Controllers.ActivitiesController.GetCalendarConnection(Activities objact, String Operation)
---> (Inner Exception #0) System.NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=430760523223-vqi4faduqgcpt3d2ruv53ltgr0rkgfsb.apps.googleusercontent.com&redirect_uri=http:%2F%2Flocalhost:53998%2Fauthorize%2F&scope=https:%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar" for authorization. See inner exception for details. ---> System.ComponentModel.Win32Exception: Access is denied
at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.d__8.MoveNext()
--- End of inner exception stack trace ---
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__1.MoveNext()<---
--> Important Link related to API : https://www.codeproject.com/Articles/1183150/Securing-ASP-NET-Web-API-using-Custom-Token-Based <--
Find and Install mentioned packages by NuGet
Can't find the mentioned packages by NuGet
Raise an exception or continue execution when browser or tab browser is closed without typing Sign In credentials
GoogleWebAuthorizationBroker.AuthorizeAsync(...).Result is blocked indefinitely
1. Execute https://developers.google.com/calendar/quickstart/dotnet code as is.
2. When Sign In page appears, close tab. Code remains blocked
3. When Sign In page appears, close browser. Code remains blocked
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
I have read client_secrect.json and return Stream is OK.
But untill credentiall is null
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(streamFile).Secrets, Scopes, "user", CancellationToken.None,null);
(Please search existing issues before creating a new one.)
Sample Name:
It should upload number of records irrespective of the count.
after the records count increases it showing the error.
Failed to validate the config schema at '.github/sync-repo-settings.yaml': [
{
"instancePath": "/permissionRules/1/permission",
"schemaPath": "#/properties/permissionRules/items/properties/permission/enum",
"keyword": "enum",
"params": {
"allowedValues": [
"pull",
"push",
"admin"
]
},
"message": "must be equal to one of the allowed values"
}
]
Schema can be found at https://github.com/googleapis/repo-automation-bots/blob/main/packages/sync-repo-settings/src/schema.json
This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.
These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.
adminSDK/directory/AdminSDKDirectoryQuickstart/AdminSDKDirectoryQuickstart.csproj
Google.Apis.Admin.Directory.directory_v1 1.57.0.2721
adminSDK/groups-settings/AdminSDKGroupsSettingsQuickstart/AdminSDKGroupsSettingsQuickstart.csproj
Google.Apis.Groupssettings.v1 1.57.0.2366
adminSDK/reports/AdminSDKReportsQuickstart/AdminSDKReportsQuickstart.csproj
Google.Apis.Admin.Reports.reports_v1 1.57.0.2532
adminSDK/reseller/AdminSDKResellerQuickstart/AdminSDKResellerQuickstart.csproj
Google.Apis.Reseller.v1 1.57.0.2501
appsScript/AppsScriptApiExecute/AppsScriptApiExecute.csproj
Google.Apis.Script.v1 1.57.0.2638
Google.Apis.Auth 1.57.0
calendar/CalendarQuickstart/CalendarQuickstart.csproj
Google.Apis.Calendar.v3 1.57.0.2696
classroom/ClassroomQuickstart/ClassroomQuickstart.csproj
Google.Apis.Classroom.v1 1.57.0.2639
classroom/snippets/ClassroomSnippets/ClassroomSnippets.csproj
Google.Apis.Classroom.v1 1.57.0.2639
Google.Apis.Auth 1.57.0
classroom/snippets/ClassroomSnippetsTest/ClassroomSnippetsTest.csproj
coverlet.collector 3.1.2
NUnit3TestAdapter 4.2.1
NUnit 3.13.3
Microsoft.NET.Test.Sdk 17.2.0
Google.Apis.Classroom.v1 1.57.0.2639
Google.Apis.Auth 1.57.0
docs/DocsQuickstart/DocsQuickstart.csproj
Google.Apis.Docs.v1 1.57.0.2716
drive/DriveQuickstart/DriveQuickstart.csproj
Google.Apis.Drive.v3 1.57.0.2684
drive/activity-v2/DriveActivityQuickstart/DriveActivityQuickstart.csproj
Google.Apis.DriveActivity.v2 1.57.0.2269
drive/snippets/drive_v2/DriveV2Snippets/DriveV2Snippets.csproj
Google.Apis.Drive.v2 1.57.0.2684
Google.Apis.Auth 1.57.0
drive/snippets/drive_v2/DriveV2SnippetsTest/DriveV2SnippetsTest.csproj
coverlet.collector 3.1.2
NUnit3TestAdapter 4.2.1
NUnit 3.13.2
Microsoft.NET.Test.Sdk 17.2.0
Google.Apis.Drive.v2 1.57.0.2663
drive/snippets/drive_v3/DriveV3Snippets/DriveV3Snippets.csproj
Google.Apis.Drive.v3 1.57.0.2684
drive/snippets/drive_v3/DriveV3SnippetsTest/DriveV3SnippetsTest.csproj
coverlet.collector 3.1.0
NUnit3TestAdapter 4.0.0
NUnit 3.13.2
Microsoft.NET.Test.Sdk 16.11.0
Google.Apis.Drive.v3 1.57.0.2663
gmail/GmailQuickstart/GmailQuickstart.csproj
Google.Apis.Gmail.v1 1.57.0.2650
sheets/SheetsQuickstart/SheetsQuickstart.csproj
Google.Apis.Sheets.v4 1.57.0.2713
slides/SlidesQuickstart/SlidesQuickstart.csproj
Google.Apis.Slides.v1 1.57.0.2650
tasks/TasksQuickstart/TasksQuickstart.csproj
Google.Apis.Tasks.v1 1.57.0.2384
vault/VaultQuickstart/VaultQuickstart.csproj
Google.Apis.Vault.v1 1.57.0.2669
Sample Name: VPA
Show VPA application name in Sign In broser page
Showing Quickstart application name
Execute https://developers.google.com/calendar/quickstart/dotnet code as is
Name: Unable to fetch tokens once User accept the Consent on OAuth screen. "Hmmm... cannot reach this page" error is shown.
Earlier this was working and now It has stopped working I am not sure if anything has been modified.
User should be able to allow the app to access Sheets, and No exception should be thrown.
Follow steps as per article
https://developers.google.com/sheets/api/quickstart/dotnet
Install-Package : Unable to find package 'Google.Apis.Calendar.v3' at source ''
Install Package successfully
Cannot find the GG Calendar API in Package Manager Console
Install-Package : Unable to find package 'Google.Apis.Calendar.v3' at source ''.
At line:1 char:1
+ CategoryInfo : NotSpecified: (:) [Install-Package], Exception
+ FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
Time Elapsed: 00:00:05.6152905
After a valid Sign In, tab browser or browser it self should be closed. If Api opens a tab, Api should close it or provide another mechanism for Sig In not based on browser
After a valid Sign In tab browser or browser it self is not closed and a ugly text appears (see attachment)
Browsers: Edge (from Win10 v10.0.17134.286), Firefox 62
.NET version: 4.7
OS (Mac/Linux/Windows): Windows
I have a vue
based app. On click of a button, i would like to make a call to google classroom api. But it doesn't seem to be the secure way since we need to store credentials.json, token.json files in browser.
dotnet-samples are concentrated on Console app. But no enterprise application uses console apps. So i suggest put up some sample Web API sample, SPA sample etc.
(Please search existing issues before creating a new one.)
Sample Name:
Within any of the Google Sheets API Quickstart docs, such as the one for .net, during step 1 there is no option to "DOWNLOAD CLIENT CONFIGURATION" as it states. The dialog is as follows (screenshot): https://i.imgur.com/GtKS30g.png. The dialog is the same for each language.
I don't see another way to download the credentials.json
file, nor do I see an example of what it should look like to create myself. Is this an error? Should there be a link to download the credentials.json
file?
I have a Problem connecting my .NET C# Application with Google Calendar using the Google.Apis.Calendar.v3 NuGet Package.
If I use the Code provided by the .NET example given by Google, I get two errors.
The example on the Google page: https://developers.google.com/calendar/quickstart/dotnet
The error occurred in the following code section after authenticating on the opened web page.
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result;
Error One:
InvalidOperationException: The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set.
Error Two:
ArgumentException: '"UTF-8"' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Full Code:
https://pastebin.com/1v7C3s66
The Application also creates a folder named token.json and not a token json file.
Is this the problem?
What should I do?
Hey guys, I followed the steps to execute the sample code and I'm getting an error surrounding the "client_secret.json"
"Could not find file 'C:\Googel Calendar App\Google Calendar\Google Calendar\bin\Debug\client_secret.json'.":"C:\Googel Calendar App\Google Calendar\Google Calendar\bin\Debug\client_secret.json"
Any advice on this would be greatly appreciated.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.