Create Google Group And Add User To Group Programatically From .NET Using Google Directory API

In this article, we will learn about how to create a Google group and add a user to the Google group programmatically from .NET. This is the fourth article in the series of accessing Google API from .NET. This will be an advanced article because it will us Google Admin SDK to perform the administrative task on GSuite. 
 
Now, as we will be doing Google administrative tasks programmatically which are available from the admin console, we would need to access it through an admin account who has access to the administrative privileges in GSuite account. For the propose of the demo, we will use service account (generic account) and then impersonate a user having GSuite admin access (who has logged into GSuite admin console at least once).
 

Google configuration

 
We won't go into details of how to create a service account and grant service access role as admin of GSuite. Below are some reference links.

.NET API

 
Get Google Admin Sdk nuget package from Visual Studio. Or you can directly download from this link, Please check for the latest version from above URL, you should get the option to Download package on the right side. Add references to below dlls.
 
 
Now to keep things simple, we will divide code into different functions for reusability and simplicity. 
 

Get Directory Service

 
First, let us create a function to get the Directory Service Object. This function will be called in the below methods.
 
Parameters keyfilepath is the path of JSON file downloaded from console.developers.com.  This function will validate the credentials and authenticate service account. If you see here we have used .CreatewithUser method, this is because we need to impersonate a admin user account to perform admin SDK operations.
  1. DirectoryService GetDirectoryService(string keyfilepath)    
  2.        {   
  3.            try    
  4.            {    
  5.                string[] Scopes = { DirectoryService.Scope.AdminDirectoryGroup, DirectoryService.Scope.AdminDirectoryGroupReadonly };    
  6.                GoogleCredential credential;    
  7.                using (var stream = new FileStream(keyfilepath, FileMode.Open, FileAccess.Read))    
  8.                {    
  9.                    // As we are using admin SDK, we need to still impersonate user who has admin access    
  10.                    //  https://developers.google.com/admin-sdk/directory/v1/guides/delegation    
  11.                    credential = GoogleCredential.FromStream(stream)    
  12.                            .CreateScoped(Scopes).CreateWithUser("[email protected]");    
  13.                }    
  14.                // Create Directory API service.    
  15.                var service = new DirectoryService(new BaseClientService.Initializer()    
  16.                {    
  17.                    HttpClientInitializer = credential,    
  18.                    ApplicationName = "Gsuite Migration Tool",    
  19.                });    
  20.                return service;    
  21.            }    
  22.            catch (Exception ex)    
  23.            {    
  24.                throw;    
  25.            }    
  26.     
  27.        }    

Create Google Group

 
This is the main method which will create Google Group. 
  • We are using the above method to get the DirectoryService object.
  • Group object to assign some parameters like Email, Name, and Description
  • InsertRequest.Execute() method will return Google Group object, it is has Id attribute populated it means that the Group is created.
    1. public string CreateGoogleGroup(string groupName, string groupEmailID, string desc)    
    2.         {    
    3.             DirectoryService _service = this.GetDirectoryService("gsuite-migration-123456-a0145651cae.json");    
    4.             Google.Apis.Admin.Directory.directory_v1.Data.Group grp = new Google.Apis.Admin.Directory.directory_v1.Data.Group();    
    5.                 grp.AdminCreated = true;    
    6.                 grp.Email = groupEmailID.Trim();    
    7.                 grp.Name = groupName;    
    8.                 grp.Description = desc;     
    9.                 GroupsResource.InsertRequest insertRequest = _service.Groups.Insert(grp);    
    10.                 try    
    11.                 {                 
    12.                 Google.Apis.Admin.Directory.directory_v1.Data.Group creategrp = insertRequest.Execute();                 
    13.                 if (creategrp.Id != null)    
    14.                     {    
    15.                         return creategrp.Id;    
    16.                     }    
    17.                     return "";    
    18.                 }    
    19.                 catch (Google.GoogleApiException ex)    
    20.                 {    
    21.                    throw ex;    
    22.                 }                
    23.             return "";    
    24.         }    
To know about more API on creating groups, refer to this link.
 

Adding User to Google Group

 
This method will add user to Google Group.
  • It requires Google group id (returned from above method) and user's email address
  • Again user DirectoryService object for InsertRequest method.
  • Using Member class for assiging parameters like email, role. 
  • Role can be MEMBER, OWNER, MANAGER 
    1. public bool AddUserToGoogleGroup(string groupdId, string UserEmailID)    
    2.         {    
    3.             DirectoryService _service = this.GetDirectoryService("gsuite-migration-123456-a0145651cae.json");      
    4.             Google.Apis.Admin.Directory.directory_v1.Data.Member body = new Google.Apis.Admin.Directory.directory_v1.Data.Member();    
    5.             body.Email = UserEmailID;    
    6.             body.Role = "MEMBER";      
    7.             MembersResource.InsertRequest request = new MembersResource.InsertRequest(_service, body, groupdId);    
    8.             try    
    9.             {    
    10.                 Google.Apis.Admin.Directory.directory_v1.Data.Member member = request.Execute();    
    11.                 if (member.Id != null)    
    12.                 {    
    13.                     return true;    
    14.                 }    
    15.             }    
    16.             catch (Exception ex)    
    17.             {    
    18.                 throw ex;    
    19.             }    
    20.             return false;    
    21.         }   
To know about more API managing members in group, refer to this link.
 
Now we have the required methods ready, let us club this together to see how it works. For my example, I have created a windows application and passed hardcoded values to create a group and a user to this group.
  1. private void button7_Click(object sender, EventArgs e)  
  2.        {  
  3.             string GroupID = CreateGoogleGroup("My Group""[email protected]""Group created from .NET");  
  4.             bool Isadded = AddUserToGoogleGroup(GroupID, "[email protected]");  
  5.            MessageBox.Show("Groupd ID-" + GroupID + "\n" + "IsUserAdded -" + Isadded);  
  6.        }   
Run the application, click on button. Output in windows application.
 
 
Now let us check in Google admin console, to check output.
 
Visit here, we can see My Group is being created.
 
 
Click on manage members to see user added to this group.
 
 
Let me conclude what we have learned in this article. 
  • Usage of Google Admin SDK
  • Creating a service account and enabling the Admin SDK.
  • Create a Google group programmatically from .NET.
  • Adding user to google group programatically from .NET.
Hope you enjoyed reading.!!!


Similar Articles