private static void NicknameOperations(AppsService service) { // Create a new nickname. NicknameEntry insertedEntry = service.CreateNickname(testUserName, testNickname); Console.WriteLine("Created nickname '{0}' for user {1}", insertedEntry.Nickname.Name, insertedEntry.Login.UserName); // Retrieve the newly-created nickname. NicknameEntry entry = service.RetrieveNickname(testNickname); Console.WriteLine("Retrieved nickname {0}", entry.Nickname.Name); // Retrieve all nicknames for testUserName (really, just this one). NicknameFeed feed = service.RetrieveNicknames(testUserName); entry = feed.Entries[0] as NicknameEntry; Console.WriteLine("Retrieved nickname '{0}' for user {1}", entry.Nickname.Name, entry.Login.UserName); // Retrieve a page of nicknames. feed = service.RetrievePageOfNicknames(testNickname); entry = feed.Entries[0] as NicknameEntry; Console.WriteLine("Retrieved page of {0} nicknames, beginning with '{1}'", feed.Entries.Count, entry.Nickname.Name); // Retrieve the feed of all nicknames. feed = service.RetrieveAllNicknames(); entry = feed.Entries[0] as NicknameEntry; Console.WriteLine("Retrieved all {0} nicknames in the domain, beginning with '{1}'", feed.Entries.Count, entry.Nickname.Name); }
protected void lbImportUsers_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(ddlDomains.SelectedValue)) { try { AppsService service = new AppsService(ddlDomains.SelectedValue, UserContext.Current.Organization.GoogleAdminAuthToken); int count = 0; int failed = 0; GoogleProvider.ImportUsers(UserContext.Current.OrganizationId, service, out count, out failed); lbImportUsers.Enabled = false; lbImportUsers.Enabled = false; lbImportUsers.Text = string.Format(CultureInfo.CurrentCulture, Resources.GoogleIntegrationControl_ImportUsers_Result_Text, count - failed, failed); } catch (AppsException a) { lblStep1Error.Text = string.Format(CultureInfo.CurrentCulture, Resources.GoogleIntegrationControl_GoogleAppsError_Text, a.ErrorCode, a.InvalidInput, a.Reason); mvStep1.SetActiveView(vwStep1Error); } catch (Exception ex) { ShowError(ex, lblStep1Error, mvStep1, vwStep1Error); } } else { lblStep1Error.Text = Resources.GoogleIntegrationControl_DomainMisingError_Text; mvStep1.SetActiveView(vwStep1Error); } }
public override void InitTest() { base.InitTest(); if (unitTestConfiguration.Contains("domainName") == true) { this.domainName = (string)unitTestConfiguration["domainName"]; Tracing.TraceInfo("Read userName value: " + this.domainName); } if (unitTestConfiguration.Contains("domainAdminUsername") == true) { this.adminUsername = (string)unitTestConfiguration["domainAdminUsername"]; Tracing.TraceInfo("Read userName value: " + this.adminUsername); } if (unitTestConfiguration.Contains("domainAdminPassword") == true) { this.adminPassword = (string)unitTestConfiguration["domainAdminPassword"]; Tracing.TraceInfo("Read userName value: " + this.adminPassword); } this.service = new AppsService(this.domainName, this.adminUsername + "@" + this.domainName, this.adminPassword); this.randomUserName = "******" + Guid.NewGuid().ToString(); this.randomEmailListName = "test_emaillist_" + Guid.NewGuid().ToString(); }
public static void ImportUsers(Guid organizationId, AppsService service, out int totalCount, out int failedCount) { totalCount = 0; failedCount = 0; if (service == null) { return; } UserFeed userFeed = service.RetrieveAllUsers(); if (userFeed == null) { return; } totalCount = userFeed.Entries.Count; for (int i = 0; i < totalCount; i++) { try { UserEntry userEntry = userFeed.Entries[i] as UserEntry; ImportUser(userEntry, organizationId, service.Domain); } catch { failedCount++; } } }
private static void RunSample(AppsService service) { try { // Demonstrate operations on user accounts. UserOperations(service); // Demonstrate operations on nicknames. NicknameOperations(service); // Demostrate operations on groups GroupOperations(service); // Clean up (delete the username, nickname and email list // that were created). CleanUp(service); } catch (AppsException a) { Console.WriteLine("A Google Apps error occurred."); Console.WriteLine(); Console.WriteLine("Error code: {0}", a.ErrorCode); Console.WriteLine("Invalid input: {0}", a.InvalidInput); Console.WriteLine("Reason: {0}", a.Reason); } }
public BookThemAllSample(string domain, string admin, string password) { apps = new AppsService(domain, admin, password); calendar = new CalendarService("BookThemAll"); calendar.setUserCredentials(admin, password); this.admin = admin; }
public static AppsService CreateAppsService(string domain, OAuth2Parameters parameters) { GOAuth2RequestFactory factory = new GOAuth2RequestFactory("apps", FrameworkConfiguration.Current.WebApplication.Integration.Google.ApplicationName, parameters); AppsService service = new AppsService(domain, parameters.AccessToken); service.SetRequestFactory(factory); return(service); }
protected void lbStep2_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(ddlDomains.SelectedValue)) { try { AppsService service = new AppsService(ddlDomains.SelectedValue, UserContext.Current.Organization.GoogleAdminAuthToken); AppsExtendedFeed groupsFeed = service.Groups.RetrieveAllGroups(); DataTable dt = new DataTable(); dt.Columns.Add(Resources.GoogleIntegrationControl_NameColumn_HeaderText, typeof(string)); dt.Columns.Add(Resources.GoogleIntegrationControl_IdColumn_HeaderText, typeof(string)); dt.Columns.Add(Resources.GoogleIntegrationControl_DescriptionColumn_HeaderText, typeof(string)); dt.Columns.Add(Resources.GoogleIntegrationControl_MembersColumn_HeaderText, typeof(string)); for (int i = 0; i < groupsFeed.Entries.Count; i++) { GroupEntry groupEntry = groupsFeed.Entries[i] as GroupEntry; MemberFeed memberFeed = service.Groups.RetrieveAllMembers(groupEntry.GroupId); StringBuilder sb = new StringBuilder(); for (int j = 0; j < memberFeed.Entries.Count; j++) { MemberEntry memberEntry = memberFeed.Entries[j] as MemberEntry; if (string.Compare(memberEntry.MemberId, "*", true) == 0) { sb.AppendFormat(Resources.GoogleIntegrationControl_MembersColumn_AllUsersValue); } else { sb.AppendFormat("{0}<br>", memberEntry.MemberId); } } dt.Rows.Add(groupEntry.GroupName, groupEntry.GroupId, groupEntry.Description, sb.ToString()); } gvStep2Results.DataSource = dt; gvStep2Results.DataBind(); mvStep2.SetActiveView(vwStep2Result); } catch (AppsException a) { lblStep2Error.Text = string.Format(CultureInfo.CurrentCulture, Resources.GoogleIntegrationControl_GoogleAppsError_Text, a.ErrorCode, a.InvalidInput, a.Reason); mvStep2.SetActiveView(vwStep2Error); } catch (Exception ex) { ShowError(ex, lblStep2Error, mvStep2, vwStep2Error); } } else { lblStep2Error.Text = Resources.GoogleIntegrationControl_DomainMisingError_Text; mvStep2.SetActiveView(vwStep2Error); } }
public static void ImportUsers(Guid organizationId, string domain, OAuth2Parameters parameters, out int totalCount, out int failedCount) { totalCount = 0; failedCount = 0; AppsService service = CreateAppsService(domain, parameters); ImportUsers(organizationId, service, out totalCount, out failedCount); }
public Service(IClient client) { _client = client; Api = new ApiService(client); Apps = new AppsService(client); Audio = new AudioService(client); Control = new ControlService(client); Notifications = new NotificationService(client); Tv = new TvService(client); }
private static void CleanUp(AppsService service) { // Delete the group that was created service.Groups.DeleteGroup(testGroup); Console.WriteLine("Deleted group {0}", testGroup); // Delete the nickname that was created. service.DeleteNickname(testNickname); Console.WriteLine("Deleted nickname {0}", testNickname); // Delete the user that was created. service.DeleteUser(testUserName); Console.WriteLine("Deleted user {0}", testUserName); }
static string AddGroupMember(AppsService service, string group, string member) { try { var entry = service.Groups.AddMemberToGroup(member, group); return(string.Format( "{0} added to group, {1}.", entry.getPropertyValueByName(AppsGroupsNameTable.memberId), group)); //return member from server } catch (GDataRequestException ex) { return(string.Format("Error adding group member: {0}.", ex.ParseError())); //or else return error message } }
private static void GroupOperations(AppsService service) { // Create a new group. AppsExtendedEntry insertedEntry = service.Groups.CreateGroup(testGroup, testGroup, testGroup, null); Console.WriteLine("Created new group '{0}'", insertedEntry.getPropertyByName("groupId").Value); // Retrieve the newly-created group. AppsExtendedEntry entry = service.Groups.RetrieveGroup(testGroup); Console.WriteLine("Retrieved group '{0}'", entry.getPropertyByName("groupId").Value); // Add Member To Group AppsExtendedEntry newMemberEntry = service.Groups.AddMemberToGroup(testUserName, testGroup); Console.WriteLine("User '{0}' was added as member to group '{1}'", newMemberEntry.getPropertyByName("memberId").Value, testGroup); // Add Owner to Group AppsExtendedEntry newOwnerEntry = service.Groups.AddOwnerToGroup(testUserName, testGroup); Console.WriteLine("User '{0}' was added as ownter to group '{1}'", newOwnerEntry.getPropertyByName("email").Value, testGroup); // Check if a User is a Group Member Console.WriteLine("Is User '{0}' member of group '{1}'? '{2}'", testUserName, testGroup, service.Groups.IsMember(testUserName, testGroup)); // Check if a User is a Group Member Console.WriteLine("Is User '{0}' owner of group '{1}'? '{2}'", testUserName, testGroup, service.Groups.IsOwner(testUserName, testGroup)); // Remove Member from Group service.Groups.RemoveMemberFromGroup(testUserName, testGroup); Console.WriteLine("User '{0}' was removed as member to group '{1}'", testUserName, testGroup); // Remove Owner from Group service.Groups.RemoveOwnerFromGroup(testUserName, testGroup); Console.WriteLine("User '{0}' was removed as ownter to group '{1}'", testUserName, testGroup); // Retreive all groups AppsExtendedFeed groupsFeed = service.Groups.RetrieveAllGroups(); Console.WriteLine("First Group from All groups: '{0}'", (groupsFeed.Entries[0] as AppsExtendedEntry).getPropertyByName("groupId").Value); }
static void ListGroupsForMember(TextWriter textWriter, AppsService service, string member) { textWriter.WriteLine("All groups of which {0} is a direct member:", member); textWriter.WriteLine(); try { var feed = service.Groups.RetrieveGroups(member, true); foreach (AppsExtendedEntry entry in feed.Entries) //cast Entry to AppsExtendedEntry { textWriter.WriteLine(entry.getPropertyValueByName(AppsGroupsNameTable.groupId)); } } catch (GDataRequestException ex) { textWriter.WriteLine(string.Format("Error: {0}.", ex.ParseError())); } }
/// <summary> /// This console application demonstrates all the Google Apps /// Provisioning API calls. It accepts authentication information /// from the command-line and performs a series of create/ /// retrieve/update/delete operations on user accounts, nicknames, /// and email lists, as described in the comments of RunTests. /// </summary> /// <param name="args">Command-line arguments: args[0] is /// the domain, args[1] is the admin email address, and args[2] /// is the admin psasword. /// /// Example: AppsDemo example.com [email protected] my_password</param> public static void Main(string[] args) { if (args.Length != 3) { Console.WriteLine("Syntax: AppsDemo <domain> <admin_email> <admin_password>"); } else { domain = args[0]; adminEmail = args[1]; adminPassword = args[2]; AppsService service = new AppsService(domain, adminEmail, adminPassword); RunSample(service); } }
static void ListGroups(TextWriter textWriter, AppsService service) { textWriter.WriteLine("All groups in {0}:", service.Domain); textWriter.WriteLine(); try { var feed = service.Groups.RetrieveAllGroups(); foreach (AppsExtendedEntry entry in feed.Entries) //cast Entry to AppsExtendedEntry { textWriter.WriteLine(entry.getPropertyValueByName(AppsGroupsNameTable.groupId)); } } catch (GDataRequestException ex) { textWriter.WriteLine(string.Format("Error: {0}.", ex.ParseError())); } }
static void ListGroupMembers(TextWriter textWriter, AppsService service, string group) { textWriter.WriteLine("All active members of {0}:", group); textWriter.WriteLine(); try { var feed = service.Groups.RetrieveAllMembers(group); foreach (AppsExtendedEntry entry in feed.Entries) //cast Entry to AppsExtendedEntry { textWriter.WriteLine(entry.getPropertyValueByName(AppsGroupsNameTable.memberId)); } } catch (GDataRequestException ex) { textWriter.WriteLine(string.Format("Error: {0}.", ex.ParseError())); } }
protected void lbStep1_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(ddlDomains.SelectedValue)) { try { AppsService service = new AppsService(ddlDomains.SelectedValue, UserContext.Current.Organization.GoogleAdminAuthToken); UserFeed userFeed = service.RetrieveAllUsers(); DataTable dt = new DataTable(); dt.Columns.Add(Resources.GoogleIntegrationControl_UsernameColumn_HeaderText, typeof(string)); dt.Columns.Add(Resources.GoogleIntegrationControl_FirstNameColumn_HeaderText, typeof(string)); dt.Columns.Add(Resources.GoogleIntegrationControl_LastNameColumn_HeaderText, typeof(string)); dt.Columns.Add(Resources.GoogleIntegrationControl_AdminColumn_HeaderText, typeof(string)); for (int i = 0; i < userFeed.Entries.Count; i++) { UserEntry userEntry = userFeed.Entries[i] as UserEntry; dt.Rows.Add(userEntry.Login.UserName, userEntry.Name.GivenName, userEntry.Name.FamilyName, userEntry.Login.Admin ? Resources.GoogleIntegrationControl_AdminColumn_Value : string.Empty); } gvStep1Results.DataSource = dt; gvStep1Results.DataBind(); mvStep1.SetActiveView(vwStep1Result); lbImportUsers.Text = Resources.GoogleIntegrationControl_ImportUsers_LinkButton_Text; lbImportUsers.Visible = lbImportUsers.Enabled = dt.Rows.Count > 0; } catch (AppsException a) { lblStep1Error.Text = string.Format(CultureInfo.CurrentCulture, Resources.GoogleIntegrationControl_GoogleAppsError_Text, a.ErrorCode, a.InvalidInput, a.Reason); mvStep1.SetActiveView(vwStep1Error); } catch (Exception ex) { ShowError(ex, lblStep1Error, mvStep1, vwStep1Error); } } else { lblStep1Error.Text = Resources.GoogleIntegrationControl_DomainMisingError_Text; mvStep1.SetActiveView(vwStep1Error); } }
private static void UserOperations(AppsService service) { // Create a new user. UserEntry insertedEntry = service.CreateUser(testUserName, "Jane", "Doe", "testuser-password"); Console.WriteLine("Created new user '{0}'", insertedEntry.Login.UserName); // Suspend the user. UserEntry suspendedEntry = service.SuspendUser(testUserName); Console.WriteLine("Suspended account for {0}", suspendedEntry.Login.UserName); // Restore the user. UserEntry restoredEntry = service.RestoreUser(testUserName); Console.WriteLine("Restored user {0}", restoredEntry.Login.UserName); // Query for a single user. UserEntry entry = service.RetrieveUser(testUserName); Console.WriteLine("Retrieved user {0}", entry.Login.UserName); // Query for a page of users. UserFeed feed = service.RetrievePageOfUsers(testUserName); entry = feed.Entries[0] as UserEntry; Console.WriteLine("Retrieved page of {0} users, beginning with '{1}'", feed.Entries.Count, entry.Login.UserName); // Query for all users. feed = service.RetrieveAllUsers(); entry = feed.Entries[0] as UserEntry; Console.WriteLine("Retrieved all {0} users in the domain, beginning with '{1}'", feed.Entries.Count, entry.Login.UserName); // Update the user's given name. restoredEntry.Name.GivenName = "John"; UserEntry updatedEntry = service.UpdateUser(entry); Console.WriteLine("Updated user with new given name '{0}'", updatedEntry.Name.GivenName); }
static void AddGroupMemberBatch(TextWriter textWriter, AppsService service, string primaryDomain, string file) { try { using (var stream = File.OpenRead(file)) using (var reader = new StreamReader(stream)) { string line; long position = 0; while (null != (line = reader.ReadLine())) { position++; line = line.Trim(); if (line.Length == 0 || line.StartsWith("#")) { continue; } //ignore lines that start with '#' string response; var split = line.Split('\t'); if (split.Length != 2) { response = string.Format("Line {0}: Error row not in the expected format.", position); } else { string group = split[0]; string member = split[1]; string result = AddGroupMember(service, group, member); response = string.Format("Line {0}: {1}", position, result); } textWriter.WriteLine(response); } } } catch (IOException ex) { textWriter.WriteLine(); textWriter.WriteLine(ex.Message); } }
public static void setPw(string username, string password) { try { AppsService service = new AppsService(DOMAIN, USERNAME, PASSWORD); UserEntry entry = service.RetrieveUser(username); entry.Login.Password = password; service.UpdateUser(entry); } catch (AppsException ex) { // Probably don't have a Google Apps account yet, do nothing if (ex.Reason == "EntityDoesNotExist") { } else { throw ex; } } }
protected void btnSaveToken_Click(object sender, EventArgs e) { trFormError.Visible = false; mvStep1.ActiveViewIndex = -1; mvStep2.ActiveViewIndex = -1; try { Service service = new Service(AppsNameTable.GAppsService, "sherpadesk"); string token = string.Empty; if (trGoogleDomain.Visible) { string googleDomain = txtGoogleDomain.Text; AppsService appService = new AppsService(googleDomain, txtGoogleEmail.Text, txtGooglePassword.Text); GroupFeed groups = appService.Groups.RetrieveAllGroups(); EmailSuffixProvider.InsertEmailSuffixName(UserContext.Current.OrganizationId, null, ref googleDomain); FillDomains(); } service.setUserCredentials(txtGoogleEmail.Text, txtGooglePassword.Text); token = service.QueryClientLoginToken(); OrganizationProvider.UpdateOrganizationGoogleAdminAuthToken(UserContext.Current.OrganizationId, token); mvConnectionSettings.SetActiveView(vwToken); } catch (AppsException a) { lblFromError.Text = string.Format(CultureInfo.CurrentCulture, Resources.GoogleIntegrationControl_GoogleAppsError_Text, a.ErrorCode, a.InvalidInput, a.Reason); trFormError.Visible = true; } catch (Exception ex) { lblFromError.Text = ex.Message; trFormError.Visible = true; } }
public static void ReplicateAllOrganizations() { int failed = 0; int success = 0; DateTime startDate = DateTime.UtcNow; WriteResponseLog(string.Format("GoogleReplicator started replication process at {0}.", startDate)); try { OrganizationCollection organizationCollection = OrganizationProvider.GetOrganizations(false, false); foreach (Organization org in organizationCollection) { try { if (!string.IsNullOrWhiteSpace(org.GoogleAdminAuthToken)) { var domains = EmailSuffixProvider.GetEmailSuffixesList(org.OrganizationId); if (domains != null) { WriteResponseLog(string.Format("Organization '{0}' is setup for Google Replication and has {1} Google domains.", org.Name, domains.Count)); foreach (string domain in domains) { bool isSuccess = false; try { WriteResponseLog(string.Format("Receiving users of Organization '{0}' from Google domain '{1}'.", org.Name, domain)); AppsService service = new AppsService(domain, org.GoogleAdminAuthToken); UserFeed userFeed = service.RetrieveAllUsers(); if (userFeed != null && userFeed.Entries != null) { int totalUsers = userFeed.Entries.Count; int failedUsers = 0; DateTime start = DateTime.UtcNow; WriteResponseLog(string.Format("Received {0} users from Google.", totalUsers)); WriteResponseLog(string.Format("Replication for Organization '{0}' is started at {1}.", org.Name, start)); totalUsers = userFeed.Entries.Count; for (int i = 0; i < totalUsers; i++) { UserEntry userEntry = userFeed.Entries[i] as UserEntry; try { GoogleProvider.ImportUser(userEntry, org.OrganizationId, service.Domain); } catch (Exception ex) { failedUsers++; WriteResponseLog(string.Format("Replication failed for Organization: {0}; Google domain: {1}; UserName: {2}. Error message: {3}.", org.Name, domain, userEntry.Login.UserName, ex.Message)); WriteResponseLog(string.Format("Full error: {0}.", ex.ToString())); } } DateTime end = DateTime.UtcNow; WriteResponseLog(string.Format("Replication for Organization '{0}' is finished at {1}. Replication takes {2} minutes.", org.Name, end, Math.Round((end - start).TotalMinutes, TIME_ROUND_DIGITS))); WriteResponseLog(string.Format("Number of successfully replicated users: {0}.", totalUsers - failedUsers)); WriteResponseLog(string.Format("Number of not successfully replicated users: {0}.", failedUsers)); isSuccess = true; } } catch (Exception ex) { WriteResponseLog(string.Format("GoogleReplicator replication process is failed for Organization '{0}' for Google domain '{1}'. Error message: {2}.", org.Name, domain, ex.Message)); WriteResponseLog(string.Format("Full error: {0}.", ex.ToString())); } if (!isSuccess) { failed++; } else { success++; } } } else { WriteResponseLog(string.Format("Organization '{0}' is not configured for Google replication. Google domain is missing.", org.Name)); } } } catch (Exception ex) { failed++; WriteResponseLog(string.Format("GoogleReplicator replication process failed for Organization '{0}'. Error: {1}.", org.Name, ex.ToString())); } } } catch (Exception ex) { WriteResponseLog(string.Format("GoogleReplicator error: {0}.", ex.ToString())); } DateTime endDate = DateTime.UtcNow; WriteResponseLog(string.Format("GoogleReplicator finished replication process at {0}. Process was run for {1} minutes.", endDate, Math.Round((endDate - startDate).TotalMinutes, TIME_ROUND_DIGITS))); WriteResponseLog(string.Format("Number of successful replications: {0}.", success)); WriteResponseLog(string.Format("Number of failed replications: {0}.", failed)); }
/// <summary> /// .... /// </summary> private int ExecInternalApps() { // Retrieve user list List <String> usernames = new List <string>(); try { if (_config.appsOnlyOAuth) { GOAuthRequestFactory reqF = new GOAuthRequestFactory("apps", "GDocBackup"); reqF.ConsumerKey = _config.appsDomain; reqF.ConsumerSecret = _config.appsOAuthSecret; UserService userService = new UserService("GDocBackup"); userService.RequestFactory = reqF; UserQuery query = new UserQuery(_config.appsDomain, true); UserFeed usersFeed = userService.Query(query); foreach (UserEntry entry in usersFeed.Entries) { usernames.Add(entry.Login.UserName); } } else { string domainAdminUsername = this.BuildDomainUserFullName(_config.userName); AppsService appsServ = new AppsService(_config.appsDomain, domainAdminUsername, _config.password); UserFeed usersFeed = appsServ.RetrieveAllUsers(); foreach (UserEntry entry in usersFeed.Entries) { usernames.Add(entry.Login.UserName); } } DoFeedback("Users: (" + usernames.Count + ")"); foreach (string x in usernames) { DoFeedback(" > " + x); } } catch (Exception ex) { throw new ApplicationException("Error retrieving users list", ex); } // Build output folders, one for each user foreach (string username in usernames) { string x = Path.Combine(_config.outDir, username); if (!Directory.Exists(x)) { Directory.CreateDirectory(x); } } // Do work for each user! int errCount = 0; _totalAppUsers = usernames.Count; for (int i = 0; i < usernames.Count; i++) { _currentAppsUserIndex = i; try { errCount += this.ExecBackupSingleUser(usernames[i]); } catch (Exception ex) { errCount++; DoFeedback("ERROR: " + ex.ToString(), 0); } } return(errCount); }
static void Main(string[] args) { //parse options var options = GoogleAppsAddGroupMemberProgramOptions.Parse(args); if (options.Help) { options.PrintHelp(Console.Out); return; } if (options.Incomplete) { CollectOptionsInteractiveConsole(options); } if (!options.Username.Contains("@")) { Console.WriteLine("Whoops. Your username must be an email address."); Console.WriteLine(); options.Username = null; CollectOptionsInteractiveConsole(options); } //create service object var service = new AppsService(options.Domain, options.Username, options.Password); try { if (options.List) { ListGroups(Console.Out, service); } else if (!string.IsNullOrEmpty(options.ListMembers)) { ListGroupMembers(Console.Out, service, options.ListMembers); } else if (!string.IsNullOrEmpty(options.ListGroupsForMember)) { ListGroupsForMember(Console.Out, service, options.ListGroupsForMember); } else { //add members to group if (string.IsNullOrEmpty(options.File)) { AddGroupMemberInteractiveConsole(service, options.Domain); } else { AddGroupMemberBatch(Console.Out, service, options.Domain, options.File); } } } catch (InvalidCredentialsException) { Console.WriteLine(); Console.WriteLine("Invalid Credentials."); } catch (CaptchaRequiredException) { Console.WriteLine(); Console.WriteLine("Your account has been locked by Google."); Console.WriteLine("Use your browser to unlock your account."); Console.WriteLine("https://www.google.com/accounts/UnlockCaptcha"); } }
static void AddGroupMemberInteractiveConsole(AppsService service, string primaryDomain) { Console.WriteLine(); Console.WriteLine("No batch file option (-f). Entering interactive mode."); Console.WriteLine("Press CTRL+C to quit."); Console.WriteLine(); string lastGroup = null; while (true) //continue until CTRL+C { bool confirm = false; string group = null, member = null; while (string.IsNullOrEmpty(group)) { if (lastGroup == null) { Console.Write("Group [group@domain]: "); } else { Console.Write(string.Format("Group {0} [enter to confirm]: ", lastGroup)); } group = Console.ReadLine(); if (lastGroup != null && string.IsNullOrEmpty(group)) { group = lastGroup; } lastGroup = group; } while (string.IsNullOrEmpty(member)) { Console.Write(String.Format("Member to add to {0}: ", group)); member = Console.ReadLine(); } Console.Write(string.Format("Please confirm: Add {0} to {1} (y/n)? ", member, group)); confirm = Console.ReadLine().StartsWith("y", StringComparison.InvariantCultureIgnoreCase); if (!confirm) { Console.WriteLine("Cancelled. Group member not added."); } else { try { Console.WriteLine(AddGroupMember(service, group, member)); } catch (InvalidCredentialsException) { Console.WriteLine(); Console.WriteLine("Invalid Credentials."); Console.WriteLine(); //collect new credentials var options = new GoogleAppsAddGroupMemberProgramOptions() { Domain = primaryDomain }; CollectOptionsInteractiveConsole(options); service = new AppsService(options.Domain, options.Username, options.Password); } } Console.WriteLine(); } }
public void Init() { service = new AppsService("example.com", "admin", "password"); }