Beispiel #1
0
        public bool Extract(NetworkCredential credential, out MailContactList list)
        {
            bool result = false;
            list = new MailContactList();

            try
            {
                var rs = new RequestSettings("eStream-AspNetDating", credential.UserName, credential.Password)
                             {AutoPaging = true};

                var cr = new ContactsRequest(rs);

                Feed<Contact> f = cr.GetContacts();
                foreach (Contact e in f.Entries)
                {
                    foreach (var email in e.Emails)
                    {
                        var mailContact = new MailContact {Email = email.Address, Name = e.Title};
                        list.Add(mailContact);
                    }
                }
                result = true;
            }
            catch (Exception ex)
            {
                Global.Logger.LogError(ex);
            }

            return result;
        }
		private ContactsRequest GetGoogleRequest() {
			if (_googleContactRequest == null) {
				RequestSettings rs = new RequestSettings("Avega.ContactSynchronizer", GoogleAuthentication.Username, GoogleAuthentication.Password);
				rs.AutoPaging = true;
				_googleContactRequest = new ContactsRequest(rs);
			}
			return _googleContactRequest;
		}
Beispiel #3
0
        public string Get()
        {
            RequestSettings settings = new RequestSettings("YOUR_APPLICATION_NAME");
            // Add authorization token.
            // ...
            ContactsRequest cr = new ContactsRequest(settings);

            return "ok";
        }
Beispiel #4
0
 private static void PrintAllContacts(ContactsRequest cr)
 {
     Feed<Contact> f = cr.GetContacts();
     foreach (Contact entry in f.Entries)
     {
         if (entry.Name != null)
         {
         Name name = entry.Name;
         if (!string.IsNullOrEmpty(name.FullName))
             Console.WriteLine("\t\t" + name.FullName);
         else
             Console.WriteLine("\t\t (no full name found)");
         if (!string.IsNullOrEmpty(name.NamePrefix))
             Console.WriteLine("\t\t" + name.NamePrefix);
         else
             Console.WriteLine("\t\t (no name prefix found)");
         if (!string.IsNullOrEmpty(name.GivenName))
         {
             string givenNameToDisplay = name.GivenName;
             if (!string.IsNullOrEmpty(name.GivenNamePhonetics))
             givenNameToDisplay += " (" + name.GivenNamePhonetics + ")";
             Console.WriteLine("\t\t" + givenNameToDisplay);
         }
         else
             Console.WriteLine("\t\t (no given name found)");
         if (!string.IsNullOrEmpty(name.AdditionalName))
         {
             string additionalNameToDisplay = name.AdditionalName;
             if (string.IsNullOrEmpty(name.AdditionalNamePhonetics))
             additionalNameToDisplay += " (" + name.AdditionalNamePhonetics + ")";
             Console.WriteLine("\t\t" + additionalNameToDisplay);
         }
         else
             Console.WriteLine("\t\t (no additional name found)");
         if (!string.IsNullOrEmpty(name.FamilyName))
         {
             string familyNameToDisplay = name.FamilyName;
             if (!string.IsNullOrEmpty(name.FamilyNamePhonetics))
             familyNameToDisplay += " (" + name.FamilyNamePhonetics + ")";
             Console.WriteLine("\t\t" + familyNameToDisplay);
         }
         else
             Console.WriteLine("\t\t (no family name found)");
         if (!string.IsNullOrEmpty(name.NameSuffix))
             Console.WriteLine("\t\t" + name.NameSuffix);
         else
             Console.WriteLine("\t\t (no name suffix found)");
         }
         else
             Console.WriteLine("\t (no name found)");
             foreach (EMail email in entry.Emails)
         {
             Console.WriteLine("\t" + email.Address);
         }
     }
 }
Beispiel #5
0
        /// <summary>
        /// constructs a new ProfilesManager and authenticate using 2-Legged OAuth
        /// </summary>
        /// <param name="consumerKey">Domain's consumer key</param>
        /// <param name="consumerSecret">Domain's consumer secret</param>
        /// <param name="adminEmail">Domain administrator's email</param>
        public ProfilesManager(String consumerKey, String consumerSecret, String adminEmail) {
            String admin = adminEmail.Substring(0, adminEmail.IndexOf('@'));
            this.domain = adminEmail.Substring(adminEmail.IndexOf('@') + 1);

            RequestSettings settings =
                new RequestSettings("GoogleInc-UnshareProfilesSample-1", consumerKey,
                                    consumerSecret, admin, this.domain);
            settings.AutoPaging = true;
            this.cr = new ContactsRequest(settings);

            this.BatchSize = 100;
        }
 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 IEnumerable<IContact> GetContacts()
 {
     ContactsRequest cr = new ContactsRequest(_rs);
     //cr.Service.RequestFactory = new GDataLoggingRequestFactory(cr.Service.ServiceIdentifier, "GContactSync");
     Feed<Google.Contacts.Contact> feed = cr.GetContacts();
     List<IContact> list = new List<IContact>();
     foreach (Google.Contacts.Contact gContact in feed.Entries)
     {
         IContact c = new GContact(_rs, gContact);
         list.Add(c);
     }
     return list;
 }
        /// <summary>
        /// Send authorized queries to a Request-based library
        /// </summary>
        /// <param name="service"></param>
        private static void RunContactsSample(OAuth2Parameters parameters) {
            try {
                RequestSettings settings = new RequestSettings(applicationName, parameters);
                ContactsRequest cr = new ContactsRequest(settings);

                Feed<Contact> f = cr.GetContacts();
                foreach (Contact c in f.Entries) {
                    Console.WriteLine(c.Name.FullName);
                }
            } catch (AppsException a) {
                Console.WriteLine("A Google Apps error occurred.");
                Console.WriteLine();
                Console.WriteLine("Error code: {0}", a.ErrorCode);
                Console.WriteLine("Invalid input: {0}", a.InvalidInput);
                Console.WriteLine("Reason: {0}", a.Reason);
            }
        }
    protected void btnContacts_Click(object sender, EventArgs e)
    {
        //Provide Login Information
        ViewState["hello"] = txtPassword.Text;
        RequestSettings rsLoginInfo = new RequestSettings("", txtEmail.Text, txtPassword.Text);
        rsLoginInfo.AutoPaging = true;

        // Fetch contacts and dislay them in ListBox
        ContactsRequest cRequest = new ContactsRequest(rsLoginInfo);
        Feed<Contact> feedContacts = cRequest.GetContacts();
        foreach (Contact gmailAddresses in feedContacts.Entries)
        {

            foreach (EMail emailId in gmailAddresses.Emails)
            {
                RadListBoxItem item = new RadListBoxItem();
                item.Text = emailId.Address;
                RadListBoxSource.Items.Add(item);
            }
        }
    }
        public static List<ContactsView> GetGmailContacts(string App_Name, string Uname, string UPassword)
        {
            var contacts = new List<ContactsView>();

            var rs = new RequestSettings(App_Name, Uname, UPassword){ AutoPaging = true };

            var contactsRequest = new ContactsRequest(rs);
            var feed = contactsRequest.GetContacts();

            foreach (Contact contact in feed.Entries)
            {
                var fetchedContact = new ContactsView { Name = contact.Name.FullName };

                foreach (EMail email in contact.Emails)
                {
                    if (email.Address == null) continue;
                    fetchedContact.Email = email.Address;
                }
                contacts.Add(fetchedContact);
            }
            return contacts;
        }
Beispiel #11
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 GoogleContactsManager CreateContactsManager()
        {
            var settings = new RequestSettings("Maintain Work Contacts",
                                               Settings.Default.EmailAddressUsername,
                                               Utility.ToInsecureString(Utility.DecryptString(Settings.Default.EmailAddressPassword)));
            settings.AutoPaging = true;
            var request = new ContactsRequest(settings);

            IEnumerable<Group> groups;
            try
            {
                groups = request.GetGroups().Entries;

                string groupName = Settings.Default.GoogleWorkGroupName;
                var workGroup = groups.Where(g => g.Title.Contains(groupName)).FirstOrDefault();
                if (workGroup == null)
                {
                    throw new ArgumentNullException("WorkGroup", "There is no group called " + groupName + " in the Google account.");
                }

                var myContactsGroup = groups.Where(g => g.Title.Contains("My Contacts")).FirstOrDefault();
                if (myContactsGroup == null)
                {
                    throw new ArgumentNullException("MyContactsGroup", "There is no group called My Contacts in the Google account.");
                }

                GoogleContactsManager contactsManager = new GoogleContactsManager();
                contactsManager.Request = request;
                contactsManager.MyContactsGroup = myContactsGroup;
                contactsManager.WorkGroup = workGroup;
                return contactsManager;
            }
            catch (GDataRequestException exception)
            {
                throw new InvalidCredentialsException("Invalid username and password were provided.", exception);
            }
        }
    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();
    }
    //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>");
            }
        }
    }
        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);
            }
        }
Beispiel #16
0
        /// <summary>
        /// New mail process
        /// </summary>
        public async Task NewMailProcess(
            GmailService service,
            string userId,
            List <string> labels,
            long userMembershipId,
            UserCredential userCredential,
            object contactList,
            UsersResource.MessagesResource.ListRequest request,
            Group group,
            ContactsRequest contactRequest,
            System.Diagnostics.Stopwatch watch,
            CancellationToken cancellationToken
            )
        {
            try
            {
                //request.LabelIds = labels;

                do
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    //Old mail process
                    ListMessagesResponse response = request.Execute(); //
                    request.PageToken = response.NextPageToken;
                    var batchrequest = new BatchRequest(service);
                    if (response.Messages != null)
                    {
                        foreach (Message message in response.Messages)
                        {
                            var req = service.Users.Messages.Get(userId, message.Id);
                            req.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full;
                            batchrequest.Queue <Message>(req,
                                                         (content, error, i, messagesvalue) =>
                            {
                                //Lead411EmailParseResult Lead411EmailParseResult = MessageParser.Parse(content);
                                ////Create new contact
                                //if (Lead411EmailParseResult.SignatureBlockContactCardInfo != null)
                                //{
                                //    Operation.CreateContact(group, contactRequest, Lead411EmailParseResult, contactList);
                                //}
                                //_noOfMailsProccessed++;
                                //if (_noOfMailsProccessed >= GeneralParameters.MaximumSingleRunIndexCount)
                                //{
                                //    _cts.Cancel(true);
                                //}
                                // Put your callback code here.
                            });
                            //cancellationToken.ThrowIfCancellationRequested();
                            //Message msg = await service.Users.Messages.Get(userId, message.Id).ExecuteAsync();
                        }
                        await batchrequest.ExecuteAsync(cancellationToken); //
                    }
                } while (!String.IsNullOrWhiteSpace(request.PageToken));
                watch.Stop();
                // _elapsedMs = watch.ElapsedMilliseconds;
                // var lastMailDate = DateTime.UtcNow;
            }
            catch (OperationCanceledException)
            {
                watch.Stop();
                //_elapsedMs = watch.ElapsedMilliseconds;
                // var lastMailDate = DateTime.UtcNow;
            }
        }
        /////////////////////////////////////////////////////////////////////////////
 

        /////////////////////////////////////////////////////////////////////
        /// <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);

        }
        /////////////////////////////////////////////////////////////////////////////


        private void DeleteList(List<Contact> list, ContactsRequest cr, Uri batch)
        {
            int i = 0; 
            foreach (Contact c in list)
            {
                c.BatchData = new GDataBatchEntryData();
                c.BatchData.Id = i.ToString();
                i++;
            }

            cr.Batch(list, batch, GDataBatchOperationType.delete);
        }
 public ContactActionUpdate(ContactsRequest request, Contact googleContact, string description)
     : base(request, googleContact, description)
 {
 }
 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
 }
        /////////////////////////////////////////////////////////////////////////////
        
        
        //////////////////////////////////////////////////////////////////////
        /// <summary>runs an authentication test, inserts a new contact</summary> 
        //////////////////////////////////////////////////////////////////////
        [Test] public void ModelBatchContactsTest()
        {
            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);

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

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

            for (int i = 0; i < numberOfInserts; i++)
            {
                Contact entry = new Contact();
                entry.AtomEntry = ObjectModelHelper.CreateContactEntry(i);
                entry.PrimaryEmail.Address = "joe" + i.ToString() + "@doe.com";
                GDataBatchEntryData g = new GDataBatchEntryData();
                g.Id = i.ToString(); 
                g.Type = GDataBatchOperationType.insert;
                entry.BatchData = g;
                list.Add(entry);
            }

            Feed<Contact> r = cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.Default);
            list.Clear();

            int iVerify = 0;

            foreach (Contact c in r.Entries )
            {
                // let's count and update them
                iVerify++; 
                c.Title = "get a nother one"; 
                c.BatchData.Type = GDataBatchOperationType.update;
                list.Add(c);
            }
            Assert.IsTrue(iVerify == numberOfInserts, "should have gotten 5 inserts");

            Feed<Contact> u = cr.Batch(list, new Uri(r.AtomFeed.Batch), GDataBatchOperationType.Default);
            list.Clear();

            iVerify = 0; 
            foreach (Contact c in u.Entries )
            {
                // let's count and update them
                iVerify++; 
                c.BatchData.Type = GDataBatchOperationType.delete;
                list.Add(c);
            }
            Assert.IsTrue(iVerify == numberOfInserts, "should have gotten 5 updates");

            Feed<Contact> d = cr.Batch(list, new Uri(u.AtomFeed.Batch), GDataBatchOperationType.Default);

            iVerify = 0; 
            foreach (Contact c in d.Entries )
            {
                if (c.BatchData.Status.Code == 200)
                {
                    // let's count and update them
                    iVerify++; 
                }
            }
            Assert.IsTrue(iVerify == numberOfInserts, "should have gotten 5 deletes");

        }
        /// <summary>
        ///     <see cref="Authenticate" /> to Google Using Oauth2 Documentation
        ///     https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">
        ///     From Google Developer console https://console.developers.google.com
        /// </param>
        /// <param name="clientSecret">
        ///     From Google Developer console https://console.developers.google.com
        /// </param>
        /// <param name="userName">
        ///     A string used to identify a user (locally).
        /// </param>
        /// <param name="fileDataStorePath">
        ///     Name/Path where the Auth Token and refresh token are stored (usually
        ///     in %APPDATA%)
        /// </param>
        /// <param name="applicationName">Applicaiton Name</param>
        /// <param name="isFullPath">
        ///     <paramref name="fileDataStorePath" /> is completePath or Directory
        ///     Name
        /// </param>
        /// <returns>
        /// </returns>
        public ContactsRequest AuthenticateContactOauth(string clientId, string clientSecret, string userName,
            string fileDataStorePath, string applicationName, bool isFullPath = false)
        {
            try
            {
                var authTask = Authenticate(clientId, clientSecret, userName, fileDataStorePath, isFullPath);

                authTask.Wait(30000);

                if (authTask.Status == TaskStatus.WaitingForActivation)
                {
                    return null;
                }

                var service = new ContactsRequest(new RequestSettings(applicationName));

                return service;
            }
            catch (AggregateException exception)
            {
                Logger.Error(exception);
                return null;
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
                return null;
            }
        }
        public virtual ActionResult GoogleAuthCallback(string code = null, string error = null)
        {
            if (String.IsNullOrWhiteSpace(code))
            {
                return(View(Views.Index));
            }

            var client = new WebClient();

            var parameters = new NameValueCollection
            {
                { "client_id", "1051352266030-l2avpmbf9kk0s8b9eshqu6fkd0gee50g.apps.googleusercontent.com" },
                { "client_secret", "5Ai2kKsRUK8Av5RehYB3rx7k" },
                { "grant_type", "authorization_code" },
                { "redirect_uri", "http://localhost:64901/GoogleAuthCallback" },
                { "code", code }
            };

            var     rawResponse    = client.UploadValues("https://accounts.google.com/o/oauth2/token", parameters);
            var     responseString = Encoding.UTF8.GetString(rawResponse);
            dynamic tokenData      = JsonConvert.DeserializeObject(responseString);

            //rawResponse = client.DownloadData(String.Format("https://www.google.com/m8/feeds/contacts/default/full?access_token={0}", tokenData.access_token));
            //responseString = Encoding.UTF8.GetString(rawResponse);

            //dynamic contactsData = JsonConvert.DeserializeObject(responseString);

            var rs = new RequestSettings("Google Contacts Test", tokenData.access_token.ToString())
            {
                AutoPaging = true
            };

            var cr = new ContactsRequest(rs);

            var rawContacts = cr.GetContacts();
            var rawGroups   = cr.GetGroups();

            var groups = new List <String>();

            foreach (var entry in rawGroups.Entries)
            {
                groups.Add(entry.Title);
            }


            var contacts = new List <Tuple <String, String> >();

            foreach (var entry in rawContacts.Entries)
            {
                if (!entry.Emails.Any())
                {
                    continue;
                }

                var b = (from gm in entry.GroupMembership
                         join rg in rawGroups.Entries on gm.HRef equals rg.AtomEntry.Id.AbsoluteUri
                         where !rg.Title.ToLower().Equals("starred in android")
                         select
                         rg.Title.ToLower().Contains("system group")
                            ? rg.Title.Split(new[] { ':' })[1].Trim()
                            : rg.Title)
                        .ToList();

                var tuple = new Tuple <string, string>(entry.Title, entry.Emails.First().Address);
                contacts.Add(tuple);
            }

            return(View(Views.Index));
        }
Beispiel #24
0
        //public void AddContact(GooglePlusAccessToken serStatus)
        //{
        //    /*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()
        //    {
        //        Scope = scopes,
        //        AccessToken = accessToken,
        //        RefreshToken = refreshToken
        //    };

        //    RequestSettings settings = new RequestSettings("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters);
        //    ContactsRequest cr = new ContactsRequest(settings);

        //    Contact newEntry = new Contact();
        //    newEntry.Name = new Name();
        //    newEntry.Name.FullName = "Abhishek k";

        //    newEntry.Emails = new
        //}

        public static Contact CreateContact(ContactsRequest cr)
        {
            Contact newEntry = new Contact();

            // Set the contact's name.
            newEntry.Name = new Name()
            {
                FullName   = "Elizabeth Bennet",
                GivenName  = "Elizabeth",
                FamilyName = "Bennet",
            };
            newEntry.Content = "Notes";
            // Set the contact's e-mail addresses.
            newEntry.Emails.Add(new EMail()
            {
                Primary = true,
                Rel     = ContactsRelationships.IsHome,
                Address = "*****@*****.**"
            });
            newEntry.Emails.Add(new EMail()
            {
                Rel     = ContactsRelationships.IsWork,
                Address = "*****@*****.**"
            });
            // Set the contact's phone numbers.
            newEntry.Phonenumbers.Add(new PhoneNumber()
            {
                Primary = true,
                Rel     = ContactsRelationships.IsWork,
                Value   = "(206)555-1212",
            });
            newEntry.Phonenumbers.Add(new PhoneNumber()
            {
                Rel   = ContactsRelationships.IsHome,
                Value = "(206)555-1213",
            });
            // 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.
            newEntry.PostalAddresses.Add(new StructuredPostalAddress()
            {
                Rel              = ContactsRelationships.IsWork,
                Primary          = true,
                Street           = "1600 Amphitheatre Pkwy",
                City             = "Mountain View",
                Region           = "CA",
                Postcode         = "94043",
                Country          = "United States",
                FormattedAddress = "1600 Amphitheatre Pkwy Mountain View",
            });
            // Insert the contact.
            Uri     feedUri      = new Uri(ContactsQuery.CreateContactsUri("default"));
            Contact createdEntry = cr.Insert(feedUri, newEntry);

            Console.WriteLine("Contact's ID: " + createdEntry.Id);
            return(createdEntry);
        }
        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);
        }
 private IEnumerable <Contact> CastEntriesToContacts(IEnumerable <global::Google.Contacts.Contact> feedContacts, ContactsRequest contactReq)
 {
     return((from fContact in feedContacts
             where !string.IsNullOrEmpty(fContact.Name.FullName)
             select CastToGoferContact(fContact, contactReq)).ToList());
 }
        public static void PrintAllContacts(ContactsRequest cr)
        {
            Feed <Contact> f = cr.GetContacts();

            foreach (Contact entry in f.Entries)
            {
                if (entry.Name != null)
                {
                    Name name = entry.Name;
                    if (!string.IsNullOrEmpty(name.FullName))
                    {
                        Console.WriteLine("\t\t" + name.FullName);
                    }
                    else
                    {
                        Console.WriteLine("\t\t (no full name found)");
                    }
                    if (!string.IsNullOrEmpty(name.NamePrefix))
                    {
                        Console.WriteLine("\t\t" + name.NamePrefix);
                    }
                    else
                    {
                        Console.WriteLine("\t\t (no name prefix found)");
                    }
                    if (!string.IsNullOrEmpty(name.GivenName))
                    {
                        string givenNameToDisplay = name.GivenName;
                        if (!string.IsNullOrEmpty(name.GivenNamePhonetics))
                        {
                            givenNameToDisplay += " (" + name.GivenNamePhonetics + ")";
                        }
                        Console.WriteLine("\t\t" + givenNameToDisplay);
                    }
                    else
                    {
                        Console.WriteLine("\t\t (no given name found)");
                    }
                    if (!string.IsNullOrEmpty(name.AdditionalName))
                    {
                        string additionalNameToDisplay = name.AdditionalName;
                        if (string.IsNullOrEmpty(name.AdditionalNamePhonetics))
                        {
                            additionalNameToDisplay += " (" + name.AdditionalNamePhonetics + ")";
                        }
                        Console.WriteLine("\t\t" + additionalNameToDisplay);
                    }
                    else
                    {
                        Console.WriteLine("\t\t (no additional name found)");
                    }
                    if (!string.IsNullOrEmpty(name.FamilyName))
                    {
                        string familyNameToDisplay = name.FamilyName;
                        if (!string.IsNullOrEmpty(name.FamilyNamePhonetics))
                        {
                            familyNameToDisplay += " (" + name.FamilyNamePhonetics + ")";
                        }
                        Console.WriteLine("\t\t" + familyNameToDisplay);
                    }
                    else
                    {
                        Console.WriteLine("\t\t (no family name found)");
                    }
                    if (!string.IsNullOrEmpty(name.NameSuffix))
                    {
                        Console.WriteLine("\t\t" + name.NameSuffix);
                    }
                    else
                    {
                        Console.WriteLine("\t\t (no name suffix found)");
                    }
                }
                else
                {
                    Console.WriteLine("\t (no name found)");
                }
                foreach (EMail email in entry.Emails)
                {
                    Console.WriteLine("\t" + email.Address);
                }
            }
        }
Beispiel #28
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);
        }
    List <Contact> _contacts    = new List <Contact>(); //We need have a list of type Contact so we can reference it for editing and deleting.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["username"] == null || Session["password"] == null)
        {
            /*oAuth 2.0 Legacy
             * code = Request.QueryString["code"]; //extract oAUTH code from the URL that google has provided us
             * accessToken = getToken();
             * Session["accessToken"] = accessToken; //Save access token for all future interactions with google for this session.
             * emailInfo.Text = "New Access Token: " + accessToken;
             */
            //Redirect the user to the login page if these variables are not set
            Response.Redirect("http://localhost:1172/Default.aspx");
        }
        else
        {
            /*oAuth 2.0 Legacy
             * accessToken = (String)Session["accessToken"];
             * emailInfo.Text = "Same Session Token: " + accessToken;
             */
        }

        //Extract the contacts from the address book.
        RequestSettings settings = new RequestSettings("ProQuorum Messaging Module", (String)Session["username"], (String)Session["password"]);

        //Setting autopaging to true means all of the contacts will be extracted instead of a portion.
        settings.AutoPaging = true;
        ContactsRequest cr = new ContactsRequest(settings);
        Feed <Contact>  f  = cr.GetContacts();

        //Input all names into a list, which will be used as the data source for the ListBox.
        foreach (Contact entry in f.Entries)
        {
            _contacts.Add(entry);
            if (entry.Name != null)
            {
                Name name = entry.Name;
                if (!string.IsNullOrEmpty(name.FullName))
                {
                    _contactNames.Add(name.FullName);
                }
                else
                {
                    _contactNames.Add("No full name found.");
                }
            }
            else
            {
                _contactNames.Add("No name found.");
            }

            /*
             * foreach (EMail email in entry.Emails)
             * {
             *  _emails.Add(email.Address);
             * }*/
        }

        //Sort both the lists of contacts in alphabetical order
        _contactNames.Sort();
        _contacts = _contacts.OrderBy(o => o.Name.FullName).ToList();
        //Set the title label on top of the address book to the number of contacts.
        title.Text = "Contact List (" + _contacts.Count.ToString() + " entries)";
        if (!Page.IsPostBack)  //this needs to be checked so that the listbox can read what index the user is selecting.
        {
            ContactsListBox.DataSource = _contactNames;
            ContactsListBox.DataBind();
        }

        //Populate the inbox with the emails
        try
        {
            tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
            ssl  = new System.Net.Security.SslStream(tcpc.GetStream());
            ssl.AuthenticateAsClient("imap.gmail.com");
            receiveResponse("");
            //IMAP login command
            string googleResponse = receiveResponse("$ LOGIN " + (String)Session["username"] + " " + (String)Session["password"] + "  \r\n");
            System.Diagnostics.Debug.WriteLine(googleResponse + " |LOGIN END|");
            //This command lists the folders (inbox,sentmail,users labels )
            //receiveResponse("$ LIST " + "\"\"" + " \"*\"" + "\r\n");
            //Select the inbox folder
            googleResponse = receiveResponse("$ SELECT INBOX\r\n");
            System.Diagnostics.Debug.WriteLine(googleResponse + " |SELECT INBOX END|");
            //Get the status of the inbox. Response includes the number of messages.
            googleResponse = receiveResponse("$ STATUS INBOX (MESSAGES)\r\n");
            System.Diagnostics.Debug.WriteLine(googleResponse + " |STATUS INBOX END|");
            //Use String.Split to extract the number of emails and parses.
            string[] stringSeparators = new string[] { "(MESSAGES", ")" };
            string[] words            = googleResponse.ToString().Split(stringSeparators, StringSplitOptions.None);

            try{
                numEmails = int.Parse(words[1]);
            }
            catch
            {
                MessageBox.Show("Error parsing number of emails.");
            }

            //Extract all emails and organize them into the table.
            if (numEmails > 0)
            {
                for (int i = numEmails; i >= 1; i--)
                {
                    TableRow r = new TableRow();
                    //Highlight when cursor is over the message.
                    r.Attributes["onmouseover"] = "highlight(this, true);";
                    //Remove the highlight when the curser exits the message
                    r.Attributes["onmouseout"] = "highlight(this, false);";
                    r.Attributes["style"]      = "cursor:pointer;";
                    r.Attributes["onclick"]    = "link(this, false);";

                    r.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");

                    //The first cell in the row will be a checkbox
                    TableCell c0 = new TableCell();
                    c0.HorizontalAlign = HorizontalAlign.Center;
                    System.Web.UI.WebControls.CheckBox checkBox = new System.Web.UI.WebControls.CheckBox();
                    //Add the js function to the checkbox that will highlight the row when checked and unhighlight when unchecked.
                    checkBox.Attributes.Add("onclick", "javascript:colorRow(this);");
                    c0.Controls.Add(checkBox);
                    r.Cells.Add(c0);

                    //Specifc email number to fetch.
                    googleResponse = receiveResponse("$ FETCH " + i + " body[HEADER.FIELDS (DATE FROM SUBJECT)]\r\n");
                    while (!googleResponse.Contains("$ OK Success"))
                    {
                        googleResponse += receiveResponse("");
                    }
                    System.Diagnostics.Debug.WriteLine(googleResponse + " |HEADER " + i + " END|");

                    string[] orderedHeaders = organizeHeaders(googleResponse);

                    //The second cell will be who the message is from (email)
                    TableCell c1 = new TableCell();
                    //c1.Controls.Add(new LiteralControl(headers[3]));
                    c1.Controls.Add(new LiteralControl(orderedHeaders[0]));
                    r.Cells.Add(c1);

                    //The third cell will be the subject.
                    TableCell c2 = new TableCell();
                    c2.Controls.Add(new LiteralControl(orderedHeaders[1]));
                    r.Cells.Add(c2);

                    //The fourth cell will be the Date.
                    TableCell c3 = new TableCell();
                    //Parse the date into a more readable format
                    string[] ss        = new string[] { " " };
                    string[] dateSplit = orderedHeaders[2].Split(ss, StringSplitOptions.None);
                    DateTime time      = Convert.ToDateTime(dateSplit[5]);
                    c3.Controls.Add(new LiteralControl(dateSplit[1] + " " + dateSplit[2] + " " + dateSplit[3] + " " + dateSplit[4] + " " + time.ToShortTimeString()));
                    r.Cells.Add(c3);

                    googleResponse = receiveResponse("$ FETCH " + i + " body[text]\r\n");
                    System.Threading.Thread.Sleep(1000);
                    googleResponse += receiveResponse("");
                    System.Diagnostics.Debug.WriteLine(googleResponse + " |MESSAGE " + i + " END|");
                    //Remove the beginning metadata
                    int beginningDataIndex = googleResponse.IndexOf("}");
                    if (beginningDataIndex != -1)
                    {
                        googleResponse = googleResponse.Remove(0, beginningDataIndex + 1);
                    }
                    googleResponse = googleResponse.Trim();
                    //Remove the ") $ OK Success" at the end of the header
                    int index = googleResponse.LastIndexOf(")");
                    if (index > -1)
                    {
                        googleResponse = googleResponse.Remove(index);
                    }

                    //Add a hidden cell so the javascript can access the message and put it in a modal when clicked on.
                    TableCell c4 = new TableCell();
                    //c4.Controls.Add(new LiteralControl(emailBody[1]));
                    c4.Controls.Add(new LiteralControl(googleResponse.ToString()));
                    r.Cells.Add(c4);
                    c4.Attributes.Add("hidden", "true");

                    InboxTable.Rows.Add(r);
                }
            }
            else
            {
                TableRow  r  = new TableRow();
                TableCell c1 = new TableCell();
                c1.Controls.Add(new LiteralControl("No Messages"));
                r.Cells.Add(c1);
                InboxTable.Rows.Add(r);
            }
            receiveResponse("$ LOGOUT\r\n");
        }
        catch (Exception ex)
        {
            MessageBox.Show("error fetching emails: " + ex.Message);
        }
        finally
        {
            if (ssl != null)
            {
                ssl.Close();
                ssl.Dispose();
            }
            if (tcpc != null)
            {
                tcpc.Close();
            }
        }
    }
Beispiel #30
0
        public void OAuth2LeggedModelContactsBatchInsertTest() {
            const int numberOfInserts = 10;
            Tracing.TraceMsg("Entering OAuth2LeggedModelContactsBatchInsertTest");

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

            ContactsTestSuite.DeleteAllContacts(rs);
            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));
                }
            }

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

            f = cr.GetContacts();
            foreach (Contact e in f.Entries) {
                list.Add(e);
            }

            Assert.AreEqual(numberOfInserts, inserted.Count);

            // now delete them again
            ContactsTestSuite.DeleteList(inserted, cr, new Uri(f.AtomFeed.Batch));
        }
Beispiel #31
0
        public List <ConciseContact> GetContactsWithBirthdaysToday()
        {
            RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord);

            // AutoPaging results in automatic paging in order to retrieve all contacts
            rs.AutoPaging = true;
            ContactsRequest cr = new ContactsRequest(rs);

            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));

            query.StartDate        = new DateTime(2000, 1, 1);
            query.NumberToRetrieve = int.MaxValue;
            //query.OrderBy =

            query.ModifiedSince = DateTime.Now.AddDays(-10000);

            List <ConciseContact> ccList = new List <ConciseContact>();
            DateTime today = DateTime.Now.Date;

            Feed <Contact> feed = cr.Get <Contact>(query);
            Contact        dbgC = null;

            foreach (Contact c in feed.Entries)
            {
                try
                {
                    dbgC = c;

                    if (string.IsNullOrEmpty(c.ContactEntry.Birthday))
                    {
                        continue;
                    }

                    DateTime birthday = DateTime.Parse(c.ContactEntry.Birthday);

                    if (birthday.Month != today.Month || birthday.Day != today.Day)
                    {
                        continue;
                    }

                    // Birthdays today found
                    ConciseContact cc = new ConciseContact();
                    cc.FirstName = c.Name.GivenName;
                    cc.LastName  = c.Name.FamilyName;

                    if (c.Organizations.Count > 0)
                    {
                        cc.Title = c.Organizations[0].Title;
                    }

                    //c.PrimaryPhonenumber
                    //c.PrimaryPhonenumber
                    //c.Phonenumbers[0]
                    if (c.Phonenumbers.Count > 0)
                    {
                        cc.PhoneNumber = c.Phonenumbers[0].Value;
                    }

                    ccList.Add(cc);

                    Console.WriteLine(c.Title);
                    Console.WriteLine("Name: " + c.Name.FullName);
                }
                catch (Exception ex)
                {
                    Logger.LogException(ex, dbgC.Name.GivenName + " " + dbgC.Name.FamilyName);
                }
            }

            return(ccList);
        }
        public void TestTheGoogleWay()
        {
            try {
                RequestSettings rs = new RequestSettings("GContactSync", GoogleContactDownloader.TestUser, GoogleContactDownloader.TestPass);
                ContactsRequest cr = new ContactsRequest(rs);

                Google.Contacts.Contact entry = new Google.Contacts.Contact();
                entry.Name = new Name();
                entry.Name.FullName = "John Doe";
                entry.Emails.Add(new EMail("*****@*****.**", ContactsRelationships.IsOther));
                Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));
                cr.Insert(feedUri, entry);
            }
            //catch (GDataRequestException ex) {
            //    throw ex;
            //}
            catch  (System.Exception ex) {
                throw ex;
            }
        }
        private void GetAllGoogleContacts(String access_code)
        {
            parameters.AccessCode = access_code;
            OAuthUtil.GetAccessToken(parameters);
            RequestSettings rs = new RequestSettings("ImportContacts", parameters);
            // AutoPaging results in automatic paging in order to retrieve all contacts
            rs.AutoPaging = true;
            ContactsRequest cr = new ContactsRequest(rs);

            Feed<Contact> f = cr.GetContacts();
            ProcessGoogleContacts(f);
        }
    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
    }
Beispiel #35
0
        private List <Friend> GetGmailContacts(int page, List <int> selectedIndexs)
        {
            int            pageSize = 10;
            List <Friend>  friends  = new List <Friend>();
            MembershipUser mu       = Membership.GetUser();
            RegisteredUser user     = registeredUserRepository.GetByMembershipId(Convert.ToInt32(mu.ProviderUserKey));

            if (Session["GMailToken"] == null)
            {
                String token = Request.QueryString["token"];
                Session["GMailToken"] = AuthSubUtil.exchangeForSessionToken(token, null).ToString();
            }

            GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cp", "testingFADE");
            RequestSettings        rs          = new RequestSettings("testingFADE", (String)Session["GMailToken"]);

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

            Feed <Contact> contacts = cr.GetContacts();
            int            i        = 1;

            if (page > 0)
            {
                foreach (Contact e in contacts.Entries)
                {
                    if (i < (page * pageSize) - 9)
                    {
                        i++;
                        continue;
                    }
                    if (i > (page * pageSize))
                    {
                        break;
                    }
                    if (e.PrimaryEmail == null)
                    {
                        continue;
                    }
                    Friend friend = new Friend();
                    friend.FirstName    = e.Title;
                    friend.EmailAddress = e.PrimaryEmail.Address;
                    friend.InvitedBy    = user;
                    friends.Add(friend);
                    i++;
                }
                ViewData["Pages"] = Common.Paging(contacts.TotalResults, page, pageSize, 10);
            }
            else if (selectedIndexs != null)
            {
                foreach (Contact e in contacts.Entries)
                {
                    if (!selectedIndexs.Exists(delegate(int record) { if (record == i)
                                                                      {
                                                                          return(true);
                                                                      }
                                                                      return(false); }))
                    {
                        i++;
                        continue;
                    }
                    Friend friend = new Friend();
                    friend.FirstName    = e.Title;
                    friend.EmailAddress = e.PrimaryEmail.Address;
                    friend.InvitedBy    = user;
                    friends.Add(friend);
                    i++;
                }
            }

            return(friends);
        }
        private void DeleteAllContacts()
        {

            RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord);
            rs.AutoPaging = true; 
            ContactsRequest cr = new ContactsRequest(rs);
            Feed<Contact> f = cr.GetContacts();

            List<Contact> list = new List<Contact>();
            int i=0; 

            foreach (Contact c in f.Entries)
            {
                c.BatchData = new GDataBatchEntryData();
                c.BatchData.Id = i.ToString();
                c.BatchData.Type = GDataBatchOperationType.delete;
                i++;
                list.Add(c);
            }

            cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.insert);

            f = cr.GetContacts();


            Assert.IsTrue(f.TotalResults == 0, "Feed should be emtpy now");
        }
Beispiel #37
0
        public IEnumerable <ChannelContact> GetContacts()
        {
            var cred = CredentialsProvider.GetCredentials();
            var rs   = new RequestSettings("Tabdeelee-Inbox2-1", cred.Claim, cred.Evidence)
            {
                AutoPaging = true
            };
            var cr = new ContactsRequest(rs);

            var feed = cr.GetContacts();

            foreach (Contact entry in feed.Entries)
            {
                ChannelContact contact = new ChannelContact();

                contact.Person.Name = entry.Title;
                contact.Profile.ChannelProfileKey = entry.Id;

                if (entry.Phonenumbers.Count > 0)
                {
                    var phone = entry.Phonenumbers.First();
                    contact.Profile.PhoneNr = phone.Value;
                }

                if (entry.PrimaryEmail != null)
                {
                    contact.Profile.SourceAddress = new SourceAddress(entry.PrimaryEmail.Address, contact.Person.Name);
                }

                try
                {
                    // Check for 404 with custom httpclient on photourl since regular HttpWebClient keeps throwing exceptions
                    //var token = cr.Service.QueryAuthenticationToken();
                    //var code = HttpStatusClient.GetStatusCode(entry.PhotoUri.ToString(),
                    //    new Dictionary<string, string> { { "Authorization", "GoogleLogin auth=" + token }});

                    //if (code.HasValue && code == 200)
                    //{
                    IGDataRequest request = cr.Service.RequestFactory.CreateRequest(GDataRequestType.Query, entry.PhotoUri);
                    request.Execute();

                    using (var avatarstream = request.GetResponseStream())
                    {
                        if (avatarstream != null)
                        {
                            ChannelAvatar avatar = new ChannelAvatar();

                            // Copy avatarstream to a new memorystream because the source
                            // stream does not support seek operations.
                            MemoryStream ms = new MemoryStream();
                            avatarstream.CopyTo(ms);

                            avatar.Url           = entry.PhotoUri.ToString();
                            avatar.ContentStream = ms;

                            contact.Profile.ChannelAvatar = avatar;
                        }
                    }
                    //}
                }
                catch (CaptchaRequiredException)
                {
                    // Since GMail will keep on raising CaptchaRequiredException, break out here
                    // todo let the user know in some way or another?
                    yield break;
                }
                catch (Exception)
                {
                }

                yield return(contact);
            }
        }
        //////////////////////////////////////////////////////////////////////
        /// <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");
            }
        }
 protected ContactAction(ContactsRequest request, Contact googleContact, string description)
 {
     Request = request;
     GoogleContact = googleContact;
     ChangeDescription = description;
 }
        /////////////////////////////////////////////////////////////////////////////



        //////////////////////////////////////////////////////////////////////
        /// <summary>runs an authentication test, inserts a new contact</summary> 
        //////////////////////////////////////////////////////////////////////
        [Test] public void ModelPhotoTest()
        {
            Tracing.TraceMsg("Entering ModelPhotoTest");

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

            ContactsRequest cr = new ContactsRequest(rs);

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

            Contact e = null;

            if (f != null)
            {
                Contact entry = new Contact();
                entry.AtomEntry = ObjectModelHelper.CreateContactEntry(1);
                entry.PrimaryEmail.Address = "*****@*****.**";
                e = cr.Insert(f, entry);
                
            }
            Assert.IsTrue(e!=null, "we should have a contact here");

            Stream s = cr.GetPhoto(e);

            Assert.IsTrue(s == null, "There should be no photo yet"); 


            using (FileStream fs = new FileStream(this.resourcePath + "contactphoto.jpg", System.IO.FileMode.Open))
            {
                cr.SetPhoto(e, fs); 
            }

            // now delete the guy, which requires us to reload him from the server first, as the photo change operation
            // changes the etag off the entry
            e = cr.Retrieve(e);
            cr.Delete(e);
        }
Beispiel #41
0
        /// <summary>
        /// Old mail process
        /// </summary>
        public async Task OldMailProcess(
            GmailService service,
            string userId,
            List <string> labels,
            long mailProcessParentId,
            long userMembershipId,
            UserCredential userCredential,
            MailProcessDates mailProcessDates,
            object contactList,
            UsersResource.MessagesResource.ListRequest request,
            Group group,
            ContactsRequest contactRequest,
            System.Diagnostics.Stopwatch watch,
            CancellationToken cancellationToken
            )
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            Message lastMailProcessed = new Message();

            try
            {
                request = service.Users.Messages.List(userId);
                //request.LabelIds = labels;
                if (mailProcessDates.OldLastProcessedMailDate != null)
                {
                    request.Q = "before:" + mailProcessDates.OldLastProcessedMailDate.Value.ToString("yyyy/MM/dd");
                }

                do
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    //Old mail process
                    ListMessagesResponse response = request.Execute(); //
                    request.PageToken = response.NextPageToken;
                    var batchrequest = new BatchRequest(service);
                    if (response.Messages != null)
                    {
                        foreach (Message message in response.Messages)
                        {
                            var req = service.Users.Messages.Get(userId, message.Id);
                            req.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Full;
                            batchrequest.Queue <Message>(req,
                                                         (content, error, i, messagesvalue) =>
                            {
                                //Lead411EmailParseResult Lead411EmailParseResult = MessageParser.Parse(content);
                                ////Create new contact
                                //if (Lead411EmailParseResult.SignatureBlockContactCardInfo != null)
                                //{
                                //    Operation.CreateContact(group, contactRequest, Lead411EmailParseResult, contactList);
                                //}
                                //lastMailProcessed = content;
                                //_noOfMailsProccessed++;
                                //if (_noOfMailsProccessed >= GeneralParameters.MaximumSingleRunIndexCount)
                                //{
                                //    _cts.Cancel(true);
                                //}
                                // Put your callback code here.
                            });
                            //cancellationToken.ThrowIfCancellationRequested();
                            //Message msg = await service.Users.Messages.Get(userId, message.Id).ExecuteAsync();
                        }
                        await batchrequest.ExecuteAsync(cancellationToken);//
                    }
                } while (!String.IsNullOrWhiteSpace(request.PageToken));
                if (string.IsNullOrWhiteSpace(request.PageToken))
                {
                    _iAccount.SaveMailProcessParentCompleted(userMembershipId);
                    watch.Stop();
                    _elapsedMs = watch.ElapsedMilliseconds;
                    DateTime lastMailDate;
                    if (lastMailProcessed.Payload != null)
                    {
                        lastMailDate = Convert.ToDateTime(lastMailProcessed.Payload.Headers.Where(payload => payload.Name == "Date").Select(payload => payload.Value).FirstOrDefault());
                    }
                }
            }
            catch (OperationCanceledException)
            {
                watch.Stop();
                _elapsedMs = watch.ElapsedMilliseconds;
                DateTime lastMailDate;
                if (lastMailProcessed.Payload != null)
                {
                    string   date = lastMailProcessed.Payload.Headers.Where(payload => payload.Name == "Date").Select(payload => payload.Value).FirstOrDefault();
                    DateTime newd;
                    if (date != null && DateTime.TryParse(date.Replace("(PDT)", ""), out newd))
                    {
                        lastMailDate = Convert.ToDateTime(newd);
                    }
                    else
                    {
                        if (mailProcessDates.OldLastProcessedMailDate != null)
                        {
                            lastMailDate = Convert.ToDateTime(mailProcessDates.OldLastProcessedMailDate);
                        }
                        else
                        {
                            lastMailDate = DateTime.UtcNow;
                        }
                    }
                }
            }
        }
        /////////////////////////////////////////////////////////////////////////////


        //////////////////////////////////////////////////////////////////////
        /// <summary>runs an authentication test, inserts a new contact</summary>
        //////////////////////////////////////////////////////////////////////
        [Test] public void ModelBatchContactsTest()
        {
            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);

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

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

            for (int i = 0; i < numberOfInserts; i++)
            {
                Contact entry = new Contact();
                entry.AtomEntry            = ObjectModelHelper.CreateContactEntry(i);
                entry.PrimaryEmail.Address = "joe" + i.ToString() + "@doe.com";
                GDataBatchEntryData g = new GDataBatchEntryData();
                g.Id            = i.ToString();
                g.Type          = GDataBatchOperationType.insert;
                entry.BatchData = g;
                list.Add(entry);
            }

            Feed <Contact> r = cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.Default);

            list.Clear();

            int iVerify = 0;

            foreach (Contact c in r.Entries)
            {
                // let's count and update them
                iVerify++;
                c.Name.FamilyName = "get a nother one";
                c.BatchData.Type  = GDataBatchOperationType.update;
                list.Add(c);
            }
            Assert.IsTrue(iVerify == numberOfInserts, "should have gotten 5 inserts");

            Feed <Contact> u = cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.Default);

            list.Clear();

            iVerify = 0;
            foreach (Contact c in u.Entries)
            {
                // let's count and update them
                iVerify++;
                c.BatchData.Type = GDataBatchOperationType.delete;
                list.Add(c);
            }
            Assert.IsTrue(iVerify == numberOfInserts, "should have gotten 5 updates");

            Feed <Contact> d = cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.Default);

            iVerify = 0;
            foreach (Contact c in d.Entries)
            {
                if (c.BatchData.Status.Code == 200)
                {
                    // let's count and update them
                    iVerify++;
                }
            }
            Assert.IsTrue(iVerify == numberOfInserts, "should have gotten 5 deletes");
        }
        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");
            }
        }
 public ContactActionDelete(ContactsRequest request, Contact googleContact)
     : base(request, googleContact, googleContact.ToString() + " will be deleted.")
 {
 }
Beispiel #45
0
 private IList <Group> GetAllContactGroups(ContactsRequest request)
 {
     request.Settings.AutoPaging = false;
     request.Settings.Maximum    = GoogleSyncSettings.DefaultMaxContactGroupCount;
     return(request.GetGroups().Entries.ToList());
 }