0

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] ]

JoBe
  • 391
  • 3
  • 12
  • 1
    I would strongly advise you to learn the basics of C# before you start using 3rd party APIs. That way you'll understand the examples for yourself. – Jon Skeet Jul 18 '13 at 11:36
  • Trying to do that as well. :) – JoBe Jul 18 '13 at 12:27
  • @Jon Skeet I'm slowly getting there. I've done a simple testprogram to list all the users in my domain, but I get an errormessage implying that I haven't provided info on what domain to list the users: An error has occured: Google.Apis.Requests.RequestError Bad Request [400] Errors [ Message[Bad Request] Location[ - ] Reason[badRequest] Domain[global] ] But I can't find any info on where and in what format I pass the domain info to my request. In python I done like this: gl = group.list(customer=domain).execute() In C# : Users results = service.Users.List().Execute(); – JoBe Jul 19 '13 at 09:19
  • Well presumably you're issuing a bad request - but as we can't see any of your code, it's hard to know what's wrong... – Jon Skeet Jul 19 '13 at 09:20
  • A bit new to stackoverflow as well :) How do I add the code? The comments are quite limited? – JoBe Jul 19 '13 at 09:23
  • You don't want to put it in comments - you want to edit your question. So hit the edit link. – Jon Skeet Jul 19 '13 at 09:24
  • Anyone have any input? Where/how to add the domain to my request? – JoBe Jul 20 '13 at 14:03
  • @JonSkeet Thanks for helping me so far. :) Do you have any input on how to proceed? I'm not sure if NativeApplicationClientis the correct way to go. I've fiddled around with AssertionFlowClient but can't seem to get it to work. – JoBe Jul 22 '13 at 13:12
  • No, I haven't used this API myself. But at least someone else who has might have more clue than when you started. – Jon Skeet Jul 22 '13 at 13:59
  • @JoBe Can I e-mail you for a problem about a peace of code? – Orlando Herrera Feb 10 '14 at 17:42

2 Answers2

1

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();
JoBe
  • 391
  • 3
  • 12
0

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

Orlando Herrera
  • 3,481
  • 1
  • 34
  • 44