示例#1
0
        /// <summary>
        /// retrieve all profiles for the domain
        /// </summary>
        public void GetAllProfiles() {
            ContactsQuery query =
                new ContactsQuery("https://www.google.com/m8/feeds/profiles/domain/" + this.domain + "/full");

            Feed<Contact> f = cr.Get<Contact>(query);
            this.profiles = new List<Contact>(f.Entries);
        }
        /////////////////////////////////////////////////////////////////////////////



        //////////////////////////////////////////////////////////////////////
        /// <summary>runs an authentication test</summary> 
        //////////////////////////////////////////////////////////////////////
        [Test] public void ContactsAuthenticationTest()
        {
            Tracing.TraceMsg("Entering ContactsAuthenticationTest");

            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri(this.userName + "@googlemail.com"));
            ContactsService service = new ContactsService("unittests");

            if (this.userName != null)
            {
                service.Credentials = new GDataCredentials(this.userName, this.passWord);
            }

            ContactsFeed feed = service.Query(query);

            ObjectModelHelper.DumpAtomObject(feed,CreateDumpFileName("ContactsAuthTest")); 

            if (feed != null && feed.Entries.Count > 0)
            {
                Tracing.TraceMsg("Found a Feed " + feed.ToString());

                foreach (ContactEntry entry in feed.Entries)
                {
                    Assert.IsTrue(entry.Etag != null, "contact entries should have etags");
                }
            }
        }
        public static ContactList GetAddressListFromGoogle(string username, string password)
        {
            ContactList list = new ContactList();
            list.Username = username;

            string appName = "adrianj-GoogleContactsMap-1";
            ContactsService service = CreateService(username, password, appName);

            int contactsPerQuery = 50;
            int maxTotal = 32000;
            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
            query.NumberToRetrieve = contactsPerQuery;

            for (int index = 0; index < maxTotal; index += contactsPerQuery)
            {
                query.StartIndex = index;
                ContactsFeed feed = GetContactsFeed(query, service);
                list.ValidCredentials = true;
                list.AddFromFeed(feed);
                if (feed.Entries.Count < contactsPerQuery)
                    break;
            }

            return list;
        }
示例#4
0
        public void CreateNewContact()
        {
            try
            {
                ContactsService service = new ContactsService("WebGear.GoogleContactsSync");
                service.setUserCredentials(ConfigurationManager.AppSettings["Gmail.Username"],
                    ConfigurationManager.AppSettings["Gmail.Password"]);

                #region Delete previously created test contact.
                ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
                query.NumberToRetrieve = 500;

                ContactsFeed feed = service.Query(query);

                foreach (ContactEntry entry in feed.Entries)
                {
                    if (entry.PrimaryEmail != null && entry.PrimaryEmail.Address == "*****@*****.**")
                    {
                        entry.Delete();
                        break;
                    }
                }
                #endregion

                ContactEntry newEntry = new ContactEntry();
                newEntry.Title.Text = "John Doe";

                EMail primaryEmail = new EMail("*****@*****.**");
                primaryEmail.Primary = true;
                primaryEmail.Rel = ContactsRelationships.IsWork;
                newEntry.Emails.Add(primaryEmail);

                PhoneNumber phoneNumber = new PhoneNumber("555-555-5551");
                phoneNumber.Primary = true;
                phoneNumber.Rel = ContactsRelationships.IsMobile;
                newEntry.Phonenumbers.Add(phoneNumber);

                PostalAddress postalAddress = new PostalAddress();
                postalAddress.Value = "123 somewhere lane";
                postalAddress.Primary = true;
                postalAddress.Rel = ContactsRelationships.IsHome;
                newEntry.PostalAddresses.Add(postalAddress);

                newEntry.Content.Content = "Who is this guy?";

                Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));

                ContactEntry createdEntry = (ContactEntry)service.Insert(feedUri, newEntry);

                Assert.IsNotNull(createdEntry.Id.Uri);

                //delete this temp contact
                createdEntry.Delete();
            }
            catch (Exception ex)
            {

            }
        }
        public List<Contact> GetContacts()
        {
            string uri = ContactsQuery.CreateContactsUri("default");
            ContactsQuery query = new ContactsQuery(uri);
            query.Group = WorkGroup.Id;

            return Request.Get<Contact>(query).Entries.ToList();
        }
示例#6
0
            protected override void ProcessRecord()
            {
                var _domain = dgcGoogleContactsService.GetDomain(service.ContactsService);
                try
                {
                    if (selfUri != null)
                    {
                        var _query = new ContactsQuery(ContactsQuery.CreateContactsUri(_domain));
                        var _feed = service.ContactsService.Query(_query);

                        foreach (ContactEntry _entry in _feed.Entries)
                        {
                            if (_entry.SelfUri.Content == selfUri)
                            {
                                var _contactEntry = dgcGoogleContactsService.CreateContactEntry(_entry);
                                WriteObject(_contactEntry);
                            }
                        }
                    }
                    else if (name != null)
                    {

                        var _query = new ContactsQuery(ContactsQuery.CreateContactsUri(_domain));
                        var _feed = service.OauthContactsService.Query(_query);
                        var _contactsEntrys = new GDataTypes.GDataContactEntrys();
                        foreach (ContactEntry _entry in _feed.Entries)
                        {
                            if (_entry.Title.Text != null)
                            {
                                if (System.Text.RegularExpressions.Regex.IsMatch(_entry.Title.Text, name))
                                {
                                    var _contactEntry = dgcGoogleContactsService.CreateContactEntry(_entry);
                                    _contactsEntrys = dgcGoogleContactsService.AppendContactEntrys(_entry, _contactsEntrys);
                                }
                            }

                        }
                        WriteObject(_contactsEntrys, true);
                    }
                    else
                    {
                        var _query = new ContactsQuery(ContactsQuery.CreateContactsUri(_domain));
                        var _feed = service.ContactsService.Query(_query);
                        var _contactEntrys = dgcGoogleContactsService.CreateContactEntrys(_feed);
                        WriteObject(_contactEntrys, true);
                    }
                }
                catch (Exception _exception)
                {
                    WriteObject(_exception);

                }
            }
 public List<Contact> ContactsChangedSince(DateTime d)
 {
     List<Contact> result = new List<Contact>();
     ContactsRequest cr = new ContactsRequest(rs);
     ContactsQuery q = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
     q.StartDate = d;
     Feed<Contact> feed = cr.Get<Contact>(q);
     foreach (Contact c in feed.Entries)
     {
         result.Add(c);
     }
     return result;
 }
    public void FillCaches ()
    {
      GroupCache.Fill();

      var query = new ContactsQuery (ContactsQuery.CreateContactsUri (_userName, ContactsQuery.fullProjection));
      query.NumberToRetrieve = int.MaxValue;

      if (GroupCache.DefaultGroupIdOrNull != null)
        query.Group = GroupCache.DefaultGroupIdOrNull;

      var contacts = _apiOperationExecutor.Execute (f =>
      {
        var contactsFeed = f.Get<Contact> (query);
        return contactsFeed?.Entries.ToArray() ?? new Contact[] { };
      });

      foreach (var contact in contacts)
      {
        _contactsById[contact.Id] = contact;
      }
    }
    public void GetContacts(GooglePlusAccessToken serStatus)
    {
        string google_client_id = "yourclientId";
        string google_client_sceret = "yourclientSecret";
        /*Get Google Contacts From Access Token and Refresh Token*/
        string refreshToken = serStatus.refresh_token;
        string accessToken = serStatus.access_token;
        string scopes = "https://www.google.com/m8/feeds/contacts/default/full/";
        OAuth2Parameters oAuthparameters = new OAuth2Parameters()
        {
            ClientId = google_client_id,
            ClientSecret = google_client_sceret,
            RedirectUri = "http://www.yogihosting.com/TutorialCode/GoogleContactAPI/google-contact-api.aspx",
            Scope = scopes,
            AccessToken = accessToken,
            RefreshToken = refreshToken
        };

        RequestSettings settings = new RequestSettings("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters);
        ContactsRequest cr = new ContactsRequest(settings);
        ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
        query.NumberToRetrieve = 5000;
        Feed<Contact> feed = cr.Get<Contact>(query);

        StringBuilder sb = new StringBuilder();
        int i = 1;
        foreach (Contact entry in feed.Entries)
        {
            foreach (EMail email in entry.Emails)
            {
                sb.Append(i + "&nbsp;").Append(email.Address).Append("<br/>");
                i++;
            }
        }
        /*End*/
        dataDiv.InnerHtml = sb.ToString();
    }
示例#10
0
        protected void ExecuteImport()
        {
            //start sync
            ContactsService GContactService = new ContactsService("Contact Infomation");
            GContactService.setUserCredentials(email, password);

            ContactsQuery query = new ContactsQuery(ContactsQuery.
            CreateContactsUri("default"));
            ContactsFeed feed = null;

            try
            {
                feed = GContactService.Query(query);
            }
            catch (Exception)
            {
                this.setLabelText("Invalid email or password", Color.Red);
                return;
            }

            //start
            this.showProgressBar(feed.TotalResults);
            this.setLabelText("Importing...", Color.Black);

            int progress = 0;
            int startIndex = 0;
            while (feed.Entries.Count > 0)
            {
                startIndex += feed.ItemsPerPage;
                query.StartIndex = startIndex;
                PhoneNumbers.PhoneNumberUtil util = PhoneNumbers.PhoneNumberUtil.GetInstance();
                foreach (ContactEntry entry in feed.Entries)
                {
                    this.setProgress(progress);
                    progress++;

                    if (entry.Phonenumbers.Count > 0)
                    {
                        foreach (PhoneNumber number in entry.Phonenumbers)
                        {
                            string numb = string.Empty;
                            try
                            {
                                PhoneNumbers.PhoneNumber num = util.Parse(number.Value, "NL");
                                numb = num.CountryCode.ToString() + num.NationalNumber.ToString();
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Exception was thrown: " + ex.Message);
                                continue;
                            }
                            if (!ContactStore.numberExists(numb + "@s.whatsapp.net"))
                            {
                                Contact contact = new Contact(0, numb + "@s.whatsapp.net", "", "", entry.Name.GivenName, entry.Name.FamilyName);
                                ContactStore.AddContact(contact);
                            }
                        }
                    }
                }
                feed = GContactService.Query(query);
            }

            //done!
            this.doExit();
        }
    public static void Main(string [] args)
    {
        if (args.Length < 2) {
            Console.WriteLine ("usage: gcontact-yomigana.exe [username] [password] [--delete]");
            return;
        }
        if (args.Length > 2 && args [2] == "--delete") {
            Console.WriteLine ("Cleanup mode");
            cleanup = true;
        }

        ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCallback;
        string username = args [0];
        string password = args [1];
        var rs = new RequestSettings (app_name, username, password);
        rs.AutoPaging = true;
        var cr = new ContactsRequest (rs);
        #if false
        var cq = new ContactsQuery (ContactsQuery.CreateContactsUri(null));
        cq.Group = "My Contacts";
        var results = cr.Get<Contact> (cq);
        #else
        var results = cr.GetContacts ();
        #endif

        if (cleanup) {
            foreach (var c in results.Entries) {
                // these silly null check is required since
                // setting value to nonexistent field causes AE.
                if (c.Name.FamilyNamePhonetics != null)
                    c.Name.FamilyNamePhonetics = null;
                if (c.Name.GivenNamePhonetics != null)
                    c.Name.GivenNamePhonetics = null;
        #if false // this does not work
                if (c.ContactEntry.Dirty)
                    Console.WriteLine ("{0} {1} being updated", c.Name.FamilyName, c.Name.GivenName);
        #else
                cr.Update<Contact> (c);
        #endif
            }
        #if false // Probably this does not work for extensions
            results.AtomFeed.Publish ();
        #endif
            return;
        }

        var l = new List<string> ();
        var dic = new Dictionary<string,string> ();
        foreach (var c in results.Entries)
            CollectName (c.Name, l);

        // query to mecab server
        string req = String.Join (" ", l.ToArray ());
        byte [] bytes = new WebClient ().DownloadData (server_url_param + req);
        string res = Encoding.UTF8.GetString (bytes);
        string [] rl = res.Split (' ');
        if (rl.Length != l.Count)
            throw new Exception ("Some error occured. I cannot handle address book entry that contains 'm(__)m'.");
        for (int i = 0; i < l.Count; i++) {
            var dst = rl [i].Replace ("m(__)m", " ");
            if (l [i] != dst)
                dic [l [i]] = dst;
        }
        foreach (var p in dic)
            Console.Write ("{0}=> {1}, ", p.Key, p.Value);

        // update
        foreach (var c in results.Entries)
            UpdateName (c, dic, cr);
        #if false // Probably this does not work for extension fields.
        results.AtomFeed.Publish ();
        #endif
    }
 /// <summary>
 ///  default constructor with user name
 /// </summary>
 /// <param name="username">the username for the contacts feed</param>
 /// <param name="iService">the Service to use</param>
 public ContactsFeed(String username, IService iService)
     : base(new Uri(ContactsQuery.CreateContactsUri(username)), iService)
 {
 }
示例#13
0
        private ActionResult OAuthCallback()
        {
            IAuthorizationState auth = client.ProcessUserAuthorization(Request);
            Session["auth"] = auth;
            var authFactory = new GAuthSubRequestFactory("cp", "Geeks Dilemma") {Token = auth.AccessToken};
            var service = new ContactsService(authFactory.ApplicationName) {RequestFactory = authFactory};

            var query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
            query.NumberToRetrieve = 1000;
            ContactsFeed contacts = service.Query(query);
            ViewBag.ImportFrom = "Google";
            var userId = GetCurrentUserId();

            DeletePreviousImportIfNecessary(userId);

            var googleContact = new GoogleContact
                {
                    UserId = userId,
                    Contacts = (from ContactEntry entry in contacts.Entries
                                from email in entry.Emails
                                where entry.Name != null
                                where email != null
                                select new ImportModel
                                    {
                                        Import = false,
                                        EmailAddress = email.Address.ToLower(),
                                        Name = entry.Name.FullName
                                    }).ToList()
                };

            RavenSession.Store(googleContact);

            return View("Import");
        }
        private void LoadAlbumBackground(object sender, DoWorkEventArgs e)
        {
            //albums = new List<PicasaEntry>();
              //albumIndex = -1;

              // Prepare for contact query
              string applicationName = "DigitalFrame";
              string username = settings.Username;
              string password = settings.Password;

              RequestSettings contactRequestSettings = new RequestSettings(applicationName, username, password);
              ContactsRequest contactRequest = new ContactsRequest(contactRequestSettings);

              // Request all groups of the auth user.
              //var allGroups = contactRequest.GetGroups();
              //foreach (var item in allGroups.Entries) {
              //  Debug.Write(item.Id + " - " + item.Title);
              //}

              // Get Family group entry.
              Group familyGroup;
              StringBuilder gs = new StringBuilder(GroupsQuery.CreateGroupsUri("default"));
              gs.Append("/");
              gs.Append("e"); // Family

              try {
            Feed<Group> gf = contactRequest.Get<Group>(new Uri(gs.ToString()));
            familyGroup = gf.Entries.First();
              }
              catch (AuthenticationException) {
            // We fail to get the group which means the login failed.
            return;
              }
              catch (GDataRequestException) {
            return;
              }

              // Get all contacts in Family group.
              ContactsQuery contactQuery = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
              contactQuery.Group = familyGroup.Id;
              Feed<Contact> friends = contactRequest.Get<Contact>(contactQuery);

              // Prepare for picasa query
              service = new PicasaService(applicationName);
              service.setUserCredentials(username, password);
              service.SetAuthenticationToken(service.QueryAuthenticationToken());

              allPhotos = new List<PicasaEntry>();

              foreach (var contact in friends.Entries) {
            try {
              string friendUsername = ParseUserName(contact);
              if (!string.IsNullOrEmpty(friendUsername)) {
            AlbumQuery query = new AlbumQuery();
            query.Uri = new Uri(PicasaQuery.CreatePicasaUri(friendUsername));

            PicasaFeed picasaFeed = service.Query(query);
            if (picasaFeed != null && picasaFeed.Entries.Count > 0) {
              foreach (PicasaEntry albumEntry in picasaFeed.Entries) {
                PhotoQuery photosQuery = new PhotoQuery(albumEntry.FeedUri);
                var photosFeed = (PicasaFeed)service.Query(photosQuery);
                foreach (PicasaEntry photoEntry in photosFeed.Entries) {
                  allPhotos.Add(photoEntry);
                }
              }
            }
              }
            }
            catch (LoggedException) {
              // Ignore the exception and continue.
            }
              }
        }
        public void ModelTestETagQuery()
        {
            const int numberOfInserts = 5;
            Tracing.TraceMsg("Entering ModelTestETagQuery");

            RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord);
            rs.AutoPaging = true;

            ContactsRequest cr = new ContactsRequest(rs);

            Feed<Contact> f = cr.GetContacts();

            ContactsQuery q = new ContactsQuery(ContactsQuery.CreateContactsUri(null));

            q.Etag = ((ISupportsEtag)f.AtomFeed).Etag;

            try
            {
                f = cr.Get<Contact>(q);
                foreach (Contact c in f.Entries)
                {
                }
            }
            catch (GDataNotModifiedException g)
            {
                Assert.IsTrue(g != null);
            }
        }
        //////////////////////////////////////////////////////////////////////
        /// <summary>runs an authentication test, inserts a new contact</summary> 
        //////////////////////////////////////////////////////////////////////
        [Test] public void InsertContactsTest()
        {
            const int numberOfInserts = 37;
            Tracing.TraceMsg("Entering InsertContactsTest");

            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri(this.userName + "@googlemail.com")); 
            ContactsService service = new ContactsService("unittests");

            if (this.userName != null)
            {
                service.Credentials = new GDataCredentials(this.userName, this.passWord);
            }

            ContactsFeed feed = service.Query(query);

            int originalCount = feed.Entries.Count;

            PhoneNumber p = null;

            List<ContactEntry> inserted = new List<ContactEntry>();
            if (feed != null)
            {
                Assert.IsTrue(feed.Entries != null, "the contacts needs entries");

                for (int i = 0; i < numberOfInserts; i++)
                {
                    ContactEntry entry = ObjectModelHelper.CreateContactEntry(i);
                    entry.PrimaryEmail.Address = "joe" + i.ToString() + "@doe.com";

                    p = entry.PrimaryPhonenumber;
                    inserted.Add(feed.Insert(entry));
                }
            }


            List<ContactEntry> list = new List<ContactEntry>();

            feed = service.Query(query);
            foreach (ContactEntry e in feed.Entries)
            {
                list.Add(e);
            }

            while (feed.NextChunk != null)
            {
                ContactsQuery nq = new ContactsQuery(feed.NextChunk); 
                feed = service.Query(nq);
                foreach (ContactEntry e in feed.Entries)
                {
                    list.Add(e);
                }
            }
            


            if (inserted.Count > 0)
            {
                int iVer = numberOfInserts;
                // let's find those guys
                for (int i = 0; i < inserted.Count; i++)
                {
                    ContactEntry test = inserted[i] as ContactEntry;
                    foreach (ContactEntry e in list)
                    {
                        if (e.Id == test.Id)
                        {
                            iVer--;
                            // verify we got the phonenumber back....
                            Assert.IsTrue(e.PrimaryPhonenumber != null, "They should have a primary phonenumber");
                            Assert.AreEqual(e.PrimaryPhonenumber.Value,p.Value, "They should be identical");
                        }
                    }
                }

                Assert.IsTrue(iVer == 0, "The new entries should all be part of the feed now, we have " + iVer + " now");
            }

            // now delete them again

            foreach (ContactEntry e in inserted)
            {
                e.Delete();
            }

            // now make sure they are gone
            if (inserted.Count > 0)
            {
                feed = service.Query(query);

                // let's find those guys, we should not find ANY
                for (int i = 0; i < inserted.Count; i++)
                {
                    ContactEntry test = inserted[i] as ContactEntry;
                    foreach (ContactEntry e in feed.Entries)
                    {
                        Assert.IsTrue(e.Id != test.Id, "The new entries should all be deleted now");
                    }
                }
                Assert.IsTrue(feed.Entries.Count == originalCount, "The count should be correct as well");
            }
        }
示例#17
0
        public void CreateNewContact()
        {
            string gmailUsername;
            string syncProfile;
            GoogleAPITests.LoadSettings(out gmailUsername, out syncProfile);

            ContactsRequest service;

            var scopes = new List<string>();
            //Contacts-Scope
            scopes.Add("https://www.google.com/m8/feeds");
            //Notes-Scope
            scopes.Add("https://docs.google.com/feeds/");
            //scopes.Add("https://docs.googleusercontent.com/");
            //scopes.Add("https://spreadsheets.google.com/feeds/");
            //Calendar-Scope
            //scopes.Add("https://www.googleapis.com/auth/calendar");
            scopes.Add(CalendarService.Scope.Calendar);

            UserCredential credential;
            byte[] jsonSecrets = Properties.Resources.client_secrets;

            using (var stream = new MemoryStream(jsonSecrets))
            {
                FileDataStore fDS = new FileDataStore(Logger.AuthFolder, true);

                GoogleClientSecrets clientSecrets = GoogleClientSecrets.Load(stream);

                credential = GCSMOAuth2WebAuthorizationBroker.AuthorizeAsync(
                                clientSecrets.Secrets,
                                scopes.ToArray(),
                                gmailUsername,
                                CancellationToken.None,
                                fDS).
                                Result;

                OAuth2Parameters parameters = new OAuth2Parameters
                {
                    ClientId = clientSecrets.Secrets.ClientId,
                    ClientSecret = clientSecrets.Secrets.ClientSecret,

                    // Note: AccessToken is valid only for 60 minutes
                    AccessToken = credential.Token.AccessToken,
                    RefreshToken = credential.Token.RefreshToken
                };

                RequestSettings settings = new RequestSettings("GoContactSyncMod", parameters);

                service = new ContactsRequest(settings);
            }

            #region Delete previously created test contact.
            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
            query.NumberToRetrieve = 500;

            Feed<Contact> feed = service.Get<Contact>(query);

            Logger.Log("Loaded Google contacts", EventType.Information);

            foreach (Contact entry in feed.Entries)
            {
                if (entry.PrimaryEmail != null && entry.PrimaryEmail.Address == "*****@*****.**")
                {
                    service.Delete(entry);
                    Logger.Log("Deleted Google contact", EventType.Information);
                    //break;
                }
            }
            #endregion

            Contact newEntry = new Contact();
            newEntry.Title = "John Doe";

            EMail primaryEmail = new EMail("*****@*****.**");
            primaryEmail.Primary = true;
            primaryEmail.Rel = ContactsRelationships.IsWork;
            newEntry.Emails.Add(primaryEmail);

            PhoneNumber phoneNumber = new PhoneNumber("555-555-5551");
            phoneNumber.Primary = true;
            phoneNumber.Rel = ContactsRelationships.IsMobile;
            newEntry.Phonenumbers.Add(phoneNumber);

            StructuredPostalAddress postalAddress = new StructuredPostalAddress();
            postalAddress.Street = "123 somewhere lane";
            postalAddress.Primary = true;
            postalAddress.Rel = ContactsRelationships.IsHome;
            newEntry.PostalAddresses.Add(postalAddress);

            newEntry.Content = "Who is this guy?";

            Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));

            Contact createdEntry = service.Insert(feedUri, newEntry);

            Logger.Log("Created Google contact", EventType.Information);

            Assert.IsNotNull(createdEntry.ContactEntry.Id.Uri);

            Contact updatedEntry = service.Update(createdEntry);

            Logger.Log("Updated Google contact", EventType.Information);

            //delete test contacts
            service.Delete(createdEntry);

            Logger.Log("Deleted Google contact", EventType.Information);
        }
示例#18
0
        public void LoadGoogleContacts()
        {
            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
            query.NumberToRetrieve = 256;
            query.StartIndex = 0;
            query.ShowDeleted = false;
            //query.OrderBy = "lastmodified";

            ContactsFeed feed;
            feed = _googleService.Query(query);
            _googleContacts = feed.Entries;
            while (feed.Entries.Count == query.NumberToRetrieve)
            {
                query.StartIndex = _googleContacts.Count;
                feed = _googleService.Query(query);
                foreach (AtomEntry a in feed.Entries)
                {
                    _googleContacts.Add(a);
                }
            }
        }
示例#19
0
 /// <summary>
 /// overloaded to create typed version of Query
 /// </summary>
 /// <param name="feedQuery"></param>
 /// <returns>EventFeed</returns>
 public ContactsFeed Query(ContactsQuery feedQuery) {
     return base.Query(feedQuery) as ContactsFeed;
 }
    public static async Task<ContactsRequest> LoginToContactsService (string user, IWebProxy proxyOrNull)
    {
      var clientSecrets = CreateClientSecrets();
      var credential = await LoginToGoogle (user, proxyOrNull);

      var parameters = CreateOAuth2Parameters (clientSecrets, credential);

      var contactsRequest = new ContactsRequest (new RequestSettings ("Outlook CalDav Synchronizer", parameters) {AutoPaging = true});

      ContactsQuery query = new ContactsQuery (ContactsQuery.CreateContactsUri ("default"));
      query.NumberToRetrieve = 1;
      try
      {
        var feed = contactsRequest.Service.Query (query);
      }
      catch (GDataRequestException x)
      {
        s_logger.Error ("Trying to access google contacts API failed. Revoking  token and reauthorizing.", x);

        await credential.RevokeTokenAsync (CancellationToken.None);
        await GoogleWebAuthorizationBroker.ReauthorizeAsync (credential, CancellationToken.None);
        parameters = CreateOAuth2Parameters (clientSecrets, credential);
        contactsRequest = new ContactsRequest (new RequestSettings ("Outlook CalDav Synchronizer", parameters) { AutoPaging = true });
      }

      if (proxyOrNull != null)
        contactsRequest.Proxy = proxyOrNull;

      return contactsRequest;
    }
示例#21
0
 /// <summary>
 /// convenience method to create an URI based on a userID for a groups feed
 /// </summary>
 /// <param name="userID">if the parameter is NULL, uses the default user</param>
 /// <param name="projection">the projection to use</param>
 /// <returns>string</returns>
 public static string CreateGroupsUri(string userID, string projection)
 {
     return(ContactsQuery.groupsBaseUri + ContactsQuery.UserString(userID) + projection);
 }
        /////////////////////////////////////////////////////////////////////////////


        /////////////////////////////////////////////////////////////////////
        /// <summary>runs an basic auth test against the groups feed test</summary> 
        //////////////////////////////////////////////////////////////////////
        [Test] public void GroupsSystemTest()
        {
            Tracing.TraceMsg("Entering GroupsSystemTest");

            GroupsQuery query = new GroupsQuery(ContactsQuery.CreateGroupsUri(this.userName + "@googlemail.com"));
            ContactsService service = new ContactsService("unittests");

            if (this.userName != null)
            {
                service.Credentials = new GDataCredentials(this.userName, this.passWord);
            }

            GroupsFeed feed = service.Query(query);

            int i = 0; 
            foreach (GroupEntry g in feed.Entries )
            {
               if (g.SystemGroup != null)
               {
                   i++;
               }
            }

            Assert.IsTrue(i==4, "There should be 4 system groups in the groups feed");


            ObjectModelHelper.DumpAtomObject(feed,CreateDumpFileName("GroupsAuthTest"));

            GroupEntry newGroup = new GroupEntry();
            newGroup.Title.Text = "Private Data";

            GroupEntry insertedGroup = feed.Insert(newGroup);

            GroupEntry g2 = new GroupEntry();
            g2.Title.Text = "Another Private Group";
            GroupEntry insertedGroup2 = feed.Insert(g2);

            // now insert a new contact that belongs to that group
            ContactsQuery q = new ContactsQuery(ContactsQuery.CreateContactsUri(this.userName + "@googlemail.com"));
            ContactsFeed cf = service.Query(q);
            ContactEntry entry = ObjectModelHelper.CreateContactEntry(1);
            GroupMembership member = new GroupMembership();
            member.HRef = insertedGroup.Id.Uri.ToString();
            GroupMembership member2 = new GroupMembership();
            member2.HRef = insertedGroup2.Id.Uri.ToString();

            ContactEntry insertedEntry = cf.Insert(entry);
            // now change the group membership
            insertedEntry.GroupMembership.Add(member);
            insertedEntry.GroupMembership.Add(member2);
            ContactEntry currentEntry = insertedEntry.Update();

            Assert.IsTrue(currentEntry.GroupMembership.Count == 2, "The entry should be in 2 groups");

            currentEntry.GroupMembership.Clear();
            currentEntry = currentEntry.Update();
            // now we should have 2 new groups and one new entry with no groups anymore


            int oldCountGroups = feed.Entries.Count;
            int oldCountContacts = cf.Entries.Count;

            currentEntry.Delete();

            insertedGroup.Delete();
            insertedGroup2.Delete();

            feed = service.Query(query);
            cf = service.Query(q);

            Assert.AreEqual(oldCountContacts, cf.Entries.Count, "Contacts count should be the same");
            Assert.AreEqual(oldCountGroups, feed.Entries.Count, "Groups count should be the same");
        }
 /// <summary>
 /// overloaded to create typed version of Query
 /// </summary>
 /// <param name="feedQuery"></param>
 /// <returns>EventFeed</returns>
 public ContactsFeed Query(ContactsQuery feedQuery)
 {
     return(base.Query(feedQuery) as ContactsFeed);
 }
        public void ConflictContactsTest()
        {
            const int numberOfInserts = 50;
            const int numberWithAdds = 60; 
            Tracing.TraceMsg("Entering InsertContactsTest");

            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri(this.userName + "@googlemail.com"));
            ContactsService service = new ContactsService("unittests");


            if (this.userName != null)
            {
                service.Credentials = new GDataCredentials(this.userName, this.passWord);
            }

            // clean the contacts feed
            DeleteAllContacts();

            ContactsFeed feed = service.Query(query);

            int originalCount = feed.Entries.Count;

            string email = Guid.NewGuid().ToString();

            List<ContactEntry> inserted = new List<ContactEntry>();

            // insert a number of guys
            for (int i = 0; i < numberOfInserts; i++)
            {
                ContactEntry entry = ObjectModelHelper.CreateContactEntry(i);
                entry.PrimaryEmail.Address = email + i.ToString() + "@doe.com";
                entry = feed.Insert(entry);
                AddContactPhoto(entry, service);
                inserted.Add(entry);

            }


            if (feed != null)
            {
                for (int x = numberOfInserts; x <= numberWithAdds; x++)
                {
                    for (int i = 0; i < x; i++)
                    {
                        ContactEntry entry = ObjectModelHelper.CreateContactEntry(i);
                        entry.PrimaryEmail.Address = email + i.ToString() + "@doe.com";

                        try
                        {
                            entry = feed.Insert(entry);
                            AddContactPhoto(entry, service);
                            inserted.Add(entry);
                        }
                        catch (GDataRequestException)
                        {
                        }
                    }
                }
            }

            List<ContactEntry> list = new List<ContactEntry>();
            feed = service.Query(query);
            foreach (ContactEntry e in feed.Entries)
            {
                list.Add(e);
            }

            while (feed.NextChunk != null)
            {
                ContactsQuery nq = new ContactsQuery(feed.NextChunk);
                feed = service.Query(nq);
                foreach (ContactEntry e in feed.Entries)
                {
                    list.Add(e);
                }
            }

            Assert.AreEqual(list.Count, numberWithAdds - originalCount, "We should have added new entries");

            // clean the contacts feed
            DeleteAllContacts();

        }
示例#25
0
        private Contact LoadGoogleContacts(AtomId id)
        {
            string message = "Error Loading Google Contacts. Cannot connect to Google.\r\nPlease ensure you are connected to the internet. If you are behind a proxy, change your proxy configuration!";

            Contact ret = null;
            try
            {
                if (id == null) // Only log, if not specific Google Contacts are searched
                    Logger.Log("Loading Google Contacts...", EventType.Information);

                GoogleContacts = new Collection<Contact>();

                ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
                query.NumberToRetrieve = 256;
                query.StartIndex = 0;

                //Only load Google Contacts in My Contacts group (to avoid syncing accounts added automatically to "Weitere Kontakte"/"Further Contacts")
                Group group = GetGoogleGroupByName(myContactsGroup);
                if (group != null)
                    query.Group = group.Id;

                //query.ShowDeleted = false;
                //query.OrderBy = "lastmodified";

                Feed<Contact> feed = ContactsRequest.Get<Contact>(query);

                while (feed != null)
                {
                    foreach (Contact a in feed.Entries)
                    {
                        GoogleContacts.Add(a);
                        if (id != null && id.Equals(a.ContactEntry.Id))
                            ret = a;
                    }
                    query.StartIndex += query.NumberToRetrieve;
                    feed = ContactsRequest.Get<Contact>(feed, FeedRequestType.Next);

                }

            }
            catch (System.Net.WebException ex)
            {
                //Logger.Log(message, EventType.Error);
                throw new GDataRequestException(message, ex);
            }
            catch (System.NullReferenceException ex)
            {
                //Logger.Log(message, EventType.Error);
                throw new GDataRequestException(message, new System.Net.WebException("Error accessing feed", ex));
            }

            return ret;
        }
示例#26
0
		public void FetchTask()
		{
			if (syncEngine.SyncCanceled)
			{
				this.FetchSem.Release();
				return;
			}

			mans.Clear();
			contactsByFullName.Clear();

			googleService = new ContactsService("Contact Infomation");

			if (Credentials == null)
			{
				this.FetchSem.Release();
				return;
			}
			else
			{
				if (Credentials.UserName != null && !Credentials.UserName.ToLower().EndsWith("@gmail.com"))
				{
					Credentials.UserName += "@gmail.com";
				}
				googleService.setUserCredentials(Credentials.UserName, Credentials.Password);
			}

			((GDataRequestFactory)googleService.RequestFactory).Timeout = 3000;

			queruUriFull = ContactsQuery.CreateContactsUri(Credentials.UserName, ContactsQuery.fullProjection);
			contactsQuery = new ContactsQuery(queruUriFull);
			contactsQuery.NumberToRetrieve = 1000;

			try
			{

				feed = googleService.Query(contactsQuery);
			}
			catch (Google.GData.Client.GDataRequestException e)
			{
				Credentials = null;

				Dispatcher.Invoke(new SyncCancelEventHandler(owner.CancelSync),
						this, e.InnerException.Message, null);

				this.FetchSem.Release();
				return;
			}
			catch (Google.GData.Client.InvalidCredentialsException e)
			{
				Credentials = null;

				Dispatcher.Invoke(new SyncCancelEventHandler(owner.CancelSync),
						this, e.Message, null);

				this.FetchSem.Release();
				return;
			}
			catch (CaptchaRequiredException e)
			{
				Credentials = null;

				Dispatcher.Invoke(new SyncCancelEventHandler(owner.CancelSync),
						this, e.Message, "https://www.google.com/accounts/UnlockCaptcha");

				this.FetchSem.Release();
				return;
			}
			catch (Exception e)
			{
				Credentials = null;

				Dispatcher.Invoke(new SyncCancelEventHandler(owner.CancelSync),
						this, e.Message, null);

				this.FetchSem.Release();
				return;
			}

			syncEngine.CurrentTotal += feed.Entries.Count;
			
			GroupsQuery groupsQuery = new GroupsQuery(GroupsQuery.
				CreateGroupsUri(Credentials.UserName, ContactsQuery.thinProjection));

			try
			{
				groupsFeed = googleService.Query(groupsQuery);
			} 
			catch (Google.GData.Client.GDataRequestException e)
			{
				Credentials = null;

				Dispatcher.Invoke(new SyncCancelEventHandler(owner.CancelSync),
						this, e.InnerException.Message, null);
								
				this.FetchSem.Release();
				return;
			}

			foreach (ContactEntry entry in feed.Entries)
			{

				if (owner != null)
				{
					Dispatcher.Invoke(new SyncProgressEventHandler(owner.Progress), this,
						"Loading " + "(" + syncEngine.CurrentItemNum + "/" + syncEngine.CurrentTotal + ")",
						syncEngine.CurrentItemNum, syncEngine.CurrentTotal);
					syncEngine.CurrentItemNum++;
				}

				Contact contact = GetCanonicalContact(entry);
				
				string fullname = contact.FullName;

				if (fullname == null || fullname.Trim() == "")
				{
				}
				else
				{
					contactsByFullName[fullname] = contact;
					mans.Add(new Man { FullName = fullname, EMail = contact.EMail, Phone = contact.Phone });
				}
				
			}

			this.FetchSem.Release();
		}
示例#27
0
 /// <summary>
 ///  default constructor with user name
 /// </summary>
 /// <param name="userName">the username for the contacts feed</param>
 /// <param name="iService">the Service to use</param>
 public GroupsFeed(String userName, IService iService) : base(new Uri(ContactsQuery.CreateGroupsUri(userName)), iService)
 {
 }
示例#28
0
            protected override void ProcessRecord()
            {
                var _domain = dgcGoogleContactsService.GetDomain(service.ContactsService);
                var _query = new ContactsQuery(ContactsQuery.CreateContactsUri(_domain));
                var _feed = service.ContactsService.Query(_query);
                foreach (var _entry in _feed.Entries)
                {
                    if (_entry.SelfUri.Content == selfUri)
                    {
                        try
                        {
                            service.ContactsService.Delete(_entry);
                            WriteObject(_entry, true);
                        }
                        catch (Exception _Exception)
                        {
                            WriteObject(_Exception);
                        }
                     }
                    else
                    {
                        throw new Exception("SelfUri not found!");
                    }

                }
            }
 private static ContactsFeed GetContactsFeed(ContactsQuery query, ContactsService service)
 {
     ContactsFeed feed = service.Query(query);
     return feed;
 }
示例#30
0
            protected override void ProcessRecord()
            {
                var _domain = dgcGoogleContactsService.GetDomain(service.ContactsService);
                var _query = new ContactsQuery(ContactsQuery.CreateContactsUri(_domain));
                var _feed = service.ContactsService.Query(_query);
                foreach (ContactEntry _entry in _feed.Entries)
                {
                    if (_entry.SelfUri.Content == selfUri)
                    {

                        if (emailAddress != null)
                        {
                            var _primaryEmail = new EMail();
                            _primaryEmail.Address = emailAddress;
                            _primaryEmail.Primary = true;
                            _primaryEmail.Rel = ContactsRelationships.IsWork;
                            _entry.Emails.Add(_primaryEmail);
                        }

                        if (phoneNumber != null)
                        {
                            bool _exists = false;
                            foreach (PhoneNumber _phEntry in _entry.Phonenumbers)
                            {
                                if (_phEntry.Rel == ContactsRelationships.IsWork)
                                {
                                    _exists = true;
                                }
                            }
                            if (_exists == true)
                            {
                                foreach (PhoneNumber _phEntry in _entry.Phonenumbers)
                                {
                                    if (_phEntry.Rel == ContactsRelationships.IsWork)
                                    {
                                        _phEntry.Value = phoneNumber;
                                    }
                                }
                            }
                            else
                            {
                                var _phoneNumber = new PhoneNumber(phoneNumber);
                                _phoneNumber.Primary = true;
                                _phoneNumber.Rel = ContactsRelationships.IsWork;
                                _entry.Phonenumbers.Add(_phoneNumber);
                            }
                        }

                        if (homePhoneNumber != null)
                        {
                            bool _exists = false;
                            foreach (PhoneNumber _phEntry in _entry.Phonenumbers)
                            {
                                if (_phEntry.Rel == ContactsRelationships.IsHome)
                                {
                                    _exists = true;
                                }
                            }
                            if (_exists == true)
                            {
                                foreach (PhoneNumber _phEntry in _entry.Phonenumbers)
                                {
                                    if (_phEntry.Rel == ContactsRelationships.IsHome)
                                    {
                                        _phEntry.Value = homePhoneNumber;
                                    }
                                }
                            }
                            else
                            {
                                var _phoneNumber = new PhoneNumber(homePhoneNumber);
                                _phoneNumber.Primary = false;
                                _phoneNumber.Rel = ContactsRelationships.IsHome;
                                _entry.Phonenumbers.Add(_phoneNumber);

                            }
                        }

                        if (mobilePhoneNumber != null)
                        {
                            bool _exists = false;
                            foreach (PhoneNumber _phEntry in _entry.Phonenumbers)
                            {
                                if (_phEntry.Rel == ContactsRelationships.IsMobile)
                                {
                                    _exists = true;
                                }
                            }
                            if (_exists == true)
                            {
                                foreach (PhoneNumber _phEntry in _entry.Phonenumbers)
                                {
                                    if (_phEntry.Rel == ContactsRelationships.IsMobile)
                                    {
                                        _phEntry.Value = mobilePhoneNumber;
                                    }
                                }
                            }
                            else
                            {
                                var _phoneNumber = new PhoneNumber(mobilePhoneNumber);
                                _phoneNumber.Primary = false;
                                _phoneNumber.Rel = ContactsRelationships.IsMobile;
                                _entry.Phonenumbers.Add(_phoneNumber);
                            }
                        }

                        if (otherPhoneNumber != null)
                        {
                            bool _exists = false;
                            foreach (PhoneNumber _phEntry in _entry.Phonenumbers)
                            {
                                if (_phEntry.Rel == ContactsRelationships.IsOther)
                                {
                                    _exists = true;
                                }
                            }
                            if (_exists == true)
                            {
                                foreach (PhoneNumber _phEntry in _entry.Phonenumbers)
                                {
                                    if (_phEntry.Rel == ContactsRelationships.IsOther)
                                    {
                                        _phEntry.Value = otherPhoneNumber;
                                    }
                                }
                            }
                            else
                            {
                                var _phoneNumber = new PhoneNumber(otherPhoneNumber);
                                _phoneNumber.Primary = false;
                                _phoneNumber.Rel = ContactsRelationships.IsOther;
                                _entry.Phonenumbers.Add(_phoneNumber);
                            }
                        }

                        if (postalAddress != null)
                        {
                            bool _exists = false;
                            foreach (StructuredPostalAddress _poEntry in _entry.PostalAddresses)
                            {
                                if (_poEntry.Rel == ContactsRelationships.IsWork)
                                {
                                    _exists = true;
                                }
                            }
                            if (_exists == true)
                            {
                                foreach (StructuredPostalAddress _poEntry in _entry.PostalAddresses)
                                {
                                    if (_poEntry.Rel == ContactsRelationships.IsWork)
                                    {
                                        _poEntry.FormattedAddress = postalAddress;
                                    }
                                }
                            }
                            else
                            {
                                var _postalAddress = new StructuredPostalAddress();
                                _postalAddress.FormattedAddress = postalAddress;
                                _postalAddress.Primary = true;
                                _postalAddress.Rel = ContactsRelationships.IsWork;
                                _entry.PostalAddresses.Add(_postalAddress);
                            }
                        }

                        if (homePostalAddress != null)
                        {
                            bool _exists = false;
                            foreach (StructuredPostalAddress _poEntry in _entry.PostalAddresses)
                            {
                                if (_poEntry.Rel == ContactsRelationships.IsHome)
                                {
                                    _exists = true;
                                }
                            }
                            if (_exists == true)
                            {
                                foreach (StructuredPostalAddress _poEntry in _entry.PostalAddresses)
                                {
                                    if (_poEntry.Rel == ContactsRelationships.IsHome)
                                    {
                                        _poEntry.FormattedAddress = homePostalAddress;
                                    }
                                }
                            }
                            else
                            {
                                var _postalAddress = new StructuredPostalAddress();
                                _postalAddress.FormattedAddress = homePostalAddress;
                                _postalAddress.Primary = false;
                                _postalAddress.Rel = ContactsRelationships.IsHome;
                                _entry.PostalAddresses.Add(_postalAddress);
                            }
                        }

                        Uri _feedUri = new Uri(ContactsQuery.CreateContactsUri(_domain));

                        try
                        {
                            ContactEntry _updateEntry = (ContactEntry)service.ContactsService.Update(_entry);
                            if (name != null)
                            {
                                var _token = service.ContactsService.QueryClientLoginToken();
                                dgcGoogleContactsService.SetContactTitle(_token, _entry.SelfUri.ToString(), name);
                                var _contactEntry = dgcGoogleContactsService.CreateContactModifidEntry(_updateEntry, name);
                                WriteObject(_contactEntry);
                            }
                            else
                            {
                                var _contactEntry = dgcGoogleContactsService.CreateContactEntry(_updateEntry);
                                WriteObject(_contactEntry);
                            }
                        }
                        catch (Exception _exception)
                        {
                            WriteObject(_exception);
                        }
                    }
                }
            }
        public string GoogleContactLookup(string username, string password, string lookup)
        {
            try
            {
                Log("Starting Google Contact Lookup for " + lookup + ".");

                ContactsService service = new ContactsService("sipsorcery-lookup");
                ((GDataRequestFactory)service.RequestFactory).KeepAlive = false;

                service.setUserCredentials(username, password);
                var result = service.QueryClientLoginToken();

                var query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
                query.ExtraParameters = "q=" + lookup + "&max-results=1";

                ContactsFeed feed = service.Query(query);

                if (feed != null && feed.Entries != null && feed.Entries.Count > 0)
                {
                    var entry = feed.Entries.First() as ContactEntry;

                    if (entry.Name != null && entry.Name.FullName.NotNullOrBlank())
                    {
                        Log("Result found Google Contact Lookup for " + lookup + " of " + entry.Name.FullName + ".");
                        return entry.Name.FullName;
                    }
                    else
                    {
                        Log("A result was found Google Contact Lookup for " + lookup + " but the FullName field was empty.");
                        return null;
                    }
                }
                else
                {
                    Log("No result was found with a Google Contact Lookup for " + lookup + ".");
                    return null;
                }
            }
            catch (Exception excp)
            {
                Log("Exception in GoogleContactLookup. " + excp.Message);
                return null;
            }
        }