public IPhoneUIApplicationDelegate()
     : base()
 {
     #if DEBUG
     log ("IPhoneUIApplicationDelegate constructor default");
     #endif
     IPhoneServiceLocator.CurrentDelegate = this;
     #if DEBUG
     log ("IPhoneUIApplicationDelegate creating event store instance");
     #endif
     eventStore = new EKEventStore ( );
     #if DEBUG
     log ("IPhoneUIApplicationDelegate creating address book instance");
     #endif
     if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) {
         NSError nsError = new NSError();
         addressBook =ABAddressBook.Create(out nsError);
         #if DEBUG
         log ("IPhoneUIApplicationDelegate creating address book result: " +((nsError!=null)?nsError.Description:"no error"));
         #endif
     } else {
         addressBook = new ABAddressBook();
     }
     #if DEBUG
     log ("IPhoneUIApplicationDelegate constructor successfully ended");
     #endif
 }
        private Contact[] GetContacts(ABAddressBook ab)
        {
            var contacts = new List<Contact>();
            foreach (var person in ab.GetPeople())
            {
                if (string.IsNullOrEmpty(person.FirstName) && string.IsNullOrEmpty(person.LastName))
                    continue;

                string displayName = string.Format("{0} {1}", person.FirstName, person.LastName);
                string number;
                var phones = person.GetPhones();
                if (phones == null || !phones.Any())
                    continue;

                number = phones[0].Value;
                if (!string.IsNullOrEmpty(number))
                {
                    contacts.Add(new Contact { Name = displayName, Number = number });   
                }
            }
            if (!contacts.Any())
            {
                return new[]
                        {
                            new Contact { Name = "Egor Bogatov", Number = "+01231"},
                            new Contact { Name = "Ian Gillan", Number = "+01232"},
                            new Contact { Name = "Freddie Mercury", Number = "+01233"},
                            new Contact { Name = "David Gilmour", Number = "+01234"},
                            new Contact { Name = "Steve Ballmer", Number = "+01235"},
                        };
            }

            return contacts.ToArray();
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			Title = "QuickContacts";

			menuArray = new NSMutableArray (0);

			NSError error;
			addressBook = ABAddressBook.Create (out error);

			CheckAddressBookAccess ();
		}
예제 #4
0
        public static object[] search(string phoneNumber)
        {
            List<ABPerson> singlePeople = new List<ABPerson> ();
            phoneNumber = Regex.Replace (phoneNumber, "[^0-9]", "");
            ABAddressBook ab = new ABAddressBook ();
            var people = ab.Where (x => x is ABPerson).Cast<ABPerson> ().Where (x => x.GetPhones ().Where (p => Regex.Replace (p.Value, "[^0-9]", "").Contains (phoneNumber) || phoneNumber.Contains (Regex.Replace (p.Value, "[^0-9]", ""))).Count () > 0).ToArray ();
            foreach (var person in people) {
                if (singlePeople.Intersect (person.GetRelatedNames ().Cast<ABPerson> ()).Count () <= 0)
                    singlePeople.Add (person);

            }
            return singlePeople.ToArray ();
        }
		public void ReloadAddressBook() {
			#if DEBUG
			log ("IPhoneUIApplicationDelegate creating address book instance");
			#endif
			if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) {
				NSError nsError = new NSError();
				addressBook =ABAddressBook.Create(out nsError);
				#if DEBUG
				log ("IPhoneUIApplicationDelegate creating address book result: " +((nsError!=null)?nsError.Description:"no error"));
				#endif
			} else {
				addressBook = new ABAddressBook();
			}
		}
 public IPhoneUIApplicationDelegate(IntPtr ptr)
     : base(ptr)
 {
     #if DEBUG
     log ("IPhoneUIApplicationDelegate constructor IntPtr");
     #endif
     IPhoneServiceLocator.CurrentDelegate = this;
     eventStore = new EKEventStore ( );
     if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) {
         NSError nsError = new NSError();
         addressBook =ABAddressBook.Create(out nsError);
         #if DEBUG
         log ("IPhoneUIApplicationDelegate creating address book result: " +((nsError!=null)?nsError.Description:"no error"));
         #endif
     } else {
         addressBook = new ABAddressBook();
     }
 }
예제 #7
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            // query the address book directly

            using (var addressBook = new ABAddressBook ()) {

                // Get all people with a specfied name
                //var people = addressBook.GetPeopleWithName ("John Doe");
                //people.ToList ().ForEach (p => Console.WriteLine ("{0} {1} - ", p.FirstName, p.LastName));

                // Use Linq to query contacts based upon any criteria
                addressBook.RequestAccess((bool x, NSError z) => {});
                var people = addressBook.GetPeople ();
                people.ToList ().FindAll (p => p.LastName == "Smith").ForEach (
                p => Console.WriteLine ("{0} {1}", p.FirstName, p.LastName));
            }
        }
예제 #8
0
 internal ABSource(IntPtr handle, ABAddressBook addressbook)
     : base(handle, false)
 {
     AddressBook = addressbook;
 }
예제 #9
0
        public void GetDefaultSource()
        {
            ABAddressBook ab = new ABAddressBook();

            Assert.NotNull(ab.GetDefaultSource(), "GetDefaultSource");
        }
        // 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);
            }
        }
        protected void BtnAddPhoneNumberTouchUpInside(object sender, EventArgs e)
        {
            // get a reference to the contact
            using (ABAddressBook addressBook = new ABAddressBook ()) {
                ABPerson contact = addressBook.GetPerson (contactID);
                if (contact != null) {
                    // 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
                    if (txtPhoneNumber.Text != null || txtPhoneLabel.Text != null) {
                        phones.Add (new NSString (txtPhoneNumber.Text), new NSString (txtPhoneLabel.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 ();
                    } else {
                        // show an alert, letting the user know he has to fill the phone label and phone number
                        new UIAlertView ("Alert", "You have to fill a label and a phone number", null, "OK", null).Show ();
                    }
                } else {
                    new UIAlertView ("Alert", "Please select a contact using the top right button", null, "OK", null).Show ();
                }
            }
        }
예제 #12
0
        public IList <string> GetAllNames()
        {
            var people = new ABAddressBook().GetPeople();

            return(people.Select(p => p.FirstName).ToList());
        }
		public AddressBookPrivacyManager ()
		{
			NSError error;
			addressBook = ABAddressBook.Create (out error);
		}
예제 #14
0
    private void OnGUI()
    {
        KitchenSink.OnGUIBack();

        GUILayout.BeginArea(new Rect(50, 50, Screen.width - 100, Screen.height / 2 - 50));

        //this is the original way of how objective C use call back functions: Delegates using separate files.
        //in this case the file is PeoplePickerNavigationControllerDelegate.cs
        //we have have it easier to use delegates instead of creating new files for each delegate.
        //see examples above.  Ex: PersonalXT.CalendarAccess += delegate( ....
        if (GUILayout.Button("pick/select from contacts", GUILayout.ExpandHeight(true)))
        {
            ABPeoplePickerNavigationController picker = new ABPeoplePickerNavigationController();
            if (pickerDelegate == null)
            {
                pickerDelegate = new PeoplePickerNavigationControllerDelegate();
            }
            picker.peoplePickerDelegate = pickerDelegate;
            UIApplication.deviceRootViewController.PresentViewController(picker, true, null);
        }

        if (GUILayout.Button("get all contacts", GUILayout.ExpandHeight(true)))
        {
            Log("Address book authorization status: " + ABAddressBook.GetAuthorizationStatus());

            var addressBook = ABAddressBook.Create(null, null);
            addressBook.RequestAccess(delegate(bool granted, NSError error) {
                Log("Granted: " + granted);

                //convienent function to get the names of the contacts
                string[] contactList = PersonalXT.GetAllContactNames();
                for (int i = 0; i < contactList.Length; i++)
                {
                    Log("Contact " + i + ": " + contactList[i]);
                }
            });
        }

        if (GUILayout.Button("add new contacts", GUILayout.ExpandHeight(true)))
        {
            addNewContact();
        }

        if (GUILayout.Button("init Calendar and show events within 30 days", GUILayout.ExpandHeight(true)))
        {
            checkEventStoreAccessForCalendar();
        }

        if (GUILayout.Button("add an event for tomorrow", GUILayout.ExpandHeight(true)))
        {
            addEventForTomorrow();
        }

        if (GUILayout.Button("add alarm to events", GUILayout.ExpandHeight(true)))
        {
            createAlarmForEvents();
        }

        if (GUILayout.Button("add reminder with geolocation of current location", GUILayout.ExpandHeight(true)))
        {
            PersonalXT.RequestReminderAccess();
        }

        if (GUILayout.Button("reverse geocode happiest place on earth", GUILayout.ExpandHeight(true)))
        {
            CLLocation location = new CLLocation(33.809, -117.919);
            CLGeocoder geocoder = new CLGeocoder();
            geocoder.ReverseGeocodeLocation(location, delegate(object[] placemarks, NSError error) {
                if (error != null)
                {
                    Debug.Log(error.LocalizedDescription());
                }
                else
                {
                    foreach (var p in placemarks)
                    {
                        var placemark = p as CLPlacemark;

                        Debug.Log("placemark: " + placemark.name + "\n"
                                  + ABAddressFormatting.ABCreateString(placemark.addressDictionary, true));
                    }
                }
            });
        }

        if (GUILayout.Button("Significant location change", GUILayout.ExpandHeight(true)))
        {
            if (!CLLocationManager.LocationServicesEnabled() || !CLLocationManager.SignificantLocationChangeMonitoringAvailable())
            {
                Debug.Log("Significant change monitoring not available.");
            }
            else
            {
//				CLLocationManager manager = new CLLocationManager();

                manager.StartMonitoringSignificantLocationChanges();
            }
        }


        //commented out remove all events and reminders so users don't accidentally remove important events

        /*
         * if (GUILayout.Button("remove all Events", GUILayout.ExpandHeight(true))) {
         *      PersonalXT.RemoveAllEvents();
         *      Log ("Removed events");
         * }
         *
         * if (GUILayout.Button("remove all Reminders", GUILayout.ExpandHeight(true))) {
         *      PersonalXT.GetAllReminders(); //you can get all the reminders and handle them in line 59 above
         *      //PersonalXT.RemoveAllReminders(); //or you can simply call removeAllReminders
         * }*/

        GUILayout.EndArea();
        OnGUILog();
    }
        Task<PermissionStatus> RequestContactsPermission()
        {

            if (ContactsPermissionStatus != PermissionStatus.Unknown)
                return Task.FromResult(ContactsPermissionStatus);

            if (addressBook == null)
                addressBook = new ABAddressBook();

            var tcs = new TaskCompletionSource<PermissionStatus>();


            addressBook.RequestAccess((success, error) => 
                {
                    tcs.SetResult((success ? PermissionStatus.Granted : PermissionStatus.Denied));
                });

            return tcs.Task;
        }
예제 #16
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();
        }
예제 #17
0
        string InitializePropsUI()
        {
            var help     = Source as IHelpful;
            var helpText = "";


            var q = from t in SourceType.GetProperties()
                    where t.DeclaringType == SourceType && t.CanWrite
                    select t;
            var props = q.ToArray();

            var rows = new List <Row> ();


            foreach (var p in props)
            {
                var ignoreAttrs = p.GetCustomAttributes(typeof(IgnoreAttribute), true);
                if (ignoreAttrs.Length > 0)
                {
                    continue;
                }

                var isEmail = p.GetCustomAttributes(typeof(EmailInputAttribute), true).Length > 0;
                if (!isEmail && p.Name == "Email")
                {
                    isEmail = true;
                }
                var isChooseEmail = p.GetCustomAttributes(typeof(ChooseEmailInputAttribute), true).Length > 0;

                var title = Theme.GetTitle(p.Name);

                if (help != null)
                {
                    var h = help.HelpForProperty(p.Name);
                    if (h != "")
                    {
                        helpText += title + " " + h + "\n";
                    }
                }

                var label = new UILabel {
                    BackgroundColor = UIColor.Black, TextColor = Lcars.ComponentColors[LcarsComponentType.CriticalFunction], Text = title, TextAlignment = UITextAlignment.Right, BaselineAdjustment = UIBaselineAdjustment.AlignBaselines, Font = Theme.InputFont, AdjustsFontSizeToFitWidth = true
                };

                var row = new Row {
                    Property = p
                };
                rows.Add(row);

                row.Label = label;
                UIKeyboardType kbd = UIKeyboardType.Default;
                if (isEmail || isChooseEmail)
                {
                    kbd = UIKeyboardType.EmailAddress;
                }
                else if (p.Name == "Url")
                {
                    kbd = UIKeyboardType.Url;
                }
                else if (p.PropertyType == typeof(int))
                {
                    kbd = UIKeyboardType.NumberPad;
                }

                var init = p.GetValue(Source, null);

                var text = new UITextField {
                    Placeholder = title, BackgroundColor = UIColor.Black, TextColor = UIColor.White, Font = Theme.InputFont, AdjustsFontSizeToFitWidth = false, AutocapitalizationType = UITextAutocapitalizationType.None, KeyboardType = kbd, Text = init != null?init.ToString() : ""
                };
                row.Text = text;
                if (p.Name.ToLowerInvariant().IndexOf("password") >= 0)
                {
                    text.SecureTextEntry    = true;
                    text.AutocorrectionType = UITextAutocorrectionType.No;
                }
                if (p.Name != "Search")
                {
                    text.AutocorrectionType = UITextAutocorrectionType.No;
                }
                if (text.Text.Length == 0 && !isChooseEmail)
                {
                    text.BecomeFirstResponder();
                }
                label.Hidden = text.Text.Length == 0;
                if (isChooseEmail)
                {
                    text.EditingDidBegin += delegate {
                        try {
                            bool hasPeople = false;
                            using (var adds = new ABAddressBook()) {
                                foreach (var pe in adds.GetPeople())
                                {
                                    var es = pe.GetEmails();
                                    if (es.Count > 0)
                                    {
                                        hasPeople = true;
                                        break;
                                    }
                                }
                            }

                            if (hasPeople)
                            {
                                Sounds.PlayBeep();
                                var em = new ChooseEmail();
                                em.EmailSelected += emailAddress =>
                                {
                                    text.Text = emailAddress;
                                    UpdateUI();
                                };
                                App.Inst.ShowDialog(em);
                                NSTimer.CreateScheduledTimer(TimeSpan.FromMilliseconds(30), delegate {
                                    try {
                                        HideKeyBoard(this);
                                    } catch (Exception err) {
                                        Log.Error(err);
                                    }
                                });
                            }
                        } catch (Exception error) {
                            Log.Error(error);
                        }
                    };
                }
                text.AllEditingEvents += delegate {
                    try {
                        label.Hidden = string.IsNullOrEmpty(text.Text);
                        UpdateUI();
                    } catch (Exception error) {
                        Log.Error(error);
                    }
                };
                AddSubview(label);
                AddSubview(text);
            }


            _propViews = rows.ToArray();

            return(helpText);
        }
예제 #18
0
 private ABAuthorizationStatus GetAuthorizationStatus()
 {
     return(ABAddressBook.GetAuthorizationStatus());
 }
예제 #19
0
      public Task<Boolean> RequestPermission()
      {
         var tcs = new TaskCompletionSource<Boolean>();
         if(UIDevice.CurrentDevice.CheckSystemVersion( 6, 0 ))
         {
            var status = ABAddressBook.GetAuthorizationStatus();
            if(status == ABAuthorizationStatus.Denied || status == ABAuthorizationStatus.Restricted)
            {
               tcs.SetResult( false );
            }
            else
            {
               if(addressBook == null)
               {
                  addressBook = new ABAddressBook();
                  provider = new ContactQueryProvider( addressBook );
               }

               if(status == ABAuthorizationStatus.NotDetermined)
               {
                  addressBook.RequestAccess(
                     ( s, e ) =>
                     {
                        tcs.SetResult( s );
                        if(!s)
                        {
                           addressBook.Dispose();
                           addressBook = null;
                           provider = null;
                        }
                     } );
               }
               else
               {
                  tcs.SetResult( true );
               }
            }
         }
         else
         {
            tcs.SetResult( true );
         }

         return tcs.Task;
      }
예제 #20
0
        public List <Contacto> GetLista()
        {
            Contacto c;

            lsc.Clear();
            try
            {
                Version ver = new Version(UIDevice.CurrentDevice.SystemVersion);
                if (ver.Major <= 8)
                {
                    NSError err;
                    var     iPhoneAddressBook = ABAddressBook.Create(out err);
                    var     authStatus        = ABAddressBook.GetAuthorizationStatus();
                    if (authStatus != ABAuthorizationStatus.Authorized)
                    {
                        iPhoneAddressBook.RequestAccess(delegate(bool granted, NSError error)
                        {
                            if (granted)
                            {
                                ABPerson[] myContacts = iPhoneAddressBook.GetPeople();
                                string phone          = string.Empty;
                                foreach (ABPerson contact in myContacts)
                                {
                                    ABMultiValue <string> phs = contact.GetPhones();
                                    if (phs.Count() > 0)
                                    {
                                        foreach (var stel in phs)
                                        {
                                            c = new Contacto()
                                            {
                                                Name   = contact.FirstName + " " + contact.LastName,
                                                Number = stel.Value,                                                 //phs.First().Value,
                                                Photo  = (contact.HasImage ? GetBitmap(contact.Image) : null),
                                            };
                                            lsc.Add(c);
                                        }
                                    }
                                }
                            }
                        });
                    }
                    else
                    {
                        ABPerson[] myContacts = iPhoneAddressBook.GetPeople();
                        string     phone      = string.Empty;
                        foreach (ABPerson contact in myContacts)
                        {
                            ABMultiValue <string> phs = contact.GetPhones();
                            if (phs.Count() > 0)
                            {
                                foreach (var stel in phs)
                                {
                                    c = new Contacto()
                                    {
                                        Name   = contact.FirstName + " " + contact.LastName,
                                        Number = stel.Value,                                         //phs.First().Value,
                                        Photo  = (contact.HasImage ? GetBitmap(contact.Image) : null),
                                    };
                                    lsc.Add(c);
                                }
                            }
                        }
                    }
                }
                if (ver.Major >= 9)
                {
                    //ios 9
                    var     store = new CNContactStore();
                    NSError error;
                    var     fetchKeys = new NSString[] { CNContactKey.Identifier, CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.PhoneNumbers, CNContactKey.ThumbnailImageData };
                    string  contid    = store.DefaultContainerIdentifier;
                    var     predicate = CNContact.GetPredicateForContactsInContainer(contid);
                    var     contacts  = store.GetUnifiedContacts(predicate, fetchKeys, out error);
                    foreach (CNContact cc in contacts)
                    {
                        for (int i = 0; i < cc.PhoneNumbers.Count(); i++)
                        {
                            Contacto ct = new Contacto()
                            {
                                Id     = cc.Identifier,
                                Name   = (!string.IsNullOrEmpty(cc.GivenName) ? cc.GivenName : "") + (!string.IsNullOrEmpty(cc.FamilyName) ? " " + cc.FamilyName : ""),
                                Number = (cc.PhoneNumbers[i] != null ? cc.PhoneNumbers[i].Value.StringValue : ""),
                                Photo  = (cc.ThumbnailImageData != null ? GetBitmap(cc.ThumbnailImageData) : null),
                            };
                            lsc.Add(ct);
                        }
                    }

                    /*lsc = contacts.Select(x => new Contacto()
                     * {
                     *      Id = x.Identifier,
                     *      Name = (!string.IsNullOrEmpty(x.GivenName) ? x.GivenName : "") + (!string.IsNullOrEmpty(x.FamilyName) ? " " + x.FamilyName : ""),
                     *      Number = (x.PhoneNumbers.FirstOrDefault() != null ? x.PhoneNumbers.FirstOrDefault().Value.StringValue : ""),
                     *      Photo = (x.ThumbnailImageData != null ? GetBitmap(x.ThumbnailImageData) : null),
                     * }).ToList();*/
                }
            }
            catch (Exception e)
            {
            }
            return(lsc);
        }
        public AddressBookPrivacyManager()
        {
            NSError error;

            addressBook = ABAddressBook.Create(out error);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            Title = "Address Book";

            // add a button to the nav bar that will select a contact to edit
            UIButton btnSelectContact = UIButton.FromType(UIButtonType.RoundedRect);

            btnSelectContact.SetTitle("Select Contact", UIControlState.Normal);
            NavigationItem.SetRightBarButtonItem(new UIBarButtonItem(UIBarButtonSystemItem.Action, SelectContact), false);

            // wire up keyboard hiding
            txtPhoneLabel.ShouldReturn  += (t) => { t.ResignFirstResponder(); return(true); };
            txtPhoneNumber.ShouldReturn += (t) => { t.ResignFirstResponder(); return(true); };
            txtFirstName.ShouldReturn   += (t) => { t.ResignFirstResponder(); return(true); };
            txtLastName.ShouldReturn    += (t) => { t.ResignFirstResponder(); return(true); };

            // wire up event handlers
            btnSaveChanges.TouchUpInside    += BtnSaveChangesTouchUpInside;
            btnAddPhoneNumber.TouchUpInside += BtnAddPhoneNumberTouchUpInside;

            #region -= Sample code showing how to loop through all the records =-
            //==== This block of code writes out each person contact in the address book and
            // each phone number for that person to the console, just to illustrate the code
            // neccessary to access each item

            // instantiate a reference to the address book
            NSError err;
            addressBook = ABAddressBook.Create(out err);
            if (err != null)
            {
                return;
            }

            // if you want to subscribe to changes
            addressBook.ExternalChange += (object sender, ExternalChangeEventArgs e) => {
                // code to deal with changes
            };

            addressBook.RequestAccess(delegate(bool granted, NSError error) {
                if (!granted || error != null)
                {
                    return;
                }

                // for each record
                foreach (ABRecord item in addressBook)
                {
                    Console.WriteLine(item.Type.ToString() + " " + item.Id);
                    // there are two possible record types, person and group
                    if (item.Type == ABRecordType.Person)
                    {
                        // since we've already tested it to be a person, just create a shortcut to that
                        // type
                        ABPerson person = item as ABPerson;
                        Console.WriteLine(person.FirstName + " " + person.LastName);

                        // get the phone numbers
                        ABMultiValue <string> phones = person.GetPhones();
                        foreach (ABMultiValueEntry <string> val in phones)
                        {
                            Console.Write(val.Label + ": " + val.Value);
                        }
                    }
                }

                // save changes (if you were to have made any)
                //addressBook.Save();
                // or cancel them
                //addressBook.Revert();
            });
            //====
            #endregion

            #region -= keyboard stuff =-

            // wire up our keyboard events
            NSNotificationCenter.DefaultCenter.AddObserver(
                UIKeyboard.WillShowNotification, delegate(NSNotification n) { KeyboardOpenedOrClosed(n, "Open"); });
            NSNotificationCenter.DefaultCenter.AddObserver(
                UIKeyboard.WillHideNotification, delegate(NSNotification n) { KeyboardOpenedOrClosed(n, "Close"); });

            #endregion
        }
		public void RequestAddressBookAccess ()
		{
			NSError error;
			addressBook = ABAddressBook.Create (out error);

			if (addressBook != null) {
				addressBook.RequestAccess (delegate (bool granted, NSError accessError) {
					ShowAlert (DataClass.Contacts, granted ? "granted" : "denied");
				});
			}
		}
예제 #24
0
 internal static string GetLabel(NSString label)
 {
     return(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ABAddressBook.LocalizedLabel(label)));
 }
예제 #25
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();
        }
        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
                    for (int i = 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 ();
                }
            }
        }
예제 #27
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 override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            Title = "Address Book";

            // add a button to the nav bar that will select a contact to edit
            UIButton btnSelectContact = UIButton.FromType (UIButtonType.RoundedRect);
            btnSelectContact.SetTitle ("Select Contact", UIControlState.Normal);
            NavigationItem.SetRightBarButtonItem (new UIBarButtonItem (UIBarButtonSystemItem.Action, SelectContact), false);

            // disable first two fields until the user select a contact
            EnableTextFields (false);

            // wire up keyboard hiding
            txtPhoneLabel.ShouldReturn += (t) => {
                t.ResignFirstResponder ();
                return true;
            };
            txtPhoneNumber.ShouldReturn += (t) => {
                t.ResignFirstResponder ();
                return true;
            };
            txtFirstName.ShouldReturn += (t) => {
                t.ResignFirstResponder ();
                return true;
            };
            txtLastName.ShouldReturn += (t) => {
                t.ResignFirstResponder ();
                return true;
            };

            // wire up event handlers
            btnSaveChanges.TouchUpInside += BtnSaveChangesTouchUpInside;
            btnAddPhoneNumber.TouchUpInside += BtnAddPhoneNumberTouchUpInside;

            #region -= Sample code showing how to loop through all the records =-
            //==== This block of code writes out each person contact in the address book and
            // each phone number for that person to the console, just to illustrate the code
            // neccessary to access each item

            // instantiate a reference to the address book
            NSError err;
            addressBook = ABAddressBook.Create (out err);
            if (err != null)
                return;

            // if you want to subscribe to changes
            addressBook.ExternalChange += (object sender, ExternalChangeEventArgs e) => {
                // code to deal with changes
            };

            addressBook.RequestAccess (delegate (bool granted, NSError error) {

                if (!granted || error != null)
                    return;

                // for each record
                foreach (ABRecord item in addressBook) {

                    Console.WriteLine (item.Type.ToString () + " " + item.Id);
                    // there are two possible record types, person and group
                    if (item.Type == ABRecordType.Person) {
                        // since we've already tested it to be a person, just create a shortcut to that
                        // type
                        ABPerson person = item as ABPerson;
                        Console.WriteLine (person.FirstName + " " + person.LastName);

                        // get the phone numbers
                        ABMultiValue<string> phones = person.GetPhones ();
                        foreach (ABMultiValueEntry<string> val in phones) {
                            Console.Write (val.Label + ": " + val.Value);
                        }
                    }
                }

                // save changes (if you were to have made any)
                //addressBook.Save();
                // or cancel them
                //addressBook.Revert();
            });
            //====
            #endregion

            #region -= keyboard stuff =-

            // wire up our keyboard events
            NSNotificationCenter.DefaultCenter.AddObserver (
                UIKeyboard.WillShowNotification, delegate (NSNotification n) {
                KeyboardOpenedOrClosed (n, "Open");
            });
            NSNotificationCenter.DefaultCenter.AddObserver (
                UIKeyboard.WillHideNotification, delegate (NSNotification n) {
                KeyboardOpenedOrClosed (n, "Close");
            });

            #endregion
        }
예제 #29
0
 public static void getMyPersonWithPhoneNumber(ABAddressBook addressBook,List<MyPerson> ContactsWithPhoneNumber)
 {
     try{
     ABPerson[] people = addressBook.GetPeople();
     foreach(var x in people)
     {
         ABMultiValue<string> PhoneNumbers=x.GetPhones();
         foreach(var y in PhoneNumbers)
         {
             if(!String.IsNullOrEmpty(y.Value)&&y.Label.ToString().ToLower().Contains("mobile"))
             {
                 MyPerson newMyPerson=new MyPerson();
                 newMyPerson.FirstName=String.IsNullOrEmpty(x.FirstName)?"":x.FirstName;
                 newMyPerson.LastName=String.IsNullOrEmpty(x.LastName)?"":x.LastName;
                 newMyPerson.Phone=y.Value;
                 ContactsWithPhoneNumber.Add(newMyPerson);
                 continue;
             }
         }
     }
     }
     catch(Exception e){
         Insights.Report(e);
     }
 }
예제 #30
0
 internal ContactQueryProvider(ABAddressBook addressBook)
 {
     this.addressBook = addressBook;
 }
예제 #31
0
파일: Form.cs 프로젝트: jorik041/lcars
        string InitializePropsUI()
        {
            var help = Source as IHelpful;
            var helpText = "";

            var q = from t in SourceType.GetProperties ()
                where t.DeclaringType == SourceType && t.CanWrite
                select t;
            var props = q.ToArray ();

            var rows = new List<Row> ();

            foreach (var p in props) {

                var ignoreAttrs = p.GetCustomAttributes (typeof(IgnoreAttribute), true);
                if (ignoreAttrs.Length > 0)
                    continue;

                var isEmail = p.GetCustomAttributes (typeof(EmailInputAttribute), true).Length > 0;
                if (!isEmail && p.Name == "Email") {
                    isEmail = true;
                }
                var isChooseEmail = p.GetCustomAttributes (typeof(ChooseEmailInputAttribute), true).Length > 0;

                var title = Theme.GetTitle (p.Name);

                if (help != null) {
                    var h = help.HelpForProperty (p.Name);
                    if (h != "") {
                        helpText += title + " " + h + "\n";
                    }
                }

                var label = new UILabel { BackgroundColor = UIColor.Black, TextColor = Lcars.ComponentColors[LcarsComponentType.CriticalFunction], Text = title, TextAlignment = UITextAlignment.Right, BaselineAdjustment = UIBaselineAdjustment.AlignBaselines, Font = Theme.InputFont, AdjustsFontSizeToFitWidth = true };

                var row = new Row { Property = p };
                rows.Add (row);

                row.Label = label;
                UIKeyboardType kbd = UIKeyboardType.Default;
                if (isEmail || isChooseEmail) {
                    kbd = UIKeyboardType.EmailAddress;
                } else if (p.Name == "Url") {
                    kbd = UIKeyboardType.Url;
                } else if (p.PropertyType == typeof(int)) {
                    kbd = UIKeyboardType.NumberPad;
                }

                var init = p.GetValue (Source, null);

                var text = new UITextField { Placeholder = title, BackgroundColor = UIColor.Black, TextColor = UIColor.White, Font = Theme.InputFont, AdjustsFontSizeToFitWidth = false, AutocapitalizationType = UITextAutocapitalizationType.None, KeyboardType = kbd, Text = init != null ? init.ToString () : "" };
                row.Text = text;
                if (p.Name.ToLowerInvariant ().IndexOf ("password") >= 0) {
                    text.SecureTextEntry = true;
                    text.AutocorrectionType = UITextAutocorrectionType.No;
                }
                if (p.Name != "Search") {
                    text.AutocorrectionType = UITextAutocorrectionType.No;
                }
                if (text.Text.Length == 0 && !isChooseEmail) {
                    text.BecomeFirstResponder ();
                }
                label.Hidden = text.Text.Length == 0;
                if (isChooseEmail) {
                    text.EditingDidBegin += delegate {
                        try {

                            bool hasPeople = false;
                            using (var adds = new ABAddressBook ()) {
                                foreach (var pe in adds.GetPeople ()) {
                                    var es = pe.GetEmails ();
                                    if (es.Count > 0) {
                                        hasPeople = true;
                                        break;
                                    }
                                }
                            }

                            if (hasPeople) {
                                Sounds.PlayBeep ();
                                var em = new ChooseEmail ();
                                em.EmailSelected += emailAddress =>
                                {
                                    text.Text = emailAddress;
                                    UpdateUI ();
                                };
                                App.Inst.ShowDialog (em);
                                NSTimer.CreateScheduledTimer (TimeSpan.FromMilliseconds (30), delegate {
                                    try {
                                        HideKeyBoard (this);
                                    } catch (Exception err) {
                                        Log.Error (err);
                                    }
                                });
                            }
                        } catch (Exception error) {
                            Log.Error (error);
                        }
                    };
                }
                text.AllEditingEvents += delegate {
                    try {
                        label.Hidden = string.IsNullOrEmpty (text.Text);
                        UpdateUI ();
                    } catch (Exception error) {
                        Log.Error (error);
                    }
                };
                AddSubview (label);
                AddSubview (text);
            }

            _propViews = rows.ToArray ();

            return helpText;
        }
예제 #32
0
        public static void RefreshAddressBook()
        {
            if(AddressBook != null)
            {
                AddressBook.Dispose();
            }

            AddressBook = new ABAddressBook();
        }
예제 #33
0
 public string CheckAddressBookAccess()
 {
     return(ABAddressBook.GetAuthorizationStatus().ToString());
 }
예제 #34
0
 public static void getMyPersonWithEmail(ABAddressBook addressBook,List<MyPerson> ContactsWithEmail)
 {
     ABPerson[] people = addressBook.GetPeople();
     foreach(var x in people)
     {
         ABMultiValue<string> Emails=x.GetEmails();
         foreach(var y in Emails)
         {
             if(!String.IsNullOrEmpty(y.Value))
             {
                 MyPerson newMyPerson=new MyPerson();
                 newMyPerson.FirstName=String.IsNullOrEmpty(x.FirstName)?"":x.FirstName;
                 newMyPerson.LastName=String.IsNullOrEmpty(x.LastName)?"":x.LastName;
                 newMyPerson.Email=y.Value;
                 ContactsWithEmail.Add(newMyPerson);
                 continue;
             }
         }
     }
 }
 protected override string CheckAccess()
 {
     return(ABAddressBook.GetAuthorizationStatus().ToString());
 }
예제 #36
0
        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();
        }
예제 #37
0
 /// <summary>
 /// Gets all people in contact list.
 /// </summary>
 public static ABPerson[] GetAllPeopleInContactList()
 {
     ABAddressBook addressBook = new ABAddressBook();
     ABPerson[] contactList = addressBook.GetPeople();
     return contactList;
 }
		void AddContact (UIAlertAction action)
		{
			try {
				#if !DEBUG
				Xamarin.Insights.Track ("Click", new Dictionary<string,string> {
					{ "item", "add contact" },
					{ "name", viewModel.Place.Name },
				});
				#endif
				NSError error;
				addressBook = ABAddressBook.Create(out error);
				CheckAddressBookAccess();
			} catch (Exception ex) {
				#if !DEBUG
				ex.Data ["call"] = "add contact";
				Xamarin.Insights.Report (ex);
				#endif
			}
		}
예제 #39
0
      private void CheckStatus()
      {
         if(UIDevice.CurrentDevice.CheckSystemVersion( 6, 0 ))
         {
            var status = ABAddressBook.GetAuthorizationStatus();
            if(status != ABAuthorizationStatus.Authorized)
            {
               throw new SecurityException( "AddressBook has not been granted permission" );
            }
         }

         if(addressBook == null)
         {
            addressBook = new ABAddressBook();
            provider = new ContactQueryProvider( addressBook );
         }
      }