I am creating shared contacts in google, it creates the contact, but I can't see the contacts in the directory in google contacts.
I have looked for answers and found this probably closest.. but I can't seem to get it right...
Here is some code:
string s = "https://www.google.com/m8/feeds";
string targetUri = #"https://www.google.com/m8/feeds/contacts/mycompany.com/full";
string serviceAccountEmail = "123456789012-xxxx1x1xx11x1xxxxxxx11xxxx1xxx11#developer.gserviceaccount.com";
string serviceClientId = "123456789012-xxxx1x1xx11x1xxxxxxx11xxxx1xxx11.apps.googleusercontent.com";
X509Certificate2 certificate = new X509Certificate2(#"C:\All\mygcertificate-1xx1xxx1xx11.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[]
{
"http://www.google.com/m8/feeds/contacts/"
},
User = "my.user#mycompany.com"
}.FromCertificate(certificate));
string AuthenticationToken1 = string.Empty;
if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
{
AuthenticationToken1 = credential.Token.AccessToken;
}
Service service = new Service(s, serviceClientId);
GAuthSubRequestFactory factory = new GAuthSubRequestFactory(s, serviceClientId);
factory.Token = AuthenticationToken1;
service.RequestFactory = factory;
Contact ct = new Contact();
ct.Name = new Google.GData.Extensions.Name() { GivenName = "Ron", FamilyName = "Swanson", FullName = "Ron Swanson" };
ct.Emails.Add(new Google.GData.Extensions.EMail("Ron.Swanson#someclient.com", #"http://schemas.google.com/g/2005#work") { Primary = true });
ct.Phonenumbers.Add(new Google.GData.Extensions.PhoneNumber("2345555522") { Rel = #"http://schemas.google.com/g/2005#work", Primary = true});
AtomCategory atc = new AtomCategory();
atc.Term = #"http://schemas.google.com/contact/2008#contact";
atc.Scheme = #"http://schemas.google.com/g/2005#kind";
ct.Categories.Add(atc);
var atomentrytoinsert = ct.AtomEntry;
var result = service.Insert(new Uri(targetUri), atomentrytoinsert);
//Stream getresult = service.Query(new Uri(targetUri)); //this read actually gets the records i inserted...
If i run that last commented out line, i can see the entries I created ... but when I go to google contacts and click directory - They are not there. Also not on autocomplete when I compose email... Am I missing a attribute somewhere.
I have left the entries over 24 hours (I created them on Friday).
Would appreciate any input.
I tryed the sharedcontact API yesterday, the new contacts were not visible in directory.
But this morning the autocomplete has suggested the new contacts! To make them visible in the directory I had to open the Admin google Console->google apps-> contacts -> advanced settings and checked the " shows both the profiles of the domain is the Domain Shared Contacts"
It worked immediately for me, I hope help you!
Related
I'm using PeopleService in order to create contacts straight into my G Suit Account. I followed the security steps about getting the key for a type of Service Account. My Application will create contacts so that there's no need to request a specific user permission. It has its own key and credentials.
My code seems to work except because the CreateContactRequest provides me ResourceName with value "people/c171255166120767303". And every time I request I got a different resourceName like this "people/c9013378989213012841".
The problem is, where the hell that goes? At my G Suite account, I can’t see the created contact anywhere.
But the resulting Person object seems to be ok.
How can I check if this works? Where the contact was created?
The code is as bellow:
private static string _clientId = "1........1";
private static string _clienteScret = "i******************_";
private static string _serviceAccountId = "aaaa#bbbb.iam.gserviceaccount.com";
public static void Cadastrar(Models.SignupRequest message)
{
var chave =
#"D:\********.p12";
var certificate = new X509Certificate2(chave, "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(_serviceAccountId)
{
Scopes = new[] {
PeopleService.Scope.Contacts,
PeopleService.Scope.ContactsReadonly,
"https://www.google.com/m8/feeds"
}
}.FromCertificate(certificate));
var service = new PeopleService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Client for www",
});
var contactToCreate = new Person();
var names = new List<Name> {new Name() {GivenName = message.name, FamilyName = "Doe"}};
contactToCreate.Names = names;
contactToCreate.EmailAddresses = new List<EmailAddress>
{
new EmailAddress()
{
DisplayName = message.name,
Value = message.email
}
};
contactToCreate.Organizations = new List<Organization>
{
new Organization()
{
Current = true,
Name = message.nome_fantasia,
}
};
contactToCreate.Biographies = new List<Biography>
{
new Biography()
{
Value = message.ToString()
}
};
contactToCreate.PhoneNumbers = new List<PhoneNumber>
{
new PhoneNumber()
{
Type = "mobile",
Value = message.celular
},
new PhoneNumber()
{
Type = "work",
Value = message.telefone
}
};
var request = new Google.Apis.PeopleService.v1.PeopleResource.CreateContactRequest(service, contactToCreate);
var createdContact = request.Execute();
}
If you want to create contact for user with 'email#yourdomain.com' through a service account you need:
Use "setServiceAccountUser(userEmail)" to impersonate the user
Enable impersonation on your G-Suite for People API service. For this point:
See section "Delegating domain wide access" here
Get client-id from your credential account
Use "https://www.googleapis.com/auth/contacts" as scope.
I have an issue with the authorization in Google Contacts.
Until June my console C# application worked.
I have made steps to get contacts https://developers.google.com/google-apps/contacts/v3/?hl=en.
I cannot get the contacts; I have only access to serviceAccountEmail (xxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com).
I have 2 contacts stored there and I have access only to them.
I want to have access to my 7000 Gmail contacts.
Is there any tutorial for this in C#?
I found ones for analytics and for calendar but not for contacts.
Below is my code:
const string serviceAccountEmail = "xxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com";
var certificate = new X509Certificate2("grdom-all-xxxxxxxxxxxx.p12", "notasecret",
X509KeyStorageFlags.Exportable);
ServiceAccountCredential.Initializer serviceAccountCredentialInitializer =
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { "https://www.google.com/m8/feeds/" },
}.FromCertificate(certificate);
var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer);
if (!credential.RequestAccessTokenAsync(CancellationToken.None).Result)
throw new InvalidOperationException("Access token request failed.");
var oauthParameters = new OAuth2Parameters()
{
AccessToken = credential.Token.AccessToken,
AccessType = "offline",
ApprovalPrompt = "force",
};
var settings = new RequestSettings("grdom-all", oauthParameters)
{
AutoPaging = true,
UseSSL = true,
};
ContactsRequest cr = new ContactsRequest(settings);
var query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
Feed<Contact> f = cr.GetContacts();
foreach (Contact entry in f.Entries)
{
//do something
};
I trying using Google Analytics with C# to get stats information to display in my webiste
Here is my code
public ActionResult Index()
{
string userName = "admin#email.com";
string passWord = "mypass";
string profileId = "ga:xxxxxxxx";
string key = "2d751338cb092ef8da65f716e37a48604386c9sw";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data"+key;
var service = new AnalyticsService("API Project");
service.setUserCredentials(userName, passWord);
var dataQuery = new DataQuery(dataFeedUrl)
{
Ids = profileId,
Metrics = "ga:pageviews",
Sort = "ga:pageviews",
GAStartDate = new DateTime(2010, 3, 1).ToString("yyyy-MM-dd"),
GAEndDate = DateTime.Now.ToString("yyyy-MM-dd")
};
var dataFeed = service.Query(dataQuery);
var totalEntry = dataFeed.Entries[0];
ViewData["Total"] = ((DataEntry)(totalEntry)).Metrics[0].Value;
dataQuery.GAStartDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
dataQuery.GAEndDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
dataFeed = service.Query(dataQuery);
var yesterdayEntry = dataFeed.Entries[0];
ViewData["Yesterday"] = ((DataEntry)(yesterdayEntry)).Metrics[0].Value;
dataQuery.GAStartDate = DateTime.Now.ToString("yyyy-MM-dd");
dataQuery.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
dataFeed = service.Query(dataQuery);
var todayEntry = dataFeed.Entries[0];
ViewData["Today"] = ((DataEntry)(todayEntry)).Metrics[0].Value;
return View(dataFeed.Entries);
}
But when i run the code it always said "{"Invalid credentials"}"
Not sure why i facing this error while i checked many time about the key,username,password and profileId
Anyone facing this problem,can help me?
Many thanks
I think that your url is wrong. try in this way (you are missing ?key=).
string dataFeedUrl = "https://www.google.com/analytics/feeds/data?key="+key;
refer this google example where there is this example that should help you
public DataFeedExample()
{
// Configure GA API.
AnalyticsService asv = new AnalyticsService("gaExportAPI_acctSample_v2.0");
// Client Login Authorization.
asv.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);
// GA Data Feed query uri.
String baseUrl = "https://www.google.com/analytics/feeds/data";
DataQuery query = new DataQuery(baseUrl);
query.Ids = TABLE_ID;
query.Dimensions = "ga:source,ga:medium";
query.Metrics = "ga:visits,ga:bounces";
query.Segment = "gaid::-11";
query.Filters = "ga:medium==referral";
query.Sort = "-ga:visits";
query.NumberToRetrieve = 5;
query.GAStartDate = "2010-03-01";
query.GAEndDate = "2010-03-15";
Uri url = query.Uri;
Console.WriteLine("URL: " + url.ToString());
// Send our request to the Analytics API and wait for the results to
// come back.
feed = asv.Query(query);
}
refer also this guide to configure your project
Also follow this guide to use OAuth 2.0
I got this code to "work" (read not throwing an exception). But the contact is not added to my gmail contacts as it should (nor on my android phone which sync contacts).
Note that I can read the contacts correctly so the credentials are right.
I read that I should check for a Status on the request, but the only Status I see is a property of ContactEntry and it's always null.
This is a console app for tests.
public static void AddContact(ContactDetail contact)
{
GContactService = new ContactsService("Contact Infomation");
GContactService.setUserCredentials("myemail#gmail.com", "mypassword");
ContactEntry newEntry = new ContactEntry();
newEntry.Title.Text = contact.Name;
newEntry.Name = new Name() { FullName = "Tristan Savage", GivenName = "Tristan", FamilyName = "Savage"};
EMail primaryEmail = new EMail(contact.EmailAddress1);
primaryEmail.Primary = true;
primaryEmail.Rel = ContactsRelationships.IsWork;
newEntry.Emails.Add(primaryEmail);
PhoneNumber phoneNumber = new PhoneNumber(contact.Phone);
phoneNumber.Primary = true;
phoneNumber.Rel = ContactsRelationships.IsMobile;
newEntry.Phonenumbers.Add(phoneNumber);
PostalAddress postalAddress = new PostalAddress();
postalAddress.Value = contact.Address;
postalAddress.Primary = true;
postalAddress.Rel = ContactsRelationships.IsCompanyMain;
newEntry.PostalAddresses.Add(new StructuredPostalAddress() { City = "montreal", Label = "Bureau"});
newEntry.Content.Content = contact.Details;
Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default")); //default
ContactEntry createdEntry = (ContactEntry)GContactService.Insert(feedUri, newEntry);
}
I finally figured it out. The GroupMembership is required in order for the contact to get to the mobile device!
Here is the missing part:
var groupMembership = new GroupMembership
{
HRef = "http://www.google.com/m8/feeds/groups/" + utilisateur.CourrielGmailContacts + "/base/6"
};
newEntry.GroupMembership.Add(groupMembership);
Try commenting some lines. With only the name and email, you should be able to create your contact.
I'm able to create a contact with the .NET example here:
https://developers.google.com/google-apps/contacts/v3/?hl=fr#creating_contacts
with Request initialized this way:
ContactsRequest Request = new ContactsRequest(new RequestSettings("appName", "user#gmail.com", "password"));
Please note that your new contact is not associated to a group. So you won't see the contact appearing in "My Contacts"/"Mes Contacts". You should see it in "Other contacts"/"Autres contacts".
I am using the Google Analytics Api to get web property information from my Analytics account.
When I log into analaytics though, I only have one website, but through the api I get several (old and deleted sites)
My code is like this:
var provider = new WebServerClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = _appId,
ClientSecret = _appSecret
};
var auth = new OAuth2Authenticator<WebServerClient>(provider, x => new AuthorizationState { AccessToken = token });
var analyticsService = new AnalyticsService(auth);
var accounts = analyticsService.Management.Accounts.List().Fetch();
foreach (var account in accounts.Items)
{
var webProperties = analyticsService.Management.Webproperties.List(account.Id).Fetch();
// todo: determine if web property is still in use?
}
From code how can I tell which ones are still active?
So after a bit more digging.
It seems there is no flag or anything like that indicating it has been removed, but if you keep digging into the result set you will notice that at the profile level, a profile that doesn't have child items seems to be a deleted one.
Which makes sense I guess there wouldn't be a profile associated with those that have been removed.
var provider = new WebServerClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = _appId,
ClientSecret = _appSecret
};
var auth = new OAuth2Authenticator<WebServerClient>(provider, x => new AuthorizationState { AccessToken = token });
var analyticsService = new AnalyticsService(auth);
var accounts = analyticsService.Management.Accounts.List().Fetch();
var result = new List<Profile>();
foreach (var account in accounts.Items)
{
var webProperties = analyticsService.Management.Webproperties.List(account.Id).Fetch();
foreach (var webProperty in webProperties.Items)
{
var profiles = analyticsService.Management.Profiles.List(account.Id, webProperty.Id).Fetch();
if (profiles.Items != null && profiles.Items.Any())
{
// these are the ones we want
result.AddRange(profiles.Items);
}
}
}
}