Skip to content

Instantly share code, notes, and snippets.

@igorkulman
Last active August 29, 2015 13:57
Show Gist options
  • Save igorkulman/9572748 to your computer and use it in GitHub Desktop.
Save igorkulman/9572748 to your computer and use it in GitHub Desktop.
Getting Address Book info in async/await way
/// <summary>
/// Address book wrapper
/// Needs address book permissions to work
/// </summary>
public class AddressBookService : IAddressBookService
{
/// <summary>
/// Gets a list of contacts in device address book
/// </summary>
/// <returns>List of contact</returns>
public Task<List<Contact>> GetContacts()
{
var t = new TaskCompletionSource<List<Contact>>();
SearchContacts(s => t.TrySetResult(s));
return t.Task;
}
/// <summary>
/// Gets a list of contacts in device address book filtered by search criteria
/// </summary>
/// <param name="searchTerm">Search term</param>
/// <param name="filter">Filter</param>
/// <returns>List of contact</returns>
public Task<List<Contact>> Search(string searchTerm, FilterKind filter)
{
var t = new TaskCompletionSource<List<Contact>>();
SearchContacts(s => t.TrySetResult(s),filter,searchTerm);
return t.Task;
}
/// <summary>
/// Gets a list of contacts in device address book filtered by search criteria
/// </summary>
/// <param name="searchTerm">Search term</param>
/// <param name="callback">Callback</param>
/// <param name="filter">Filter</param>
/// <returns>List of contact</returns>
private void SearchContacts(Action<List<Contact>> callback, FilterKind filter = FilterKind.None, string searchTerm = null)
{
var cons = new Contacts();
cons.SearchCompleted += (s, e) => callback(e.Results.ToList());
cons.SearchAsync(String.IsNullOrEmpty(searchTerm) ? string.Empty : searchTerm, filter, null);
}
}
private void ButtonContacts_Click(object sender, RoutedEventArgs e)
{
Contacts cons = new Contacts();
//Identify the method that runs after the asynchronous search completes.
cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(Contacts_SearchCompleted);
//Start the asynchronous search.
cons.SearchAsync(String.Empty, FilterKind.None, "Contacts Test #1");
}
void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
//Do something with the results.
MessageBox.Show(e.Results.Count().ToString());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment