I'm trying to use Google Directory API Library for .NET to maintain email addresses for a domain. The latest library is google-admin-directory_v1-rev6-csharp-1.4.0-beta. The best and farthest I've gotten so far is to receive a 403 error (Not Authorized to access this resource/api).
Has anyone out there successfully used it? If so, could you share some code, tips, or tricks?
I have used it and got some success in creating a console-application.
At the moment I'm trying to find a way to skip the copy/paste of the authorization code.
Don't forget to turn on API access in your APIs Console.
I'll show you a small sample:
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
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.CreateNewUser
{
public class Program
{
static void Main(string[] args)
{
// Display the header and initialize the sample.
CommandLine.EnableExceptionHandling();
Console.WriteLine("Create users in a google apps domain!");
Console.WriteLine("by Jonas Bergstedt 2013");
// Get the user data and store in user object
Console.Write("Email: ");
string userId = Console.ReadLine();
Console.Write("Givenname: ");
string GivenName = Console.ReadLine();
Console.Write("Familyname: ");
string FamilyName = Console.ReadLine();
Console.Write("Password: ");
string Password = Console.ReadLine();
User newuserbody = new User();
UserName newusername = new UserName();
newuserbody.PrimaryEmail = userId;
newusername.GivenName = GivenName;
newusername.FamilyName = FamilyName;
newuserbody.Name = newusername;
newuserbody.Password = Password;
// Register the authenticator.
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = "<your clientId from Google APIs Console>",
ClientSecret = "<your clientsecret from Google APIs Console>",
};
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
// Create the service.
var service = new DirectoryService(new BaseClientService.Initializer()
{
Authenticator = auth,
ApplicationName = "Create User",
ApiKey = "<your API Key from Google APIs console> (not sure if needed)"
});
User results = service.Users.Insert(newuserbody).Execute();
Console.WriteLine("User :" + results.PrimaryEmail + " is created");
Console.WriteLine("Press any key to continue!");
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.WriteLine();
Console.Write("Authorization Code: ");
string authCode = Console.ReadLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
}
}
Related
I am trying to connect to the new Google Analytics Data api using C# to request data from the new google analytics GA4. The only sample i can find is
Quickstart client libraries .net This does work but it uses a service account. The cloud .net client library google-cloud-dotnet only has examples for using a service account.
When i try to pass it desktop app credentials for using Oauth" authorization i get
Error creating credential from JSON. Unrecognized credential type.
using System;
using System.Threading;
using System.Threading.Tasks;
using Google.Analytics.Data.V1Beta;
namespace GoogleAnalyticsExamplesData
{
class Program
{
private const string PropertyId = "250796939";
private const string PathToCreds = #"C:\dev\ServiceAccountCred.json";
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
// Check whether the environment variable exists.
var environmentVariable = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
// If necessary, create it.
if (environmentVariable == null)
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", PathToCreds);
await SampleRunReport(PropertyId);
}
static async Task SampleRunReport(string propertyId = "YOUR-GA4-PROPERTY-ID")
{
// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
var client = await BetaAnalyticsDataClient.CreateAsync(CancellationToken.None);
var request = new RunReportRequest
{
Property = "properties/" + PropertyId,
Dimensions = {new Dimension {Name = "date"},},
Metrics = {new Metric {Name = "totalUsers"}, new Metric {Name = "newUsers"}},
DateRanges = {new DateRange {StartDate = "2021-04-01", EndDate = "today"},},
};
var response = await client.RunReportAsync(request);
Console.WriteLine("Report result:");
foreach (var row in response.Rows)
{
Console.WriteLine(
$"{row.DimensionValues[0].Value}, {row.MetricValues[0].Value}, {row.MetricValues[1].Value}");
}
}
}
}
Links to Google.Analytics.Data.V1Beta Web client credentials, desktop credentials
After several hours of digging around i found that you can use ICredential using a builder. This works with a Desktop app credentials, for installed applications.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Google.Analytics.Data.V1Beta;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
namespace GoogleAnalyticsExamplesData
{
class Program
{
private const string PropertyId = "250796939";
private const string PathToCreds = #"C:\dev\credentials.json";
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
await SampleRunReport(PropertyId);
}
static async Task SampleRunReport(string propertyId = "YOUR-GA4-PROPERTY-ID")
{
// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
//var client = await BetaAnalyticsDataClient.CreateAsync(CancellationToken.None);
BetaAnalyticsDataClient client ;
await using (var stream = new FileStream(PathToCreds, FileMode.Open, FileAccess.Read))
{
// Requesting Authentication or loading previously stored authentication for userName
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
new[] { "https://www.googleapis.com/auth/analytics.readonly"},
"userName",
CancellationToken.None,
new FileDataStore("credPath", true)).Result;
client = await new BetaAnalyticsDataClientBuilder
{
TokenAccessMethod = credential.GetAccessTokenForRequestAsync
}.BuildAsync();
}
var request = new RunReportRequest
{
Property = "properties/" + PropertyId,
Dimensions = {new Dimension {Name = "date"},},
Metrics = {new Metric {Name = "totalUsers"}, new Metric {Name = "newUsers"}},
DateRanges = {new DateRange {StartDate = "2021-04-01", EndDate = "today"},},
};
var response = await client.RunReportAsync(request);
Console.WriteLine("Report result:");
foreach (var row in response.Rows)
{
Console.WriteLine(
$"{row.DimensionValues[0].Value}, {row.MetricValues[0].Value}, {row.MetricValues[1].Value}");
}
}
}
}
I'm using the Google APIs Preview (1.7.0) to authorize a user via OAuth2. I've been following the sample MVC code. This is my implementation of FlowMetadata:
private static readonly IAuthorizationCodeFlow flow = ...; // Implementation of tokens
public static async Task<Google.Apis.Auth.OAuth2.Web.AuthorizationCodeWebApp.AuthResult> GetCredentials(Controller controller, CancellationToken cancellationToken) {
var result = await new AuthorizationCodeMvcApp(controller, new Models.Generic.AppFlowMetadata()).AuthorizeAsync(cancellationToken);
if (result.Credential != null)
{
// Struggling here. How do I make a request to get the e-mail address?
}
}
I now have a valid UserCredential and therefore Access Token, but I cannot find any managed APIs for accessing the user info. I did find this question, but this appears to assume I am just making raw requests, rather than using the official library.
How can I get the user's e-mail address?
You should do the following:
In addition to Google.Apis.Auth NuGet package you should install the following page: https://www.nuget.org/packages/Google.Apis.Oauth2.v2
Add Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoProfile and also Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoEmail to the scopes list (When you initialize the AppFlowMetadata).
Now, add the following code:
if (result.Credential != null)
{
var oauthSerivce = new Google.Apis.Oauth2.v2.Oauth2Service(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "OAuth 2.0 Sample",
});
var userInfo = await oauthSerivce.Userinfo.Get().ExecuteAsync();
// You can use userInfo.Email, Gender, FamilyName, ...
}
Set your scopes to:
https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/userinfo.profile
At: Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow.Scopes
And use this endpoint address: https://www.googleapis.com/oauth2/v1/userinfo?alt=json
That should help you to acquire the required information.
Here ,I edit my answere. Please look into this. On Default2.aspx page , I am displaying Session["username"] and Session["useremail"] value in label. I hope these will be help for you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
openIdAuth();
}
protected void openIdAuth()
{
OpenIdAjaxRelyingParty rp = new OpenIdAjaxRelyingParty();
var response = rp.GetResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
NotLoggedIn.Visible = false;
Session["GoogleIdentifier"] = response.ClaimedIdentifier.ToString();
var fetchResponse = response.GetExtension<FetchResponse>();
Session["FetchResponse"] = fetchResponse;
var response2 = Session["FetchResponse"] as FetchResponse;
string UserName = response2.GetAttributeValue(WellKnownAttributes.Name.First) ?? "Guest"; // with the OpenID Claimed Identifier as their username.
string UserEmail = response2.GetAttributeValue(WellKnownAttributes.Contact.Email) ?? "Guest";
Session["username"] = UserName;
Session["useremail"] = UserEmail;
Response.Redirect("Default2.aspx");
break;
case AuthenticationStatus.Canceled:
lblAlertMsg.Text = "Cancelled.";
break;
case AuthenticationStatus.Failed:
lblAlertMsg.Text = "Login Failed.";
break;
}
}
var CommandArgument = "https://www.google.com/accounts/o8/id";
string discoveryUri = CommandArgument.ToString();
OpenIdRelyingParty openid = new OpenIdRelyingParty();
var url = new UriBuilder(Request.Url) { Query = "" };
var request = openid.CreateRequest(discoveryUri); // This is where you would add any OpenID extensions you wanted
var fetchRequest = new FetchRequest(); // to fetch additional data fields from the OpenID Provider
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.Country);
request.AddExtension(fetchRequest);
request.RedirectToProvider();
}
}
Complete code to get UserProfile data.
var secrect = new ClientSecrets()
{
ClientId = "myClientId",
ClientSecret = "mySecret"
};
var scopes = new[] { Oauth2Service.Scope.UserinfoEmail, auth2Service.Scope.UserinfoProfile };
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(secrect, scopes, "user", CancellationToken.None).Result;
var oauthSerivce = new Oauth2Service(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MyApplicationName",
});
var userInfo = oauthSerivce.Userinfo.Get().Execute();
I have a requirement to integerate Quickbook api with my web application. I just created a sample application to accomplish it. I am strange to this I really dont have any idea about how to connect the api or to consume the api.I have mentioned the codes that i have took from ("https://developer.intuit.com/").
I tried by creating an app in the app manager, I have atttached the image FYR. After entering all those details i am not getting "accessTokenSecret" value. Here i just entered the apptoken valuea as accessToken value. Iam getting exception as "Unauthorized" in the service context line. Help me on this.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Intuit.Ipp.Core;
using Intuit.Ipp.Services;
using Intuit.Ipp.Data;
using Intuit.Ipp.Utility;
using Intuit.Ipp.Security;
using Intuit.Ipp.Data.Qbo;
using Newtonsoft.Json;
namespace QuickBookApiConsumption
{
public partial class Invoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnsendInvoiceDetails_Click(object sender, EventArgs e)
{
string accessToke = "";
string appToken = "297db54bb5526b494dba97fb2a41063192cd";
string accessTokenSecret = "297db54bb5526b494dba97fb2a41063192cd";
string consumerKey = "qyprdMSG1YHpCPSlWQZTiKVc78dywR";
string consumerSecret = "JPfXE17YnCPGU9m9vuXkF2M765bDb7blhcLB7HeF";
string companyID = "812947125";
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(appToken, accessTokenSecret, consumerKey, consumerSecret);
ServiceContext context = new ServiceContext(oauthValidator, appToken, companyID, IntuitServicesType.QBO);
DataServices service = new DataServices(context);
Invoice os = new Invoice();
Intuit.Ipp.Data.Qbo.InvoiceHeader o = new Intuit.Ipp.Data.Qbo.InvoiceHeader();
o.CustomerName = "Viki";
o.CustomerId = new Intuit.Ipp.Data.Qbo.IdType { Value = "12" };
o.ShipMethodName = "Email";
o.SubTotalAmt = 3.00m;
o.TotalAmt = 6.00m;
o.ShipAddr = new Intuit.Ipp.Data.Qbo.PhysicalAddress { City = "Chni" };
}
}
}
Image:
You should check if you are using correct BASE URL
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0400_quickbooks_online/0100_calling_data_services/0010_getting_the_base_url
Using some RESTClient[ ex - RestClient plugin of mozilla browser], verify the OAuth tokens.
Header(content-type) config window.
You can use the following
public void ConnectUsingAuth()
{
string accessToken = ConfigurationManager.AppSettings["AccessTokenQBD"];
string accessTokenSecret = ConfigurationManager.AppSettings["access-secret"];
string consumerKey = ConfigurationManager.AppSettings["consumerKey"];
string consumerKeySecret = ConfigurationManager.AppSettings["consumerSecret"];
string URI = "https://apiend-point";
WebRequest webRequest = WebRequest.Create(URI);
webRequest.Headers.Add("ContentType", "text/xml");
OAuthRequestValidator target = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerKeySecret);
}
Or [ Better option ] You can download the sample program from github and configure the web.config(with proper consumer key and secret)
https://developer.intuit.com/docs/0025_quickbooksapi/0055_devkits/sample_code
You can test all these API endpoints using APIExplorer tool.
Docs - https://developer.intuit.com/docs/0025_quickbooksapi/0010_getting_started/0007_firstrequest
ApiExplorer - https://developer.intuit.com/apiexplorer?apiname=V2QBO
Thanks
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();
}
}
}