Exemple #1
0
		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());
		}
 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());
 }
Exemple #3
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);
        }
Exemple #4
0
        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());
        }
        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());
        }
Exemple #6
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());
 }
Exemple #7
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();
            }
        }
        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;
        }
Exemple #9
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();
            }
        }
        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();
            }
        }
		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

		}
Exemple #12
0
		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());
		}
        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());
        }
		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();

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