Използвате API на директорията на Google за .Net?

Опитвам се да създам първото си конзолно приложение, използвайки API на директорията на Google за .Net.

Имам код, базиран на извадка на Google. Показва ми няколко грешки, една от тях е, когато се опитвам да създам услугата:

var service = new DirectoryService(new BaseClientService.Initializer()
{
   Authenticator = auth,
   ApplicationName = "Create User",
   ApiKey = "<your API Key from Google APIs console>"
 });

Показва ми: "Грешка 3 'Google.Apis.Services.BaseClientService.Initializer' не съдържа дефиниция за 'Authenticator'"

И втората грешка е в тази функция

private static IAuthorizationState GetAuthorization(NativeApplicationClient arg){}

Показва ми: "DotNetOpenAuth.OAuth2.UserAgentClient' е дефиниран в сборка, която не е реферирана."

В този случай написах (използвайки nuget конзола): PM> Install-Package DotNetOpenAuth -Version 4.3.4.13329 .... но това не решава проблема ми.


Това е моят код:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using System.Diagnostics;

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.directory_v1;
using Google.Apis.Admin.Directory.directory_v1.Data;


namespace GoogleDirectoryApi_test02_consola
{
    class Program
    {
        static void Main(string[] args)
        {
        String CLIENT_ID = "YOUR_CLIENT_ID";
        String CLIENT_SECRET = "YOUR_CLIENT_SECRET";

        // Register the authenticator and create the service
        var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
        var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

        //New User
        User newuserbody = new User();
        string userId = "SampleId01";
        UserName newusername = new UserName();
        newuserbody.PrimaryEmail = userId;

        // Create the service.
        var service = new DirectoryService(new BaseClientService.Initializer()
        {
            Authenticator = auth,
            ApplicationName = "Create User",
            ApiKey = "<your API Key from Google APIs console>"
        });


        User results = service.Users.Insert(newuserbody).Execute();
    }



    private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
    {
        // Get the auth URL:
        //IAuthorizationState state = new AuthorizationState(new[] { DirectoryService.Scopes.AdminDirectoryUser.GetStringValue() });
        IAuthorizationState state = new AuthorizationState(new[] { DirectoryService.Scope.AdminDirectoryUser.ToString() });
        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);
        }
    }
}

Благодарим ви предварително за помощта


person Orlando Herrera    schedule 07.02.2014    source източник
comment
вижте моя код тук stackoverflow.com/questions/54868344/   -  person Zunair    schedule 05.03.2019


Отговори (1)


трябва да имате акаунт за услуга с Извършване на делегиране на правомощия за целия домейн на Google Приложения, както е определено в

https://developers.google.com/admin-sdk/directory/v1/guides/delegation

казва да го добавите в „Управление на достъпа на OAuth клиент на трета страна“, имах „Управление на достъп на OAuth клиент“

 String serviceAccountEmail = "[email protected]";
                X509Certificate2 certificate = new X509Certificate2(@"C:\key.p12", "notasecret", X509KeyStorageFlags.Exportable);
                ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
                {
                    Scopes = new[]
                    {
                        DirectoryService.Scope.AdminDirectoryUser
                    },
                    User = "[email protected]"
                }.FromCertificate(certificate));

                var ser = new DirectoryService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Get it to work",
                });

                User newuserbody = new User();
                UserName newusername = new UserName();
                newuserbody.PrimaryEmail = "[email protected]";
                newusername.GivenName = "jack";
                newusername.FamilyName = "black";
                newuserbody.Name = newusername;
                newuserbody.Password = "password";

                User results = ser.Users.Insert(newuserbody).Execute();
person heyyan khan    schedule 12.08.2014