コード例 #1
0
        public async Task <List <Contato> > BuscaContatos()
        {
            var            book = new Xamarin.Contacts.AddressBook();
            List <Contato> ct   = new List <Contato>();

            await book.RequestPermission().ContinueWith(t =>
            {
                if (!t.Result)
                {
                    Console.WriteLine("Permission denied by user or manifest");
                }


                Parallel.ForEach(book, contact =>
                {
                    if (contact.Phones.Any())
                    {
                        ct.Add(new Contato()
                        {
                            Nome     = contact.DisplayName,
                            Telefone = contact.Phones.FirstOrDefault().Number
                        });
                    }
                });
            }, TaskScheduler.FromCurrentSynchronizationContext());

            return(ct);
        }
コード例 #2
0
ファイル: MainActivity.cs プロジェクト: antixaker/GetContacts
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            MessagingCenter.Subscribe<object>(this, "get",  (o) =>
            {
                var book = new AddressBook(this);
                //if (!await book.RequestPermission())
                //{
                //    Toast.MakeText(this, "Go to ass", ToastLength.Long).Show();
                //    return;
                //}
                int counter = 0;
                //var kj = book.ToList<Contact>();
                foreach (var item in book)//.OrderBy(x => x.Emails!=null || x.Emails.Count<Email>()!=0/*.First<Email>().Address*/))
                {
                    var numb = item.Emails.Count<Email>();
                    if(numb>0)
                        MessagingCenter.Send<object, string>(this, "contact", item.Emails.FirstOrDefault<Email>().Address);

                    Console.WriteLine(counter++);
                    //if (counter > 2)
                    //    return;
                }

            });

            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new App());
        }
コード例 #3
0
ファイル: MainView.cs プロジェクト: Nahums0/caller-id
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            SetupUI();

            var book = new Xamarin.Contacts.AddressBook();

            // We must request permission to access the user's address book
            // This will prompt the user on platforms that ask, or it will validate
            // manifest permissions on platforms that declare their required permissions.
            book.RequestPermission().ContinueWith(t =>
            {
                if (!t.Result)
                {
                    alert = new UIAlertView("Permission denied", "User has denied this app access to their contacts", null, "Close");
                    alert.Show();
                }
                else
                {
                    // Contacts can be selected and sorted using LINQ!
                    //
                    // In this sample, we'll just use LINQ to sort contacts by
                    // their last name in reverse order.
                    list = book.OrderByDescending(c => c.LastName).ToList();

                    tableView.Source = new TableViewDataSource(list);
                    tableView.ReloadData();
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
コード例 #4
0
		protected override void OnActivityResult (int requestCode, Result resultCode, Intent data)
		{
			if (requestCode == ligacao_agenda && resultCode == Result.Ok) {
				if (data == null || data.Data == null)
					return;

				var addressBook = new AddressBook (this);
				addressBook.PreferContactAggregation = true;

				var pathSegments = data.Data.PathSegments;
				var contact = addressBook.Load (pathSegments[pathSegments.Count - 1]);
				if (contact == null)
					contact = addressBook.Load (pathSegments[pathSegments.Count - 2]);
				if (contact == null)
					return;

				var mobile = (from p in contact.Phones
				               where p.Type == Xamarin.Contacts.PhoneType.Mobile
				               select p.Number).FirstOrDefault ();

				if (string.IsNullOrEmpty (mobile))
					return;

				var uri = Android.Net.Uri.Parse (string.Format ("tel:{0}", mobile));
				var intent = new Intent (Intent.ActionView, uri); 

				StartActivity (intent);
			}
		}
コード例 #5
0
ファイル: EmailListFragment.cs プロジェクト: MADMUC/TAP5050
        public void GetEmailList(EmailListFragment fragment,ViewGroup rootview)
        {
            nn_activity.RunOnUiThread(()=>{
                fragment.AddSpinner(rootview,"Loading");
            });

            var book = new Xamarin.Contacts.AddressBook (nn_activity);
            book.ToList ().ForEach (p=>{
                string name = "";
                if (p.FirstName != null) {
                    name += p.FirstName+" ";
                }
                if (p.LastName != null) {
                    name += p.LastName;
                }

                List<Email> emaillist = p.Emails.ToList ();
                if (emaillist.Count > 0) {
                    foreach(var email in emaillist){
                        ContactInfo info = new ContactInfo (name,email.Address);
                        contactinfolist.Add (info);
                        break;
                    }
                }
            }
            );
            nn_activity.RunOnUiThread(()=>{
                fragment.RemoveSpinner(rootview);
                fragment.adapter.notifycontactlistdatachange();
            });
        }
コード例 #6
0
ファイル: MainActivity.cs プロジェクト: TerribleDev/DrunkDial
 private void Dial()
 {
     var book = new Xamarin.Contacts.AddressBook(this);
     book.RequestPermission().ContinueWith(t =>
         {
             if (!t.Result)
             {
                 Console.WriteLine("Permission denied by user or manifest");
                 return;
             }
             var validContacts = book.Where(a => a.Phones.Any(b => b.Number.Any())).ToList();
             var totalValidContacts = validContacts.Count;
             if (totalValidContacts < 1)
             {
                 var alert = new AlertDialog.Builder(this);
                 alert.SetTitle("No valid Contacts Found");
                 alert.SetMessage("No valid Contacts Found");
             }
             var rnd = new Random();
             Contact contact = null;
             while (contact == null)
             {
                 contact = validContacts.Skip(rnd.Next(0, totalValidContacts)).FirstOrDefault();
             }
             var urlNumber = Android.Net.Uri.Parse("tel:" + contact.Phones.First().Number);
             var intent = new Intent(Intent.ActionCall);
             intent.SetData(urlNumber);
             this.StartActivity(intent);
         }, TaskScheduler.FromCurrentSynchronizationContext());
 }
コード例 #7
0
ファイル: MainView.cs プロジェクト: TerabyteX/Xamarin.Mobile
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			SetupUI();

			var book = new Xamarin.Contacts.AddressBook ();

			// We must request permission to access the user's address book
			// This will prompt the user on platforms that ask, or it will validate
			// manifest permissions on platforms that declare their required permissions.
			book.RequestPermission().ContinueWith (t =>
			{
				if (!t.Result)
				{
					alert = new UIAlertView ("Permission denied", "User has denied this app access to their contacts", null, "Close");
					alert.Show();
				}
				else
				{
					// Contacts can be selected and sorted using LINQ!
					//
					// In this sample, we'll just use LINQ to sort contacts by
					// their last name in reverse order.
					list = book.OrderByDescending (c => c.LastName).ToList();

					tableView.Source = new TableViewDataSource (list);
					tableView.ReloadData();
				}
			}, TaskScheduler.FromCurrentSynchronizationContext());
		}
コード例 #8
0
ファイル: ContactListFragment.cs プロジェクト: MADMUC/TAP5050
        public void GetContactList(ContactListFragment fragment,ViewGroup rootview)
        {
            nn_activity.RunOnUiThread(()=>{
                fragment.AddSpinner(rootview,"Loading");
            });

                var book = new Xamarin.Contacts.AddressBook (nn_activity);
                book.ToList ().ForEach (p=>{
                    string name = "";
                    if (p.FirstName != null) {
                        name += p.FirstName+" ";
                    }
                    if (p.LastName != null) {
                        name += p.LastName;
                    }

                    List<Phone> phonelist = p.Phones.ToList ();
                    if (phonelist.Count > 0) {
                        foreach(var phone in phonelist){
                            if(phone.Type.Equals(Xamarin.Contacts.PhoneType.Mobile)){
                                ContactInfo info = new ContactInfo (name,phone.Number);
                                contactinfolist.Add (info);
                                break;
                            }

                        }
                    }
                }
                );
                nn_activity.RunOnUiThread(()=>{
                fragment.RemoveSpinner(rootview);
                fragment.adapter.notifycontactlistdatachange();
                });
        }
コード例 #9
0
ファイル: MainActivity.cs プロジェクト: GSerjo/Seminars
		protected override void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);
			
			//
			// get the address book, which gives us access to the
			// the contacts store
			//
			var book = new AddressBook (this);
			
			//
			// important: PreferContactAggregation must be set to the 
			// the same value when looking up contacts by ID
			// since we look up contacts by ID on the subsequent 
			// ContactsActivity in this sample, we will set both to true
			//
			book.PreferContactAggregation = true;
			
			//
			// loop through the contacts and put them into a List<String>
			//
			// Note that the contacts are ordered by last name - contacts can be selected and sorted using LINQ!
			// A more performant solution would create a custom adapter to lazily pull the contacts
			//
			// In this sample, we'll just use LINQ to grab the first 10 users with mobile phone entries
			//
			foreach (Contact contact in book.Where(c => c.Phones.Any(p => p.Type == PhoneType.Mobile)).Take(10))
			{
				contacts.Add(contact.DisplayName);
				contactIDs.Add(contact.Id); //save the ID in a parallel list
			}
			
			ListAdapter = new ArrayAdapter<string> (this, Resource.Layout.list_item, contacts.ToArray());
		    ListView.TextFilterEnabled = true;
			
			//
			// When clicked, start a new activity to display more contact details
			//	
			ListView.ItemClick += delegate (object sender, AdapterView.ItemClickEventArgs args) {
		        
				//
				// to show the contact on the details activity, we
				// need to send that activity the contacts ID
				//
				String contactID = contactIDs[args.Position];
				Intent showContactDetails = new Intent(this, typeof(ContactActivity));
				showContactDetails.PutExtra("contactID", contactID);
				StartActivity(showContactDetails);
				
				//
				// alternatively, show a toast with the name of the contact selected
				//
				//Toast.MakeText (Application, ((TextView)args.View).Text, ToastLength.Short).Show ();
		    };
		}
コード例 #10
0
ファイル: MainView.cs プロジェクト: GSerjo/Seminars
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			
			this.Title = "Contacts";
			
			list = new List<Contact>();
            
			//
			// get the address book, which gives us access to the
			// the contacts store
			//
			var book = new AddressBook ();
			
			//
			// important: PreferContactAggregation must be set to the 
			// the same value when looking up contacts by ID
			// since we look up contacts by ID on the subsequent 
			// ContactsActivity in this sample, we will set to false
			//
			book.PreferContactAggregation = true;
			
			//
			// loop through the contacts and put them into a List
			//
			// contacts can be selected and sorted using linq!
			//
			// In this sample, we'll just use LINQ to grab the first 10 users with mobile phone entries
			//
			foreach (Contact contact in book.Where(c => c.Phones.Any(p => p.Type == PhoneType.Mobile)).Take(10))
			{
				list.Add(contact);
			}
			
			//
			// create a tableview and use the list as the datasource
			//
			tableView = new UITableView()
            {
				Delegate = new TableViewDelegate(this),
                DataSource = new TableViewDataSource(list),
                AutoresizingMask =
                    UIViewAutoresizing.FlexibleHeight|
                    UIViewAutoresizing.FlexibleWidth,
            };
			
			//
			// size the tableview and add it to the parent view
			//
			tableView.SizeToFit();
			tableView.Frame = new RectangleF (
                0, 0, this.View.Frame.Width,
                this.View.Frame.Height);
            this.View.AddSubview(tableView);
		}
コード例 #11
0
ファイル: AddressBook.cs プロジェクト: irfannuri/dial-at-once
        public void CheckAccessPermission(Action<bool> onResult)
        {
            Xamarin.Contacts.AddressBook book = new Xamarin.Contacts.AddressBook ();
            book.RequestPermission().ContinueWith (t => {
                if (!t.Result) {
                    onResult(false);
                }
                else onResult(true);

            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
コード例 #12
0
 public void CheckAccessPermission(Action <bool> onResult)
 {
     Xamarin.Contacts.AddressBook book = new Xamarin.Contacts.AddressBook();
     book.RequestPermission().ContinueWith(t => {
         if (!t.Result)
         {
             onResult(false);
         }
         else
         {
             onResult(true);
         }
     }, TaskScheduler.FromCurrentSynchronizationContext());
 }
コード例 #13
0
        public List <Person> GetPeople()
        {
            NSError       error;
            List <Person> result = new List <Person> ();

            Xamarin.Contacts.AddressBook book = new Xamarin.Contacts.AddressBook();

            ABAddressBook nativeBook = ABAddressBook.Create(out error);

            nativeBook.ExternalChange += BookChanged;

            foreach (Xamarin.Contacts.Contact c in book)
            {
                if (c.Phones.Count() > 0)
                {
                    Person p = new Person(Convert.ToInt32(c.Id), c.FirstName, c.MiddleName, c.LastName);

                    p.ModificationDate = nativeBook.GetPerson(p.Id).ModificationDate;

                    p.NickName = c.Nickname;
                    if (c.Organizations.Count() > 0)
                    {
                        p.Organization = c.Organizations.ElementAt(0).Name;
                    }

                    p.Notes = String.Concat(c.Notes.Select(n => n.Contents));

                    StringBuilder sb = new StringBuilder();

                    foreach (Phone phone in c.Phones)
                    {
                        PhoneNumber pnb = new PhoneNumber()
                        {
                            Type = (PhoneNumberType)((int)phone.Type), Number = phone.Number
                        };
                        p.Phones.Add(pnb);
                        sb.AppendFormat("{0},{1};", (int)pnb.Type, pnb.Number);
                    }
                    p.DetailData = p.Details;
                    p.PhoneData  = sb.ToString();

                    result.Add(p);
                }
            }



            return(result);
        }
コード例 #14
0
        public async void GetMobileContacts(ContatoViewModel vm)
        {
            var book = new Xamarin.Contacts.AddressBook();

            if (await book.RequestPermission())
            {
                foreach (Contact contact in book)
                {
                    SetContato(contact, vm);
                }
            }
            else
            {
                var         message = "Permissão negada. Habite acesso a lista de contatos";
                UIAlertView avAlert = new UIAlertView("Autorização", message, null, "OK", null);
                avAlert.Show();
            }
        }
コード例 #15
0
        public async Task<List<string>> GetContacts()
        {
            List<string> contactList = null;
            try
            {

                await  Task.Run(async () =>
                {
                    contactList = new List<string>();
                    var book = new AddressBook(MainActivity.GetMainActivity());


                    if (!await book.RequestPermission())
                    {
                        Toast.MakeText(MainActivity.GetMainActivity(), "Permission denied.", ToastLength.Short);
                        return;
                    }

                    //foreach (Xamarin.Contacts.Contact contact in book.OrderBy(c => c.LastName))
                    try
                    {
                        book.OrderBy(c => c.DisplayName);
                    }
                    catch (Exception ex)
                    {
                        var test = ex.Message;
                    }

                    foreach (Xamarin.Contacts.Contact contact in book)
                    {
                        if (contact.FirstName != null && contact.FirstName.Trim().Length > 0 && contact.Phones != null && contact.Phones.Count() > 0)
                            contactList.Add(contact.FirstName);
                    }
                });
              

            }
            catch (Exception ex)
            {
                var test = ex.Message;
            }
            return contactList;
        }
コード例 #16
0
ファイル: ContactListFragment.cs プロジェクト: MADMUC/TAP5050
        public void GetContactList(ContactListFragment fragment,ViewGroup rootview)
        {
            nn_activity.RunOnUiThread(()=>{
                fragment.AddSpinner(rootview,"Loading");
            });

                var book = new Xamarin.Contacts.AddressBook (nn_activity);
                List<Contact> list = book.ToList ();
                list.Sort (
                delegate(Contact x, Contact y)
                {
                    if (String.IsNullOrEmpty(x.FirstName) && String.IsNullOrEmpty(y.FirstName)) return 0;
                    else if (x.FirstName == null) return -1;
                    else if (y.FirstName == null) return 1;
                    else return x.FirstName.CompareTo(y.FirstName);
                });
                list.ForEach (p=>{
                    string name = "";
                    if (p.FirstName != null) {
                        name += p.FirstName+" ";
                    }
                    if (p.LastName != null) {
                        name += p.LastName;
                    }

                    List<Phone> phonelist = p.Phones.ToList ();
                    if (phonelist.Count > 0) {
                        foreach(var phone in phonelist){
                            if(phone.Type.Equals(Xamarin.Contacts.PhoneType.Mobile)){
                                ContactInfo info = new ContactInfo (name,phone.Number);
                                contactinfolist.Add (info);
                                break;
                            }

                        }
                    }
                }
                );
                nn_activity.RunOnUiThread(()=>{
                fragment.RemoveSpinner(rootview);
                fragment.adapter.notifycontactlistdatachange();
                });
        }
コード例 #17
0
        //Get Photo and Name from Contact
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            if (requestCode != 101 || resultCode != Result.Ok) return;
            if (data == null || data.Data == null) return;

            var addressBook = new AddressBook(Application.Context)
            {
                PreferContactAggregation = false
            };

            var contact = addressBook.Load(data.Data.LastPathSegment);
            if (string.IsNullOrEmpty(contact.DisplayName))
            {
                Toast.MakeText(this, Resources.GetString(Resource.String.NoNameString), ToastLength.Short).Show();
                return;
            }

            _editText.Text = contact.DisplayName;
            PlayerImage = contact.GetThumbnail();
        }
コード例 #18
0
        public async void GetMobileContacts(ContatoViewModel vm)
        {
            var context = Forms.Context as Activity;
            var book    = new Xamarin.Contacts.AddressBook(context);

            if (await book.RequestPermission())
            {
                foreach (Contact contact in book)
                {
                    AdicionarContato(contact, vm);
                }
            }
            else
            {
                AlertDialog.Builder messageUI = new AlertDialog.Builder(context);
                messageUI.SetMessage("Permissao negada. Habite acesso a lista de contatos");
                messageUI.SetTitle("Autorizacao");
                messageUI.Create().Show();
            }
        }
コード例 #19
0
        public async void GetMobileContacts(ContatoViewModel vm)
        {
#pragma warning disable CS0618 // O tipo ou membro é obsoleto
            var context = Forms.Context as Activity;
#pragma warning restore CS0618 // O tipo ou membro é obsoleto
            var book = new Xamarin.Contacts.AddressBook(context);
            if (await book.RequestPermission())
            {
                foreach (Contact contact in book)
                {
                    SetContato(contact, vm);
                }
            }
            else
            {
                AlertDialog.Builder messageUI = new AlertDialog.Builder(context);
                messageUI.SetMessage("Permissão negada. Habite acesso a lista de contatos");
                messageUI.SetTitle("Autorização");
                messageUI.Create().Show();
            }
        }
コード例 #20
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            this.Window.AddFlags(WindowManagerFlags.Fullscreen);
            RequestWindowFeature(WindowFeatures.NoTitle);

            SetContentView(Resource.Layout.FriendsList);
            frView = FindViewById <ListView>(Resource.Id.listView1);

            friendsList = new List <string>();
            var book = new Xamarin.Contacts.AddressBook(this);

            foreach (var contact in book)
            {
                friendsList.Add(contact.DisplayName);
            }


            ArrayAdapter <string> adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItemActivated1, friendsList);

            frView.Adapter    = adapter;
            frView.ChoiceMode = ChoiceMode.Multiple;
        }
コード例 #21
0
        public IEnumerable<SelectableContact> GetContactsWithEmailAddresses()
        {
            #if MONOANDROID
            var androidGlobals = this.GetService<Cirrious.MvvmCross.Droid.Interfaces.IMvxAndroidGlobals>();
            var ab = new AddressBook(androidGlobals.ApplicationContext);
            #else
            var ab = new AddressBook();
            #endif

            var allContacts = ab.ToList();

            return (from c in allContacts
                    orderby c.DisplayName
                    where c.Emails != null && c.Emails.Any()
                    let email = c.Emails.FirstOrDefault()
                    where email != null && !string.IsNullOrEmpty(email.Address)
                    select
                        new SelectableContact
                        {
                            DisplayName = c.DisplayName,
                            Email = email.Address,
                            IsSelected = false
                        }).ToList();
        }
コード例 #22
0
		public void Execute ()
		{

			var abook = new AddressBook();


			abook.RequestPermission().ContinueWith (t =>
			                                         {
				if (!t.Result)
					return; // Permission denied

				_persons = new List<Person>();

				// Full LINQ support
				foreach (Contact c in abook)
				{
					_persons.Add(new Person(c.FirstName, c.LastName));
				}

				PersonsAccessed(this, EventArgs.Empty);

			}, TaskScheduler.FromCurrentSynchronizationContext()); // Ensure we're on the UI Thread

		}
コード例 #23
0
 public DroidDeviceUsersService()
 {
     _book = new Xamarin.Contacts.AddressBook(Forms.Context.ApplicationContext);
 }
コード例 #24
0
        //Get Photo and Name from Contact
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            try
            {
                if (resultCode == Result.Canceled)
                    return;

                if (requestCode == 2)
                {
                    _player.FromContacts = false;
                    data.GetMediaFileExtraAsync(this).ContinueWith(t =>
                        PlayerImagePath = t.Result.Path);
                }

                if (requestCode == 3)
                {
                    if (data == null || data.Data == null)
                        return;

                    var addressBook = new AddressBook(Application.Context)
                    {
                        PreferContactAggregation = false
                    };

                    var contact = addressBook.Load(data.Data.LastPathSegment);

                    if (string.IsNullOrEmpty(contact.DisplayName))
                        Toast.MakeText(this, Resources.GetString(Resource.String.NoNameString), ToastLength.Short)
                            .Show();
                    else
                        _editText.Text = contact.DisplayName;


                    if (contact.GetThumbnail() != null)
                    {
                        _player.FromContacts = true;
                        PlayerImagePath = data.Data.LastPathSegment;
                    }
                    else
                    {
                        _player.FromContacts = false;
                        PlayerImagePath = null;
                    }
                }
            }

            catch (Exception exception)
            {
                GaService.TrackAppException(this.Class, "OnActivityResult", exception, false);
            }
        }
コード例 #25
0
ファイル: Player.cs プロジェクト: okrotowa/Mosigra.Yorsh
        public void LoadBitmap(int desiredSize)
        {
            try
            {
                if (Image != null)
                {
                    Image.Recycle();
                    Image.Dispose();
                }

                if (string.IsNullOrEmpty(PhotoPath))
                {
                    SetDefaultImage();
                }
                else if (FromContacts)
                {
                    var addressBook = new AddressBook(Application.Context) { PreferContactAggregation = false };
                    var contact = addressBook.Load(PhotoPath);
                    var image = contact.GetThumbnail();
                    Image = image == null ? GetDefaultImage() : image.GetRoundedCornerBitmap();
                }
                else
                {
                    var image = BitmapExtensions.DecodeBitmap(PhotoPath, desiredSize, desiredSize);
                    Image = image == null ? GetDefaultImage() : image.GetRoundedCornerBitmap();
                }
            }
            catch (Exception ex)
            {
                GaService.TrackAppException("Player", "LoadBitmap", ex, false);
                SetDefaultImage();
                if (!string.IsNullOrEmpty(PhotoPath)) PhotoPath = null;
            }

        }
コード例 #26
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();
        }
コード例 #27
0
ファイル: ContactActivity.cs プロジェクト: GSerjo/Seminars
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);
			
			//
			// Get the contact ID that is passed in
			// from the main activity
			//
			String contactID = String.Empty;
			if(bundle != null)
			{
				contactID = bundle.GetString("contactID");
			}
			else
			{
				contactID = Intent.GetStringExtra("contactID");	
			}
			
			//
			// Get the address book
			//
			var book = new AddressBook (this);
			
			//
			// Important: PreferContactAggregation must be set to the 
			// the same value as when the ID was generated (from the
			// previous activity)
			//
			book.PreferContactAggregation = true;
			
			Contact contact = book.Load (contactID);
			
			//
			// If the contact is empty, we'll
			// display a 'not found' error
			//
			String displayName = "Contact Not Found";
			String mobilePhone = String.Empty;
			
			//
			// Set the displayName variable to the contact's
			// DisplayName property
			//
			if(contact != null)
			{
				displayName = contact.DisplayName;
				var phone = contact.Phones.FirstOrDefault (p => p.Type == PhoneType.Mobile);
				if(phone != null)
				{
					mobilePhone = phone.Number;	
				}
			}
			
			//
			// Show the contacts display name and mobile phone
			//
			SetContentView (Resource.Layout.contact_view);
			var fullNameTextView = FindViewById<TextView> (Resource.Id.full_name);
			fullNameTextView.Text = displayName;
			var mobilePhoneTextView = FindViewById<TextView> (Resource.Id.mobile_phone);
			mobilePhoneTextView.Text = mobilePhone;
			
		}
コード例 #28
0
        private void CheckForExistingAndContinue(UINavigationController navigationController, 
		                                          User user, bool mainThreadRequired)
        {
            KeyValuePair <string, string> namePair = GetFirstAndLastName (user);

            string firstName = namePair.Key;
            string lastName = namePair.Value;

            AddressBook book = new AddressBook ();

            foreach (Contact contact in book)
            {
                if (contact.FirstName == firstName &&
                    contact.LastName == lastName)
                {
                    if (!mainThreadRequired)
                        AskShouldAddDuplicateAndContinue (navigationController, user);
                    else
                    {
                        navigationController.BeginInvokeOnMainThread (delegate {
                            AskShouldAddDuplicateAndContinue (navigationController, user);
                        });
                    }
                    return;
                }
            }

            if (!mainThreadRequired)
                ShowAddContactController (navigationController, user);
            else
            {
                navigationController.BeginInvokeOnMainThread (delegate {
                    ShowAddContactController (navigationController, user);
                });
            }
        }
コード例 #29
0
		public static void RefreshPushDirectory()
		{
			Console.WriteLine("starting contacts sync");
			AddressBook book = new AddressBook();
			PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance();
			book.RequestPermission().ContinueWith(t => {
				if (!t.Result) {
					Console.WriteLine("Permission denied by user or manifest");
					return;
				}
				long now = Utils.CurrentTimeMillis();
				Dictionary<String, String> map = new Dictionary<String, String>();
				int i = 0, j = 0, k = 0;
				foreach (Contact contact in book) {
					if (String.IsNullOrEmpty(contact.DisplayName))
						continue;
					foreach (Phone phone in contact.Phones) {
						j++;
						if (phone.Number.Contains("*") || phone.Number.Contains("#"))
							continue;
						try {
							String number = phoneUtil.Format(phoneUtil.Parse(phone.Number, AppDelegate.GetCountryCode()), PhoneNumberFormat.E164);
							if (!map.ContainsKey(number))
								map.Add(number, contact.DisplayName);
						} catch (Exception e) {
							Console.WriteLine("Exception parsing/formatting '" + phone.Number + "': " + e.Message);
						}
					}
					foreach (Email email in contact.Emails) {
						k++;
						if (!map.ContainsKey(email.Address))
							map.Add(email.Address, contact.DisplayName);
					}
					i++;
				}
				Console.WriteLine(i + " contacts in address book with " + j + " phone numbers and " + k + " email addresses");
				Dictionary<String, String> tokens = hashNumbers(map.Keys.ToList());
				List<String> response = MessageManager.RetrieveDirectory(tokens.Keys.ToList());
				Console.WriteLine("found " + response.Count + " securecom users");
				using (var conn = new SQLite.SQLiteConnection(AppDelegate._dbPath)) {
					conn.BeginTransaction();
					conn.Execute("DELETE FROM PushContact");
					foreach (String key in response) {
						String number = tokens[key];
						if (number == null) // is this needed?
							continue;
						conn.Insert(new PushContact { Number = number, Name = map[number] });
					}
					conn.Commit();

				}
				Console.WriteLine("contacts sync finished, took " + ((Utils.CurrentTimeMillis() - now) / 1000.0) + " seconds");
			}, TaskScheduler.Current);
		}
コード例 #30
0
		public static void UpdateThreadNames()
		{
			var conn = new SQLite.SQLiteConnection(AppDelegate._dbPath);
			List<PushChatThread> pct = conn.Query<PushChatThread>("SELECT * FROM PushChatThread where DisplayName is null or DisplayName = ''");
			PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance();
			AddressBook book = new AddressBook();
			foreach (PushChatThread thread in pct) {
				String display_name = null;
				foreach (Contact c in book) {
					if (thread.Number.Contains("@")) {
						if (!c.Emails.Any())
							continue;
						foreach (Email e in c.Emails) {
							if (thread.Number.Equals(e.Address)) {
								display_name = c.DisplayName;
								break;
							}
						}
					} else {
						if (!c.Phones.Any())
							continue;
						foreach (Phone p in c.Phones) {
							if (p.Number.Contains("*") || p.Number.Contains("#"))
								continue;
							try {
								String number = phoneUtil.Format(phoneUtil.Parse(p.Number, AppDelegate.GetCountryCode()), PhoneNumberFormat.E164);
								if (thread.Number.Equals(number)) {
									display_name = c.DisplayName;
									break;
								}
							} catch (Exception e) {
								Console.WriteLine("Exception parsing/formatting '" + p.Number + "': " + e.Message);
							}
						}
					}
					if (display_name != null) {
						conn.Execute("UPDATE PushChatThread Set DisplayName = ? WHERE ID = ?", display_name, thread.ID);
						break;
					}
				}
			}
			conn.Commit();
			conn.Close();
		}
コード例 #31
0
ファイル: AddressBook.cs プロジェクト: irfannuri/dial-at-once
        public List<Person> GetPeople()
        {
            NSError error;
            List<Person> result = new List<Person> ();

            Xamarin.Contacts.AddressBook book = new Xamarin.Contacts.AddressBook ();

            ABAddressBook nativeBook = ABAddressBook.Create (out error);
            nativeBook.ExternalChange += BookChanged;

            foreach (Xamarin.Contacts.Contact c in book) {

                if (c.Phones.Count() > 0) {
                    Person p = new Person (Convert.ToInt32(c.Id), c.FirstName, c.MiddleName, c.LastName);

                    p.ModificationDate = nativeBook.GetPerson(p.Id).ModificationDate;

                    p.NickName = c.Nickname;
                    if (c.Organizations.Count () > 0) {
                        p.Organization = c.Organizations.ElementAt (0).Name;
                    }

                    p.Notes = String.Concat (c.Notes.Select (n => n.Contents));

                    StringBuilder sb = new StringBuilder ();

                    foreach (Phone phone in c.Phones) {
                        PhoneNumber pnb = new PhoneNumber (){ Type = (PhoneNumberType)((int)phone.Type), Number = phone.Number };
                        p.Phones.Add (pnb);
                        sb.AppendFormat ("{0},{1};", (int)pnb.Type, pnb.Number);
                    }
                    p.DetailData = p.Details;
                    p.PhoneData = sb.ToString ();

                    result.Add (p);
                }
            }

            return result;
        }
コード例 #32
0
		private void ProcessSearchOnAllContacts(string searchText)
		{
			List<CustomCellGroup> mCellGroups = new List<CustomCellGroup>();
			CustomCellGroup mTableCellGroup = new CustomCellGroup();
			AddressBook book = new AddressBook();
			foreach (Contact contact in book.OrderBy(c => c.DisplayName)) {
				if (String.IsNullOrEmpty(contact.DisplayName))
					continue;
				bool found = false;
				//Decide contact group based on the first character
				String group = contact.DisplayName.Substring(0, 1).ToUpper();
				if (contact.DisplayName.ToLower().Contains(searchText)) {
					found = true;
				} else if (contact.Phones.Any()) {
					foreach (Phone p in contact.Phones) {
						String temp = p.Number
							.Replace("(", string.Empty)
							.Replace(")", string.Empty)
							.Replace("-", string.Empty)
							.Replace(" ", string.Empty);
						found |= temp.Contains(searchText);
					}
				} else if (contact.Emails.Any()) {
					foreach (Email e in contact.Emails) {
						found |= e.Address.ToLower().Contains(searchText);
					}
				}
				if (!found)
					continue;
				ContactListCell cell = ContactListCell.Create();
				cell.SetName(contact.DisplayName);
				foreach (Phone p in contact.Phones) {
					cell.SetPhone(p.Number);
					break;
				}
				foreach (Email e in contact.Emails) {
					cell.SetEmail(e.Address);
					break;
				}
				mTableCellGroup.Cells.Add(cell);
			}
			mTableCellGroup.Name = mTableCellGroup.Cells.Count == 0 ? "No Results" : "Search Results";
			mCellGroups.Add(mTableCellGroup);
			source = new CustomCellTableSource(mCellGroups);
			source.RowSelectedAction = RowSelected;
			table.Source = source;
		}
コード例 #33
0
		private void AddContactsData(String contactFilter)
		{

			// Figure out where the SQLite database will be.
			bool showAll = contactFilter != "Securecom users";
			var conn = new SQLite.SQLiteConnection(AppDelegate._dbPath);
			List<PushContact> pc = conn.Query<PushContact>("select * from PushContact");
			conn.Close();
			List<String> registeredContacts = new List<String>();
			List<String> groups = new List<String>();
			foreach (PushContact c in pc)
				registeredContacts.Add(c.Number);
			var phoneUtil = PhoneNumberUtil.GetInstance();
			if (!showAll) {
				Dictionary<String, List<String>> map = new Dictionary<String, List<String>>();
				foreach (PushContact c in pc) {
					String n = c.Name ?? c.Number;
					if (!map.ContainsKey(n))
						map[n] = new List<String>();
					map[n].Add(c.Number);
				}
				foreach (KeyValuePair<String, List<String>> entry in map.OrderBy(c => c.Key)) {
					String group = entry.Key.Substring(0, 1).ToUpper();
					bool newGroup = !groups.Contains(group);
					foreach (CustomCellGroup ccg in cellGroups) {
						if (ccg.Name.Equals(group)) {
							newGroup = false;
							tableCellGroup = ccg;
						}
					}
					ContactListCell cell = ContactListCell.Create();
					cell.SetName(entry.Key);
					foreach (String number in entry.Value) {
						if (number.Contains("@"))
							cell.SetEmail(number);
						else
							cell.SetPhone(number);
					}
					if (newGroup) {
						tableCellGroup = new CustomCellGroup { Name = group };
						cellGroups.Add(tableCellGroup);
					}
					tableCellGroup.Cells.Add(cell);
				}
				return;
			}

			AddressBook book = new AddressBook();
			book.RequestPermission().ContinueWith(t => {
				if (!t.Result) {
					Console.WriteLine("Permission denied by user or manifest");
					return;
				}
			}, TaskScheduler.FromCurrentSynchronizationContext());

			foreach (Contact contact in book.OrderBy(c => c.DisplayName)) {
				if (!showAll && registeredContacts.Count == 0)
					break;
				if (String.IsNullOrEmpty(contact.DisplayName))
					continue;
				String group = contact.DisplayName.Substring(0, 1).ToUpper();
				bool newGroup = !groups.Contains(group);
				foreach (CustomCellGroup ccg in cellGroups) {
					if (ccg.Name.Equals(group)) {
						newGroup = false;
						tableCellGroup = ccg;
					}
				}

				ContactListCell cell = ContactListCell.Create();
				cell.SetName(contact.DisplayName);
				cell.SetEmail(null);
				cell.SetPhone(null);

				if (contact.Phones.Any()) {
					foreach (Phone p in contact.Phones) {
						if (showAll) {
							cell.SetPhone(p.Number);
							cell.registeredState = ContactListCell.STATE_PENDING;
							break;
						}
						if (p.Number.Contains("*") || p.Number.Contains("#"))
							continue;
						String number;
						try {
							number = phoneUtil.Format(phoneUtil.Parse(p.Number, AppDelegate.GetCountryCode()), PhoneNumberFormat.E164);
						} catch (Exception e) {
							continue;
						}
						if (!registeredContacts.Contains(number))
							continue;
						registeredContacts.Remove(number);
						cell.SetPhone(p.Number);
						cell.registeredState = ContactListCell.STATE_REGISTERED;
						//conn.Execute("UPDATE PushContact Set Name = ? WHERE Number = ?", contact.DisplayName, number);
						break;
					}
				}
				if (contact.Emails.Any()) {
					foreach (Email e in contact.Emails) {
						if (showAll) {
							cell.SetEmail(e.Address);
							cell.registeredState = ContactListCell.STATE_PENDING;
							break;
						}
						if (!registeredContacts.Contains(e.Address))
							continue;						
						registeredContacts.Remove(e.Address);
						cell.SetEmail(e.Address);
						cell.registeredState = ContactListCell.STATE_REGISTERED;
						//conn.Execute("UPDATE PushContact Set Name = ? WHERE Number = ?", contact.DisplayName, e.Address);
						break;
					}
				}
				if (cell._email == null && cell.mobile == null)
					continue;
				if (newGroup) {
					tableCellGroup = new CustomCellGroup { Name = group };
					cellGroups.Add(tableCellGroup);
				}
				tableCellGroup.Cells.Add(cell);
			}
			//conn.Close();

		}
コード例 #34
0
ファイル: MainView.cs プロジェクト: ARMoir/mobile-samples
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			
			Title = "Contacts";
			//
			// create a tableview and use the list as the datasource
			//
			tableView = new UITableView()
			{
				Delegate = new TableViewDelegate(this),
				AutoresizingMask =
				UIViewAutoresizing.FlexibleHeight|
				UIViewAutoresizing.FlexibleWidth,
			};
			
			//
			// size the tableview and add it to the parent view
			//
			tableView.SizeToFit();
			tableView.Frame = new RectangleF (
				0, 0, this.View.Frame.Width,
				this.View.Frame.Height);
			this.View.AddSubview(tableView);


			list = new List<Contact>();

			//
			// get the address book, which gives us access to the
			// the contacts store
			//
			var book = new AddressBook ();

			//
			// important: PreferContactAggregation must be set to the 
			// the same value when looking up contacts by ID
			// since we look up contacts by ID on the subsequent 
			// ContactsActivity in this sample, we will set to false
			//
			book.PreferContactAggregation = true;

			book.RequestPermission().ContinueWith (t =>
			{
				if (!t.Result)
				{
					alert = new UIAlertView ("Permission denied", "User has denied this app access to their contacts", null, "Close");
					alert.Show();
				}
				else
				{
					//
					// loop through the contacts and put them into a List
					//
					// contacts can be selected and sorted using linq!
					//
					// In this sample, we'll just use LINQ to grab the first 10 users with mobile phone entries
					//
					foreach (Contact contact in book.Where(c => c.Phones.Any(p => p.Type == PhoneType.Mobile)).Take(10))
					{
						list.Add(contact);
					}

					tableView.DataSource = new TableViewDataSource (list);
					tableView.ReloadData();
				}
			}, TaskScheduler.FromCurrentSynchronizationContext());
		}
コード例 #35
0
ファイル: AppDelegate.cs プロジェクト: GSerjo/Seminars
 public override bool FinishedLaunching (UIApplication app, NSDictionary options)
 {
     window = new UIWindow (UIScreen.MainScreen.Bounds);
     
     var book = new AddressBook ();
     
     _rootElement = new RootElement ("Json Example"){
         
         new Section ("Json Demo"){
             JsonElement.FromFile ("sample.json"),        
             new JsonElement ("Load from url", "http://localhost/sample.json")                    
         },
         new Section ("MT.D+Linq+Xamarin.Mobile"){
             new RootElement ("Contacts with Phones") {
                 from c in book.Where (c => c.Phones.Count () > 0)
                 select new Section (c.DisplayName){
                     from p in c.Phones
                     select (Element)new StringElement (p.Number)
                 }
             }
         },
         new Section ("Tasks Sample using Json")
     };
      
     _vc = new DialogViewController (_rootElement);
     _nav = new UINavigationController (_vc);
     
     window.RootViewController = _nav;
     window.MakeKeyAndVisible ();
     
     #region task demo
     
     int n = 0;
     
     _addButton = new UIBarButtonItem (UIBarButtonSystemItem.Add);
     _vc.NavigationItem.RightBarButtonItem = _addButton;
     
     _addButton.Clicked += (sender, e) => {
         
         ++n;
         
         var task = new Task{Name = "task " + n, DueDate = DateTime.Now};
         
         var taskElement = JsonElement.FromFile ("task.json");
         
         taskElement.Caption = task.Name;
         
         var description = taskElement ["task-description"] as EntryElement;
         
         if (description != null) {
             description.Caption = task.Name;
             description.Value = task.Description;       
         }
         
         var duedate = taskElement ["task-duedate"] as DateElement;
         
         if (duedate != null) {                
             duedate.DateValue = task.DueDate;
         }
  
         _rootElement [2].Add (taskElement);
     };
     
     #endregion
     
     return true;
 }
コード例 #36
0
		public void PopulateTable()
		{
			table.ReloadData();
			UIImage thumbnail = null;
			List<CustomCellGroup> cellGroups = new List<CustomCellGroup>();
			tableCellGroup = new CustomCellGroup();
			cellGroups.Add(tableCellGroup);
			PhoneNumberUtil phoneUtil = PhoneNumberUtil.GetInstance();
			AddressBook book = new AddressBook();
			var conn = new SQLite.SQLiteConnection(AppDelegate._dbPath);
			pct = conn.Query<PushChatThread>("SELECT * FROM PushChatThread ORDER BY TimeStamp DESC");
			conn.Close();
			int count = 0;

			foreach (PushChatThread thread in pct) {
				String display_name = thread.DisplayName;

				ChatCell chatCell = ChatCell.Create();
				chatCell.SetHeader(display_name + " (" + thread.Number + ")");
				chatCell.SetSubheading(thread.Snippet);
				chatCell.SetThreadID(thread.ID);
				chatCell.SetNumber(thread.Number);
				chatCell.SetAvatar(thumbnail);
				DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(thread.TimeStamp / 1000).ToLocalTime();
				chatCell.SetLabelTime("" + epoch.ToString("HH:mm"));
				chatCell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
					
				if (thread.Read != 0)
					chatCell.BackgroundColor = UIColor.Green;
				tableCellGroup.Cells.Insert(count, chatCell);
				count++;

			}
			source = new CustomCellTableSource(cellGroups);
			source.RowSelectedAction = RowSelected;
			source.DeleteAction = DeleteSelected;
			source.DeleteTitle = "Delete";
			table.Source = source;

			ShowEditButton();

		}
コード例 #37
0
        private void StartOnAddContactAction(UINavigationController navigationController, User user)
        {
            AddressBook book = new AddressBook ();
            book.RequestPermission ().ContinueWith (task => {
                navigationController.BeginInvokeOnMainThread (delegate {
                    if (task.IsFaulted || task.IsCanceled || !task.Result)
                    {
                        ShowNoContactAccess ();
                    }

                    else
                    {
                        _canAccessAddress = true;
                        CheckForExistingAndContinue (navigationController, user, false);
                    }
                });

            },TaskScheduler.FromCurrentSynchronizationContext());
        }