// get people work with public async Task <List <MsPerson> > GetPeopleAsync(string name) { PeopleResource.ConnectionsResource.ListRequest peopleRequest = service.People.Connections.List("people/me"); peopleRequest.RequestMaskIncludeField = "person.emailAddresses,person.names"; ListConnectionsResponse connectionsResponse = await peopleRequest.ExecuteAsync(); IList <GooglePerson> connections = connectionsResponse.Connections; var result = new List <MsPerson>(); if (connections != null && connections.Count > 0) { foreach (var people in connections) { // filter manually var displayName = people.Names[0]?.DisplayName; if (people.EmailAddresses?.Count > 0 && displayName != null && displayName.ToLower().Contains(name.ToLower())) { result.Add(this.GooglePersonToMsPerson(people)); } } } return(result); }
// get people work with private async Task <List <PersonModel> > GetGooglePeopleAsync() { try { PeopleResource.ConnectionsResource.ListRequest peopleRequest = service.People.Connections.List("people/me"); peopleRequest.RequestMaskIncludeField = "person.emailAddresses,person.names,person.photos"; ListConnectionsResponse connectionsResponse = await((IClientServiceRequest <ListConnectionsResponse>)peopleRequest).ExecuteAsync(); IList <Person> connections = connectionsResponse.Connections; List <PersonModel> result = new List <PersonModel>(); if (connections != null && connections.Count > 0) { foreach (var people in connections) { if (people != null) { result.Add(new PersonModel(people)); } } } return(result); } catch (GoogleApiException ex) { throw GoogleClient.HandleGoogleAPIException(ex); } }
private async Task <IList <Person> > GetPeople() { try { PeopleResource.ConnectionsResource.ListRequest peopleRequest = service.People.Connections.List("people/me"); peopleRequest.RequestMaskIncludeField = "person.phoneNumbers,person.names"; ListConnectionsResponse connectionsResponse = await((IClientServiceRequest <ListConnectionsResponse>)peopleRequest).ExecuteAsync(); if (connectionsResponse == null) { return(new List <Person>()); } IList <Person> connections = connectionsResponse.Connections; if (connections == null) { return(new List <Person>()); } return(connections); } catch (GoogleApiException ex) { throw GoogleClient.HandleGoogleAPIException(ex); } }
// get people work with private async Task <List <Person> > GetGooglePeopleAsync(string name) { try { PeopleResource.ConnectionsResource.ListRequest peopleRequest = service.People.Connections.List("people/me"); peopleRequest.RequestMaskIncludeField = "person.emailAddresses,person.names"; ListConnectionsResponse connectionsResponse = await((IClientServiceRequest <ListConnectionsResponse>)peopleRequest).ExecuteAsync(); IList <Person> connections = connectionsResponse.Connections; List <Person> result = new List <Person>(); if (connections != null && connections.Count > 0) { foreach (var people in connections) { // filter manually var displayName = people.Names[0]?.DisplayName; if (people.EmailAddresses?.Count > 0 && displayName != null && displayName.ToLower().Contains(name.ToLower())) { result.Add(people); } } } return(result); } catch (GoogleApiException ex) { throw GoogleClient.HandleGoogleAPIException(ex); } }
/// <summary> /// Get Google Access Tokens /// </summary> /// <param name="userId"></param> /// <returns></returns> public async Task <string> GetGoogleAccessToken(string userId) { string accessToken = null; User user = await GetUser(userId); foreach (Identity userIdentity in user?.Identities) { if (userIdentity.Provider == "google-oauth2") { accessToken = userIdentity.AccessToken; string refreshToken = userIdentity.RefreshToken; PeopleServiceService peopleService = new PeopleServiceService(new BaseClientService.Initializer() { ApplicationName = "Pizza42", }); peopleService.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); PeopleResource.ConnectionsResource.ListRequest peopleRequest = peopleService.People.Connections.List("people/me"); peopleRequest.PersonFields = "names,emailAddresses"; ListConnectionsResponse connectionsResponse = peopleRequest.Execute(); IList <Person> connections = connectionsResponse.Connections; int connectionCount = connections.Count; } } return(accessToken); }
public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems) { AmazonCodeStarconnectionsConfig config = new AmazonCodeStarconnectionsConfig(); config.RegionEndpoint = region; ConfigureClient(config); AmazonCodeStarconnectionsClient client = new AmazonCodeStarconnectionsClient(creds, config); ListConnectionsResponse resp = new ListConnectionsResponse(); do { ListConnectionsRequest req = new ListConnectionsRequest { NextToken = resp.NextToken , MaxResults = maxItems }; resp = client.ListConnections(req); CheckError(resp.HttpStatusCode, "200"); foreach (var obj in resp.Connections) { AddObject(obj); } }while (!string.IsNullOrEmpty(resp.NextToken)); }
/// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { ListConnectionsResponse response = new ListConnectionsResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ConnectionSummaryList", targetDepth)) { var unmarshaller = new ListUnmarshaller <ConnectionSummary, ConnectionSummaryUnmarshaller>(ConnectionSummaryUnmarshaller.Instance); response.ConnectionSummaryList = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("NextToken", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.NextToken = unmarshaller.Unmarshall(context); continue; } } return(response); }
/// <summary> /// Get Goolge Connections /// </summary> /// <returns></returns> public IList <Person> GetGoogleConnections() { PeopleResource.ConnectionsResource.ListRequest peopleRequest = _peopleService.People.Connections.List("people/me"); peopleRequest.PersonFields = "names,emailAddresses"; ListConnectionsResponse connectionsResponse = peopleRequest.Execute(); return(connectionsResponse.Connections); }
/// <summary>Snippet for ListConnections</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void ListConnectionsResourceNames() { // Create client ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); uint? maxResults = 0U; // Make the request ListConnectionsResponse response = connectionServiceClient.ListConnections(parent, maxResults); }
//with uuid // public bool updateAttendees(string uuid) public IList <Person> getAll() { PeopleResource.ConnectionsResource.ListRequest peopleRequest = peopleService.People.Connections.List("people/me"); peopleRequest.PersonFields = "names,emailAddresses,userDefined"; ListConnectionsResponse connectionsResponse = peopleRequest.Execute(); IList <Person> connections = connectionsResponse.Connections; return(connections); }
/// <summary>Snippet for ListConnectionsAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task ListConnectionsAsync() { // Create client ConnectionServiceClient connectionServiceClient = await ConnectionServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; uint? maxResults = 0U; // Make the request ListConnectionsResponse response = await connectionServiceClient.ListConnectionsAsync(parent, maxResults); }
// returns null if there are no Attendees public static IList <Person> IgetAllAttendees() { // gets all attendees PeopleResource.ConnectionsResource.ListRequest peopleRequest = peopleService.People.Connections.List("people/me"); peopleRequest.PersonFields = "names,emailAddresses,userDefined"; ListConnectionsResponse connectionsResponse = peopleRequest.Execute(); IList <Person> attendees = connectionsResponse.Connections; return(attendees); }
/// <summary>Snippet for ListConnections</summary> public void ListConnections() { // Snippet: ListConnections(string, uint?, CallSettings) // Create client ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; uint? maxResults = 0U; // Make the request ListConnectionsResponse response = connectionServiceClient.ListConnections(parent, maxResults); // End snippet }
/// <summary>Snippet for ListConnections</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void ListConnectionsRequestObject() { // Create client ConnectionServiceClient connectionServiceClient = ConnectionServiceClient.Create(); // Initialize request argument(s) ListConnectionsRequest request = new ListConnectionsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), MaxResults = 0U, PageToken = "", }; // Make the request ListConnectionsResponse response = connectionServiceClient.ListConnections(request); }
private static void Main(string[] args) { //var header = new Header //{ // Algorithmn = "SHA256", // Type = "JWT" //}; //var headerEncoded = Base64UrlEncoder.Encode(JsonConvert.SerializeObject(header)); //var claimSet = new ClaimSet //{ // Audience = "https://www.googleapis.com/oauth2/v4/token", // Email = "*****@*****.**", // Expiry = 1328554385, // IssuedAt = 1328550785 //}; //var claimSetEncoded = Base64UrlEncoder.Encode(JsonConvert.SerializeObject(claimSet)); //var signature = new Signature().Encode(header, claimSet); //var base64Encoded = $"{headerEncoded}.{claimSetEncoded}.{signature}"; //var certificate = new X509Certificate2(@"deployment_cert.der"); //ServiceAccountCredential credential = new ServiceAccountCredential( // new ServiceAccountCredential.Initializer("email") // { // }..FromCertificate(certificate)); //var credential = ServiceAccountCredential.FromServiceAccountData(/*File.OpenRead(@"C:\Users\danchi\Desktop\logos.json")*/) var scope = DriveService.Scope.Drive; var credential = GoogleCredential.FromStream(File.OpenRead(@"C:\Users\danchi\Desktop\logos.json")) .CreateScoped("https://www.googleapis.com/auth/contacts.readonly") .UnderlyingCredential as ServiceAccountCredential; // Create the service. var service = new PeopleService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "logos", }); PeopleResource.ConnectionsResource.ListRequest peopleRequest = service.People.Connections.List("people/me"); //peopleRequest.PersonFields = "names,emailAddresses"; ListConnectionsResponse connectionsResponse = peopleRequest.Execute(); IList <Person> connections = connectionsResponse.Connections; }
/// <summary>Snippet for ListConnectionsAsync</summary> public async Task ListConnectionsAsync() { // Snippet: ListConnectionsAsync(string, uint?, CallSettings) // Additional: ListConnectionsAsync(string, uint?, CancellationToken) // Create client ConnectionServiceClient connectionServiceClient = await ConnectionServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; uint? maxResults = 0U; // Make the request ListConnectionsResponse response = await connectionServiceClient.ListConnectionsAsync(parent, maxResults); // End snippet }
/// <summary>Snippet for ListConnectionsAsync</summary> public async Task ListConnectionsResourceNamesAsync() { // Snippet: ListConnectionsAsync(LocationName, uint?, CallSettings) // Additional: ListConnectionsAsync(LocationName, uint?, CancellationToken) // Create client ConnectionServiceClient connectionServiceClient = await ConnectionServiceClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); uint? maxResults = 0U; // Make the request ListConnectionsResponse response = await connectionServiceClient.ListConnectionsAsync(parent, maxResults); // End snippet }
private IList <Person> GetContact() { PeopleResource.ConnectionsResource.ListRequest peopleRequest = GoogleContactManager.Instance.Service.People.Connections.List("people/me"); peopleRequest.RequestMaskIncludeField = "person.names,person.emailAddresses,person.PhoneNumbers"; ListConnectionsResponse connectionsResponse = peopleRequest.Execute(); IList <Person> contact = connectionsResponse.Connections; IList <Person> allContacts = contact; while (connectionsResponse.NextPageToken != null) { peopleRequest.PageToken = connectionsResponse.NextPageToken; connectionsResponse = peopleRequest.Execute(); allContacts = allContacts.Union(connectionsResponse.Connections).ToList(); } return(allContacts); }
public GoogleContacts() { // Create OAuth credential. UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = m_client_id, ClientSecret = m_client_secret }, new[] { "profile", "https://www.googleapis.com/auth/contacts.readonly" }, "me", CancellationToken.None).Result; // Create the service. var service = new PeopleServiceService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "My App", }); // Groups list //////////// ContactGroupsResource groupsResource = new ContactGroupsResource(service); ContactGroupsResource.ListRequest listRequest = groupsResource.List(); ListContactGroupsResponse response = listRequest.Execute(); // eg to show name of each group List <string> groupNames = new List <string>(); foreach (ContactGroup group in response.ContactGroups) { groupNames.Add(group.FormattedName); } /////////////// // Contact list //////////// PeopleResource.ConnectionsResource.ListRequest peopleRequest = service.People.Connections.List("people/me"); peopleRequest.PersonFields = "names,emailAddresses"; peopleRequest.SortOrder = (PeopleResource.ConnectionsResource.ListRequest.SortOrderEnum) 1; ListConnectionsResponse people = peopleRequest.Execute(); // eg to show display name of each contact List <string> contacts = new List <string>(); foreach (var person in people.Connections) { contacts.Add(person.Names[0].DisplayName); } /////////////// }
public static ListConnectionsResponse Unmarshall(UnmarshallerContext context) { ListConnectionsResponse listConnectionsResponse = new ListConnectionsResponse(); listConnectionsResponse.HttpResponse = context.HttpResponse; listConnectionsResponse.HttpStatusCode = context.IntegerValue("ListConnections.HttpStatusCode"); listConnectionsResponse.Success = context.BooleanValue("ListConnections.Success"); listConnectionsResponse.RequestId = context.StringValue("ListConnections.RequestId"); ListConnectionsResponse.ListConnections_Data data = new ListConnectionsResponse.ListConnections_Data(); data.PageNumber = context.IntegerValue("ListConnections.Data.PageNumber"); data.PageSize = context.IntegerValue("ListConnections.Data.PageSize"); data.TotalCount = context.IntegerValue("ListConnections.Data.TotalCount"); List <ListConnectionsResponse.ListConnections_Data.ListConnections_ConnectionsItem> data_connections = new List <ListConnectionsResponse.ListConnections_Data.ListConnections_ConnectionsItem>(); for (int i = 0; i < context.Length("ListConnections.Data.Connections.Length"); i++) { ListConnectionsResponse.ListConnections_Data.ListConnections_ConnectionsItem connectionsItem = new ListConnectionsResponse.ListConnections_Data.ListConnections_ConnectionsItem(); connectionsItem.Shared = context.BooleanValue("ListConnections.Data.Connections[" + i + "].Shared"); connectionsItem.GmtModified = context.StringValue("ListConnections.Data.Connections[" + i + "].GmtModified"); connectionsItem.ConnectStatus = context.IntegerValue("ListConnections.Data.Connections[" + i + "].ConnectStatus"); connectionsItem.BindingCalcEngineId = context.IntegerValue("ListConnections.Data.Connections[" + i + "].BindingCalcEngineId"); connectionsItem.Description = context.StringValue("ListConnections.Data.Connections[" + i + "].Description"); connectionsItem.ConnectionType = context.StringValue("ListConnections.Data.Connections[" + i + "].ConnectionType"); connectionsItem.GmtCreate = context.StringValue("ListConnections.Data.Connections[" + i + "].GmtCreate"); connectionsItem.DefaultEngine = context.BooleanValue("ListConnections.Data.Connections[" + i + "].DefaultEngine"); connectionsItem._Operator = context.StringValue("ListConnections.Data.Connections[" + i + "].Operator"); connectionsItem.Sequence = context.IntegerValue("ListConnections.Data.Connections[" + i + "].Sequence"); connectionsItem.EnvType = context.IntegerValue("ListConnections.Data.Connections[" + i + "].EnvType"); connectionsItem.TenantId = context.LongValue("ListConnections.Data.Connections[" + i + "].TenantId"); connectionsItem.Name = context.StringValue("ListConnections.Data.Connections[" + i + "].Name"); connectionsItem.SubType = context.StringValue("ListConnections.Data.Connections[" + i + "].SubType"); connectionsItem.Id = context.IntegerValue("ListConnections.Data.Connections[" + i + "].Id"); connectionsItem.ProjectId = context.IntegerValue("ListConnections.Data.Connections[" + i + "].ProjectId"); connectionsItem.Status = context.IntegerValue("ListConnections.Data.Connections[" + i + "].Status"); connectionsItem.Content = context.StringValue("ListConnections.Data.Connections[" + i + "].Content"); data_connections.Add(connectionsItem); } data.Connections = data_connections; listConnectionsResponse.Data = data; return(listConnectionsResponse); }
/// <summary>Snippet for ListConnectionsAsync</summary> public async Task ListConnectionsRequestObjectAsync() { // Snippet: ListConnectionsAsync(ListConnectionsRequest, CallSettings) // Additional: ListConnectionsAsync(ListConnectionsRequest, CancellationToken) // Create client ConnectionServiceClient connectionServiceClient = await ConnectionServiceClient.CreateAsync(); // Initialize request argument(s) ListConnectionsRequest request = new ListConnectionsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), MaxResults = 0U, PageToken = "", }; // Make the request ListConnectionsResponse response = await connectionServiceClient.ListConnectionsAsync(request); // End snippet }
private void btnGetContacts_Click(object sender, EventArgs e) { PeopleResource.ConnectionsResource.ListRequest peopleRequest = peopleService.People.Connections.List("people/me"); peopleRequest.RequestMaskIncludeField = "person.addresses,person.biographies,person.birthdays,person.emailAddresses," + "person.genders,person.names,person.organizations,person.phoneNumbers"; peopleRequest.PageSize = 2000; ListConnectionsResponse connectionsResponse = peopleRequest.Execute(); IList <Person> connections = connectionsResponse.Connections; pbrContacts.Maximum = connections.Count; int contacts = 0; foreach (Person person in connections) { ContactEventArgs args = new ContactEventArgs(); if (person.Names != null) { args.firstName = person.Names[0].GivenName; args.lastName = person.Names[0].FamilyName; args.middleName = person.Names[0].MiddleName; } if (person.Addresses != null) { foreach (var addr in person.Addresses) { if (addr.Type == "work") { args.businessStreet = addr.StreetAddress; args.businessCity = addr.City; args.businessRegion = addr.Region; args.businessPostcode = addr.PostalCode; args.businessCountry = addr.Country; } else { args.privateStreet = addr.StreetAddress; args.privateCity = addr.City; args.privateRegion = addr.Region; args.privatePostcode = addr.PostalCode; args.privateCountry = addr.Country; } } } if (person.PhoneNumbers != null) { foreach (var numb in person.PhoneNumbers) { if (numb.Type == "work" && string.IsNullOrEmpty(args.businessPhone)) { args.businessPhone = numb.Value; } else if (numb.Type == "work" && !string.IsNullOrEmpty(args.businessPhone)) { args.business2Phone = numb.Value; } else if (numb.Type == "home" && string.IsNullOrEmpty(args.privatePhone)) { args.privatePhone = numb.Value; } else if (numb.Type == "mobile" && string.IsNullOrEmpty(args.mobilePhone)) { args.mobilePhone = numb.Value; } else if (numb.Type == "homeFax" && string.IsNullOrEmpty(args.privateFax)) { args.privateFax = numb.Value; } else if (numb.Type == "workFax" && string.IsNullOrEmpty(args.businessFax)) { args.businessFax = numb.Value; } else if (numb.Type == "pager" && string.IsNullOrEmpty(args.pager)) { args.pager = numb.Value; } else { args.notes += "Other Phone Numbers: " + numb.Type + ": " + numb.Value + Environment.NewLine; } } } if (person.EmailAddresses != null) { foreach (var mail in person.EmailAddresses) { if (mail.Type == "home") { args.privateEmail = mail.Value; } else if (mail.Type == "work" && string.IsNullOrEmpty(args.businessEmail)) { args.businessEmail = mail.Value; } else if (mail.Type == "work" && !string.IsNullOrEmpty(args.businessEmail) && string.IsNullOrEmpty(args.business2Email)) { args.business2Email = mail.Value; } else if (mail.Type == "other" && string.IsNullOrEmpty(args.businessEmail)) { args.businessEmail = mail.Value; } else if (mail.Type == "other" && string.IsNullOrEmpty(args.business2Email)) { args.business2Email = mail.Value; } else if (mail.Type == "other" && string.IsNullOrEmpty(args.privateEmail)) { args.privateEmail = mail.Value; } else { args.notes += "Other E-Mail Addresses: " + mail.Type + ": " + mail.Value + Environment.NewLine; } } } if (person.Biographies != null) { if (!string.IsNullOrEmpty(args.notes)) { args.notes += Environment.NewLine + person.Biographies[0].Value; } else { args.notes = person.Biographies[0].Value; } } if (person.Birthdays != null) { args.birthday = new DateTime(person.Birthdays[0].Date.Year.Value, person.Birthdays[0].Date.Month.Value, person.Birthdays[0].Date.Day.Value); } if (person.Genders != null) { args.gender = person.Genders[0].Value; } if (person.Organizations != null) { args.company = person.Organizations[0].Name; args.jobTitle = person.Organizations[0].Title; } OnContactReady(args); contacts++; pbrContacts.PerformStep(); } MessageBox.Show("Successfully imported " + contacts + " contacts!"); }
static void GetPeople(PeopleService service, string pageToken) { // Define parameters of request. PeopleResource.ConnectionsResource.ListRequest peopleRequest = service.People.Connections.List("people/me"); // // Lista de campos a usar en RequestMaskIncludeField: // https://developers.google.com/people/api/rest/v1/people/get // peopleRequest.RequestMaskIncludeField = new List <string>() { "person.names", "person.phoneNumbers", "person.emailAddresses", "person.birthdays", "person.Addresses" }; if (pageToken != null) { peopleRequest.PageToken = pageToken; } ListConnectionsResponse people = peopleRequest.Execute(); if (people != null && people.Connections != null && people.Connections.Count > 0) { total += people.Connections.Count; foreach (var person in people.Connections) { Console.Write(person.Names != null ? ($"{person.Names.FirstOrDefault().DisplayName} - ") : ""); Console.Write(person.PhoneNumbers != null ? ($"{person.PhoneNumbers.FirstOrDefault().Value} - ") : ""); Console.Write(person.EmailAddresses != null ? ($"{person.EmailAddresses.FirstOrDefault().Value} - ") : ""); Console.Write(person.Addresses != null ? ($"{person.Addresses.FirstOrDefault()?.City} - ") : ""); if (person.Birthdays != null) { var fecha = ""; var b = person.Birthdays.FirstOrDefault()?.Date; if (b != null) { fecha = $"{b.Day}/{b.Month}/{b.Year}"; } Console.Write($"{fecha}"); } Console.WriteLine(); } if (people.NextPageToken != null) { Console.WriteLine(); Console.WriteLine($"{total} contactos mostrados hasta ahora. Pulsa una tecla para seguir mostrando contactos."); Console.WriteLine(); Console.ReadKey(); GetPeople(service, people.NextPageToken); } } else { Console.WriteLine("No se han encontrado contactos."); return; } }
public async Task <IActionResult> Contact() { string gCode = TempData["code"].ToString(); string ClientSecret = _config.GetValue <string>("GooglePoepleAPI:ClientSecret"); string ClientId = _config.GetValue <string>("GooglePoepleAPI:ClientId"); string userId = "userId"; const string dataStoreFolder = "googleApiStorageFile"; // create authorization code flow with clientSecrets GoogleAuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { DataStore = new FileDataStore(dataStoreFolder), ClientSecrets = new ClientSecrets() { ClientId = ClientId, ClientSecret = ClientSecret } }); FileDataStore fileStore = new FileDataStore(dataStoreFolder); TokenResponse tokenResponse = await fileStore.GetAsync <TokenResponse>(userId); if (tokenResponse == null) { // token data does not exist for this user tokenResponse = await authorizationCodeFlow.ExchangeCodeForTokenAsync( userId, // user for tracking the userId on our backend system gCode, "http://localhost:5000/people/", // redirect_uri can not be empty. Must be one of the redirects url listed in your project in the api console CancellationToken.None); } UserCredential userCredential = new UserCredential(authorizationCodeFlow, userId, tokenResponse); var service = new PeopleServiceService(new BaseClientService.Initializer() { HttpClientInitializer = userCredential, ApplicationName = "VAapps", }); ContactGroupsResource groupsResource = new ContactGroupsResource(service); ContactGroupsResource.ListRequest listRequest = groupsResource.List(); ListContactGroupsResponse response = listRequest.Execute(); List <string> listOnView = new List <string>(); foreach (ContactGroup group in response.ContactGroups) { listOnView.Add("Groups: " + group.FormattedName); } Google.Apis.PeopleService.v1.PeopleResource.ConnectionsResource.ListRequest peopleRequest = service.People.Connections.List("people/me"); peopleRequest.PersonFields = "names,emailAddresses,phoneNumbers"; peopleRequest.SortOrder = (Google.Apis.PeopleService.v1.PeopleResource.ConnectionsResource.ListRequest.SortOrderEnum) 1; peopleRequest.PageSize = 1999; ListConnectionsResponse people = peopleRequest.Execute(); // are: * addresses * ageRanges * biographies * birthdays * braggingRights * coverPhotos // * emailAddresses * events * genders * imClients * interests * locales * memberships // * metadata * names * nicknames * occupations * organizations * phoneNumbers * // photos * relations * relationshipInterests * relationshipStatuses * residences // * sipAddresses * skills * taglines * urls * userDefined var me = service.People.Get("people/me"); me.PersonFields = "names,emailAddresses,phoneNumbers,birthdays,coverPhotos,metadata,events"; var aboutMe = me.Execute(); ViewBag.AboutMe = aboutMe; ViewBag.ContactList = people.Connections; return(View()); }
public override async Task <ActionResult> IndexAsync(AuthorizationCodeResponseUrl authorizationCode, CancellationToken taskCancellationToken) { if (string.IsNullOrEmpty(authorizationCode.Code)) { var errorResponse = new TokenErrorResponse(authorizationCode); Logger.Info("Received an error. The response is: {0}", errorResponse); return(OnTokenError(errorResponse)); } Logger.Debug("Received \"{0}\" code", authorizationCode.Code); var returnUrl = Request.Url.ToString(); returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?")); //Asynchronously exchanges code with a token. var token = await Flow.ExchangeCodeForTokenAsync(UserId, authorizationCode.Code, returnUrl, taskCancellationToken).ConfigureAwait(false); //Constructs a new credential instance with access token var credential = new UserCredential(Flow, UserId, token); try { var peopleService = new PeopleServiceService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "< YOUR APP NAME >", }); #region Contacts PeopleResource.ConnectionsResource.ListRequest peopleRequest = peopleService.People.Connections.List("people/me"); peopleRequest.PersonFields = "addresses,ageRanges,biographies,birthdays,calendarUrls," + "clientData,coverPhotos,emailAddresses,events,externalIds,genders,imClients," + "interests,locales,locations,memberships,metadata,miscKeywords,names,nicknames," + "occupations,organizations,phoneNumbers,photos,relations,sipAddresses,skills,urls,userDefined"; peopleRequest.SortOrder = PeopleResource.ConnectionsResource.ListRequest.SortOrderEnum.LASTMODIFIEDDESCENDING; peopleRequest.PageSize = 1000; ListConnectionsResponse connectionsResponse = peopleRequest.Execute(); List <Person> connections = connectionsResponse.Connections as List <Person>; // get all pages while (!string.IsNullOrEmpty(connectionsResponse.NextPageToken)) { peopleRequest.PageToken = connectionsResponse.NextPageToken; connectionsResponse = peopleRequest.Execute(); connections.AddRange(connectionsResponse.Connections); } #endregion var model = connections.Where(x => x.EmailAddresses != null && x.EmailAddresses.Any()); return(View(model)); } catch (Exception exp) { Logger.Info("Received an error. The response is: {0}", exp.Message); return(View("Error")); } }