I was able to access the Google Calendar API using the .NET Quickstart tutorial and it worked great!
The problem with that tutorial is that it uses Open Authentication or OAuth2. I will like to do the same using Service Account Authentication.
(https://support.google.com/googleapi/answer/6158857?hl=en)
Can someone give me an example of how I can access my calendar using a Service account key file?
I have tried also tried using Google Calendar API Authentication with C# tutorial and was not able to accomplish it.
I am curious as to why your first attempt with the service account tutorial didn't work. What was wrong? Was there an error?
Remember service accounts are not you. The service account has its own Google calendar account, so if you are trying to read one of your "personal calendars", it will not work. You are going to have to share your personal calendar with the service account.
Here is another example using the Json service account key file.
string[] scopes = new string[] { CalendarService.Scope.Calendar };
GoogleCredential credential;
using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(scopes);
}
// Create the Calendar service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar Authentication Sample",
});
Try this. First Create a service account which can be found in your Google Dev Console.
For reference on implementation, check DalmTo's blogpost on how to use Service Accounts here.
Here's a snippet:
var certificate = new X509Certificate2(keyFile, "notasecret", X509KeyStorageFlags.Exportable);
try{
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
//Create the service.
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample"
});
return service;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
return null;
}
For anybody finding their way to this question but needing a NodeJS solution, this is how you can log in with a service account that has domain-wide delegation permissions as a specific user:
const auth = new google.auth.JWT({ // use JWT instead of GoogleAuth
subject: "me#mycompany.com", // specify subject (user whose context you want to operate in)
keyFile: "service-account-key.json",
scopes: [
"https://www.googleapis.com/auth/calendar.events",
"https://www.googleapis.com/auth/calendar.readonly"
],
})
visit this link have complete working project google service account authentication with google calendar event insert method you have to change your json private key and your Credentials only
https://github.com/CodeForget/Google-Service-Account-Authentication
here json key file othentication as well p12 authentication both
ServiceAccountAuthentication.cs
using Google.Apis.Calendar.v3;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Calendar.v3.Data;
namespace GoogleSamplecSharpSample.Calendarv3.Auth
{
public static class ServiceAccountExample
{
/// <summary>
/// Authenticating to Google calender using a Service account
/// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
/// </summary>
/// Both param pass from webform1.aspx page on page load
/// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com/projectselector/iam-admin/serviceaccounts </param>
/// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com/projectselector/iam-admin/serviceaccounts </param>
/// <returns>AnalyticsService used to make requests against the Analytics API</returns>
public static CalendarService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
{
try
{
if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
throw new Exception("Path to the service account credentials file is required.");
if (!File.Exists(serviceAccountCredentialFilePath))
throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
if (string.IsNullOrEmpty(serviceAccountEmail))
throw new Exception("ServiceAccountEmail is required.");
// For Json file
if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
{
GoogleCredential credential;
//using(FileStream stream = File.Open(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read, FileShare.None))
using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(scopes).CreateWithUser("xyz#gmail.com");//put a email address from which you want to send calendar its like (calendar by xyz user )
}
// Create the Calendar service.
return new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar_Appointment event Using Service Account Authentication",
});
}
else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
{ // If its a P12 file
var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
// Create the Calendar service.
return new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar_Appointment event Using Service Account Authentication",
});
}
else
{
throw new Exception("Something Wrong With Service accounts credentials.");
}
}
catch (Exception ex)
{
throw new Exception("Create_Service_Account_Calendar_Failed", ex);
}
}
}
}
add webform.aspx and put this code on webform.aspx.cs
using System;
using Google.Apis.Calendar.v3;
using GoogleSamplecSharpSample.Calendarv3.Auth;
using Google.Apis.Calendar.v3.Data;
namespace CalendarServerToServerApi
{
public partial class WebForm1 : System.Web.UI.Page
{
// create event which you want to set using service account authentication
Event myEvent = new Event
{
Summary = "Visa Counselling",
Location = "Gurgaon sector 57",
Start = new EventDateTime()
{
DateTime = new DateTime(2017, 10, 4, 2, 0, 0),
TimeZone = "(GMT+05:30) India Standard Time"
},
End = new EventDateTime()
{
DateTime = new DateTime(2017, 10, 4, 2, 30, 0),
TimeZone = "(GMT+05:30) India Standard Time"
}
//,
// Recurrence = new String[] {
//"RRULE:FREQ=WEEKLY;BYDAY=MO"
//}
//,
// Attendees = new List<EventAttendee>()
// {
// new EventAttendee() { Email = "Srivastava998#gmail.com" }
//}
};
protected void Page_Load(object sender, EventArgs e)
{
}
public void Authenticate(object o, EventArgs e)
{
string[] scopes = new string[] {
CalendarService.Scope.Calendar //, // Manage your calendars
//CalendarService.Scope.CalendarReadonly // View your Calendars
};
string cal_user = "calenderID#gamil.com"; //your CalendarID On which you want to put events
//you get your calender id "https://calendar.google.com/calendar"
//go to setting >>calenders tab >> select calendar >>Under calender Detailes at Calendar Address:
string filePath = Server.MapPath("~/Key/key.json");
var service = ServiceAccountExample.AuthenticateServiceAccount("xyz#projectName.iam.gserviceaccount.com", filePath, scopes);
//"xyz#projectName.iam.gserviceaccount.com" this is your service account email id replace with your service account emailID you got it .
//when you create service account https://console.developers.google.com/projectselector/iam-admin/serviceaccounts
insert(service, cal_user, myEvent);
}
public static Event insert(CalendarService service, string id, Event myEvent)
{
try
{
return service.Events.Insert(myEvent, id).Execute();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
}
}
Related
I am trying to update custom dimension fields(https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/customDimensions/update) in google analytics by calling the analytics api from C#.
I created a project in https://console.developers.google.com, added a service account(downloaded the .p12, private key file),enabled the analytics api and linked the service account email in https://analytics.google.com
I am able to read the "analytics data"(like account summaries etc) but not insert or update. When I try to do that, I get the Insufficient permission 403 error. The service account added to google analytics has all the privileges.
class Program
{
static void Main(string[] args)
{
test();
}
public static void test() //takes clientid as input
{
string[] scopes = new string[] { AnalyticsService.Scope.Analytics }; // view and manage your Google Analytics data
var keyFilePath = #"C:\Users\xyz\Desktop\CustomDimUpdate\xxxxxxxx.p12"; // Downloaded from https://console.developers.google.com
var serviceAccountEmail = "xxxx.iam.gserviceaccount.com"; // found https://console.developers.google.com
//loading the Key file
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
var service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
//ApplicationName = "Analytics API Sample",
});
CustomDimension body = new CustomDimension();
body.Name = "Configurable"; //Found in https://analytics.google.com
body.Scope = "Product"; //Found in https://analytics.google.com
body.Active = true;
try
{
//analytics.management().customDimensions()
// .update("123456", "UA-123456-1", "ga:dimension2", body).execute();
ManagementResource.CustomDimensionsResource.UpdateRequest update = service.Management.CustomDimensions.Update(body, "123456", "UA-123456-1", "ga:dimension1");
update.Execute(); //Errors out here
ManagementResource.AccountsResource.ListRequest list = service.Management.Accounts.List();
list.MaxResults = 1000; // Maximum number of Accounts to return, per request.
Accounts feed1 = list.Execute(); //Works perfectly fine
foreach (Account account in feed1.Items)
{
// Account
Console.WriteLine(string.Format("Account: {0}({1})", account.Name, account.Id));
}
ManagementResource.ProfilesResource.ListRequest list1 = service.Management.Profiles.List("123456", "UA-123456-1");
Profiles feed = list1.Execute();
foreach (Profile profile in feed.Items)
{
Console.WriteLine(string.Format("\t\tProfile: {0}({1})", profile.Name, profile.Id));
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
I was able to resolve this by changing the below line of code
string[] scopes = new string[] { AnalyticsService.Scope.Analytics }; // view and manage your Google Analytics data
to
string[] scopes = new string[] { AnalyticsService.Scope.AnalyticsEdit }; // view and manage your Google Analytics data
How do I specify an email address for GoogleCalendar API notifications?
I need to programatically manipulate my Google Calendar via the Google API using C# dot-net. I've been able to create, delete and modify events successfully, but I'd like some control over notifications. Currently only email and UI popup options are available, and email defaults to the Google email account.
What I'm thinking is that if I can manipulate the email address used, I can send email to my Verizon email-to-SMS address, and send a text message instead of email (SMS is an option only for Government accounts). Or possibly to a dummy email that interfaces to an SMS service like Twilio. Bottom line is I would like to send email notifications to one or more email addresses of my choosing.
The only option for email is in a constructor for an EventReminder override:
new EventReminder{Method="email",Minutes=60};
Here's my working code:
namespace stuff
{
class Program
{
static string[] Scopes = { CalendarService.Scope.Calendar };
static string ApplicationName = "Google Calendar API .NET Quickstart";
static string _Chelle = "fake_id#gmail.com";
static string _EventCalendar = "jwejq36jjgwijg54iw7yjs7j7e#group.calendar.google.com";
static void Main(string[] args)
{
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/calendar-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 Calendar API service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
EventsResource.ListRequest request = service.Events.List(_EventCalendar);
request.TimeMin = DateTime.Now;
request.TimeMax = DateTime.Now.AddDays(30);
request.ShowDeleted = false;
Events events = request.Execute();
if (events.Items != null && events.Items.Count > 0)
{
foreach (var eventItem in events.Items)
{
// add new reminders
eventItem.Reminders = new Event.RemindersData
{
UseDefault = false,
Overrides = new[]
{
new EventReminder {Method="popup",Minutes=((60*24*7) - (60*9)) }, // one week before # 0900
new EventReminder {Method="email",Minutes=((60*24*7) - (60*9)) }
}
};
try
{
service.Events.Update(eventItem, _EventCalendar, eventItem.Id).Execute();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Thread.Sleep(1000);
}
}
else
{
Console.WriteLine("No events found.");
}
Console.Read();
}
}
}
I created a google spreadsheet using Google API NET like below. I am receiving no exception and from code i was able to retrieve file id also. But when I look in google drive I am not seeing file. Is there some thing I should do to notify google drive. I did a refresh my drive too. But no use. Any idea?
I authenticated my service like below:
authenticate.cs
public class SerivceAccount
{
private const string ServiceAccountEmail = "182464555438-#developer.gserviceaccount.com";
private static readonly X509Certificate2 Certificate = new X509Certificate2("ADExpress.p12", "notasecret", X509KeyStorageFlags.Exportable);
readonly ServiceAccountCredential _credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(ServiceAccountEmail)
{
Scopes = new[]
{
"https://spreadsheets.google.com/feeds",
DriveService.Scope.Drive,
"https://www.googleapis.com/auth/drive.file"
}
}.FromCertificate(Certificate));
public bool Authenticate()
{
var isAuthenticated = false;
try
{
if (!_credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result)
throw new InvalidOperationException("Access token request failed.");
isAuthenticated = true;
}
catch (Exception e)
{
Console.WriteLine("Exception in Authenticating " + e.ToString());
}
return isAuthenticated;
}
public ServiceAccountCredential Credential
{
get { return _credential; }
}
}
main.cs
var account = new SerivceAccount();
if (account.Authenticate())
{
FilesResource.InsertRequest request = service.Files.Insert(new Google.Apis.Drive.v2.Data.File()
{
Title = "Test",
Description = "Test",
MimeType = "application/vnd.google-apps.spreadsheet"
});
var file = request.Execute();
Console.WriteLine("File ID: " + file.Id);
}
You are authenticating using a service account.
I did a refresh my drive too
Checking your own Google Drive web version will not show you the files that where created by a service account. Service account is its own user. Your file is probably being created on the service accounts Google Drive account you can test that by doing files.list
example:
/// <summary>
/// Retrieve a list of File resources.
/// </summary>
/// <param name="service">Drive API service instance.</param>
/// <returns>List of File resources.</returns>
public static List<File> retrieveAllFiles(DriveService service) {
List<File> result = new List<File>();
FilesResource.ListRequest request = service.Files.List();
do {
try {
FileList files = request.Execute();
result.AddRange(files.Items);
request.PageToken = files.NextPageToken;
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
request.PageToken = null;
}
} while (!String.IsNullOrEmpty(request.PageToken));
return result;
}
In order for another user to see the file you must grant them permission to see the file created by the service account.
Actually This helps to resolve my issue. I need to provide permissions to the file to be visible in UI interface. Hope this helps.
Permission newPermission = new Permission();
newPermission.Value = "yourdriveaccount#domain.com";
newPermission.Type = "user";
newPermission.Role = "reader";
service.Permissions.Insert(newPermission, file.Id).Execute();
Trying to get the hang of how to use google-admin-sdk in C# (got a possible job-opening)
I've managed to create code for creating users and adding a user to a group in Python 2.7 as commandline-tools.
But the employer asked med if I could do the same in C#. I think I would get the hang of it, but would appreciate some help on how to start.
I have installed Visual Studio Express 2012 for Desktop and downloaded:
google-admin-directory_v1-rev6-csharpp-1.4.0-beta.zip
google-api-dotnet-client-1.4.0-beta-samples.zip
google-api-dotnet-client-1.4.0-beta.zip
But I can't find any (for me understandble) samples.
Any one care to give me any good pointers? Would be very much appreciated. :)
/Jonas
Edit : Adding my code so far!
using System;
using System.Diagnostics;
using System.Linq;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Samples.Helper;
using Google.Apis.Services;
using Google.Apis.Util;
using Google.Apis.Admin.directory_v1;
using Google.Apis.Admin.directory_v1.Data;
namespace Bergstedts.ListUsers
{
public class Program
{
static void Main(string[] args)
{
// Display the header and initialize the sample.
CommandLine.EnableExceptionHandling();
CommandLine.DisplayGoogleSampleHeader("Lists all Users");
// Register the authenticator.
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = "my ID",
ClientSecret = "my secret"
};
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
// Create the service.
var service = new DirectoryService(new BaseClientService.Initializer()
{
Authenticator = auth,
ApplicationName = "List Users",
});
service.Users.List().Domain = "mydomain.com";
Users results = service.Users.List().Execute();
Console.WriteLine("Users:");
foreach (User list in results.UsersValue)
{
Console.WriteLine("- " + list.Name);
}
Console.ReadKey();
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { DirectoryService.Scopes.AdminDirectoryUser.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
}
}
Edit : Found how to add the domain :
service.Users.List().Domain = "mydomain.com";
But I still get the same error message :
An error has occured:
Google.Apis.Requests.RequestError
Bad Request [400]
Errors [
Message[Bad Request] Location[ - ] Reason[badRequest] Domain[global]
]
This is fixed now!
split the list().Execute() like this! Got help from #peleyal
var listReq = service.Users.List();
listReq.Domain = domain;
Users results = listReq.Execute();
This is another way to get users from a Domain (just a little different)
String serviceAccountEmail = "xxxxxxx#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"xxxxx.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser},
User = "your USER",
}.FromCertificate(certificate));
var service = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "name of your app",
});
var listReq = service.Users.List();
listReq.Domain = "your domain";
Users allUsers = listReq.Execute();
foreach(User myUser in allUsers.UsersValue){
Console.WriteLine("*" + myUser.PrimaryEmail);
}
Console.ReadKey();
For people who want more information, can visit Admin-SDK Users: list and the Directory API: Limits and Quotas
I'm trying to use the AdminService to manage my domain's users and groups, but I'm stuck with a simple request to get all the users of my domain. There is the code in C#:
public Users GetAllUsers()
{
var provider = new AssertionFlowClient(
GoogleAuthenticationServer.Description,
new X509Certificate2(privateKeyPath, keyPassword, X509KeyStorageFlags.Exportable))
{
ServiceAccountId = serviceAccountEmail,
Scope = AdminService.Scopes.AdminDirectoryUser.GetStringValue()
};
var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
m_serviceGroup = new AdminService(new BaseClientService.Initializer()
{
Authenticator = auth,
});
var request = m_serviceUser.Users.List();
request.Domain = m_domainName;
return request.Fetch();
}
I'm getting an exception when Fetch() that says:
Code: 403
Message: Not Authorized to access this resource/api
Error: {Message[Not Authorized to access this resource/api] Location[ - ] Reason[forbidden] Domain[global]}
I've followed the instructions here to have enabled API access, and also authorized my service account in domain control panel:
[Security]->[Advanced Setting]->[Authentication]->[Manage third party OAuth Client access]
with scopes:
https://www.googleapis.com/auth/admin.directory.group
https://www.googleapis.com/auth/admin.directory.user
Admin SDK Service is also enabled in API control panel.
I tried the code to use the DriveService and successfully listed/created/deleted files without any problem, so the authentication part of the code should be alright. I couldn't figure out what else needs to be configured or if there is any other problems with my code.
Thanks for any help.
As described on the page:
Manage API client access
Developers can register their web applications and other API clients with Google to enable access to
data in Google services like Calendar. You can authorize these
registered clients to access your user data without your users having to individually give consent or their passwords. Learn more
The service account needs to act on behave of a user, so when initializing the client the ServiceAccountUser needs to be assigned.
var provider = new AssertionFlowClient(
GoogleAuthenticationServer.Description,
new X509Certificate2(privateKeyPath, keyPassword, X509KeyStorageFlags.Exportable))
{
ServiceAccountId = serviceAccountEmail,
Scope = AdminService.Scopes.AdminDirectoryUser.GetStringValue(),
ServiceAccountUser = domainManangerEmail
};
Edit: AssertionFlowClient is deprecated, the following should work:
var cert = new X509Certificate2(privateKeyPath, keyPassword, X509KeyStorageFlags.Exportable);
var serverCredential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new []{DirectoryService.Scope.AdminDirectoryUser},
User = domainManagerAccountEmail
}.FromCertificate(cert));
var dirService = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = serverCredential
});
This code works for me
static void GettingUsers()
{
String serviceAccountEmail = "xxxxxxx#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"xxxxx.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser},
User = "your USER",
}.FromCertificate(certificate));
var service = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "name of your app",
});
var listReq = service.Users.List();
listReq.Domain = "your domain";
Users allUsers = listReq.Execute();
int counter = 0;
foreach(User myUser in allUsers.UsersValue){
Console.WriteLine("*" + myUser.PrimaryEmail);
counter++;
}
Console.WriteLine(counter);
Console.ReadKey();
For more information, Please take a look in Directory API: Users list.
There are Limits and Quotas.
We will need to give the service ID that we are using the super admin or the right privileges to get pass this error.
Hope this helps.
-Venu Murthy
Work for me.
using Google.Apis.Auth.OAuth2;
using Google.Apis.Admin.Directory.directory_v1;
using Google.Apis.Admin.Directory.directory_v1.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 ConsoleApplication1
{
class Program
{
static string[] Scopes = { DirectoryService.Scope.AdminDirectoryUserReadonly};
static string ApplicationName = "API G Suite implementation guid by amit";
static void Main(string[] args)
{
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, ".credentials1/admin-directory_v1-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 Directory API service.
var service = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
////// Define parameters of request.
UsersResource.ListRequest request = service.Users.List();
request.Customer = "my_customer";
request.MaxResults = 10;
request.OrderBy = UsersResource.ListRequest.OrderByEnum.Email;
////// List users.
IList<User> users = request.Execute().UsersValue;
Console.WriteLine("Users:");
if (users != null && users.Count > 0)
{
foreach (var userItem in users)
{
Console.WriteLine("{0} ({1})", userItem.PrimaryEmail,
userItem.Name.FullName);
}
}
else
{
Console.WriteLine("No users found.");
}
Console.Read();
}
}
}