Universal Windows Platform – Contacts App

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 locate and select Visual Studio 2017.

vs2017-home

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

vs2017-file-new-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

vs2017-new-project

Step 4

Then in New Universal Windows Project you need to select the Target Version to be Windows 10 Creators Update (10.0; Build 15063) and the Minimum Version to be at least Windows 10 Anniversary Update (10.0; Build 14393) or Windows 10 Creators Update (10.0; Build 15063)

vs2017-platform

Step 5

From the Menu choose Project, then Add New Item…

vs2017-add-new-item

Step 6

From the Add New Item choose Visual C# from Installed then choose Code then select Code File and then in the Name as Library.cs and then select Add to add the file to the Project

vs2017-library

Step 7

Then 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 contacts_list = "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(contacts_list);
            }
            else
            {
                result = list.FirstOrDefault(s => s.DisplayName == contacts_list);
            }
        }
        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> Add(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> Edit(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> Delete(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;
    }
}

Step 8

Then in the Solution Explorer select MainPage.xaml

vs2017-library-mainpage

Step 9

From the Menu choose View and then Designer

vs2017-view-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>
	<Grid.RowDefinitions>
		<RowDefinition Height="*"/>
		<RowDefinition Height="Auto"/>
	</Grid.RowDefinitions>
	<CommandBar Grid.Row="1">
		<AppBarButton Name="Add" Icon="Add" Label="New" Click="Add_Click"/>
	</CommandBar>
	<ListBox Grid.Row="0" 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>

It should appear as such:

xaml-contacts-app

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

Once in the Code View, below the 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.Add(Add))
	{
		Display.ItemsSource = await library.ListAsync();
	}
}

private async void Edit_Click(object sender, RoutedEventArgs e)
{
	if (await library.Edit((AppBarButton)sender))
	{ 
		Display.ItemsSource = await library.ListAsync();
	}
}

private async void Delete_Click(object sender, RoutedEventArgs e)
{
	if (await library.Delete((AppBarButton)sender))
	{
		Display.ItemsSource = await library.ListAsync();
	}
}

It should then appear as such:

code-contacts-app

Step 13

Then in the Solution Explorer select Package.appxmanifest

vs2017-library-manifest

Step 14

Then from the Menu choose View and then Designer

vs2017-view-designer

Step 15

The Design View will be displayed for the Package.appxmanifest, then select the Capabilities Tab and Tick the Contacts option from the list of Capabilities

manifest-contact-app

Step 16

That completes the Universal Windows Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-debug

Step 17

Once started the Application should then appear

run-contacts-app

Step 18

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.

ran-contacts-app

Step 19

To Exit the application select Stop in Visual Studio

vs2017-stop

Creative Commons License

Advertisements

One thought on “Universal Windows Platform – Contacts App

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s