Contacts App demonstrates how to create an application which allows Contacts to be added, viewed, edited or deleted from an in-app Windows 10 Contacts List
Step 1
If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.
Step 2
Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…
Step 3
From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in a Name and select a Location and then select Ok to create the Project
Step 4
Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10, version 1803 (10.0; Build 17134) which is the April 2018 Update and the Minimum Version to be the same.
The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates
Step 5
Once done select from the Menu, Project, then Add New Item…
Step 6
From the Add New Item window select Visual C#, then Code from Installed then select Code File from the list, then type in the Name as Library.cs before selecting Add to add the file to the Project
Step 7
Once in the Code View for Library.cs the following should be entered:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Windows.ApplicationModel.Contacts; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; public class Item { public string Id { get; set; } public string Address { get; set; } public string DisplayName { get; set; } } public class Library { private const string app_title = "Contacts App"; private async Task<ContactStore> Store() { return await ContactManager.RequestStoreAsync(ContactStoreAccessType.AppContactsReadWrite); } private InputScope Scope(InputScopeNameValue value) { InputScope scope = new InputScope(); InputScopeName name = new InputScopeName() { NameValue = value }; scope.Names.Add(name); return scope; } private async Task<Contact> Dialog(Contact contact) { Thickness margin = new Thickness(5); TextBox firstname = new TextBox() { Text = contact.FirstName, Margin = margin, PlaceholderText = "First Name" }; TextBox lastname = new TextBox() { Text = contact.LastName, Margin = margin, PlaceholderText = "Last Name" }; TextBox email = new TextBox() { Text = contact?.Emails?.FirstOrDefault()?.Address ?? string.Empty, Margin = margin, PlaceholderText = "Email Address", InputScope = Scope(InputScopeNameValue.EmailSmtpAddress) }; StackPanel panel = new StackPanel() { Orientation = Orientation.Vertical }; panel.Children.Add(firstname); panel.Children.Add(lastname); panel.Children.Add(email); ContentDialog dialog = new ContentDialog() { Title = "Contact", PrimaryButtonText = "Save", CloseButtonText = "Cancel", Content = panel }; ContentDialogResult result = await dialog.ShowAsync(); if (result == ContentDialogResult.Primary) { contact.FirstName = firstname.Text; contact.LastName = lastname.Text; contact.Emails.Add(new ContactEmail() { Address = email.Text }); return contact; } return null; } private async Task<ContactList> GetAsync() { ContactList result = null; ContactStore store = await Store(); if (store != null) { IReadOnlyList<ContactList> list = await store.FindContactListsAsync(); if (list.Count == 0) { result = await store.CreateContactListAsync(app_title); } else { result = list.FirstOrDefault(s => s.DisplayName == app_title); } } return result; } private async Task<IReadOnlyList<Contact>> ListContactsAsync() { ContactStore store = await Store(); if (store != null) { ContactList list = await GetAsync(); if (list != null) { ContactReader reader = list.GetContactReader(); if (reader != null) { ContactBatch batch = await reader.ReadBatchAsync(); if (batch != null) { return batch.Contacts; } } } } return null; } private async Task<Contact> GetContactAsync(string id) { ContactList list = await GetAsync(); if (list != null) { return await list.GetContactAsync(id); } return null; } public async Task<List<Item>> ListAsync() { List<Item> results = new List<Item>(); IReadOnlyList<Contact> contacts = await ListContactsAsync(); foreach (Contact contact in contacts) { results.Add(new Item { Id = contact.Id, DisplayName = contact.DisplayName, Address = contact?.Emails?.FirstOrDefault()?.Address }); } return results; } public async Task<bool> AddAsync(AppBarButton button) { Contact contact = await Dialog(new Contact()); if (contact != null) { ContactList list = await GetAsync(); if (list != null) { await list.SaveContactAsync(contact); return true; } } return false; } public async Task<bool> EditAsync(AppBarButton button) { Item item = (Item)button.Tag; Contact contact = await GetContactAsync(item.Id); if (contact != null) { contact = await Dialog(contact); if (contact != null) { ContactList list = await GetAsync(); if (list != null) { await list.SaveContactAsync(contact); return true; } } } return false; } public async Task<bool> DeleteAsync(AppBarButton button) { Item item = (Item)button.Tag; Contact contact = await GetContactAsync(item.Id); if (contact != null) { ContactList list = await GetAsync(); if (list != null) { await list.DeleteContactAsync(contact); return true; } } return false; } }
There’s an Item class to store a string Id plus a string to store an Address and DisplayName for a Contact. The Library class has a const for the name of Contacts List, then there’s the ContactStore which is specific to the Application, there’s also a method Scope which returns InputScope based on a given InputScopeNameValue. The Dialog method has a Contact passed in and creates a ContentDialog with a given layout to include the First Name, Last Name and Email Address of a Contact object, it also returns the values that have been entered as a Contact when the Save button is selected.
The GetAsync method uses the ContactStore to get the ContactList for the application with FindContactListsAsync and creates one if it doesn’t exist with CreateContactListAsync, ListContactsAsync gets the a list of Contact from the ContactList via ContactReader with GetContactReader and ContactBatch with ReadBatchAsync. GetContactAsync gets an Contact from the ContactList with the GetContactAsync method. The ListAsync is used to populate the list of Item which is based from a list of Contact from the ListContactsAsync method. The Add method uses Dialog to create a new Contact and writes it to the ContactList with SaveContactAsync, Edit uses Dialog with an existing Contact from the list in the UI to make changes and then save this with SaveContactAsync and Delete will remove an existing Contact from the ContactList with the DeleteContactAsync method.
Step 8
In the Solution Explorer select MainPage.xaml
Step 9
From the Menu choose View and then Designer
Step 10
The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:
<Grid Margin="50"> <ListBox Name="Display" Loaded="Display_Loaded"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="HorizontalContentAlignment" Value="Stretch"/> </Style> </ListBox.ItemContainerStyle> <ListBox.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="40*"/> <ColumnDefinition Width="40*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <Grid Padding="5" Grid.Column="0" Background="{ThemeResource AccentButtonBackground}"> <TextBlock Text="{Binding DisplayName}" VerticalAlignment="Center" Foreground="{ThemeResource AccentButtonForeground}"/> </Grid> <Grid Padding="5" Grid.Column="1" Background="{ThemeResource AccentButtonForeground}"> <TextBlock Text="{Binding Address}" VerticalAlignment="Center" Foreground="{ThemeResource AccentButtonBackground}"/> </Grid> <StackPanel Grid.Column="3" Orientation="Horizontal"> <AppBarButton Name="Edit" Icon="Edit" Label="Edit" Tag="{Binding}" Click="Edit_Click"/> <AppBarButton Name="Delete" Icon="Delete" Label="Delete" Tag="{Binding}" Click="Delete_Click"/> </StackPanel> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> <CommandBar VerticalAlignment="Bottom"> <AppBarButton Name="Add" Icon="Add" Label="New" Click="Add_Click"/> </CommandBar>
The MainPage has a Listbox to display Contacts with an ItemTemplate to define how this looks. The second block of XAML is is the CommandBar which contains Add – to add a Contact.
Step 11
From the Menu choose View and then Code
Step 12
Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:
Library library = new Library(); private async void Display_Loaded(object sender, RoutedEventArgs e) { Display.ItemsSource = await library.ListAsync(); } private async void Add_Click(object sender, RoutedEventArgs e) { if (await library.AddAsync(Add)) { Display.ItemsSource = await library.ListAsync(); } } private async void Edit_Click(object sender, RoutedEventArgs e) { if (await library.EditAsync((AppBarButton)sender)) { Display.ItemsSource = await library.ListAsync(); } } private async void Delete_Click(object sender, RoutedEventArgs e) { if (await library.DeleteAsync((AppBarButton)sender)) { Display.ItemsSource = await library.ListAsync(); } }
Below the MainPage() Method an instance of the Library Class is created, then Display_Loaded is used to set the ListBox to show Contacts, Add_Click is used to create Contacts then updates the ListBox which is also done by Edit_Click to amend an existing Contact and Delete_Click is used to remove a Contact.
Step 13
In the Solution Explorer select Package.appxmanifest
Step 14
From the Menu choose View and then Designer
Step 15
Finally in the Package.appxmanifest select Capabilities and then make sure the Contacts option is checked
Step 16
That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application
Step 17
After the Application has started running you can then select Add to create a new Contact, this will display a Dialog where you can enter the First Name, Last Name and Email Address for a Contact. Contacts added will be displayed in the List where you can Edit or Delete them.
Step 18
To Exit the Application select the Close button in the top right of the Application
This example shows how easy it is to integrate with the built-in Contacts functionality of Windows 10 – you always need to provide your own UI to add / edit or view any Contacts but it’s quite straightforward to implement and is very similar to how Appointment works with Calendars. You can set many more properties of a Contact beyond those shown to add items such as multiple Email Address types and Telephone Numbers.