Universal Windows Platform – Custom Checkbox

Custom Checkbox demonstrates how to create a custom Style for a CheckBox Control

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.

vs2017

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-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

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 the Project is created from the Solution Explorer select App.xaml

vs2017-app

Step 6

From the Menu choose View and then Designer

vs2017-view-designer

Step 7

Once in the Design View for App.xaml between the Application and /Application elements the following should be entered:

<Application.Resources>
	<Style x:Key="CustomCheckbox" TargetType="CheckBox">
		<Setter Property="Background" Value="Transparent"/>
		<Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/>
		<Setter Property="Padding" Value="5,5,0,0"/>
		<Setter Property="HorizontalAlignment" Value="Left"/>
		<Setter Property="VerticalAlignment" Value="Center"/>
		<Setter Property="HorizontalContentAlignment" Value="Left"/>
		<Setter Property="VerticalContentAlignment" Value="Top"/>
		<Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
		<Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
		<Setter Property="UseSystemFocusVisuals" Value="True"/>
		<Setter Property="Template">
			<Setter.Value>
				<ControlTemplate TargetType="CheckBox">
					<Grid BorderBrush="{TemplateBinding BorderBrush}"
					  BorderThickness="{TemplateBinding BorderThickness}"
					  Background="{TemplateBinding Background}">
						<Grid.ColumnDefinitions>
							<ColumnDefinition Width="30"/>
							<ColumnDefinition Width="*"/>
						</Grid.ColumnDefinitions>
						<VisualStateManager.VisualStateGroups>
							<VisualStateGroup x:Name="CombinedStates">
								<VisualState x:Name="UncheckedNormal"/>
								<VisualState x:Name="CheckedNormal">
									<Storyboard>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity"
										Storyboard.TargetName="InnerRectangle">
											<DiscreteObjectKeyFrame KeyTime="0" Value="1"/>
										</ObjectAnimationUsingKeyFrames>
									</Storyboard>
								</VisualState>
								<VisualState x:Name="CheckedPressed">
									<Storyboard>
										<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity"
										Storyboard.TargetName="InnerRectangle">
											<DiscreteObjectKeyFrame KeyTime="0" Value="1"/>
										</ObjectAnimationUsingKeyFrames>
									</Storyboard>
								</VisualState>
							</VisualStateGroup>
						</VisualStateManager.VisualStateGroups>
						<Grid>
							<Rectangle x:Name="NormalRectangle" Height="30" Width="30" RadiusY="10" RadiusX="10"  
							UseLayoutRounding="False" StrokeThickness="2" Stroke="Salmon" Fill="LightSalmon"/>
							<Rectangle x:Name="InnerRectangle" Height="20" Width="20" RadiusY="4" RadiusX="4"  
							UseLayoutRounding="False" StrokeThickness="2" Stroke="Goldenrod" Fill="Gold" Opacity="0"/>
						</Grid>
						<ContentPresenter x:Name="ContentPresenter" Grid.Column="1"
						AutomationProperties.AccessibilityView="Raw"
						ContentTemplate="{TemplateBinding ContentTemplate}"
						ContentTransitions="{TemplateBinding ContentTransitions}"
						Content="{TemplateBinding Content}"
						HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
						Margin="{TemplateBinding Padding}" TextWrapping="Wrap"
						VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
					</Grid>
				</ControlTemplate>
			</Setter.Value>
		</Setter>
	</Style>
</Application.Resources>

In the App.xaml there is a CustomCheckbox resource Style declared and it is a customised copy of the default ControlTemplate for a CheckBox Control with the Tick changed to appear as a rounded-rectangle within another rounded-rectangle.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-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:

<CheckBox Content="Checkbox" VerticalAlignment="Center" HorizontalAlignment="Center" Style="{StaticResource CustomCheckbox}"/>

The block of XAML represents the CheckBox Control with the Style of the the CustomCheckbox.

Step 11

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

vs2017-local-machine

Step 12

After the Application has started running you can tap the CheckBox to set it to Checked in the Application

ran-custom-checkbox

Step 13

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Advertisements

Universal Windows Platform – Jsonfile App

Jsonfile App demonstrates how to store JSON Data using DataContractJsonSerializer with an ObservableCollection of items being stored or retrieved

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.

vs2017

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 the Name as JsonfileApp and select a Location and then select Ok to create the Project
vs2017-new-project-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

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…

vs2017-project-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

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Json;
using Windows.Storage;
using Windows.UI.Xaml.Controls;

namespace JsonfileApp
{
    public class Music
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private string _album;
        private string _artist;
        private string _genre;

        public Music() { Id = Guid.NewGuid().ToString(); }

        public string Id { get; set; }
        public string Album { get { return _album; } set { _album = value; NotifyPropertyChanged(); } }
        public string Artist { get { return _artist; } set { _artist = value; NotifyPropertyChanged(); } }
        public string Genre { get { return _genre; } set { _genre = value; NotifyPropertyChanged(); } }
    }

    public class Library
    {
        private const string file_name = "file.json";

        private StorageFile _file;

        public static ObservableCollection Collection { get; private set; } = new ObservableCollection();

        private async void Read()
        {
            try
            {
                _file = await ApplicationData.Current.LocalFolder.GetFileAsync(file_name);
                using (Stream stream = await _file.OpenStreamForReadAsync())
                {
                    Collection = (ObservableCollection)
                        new DataContractJsonSerializer(typeof(ObservableCollection))
                        .ReadObject(stream);
                }
            }
            catch
            {
            }
        }

        private async void Write()
        {
            try
            {
                _file = await ApplicationData.Current.LocalFolder.CreateFileAsync(file_name,
                    CreationCollisionOption.ReplaceExisting);
                using (Stream stream = await _file.OpenStreamForWriteAsync())
                {
                    new DataContractJsonSerializer(typeof(ObservableCollection))
                        .WriteObject(stream, Collection);
                }
            }
            catch
            {
            }
        }

        public Library()
        {
            Read();
        }

        public void Add(FlipView display)
        {

            Collection.Insert(0, new Music());
            display.SelectedIndex = 0;
        }

        public void Save()
        {
            Write();
        }

        public void Remove(FlipView display)
        {
            if (display.SelectedItem != null)
            {
                Collection.Remove(Collection.Where(w => w.Id ==
                ((Music)display.SelectedValue).Id).Single());
                Write();
            }
        }

        public async void Delete(FlipView display)
        {
            try
            {
                Collection = new ObservableCollection();
                display.ItemsSource = Collection;
                _file = await ApplicationData.Current.LocalFolder.GetFileAsync(file_name);
                await _file.DeleteAsync();
            }
            catch
            {

            }
        }
    }
}

In the Library.cs there are using statements to include the necessary functionality. There is a Class for Music which has a PropertyChangedEventHandler and NotifyPropertyChanged Event trigger. It also has string Properties for Album, Artist and Genre plus an Id which will be represented by a guid. The Library Class has an ObservableCollection of the Music Class, Read uses ApplicationData with GetFileAsync to get stored data with DataContractJsonSerializer and ReadObject to read the ObservableCollection and Write uses ApplicationData with OpenStreamForWriteAsync to write stored data with DataContractJsonSerializer and WriteObject. The Constructor will call the Read Method, Add will insert items into the ObservableCollection of Music, Save will call the Write Method, Remove will delete items from the ObservableCollection based on the SelectedValue of the FlipView and call the Write Method and Delete will delete the file used for storage.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

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:


	
		
			
				
					
					
					
					
				
				
					
					
				
				Id:
				
				Album:
				
				Artist:
				
				Genre:
				
			
		
	


	
	
	
	

The first block of XAML the main user interface of the Application, this features a FlipView with a DataTemplate which contains a Grid which makes up the look-and-feel of a record made up of a Grid with rows of TextBlock Controls for Labels and TextBox for entry. The second block of XAML is is the CommandBar which contains Add – to create a new data item, Remove – to remove a data item, Save – to update the storage with the data and Delete to delete the data file.

Step 11

From the Menu choose View and then Code

vs2017-view-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 void Add_Click(object sender, RoutedEventArgs e)
{
	library.Add(Display);
}

private void Remove_Click(object sender, RoutedEventArgs e)
{
	library.Remove(Display);
}


private void Save_Click(object sender, RoutedEventArgs e)
{
	library.Save();
}

private void Delete_Click(object sender, RoutedEventArgs e)
{
	library.Delete(Display);
}

Below the MainPage() Method an instance of the Library Class is created, in Add_Click it calls the Add Method in the Library Class and Remove_Click calls the Remove Method. Save_Click calls the Save Method and Delete_Click will call the Delete Method in the Library Class

Step 13

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

vs2017-local-machine

Step 14

After the Application has started running you can tap the Add button, then enter Album, Artist and Genre then can use Save to store the data using JSON in the Application

ran-jsonfile-app

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Universal Windows Platform – Keyboard App

Keyboard App demonstrates how to create an on-screen Keyboard application using Button and StackPanel Controls

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.

vs2017

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-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

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…

vs2017-project-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

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

public enum Modes
{
    Character, Backspace, Tab, Enter, Shift, Space
}

public class Item
{
    public Modes Mode { get; set; }
    public string Content { get; set; }
    public string Normal { get; set; }
    public string Shift { get; set; }
    public string Value { get; set; }
}

public class Library
{
    private readonly string[][][] keys =
    {
        new string[][]
        {
            new string[] { "`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=" },
            new string[] { "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]" },
            new string[] { "a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'", "#" },
            new string[] { "\\", "z", "x", "c", "v", "b", "n", "m", ",", ".", "/" }
        },
        new string[][]
        {
            new string[] { "¬", "!", "\"", "£", "$", "%", "^", "&", "*", "(", ")", "_", "+" },
            new string[] { "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "{", "}" },
            new string[] { "A", "S", "D", "F", "G", "H", "J", "K", "L", ":", "@", "~" },
            new string[] { "|", "Z", "X", "C", "V", "B", "N", "M", "", "?" }
        },
    };

    private enum Chords { normal, shift };
    private enum Rows { top, upper, middle, lower, bottom };

    private Chords _chord = Chords.normal;

    public delegate void PressedEvent(Item item);
    public event PressedEvent Pressed;

    public static IEnumerable GetChildren(DependencyObject depObj) where T : DependencyObject
    {
        if (depObj != null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                if (child != null && child is T)
                {
                    yield return (T)child;
                }
                foreach (T childOfChild in GetChildren(child))
                {
                    yield return childOfChild;
                }
            }
        }
    }

    private Button Add(Item item, int width, int height)
    {
        Button button = new Button()
        {
            Height = height,
            Width = width,
            FontSize = 10,
            Padding = new Thickness(0),
            Margin = new Thickness(0.5),
            Content = item.Content,
            Tag = item,
        };
        button.Click += (object sender, RoutedEventArgs e) =>
        {
            button = (Button)sender;
            Pressed?.Invoke((Item)button.Tag);
        };
        return button;
    }

    private void Row(StackPanel panel, string[] normal, string[] shift)
    {
        for (int i = 0; i < normal.Length; i++)
        {
            Item item = new Item()
            {
                Mode = Modes.Character,
                Normal = normal[i],
                Shift = shift[i],
                Value = (_chord == Chords.shift) ? shift[i] : normal[i],
                Content = (_chord == Chords.shift) ? shift[i] : normal[i],
            };
            panel.Children.Add(Add(item, 24, 24));
        }
    }

    private void Layout(ref StackPanel panel)
    {
        // Top
        StackPanel top = new StackPanel()
        {
            Orientation = Orientation.Horizontal,
            BorderThickness = new Thickness(1, 0, 1, 0)
        };
        Row(top, keys[(int)Chords.normal][(int)Rows.top],
            keys[(int)Chords.shift][(int)Rows.top]);
        top.Children.Add(Add(new Item()
        {
            Mode = Modes.Backspace,
            Content = "BkSp",
        }, 42, 24));
        panel.Children.Add(top);
        // Upper
        StackPanel upper = new StackPanel()
        {
            Orientation = Orientation.Horizontal,
            BorderThickness = new Thickness(1, 0, 1, 0)
        };
        upper.Children.Add(Add(new Item()
        {
            Mode = Modes.Tab,
            Content = "↹",
        }, 34, 24));
        Row(upper, keys[(int)Chords.normal][(int)Rows.upper],
            keys[(int)Chords.shift][(int)Rows.upper]);
        upper.Children.Add(Add(new Item()
        {
            Mode = Modes.Enter,
            Content = "↵",
        }, 32, 24));
        panel.Children.Add(upper);
        // Middle
        StackPanel middle = new StackPanel()
        {
            Orientation = Orientation.Horizontal,
            BorderThickness = new Thickness(1, 0, 1, 0)
        };
        middle.Children.Add(new Canvas()
        {
            Width = 42,
            Height = 24
        });
        Row(middle, keys[(int)Chords.normal][(int)Rows.middle],
                    keys[(int)Chords.shift][(int)Rows.middle]);
        panel.Children.Add(middle);
        // Lower
        StackPanel lower = new StackPanel()
        {
            Orientation = Orientation.Horizontal,
            BorderThickness = new Thickness(1, 0, 1, 0)
        };
        lower.Children.Add(new Canvas()
        {
            Width = 50,
            Height = 24
        });
        Row(lower, keys[(int)Chords.normal][(int)Rows.lower],
                    keys[(int)Chords.shift][(int)Rows.lower]);
        panel.Children.Add(lower);
        // Bottom
        StackPanel bottom = new StackPanel()
        {
            Orientation = Orientation.Horizontal,
            BorderThickness = new Thickness(1, 0, 1, 0)
        };
        bottom.Children.Add(new Canvas()
        {
            Width = 60,
            Height = 24
        });
        bottom.Children.Add(Add(new Item()
        {
            Mode = Modes.Shift,
            Content = "Shift",
        }, 40, 24));
        bottom.Children.Add(Add(new Item()
        {
            Mode = Modes.Space,
            Content = "Space",
        }, 170, 24));
        bottom.Children.Add(Add(new Item()
        {
            Mode = Modes.Shift,
            Content = "Shift",
        }, 40, 24));
        panel.Children.Add(bottom);
    }

    private void Update(StackPanel input)
    {
        IEnumerable buttons = GetChildren(input);
        foreach (Button button in buttons)
        {
            if (button.Tag != null &&
                button.Tag.GetType() == typeof(Item))
            {
                Item item = (Item)button.Tag;
                if (item.Mode == Modes.Character)
                {
                    item.Value = (_chord == Chords.shift) ? item.Shift : item.Normal;
                    item.Content = item.Value;
                    button.Content = item.Content;
                    button.Tag = item;
                }
            }
        }
    }

    public void Init(ref StackPanel panel)
    {
        Layout(ref panel);
    }

    public void Output(TextBox display, StackPanel input, Item item)
    {
        string value = string.Empty;
        switch (item.Mode)
        {
            case Modes.Backspace:
                int start = display.SelectionStart == 0 ?
                    display.Text.Length + 1 : display.SelectionStart;
                display.Select(start - 1, 1);
                display.SelectedText = string.Empty;
                break;
            case Modes.Character:
                value = (_chord == Chords.shift) ? item.Shift : item.Normal;
                break;
            case Modes.Enter:
                value = "\n";
                break;
            case Modes.Shift:
                _chord = (_chord == Chords.shift) ? Chords.normal : Chords.shift;
                Update(input);
                break;
            case Modes.Space:
                value = " ";
                break;
            case Modes.Tab:
                value = "\t";
                break;
        }
        display.Text += value;
    }
}

In the Library.cs there are using statements to include the necessary functionality. There is an enum for the different Modes of the Keyboard, there is an Item Class to represent each of the Keys of the Keyboard and there is a custom event called PressedEvent. The Library Class contains a string[][][] to represent sets of keys and their rows, plus the Chords and Rows. There is a GetChildren Helper Method, the Add Method that will along with Row make up each set of Button Controls that will make up the Layout of the Keyboard. The Layout Method will create the look-and-feel of the Application, Update will toggle the state of the Keys, Init will help initialise the look-and-feel and Output will get any inputs from the Keyboard and produce the desired results.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

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="75*"/>
		<RowDefinition Height="25*"/>
	</Grid.RowDefinitions>
	<TextBox Name="Display" Grid.Row="0" AcceptsReturn="True" TextWrapping="Wrap"
		VerticalAlignment="Stretch" PreventKeyboardDisplayOnProgrammaticFocus="True"/>
	<Viewbox Grid.Row="1">
		<StackPanel Name="Input"/>
	</Viewbox>
</Grid>

The first block of XAML the main user interface of the Application, this features a Grid with two rows, the first is a TextBox which will be used for Output and the second row is a StackPanel where the Keyboard will appear in a ViewBox.

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:

Library library = new Library();
 
protected override void OnNavigatedTo(NavigationEventArgs e) 
{
	library.Init(ref Input);
	library.Pressed += (Item item) =>
	{
		library.Output(Display, Input, item);
	};
}

Below the MainPage() Method an instance of the Library Class is created and in OnNavigatedTo calls the Init Method in the Library Class and sets up the Pressed Event.

Step 13

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

vs2017-local-machine

Step 14

After the Application has started running you can tap any button on the Keyboard to type the selected character into the Application

ran-keyboard-app

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Universal Windows Platform – Adaptive App

Adaptive App demonstrates how to create an application that will respond to the Width of the Window when it is resized.

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.

vs2017

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 the Name as AdaptiveApp and select a Location and then select Ok to create the Project
vs2017-new-project-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

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…

vs2017-project-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

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using Windows.System;
using Windows.UI.Xaml.Controls;

namespace AdaptiveApp
{
    public class Setting
    {
        public string Name { get; set; }
        public string Icon { get; set; }
        public string Value { get; set; }
    }

    public class Library
    {
        public static List Settings
        {
            get
            {
                return new List()
                {
                    new Setting() { Name = "Display", Icon = "\uE7F8", Value = "display" },
                    new Setting() { Name = "Notifications", Icon = "\uE91C", Value = "notifications" },
                    new Setting() { Name = "Battery", Icon = "\uE8BE", Value = "batterysaver" },
                    new Setting() { Name = "Storage", Icon = "\uE8B7", Value = "storagesense" },
                    new Setting() { Name = "Data", Icon = "\uE774", Value = "datausage" },
                    new Setting() { Name = "Personalisation", Icon = "\uE771", Value = "personalization" },
                    new Setting() { Name = "Privacy", Icon = "\uE1F6", Value = "privacy" },
                    new Setting() { Name = "Developers", Icon = "\uEC7A", Value = "developers" }
                };
            }
        }

        public async void Launch(GridView display)
        {
            string value = ((Setting)(display.SelectedItem)).Value;
            await Launcher.LaunchUriAsync(new Uri($"ms-settings:{value}"));
        }
    }
}

In the Library.cs there are using statements to include the necessary functionality. There is a Setting Class with some string Properties and in the Library Class there is a static Property of a List of Setting and there is a Launch Method which will launch a given Windows 10 Setting from Settings.

Step 8

From the Solution Explorer select App.xaml

vs2017-app

Step 9

From the Menu choose View and then Designer

vs2017-view-designer

Step 10

The XAML View will be displayed and in this between the Application and /Application elements, enter the following XAML:

<Application.Resources>
	<DataTemplate x:Key="Large">
		<Grid Width="200" Height="200">
			<StackPanel VerticalAlignment="Center">
				<Viewbox Height="50" Width="50" HorizontalAlignment="Center">
					<TextBlock Text="{Binding Icon}" FontFamily="Segoe MDL2 Assets"
					Foreground="{ThemeResource SystemControlHighlightAccentBrush}"/>
				</Viewbox>
				<TextBlock Text="{Binding Name}" Margin="10" HorizontalAlignment="Center"
				Style="{StaticResource FlyoutPickerTitleTextBlockStyle}"/>
			</StackPanel>
		</Grid>
	</DataTemplate>
	<ItemsPanelTemplate x:Key="LargeItems">
		<ItemsWrapGrid Orientation="Horizontal" MaximumRowsOrColumns="4"/>
	</ItemsPanelTemplate>
	<DataTemplate x:Key="Small">
		<Grid Width="200">
			<StackPanel Orientation="Horizontal">
				<Viewbox Height="25" Width="25" HorizontalAlignment="Left">
					<TextBlock Text="{Binding Icon}" FontFamily="Segoe MDL2 Assets"
					Foreground="{ThemeResource SystemControlHighlightAccentBrush}"/>
				</Viewbox>
				<TextBlock Text="{Binding Name}" Margin="10" HorizontalAlignment="Left"
				Style="{StaticResource BodyTextBlockStyle}"/>
			</StackPanel>
		</Grid>
	</DataTemplate>
	<ItemsPanelTemplate x:Key="SmallItems">
		<ItemsWrapGrid Orientation="Horizontal" MaximumRowsOrColumns="1"/>
	</ItemsPanelTemplate>
</Application.Resources>

The block of XAML represents the Resources for the Application and contains a DataTemplate for both Large and Small items using a StackPanel to display content either as Horizontal optimised for a narrow Window and Vertical for a wider Window.

Step 11

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

Step 12

From the Menu choose View and then Designer

vs2017-view-designer

Step 13

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<GridView Name="Display" HorizontalAlignment="Center" VerticalAlignment="Center" 
SelectionChanged="Display_SelectionChanged"
ItemsSource="{x:Bind Path=local:Library.Settings}"/>
<VisualStateManager.VisualStateGroups>
	<VisualStateGroup>
		<VisualState>
			<VisualState.StateTriggers>
				<AdaptiveTrigger MinWindowWidth="720"/>
			</VisualState.StateTriggers>
			<VisualState.Setters>
				<Setter Target="Display.ItemTemplate" Value="{StaticResource Large}"/>
				<Setter Target="Display.ItemsPanel" Value="{StaticResource LargeItems}"/>
			</VisualState.Setters>
		</VisualState>
		<VisualState>
			<VisualState.StateTriggers>
				<AdaptiveTrigger MinWindowWidth="0"/>
			</VisualState.StateTriggers>
			<VisualState.Setters>
				<Setter Target="Display.ItemTemplate" Value="{StaticResource Small}"/>
				<Setter Target="Display.ItemsPanel" Value="{StaticResource SmallItems}"/>
			</VisualState.Setters>
		</VisualState>
	</VisualStateGroup>
</VisualStateManager.VisualStateGroups>

The block of XAML features a GridView which will have its ItemsSource set to the Settings in the Library Class and has the ItemTemplate set to the Large Resource from App.xaml.

Step 14

From the Menu choose View and then Code

vs2017-view-code

Step 15

Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:

Library library = new Library();

private void Display_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
	library.Launch(Display);
}

Below the MainPage() Method an instance of the Library Class is created, Display_SelectionChanged is triggered when the GridView is Selected and will Call the Launch Method in the Library Class.

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

vs2017-local-machine

Step 17

After the Application has started running you can select any of the options and launch any of the Settings or select the Restore button in the top right of the Appliciation and resize the Window, if it gets below a certain Width it will appear with the narrower Style or if larger with the wider Style.

ran-adaptive-app

Step 18

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Universal Windows Platform – Tailored App

Tailored App demonstrates how to create an application that will respond to the Width of the Window the Application is Launched in or has been last had it’s Width resized to its smallest possible value.

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.

vs2017

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 the Name as TailoredApp and select a Location and then select Ok to create the Project
vs2017-new-project-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

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…

vs2017-project-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

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using Windows.System;
using Windows.UI.Xaml.Controls;

namespace TailoredApp
{
    public class Setting
    {
        public string Name { get; set; }
        public string Icon { get; set; }
        public string Value { get; set; }
    }

    public class Library
    {
        public static List Settings
        {
            get
            {
                return new List()
                {
                    new Setting() { Name = "Display", Icon = "\uE7F8", Value = "display" },
                    new Setting() { Name = "Notifications", Icon = "\uE91C", Value = "notifications" },
                    new Setting() { Name = "Battery", Icon = "\uE8BE", Value = "batterysaver" },
                    new Setting() { Name = "Storage", Icon = "\uE8B7", Value = "storagesense" },
                    new Setting() { Name = "Data", Icon = "\uE774", Value = "datausage" },
                    new Setting() { Name = "Personalisation", Icon = "\uE771", Value = "personalization" },
                    new Setting() { Name = "Privacy", Icon = "\uE1F6", Value = "privacy" },
                    new Setting() { Name = "Developers", Icon = "\uEC7A", Value = "developers" }
                };
            }
        }

        public async void Launch(GridView display)
        {
            string value = ((Setting)(display.SelectedItem)).Value;
            await Launcher.LaunchUriAsync(new Uri($"ms-settings:{value}"));
        }
    }
}

In the Library.cs there are using statements to include the necessary functionality. There is a Setting Class with some string Properties and in the Library Class there is a static Property of a List of Setting and there is a Launch Method which will launch a given Windows 10 Setting from Settings.

Step 8

From the Solution Explorer select App.xaml

vs2017-app

Step 9

From the Menu choose View and then Designer

vs2017-view-designer

Step 10

The XAML View will be displayed and in this between the Application and /Application elements, enter the following XAML:

<Application.Resources>
	<DataTemplate x:Key="Large">
		<Grid Width="200" Height="200">
			<StackPanel VerticalAlignment="Center">
				<Viewbox Height="50" Width="50" HorizontalAlignment="Center">
					<TextBlock Text="{Binding Icon}" FontFamily="Segoe MDL2 Assets"
					Foreground="{ThemeResource SystemControlHighlightAccentBrush}"/>
				</Viewbox>
				<TextBlock Text="{Binding Name}" Margin="10" HorizontalAlignment="Center"
				Style="{StaticResource FlyoutPickerTitleTextBlockStyle}"/>
			</StackPanel>
		</Grid>
	</DataTemplate>
	<ItemsPanelTemplate x:Key="LargeItems">
		<ItemsWrapGrid Orientation="Horizontal" MaximumRowsOrColumns="4"/>
	</ItemsPanelTemplate>
	<DataTemplate x:Key="Small">
		<Grid Width="200">
			<StackPanel Orientation="Horizontal">
				<Viewbox Height="25" Width="25" HorizontalAlignment="Left">
					<TextBlock Text="{Binding Icon}" FontFamily="Segoe MDL2 Assets"
					Foreground="{ThemeResource SystemControlHighlightAccentBrush}"/>
				</Viewbox>
				<TextBlock Text="{Binding Name}" Margin="10" HorizontalAlignment="Left"
				Style="{StaticResource BodyTextBlockStyle}"/>
			</StackPanel>
		</Grid>
	</DataTemplate>
	<ItemsPanelTemplate x:Key="SmallItems">
		<ItemsWrapGrid Orientation="Horizontal" MaximumRowsOrColumns="1"/>
	</ItemsPanelTemplate>
</Application.Resources>

The block of XAML represents the Resources for the Application and contains a DataTemplate for both Large and Small items using a StackPanel to display content either as Horizontal optimised for a narrow screen and Vertical for a larger display.

Step 11

Once done select from the Menu, Project, then Add New Item…

vs2017-project-add-new-item

Step 12

From the Add New Item window select Visual C#, then XAML from Installed then select Blank Page from the list, then type in the Name as SecondaryPage.xaml before selecting Add to add the file to the Project

vs2017-add-new-item-carousel-control

Step 13

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<GridView Name="Display" HorizontalAlignment="Center" VerticalAlignment="Center" 
	SelectionChanged="Display_SelectionChanged"
	ItemTemplate="{StaticResource Small}"
	ItemsPanel="{StaticResource SmallItems}"
	ItemsSource="{x:Bind Path=local:Library.Settings}"/>

The block of XAML features a GridView which will have its ItemsSource set to the Settings in the Library Class and has the ItemTemplate set to the Small Resource from App.xaml.

Step 14

From the Menu choose View and then Code

vs2017-view-code

Step 15

Once in the Code View, below the end of public SecondaryPage() { … } the following Code should be entered:

Library library = new Library();

private void Display_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
	library.Launch(Display);
}

Below the MainPage() Method an instance of the Library Class is created, Display_SelectionChanged is triggered when the GridView is Selected and will Call the Launch Method in the Library Class.

Step 16

From the Solution Explorer select App.xaml

vs2017-app

Step 17

Once in the Code View for App.xaml.cs above rootFrame.Navigate(typeof(MainPage), e.Arguments); in the protected override void OnLaunched(LaunchActivatedEventArgs e) { … } Event handler the following should be entered:

if (Window.Current.Bounds.Width < 600)
{
	rootFrame.Navigate(typeof(SecondaryPage), e.Arguments);
	Window.Current.Activate();
	return;
}

This Code will check if the Window has a Width that is less than 600 Pixels, if so it will Navigate to the SecondaryPage.

Step 18

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

Step 19

From the Menu choose View and then Designer

vs2017-view-designer

Step 20

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<GridView Name="Display" HorizontalAlignment="Center" VerticalAlignment="Center" 
	SelectionChanged="Display_SelectionChanged"
	ItemTemplate="{StaticResource Large}"
	ItemsPanel="{StaticResource LargeItems}"
	ItemsSource="{x:Bind Path=local:Library.Settings}"/>

The block of XAML features a GridView which will have its ItemsSource set to the Settings in the Library Class and has the ItemTemplate set to the Large Resource from App.xaml.

Step 21

From the Menu choose View and then Code

vs2017-view-code

Step 22

Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:

Library library = new Library();

private void Display_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
	library.Launch(Display);
}

Below the MainPage() Method an instance of the Library Class is created, Display_SelectionChanged is triggered when the GridView is Selected and will Call the Launch Method in the Library Class.

Step 23

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

vs2017-local-machine

Step 24

After the Application has started running you can select any of the options and launch any of the Settings present in the GridView then the Window should have it’s Width set to a small as possible, you may need to select the Restore button in the top right of the Applciation.

run-tailored-app

Step 25

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Step 26

Then back in Visual Studio select the Local Machine to run the Application again

vs2017-local-machine

Step 26

After the Application has started running it will use the SecondaryPage.xaml Style rather than the MainPage.xaml and you can select any of the options and launch any of the Settings present in the GridView.

ran-tailored-app

Step 27

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Universal Windows Platform – Recognition App

Recognition App demonstrates how to use OcrEngine to recognise text within an Image that can be saved from the contents of the TextBox.

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.

vs2017

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-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

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…

vs2017-project-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

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Globalization;
using Windows.Graphics.Imaging;
using Windows.Media.Ocr;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

public class Library
{
    private const string app_title = "Recognition App";
    private const string text_file_extension = ".txt";
    private const string image_file_extension = ".jpg";

    public async Task ConfirmAsync(string content, string title, string ok, string cancel)
    {
        bool result = false;
        MessageDialog dialog = new MessageDialog(content, title);
        dialog.Commands.Add(new UICommand(ok, new UICommandInvokedHandler((cmd) => result = true)));
        dialog.Commands.Add(new UICommand(cancel, new UICommandInvokedHandler((cmd) => result = false)));
        await dialog.ShowAsync();
        return result;
    }

    public async void NewAsync(Image source, TextBox target)
    {
        if (await ConfirmAsync("Create New?", app_title, "Yes", "No"))
        {
            source.Source = null;
            target.Text = string.Empty;
        }
    }

    public async void OpenAsync(Image source, TextBox target)
    {
        try
        {
            FileOpenPicker picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };
            picker.FileTypeFilter.Add(text_file_extension);
            picker.FileTypeFilter.Add(image_file_extension);
            StorageFile file = await picker.PickSingleFileAsync();
            switch (file.FileType)
            {
                case text_file_extension:
                    target.Text = await FileIO.ReadTextAsync(file);
                    break;
                case image_file_extension:
                    using (IRandomAccessStream stream = await file.OpenReadAsync())
                    {
                        BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(stream);
                        SoftwareBitmap softwareBitmap = await bitmapDecoder.GetSoftwareBitmapAsync(
                            BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
                        OcrEngine engine = OcrEngine.TryCreateFromLanguage(new Language("en-us"));
                        OcrResult ocrResult = await engine.RecognizeAsync(softwareBitmap);
                        target.Text = ocrResult.Text;
                        stream.Seek(0);
                        BitmapImage image = new BitmapImage();
                        image.SetSource(stream);
                        source.Source = image;
                    }
                    break;
                default:
                    break;
            }
        }
        catch
        {

        }
    }

    public async void SaveAsync(Image source, TextBox target)
    {
        try
        {
            FileSavePicker picker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };
            picker.FileTypeChoices.Add("Image File", new List() { image_file_extension });
            picker.FileTypeChoices.Add("Text File", new List() { text_file_extension });
            picker.DefaultFileExtension = text_file_extension;
            StorageFile file = await picker.PickSaveFileAsync();
            switch (file.FileType)
            {
                case text_file_extension:
                    await FileIO.WriteTextAsync(file, target.Text);
                    break;
                case image_file_extension:
                    using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
                        RenderTargetBitmap render = new RenderTargetBitmap();
                        await render.RenderAsync(target);
                        IBuffer buffer = await render.GetPixelsAsync();
                        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                        (uint)render.PixelWidth, (uint)render.PixelHeight, 96.0, 96.0, buffer.ToArray());
                        await encoder.FlushAsync();
                        buffer = null;
                        encoder = null;
                    }
                    break;
                default:
                    break;
            }
        }
        catch
        {

        }
    }

    public void Sample(ref TextBox target)
    {
        target.Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris non massa diam. " +
            "Nunc luctus non lorem id imperdiet. Nunc quis mi nec enim malesuada commodo mollis eget nisl. " +
            "Sed vulputate in purus eu vulputate. Quisque commodo eu odio et malesuada. Duis porttitor, " +
            "lectus ut egestas placerat, purus nisi elementum diam, congue lacinia erat lectus sit amet felis. " +
            "Proin suscipit lobortis bibendum. Aliquam erat volutpat. Nunc vitae nulla nunc.";
    }
}

In the Library.cs there are using statements to include the necessary functionality. The ConfirmAsync Method is used to create a dialog with two buttons, this is used by the NewAsync method to confirm if a new document is to be created, if the answer is “Yes” then the TextBox will have it’s contents set to an empty string. OpenAsync is used to set the TextBox contents to the contents of a file – this is opened with a FileOpenPicker using ReadTextAsync and can also open a file for the Image then using the OcrEngine to recognise any text in this. SaveAsync is used to get the contents of the TextBox and then this is saved to a file, using the FileSavePicker and WriteTextAsync and can also save the contents of the TextBox as an Image. Then there is a Sample Method which will set the TextBox to some example text.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

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 HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
	<Grid.RowDefinitions>
		<RowDefinition Height="50*"/>
		<RowDefinition Height="50*"/>
	</Grid.RowDefinitions>
	<Image Grid.Row="0" Name="Source"/>
	<TextBox Grid.Row="1" Name="Target" AcceptsReturn="True" TextWrapping="Wrap"/>
</Grid>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="Page2" Label="New" Click="New_Click"/>
	<AppBarButton Icon="OpenFile" Label="Open" Click="Open_Click"/>
	<AppBarButton Icon="Save" Label="Save" Click="Save_Click"/>
	<AppBarButton Icon="Document" Label="Sample" Click="Sample_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a Grid with two rows, the first is an Image which will be set when one has been opened and the text recognised and the second row is a TextBox where any text may be entered or opened and then saved as an image to be opened and recognised. The second block of XAML is is the CommandBar which contain New which can set the TextBox to empty text, Open which will allow a file to be opened and Save will allow a file to be saved and Sample is used to insert some example text.

Step 11

From the Menu choose View and then Code

vs2017-view-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 void New_Click(object sender, RoutedEventArgs e)
{
	library.NewAsync(Target);
}

private void Open_Click(object sender, RoutedEventArgs e)
{
	library.OpenAsync(Source, Target);
}

private void Save_Click(object sender, RoutedEventArgs e)
{
	library.SaveAsync(Source, Target);
}

private void Sample_Click(object sender, RoutedEventArgs e)
{
	library.Sample(ref Target);
}

Below the MainPage() Method an instance of the Library Class is created, New_Click, Open_Click and Save_Click Methods call the related methods in the Library Class as does Sample_Click.

Step 13

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

vs2017-local-machine

Step 14

After the Application has started running you can enter any text or use Sample then use Save to store an Image file of the text, then Open to recognise a stored Image file as text in the Application

ran-recognition-app

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Universal Windows Platform – Compression App

Compression App demonstrates how to Compress with Compressor and Decompress with Decompressor Text with a given CompressAlgorithm.

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.

vs2017

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-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

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…

vs2017-project-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

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;
using Windows.Storage.Compression;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;

public class Library
{
    private const string app_title = "Compression App";
    private const string text_file_extension = ".txt";
    private const string compressed_file_extension = ".compressed";
    private readonly CompressAlgorithm compression_algorithm = CompressAlgorithm.Lzms;

    public void Show(string content, string title)
    {
        IAsyncOperation command = new MessageDialog(content, title).ShowAsync();
    }

    public async Task ConfirmAsync(string content, string title, string ok, string cancel)
    {
        bool result = false;
        MessageDialog dialog = new MessageDialog(content, title);
        dialog.Commands.Add(new UICommand(ok, new UICommandInvokedHandler((cmd) => result = true)));
        dialog.Commands.Add(new UICommand(cancel, new UICommandInvokedHandler((cmd) => result = false)));
        await dialog.ShowAsync();
        return result;
    }

    public async void NewAsync(TextBox display)
    {
        if (await ConfirmAsync("Create New?", app_title, "Yes", "No"))
        {
            display.Text = string.Empty;
        }
    }

    public async void OpenAsync(TextBox display)
    {
        try
        {
            FileOpenPicker picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };
            picker.FileTypeFilter.Add(text_file_extension);
            picker.FileTypeFilter.Add(compressed_file_extension);
            StorageFile file = await picker.PickSingleFileAsync();
            switch (file.FileType)
            {
                case text_file_extension:
                    display.Text = await FileIO.ReadTextAsync(file);
                    break;
                case compressed_file_extension:
                    using (MemoryStream stream = new MemoryStream())
                    using (IInputStream input = await file.OpenSequentialReadAsync())
                    using (Decompressor decompressor = new Decompressor(input))
                    using (IRandomAccessStream output = stream.AsRandomAccessStream())
                    {
                        long inputSize = input.AsStreamForRead().Length;
                        ulong outputSize = await RandomAccessStream.CopyAsync(decompressor, output);
                        output.Seek(0);
                        display.Text = await new StreamReader(output.AsStream()).ReadToEndAsync();
                        Show($"Decompressed {inputSize} bytes to {outputSize} bytes", app_title);
                    }
                    break;
                default:
                    break;
            }
        }
        catch
        {

        }
    }

    public async void SaveAsync(TextBox display)
    {
        try
        {
            FileSavePicker picker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };
            picker.FileTypeChoices.Add("Text File", new List() { text_file_extension });
            picker.FileTypeChoices.Add("Compressed File", new List() { compressed_file_extension });
            picker.DefaultFileExtension = text_file_extension;
            StorageFile file = await picker.PickSaveFileAsync();
            switch (file.FileType)
            {
                case text_file_extension:
                    await FileIO.WriteTextAsync(file, display.Text);
                    break;
                case compressed_file_extension:
                    using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(display.Text)))
                    using (IRandomAccessStream input = stream.AsRandomAccessStream())
                    using (IRandomAccessStream output = await file.OpenAsync(FileAccessMode.ReadWrite))
                    using (Compressor compressor = new Compressor(output.GetOutputStreamAt(0), compression_algorithm, 0))
                    {
                        ulong inputSize = await RandomAccessStream.CopyAsync(input, compressor);
                        bool finished = await compressor.FinishAsync();
                        ulong outputSize = output.Size;
                        Show($"Compressed {inputSize} bytes to {outputSize} bytes", app_title);
                    }
                    break;
                default:
                    break;
            }
        }
        catch
        {

        }
    }

    public void Sample(ref TextBox display)
    {
        StringBuilder text = new StringBuilder();
        for (int i = 0; i < 10; i++)
        {
            text.AppendLine("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris non massa diam. " +
            "Nunc luctus non lorem id imperdiet. Nunc quis mi nec enim malesuada commodo mollis eget nisl. " +
            "Sed vulputate in purus eu vulputate. Quisque commodo eu odio et malesuada. Duis porttitor, " +
            "lectus ut egestas placerat, purus nisi elementum diam, congue lacinia erat lectus sit amet felis. " +
            "Proin suscipit lobortis bibendum. Aliquam erat volutpat. Nunc vitae nulla nunc.\n");
        }
        display.Text = text.ToString();
    }
}

In the Library.cs there are using statements to include the necessary functionality. The Show Method is used to display a MessageDialog and the ConfirmAsync Method is used to create a dialog with two buttons, this is used by the NewAsync method to confirm if a new document is to be created, if the answer is “Yes” then the TextBox will have it’s contents set to an empty string. OpenAsync is used to set the TextBox contents to the contents of a file – this is opened with a FileOpenPicker using ReadTextAsync and can also Decompress a compressed File with Decompressor. SaveAsync is used to get the contents of the TextBox and then this is saved to a file, using the FileSavePicker and WriteTextAsync and can also Compress a File with Compressor. Then there is a Sample Method which will set the TextBox to some example text.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

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:

<TextBox Name="Display" AcceptsReturn="True" TextWrapping="Wrap" VerticalAlignment="Stretch"/>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="Page2" Label="New" Click="New_Click"/>
	<AppBarButton Icon="OpenFile" Label="Open" Click="Open_Click"/>
	<AppBarButton Icon="Save" Label="Save" Click="Save_Click"/>
	<AppBarButton Icon="Document" Label="Sample" Click="Sample_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a TextBox where any text may be entered that can be compressed or decompressed. The second block of XAML is is the CommandBar which contain New which can set the TextBox to empty text, Open which will allow a file to be opened and Save will allow a file to be saved. Encrypt is used to perform encryption and Sample is used to insert some example text.

Step 11

From the Menu choose View and then Code

vs2017-view-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 void New_Click(object sender, RoutedEventArgs e)
{
	library.NewAsync(Display);
}

private void Open_Click(object sender, RoutedEventArgs e)
{
	library.OpenAsync(Display);
}

private void Save_Click(object sender, RoutedEventArgs e)
{
	library.SaveAsync(Display);
}

private void Sample_Click(object sender, RoutedEventArgs e)
{
	library.Sample(ref Display);
}

Below the MainPage() Method an instance of the Library Class is created, New_Click, Open_Click and Save_Click Methods call the related methods in the Library Class as does Sample_Click.

Step 13

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

vs2017-local-machine

Step 14

After the Application has started running you can enter any text or insert some example text with Sample then use Save to store a Compressed version of the text or Open to decompress a stored file as text in the Application

ran-compression-app

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Universal Windows Platform – Cryptograph App

Cryptograph App demonstrates how to Encrypt and Decrypt Text with a CryptographicBuffer.

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.

vs2017

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-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

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…

vs2017-project-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

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Controls;

public class Library
{
    private const string file_extension = ".txt";

    private static readonly byte[] values =
    {
        1, 4, 8, 15, 16, 23, 42, 108, 1, 4, 8, 15, 16, 23, 42, 108,
        1, 4, 8, 15, 16, 23, 42, 108, 1, 4, 8, 15, 16, 23, 42, 108
    };
    private static readonly SymmetricKeyAlgorithmProvider algorithm =
        SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
    private static readonly CryptographicKey key =
        algorithm.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(values));
    private static readonly IBuffer iv = values.AsBuffer();

    public async void OpenAsync(TextBox display)
    {
        try
        {
            FileOpenPicker picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };
            picker.FileTypeFilter.Add(file_extension);
            StorageFile file = await picker.PickSingleFileAsync();
            display.Text = await FileIO.ReadTextAsync(file);
        }
        catch
        {

        }
    }

    public async void SaveAsync(TextBox display)
    {
        try
        {
            FileSavePicker picker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
                DefaultFileExtension = file_extension,
                SuggestedFileName = "Document"
            };
            picker.FileTypeChoices.Add("Plain Text", new List() { file_extension });
            StorageFile file = await picker.PickSaveFileAsync();
            if (file != null)
            {
                await FileIO.WriteTextAsync(file, display.Text);
            }
        }
        catch
        {

        }
    }

    public void Encrypt(ref TextBox display)
    {
        try
        {
            IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(display.Text,
            BinaryStringEncoding.Utf8);
            IBuffer bufferEncrypt = CryptographicEngine.Encrypt(key, buffer, iv);
            display.Text = CryptographicBuffer.EncodeToBase64String(bufferEncrypt);
        }
        catch
        {

        }
    }

    public void Decrypt(ref TextBox display)
    {
        try
        {
            IBuffer buffer = Convert.FromBase64String(display.Text).AsBuffer();
            IBuffer bufferDecrypt = CryptographicEngine.Decrypt(key, buffer, iv);
            display.Text = CryptographicBuffer.ConvertBinaryToString(
                BinaryStringEncoding.Utf8, bufferDecrypt);
        }
        catch
        {

        }
    }
}

In the Library.cs there are using statements to include the necessary functionality. There are Members that help with encryption including SymmetricKeyAlgorithmProvider, CryptographicKey and a IBuffer. OpenAsync is used to set the TextBox contents to the contents of a file – this is opened with a FileOpenPicker using ReadTextAsync, SaveAsync is used to get the contents of the TextBox and then this is saved to a file, using the FileSavePicker and WriteTextAsync. The Encrypt Method will encode any text so it is encrypted and Decrypt is used to decode any text so it is decrypted.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

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:

<TextBox Name="Display" AcceptsReturn="True" TextWrapping="Wrap" VerticalAlignment="Stretch"/>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="OpenFile" Label="Open" Click="Open_Click"/>
	<AppBarButton Icon="Save" Label="Save" Click="Save_Click"/>
	<AppBarButton Name="Encrypt" Icon="ProtectedDocument" Label="Encrypt" Click="Encrypt_Click"/>
	<AppBarButton Name="Decrypt" Icon="Document" Label="Decrypt" Click="Decrypt_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a TextBox where any text may be entered that can be decrypted or encrypted. The second block of XAML is is the CommandBar which contain Open which will allow a file to be opened and Save will allow a file to be saved. Encrypt is used to perform encryption and Decrypt is used to perform decryption.

Step 11

From the Menu choose View and then Code

vs2017-view-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 void Open_Click(object sender, RoutedEventArgs e)
{
	library.OpenAsync(Display);
}

private void Save_Click(object sender, RoutedEventArgs e)
{
	library.SaveAsync(Display);
}

private void Encrypt_Click(object sender, RoutedEventArgs e)
{
	library.Encrypt(ref Display);
}

private void Decrypt_Click(object sender, RoutedEventArgs e)
{
	library.Decrypt(ref Display);
}

Below the MainPage() Method an instance of the Library Class is created, Open_Click and Save_Click Methods call the related methods in the Library Class as does Encrypt_Click and Decrypt_Click.

Step 13

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

vs2017-local-machine

Step 14

After the Application has started running you can enter any text then use Encrypt to encode the text or Decrypt to decode the text in the Application

ran-cryptograph-app

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Universal Windows Platform – Appointment App

Appointment App demonstrates how to add an Appointment to the Calendar in Windows 10.

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.

vs2017

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-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

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…

vs2017-project-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

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using Windows.ApplicationModel.Appointments;
using Windows.Foundation;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

public class Library
{
    private const string app_title = "Appointment App";

    public void Show(string content, string title)
    {
        IAsyncOperation command = new MessageDialog(content, title).ShowAsync();
    }

    public void New(DatePicker startDate, TimePicker startTime, TextBox subject,
        TextBox location, TextBox details, ComboBox duration, CheckBox allDay)
    {
        startDate.Date = DateTime.Now;
        startTime.Time = DateTime.Now.TimeOfDay;
        subject.Text = string.Empty;
        location.Text = string.Empty;
        details.Text = string.Empty;
        duration.SelectedIndex = 0;
        allDay.IsChecked = false;
    }

    public async void Add(object sender, DatePicker startDate, TimePicker startTime,
        TextBox subject, TextBox location, TextBox details, ComboBox duration, CheckBox allDay)
    {
        FrameworkElement element = (FrameworkElement)sender;
        GeneralTransform transform = element.TransformToVisual(null);
        Point point = transform.TransformPoint(new Point());
        Rect rect = new Rect(point, new Size(element.ActualWidth, element.ActualHeight));
        DateTimeOffset date = startDate.Date;
        TimeSpan time = startTime.Time;
        int minutes = int.Parse((string)((ComboBoxItem)duration.SelectedItem).Tag);
        Appointment appointment = new Appointment()
        {
            StartTime = new DateTimeOffset(date.Year, date.Month, date.Day,
            time.Hours, time.Minutes, 0, TimeZoneInfo.Local.GetUtcOffset(DateTime.Now)),
            Subject = subject.Text,
            Location = location.Text,
            Details = details.Text,
            Duration = TimeSpan.FromMinutes(minutes),
            AllDay = (bool)allDay.IsChecked
        };
        string id = await AppointmentManager.ShowAddAppointmentAsync(appointment, rect, Placement.Default);
        if (string.IsNullOrEmpty(id))
        {
            Show("Appointment not Added", app_title);
        }
        else
        {
            Show($"Appointment {id} Added", app_title);
        }
    }

    public async void Calendar(DatePicker startDate, TimePicker startTime)
    {
        await AppointmentManager.ShowTimeFrameAsync(startDate.Date, startTime.Time);
    }
}

In the Library.cs there are using statements to include the necessary functionality. There is a Show Method that will display a MessageDialog, New is used to reset the Controls in the Application and Add is used to create an Appointment it also requires a location in which to use ShowAddAppointmentAsync with and a MessageDialog to display if this has been successful or not. CalendarAsync is used to display the Calendar in Windows 10.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

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:

<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
	<TextBlock Margin="10">Start:</TextBlock>
	<DatePicker Name="StartDate" Margin="5"/>
	<TimePicker Name="StartTime" Margin="5"/>
	<TextBlock Margin="10">Subject:</TextBlock>
	<TextBox Name="Subject" Width="300" MaxLength="255" HorizontalAlignment="Left"/>
	<TextBlock Margin="10">Location:</TextBlock>
	<TextBox Name="Location" Width="300" MaxLength="32768" HorizontalAlignment="Left"/>
	<TextBlock Margin="10">Details:</TextBlock>
	<TextBox Name="Details" Width="300" MaxLength="1073741823" HorizontalAlignment="Left"/>
	<TextBlock  Margin="10">Duration:</TextBlock>
	<ComboBox x:Name="Duration" SelectedIndex="0">
		<ComboBoxItem Tag="30">30 Minutes</ComboBoxItem>
		<ComboBoxItem Tag="60">1 Hour</ComboBoxItem>
	</ComboBox>
	<CheckBox Name="AllDay" Content="All Day" Margin="10"/>
</StackPanel>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="Page2" Label="New" Click="New_Click"/>
	<AppBarButton Icon="Add" Label="Add" Click="Add_Click"/>
	<AppBarButton Icon="Calendar" Label="Calendar" Click="Calendar_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a StackPanel containing TextBlock Controls to act as Labels, plus a DatePicker and TimePicker to select when event occur and there are TextBox Controls for the Subject, Location and Details of the event with a ComboBox for Duration and a CheckBox to denote if an event occurs All Day. The second block of XAML is is the CommandBar which contains New – to reset the Control, Add to add an Appointment and Calendar to view the Calendar in Windows 10 to allow the viewing of added events.

Step 11

From the Menu choose View and then Code

vs2017-view-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 void New_Click(object sender, RoutedEventArgs e)
{
	library.New(StartDate, StartTime, Subject, Location, Details, Duration, AllDay);
}

private void Add_Click(object sender, RoutedEventArgs e)
{
	library.Add(sender, StartDate, StartTime, Subject, Location, Details, Duration, AllDay);
}

private void Calendar_Click(object sender, RoutedEventArgs e)
{
	library.Calendar(StartDate, StartTime);
}

Below the MainPage() Method an instance of the Library Class is created, then New_Click is used to call the New method to reset the Application and Add_Click calls the Add Method and Calendar_Click calls the Calendar Method in the Library Class

Step 13

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

vs2017-local-machine

Step 14

After the Application has started running you can enter details for an Appointment then use Add to add it or you can use Calendar to view any appointments added by the Application

ran-appointment-app

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Universal Windows Platform – Sound Game

Sound Game demonstrates how to create a simple game to play sounds using a MediaElement with a provided frequency as an audio stream.

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.

vs2017

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-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

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…

vs2017-project-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

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

public class Library
{
    private readonly Dictionary _notes = new Dictionary()
    {
        { "C", 261.6 }, { "C#", 277.2 }, { "D", 293.7 },
        { "D#", 311.1 } , { "E", 329.6 }, { "F", 349.2 },
        { "F#", 370.0 }, { "G", 392.0 }, { "G#", 415.3 },
        { "A", 440.0 }, { "A#", 466.2 }, { "B", 493.9 }
    };

    private void Play(double note)
    {
        MediaElement playback = new MediaElement();
        IRandomAccessStream stream = new InMemoryRandomAccessStream();
        BinaryWriter writer = new BinaryWriter(stream.AsStream());
        int formatChunkSize = 16;
        int headerSize = 8;
        short formatType = 1;
        short tracks = 1;
        int samplesPerSecond = 44100;
        short bitsPerSample = 16;
        short frameSize = (short)(tracks * ((bitsPerSample + 7) / 8));
        int bytesPerSecond = samplesPerSecond * frameSize;
        int waveSize = 4;
        int data = 0x61746164;
        int samples = 88200 * 4;
        int dataChunkSize = samples * frameSize;
        int fileSize = waveSize + headerSize + formatChunkSize + headerSize + dataChunkSize;
        double frequency = note * 1.5;
        writer.Write(0x46464952); // RIFF
        writer.Write(fileSize);
        writer.Write(0x45564157); // WAVE
        writer.Write(0x20746D66); // Format
        writer.Write(formatChunkSize);
        writer.Write(formatType);
        writer.Write(tracks);
        writer.Write(samplesPerSecond);
        writer.Write(bytesPerSecond);
        writer.Write(frameSize);
        writer.Write(bitsPerSample);
        writer.Write(data);
        writer.Write(dataChunkSize);
        for (int i = 0; i 
        {
            button = (Button)sender;
            int note = Grid.GetColumn(button);
            Play(_notes[_notes.Keys.ElementAt(note)]);
        };
        button.SetValue(Grid.ColumnProperty, column);
        grid.Children.Add(button);
    }

    private void Layout(ref Grid Grid)
    {
        Grid.Children.Clear();
        Grid.ColumnDefinitions.Clear();
        Grid.RowDefinitions.Clear();
        // Setup Grid
        for (int Column = 0; (Column < _notes.Count); Column++)
        {
            Grid.ColumnDefinitions.Add(new ColumnDefinition());
            Add(Grid, Column);
        }
    }

    public void New(ref Grid grid)
    {
        Layout(ref grid);
    }
}

In the Library.cs there are using statements to include the necessary functionality. There is a Dictionary of string and double to store the musical notes that will be played and their approximate audio frequency. The Play Method is used to play a musical note with a MediaElement and a InMemoryRandomAccessStream which will be used to help create the audio with a BinaryWriter to create a WAVE audio stream that will be written to with the given frequency to produce the Samples that will create the required musical note.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

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:


	


	

The first block of XAML the main user interface of the Application, this features a ViewBox containing a Grid Control that will be the look-and-feel of the game. The second block of XAML is is the CommandBar which contains New – to start the game.

Step 11

From the Menu choose View and then Code

vs2017-view-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 void New_Click(object sender, RoutedEventArgs e)
{
	library.New(ref Display);
}

Below the MainPage() Method an instance of the Library Class is created, then New_Click is used to call the New method to setup the game in the Library Class

Step 13

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

vs2017-local-machine

Step 14

After the Application has started running use New to start then can Play sounds by tapping the buttons in the Application.

ran-sound-game

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License