bool ShouldContinue(ABPeoplePickerNavigationController peoplePicker, ABPerson selectedPerson, int propertyId, int identifier)
        {
            RaiseEmailPicked(PersonFormatter.GetPickedEmail(selectedPerson, identifier));
            peoplePicker.DismissViewController(true, null);

            return(false);
        }
Example #2
0
        void ShowUnknownPersonViewController()
        {
            using (var contact = new ABPerson()) {
                using (var email = new ABMutableStringMultiValue()) {
                    bool didAdd = email.Add("*****@*****.**", ABLabel.Other);

                    if (didAdd)
                    {
                        try {
                            contact.SetEmails(email);

                            var upvc = new ABUnknownPersonViewController {
                                DisplayedPerson           = contact,
                                AllowsAddingToAddressBook = true,
                                AllowsActions             = true,
                                AlternateName             = "John Appleseed",
                                Title   = "John Appleseed",
                                Message = "Company, Inc"
                            };
                            upvc.PersonCreated        += HandlePersonCreated;
                            upvc.PerformDefaultAction += HandlePerformDefaultAction;

                            NavigationController.PushViewController(upvc, true);
                        } catch (Exception) {
                            var alert = UIAlertController.Create("Error", "Could not create unknown user.", UIAlertControllerStyle.Alert);
                            alert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Default, null));
                            PresentViewController(alert, true, null);
                        }
                    }
                }
            }
        }
        protected void BtnAddPhoneNumberTouchUpInside(object sender, EventArgs e)
        {
            // get a reference to the contact
            using (ABAddressBook addressBook = new ABAddressBook())
            {
                ABPerson contact = addressBook.GetPerson(contactID);

                // get the phones and copy them to a mutable set of multivalues (so we can edit)
                ABMutableMultiValue <string> phones = contact.GetPhones().ToMutableMultiValue();

                // add the phone number to the phones via the multivalue.Add method
                phones.Add(new NSString(txtPhoneLabel.Text), new NSString(txtPhoneNumber.Text));

                // attach the phones back to the contact
                contact.SetPhones(phones);

                // save the address book changes
                addressBook.Save();

                // show an alert, letting the user know the number addition was successful
                new UIAlertView("Alert", "Phone Number Added", null, "OK", null).Show();

                // update the page
                PopulatePage(contact);

                // we have to call reload to refresh the table because the action didn't originate
                // from the table.
                tblPhoneNumbers.ReloadData();
            }
        }
Example #4
0
 private static Item GetExistingContact(ABPerson selectedPerson)
 {
     /* RelatedNames doesn't work on a real device (iPad)
      * var list = selectedPerson.GetRelatedNames().ToList();
      * if (list.Any(name => name.Label == ZaplifyContactHeader))
      * {
      *  var zapField = list.Single(name => name.Label == ZaplifyContactHeader);
      *  Guid id = new Guid(zapField.Value);
      *  return App.ViewModel.Items.FirstOrDefault(i => i.ID == id);
      * }
      * return null;
      */
     if (selectedPerson == null || selectedPerson.Note == null)
     {
         return(null);
     }
     if (selectedPerson.Note.Contains(ZaplifyContactHeader))
     {
         var zapField = selectedPerson.Note;
         var idstring = GetContactID(zapField);
         if (idstring == null)
         {
             return(null);
         }
         Guid id = new Guid(idstring);
         return(App.ViewModel.Items.FirstOrDefault(i => i.ID == id));
     }
     return(null);
 }
Example #5
0
        public void ShowContact(NavigationPage page)
        {
            var key = DateTime.Now.ToString();
            var newPersonController = new ABNewPersonViewController();
            var person = new ABPerson();

            person.FirstName          = "John " + key;
            person.LastName           = "Doe" + key;
            newPersonController.Title = "This is a test";

            newPersonController.DisplayedPerson = person;

            UINavigationController nav = null;

            foreach (var vc in UIApplication.SharedApplication.Windows[0].RootViewController.ChildViewControllers)
            {
                if (vc is UINavigationController)
                {
                    nav = (UINavigationController)vc;
                }
            }

            newPersonController.NewPersonComplete += (object sender, ABNewPersonCompleteEventArgs e) =>
            {
                nav.DismissModalViewController(true);
            };


            nav.PresentModalViewController(new UINavigationController(newPersonController), true);
        }
Example #6
0
        internal static ABRecord FromHandle(IntPtr handle, ABAddressBook addressbook, bool owns = true)
        {
            if (handle == IntPtr.Zero)
            {
                throw new ArgumentNullException("handle");
            }
            // TODO: does ABGroupCopyArrayOfAllMembers() have Create or Get
            // semantics for the array elements?
            var      type = ABRecordGetRecordType(handle);
            ABRecord rec;

            switch (type)
            {
            case ABRecordType.Person:
                rec = new ABPerson(handle, owns);
                break;

            case ABRecordType.Group:
                rec = new ABGroup(handle, owns);
                break;

            case ABRecordType.Source:
                rec = new ABSource(handle, owns);
                break;

            default:
                throw new NotSupportedException("Could not determine record type.");
            }

            rec.AddressBook = addressbook;
            return(rec);
        }
        // Called when a phone number is swiped for deletion. Illustrates how to delete a multivalue property
        protected void DeletePhoneNumber(int phoneNumberID)
        {
            using (ABAddressBook addressBook = new ABAddressBook()) {
                ABPerson contact = addressBook.GetPerson(contactID);

                // get the phones and copy them to a mutable set of multivalues (so we can edit)
                ABMutableMultiValue <string> phones = contact.GetPhones().ToMutableMultiValue();

                // loop backwards and delete the phone number
                for (int i = phones.Count - 1; i >= 0; i--)
                {
                    if (phones [i].Identifier == phoneNumberID)
                    {
                        phones.RemoveAt(i);
                    }
                }

                // attach the phones back to the contact
                contact.SetPhones(phones);

                // save the changes
                addressBook.Save();

                // show an alert, letting the user know the number deletion was successful
                new UIAlertView("Alert", "Phone Number Deleted", null, "OK", null).Show();

                // repopulate the page
                PopulatePage(contact);
            }
        }
        //create a meeting
        public void createMeeting(ABPerson target)
        {
            if (target == null)
            {
                MessageHelper.showErrorMesage("No abPerson target createMeeting top");
            }
            else
            if (target.GetPhones().Count > 1)
            {
                List <string> trackerNumbers = new List <string>();

                foreach (var number in target.GetPhones())
                {
                    trackerNumbers.Add(number.Value);
                }

                //ServiceHelper.instance.checkPhoneNumbers(trackerNumbers,delegate(Object sender, CheckNumbersCompletedEventArgs e){this.numbersChecked(sender,e);}); //get _trackNumber
            }
            else if (target.GetPhones().Count == 1)
            {
                var targetPhones = target.GetPhones();
                var phoneArray   = targetPhones.GetValues();

                var targetNumber = MessageHelper.cleanString(phoneArray[0]);

                ServiceHelper.instance.createMeeting(targetNumber, ServiceHelper.instance.localPhoneNumber, meetingRequested);
            }
            else
            {
                MessageHelper.showCouldNotCreateMeeting();
            }
        }
Example #9
0
        public override void ViewWillAppear(bool animated)
        {
            ABPerson      person         = null;
            List <string> tempRecipients = new List <string>();

            for (int i = 0; i < BatchSize; i++)
            {
                if (LeftRecipients.Count == 0)
                {
                    break;
                }

                person = LeftRecipients.Pop();
                string rec = person.GetPhones().First(x => x.Label.ToString().ToLower().Contains("mobile")).Value;
                tempRecipients.Add(rec);
            }

            this.Recipients = tempRecipients.ToArray();
#if FULL
            // Replace magic expression
            if (this.MagicExpressionEnabled && person != null)
            {
                this.Body = this.Body.Replace(Settings.MagicExpressionFirstName, person.FirstName)
                            .Replace(Settings.MagicExpressionLastName, person.LastName);
            }
#endif
            base.ViewWillAppear(animated);
        }
Example #10
0
        public Contact Load(string id)
        {
            if (String.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentNullException("id");
            }

            CheckStatus();

            int rowId;

            if (!Int32.TryParse(id, out rowId))
            {
                throw new ArgumentException("Not a valid contact ID", "id");
            }

            ABPerson person = this.addressBook.GetPerson(rowId);

            if (person == null)
            {
                return(null);
            }

            return(ContactHelper.GetContact(person));
        }
Example #11
0
        private void CadastraContatos(List <Contato> contatos)
        {
            foreach (Contato contatoArquivo in contatos)
            {
                var novoContato = new ABPerson();
                novoContato.FirstName = contatoArquivo.NomeFuncionario;
                novoContato.LastName  = contatoArquivo.SobrenomeFuncionario;

                var fones = new ABMutableStringMultiValue();

                var emails = new ABMutableStringMultiValue();

                foreach (Telefone telefone in contatoArquivo.Telefones)
                {
                    fones.Add(telefone.DDD + telefone.Numero, ABPersonPhoneLabel.Main);
                }
                novoContato.SetPhones(fones);

                foreach (String email in contatoArquivo.Emails)
                {
                    emails.Add(email, ABPersonPhoneLabel.Main);
                }
                novoContato.SetEmails(emails);

                agenda.Add(novoContato);
                agenda.Save();
            }
        }
Example #12
0
        public static List <Element> GetABPersonElementFrom(SmsGroupObject sms, bool returnOnlySelected = false)
        {
            List <Element> personElements = new List <Element>();

            foreach (var a in Contacts.AddressBook.Where(x => x.Type == ABRecordType.Person))
            {
                ABPerson person = a as ABPerson;

                foreach (var phone in person.GetPhones())
                {
                    if (phone.Label.ToString().ToLower().Contains("mobile"))
                    {
                        bool isInGroup = false;
                        try{
                            isInGroup = (sms != null && sms.Persons.Any(x => x.Id == a.Id));
                        }catch (Exception ex)
                        {
                            //Console.WriteLine(ex);
                        }

                        if (returnOnlySelected && !isInGroup)
                        {
                            break;
                        }
                        ABPersonElement el = new ABPersonElement(phone.Value, isInGroup, person);
                        personElements.Add(el);
                    }
                }
            }

            return(personElements.OrderBy(x => ((ABPersonElement)x).Person.FirstName).OrderByDescending(x => ((ABPersonElement)x).IsChecked).ToList <Element>());
        }
Example #13
0
        /*public static async Task<bool> SendSMS(string number, string message, string name,
         *          string ConfirmOrBOM, bool AutoCall = false, string TodayOrTomorrow = null)
         * {
         *      //var notifier = new iOSReminderService();
         *      try
         *      {
         *              var vc = UIApplication.SharedApplication.KeyWindow.RootViewController;
         *
         *              while (vc.PresentedViewController != null)
         *              {
         *                      vc = vc.PresentedViewController;
         *              }
         *              if (MFMessageComposeViewController.CanSendText)
         *              {
         *                      Console.WriteLine("SMS available");
         *
         *                      var messageController =
         *                              new MessageComposeController();
         *
         *                      messageController.Finished +=
         *                              //async
         *                              (sender, e) =>
         *                      {
         *                              Console.WriteLine("sms sent: {0}", messageController.Body);
         *                              AutoCaller.Calling = false;
         *                              if (string.Equals(ConfirmOrBOM, Values.BOM))
         *                              {
         *                                      CalendarService.IsConfirmingAppointments = false;
         *
         *                                      //set notification time to confirm appointment
         *                              }
         *                              else {
         *                                      CalendarService.IsConfirmingAppointments = true;
         *
         *                              }
         *                              messageController.DismissViewController(DeviceUtil.CanAnimate, null);
         *                      };
         *
         *                      messageController.Body = message;
         *                      messageController.Recipients = new string[] { number };
         *                      vc.PresentModalViewController(messageController, false);
         *              }
         *              else {
         *                      Console.WriteLine("Can't send text");
         *              }
         *              return true;
         *      }
         *      catch (Exception e)
         *      {
         *              Console.WriteLine("PhoneContacts.SendSMS() error: {0}", e.Message);
         *              if (string.Equals(ConfirmOrBOM, Values.BOM))
         *              {
         *                      //notifier.Remind(DateTime.Now.AddMilliseconds(0), "BOM Confirmation failed sending to " + name, "Text Confirmation Failed");
         *              }
         *              else {
         *
         *                      if (string.Equals(TodayOrTomorrow, Values.TODAY))
         *                      {
         *                              //notifier.Remind(DateTime.Now.AddMilliseconds(0), "SMS failed to send", "Couldn't confirm " + name + " for later's meeting");
         *                      }
         *                      else {
         *                              //notifier.Remind(DateTime.Now.AddMilliseconds(0), "SMS failed to send", "Couldn't confirm " + name + " for tomorrow's meeting");
         *                      }
         *              }
         *      }
         *      return false;
         * }*/

        /*string SaveDefaultImage(ContactData contact){
         *      string filename = System.IO.Path.Combine (Environment.GetFolderPath
         *              (Environment.SpecialFolder.Personal),
         *              "placeholder-contact-male.png");
         *
         *      Console.WriteLine("Assigned default image to {0} {1}. Saving it as {1}",
         *              contact.FirstName, contact.LastName, filename);
         *
         *      return filename;
         * }
         * string SaveImageThenGetPath(ContactData contact, NSData image, ABPersonImageFormat format){
         *      string filename = "";
         *
         *      try{
         *              if(format == ABPersonImageFormat.Thumbnail){
         *                      filename = System.IO.Path.Combine (Environment.GetFolderPath
         *                              (Environment.SpecialFolder.Personal),
         *                              string.Format("{0}.jpg", contact.ID));
         *              }else{
         *                      filename = System.IO.Path.Combine (Environment.GetFolderPath
         *                              (Environment.SpecialFolder.Personal),
         *                              string.Format("{0}-large.jpg", contact.ID));
         *              }
         *
         *              image.Save (filename, true);
         *
         *              Console.WriteLine("Found {0} {1}'s image. Saving it as {2}",
         *                      contact.FirstName, contact.LastName, filename);
         *
         *              return filename;
         *      }catch(Exception e){
         *              Console.WriteLine ("Error in SaveImageThenGetPath(): {0}", e.Message);
         *      }
         *      return string.Empty;
         * }*/
        public bool SaveContactToDevice(string firstName, string lastName, string phone, string aff)
        {
            try {
                ABAddressBook ab = new ABAddressBook();
                ABPerson      p  = new ABPerson();

                p.FirstName    = firstName;
                p.LastName     = lastName;
                p.Organization = aff;
                //p.GetImage(ABPersonImageFormat.Thumbnail).

                ABMutableMultiValue <string> phones = new ABMutableStringMultiValue();
                phones.Add(phone, ABPersonPhoneLabel.Mobile);

                p.SetPhones(phones);

                ab.Add(p);
                ab.Save();

                UserDialogs.Instance.ShowSuccess("Contact saved: " + firstName + " " + lastName, 2000);

                return(true);
            } catch (Exception e) {
                System.Console.WriteLine("[iOS.PhoneContacts] Couldn't save contact: {0} {1}, {2}", firstName, lastName, e.Message);
                UserDialogs.Instance.ShowError("Failed to save contact: " + firstName + " " + lastName + ". Pls try again.", 2000);
            }
            return(false);
        }
Example #14
0
        private AddressBookEntry ConvertFromAddressBook(ABPerson from)
        {
            AddressBookEntry entry = new AddressBookEntry();

            entry.ExternalContactId     = from.Id.ToString();
            entry.ExternalContactSource = Constants.ExternalContactSource;
            entry.IsCompany             = this.IsCompany(from);
            entry.FirstName             = from.FirstName;
            entry.LastName    = from.LastName;
            entry.CompanyName = from.Organization;
            entry.ExternalModificationDate = this.ToDateTime(from.ModificationDate);

            if (from.HasImage)
            {
                NSData imageData = from.GetImage(ABPersonImageFormat.OriginalSize);
                byte[] image     = new byte[imageData.Length];

                Marshal.Copy(imageData.Bytes, image, 0, Convert.ToInt32(imageData.Length));

                entry.Image = image;
            }

            List <KeyValuePair <string, Address> > addresses = new List <KeyValuePair <string, Address> >();

            foreach (ABMultiValueEntry <PersonAddress> address in from.GetAllAddresses())
            {
                Address newAddress = new Address();

                newAddress.Street     = address.Value.Street;
                newAddress.City       = address.Value.City;
                newAddress.Province   = address.Value.State;
                newAddress.PostalCode = address.Value.Zip;
                newAddress.Country    = address.Value.Country;

                addresses.Add(new KeyValuePair <string, Address>(this.NormalizeLabel(address.Label), newAddress));
            }

            entry.Addresses = addresses;

            List <KeyValuePair <string, string> > emailAddresses = new List <KeyValuePair <string, string> >();

            foreach (ABMultiValueEntry <string> emailAddress in from.GetEmails())
            {
                emailAddresses.Add(new KeyValuePair <string, string>(this.NormalizeLabel(emailAddress.Label), emailAddress.Value));
            }

            entry.EmailAddresses = emailAddresses;

            List <KeyValuePair <string, string> > phoneNumbers = new List <KeyValuePair <string, string> >();

            foreach (ABMultiValueEntry <string> phoneNumber in from.GetPhones())
            {
                phoneNumbers.Add(new KeyValuePair <string, string>(this.NormalizeLabel(phoneNumber.Label), phoneNumber.Value));
            }

            entry.PhoneNumbers = phoneNumbers;

            return(entry);
        }
Example #15
0
        private static Item CreateNewContact(ABPerson selectedPerson)
        {
            Guid id = Guid.NewGuid();
            // get the default list for contacts
            Guid         folderID;
            Guid?        parentID    = null;
            ClientEntity defaultList = App.ViewModel.GetDefaultList(SystemItemTypes.Contact);

            if (defaultList == null)
            {
                TraceHelper.AddMessage("CreateNewContact: error - could not find default contact list");
                return(null);
            }
            if (defaultList is Item)
            {
                folderID = ((Item)defaultList).FolderID;
                parentID = defaultList.ID;
            }
            else
            {
                folderID = defaultList.ID;
                parentID = null;
            }

            Item newContact = new Item()
            {
                ID          = id,
                Name        = selectedPerson.ToString(),
                FolderID    = folderID,
                ParentID    = parentID,
                ItemTypeID  = SystemItemTypes.Contact,
                FieldValues = new ObservableCollection <FieldValue>()
            };

            // add the new contact locally
            Folder folder = App.ViewModel.Folders.FirstOrDefault(f => f.ID == folderID);

            if (folder == null)
            {
                TraceHelper.AddMessage("CreateNewContact: error - could not find the folder for this item");
                return(null);
            }
            folder.Items.Add(newContact);

            // save the current state of the folder
            StorageHelper.WriteFolder(folder);

            // enqueue the Web Request Record
            RequestQueue.EnqueueRequestRecord(RequestQueue.UserQueue,
                                              new RequestQueue.RequestRecord()
            {
                ReqType = RequestQueue.RequestRecord.RequestType.Insert,
                Body    = newContact,
            });

            return(newContact);
        }
        public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            _controller.View.AddSubview(_loading);
            _loading.StartAnimating();

            ABPerson person = _contacts[indexPath.Row];

            //create meeting
            createMeeting(person);
        }
        public override bool ShouldPerformDefaultActionForPerson(ABUnknownPersonViewController personViewController, IntPtr personId, int propertyId, int identifier)
        {
            ABPerson person = personId == IntPtr.Zero ? null : new ABPerson(personId, personViewController.AddressBook);
#endif
            ABPersonProperty property = ABPersonPropertyId.ToPersonProperty(propertyId);
            int?id = identifier == ABRecord.InvalidPropertyId ? null : (int?)identifier;

            var e = new ABPersonViewPerformDefaultActionEventArgs(person, property, id);
            personViewController.OnPerformDefaultAction(e);
            return(e.ShouldPerformDefaultAction);
        }
 public BatchMFMessageComposeViewController(MainScreenGroup parent, ABPerson[] recipients, string body, int batchSize, bool magicExpressionEnabled)
     : base()
 {
     this.Parent = parent;
     IndexSent = 0;
     this.Body = body;
     this.BatchSize = batchSize;
     LeftRecipients = new Stack<ABPerson>(recipients);
     this.MessageComposeDelegate = new CustomMessageComposeDelegate();
     this.MagicExpressionEnabled = magicExpressionEnabled;
 }
Example #19
0
        public override bool ShouldContinue(ABPeoplePickerNavigationController peoplePicker, IntPtr selectedPerson, int propertyId, int identifier)
        {
            ABPerson         person   = selectedPerson == IntPtr.Zero ? null : new ABPerson(selectedPerson, peoplePicker.AddressBook);
            ABPersonProperty property = ABPersonPropertyId.ToPersonProperty(propertyId);
            int?id = identifier == ABRecord.InvalidPropertyId ? null : (int?)identifier;

            var e = new ABPeoplePickerPerformActionEventArgs(person, property, id);

            peoplePicker.OnPerformAction(e);
            return(e.Continue);
        }
Example #20
0
        /// <summary>
        /// Processes the contact - creates a new contact if one doesn't exist, or refreshes the contact
        /// if it's already in the database
        /// </summary>
        /// <returns>
        /// A new ItemRef Item (already added to the Folder and queued up to the server) which points to the new or existing Contact Item
        /// </returns>
        /// <param name='selectedPerson'>
        /// Selected person from the people picker
        /// </param>
        public static Item ProcessContact(ABPerson selectedPerson)
        {
            var contact = GetExistingContact(selectedPerson);
            if (contact == null)
                contact = CreateNewContact(selectedPerson);

            // add the contact info from the phone address book to the new contact
            AddContactInfo(selectedPerson, contact);

            return contact;
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			Title = "Address Book Controllers";

			// displays the contact picker controller when the choose contact button is clicked
			btnChooseContact.TouchUpInside += (s, e) => {
				// create the picker control
				addressBookPicker = new ABPeoplePickerNavigationController();

				// in this case, we can call present modal view controller from the nav controller,
				// but we could have just as well called PresentModalViewController(...)
				NavigationController.PresentModalViewController(addressBookPicker, true);

				// when cancel is clicked, dismiss the controller
				// HACK: NavigationController.DismissModalViewControllerAnimated to NavigationController.DismissModalViewController
				addressBookPicker.Cancelled += (sender, eventArgs) => { NavigationController.DismissModalViewController(true); };

				// when a contact is chosen, populate the page with details and dismiss the controller
				addressBookPicker.SelectPerson2 += (sender, args) => {
					selectedPerson = args.Person;
					lblFirstName.Text = selectedPerson.FirstName;
					lblLastName.Text = selectedPerson.LastName;
					// HACK: NavigationController.DismissModalViewControllerAnimated to NavigationController.DismissModalViewController
					NavigationController.DismissModalViewController(true);
				};
			};

			// shows the view/edit contact controller when the button is clicked
			btnViewSelectedContact.TouchUpInside += (s, e) => {

				// if a contact hasn't been selected, show an alert and return out
				if(selectedPerson == null)
				{
					new UIAlertView ("Alert", "You must select a contact first.", null, "OK", null).Show ();
					return;
				}

				// instantiate a new controller
				addressBookViewPerson = new ABPersonViewController ();

				// set the contact to display
				addressBookViewPerson.DisplayedPerson = selectedPerson;

				// allow editing
				addressBookViewPerson.AllowsEditing = true;

				// push the controller onto the nav stack. the view/edit controller requires a nav
				// controller and handles it's own dismissal
				NavigationController.PushViewController (addressBookViewPerson, true);
			};
		}
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            Title = "Address Book Controllers";

            // displays the contact picker controller when the choose contact button is clicked
            btnChooseContact.TouchUpInside += (s, e) => {
                // create the picker control
                addressBookPicker = new ABPeoplePickerNavigationController();

                // in this case, we can call present modal view controller from the nav controller,
                // but we could have just as well called PresentModalViewController(...)
                NavigationController.PresentModalViewController(addressBookPicker, true);

                // when cancel is clicked, dismiss the controller
                // HACK: NavigationController.DismissModalViewControllerAnimated to NavigationController.DismissModalViewController
                addressBookPicker.Cancelled += (sender, eventArgs) => { NavigationController.DismissModalViewController(true); };

                // when a contact is chosen, populate the page with details and dismiss the controller
                addressBookPicker.SelectPerson += (object sender, ABPeoplePickerSelectPersonEventArgs args) => {
                    selectedPerson    = args.Person;
                    lblFirstName.Text = selectedPerson.FirstName;
                    lblLastName.Text  = selectedPerson.LastName;
                    // HACK: NavigationController.DismissModalViewControllerAnimated to NavigationController.DismissModalViewController
                    NavigationController.DismissModalViewController(true);
                };
            };

            // shows the view/edit contact controller when the button is clicked
            btnViewSelectedContact.TouchUpInside += (s, e) => {
                // if a contact hasn't been selected, show an alert and return out
                if (selectedPerson == null)
                {
                    new UIAlertView("Alert", "You must select a contact first.", null, "OK", null).Show();
                    return;
                }

                // instantiate a new controller
                addressBookViewPerson = new ABPersonViewController();

                // set the contact to display
                addressBookViewPerson.DisplayedPerson = selectedPerson;

                // allow editing
                addressBookViewPerson.AllowsEditing = true;

                // push the controller onto the nav stack. the view/edit controller requires a nav
                // controller and handles it's own dismissal
                NavigationController.PushViewController(addressBookViewPerson, true);
            };
        }
Example #23
0
        /// <summary>
        /// Processes the contact - creates a new contact if one doesn't exist, or refreshes the contact
        /// if it's already in the database
        /// </summary>
        /// <returns>
        /// A new ItemRef Item (already added to the Folder and queued up to the server) which points to the new or existing Contact Item
        /// </returns>
        /// <param name='selectedPerson'>
        /// Selected person from the people picker
        /// </param>
        public static Item ProcessContact(ABPerson selectedPerson)
        {
            var contact = GetExistingContact(selectedPerson);

            if (contact == null)
            {
                contact = CreateNewContact(selectedPerson);
            }

            // add the contact info from the phone address book to the new contact
            AddContactInfo(selectedPerson, contact);

            return(contact);
        }
		public static string GetPickedEmail(ABPerson person, int? identifier = null)
		{
			string emailAddress = "no email address";
			using (ABMultiValue<string> emails = person.GetEmails ()) {
				bool emailExists = emails != null && emails.Count > 0;

				if (emailExists) {
					nint index = identifier.HasValue ? emails.GetIndexForIdentifier (identifier.Value) : 0;
					emailAddress = emails [index].Value;
				}
			}

			return string.Format ("Picked {0}", emailAddress);
		}
Example #25
0
        protected void BtnSaveChangesTouchUpInside(object sender, EventArgs e)
        {
            using (ABAddressBook addressBook = new ABAddressBook()) {
                ABPerson contact = addressBook.GetPerson(contactID);

                if (contact != null)
                {
                    // save contact name information
                    contact.FirstName = txtFirstName.Text;
                    contact.LastName  = txtLastName.Text;

                    // get the phones and copy them to a mutable set of multivalues (so we can edit)
                    ABMutableMultiValue <string> phones = contact.GetPhones().ToMutableMultiValue();

                    // remove all phones data
                    // HACK: Cast nint to int
                    for (int i = (int)phones.Count - 1; i >= 0; i--)
                    {
                        phones.RemoveAt(i);
                    }

                    // add the phone number to the phones from the table data source
                    for (int i = 0; i < PhoneNumberTableSource.labels.Count; i++)
                    {
                        phones.Add(new NSString(PhoneNumberTableSource.numbers [i]), new NSString(PhoneNumberTableSource.labels [i]));
                    }

                    // attach the phones back to the contact
                    contact.SetPhones(phones);

                    // save the address book changes
                    addressBook.Save();

                    // show an alert, letting the user know information saved successfully
                    new UIAlertView("Alert", "Contact Information Saved!", null, "OK", null).Show();

                    // update the page
                    PopulatePage(contact);

                    // we have to call reload to refresh the table because the action didn't originate
                    // from the table.
                    tblPhoneNumbers.ReloadData();
                }
                else
                {
                    new UIAlertView("Alert", "Please select a contact using the top right button", null, "OK", null).Show();
                }
            }
        }
        protected void PopulatePage(ABPerson contact)
        {
            // save the ID of our person
            contactID = contact.Id;

            // set the data on the page
            txtFirstName.Text      = contact.FirstName;
            txtLastName.Text       = contact.LastName;
            tableDataSource        = new AddressBookScreen.PhoneNumberTableSource(contact.GetPhones());
            tblPhoneNumbers.Source = tableDataSource;

            // wire up our delete clicked handler
            tableDataSource.DeleteClicked +=
                (object sender, PhoneNumberTableSource.PhoneNumberClickedEventArgs e) => { DeletePhoneNumber(e.PhoneNumberID); };
        }
Example #27
0
    private void addNewContact()
    {
        ABAddressBook addressBook = ABAddressBook.Create();

        ABRecord person = ABPerson.Create();

        person.SetValue(ABPerson.kABPersonFirstNameProperty, CFType.FromObject("vitapoly"), null);
        person.SetValue(ABPerson.kABPersonBirthdayProperty, CFType.FromObject(new DateTime(2000, 1, 1)), null);

        addressBook.AddRecord(person, null);

        addressBook.Save(null);

        Log("Added vitapoly to address book.");
    }
        bool ShouldContinue(ABPeoplePickerNavigationController peoplePicker, ABPerson selectedPerson)
        {
            bool shouldcontinue = false;

            using (ABMultiValue <string> emails = selectedPerson.GetEmails())
                shouldcontinue = emails.Count == 1;

            if (!shouldcontinue)
            {
                peoplePicker.DismissViewController(true, null);
                RaiseEmailPicked(PersonFormatter.GetPickedEmail(selectedPerson));
            }

            return(shouldcontinue);
        }
Example #29
0
        public static string GetPickedEmail(ABPerson person, int?identifier = null)
        {
            string emailAddress = "no email address";

            using (ABMultiValue <string> emails = person.GetEmails()) {
                bool emailExists = emails != null && emails.Count > 0;

                if (emailExists)
                {
                    nint index = identifier.HasValue ? emails.GetIndexForIdentifier(identifier.Value) : 0;
                    emailAddress = emails [index].Value;
                }
            }

            return(string.Format("Picked {0}", emailAddress));
        }
Example #30
0
        private bool IsCompany(ABPerson person)
        {
            if (person.PersonKind == ABPersonKind.Organization)
            {
                return(true);
            }

            if (!string.IsNullOrWhiteSpace(person.Organization))
            {
                return
                    (string.IsNullOrWhiteSpace(person.FirstName) &&
                     string.IsNullOrWhiteSpace(person.LastName));
            }

            return(false);
        }
Example #31
0
        string GetPropertyValue(ABPerson person, ABPersonProperty property, int?identifier)
        {
            switch (property)
            {
            case ABPersonProperty.Birthday:
                return(person.Birthday.ToString());

            case ABPersonProperty.Email:
                return(GetEmail(person, identifier.Value));

            case ABPersonProperty.Phone:
                return(GetPhone(person, identifier.Value));

            default:
                throw new NotImplementedException();
            }
        }
Example #32
0
        private static bool AddPersonToGroup(string groupname, ABPerson p)
        {
            if (!Groups.ContainsKey(groupname))
            {
                Groups.Add(groupname, new SmsGroupObject()
                {
                    Name = groupname
                });
            }

            if (!Groups[groupname].Persons.Any(x => x.Id == p.Id))
            {
                Groups[groupname].Persons.Add(p);
                return(true);
            }

            return(false);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            Title = "How to Create a Contact";

            View.BackgroundColor = UIColor.White;

            _createContact                  = UIButton.FromType(UIButtonType.RoundedRect);
            _createContact.Frame            = new CGRect(10, 60, 300, 50);
            _createContact.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
            _createContact.SetTitle("Create a Contact", UIControlState.Normal);
            _contactName = new UILabel {
                Frame = new CGRect(10, 120, 300, 50)
            };
            _contactName.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;

            View.AddSubviews(_createContact, _contactName);

            _newPersonController = new ABNewPersonViewController();

            _createContact.TouchUpInside += (sender, e) => {
                var person = new ABPerson();
                person.FirstName = "John";
                person.LastName  = "Doe";

                _newPersonController.DisplayedPerson = person;

                NavigationController.PushViewController(_newPersonController, true);
            };

            _newPersonController.NewPersonComplete += (object sender, ABNewPersonCompleteEventArgs e) => {
                if (e.Completed)
                {
                    _contactName.Text = String.Format("new contact: {0} {1}", e.Person.FirstName, e.Person.LastName);
                }
                else
                {
                    _contactName.Text = "cancelled";
                }

                NavigationController.PopViewController(true);
            };
        }
Example #34
0
        public void BookChanged(object sender, ExternalChangeEventArgs e)
        {
            List <int> changes = new List <int> ();

            DateTime dt = new DateTime(2014, 12, 9);

            foreach (ABRecord rec in e.AddressBook)
            {
                ABPerson per = rec as ABPerson;

                if (per != null)
                {
                    if (per.CreationDate > dt)
                    {
                        changes.Add(per.Id);
                    }
                }
            }
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            Title = "How to Create a Contact";

            View.BackgroundColor = UIColor.White;

            _createContact = UIButton.FromType (UIButtonType.RoundedRect);
            _createContact.Frame = new CGRect (10, 60, 300, 50);
            _createContact.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
            _createContact.SetTitle ("Create a Contact", UIControlState.Normal);
            _contactName = new UILabel{Frame = new CGRect (10, 120, 300, 50)};
            _contactName.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;

            View.AddSubviews (_createContact, _contactName);

            _newPersonController = new ABNewPersonViewController ();

            _createContact.TouchUpInside += (sender, e) => {

                var person = new ABPerson ();
                person.FirstName = "John";
                person.LastName = "Doe";

                _newPersonController.DisplayedPerson = person;

                NavigationController.PushViewController (_newPersonController, true);
            };

            _newPersonController.NewPersonComplete += (object sender, ABNewPersonCompleteEventArgs e) => {

                if (e.Completed) {
                    _contactName.Text = String.Format ("new contact: {0} {1}", e.Person.FirstName, e.Person.LastName);
                } else {
                    _contactName.Text = "cancelled";
                }

                NavigationController.PopViewController (true);
            };
        }
Example #36
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="person">
        /// A <see cref="ABPerson"/>
        /// </param>
        /// <returns>
        /// A <see cref="System.String[]"/>
        /// </returns>
        private string[] GetContactWebsites(ABPerson person)
        {
            List<string> contactUrlList = new List<string>();

            if(person != null) {
                ABMultiValue<string> urls = person.GetUrls();
                if(urls!=null) {

                    IEnumerator enumerator = urls.GetEnumerator();
                    while(enumerator.MoveNext()){
                        object currentUrll = enumerator.Current;
                        // string label = ((ABMultiValueEntry<string>)currentUrll).Label;
                        string url = ((ABMultiValueEntry<string>)currentUrll).Value;
                        contactUrlList.Add(url);
                    }
                }
            }
            return contactUrlList.ToArray();
        }
Example #37
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="addressBook">
        /// A <see cref="ABAddressBook"/>
        /// </param>
        /// <param name="requestedGroupName">
        /// A <see cref="System.String"/>
        /// </param>
        /// <returns>
        /// A <see cref="ABPerson[]"/>
        /// </returns>
        private ABPerson[] GetContactsByGroup(ABAddressBook addressBook, string requestedGroupName)
        {
            ABPerson [] people = new ABPerson[0];

            ABGroup[] groups = addressBook.GetGroups();

            foreach(ABGroup abGroup in groups) {
                if(abGroup.Name == requestedGroupName) {
                    ABRecord[] records = abGroup.GetMembers(DEFAULT_CONTACTS_LIST_SORT); //get list sorted by FirstName (default)
                    people = new ABPerson[records.Length];
                    for(int i=0; i< records.Length; i++) {
                        ABRecord record = records[i];
                        ABPerson person = addressBook.GetPerson(record.Id);
                        if(person!=null) {
                            people[i] = person;
                        }
                    }
                    break;
                }
            }
            return people;
        }
		public static string GetPickedName(ABPerson person)
		{
			string contactName = person.ToString ();
			return string.Format ("Picked {0}", contactName ?? "No Name");
		}
        private void PopulateContacts()
        {
            var addressBook = new ABAddressBook();
            var people = addressBook.GetPeople();

            // clear address book
            foreach(var person in people)
            {
                addressBook.Remove(person);
            }

            addressBook.Save();

            var random = new Random();
            // create 200 random contacts
            foreach (var name in _names)
            {
              // create an ABRecordRef
                var record = new ABPerson();
                record.FirstName = name[0];
                record.LastName = name[1];
                var phones = new ABMutableStringMultiValue();
                phones.Add(GeneratePhone(random).ToString(), ABPersonPhoneLabel.Mobile);

                if(random.Next() % 2 == 1) {
                    phones.Add(GeneratePhone(random).ToString(), ABPersonPhoneLabel.Main);
                }

                record.SetPhones(phones);

                addressBook.Add(record);
            }
            addressBook.Save();
        }
Example #40
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="person">
        /// A <see cref="ABPerson"/>
        /// </param>
        /// <returns>
        /// A <see cref="ContactEmail[]"/>
        /// </returns>
        private ContactEmail[] GetContactEmails(ABPerson person)
        {
            List<ContactEmail> contactEmailList = new List<ContactEmail>();

            if(person != null) {
                ABMultiValue<string> emails = person.GetEmails();
                if(emails!=null) {

                    IEnumerator enumerator = emails.GetEnumerator();
                    while(enumerator.MoveNext()){
                        object currentEmail = enumerator.Current;
                        string label = ((ABMultiValueEntry<string>)currentEmail).Label;
                        string email = ((ABMultiValueEntry<string>)currentEmail).Value;

                        ContactEmail contactEmail = new ContactEmail();
                        contactEmail.Address = email;

                        // Following data not provided.
                        //contactEmail.CommonName =
                        //contactEmail.Firstname =
                        //contactEmail.IsPrimary =
                        //contactEmail.Surname =

                        if(label == ABLabel.Home) {
                            contactEmail.Type = DispositionType.HomeOffice;
                        } else if(label == ABLabel.Work) {
                            contactEmail.Type = DispositionType.Work;
                        } else {
                            contactEmail.Type = DispositionType.Other;
                        }

                        contactEmailList.Add(contactEmail);
                    }
                }
            }
            return contactEmailList.ToArray();
        }
Example #41
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="people">
 /// A <see cref="ABPerson[]"/>
 /// </param>
 /// <param name="requestedName">
 /// A <see cref="System.String"/>
 /// </param>
 /// <returns>
 /// A <see cref="ABPerson[]"/>
 /// </returns>
 private ABPerson[] FilterContactsByName(ABPerson[] people, string requestedName)
 {
     List<ABPerson> filteredPeopleList = new List<ABPerson>();
     foreach(ABPerson person in people) {
         // Check if requested name matches FistName,LastName,MiddleName or Nickname (ignoring case)
         if((person.FirstName!=null && person.FirstName.ToUpper().Contains(requestedName.ToUpper()))
            ||(person.LastName!=null && person.LastName.ToUpper().Contains(requestedName.ToUpper()))
             ||(person.MiddleName!=null && person.MiddleName.ToUpper().Contains(requestedName.ToUpper()))
            		||(person.Nickname!=null && person.Nickname.ToUpper().Contains(requestedName.ToUpper()))) {
             filteredPeopleList.Add(person);
         }
     }
     return filteredPeopleList.ToArray();
 }
Example #42
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ABPerson">
        /// A <see cref="ABPerson"/>
        /// </param>
        /// <returns>
        /// A <see cref="ContactLite"/>
        /// </returns>
        protected ContactLite ABPersonToContactLite(ABPerson person)
        {
            ContactLite contact = new ContactLite ();

            // Basic Info
            contact.ID = "" + person.Id;
            contact.Name = person.FirstName;
            contact.Firstname = person.MiddleName;
            contact.Lastname = person.LastName;
            contact.DisplayName = person.Nickname;

            // TODO how to get the group(s) this person belongs to
            contact.Group = person.Organization;

            // Phones
            contact.Phones = this.GetContactPhones (person);

            // Emails
            contact.Emails = this.GetContactEmails (person);

            return contact;
        }
Example #43
0
        private static void AddContactInfo(ABPerson selectedPerson, Item item)
        {
            // find the contact in the address book
            var book = new AddressBook();
            Contact contact = null;
            if (book.LoadSupported)
                contact = book.Load(selectedPerson.Id.ToString());
            else
                contact = book.FirstOrDefault(c => c.Id == selectedPerson.Id.ToString());

            if (contact == null)
                return;

            // make a copy of the item
            var itemCopy = new Item(item, true);

            // get more info from the address book
            var mobile = (from p in contact.Phones where
                p.Type == Xamarin.Contacts.PhoneType.Mobile
                select p.Number).FirstOrDefault();
            var home = (from p in contact.Phones where
                p.Type == Xamarin.Contacts.PhoneType.Home
                select p.Number).FirstOrDefault();
            var work = (from p in contact.Phones where
                p.Type == Xamarin.Contacts.PhoneType.Work
                select p.Number).FirstOrDefault();
            var email = (from em in contact.Emails
                select em.Address).FirstOrDefault();
            //var website = (from w in contact.Websites
            //    select w.Address).FirstOrDefault();

            string birthday = null;
            if (selectedPerson.Birthday != null)
                birthday = ((DateTime)selectedPerson.Birthday).ToString("d");

            if (birthday != null)
                item.GetFieldValue(FieldNames.Birthday, true).Value = birthday;
            if (mobile != null)
                item.GetFieldValue(FieldNames.Phone, true).Value = mobile;
            if (home != null)
                item.GetFieldValue(FieldNames.HomePhone, true).Value = home;
            if (work != null)
                item.GetFieldValue(FieldNames.WorkPhone, true).Value = work;
            if (email != null)
                item.GetFieldValue(FieldNames.Email, true).Value = email;
            /*
            if (website != null)
                item.GetFieldValue(FieldNames.Website, true).Value = website
                */

            // save changes to local storage
            Folder folder = App.ViewModel.LoadFolder(item.FolderID);
            StorageHelper.WriteFolder(folder);

            // enqueue the Web Request Record
            RequestQueue.EnqueueRequestRecord(RequestQueue.UserQueue,
                new RequestQueue.RequestRecord()
                {
                    ReqType = RequestQueue.RequestRecord.RequestType.Update,
                    Body = new List<Item>() { itemCopy, item },
                    BodyTypeName = "Item",
                    ID = item.ID
                });

            // add the zaplify contact header to a special Zaplify "related name" field
            // use the native address book because the cross-platform AddressBook class is read-only
            var ab = new ABAddressBook();
            var contactToModify = ab.GetPerson(selectedPerson.Id);

            /* RelatedNames doesn't work on a real device (iPad)
            var relatedNames = contactToModify.GetRelatedNames().ToMutableMultiValue();
            if (relatedNames.Any(name => name.Label == ZaplifyContactHeader))
            {
                // remove the existing one (can't figure out a way to get a mutable ABMultiValueEntry out of zapField)
                var zapField = relatedNames.Single(name => name.Label == ZaplifyContactHeader);
                relatedNames.RemoveAt(relatedNames.GetIndexForIdentifier(zapField.Identifier));
            }
            // add the Zaplify related name field with the itemID value
            relatedNames.Add(item.ID.ToString(), new MonoTouch.Foundation.NSString(ZaplifyContactHeader));
            contactToModify.SetRelatedNames(relatedNames);
            */

            var zapField = contactToModify.Note;
            if (zapField == null)
                contactToModify.Note = ZaplifyContactHeader + item.ID.ToString();
            else
            {
                if (zapField.Contains(ZaplifyContactHeader))
                {
                    var idstring = GetContactID(zapField);
                    if (idstring != null)
                        contactToModify.Note = zapField.Replace(idstring, item.ID.ToString());
                    else
                        contactToModify.Note += String.Format("\n{0}{1}", ZaplifyContactHeader, item.ID.ToString());
                }
                else
                    contactToModify.Note += String.Format("\n{0}{1}", ZaplifyContactHeader, item.ID.ToString());
            }

            // save changes to the address book
            ab.Save();
        }
Example #44
0
 public override void DidCompleteWithNewPerson(ABNewPersonViewController controller, ABPerson person)
 {
     controller.OnNewPersonComplete (new ABNewPersonCompleteEventArgs (person));
 }
Example #45
0
 public ABNewPersonCompleteEventArgs(ABPerson person)
 {
     Person = person;
 }
        protected void PopulatePage(ABPerson contact)
        {
            // save the ID of our person
            contactID = contact.Id;

            // set the data on the page
            txtFirstName.Text = contact.FirstName;
            txtLastName.Text = contact.LastName;
            tableDataSource = new AddressBookScreen.PhoneNumberTableSource (contact.GetPhones ());
            tblPhoneNumbers.Source = tableDataSource;

            // wire up our delete clicked handler
            tableDataSource.DeleteClicked +=
                (object sender, PhoneNumberTableSource.PhoneNumberClickedEventArgs e) => {
                DeletePhoneNumber (e.PhoneNumberID);
            };
        }
Example #47
0
        /// <summary>
        /// Gets the person from phone number.
        /// </summary>
        /// <returns>The person from number.</returns>
        /// <param name="number">Number.</param>
        public static ABPerson GetPersonFromNumber(string number)
        {
            number = Utils.StandardizePhoneNumber(number);
            ABPerson[] allContact = Utils.GetAllPeopleInContactList();
            ABPerson result = new ABPerson();
            bool hasResult = false;

            // go through all contact in contact list
            foreach(ABPerson person in allContact){
                // get phones property
                ABMultiValue<string> phones = person.GetPhones();
                // go through all phone numbers
                for (int i = 0; i < phones.Count; i++){
                    // make the phone number standard
                    string phone = Utils.StandardizePhoneNumber(phones[i].Value);
                    // compare phone number
                    if (phone.Equals(number)){
                        // if this is the right one
                        result = person;
                        hasResult = true;
                        // stop searching
                        break;
                    }
                }
                // stop searching if result found
                if (hasResult) break;
            }

            // return result;
            if (hasResult) return result;
            else return null;
        }
Example #48
0
 public override void DidResolveToPerson(ABUnknownPersonViewController personViewController, ABPerson person)
 {
     UIApplication.SharedApplication.InvokeOnMainThread (delegate {
         SystemLogger.Log(SystemLogger.Module.PLATFORM, "On UnknownPersonViewControllerDelegate::DidResolveToPerson");
         personViewController.DismissModalViewController(true);
         IPhoneServiceLocator.CurrentDelegate.MainUIViewController ().DismissModalViewController(true);
     });
 }
Example #49
0
 public override bool ShouldPerformDefaultActionForPerson(ABUnknownPersonViewController personViewController, ABPerson person, int propertyId, int identifier)
 {
     UIApplication.SharedApplication.InvokeOnMainThread (delegate {
         SystemLogger.Log(SystemLogger.Module.PLATFORM, "On UnknownPersonViewControllerDelegate::ShouldPerformDefaultActionForPerson");
     });
     return true;
 }
Example #50
0
        private static bool AddPersonToGroup(string groupname, ABPerson p)
        {
            if(!Groups.ContainsKey(groupname))
            {
                Groups.Add(groupname, new SmsGroupObject() {Name = groupname});
            }

            if(!Groups[groupname].Persons.Any(x => x.Id == p.Id))
            {
                Groups[groupname].Persons.Add(p);
                return true;
            }

            return false;
        }
Example #51
0
        /// <summary>
        /// Launchs the create new contact.
        /// </summary>
        /// <param name='contact'>
        /// Contact.
        /// </param>
        /// 
        protected void LaunchCreateNewContact(Contact contact)
        {
            ABPerson person = new ABPerson();
            // Basic Info
            person.FirstName = contact.Name;
            person.MiddleName = contact.Firstname;
            person.LastName = contact.Lastname;
            person.Nickname = contact.DisplayName;
            person.Note = contact.Notes;

            // Work info
            person.Organization = contact.Company;
            person.JobTitle = contact.JobTitle;
            person.Department =	contact.Department;

            // Addresses
            person.SetAddresses(this.ConvertContactAddressesToNative(contact.Addresses));

            // Phones
            person.SetPhones(this.ConvertContactPhonesToNative(contact.Phones));

            // Emails
            person.SetEmails(this.ConvertContactEmailsToNative(contact.Emails));

            // Websites
            person.SetUrls(this.ConvertContactWebsitesToNative(contact.WebSites));

            // Photo
            if(contact.Photo==null && contact.PhotoBase64Encoded!=null) {
                contact.Photo = Convert.FromBase64String(contact.PhotoBase64Encoded);
            }
            if(contact.Photo!=null) {
                NSData imageData = this.ConvertContactBinaryDataToNative(contact.Photo);
                if(imageData!=null && imageData.Length>0) {
                    person.Image = imageData;
                }
            }

            ABUnknownPersonViewController unknownPersonViewController = new ABUnknownPersonViewController();
            unknownPersonViewController.AddressBook = IPhoneServiceLocator.CurrentDelegate.AddressBook;
            unknownPersonViewController.AllowsActions = false;
            unknownPersonViewController.AllowsAddingToAddressBook = true;
            unknownPersonViewController.DisplayedPerson = person;
            unknownPersonViewController.PerformDefaultAction += HandlePerformDefaultAction;
            unknownPersonViewController.PersonCreated += HandleUnknownPersonCreated;
            unknownPersonViewController.Delegate = new UnknownPersonViewControllerDelegate();
            UIBarButtonItem backButtonItem = new UIBarButtonItem();
            backButtonItem.Title = "Cancel";
            backButtonItem.Clicked += HandleBackButtonItemClicked;
            unknownPersonViewController.NavigationItem.SetLeftBarButtonItem(backButtonItem,false);

            UINavigationController contactNavController = new UINavigationController();
            contactNavController.PushViewController(unknownPersonViewController,false);

            IPhoneServiceLocator.CurrentDelegate.MainUIViewController ().PresentModalViewController (contactNavController, true);
            IPhoneServiceLocator.CurrentDelegate.SetMainUIViewControllerAsTopController(false);
        }
		internal static Contact GetContact (ABPerson person)
		{
			Contact contact = new Contact (person)
			{
				DisplayName = person.ToString(),
				Prefix = person.Prefix,
				FirstName = person.FirstName,
				MiddleName = person.MiddleName,
				LastName = person.LastName,
				Suffix = person.Suffix,
				Nickname = person.Nickname
			};
			
			contact.Notes = (person.Note != null) ? new [] { new Note { Contents = person.Note } } : new Note[0];

			contact.Emails = person.GetEmails().Select (e => new Email
			{
				Address = e.Value,
				Type = GetEmailType (e.Label),
				Label = (e.Label != null) ? GetLabel (e.Label) : GetLabel (ABLabel.Other)
			});
			
			contact.Phones = person.GetPhones().Select (p => new Phone
			{
				Number = p.Value,
				Type = GetPhoneType (p.Label),
				Label = (p.Label != null) ? GetLabel (p.Label) : GetLabel (ABLabel.Other)
			});
			
			Organization[] orgs;
			if (person.Organization != null)
			{
				orgs = new Organization[1];
				orgs[0] = new Organization
				{
					Name = person.Organization,
					ContactTitle = person.JobTitle,
					Type = OrganizationType.Work,
					Label = GetLabel (ABLabel.Work)
				};
			}
			else
				orgs = new Organization[0];

			contact.Organizations = orgs;

			contact.InstantMessagingAccounts = person.GetInstantMessages().Select (ima => new InstantMessagingAccount()
			{
				Service = GetImService ((NSString)ima.Value[ABPersonInstantMessageKey.Service]),
				ServiceLabel = (NSString)ima.Value[ABPersonInstantMessageKey.Service],
				Account = (NSString)ima.Value[ABPersonInstantMessageKey.Username]
			});

			contact.Addresses = person.GetAddresses().Select (a => new Address()
			{
				Type = GetAddressType (a.Label),
				Label = (a.Label != null) ? GetLabel (a.Label) : GetLabel (ABLabel.Other),
				StreetAddress = (NSString)a.Value[ABPersonAddressKey.Street],
				City = (NSString)a.Value[ABPersonAddressKey.City],
				Region = (NSString)a.Value[ABPersonAddressKey.State],
				Country = (NSString)a.Value[ABPersonAddressKey.Country],
				PostalCode = (NSString)a.Value[ABPersonAddressKey.Zip]
			});
			
			contact.Websites = person.GetUrls().Select (url => new Website
			{
				Address = url.Value
			});

			contact.Relationships = person.GetRelatedNames().Select (p => new Relationship
			{
				Name = p.Value,
				Type = GetRelationType (p.Label)
			});

			return contact;
		}
Example #53
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="person">
        /// A <see cref="ABPerson"/>
        /// </param>
        /// <returns>
        /// A <see cref="ContactAddress[]"/>
        /// </returns>
        private ContactAddress[] GetContactAdresses(ABPerson person)
        {
            List<ContactAddress> contactAddressList = new List<ContactAddress>();

            if(person != null) {
                ABMultiValue<PersonAddress> addresses = person.GetAllAddresses();
                if(addresses!=null) {

                    IEnumerator enumerator = addresses.GetEnumerator();
                    while(enumerator.MoveNext()){
                        object currentAddress = enumerator.Current;
                        string label = ((ABMultiValueEntry<PersonAddress>)currentAddress).Label;
                        PersonAddress personAddress = ((ABMultiValueEntry<PersonAddress>)currentAddress).Value;

                        ContactAddress contactAddress = new ContactAddress();

                        if(label == ABLabel.Home) {
                            contactAddress.Type = DispositionType.HomeOffice;
                        } else if(label == ABLabel.Work) {
                            contactAddress.Type = DispositionType.Work;
                        } else if (label == ABLabel.Other) {
                            contactAddress.Type = DispositionType.Other;
                        }

                        /* old API
                        NSObject[] keys = addressDictionary.Keys;

                        foreach(NSObject key in keys) {
                            NSObject currentValue = addressDictionary.ObjectForKey(key);
                            if(currentValue != null) {
                                if(key.ToString() == ABPersonAddressKey.Street) {
                                    contactAddress.Address = currentValue.ToString();
                                    // contactAddress.AddressNumber = NOT PROVIDED BY API
                                }

                                if(key.ToString() == ABPersonAddressKey.City) {
                                    contactAddress.City = currentValue.ToString();
                                }
                                if(key.ToString() == ABPersonAddressKey.Country) {
                                    contactAddress.Country = currentValue.ToString();
                                }
                                if(key.ToString() == ABPersonAddressKey.Zip) {
                                    contactAddress.PostCode = currentValue.ToString();
                                }
                            }
                        }
                        */
                        contactAddress.Address =  personAddress.Street;
                        contactAddress.City = personAddress.City;
                        contactAddress.Country = personAddress.Country;
                        contactAddress.PostCode = personAddress.Zip;

                        contactAddressList.Add(contactAddress);
                    }
                }
            }
            return contactAddressList.ToArray();
        }
Example #54
0
		internal Contact (ABPerson person)
		{
			Id = person.Id.ToString();
			this.person = person;
		}
Example #55
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="person">
        /// A <see cref="ABPerson"/>
        /// </param>
        /// <returns>
        /// A <see cref="ContactPhone[]"/>
        /// </returns>
        private ContactPhone[] GetContactPhones(ABPerson person)
        {
            List<ContactPhone> contactPhoneList = new List<ContactPhone>();

            if(person != null) {
                ABMultiValue<string> phones = person.GetPhones();
                if(phones!=null) {

                    IEnumerator enumerator = phones.GetEnumerator();
                    while(enumerator.MoveNext()){
                        object currentPhone = enumerator.Current;
                        string label = ((ABMultiValueEntry<string>)currentPhone).Label;
                        string phone = ((ABMultiValueEntry<string>)currentPhone).Value;

                        ContactPhone contactPhone = new ContactPhone();
                        contactPhone.Number = phone;

                        if(label == ABLabel.Home) {
                            contactPhone.Type = NumberType.FixedLine;
                        } else if(label == ABLabel.Work) {
                            contactPhone.Type = NumberType.Work;
                        } else if(label == ABPersonPhoneLabel.HomeFax) {
                            contactPhone.Type = NumberType.HomeFax;
                        } else if(label == ABPersonPhoneLabel.WorkFax) {
                            contactPhone.Type = NumberType.WorkFax;
                        } else if(label == ABPersonPhoneLabel.Mobile) {
                            contactPhone.Type = NumberType.Mobile;
                        } else if(label == ABPersonPhoneLabel.Pager) {
                            contactPhone.Type = NumberType.Pager;
                        } else if (label == ABPersonPhoneLabel.Main) {
                            contactPhone.Type = NumberType.Other;
                            contactPhone.IsPrimary = true;
                        } else {
                            contactPhone.Type = NumberType.Other;
                        }

                        contactPhoneList.Add(contactPhone);
                    }
                }
            }
            return contactPhoneList.ToArray();
        }
        public void ShowAddContactController(UINavigationController navigationController, User user)
        {
            ABNewPersonViewController abController = new ABNewPersonViewController ();

            ABPerson person = new ABPerson ();

            KeyValuePair <string, string> namePair = GetFirstAndLastName (user);

            person.FirstName = namePair.Key;
            person.LastName = namePair.Value;

            if (!string.IsNullOrEmpty (user.Company))
            {
                person.Organization = user.Company;
            }

            if (!string.IsNullOrEmpty (user.Phone))
            {
                ABMutableMultiValue<string> phones = new ABMutableStringMultiValue();
                phones.Add(user.Phone, ABPersonPhoneLabel.Main);
                person.SetPhones(phones);
            }

            if (!string.IsNullOrEmpty (user.Email))
            {
                ABMutableMultiValue<string> emails = new ABMutableStringMultiValue();
                emails.Add(user.Email, null);
                person.SetEmails(emails);
            }

            // Get any image from cache
            byte [] data = Engine.Instance.ImageCache.FindAny (user);

            if (data != null && data.Length > 0)
            {
                person.Image = NSData.FromArray(data);
            }

            abController.DisplayedPerson  = person;

            abController.NewPersonComplete += delegate {
                navigationController.PopViewControllerAnimated (true);
            };

            navigationController.PushViewController (abController, true);

            if (OnAddContactCompleted != null)
                OnAddContactCompleted ();
        }
Example #57
0
        private static Item CreateNewContact(ABPerson selectedPerson)
        {
            Guid id = Guid.NewGuid();
            // get the default list for contacts
            Guid folderID;
            Guid? parentID = null;
            ClientEntity defaultList = App.ViewModel.GetDefaultList(SystemItemTypes.Contact);
            if (defaultList == null)
            {
                TraceHelper.AddMessage("CreateNewContact: error - could not find default contact list");
                return null;
            }
            if (defaultList is Item)
            {
                folderID = ((Item)defaultList).FolderID;
                parentID = defaultList.ID;
            }
            else
            {
                folderID = defaultList.ID;
                parentID = null;
            }

            Item newContact = new Item()
            {
                ID = id,
                Name = selectedPerson.ToString(),
                FolderID = folderID,
                ParentID = parentID,
                ItemTypeID = SystemItemTypes.Contact,
                FieldValues = new ObservableCollection<FieldValue>()
            };

            // add the new contact locally
            Folder folder = App.ViewModel.Folders.FirstOrDefault(f => f.ID == folderID);
            if (folder == null)
            {
                TraceHelper.AddMessage("CreateNewContact: error - could not find the folder for this item");
                return null;
            }
            folder.Items.Add(newContact);

            // save the current state of the folder
            StorageHelper.WriteFolder(folder);

            // enqueue the Web Request Record
            RequestQueue.EnqueueRequestRecord(RequestQueue.UserQueue,
                new RequestQueue.RequestRecord()
                {
                    ReqType = RequestQueue.RequestRecord.RequestType.Insert,
                    Body = newContact,
                });

            return newContact;
        }
Example #58
0
    internal static Contact GetContact(ABPerson person)
    {
      Contact contact = new Contact(person.Id.ToString(), true)
      {
        DisplayName = person.ToString(),
        Prefix = person.Prefix,
        FirstName = person.FirstName,
        MiddleName = person.MiddleName,
        LastName = person.LastName,
        Suffix = person.Suffix,
        Nickname = person.Nickname,
        Tag = person
      };

      contact.Notes = (person.Note != null) ? new List<Note> { new Note { Contents = person.Note } } : new List<Note>();

      contact.Emails = person.GetEmails().Select(e => new Email
      {
        Address = e.Value,
        Type = GetEmailType(e.Label),
        Label = (e.Label != null) ? GetLabel(e.Label) : GetLabel(ABLabel.Other)
      }).ToList();

      contact.Phones = person.GetPhones().Select(p => new Phone
      {
        Number = p.Value,
        Type = GetPhoneType(p.Label),
        Label = (p.Label != null) ? GetLabel(p.Label) : GetLabel(ABLabel.Other)
      }).ToList();

      var orgs = new List<Organization>();
      if (person.Organization != null)
      {
        orgs.Add(new Organization
        {
          Name = person.Organization,
          ContactTitle = person.JobTitle,
          Type = OrganizationType.Work,
          Label = GetLabel(ABLabel.Work)
        });
      }

      contact.Organizations = orgs;

      contact.InstantMessagingAccounts = person.GetInstantMessageServices().Select(ima => new InstantMessagingAccount()
      {
        Service = GetImService(ima.Value.ServiceName),
        ServiceLabel = ima.Value.ServiceName,
        Account = ima.Value.Username
      }).ToList();

      contact.Addresses = person.GetAllAddresses().Select(a => new Address()
      {
        Type = GetAddressType(a.Label),
        Label = (a.Label != null) ? GetLabel(a.Label) : GetLabel(ABLabel.Other),
        StreetAddress = a.Value.Street,
        City = a.Value.City,
        Region = a.Value.State,
        Country = a.Value.Country,
        PostalCode = a.Value.Zip
      }).ToList();

      contact.Websites = person.GetUrls().Select(url => new Website
      {
        Address = url.Value
      }).ToList();

      contact.Relationships = person.GetRelatedNames().Select(p => new Relationship
      {
        Name = p.Value,
        Type = GetRelationType(p.Label)
      }).ToList();

      return contact;
    }
		async void ShowNewContactViewController ()
		{
			using (var contact = new ABPerson ()) {
				try {

					contact.FirstName = viewModel.Place.Name;

					if (viewModel.Place.HasImage) {
						var data = await ResourceLoader.DefaultLoader.GetImageData(viewModel.Place.Photos[0].ImageUrl);
						contact.Image = UIImage.LoadFromData(NSData.FromArray(data)).AsJPEG();
					}

					using (var phone = new ABMutableStringMultiValue ()) {
						phone.Add(viewModel.Place.PhoneNumberFormatted, ABLabel.Other);
						contact.SetPhones(phone);
					}

					using (var webSite = new ABMutableStringMultiValue ()) {
						webSite.Add(viewModel.Place.Website, ABLabel.Other);
						contact.SetUrls(webSite);
					}

					var upvc = new ABUnknownPersonViewController {
						DisplayedPerson = contact,
						AllowsAddingToAddressBook = true,
						AllowsActions = true,
						AlternateName = viewModel.Place.Name,
						Title = viewModel.Place.Name
					};

					NavigationController.PushViewController(upvc, true);
				} catch (Exception) {
					var alert = UIAlertController.Create("Error", "Could not create unknown user.", UIAlertControllerStyle.Alert);
					alert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Default, null));
					PresentViewController(alert, true, null);
				}
			}
		}
Example #60
0
 private static Item GetExistingContact(ABPerson selectedPerson)
 {
     /* RelatedNames doesn't work on a real device (iPad)
     var list = selectedPerson.GetRelatedNames().ToList();
     if (list.Any(name => name.Label == ZaplifyContactHeader))
     {
         var zapField = list.Single(name => name.Label == ZaplifyContactHeader);
         Guid id = new Guid(zapField.Value);
         return App.ViewModel.Items.FirstOrDefault(i => i.ID == id);
     }
     return null;
     */
     if (selectedPerson == null || selectedPerson.Note == null)
         return null;
     if (selectedPerson.Note.Contains(ZaplifyContactHeader))
     {
         var zapField = selectedPerson.Note;
         var idstring = GetContactID(zapField);
         if (idstring == null)
             return null;
         Guid id = new Guid(idstring);
         return App.ViewModel.Items.FirstOrDefault(i => i.ID == id);
     }
     return null;
 }