/////////////////////////////////////////////////////////////////////////////


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


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

            rs.AutoPaging = true;
            ContactsRequest cr = new ContactsRequest(rs);

            Feed <Group> fg = cr.GetGroups();

            Group newGroup = new Group();

            newGroup.Title = "Private Data";

            Group insertedGroup = cr.Insert(fg, newGroup);

            Group g2 = new Group();

            g2.Title = "Another private Group";

            Group insertedGroup2 = cr.Insert(fg, g2);

            // now insert a new contact that belongs to that group
            Feed <Contact> fc = cr.GetContacts();
            Contact        c  = new Contact();

            c.AtomEntry = ObjectModelHelper.CreateContactEntry(1);

            GroupMembership member = new GroupMembership();

            member.HRef = insertedGroup.Id;


            GroupMembership member2 = new GroupMembership();

            member2.HRef = insertedGroup2.Id;

            Contact insertedEntry = cr.Insert(fc, c);

            // now change the group membership
            insertedEntry.GroupMembership.Add(member);
            insertedEntry.GroupMembership.Add(member2);
            Contact currentEntry = cr.Update(insertedEntry);

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

            currentEntry.GroupMembership.Clear();
            currentEntry = cr.Update(currentEntry);
            Assert.IsTrue(currentEntry.GroupMembership.Count == 0, "The entry should not be in a group");

            cr.Delete(currentEntry);
            cr.Delete(insertedGroup);
            cr.Delete(insertedGroup2);
        }
 public void UpdateContactFromOutlook(ContactItem oContact, Contact gContact)
 {
     try
     {
         //MessageBox.Show("In Update");
         LogInfo("Updating contact from Outlook");
         if (gContact == null)
         {
             LogInfo("Finding contact by FullName");
             var gContactsQuery = Contacts.Where(c => c.Title == oContact.FullName);
             if (gContactsQuery.Count() > 0)
             {
                 gContact = gContactsQuery.First();
                 LogInfo("Contact found: " + gContact.Title);
             }
             {
                 CreateContactFromOutlook(oContact);
                 return;
             }
         }
         ContactsRequest cr = new ContactsRequest(rs);
         UpdateContactDataFromOutlook(oContact, gContact);
         cr.Update(gContact);
         LogInfo("Contact updated");
     }
     catch (System.Exception ex)
     {
         LogError(ex.Message);
         LogDebug(ex.StackTrace.ToString());
     }
 }
Beispiel #3
0
        public void OAuth2LeggedContactsTest()
        {
            Tracing.TraceMsg("Entering OAuth2LeggedContactsTest");

            RequestSettings rs = new RequestSettings(this.ApplicationName, this.oAuthConsumerKey,
                                                     this.oAuthConsumerSecret, this.oAuthUser, this.oAuthDomain);

            ContactsRequest cr = new ContactsRequest(rs);

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

            // modify one
            foreach (Contact c in f.Entries)
            {
                c.Title = "new title";
                cr.Update(c);
                break;
            }

            Contact entry = new Contact();

            entry.AtomEntry            = ObjectModelHelper.CreateContactEntry(1);
            entry.PrimaryEmail.Address = "*****@*****.**";
            Contact e = cr.Insert(f, entry);

            cr.Delete(e);
        }
 /// <summary>
 /// 更新Google Contact
 /// </summary>
 private void UpdateGoogleContact(GoogleContactSyncData contactData, ContactsRequest contactRequest)
 {
     try
     {
         ReplaceContactEditUrl(contactData.Contact);
         var updatedContact = contactRequest.Update(contactData.Contact);
         _logger.InfoFormat("更新Google联系人#{0}|{1}|{2}", contactData.Id, contactData.Subject, _account.ID);
         UpdateContactLastUpdateTime(int.Parse(contactData.SyncId), updatedContact.Updated.ToLocalTime());
     }
     catch (Exception ex)
     {
         _logger.Error("UpdateGoogleContact has exception.", ex);
     }
 }
Beispiel #5
0
 public override void Update()
 {
     try
     {
         ContactsRequest cr = new ContactsRequest(_rs);
         if (_alreadyExistsOnGoogle)
         {
             //System.Windows.Forms.MessageBox.Show("Updating " + this.ToString() + " on Google");
             cr.Update(_item);
         }
         else
         {
             //System.Windows.Forms.MessageBox.Show("Inserting " + this.ToString() + " into Google");
             Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));
             cr.Insert(feedUri, _item);
         }
     }
     catch (GDataRequestException ex)
     {
         System.Windows.Forms.MessageBox.Show("GDataRequestException while saving data for " + this.ToString() + ": " + ex.ResponseString);
     }
 }
Beispiel #6
0
 public override void Update()
 {
     try
     {
         ContactsRequest cr = new ContactsRequest(_rs);
         if (_alreadyExistsOnGoogle)
         {
             //System.Windows.Forms.MessageBox.Show("Updating " + this.ToString() + " on Google");
             cr.Update(_item);
         }
         else
         {
             //System.Windows.Forms.MessageBox.Show("Inserting " + this.ToString() + " into Google");
             Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));
             cr.Insert(feedUri, _item);
         }
     }
     catch (GDataRequestException ex)
     {
         System.Windows.Forms.MessageBox.Show("GDataRequestException while saving data for " + this.ToString() + ": " + ex.ResponseString);
     }
 }
    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
    }
 static void UpdateName(Contact c, Dictionary<string,string> dic, ContactsRequest cr)
 {
     var name = c.Name;
     if (name.FamilyNamePhonetics != null && name.GivenNamePhonetics != null || !IsYomiTarget (name.FamilyName) && !IsYomiTarget (name.GivenName))
         return;
     if (name.FamilyNamePhonetics == null && IsYomiTarget (name.FamilyName) && dic.ContainsKey (name.FamilyName))
         name.FamilyNamePhonetics = dic [name.FamilyName];
     if (name.GivenNamePhonetics == null && IsYomiTarget (name.GivenName) && dic.ContainsKey (name.GivenName))
         name.GivenNamePhonetics = dic [name.GivenName];
     Console.WriteLine ("Setting {0} {1} => {2} {3}", name.FamilyName, name.GivenName, name.FamilyNamePhonetics, name.GivenNamePhonetics);
     #if false
     #else
     cr.Update<Contact> (c);
     #endif
 }
        public void OAuth2LeggedContactsTest() {
            Tracing.TraceMsg("Entering OAuth2LeggedContactsTest");

            RequestSettings rs = new RequestSettings(this.ApplicationName, this.oAuthConsumerKey,
                this.oAuthConsumerSecret, this.oAuthUser, this.oAuthDomain);

            ContactsRequest cr = new ContactsRequest(rs);

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

            // modify one
            foreach (Contact c in f.Entries) {
                c.Title = "new title";
                cr.Update(c);
                break;
            }

            Contact entry = new Contact();
            entry.AtomEntry = ObjectModelHelper.CreateContactEntry(1);
            entry.PrimaryEmail.Address = "*****@*****.**";
            Contact e = cr.Insert(f, entry);

            cr.Delete(e);
        }
        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);
        }
        public void ModelUpdateIfMatchAllContactsTest()
        {
            const int numberOfInserts = 5;

            Tracing.TraceMsg("Entering ModelInsertContactsTest");

            DeleteAllContacts();

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

            rs.AutoPaging = true;

            ContactsRequest cr = new ContactsRequest(rs);

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

            int originalCount = f.TotalResults;

            PhoneNumber    p        = null;
            List <Contact> inserted = new List <Contact>();

            if (f != null)
            {
                Assert.IsTrue(f.Entries != null, "the contacts needs entries");

                for (int i = 0; i < numberOfInserts; i++)
                {
                    Contact entry = new Contact();
                    entry.AtomEntry            = ObjectModelHelper.CreateContactEntry(i);
                    entry.PrimaryEmail.Address = "joe" + i.ToString() + "@doe.com";
                    p = entry.PrimaryPhonenumber;
                    inserted.Add(cr.Insert(f, entry));
                }
            }

            string newTitle = "This is an update to the title";

            f = cr.GetContacts();
            if (inserted.Count > 0)
            {
                int iVer = numberOfInserts;
                // let's find those guys
                foreach (Contact e in f.Entries)
                {
                    for (int i = 0; i < inserted.Count; i++)
                    {
                        Contact test = inserted[i];
                        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");
                            e.Name.FamilyName = newTitle;
                            e.ETag            = GDataRequestFactory.IfMatchAll;
                            inserted[i]       = cr.Update(e);
                        }
                    }
                }

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

            f = cr.GetContacts();
            if (inserted.Count > 0)
            {
                int iVer = numberOfInserts;
                // let's find those guys
                foreach (Contact e in f.Entries)
                {
                    for (int i = 0; i < inserted.Count; i++)
                    {
                        Contact test = inserted[i];
                        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.AreEqual(e.Name.FamilyName, newTitle, "The familyname should have been updated");
                        }
                    }
                }
                Assert.IsTrue(iVer == 0, "The new entries should all be part of the feed now, we have: " + iVer + " now");
            }


            // now delete them again
            DeleteList(inserted, cr, new Uri(f.AtomFeed.Batch));



            // now make sure they are gone
            if (inserted.Count > 0)
            {
                int iVer = inserted.Count;
                f = cr.GetContacts();
                foreach (Contact e in f.Entries)
                {
                    // let's find those guys, we should not find ANY
                    for (int i = 0; i < inserted.Count; i++)
                    {
                        Contact test = inserted[i] as Contact;
                        Assert.IsTrue(e.Id != test.Id, "The new entries should all be deleted now");
                    }
                }
                Assert.IsTrue(f.TotalResults == originalCount, "The count should be correct as well");
            }
        }
Beispiel #12
0
        public Google.Contacts.Contact UpdateContact(contacts item)
        {
            Uri contactURL = new Uri(item.gID);

            Google.Contacts.Contact newEntry = cr.Retrieve <Google.Contacts.Contact>(contactURL);

            Google.Contacts.Contact updatedContact2 = cr.Update(newEntry);

            // ----- NAME -----
            newEntry.Name = new Name()
            {
                FullName       = item.Name.FullName,
                NamePrefix     = item.Name.Prefix,
                GivenName      = item.Name.Firstname,
                AdditionalName = item.Name.AdditionalName,
                FamilyName     = item.Name.Surname,
                NameSuffix     = item.Name.Suffix,

                //FamilyNamePhonetics = ,
                //AdditionalNamePhonetics = ,
                //FamilyNamePhonetics = ,
            };

            updatedContact2 = cr.Update(newEntry);

            newEntry.ContactEntry.Nickname = item.Name.Nick;

            updatedContact2 = cr.Update(newEntry);

            // ----- EMAIL -----
            newEntry.Emails.Clear();
            if (item.Email != null)
            {
                foreach (var email in item.Email)
                {
                    if (email.Desc.IndexOf("#") == 0)
                    {
                        newEntry.Emails.Add(new EMail()
                        {
                            Primary = email.Primary,
                            Rel     = "http://schemas.google.com/g/2005" + email.Desc,
                            Address = email.Value
                        });
                    }
                    else if (email.Desc == "")
                    {
                        newEntry.Emails.Add(new EMail()
                        {
                            Primary = email.Primary,
                            Rel     = "http://schemas.google.com/g/2005#other",
                            Address = email.Value
                        });
                    }
                    else
                    {
                        newEntry.Emails.Add(new EMail()
                        {
                            Primary = email.Primary,
                            Label   = email.Desc,
                            Address = email.Value
                        });
                    }
                }
            }

            updatedContact2 = cr.Update(newEntry);

            // ----- PHONE -----
            newEntry.Phonenumbers.Clear();
            if (item.Phone != null)
            {
                foreach (var phone in item.Phone)
                {
                    if (phone.Desc.IndexOf("#") == 0)
                    {
                        newEntry.Phonenumbers.Add(new PhoneNumber()
                        {
                            Primary = phone.Primary,
                            Rel     = "http://schemas.google.com/g/2005" + phone.Desc,
                            Value   = phone.Value
                        });
                    }
                    else if (phone.Desc == "")
                    {
                        newEntry.Phonenumbers.Add(new PhoneNumber()
                        {
                            Primary = phone.Primary,
                            Rel     = "http://schemas.google.com/g/2005#other",
                            Value   = phone.Value
                        });
                    }
                    else
                    {
                        newEntry.Phonenumbers.Add(new PhoneNumber()
                        {
                            Primary = phone.Primary,
                            Label   = phone.Desc,
                            Value   = phone.Value
                        });
                    }
                }
            }

            updatedContact2 = cr.Update(newEntry);

            // ----- Organization -----
            newEntry.Organizations.Clear();
            if (item.Company != null)
            {
                foreach (var comp in item.Company)
                {
                    newEntry.Organizations.Add(new Organization()
                    {
                        Name  = comp.Name,
                        Title = comp.Position,
                        Rel   = "http://schemas.google.com/g/2005#other"
                    });
                }
            }

            updatedContact2 = cr.Update(newEntry);

            // ----- ADDRESS -----

            /*if (item.Address != null)
             * {
             *  foreach (var address in item.Address)
             *  {
             *      newEntry.PostalAddresses.Add(new StructuredPostalAddress()
             *      {
             *          Rel = address.Tag,            // ContactsRelationships.IsWork,
             *          Primary = address.Primary,
             *          Street = address.Street,
             *          City = address.City,
             *          Region = address.Region,
             *          Postcode = address.ZipCode,
             *          Country = address.Country,
             *          FormattedAddress = address.Street + ", " + address.City + ", " + address.Region + ", " + address.Country + ", " + address.ZipCode
             *      });
             *  }
             * }*/


            // ----- BIRTHDATE -----
            if (item.BirthDate != DateTime.MinValue)
            {
                //newEntry.AtomEntry.Birthday = item.BirthDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
                newEntry.ContactEntry.Birthday = item.BirthDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            }

            updatedContact2 = cr.Update(newEntry);

            // ----- DATES -----

            // ----- WEBSITES -----
            newEntry.ContactEntry.Websites.Clear();
            if (item.Web != null)
            {
                foreach (var web in item.Web)
                {
                    if (web.Desc.IndexOf("#") == 0)
                    {
                        newEntry.ContactEntry.Websites.Add(new Website()
                        {
                            Primary = web.Primary,
                            Rel     = "http://schemas.google.com/g/2005" + web.Desc,
                            Value   = web.Value
                        });
                    }
                    else if (web.Desc == "")
                    {
                        newEntry.ContactEntry.Websites.Add(new Website()
                        {
                            Primary = web.Primary,
                            Rel     = "http://schemas.google.com/g/2005#other",
                            Value   = web.Value
                        });
                    }
                    else
                    {
                        newEntry.ContactEntry.Websites.Add(new Website()
                        {
                            Primary = web.Primary,
                            Label   = web.Desc,
                            Value   = web.Value
                        });
                    }
                }
            }

            updatedContact2 = cr.Update(newEntry);

            // ----- IM -----
            newEntry.IMs.Clear();
            if (item.IM != null)
            {
                foreach (var im in item.IM)
                {
                    if (im.Desc.IndexOf("#") == 0)
                    {
                        newEntry.IMs.Add(new IMAddress()
                        {
                            Primary = im.Primary,
                            Rel     = "http://schemas.google.com/g/2005" + im.Desc,
                            Address = im.Value
                        });
                    }
                    else if (im.Desc == "")
                    {
                        newEntry.IMs.Add(new IMAddress()
                        {
                            Primary = im.Primary,
                            Rel     = "http://schemas.google.com/g/2005#other",
                            Address = im.Value
                        });
                    }
                    else
                    {
                        newEntry.IMs.Add(new IMAddress()
                        {
                            Primary  = im.Primary,
                            Protocol = im.Desc,
                            Address  = im.Value
                        });
                    }
                }
            }

            updatedContact2 = cr.Update(newEntry);

            // ----- GENRE -----
            for (int i = 0; i < newEntry.ContactEntry.UserDefinedFields.Count; i++)
            {
                if (newEntry.ContactEntry.UserDefinedFields[i].Key == "Genre")
                {
                    newEntry.ContactEntry.UserDefinedFields.RemoveAt(i);
                }
            }
            if (item.Genre != "")
            {
                newEntry.ContactEntry.UserDefinedFields.Add(new UserDefinedField()
                {
                    Key   = "Genre",
                    Value = item.Genre
                });
            }



            // ----- RELATIONS -----

            // ----- NOTE -----
            newEntry.Content = item.Note;

            // ----- google ID -----

            // ----- GROUP -----



            // Insert the contact.
            try
            {
                Google.Contacts.Contact updatedContact = cr.Update(newEntry);
                Console.WriteLine("Updated: " + updatedContact.Updated.ToString());
                return(updatedContact);
            }
            catch (GDataVersionConflictException e)
            {
                // Etags mismatch: handle the exception.
            }
            return(null);
        }
 /// <summary>
 /// 更新Google Contact
 /// </summary>
 private void UpdateGoogleContact(GoogleContactSyncData contactData, ContactsRequest contactRequest)
 {
     try
     {
         ReplaceContactEditUrl(contactData.Contact);
         var updatedContact = contactRequest.Update(contactData.Contact);
         _logger.InfoFormat("更新Google联系人#{0}|{1}|{2}", contactData.Id, contactData.Subject, _account.ID);
         UpdateContactLastUpdateTime(int.Parse(contactData.SyncId), updatedContact.Updated.ToLocalTime());
     }
     catch (Exception ex)
     {
         _logger.Error("UpdateGoogleContact has exception.", ex);
     }
 }
 public void UpdateContactFromOutlook(ContactItem oContact, Contact gContact)
 {
     try
     {
         //MessageBox.Show("In Update");
         LogInfo("Updating contact from Outlook");
         if (gContact == null)
         {
             LogInfo("Finding contact by FullName");
             var gContactsQuery = Contacts.Where(c => c.Title == oContact.FullName);
             if (gContactsQuery.Count() > 0)
             {
                 gContact = gContactsQuery.First();
                 LogInfo("Contact found: " + gContact.Title);
             }
             {
                 CreateContactFromOutlook(oContact);
                 return;
             }
         }
         ContactsRequest cr = new ContactsRequest(rs);
         UpdateContactDataFromOutlook(oContact, gContact);
         cr.Update(gContact);
         LogInfo("Contact updated");
     }
     catch (System.Exception ex)
     {
         LogError(ex.Message);
         LogDebug(ex.StackTrace.ToString());
     }
 }
        /////////////////////////////////////////////////////////////////////////////
 

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


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

            Feed<Group> fg = cr.GetGroups();

            Group newGroup = new Group();
            newGroup.Title = "Private Data";

            Group insertedGroup = cr.Insert(fg, newGroup);

            Group g2 = new Group();
            g2.Title = "Another private Group"; 

            Group insertedGroup2 = cr.Insert(fg, g2); 

            // now insert a new contact that belongs to that group
            Feed<Contact> fc = cr.GetContacts();
            Contact c = new Contact();
            c.AtomEntry = ObjectModelHelper.CreateContactEntry(1);

            GroupMembership member = new GroupMembership();
            member.HRef = insertedGroup.Id; 


            GroupMembership member2 = new GroupMembership();
            member2.HRef = insertedGroup2.Id; 
            
            Contact insertedEntry = cr.Insert(fc, c);

            // now change the group membership
            insertedEntry.GroupMembership.Add(member);
            insertedEntry.GroupMembership.Add(member2);
            Contact currentEntry = cr.Update(insertedEntry);

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

            currentEntry.GroupMembership.Clear();
            currentEntry = cr.Update(currentEntry);
            Assert.IsTrue(currentEntry.GroupMembership.Count == 0, "The entry should not be in a group");

            cr.Delete(currentEntry);
            cr.Delete(insertedGroup);
            cr.Delete(insertedGroup2);

        }
Beispiel #16
0
        public void CreateNewContact()
        {
            string gmailUsername;
            string syncProfile;

            LoadSettings(out gmailUsername, out syncProfile);

            ContactsRequest service;

            var scopes = new List <string>();

            //Contacts-Scope
            scopes.Add("https://www.google.com/m8/feeds");
            //Calendar-Scope
            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);
        }
        //////////////////////////////////////////////////////////////////////
        /// <summary>runs an authentication test, inserts a new contact</summary> 
        //////////////////////////////////////////////////////////////////////
        [Test] public void ModelUpdateContactsTest()
        {
            const int numberOfInserts = 5;
            Tracing.TraceMsg("Entering ModelInsertContactsTest");

            DeleteAllContacts();

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

            ContactsRequest cr = new ContactsRequest(rs);

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

            int originalCount = f.TotalResults;

            PhoneNumber p = null;
            List<Contact> inserted = new List<Contact>();

            if (f != null)
            {
                Assert.IsTrue(f.Entries != null, "the contacts needs entries");

                for (int i = 0; i < numberOfInserts; i++)
                {
                    Contact entry = new Contact();
                    entry.AtomEntry = ObjectModelHelper.CreateContactEntry(i);
                    entry.PrimaryEmail.Address = "joe" + i.ToString() + "@doe.com";
                    p = entry.PrimaryPhonenumber;
                    inserted.Add(cr.Insert(f, entry));
                }
            }

            string newTitle = "This is an update to the title";
            f = cr.GetContacts();
            if (inserted.Count > 0)
            {
                int iVer = numberOfInserts;
                // let's find those guys
                foreach (Contact e in f.Entries )
                {
                    for (int i = 0; i < inserted.Count; i++)
                    {
                        Contact test = inserted[i];
                        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");
                            e.Title = newTitle;
                            inserted[i] = cr.Update(e);
                        }
                    }
                }

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

            f = cr.GetContacts();
            if (inserted.Count > 0)
            {
                int iVer = numberOfInserts;
                // let's find those guys
                foreach (Contact e in f.Entries )
                {
                    for (int i = 0; i < inserted.Count; i++)
                    {
                        Contact test = inserted[i];
                        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.AreEqual(e.Title, newTitle, "The title should have been updated");
                        }
                    }
                }
                Assert.IsTrue(iVer == 0, "The new entries should all be part of the feed now, we have: " +  iVer + " now");
            }


            // now delete them again
            DeleteList(inserted, cr, new Uri(f.AtomFeed.Batch));



            // now make sure they are gone
            if (inserted.Count > 0)
            {
                int iVer = inserted.Count;
                f = cr.GetContacts();
                foreach (Contact e in f.Entries)
                {
                    // let's find those guys, we should not find ANY
                    for (int i = 0; i < inserted.Count; i++)
                    {
                        Contact test = inserted[i] as Contact;
                        Assert.IsTrue(e.Id != test.Id, "The new entries should all be deleted now");
                    }
                }
                Assert.IsTrue(f.TotalResults == originalCount, "The count should be correct as well");
            }
        }
    //This event controls the submit button for both the add contact modal and the edit contact modal.
    protected void addSubmitButton_Click(object sender, EventArgs e)
    {
        RequestSettings settings = new RequestSettings("ProQuorum Messaging Module", (String)Session["username"], (String)Session["password"]);
        ContactsRequest cr       = new ContactsRequest(settings);

        if (!editContactFlag)   //If we are adding a contact and not editing one.
        {
            Contact newEntry = new Contact();
            // Set the contact's name.
            if (fullName.Text != "")    //make sure the user has put in a full name.
            {
                newEntry.Name = new Name()
                {
                    FullName = fullName.Text
                               //GivenName = "Elizabeth",
                               //FamilyName = "Bennet",
                };
            }
            if (notes.Text != "")
            {
                newEntry.Content = notes.Text;
            }

            // Set the contact's e-mail addresses.
            if (prEmail.Text != "")         //make sure the user has put in a primary email.
            {
                newEntry.Emails.Add(new EMail()
                {
                    Primary = true,
                    Rel     = ContactsRelationships.IsHome,
                    Address = prEmail.Text
                });
            }
            // Set the contact's phone numbers.
            if (homePhone.Text != "")
            {
                newEntry.Phonenumbers.Add(new PhoneNumber()
                {
                    Primary = true,
                    Rel     = ContactsRelationships.IsHome,
                    Value   = homePhone.Text
                });
            }

            /* Set the contact's IM information.
             * newEntry.IMs.Add(new IMAddress()
             * {
             *  Primary = true,
             *  Rel = ContactsRelationships.IsHome,
             *  Protocol = ContactsProtocols.IsGoogleTalk,
             * });*/
            // Set the contact's postal address.
            if (address.Text != "" || city.Text != "" || state.Text != "" || zip.Text != "" || country.Text != "")
            {
                newEntry.PostalAddresses.Add(new StructuredPostalAddress()
                {
                    Rel      = ContactsRelationships.IsWork,
                    Primary  = true,
                    Street   = address.Text,
                    City     = city.Text,
                    Region   = state.Text,
                    Postcode = zip.Text,
                    Country  = country.Text
                               //FormattedAddress = "1600 Amphitheatre Pkwy Mountain View",
                });
            }
            // Insert the contact.
            Uri     feedUri      = new Uri(ContactsQuery.CreateContactsUri("default"));
            Contact createdEntry = cr.Insert(feedUri, newEntry);

            //Update the contacts list box to reflect the new contact as well as the contacts data structures.
            _contacts.Add(newEntry);
            _contactNames.Add(newEntry.Name.FullName);
            //Sort both the lists of contacts in alphabetical order
            _contactNames.Sort();
            _contacts = _contacts.OrderBy(o => o.Name.FullName).ToList();
            ContactsListBox.DataSource = null;      //update the listbox.
            ContactsListBox.DataSource = _contactNames;
            ContactsListBox.DataBind();
            title.Text = "Contact List (" + _contacts.Count.ToString() + " entries)";

            //MessageBox.Show("Contact was successfully added.");
            successOutput.Text = "Contact was successfully added.";
            ClientScript.RegisterStartupScript(GetType(), "Show", "<script> $('#successModal').modal('toggle');</script>");
        }
        else //We are editing a contact.
        {
            try
            {
                //set all of the contacts fields to the new values of the text fields.
                if (fullName.Text.Length > 0)
                {
                    contact.Name.FullName = fullName.Text;
                }
                else
                {
                    contact.Name.FullName = "";
                }

                if (notes.Text.Length > 0)
                {
                    contact.Content = notes.Text;
                }
                else
                {
                    contact.Content = "";
                }

                if (prEmail.Text.Length > 0)
                {
                    contact.PrimaryEmail.Address = prEmail.Text;
                }
                else
                {
                    contact.PrimaryEmail.Address = "";
                }

                if (homePhone.Text.Length > 0)
                {
                    contact.PrimaryPhonenumber.Value = homePhone.Text;
                }
                else
                {
                    contact.PrimaryPhonenumber.Value = "";
                }

                if (address.Text.Length > 0)
                {
                    contact.PrimaryPostalAddress.Street = address.Text;
                }
                else
                {
                    contact.PrimaryPostalAddress.Street = "";
                }

                if (city.Text.Length > 0)
                {
                    contact.PrimaryPostalAddress.City = city.Text;
                }
                else
                {
                    contact.PrimaryPostalAddress.City = "";
                }

                if (state.Text.Length > 0)
                {
                    contact.PrimaryPostalAddress.Region = state.Text;
                }
                else
                {
                    contact.PrimaryPostalAddress.Region = "";
                }

                if (zip.Text.Length > 0)
                {
                    contact.PrimaryPostalAddress.Postcode = zip.Text;
                }
                else
                {
                    contact.PrimaryPostalAddress.Postcode = "";
                }

                if (country.Text.Length > 0)
                {
                    contact.PrimaryPostalAddress.Country = country.Text;
                }
                else
                {
                    contact.PrimaryPostalAddress.Country = "";
                }

                Contact updatedContact = cr.Update(contact);

                //MessageBox.Show("Contact was updated successfully.");
                successOutput.Text = "Contact was updated successfully.";
                ClientScript.RegisterStartupScript(GetType(), "Show", "<script> $('#successModal').modal('toggle');</script>");
            }
            catch (GDataVersionConflictException ex)
            {
                //MessageBox.Show("Etag mismatch. Could not update contact.");
                errorOutput.Text = "Etag mismatch. Could not update contact.";
                ClientScript.RegisterStartupScript(GetType(), "Show", "<script> $('#errorModal').modal('toggle');</script>");
            }
        }
    }