Universal Windows Platform – Four in Row

Four in Row demonstrates how to create a simple two-player game where the objective is to get four pieces in a row in either horizontal, vertical or diagonal directions.

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.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;

public class Library
{
    private const string app_title = "Four In Row";
    private const int size = 7;

    private bool _won = false;
    private int[,] _board = new int[size, size];
    private int _player = 0;

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

    public async Task<bool> 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 bool Winner(int column, int row)
    {
        int total = 3; // Total Excluding Current
        int value = 0; // Value in Line
        int amend = 0; // Add or Remove
        // Check Vertical
        do
        {
            value++;
        }
        while (row + value < size &&
        _board[column, row + value] == _player);
        if (value > total)
        {
            return true;
        }
        value = 0;
        amend = 0;
        // Check Horizontal - From Left
        do
        {
            value++;
        }
        while (column - value >= 0 &&
        _board[column - value, row] == _player);
        if (value > total)
        {
            return true;
        }
        value -= 1; // Deduct Middle - Prevent double count
        // Then Right
        do
        {
            value++;
            amend++;
        }
        while (column + amend < size &&
        _board[column + amend, row] == _player);
        if (value > total)
        {
            return true;
        }
        value = 0;
        amend = 0;
        // Diagonal - Left Top
        do
        {
            value++;
        }
        while (column - value >= 0 && row - value >= 0 &&
        _board[column - value, row - value] == _player);
        if (value > total)
        {
            return true;
        }
        value -= 1; // Deduct Middle - Prevent double count
        // To Right Bottom
        do
        {
            value++;
            amend++;
        }
        while (column + amend < size && row + amend < size &&
        _board[column + amend, row + amend] == _player);
        if (value > total)
        {
            return true;
        }
        value = 0;
        amend = 0;
        // Diagonal - From Right Top
        do
        {
            value++;
        }
        while (column + value < size && row - value >= 0 &&
        _board[column + value, row - value] == _player);
        if (value > total)
        {
            return true;
        }
        value -= 1; // Deduct Middle - Prevent double count
        // To Left Bottom
        do
        {
            value++;
            amend++;
        }
        while (column - amend >= 0 &&
        row + amend < size &&
        _board[column - amend, row + amend] == _player);
        if (value > total)
        {
            return true;
        }
        return false;
    }

    private bool Full()
    {
        for (int row = 0; row < size; row++)
        {
            for (int column = 0; column < size; column++)
            {
                if (_board[column, row] == 0)
                {
                    return false;
                }
            }
        }
        return true;
    }

    private Path GetPiece(int player)
    {
        Path path = new Path
        {
            Stretch = Stretch.Uniform,
            StrokeThickness = 5,
            Margin = new Thickness(5),
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center
        };
        if ((player == 1))
        {
            LineGeometry line1 = new LineGeometry
            {
                StartPoint = new Point(0, 0),
                EndPoint = new Point(30, 30)
            };
            LineGeometry line2 = new LineGeometry
            {
                StartPoint = new Point(30, 0),
                EndPoint = new Point(0, 30)
            };
            GeometryGroup linegroup = new GeometryGroup();
            linegroup.Children.Add(line1);
            linegroup.Children.Add(line2);
            path.Data = linegroup;
            path.Stroke = new SolidColorBrush(Colors.Red);
        }
        else
        {
            EllipseGeometry ellipse = new EllipseGeometry
            {
                Center = new Point(15, 15),
                RadiusX = 15,
                RadiusY = 15
            };
            path.Data = ellipse;
            path.Stroke = new SolidColorBrush(Colors.Blue);
        }
        return path;
    }

    private void Place(Grid grid, int column, int row)
    {
        for (int i = size - 1; i > -1; i--)
        {
            if (_board[column, i] == 0)
            {
                _board[column, i] = _player;
                Grid element = (Grid)grid.Children.Single(
                    w => Grid.GetRow((Grid)w) == i
                    && Grid.GetColumn((Grid)w) == column);
                element.Children.Add(GetPiece(_player));
                row = i;
                break;
            }
        }
        if (Winner(column, row))
        {
            _won = true;
            Show($"Player {_player} has won!", app_title);
        }
        else if (Full())
        {
            Show("Board Full!", app_title);
        }
        _player = _player == 1 ? 2 : 1; // Set Player
    }

    private void Add(Grid grid, int row, int column)
    {
        Grid element = new Grid
        {
            Height = 40,
            Width = 40,
            Margin = new Thickness(5),
            Background = new SolidColorBrush(Colors.WhiteSmoke),
        };
        element.Tapped += (object sender, TappedRoutedEventArgs e) =>
        {
            if (!_won)
            {
                element = ((Grid)(sender));
                row = (int)element.GetValue(Grid.RowProperty);
                column = (int)element.GetValue(Grid.ColumnProperty);
                if (_board[column, 0] == 0) // Check Free Row
                {
                    Place(grid, column, row);
                }
            }
            else
            {
                Show("Game Over!", app_title);
            }
        };
        element.SetValue(Grid.ColumnProperty, column);
        element.SetValue(Grid.RowProperty, row);
        grid.Children.Add(element);
    }

    private void Layout(ref Grid Grid)
    {
        _player = 1;
        Grid.Children.Clear();
        Grid.ColumnDefinitions.Clear();
        Grid.RowDefinitions.Clear();
        // Setup Grid
        for (int index = 0; (index < size); index++)
        {
            Grid.RowDefinitions.Add(new RowDefinition());
            Grid.ColumnDefinitions.Add(new ColumnDefinition());
        }
        // Setup Board
        for (int column = 0; (column < size); column++)
        {
            for (int row = 0; (row < size); row++)
            {
                Add(Grid, row, column);
                _board[row, column] = 0;
            }
        }
    }

    public async void NewAsync(Grid grid)
    {
        Layout(ref grid);
        _won = false;
        _player = await ConfirmAsync("Who goes First?", app_title, "X", "O") ? 1 : 2;
    }
}

In the Library.cs there are using statements to include the necessary functionality. The Show Method is used to display a MessageDialog to display a message, the ConfirmAsync Method is used to display a MessageDialog to get a response from the player. Winner is used to determine if a winning solution has been provided, which is four pieces in a row and the Method is used for this purpose. The Full Method is used to determine if the board is completely full, GetPiece is used to generate the pieces to use in the game, Place is used to position a game piecewhen playing and Add is used to help setup the look-and-feel of the game along with Layout which is a set of Grid elements within a Grid and is called by the NewAsync Method.

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:

<Viewbox>
	<Grid Margin="50" Name="Display" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Viewbox>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Name="New" Icon="Page2" Label="New" Click="New_Click"/>
</CommandBar>

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 a 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.NewAsync(Display);
}

Below the MainPage() Method an instance of the Library Class is created, then New_Click is used to call the NewAsync 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 the playing, first can chose to play as “X” or “O”, you can win by getting four pieces in a horizontal, vertical or diagonal row in the Application

ran-four-in-row

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 – Hit or Miss

Hit or Miss demonstrates how to create a simple random game where you can score a Hit or a Miss based on which Grid is Tapped.

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 Windows.Foundation;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;

public class Library
{
    private const string app_title = "Hit or Miss";

    private const int score = 18;
    private const int size = 6;
    private const int hit = 1;
    private const int miss = 0;
    private readonly List<string> values = new List<string> { "Miss", "Hit" };

    private int _moves = 0;
    private int _hits = 0;
    private int _misses = 0;
    private bool _won = false;
    private int[,] _board = new int[size, size];
    private Random _random = new Random((int)DateTime.Now.Ticks);

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

    private List<int> Select(int start, int finish, int total)
    {
        int number;
        List<int> numbers = new List<int>();
        while ((numbers.Count < total)) // Select Numbers
        {
            // Random Number between Start and Finish
            number = _random.Next(start, finish + 1);
            if ((!numbers.Contains(number)) || (numbers.Count < 1))
            {
                numbers.Add(number); // Add if number Chosen or None
            }
        }
        return numbers;
    }

    private Path GetPiece(string value)
    {
        Path path = new Path
        {
            Stretch = Stretch.Uniform,
            StrokeThickness = 5,
            Margin = new Thickness(5),
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center
        };
        if ((value == "Miss")) // Draw Miss
        {
            LineGeometry line1 = new LineGeometry
            {
                StartPoint = new Point(0, 0),
                EndPoint = new Point(30, 30)
            };
            LineGeometry line2 = new LineGeometry
            {
                StartPoint = new Point(30, 0),
                EndPoint = new Point(0, 30)
            };
            GeometryGroup linegroup = new GeometryGroup();
            linegroup.Children.Add(line1);
            linegroup.Children.Add(line2);
            path.Data = linegroup;
            path.Stroke = new SolidColorBrush(Colors.Red);
        }
        else // Draw Hit
        {
            EllipseGeometry ellipse = new EllipseGeometry
            {
                Center = new Point(15, 15),
                RadiusX = 15,
                RadiusY = 15
            };
            path.Data = ellipse;
            path.Stroke = new SolidColorBrush(Colors.Blue);
        }
        return path;
    }

    private void Add(ref Grid grid, int row, int column)
    {
        Grid element = new Grid
        {
            Height = 50,
            Width = 50,
            Margin = new Thickness(5),
            Background = new SolidColorBrush(Colors.WhiteSmoke)
        };
        element.Tapped += (object sender, TappedRoutedEventArgs e) =>
        {
            if (!_won)
            {
                int selected;
                element = ((Grid)(sender));
                selected = _board[(int)element.GetValue(Grid.RowProperty), 
                    (int)element.GetValue(Grid.ColumnProperty)];
                if (element.Children.Count <= 0)
                {
                    element.Children.Clear();
                    element.Children.Add(GetPiece(values[selected]));
                    if (selected == hit)
                    {
                        _hits++;
                    }
                    else if (selected == miss)
                    {
                        _misses++;
                    }
                    _moves++;
                }
                if (_moves < (size * size) && _misses < score)
                {
                    if (_hits == score)
                    {
                        Show($"Well Done! You scored {_hits} hits and {_misses} misses!", app_title);
                        _won = true;
                    }
                }
                else
                {
                    Show($"Game Over! You scored {_hits} hits and {_misses} misses!", app_title);
                    _won = true;
                }
            }
        };
        element.SetValue(Grid.ColumnProperty, column);
        element.SetValue(Grid.RowProperty, row);
        grid.Children.Add(element);
    }

    private void Layout(ref Grid grid)
    {
        _moves = 0;
        _hits = 0;
        _misses = 0;
        grid.Children.Clear();
        grid.ColumnDefinitions.Clear();
        grid.RowDefinitions.Clear();
        // Setup Grid
        for (int index = 0; (index < size); index++)
        {
            grid.RowDefinitions.Add(new RowDefinition());
            grid.ColumnDefinitions.Add(new ColumnDefinition());
        }
        for (int row = 0; (row < size); row++)
        {
            for (int column = 0; (column < size); column++)
            {
                Add(ref grid, row, column);
            }
        }
    }

    public void New(ref Grid grid)
    {
        Layout(ref grid);
        List<int> values = new List<int>();
        List<int> indices = new List<int>();
        _won = false;
        int counter = 0;
        while (values.Count < (size * size))
        {
            values.Add(hit);
            values.Add(miss);
        }
        indices = Select(1, (size * size), (size * size));
        // Setup Board
        for (int column = 0; (column < size); column++)
        {
            for (int row = 0; (row < size); row++)
            {
                _board[column, row] = values[indices[counter] - 1];
                counter++;
            }
        }
    }
}

In the Library.cs there are using statements to include the necessary functionality. Show is used to display a MessageDialog and Select is used along with Random to pick a set of numbers. GetPiece is used to generate the pieces to use in the game, Add is used to help setup the look-and-feel of the game along with Layout which is a set of Grid elements within a Grid. The New Method is used to begin a game and configure the game board and call Layout.

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:

<Viewbox>
	<Grid Margin="50" Name="Display" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Viewbox>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Name="New" Icon="Page2" Label="New" Click="New_Click"/>
</CommandBar>

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 a 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 the playing, to win need to get more hits (Circles) than misses (Crosses) up to a total of 18 in the Application

ran-hit-or-miss

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 – Lucky Bingo

Lucky Bingo demonstrates how to create a simple Random Number game displayed with a Grid and TextBlock where can pick choice from a ComboBox.

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.Collections.ObjectModel;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;

public class Library
{
    private int _index = 0;
    private List<int> _numbers = null;
    private ObservableCollection<Grid> _list = new ObservableCollection<Grid>();
    private Random _random = new Random((int)DateTime.Now.Ticks);

    private List<int> Select(int start, int finish, int total)
    {
        int number;
        List<int> numbers = new List<int>();
        while ((numbers.Count < total)) // Select Numbers
        {
            // Random Number between Start and Finish
            number = _random.Next(start, finish + 1);
            if ((!numbers.Contains(number)) || (numbers.Count < 1))
            {
                numbers.Add(number); // Add if number Chosen or None
            }
        }
        return numbers;
    }

    private void Pick(ref GridView grid)
    {
        if (_index < _numbers.Count)
        {
            int number = _numbers[_index];
            TextBlock text = new TextBlock()
            {
                Foreground = new SolidColorBrush(Colors.White),
                FontSize = 24,
                Text = number.ToString(),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center
            };
            Grid container = new Grid()
            {
                Margin = new Thickness(2),
                Width = 48,
                Height = 48
            };
            Color fill = Colors.Transparent;
            if (number >= 1 && number <= 10)
            {
                fill = Colors.Magenta;
            }
            else if (number >= 11 && number <= 20)
            {
                fill = Colors.Blue;
            }
            else if (number >= 21 && number <= 30)
            {
                fill = Colors.DarkGreen;
            }
            else if (number >= 31 && number <= 40)
            {
                fill = Colors.YellowGreen;
            }
            else if (number >= 41 && number <= 50)
            {
                fill = Colors.Orange;
            }
            else if (number >= 51 && number <= 60)
            {
                fill = Colors.DarkBlue;
            }
            else if (number >= 61 && number <= 70)
            {
                fill = Colors.Red;
            }
            else if (number >= 71 && number <= 80)
            {
                fill = Colors.DarkCyan;
            }
            else if (number >= 81 && number <= 90)
            {
                fill = Colors.Purple;
            }
            Ellipse ball = new Ellipse
            {
                Width = container.Width,
                Height = container.Height,
                Fill = new SolidColorBrush(fill)
            };
            container.Children.Add(ball);
            container.Children.Add(text);
            _list.Add(container);
            _index++;
            grid.ItemsSource = _list;
        }
    }

    private void Layout(ref GridView grid)
    {
        grid.ItemsSource = null;
        _list = new ObservableCollection<Grid>();
        _index = 0;
        _numbers = Select(1, 90, 90);
    }

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

    public void Pick(GridView grid)
    {
        if (_numbers == null) Layout(ref grid);
        Pick(ref grid);
    }
}

In the Library.cs there are using statements to include the necessary functionality. There is an ObservableCollection of Grid and a Select Method to pick randomised numbers using Random. The Pick Method is used to add to a GridView and will add a Ellipse with a given background colour for each range of possible values. Layout is used by New to intialise everything needed and to pick all the numbers, which is displayed with the Pick Method.

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:

<Viewbox>
	<GridView Margin="50" Name="Display" HorizontalAlignment="Center" VerticalAlignment="Center">
		<GridView.ItemsPanel>
			<ItemsPanelTemplate>
				<ItemsWrapGrid Orientation="Horizontal" MaximumRowsOrColumns="10"/>
			</ItemsPanelTemplate>
		</GridView.ItemsPanel>
	</GridView>
</Viewbox>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Name="New" Icon="Page2" Label="New" Click="New_Click"/>
	<AppBarButton Name="Pick" Icon="Accept" Label="Pick" Click="Pick_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a ViewBox containing a GridView Control that has its ItemsPanelTemplate set to an ItemsWrapGrid. The second block of XAML is is the CommandBar which contains New – to start a gane and Pick to display a picked number.

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

private void Pick_Click(object sender, RoutedEventArgs e)
{
	library.Pick(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 and Pick_Click is used to call the Pick 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 use Pick to start selecting Bingo numbers or you can use New to reset the Application

ran-lucky-bingo

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 – Lucky Roulette

Lucky Roulette demonstrates how to create a simple Random Number game displayed with a Grid and TextBlock where can pick choice from a ComboBox.

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.Linq;
using Windows.Foundation;
using Windows.UI;
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 = "Lucky Roulette";

    private int _spins = 0;
    private int _spinValue = 0;
    private int _pickValue = 0;
    private Grid _pocket;
    private Random _random = new Random((int)DateTime.Now.Ticks);

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

    private bool IsOdd(int value)
    {
        return (value % 2 != 0);
    }

    private void Pick()
    {
        _spins++;
        _pocket.Children.Clear();
        _spinValue = _random.Next(0, 36);
        Color fill = Colors.Transparent;
        if (_spinValue >= 1 && _spinValue <= 10 || _spinValue >= 19 && _spinValue <= 28)
        {
            fill = IsOdd(_spinValue) ? Colors.Black : Colors.DarkRed;
        }
        else if (_spinValue >= 11 && _spinValue <= 18 || _spinValue >= 29 && _spinValue <= 36)
        {
            fill = IsOdd(_spinValue) ? Colors.DarkRed : Colors.Black;
        }
        else if (_spinValue == 0)
        {
            fill = Colors.DarkGreen;
        }
        Grid container = new Grid()
        {
            Height = 200,
            Width = 180,
            BorderBrush = new SolidColorBrush(Colors.Black),
            BorderThickness = new Thickness(5),
            Background = new SolidColorBrush(fill)
        };
        TextBlock text = new TextBlock()
        {
            Foreground = new SolidColorBrush(Colors.White),
            FontSize = 120,
            Text = _spinValue.ToString(),
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center
        };
        container.Children.Add(text);
        _pocket.Children.Add(container);
        if (_spinValue == _pickValue) // Check Win
        {
            Show($"Spin {_spins} matched {_spinValue}", app_title);
            _spins = 0;
        }
    }

    private void Layout(ref Grid grid)
    {
        grid.Children.Clear();
        _spins = 0;
        List<int> values = Enumerable.Range(0, 36).ToList();
        _pocket = new Grid()
        {
            Height = 200,
            Width = 180,
            HorizontalAlignment = HorizontalAlignment.Center
        };
        ComboBox combobox = new ComboBox()
        {
            Margin = new Thickness(10),
            HorizontalAlignment = HorizontalAlignment.Center,
            ItemsSource = values,
            SelectedIndex = 0,
        };
        combobox.SelectionChanged += (object sender, SelectionChangedEventArgs e) =>
        {
            _pickValue = (int)combobox.SelectedValue;
        };
        StackPanel panel = new StackPanel();
        panel.Children.Add(_pocket);
        panel.Children.Add(combobox);
        grid.Children.Add(panel);
    }

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

    public void Pick(Grid grid)
    {
        if (_pocket == null) Layout(ref grid);
        Pick();
    }
}

In the Library.cs there are using statements to include the necessary functionality. The Show Method is used to display a MessageDialog and IsOdd is used to determine if a number is odd. Pick is used to select the number to display in a Grid with a TextBlock using the appropriate colour for a Roulette Wheel Pocket number. Layout is used to create the main layout which is a Grid for the Pocket and then a ComboBox to pick your selection within a StackPanel. The New Method uses Layout Method and Pick will also create the look-and-feel of the game if not done already and then it will call Pick.

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:

<Viewbox>
	<Grid Margin="50" Name="Display" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Viewbox>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Name="New" Icon="Page2" Label="New" Click="New_Click"/>
	<AppBarButton Name="Pick" Icon="Accept" Label="Pick" Click="Pick_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a ViewBox containing a Grid Control that will be use for the contents of the game. The second block of XAML is is the CommandBar which contains New – to start a gane and Pick to pick numbers and compare against the selection from the ComboBox.

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

private void Pick_Click(object sender, RoutedEventArgs e)
{
	library.Pick(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 and Pick_Click is used to call the Pick 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 use New to start the Game then select a number from the dropdown list and choose Pick – if you get it right, you win!

ran-lucky-roulette

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 – Photo Rotate

Photo Rotate demonstrates how to use BitmapTransform and related Properties and Methods to create a simple image-rotating application

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 System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

public class Library
{
    private int _angle;
    private StorageFile _file;
    private WriteableBitmap _bitmap;

    private readonly Dictionary<int, BitmapRotation> rotation_angles = 
        new Dictionary<int, BitmapRotation>()
    {
        { 0, BitmapRotation.None },
        { 90,  BitmapRotation.Clockwise90Degrees },
        { 180,  BitmapRotation.Clockwise180Degrees },
        { 270, BitmapRotation.Clockwise270Degrees },
        { 360, BitmapRotation.None }
    };
    private const string file_extension = ".jpg";

    private async Task<WriteableBitmap> ReadAsync()
    {
        using (IRandomAccessStream stream = await _file.OpenAsync(FileAccessMode.ReadWrite))
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(BitmapDecoder.JpegDecoderId, stream);
            uint width = decoder.PixelWidth;
            uint height = decoder.PixelHeight;
            if (_angle % 180 != 0)
            {
                width = decoder.PixelHeight;
                height = decoder.PixelWidth;
            }
            BitmapTransform transform = new BitmapTransform
            {
                Rotation = rotation_angles[_angle]
            };
            PixelDataProvider data = await decoder.GetPixelDataAsync(
            BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, transform,
            ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);
            _bitmap = new WriteableBitmap((int)width, (int)height);
            byte[] buffer = data.DetachPixelData();
            using (Stream pixels = _bitmap.PixelBuffer.AsStream())
            {
                pixels.Write(buffer, 0, (int)pixels.Length);
            }
        }
        return _bitmap;
    }

    private async void WriteAsync()
    {
        using (IRandomAccessStream stream = await _file.OpenAsync(FileAccessMode.ReadWrite))
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
            (uint)_bitmap.PixelWidth, (uint)_bitmap.PixelHeight, 96.0, 96.0, _bitmap.PixelBuffer.ToArray());
            await encoder.FlushAsync();
        }
    }

    public async void OpenAsync(Image display)
    {
        _angle = 0;
        try
        {
            FileOpenPicker picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };
            picker.FileTypeFilter.Add(file_extension);
            _file = await picker.PickSingleFileAsync();
            if (_file != null)
            {
                display.Source = await ReadAsync();
            }
        }
        catch
        {

        }
    }

    public async void SaveAsync()
    {
        try
        {
            FileSavePicker picker = new FileSavePicker
            {
                DefaultFileExtension = file_extension,
                SuggestedFileName = "Picture",
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };
            picker.FileTypeChoices.Add("Picture", new List<string>() { file_extension });
            _file = await picker.PickSaveFileAsync();
            if (_file != null)
            {
                WriteAsync();
            }
        }
        catch
        {

        }
    }

    public async void RotateAsync(Image display)
    {
        if (_angle == 360) _angle = 0;
        _angle += 90;
        display.Source = await ReadAsync();
    }
}

In the Library.cs there are using statements to include the necessary functionality. There is an int to store the rotation angle, then a StorageFile to get or set the File of the photo and a Dictionary to store the supported rotation angles. The ReadAsync Method is used to get an IRandomAccessStream from this File and get the image with a BitmapDecoder. The photo is then manipulated to introduce a transformation – in this case the rotation with the PixelDataProvider and this information is then written back to the File to produce the rotated image. The WriteAsync Method is used encode any resulting image as the correct format with BitmapEncoder set to the settings optimised for a photo. OpenAsync is used to get a photo with a FileOpenPicker and calls the ReadAsync to get the File and set the Source of the Image passed in. The SaveAsync Method is use to store a photo after it has be rotated with the FileSavePicker used along with the WriteAsync Method. RotateAsync is used to rotate the image and increments the value to be used by 90 degrees each time it is called up to 360 degrees when it is reset, the image is then obtained again with this rotation using the ReadAsync Method.

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:

<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" ZoomMode="Enabled">
	<Image Name="Display"/>
</ScrollViewer>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Name="Open" Icon="OpenFile" Label="Open" Click="Open_Click"/>
	<AppBarButton Name="Save" Icon="Save" Label="Save" Click="Save_Click"/>
	<AppBarButton Name="Rotate" Icon="Rotate" Label="Rotate" Click="Rotate_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a ScrollViewer containing an Image Control that can be zoomed in or out of so you can view the image at any needed size with pinch-to-zoom or scroll-wheel. The second block of XAML is is the CommandBar which contains Open – to read and show a photo in the Image Control and Save to write a photo after it has been rotated and finally Rotate to perform the rotation.

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

private void Rotate_Click(object sender, RoutedEventArgs e)
{
	library.RotateAsync(Display);
}

Below the MainPage() Method an instance of the Library Class is created, then Open_Click is used to call the OpenAsync method to get a photo, SaveAsync is used to store a photo and RotateAsync is used to perform the rotation of the photo.

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 use Open to select a Photo to Rotate after which you can then Save the rotated photo

ran-photo-rotate

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 – Drag and Drop

Drag and Drop demonstrates how to use a ListBox to create a simple drag-and-drop example

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.ObjectModel;
using System.Linq;

public class Item
{
    public Guid Id { get; set; }
    public string Value { get; set; }
}

public class Library
{
    public ObservableCollection<Item> Items { get; set; } = new ObservableCollection<Item>();

    public void Add(string value)
    {
        Items.Add(new Item
        {
            Id = Guid.NewGuid(),
            Value = value
        });
    }

    public void Remove(Guid id)
    {
        Item result = Items.FirstOrDefault(item => item.Id == id);
        if (result != null)
        {
            Items.Remove(result);
        }
    }
}

In the Library.cs there are using statements to include the necessary functionality. There is an Item Class used to represent items in an ObservableCollection. This is represented by the Property Items which is an ObservableCollection of Item in the Library Class. The Add Method takes a string which is used to add an Item to the ObservableCollection along with a Guid used for an Id, and there’s a Remove Method to get an Item by it’s Id and Remove it from the ObservableCollection.

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="Auto"/>
		<RowDefinition Height="*"/>
	</Grid.RowDefinitions>
	<TextBox Grid.Row="0" Margin="20" Name="Value"/>
	<ListView Grid.Row="1" VerticalAlignment="Stretch" AllowDrop="True" CanReorderItems="True" SelectionMode="Single" Name="Display">
		<ListView.ItemTemplate>
			<DataTemplate>
				<TextBlock FontFamily="Segoe UI" FontSize="16" Text="{Binding Value}"/>
			</DataTemplate>
		</ListView.ItemTemplate>
	</ListView>
</Grid>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="Add" Label="Add" Click="Add_Click"/>
	<AppBarButton Icon="Remove" Label="Remove" Click="Remove_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a Grid with two row – the first of which is a TextBox to enter a Valye to add and the second row is a ListBox to show added items with the AllowDrop and CanReorderItems properties set enabling the Control to support drag-and-drop. The second block of XAML is is the CommandBar which contains the Add – to add to the ListBox and Remove to remove items from the ListBox

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)
{
	Display.ItemsSource = library.Items;
}

private void Add_Click(object sender, RoutedEventArgs e)
{
	library.Add(Value.Text);
}

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

Below the MainPage() Method an instance of the Library Class is created, then in the OnNavigatedTo Event Handler the ListBox has its ItemsSource set to the ObservableCollection in the Library Class, Add_Click will add items to this with the Text from the TextBox and the Remove_Click will use Remove from the Library Class to remove items.

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 then type in some text then tap Add you can then add multiple items, then tap and hold or select with a mouse on any of them to move them up and down the list

ran-drag-and-drop

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 – Navigation View

Navigation View shows how to use the NavigationView Control to display hamburger-style navigation.

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

In the Solution Explorer select MainPage.xaml

vs2017-mainpage

Step 6

From the Menu choose View and then Designer

vs2017-view-designer

Step 7

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

<NavigationView Name="Navigation" IsSettingsVisible="False">
	<NavigationView.MenuItems>
		<NavigationViewItem Content="Toggle" Tapped="Toggle_Tapped">
			<NavigationViewItem.Icon>
				<SymbolIcon Symbol="Accept"/>
			</NavigationViewItem.Icon>
		</NavigationViewItem>
	</NavigationView.MenuItems>
</NavigationView>

The NavigationView is used to display the hamburger-style menu and contains within its MenuItems a NavigationViewItem that can be used to toggle the visibility of the menu, this can also be done with the “hamburger” Button near the top of the control, it will also change width and visibility based on the width of the Application Window.

Step 8

From the Menu choose View and then Code

vs2017-view-code

Step 9

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

private void Toggle_Tapped(object sender, TappedRoutedEventArgs e)
{
	Navigation.IsPaneOpen = !Navigation.IsPaneOpen;
}

The Toggle_Tapped is an Event that will toggle the IsPaneOpen value of the NavigationView.

Step 10

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 11

Once the Application has started running it will be displayed with the NavigationView Control, you can use the Toggle Button to show or hide the navigation pane.

uwp-ran-navigation-view

Step 12

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

vs2017-close

Creative Commons License

Universal Windows Platform – Custom Dialog

Custom Dialog shows how to use the ContentDialog to display a customised popup dialog

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

In the Solution Explorer select MainPage.xaml

vs2017-mainpage

Step 6

From the Menu choose View and then Designer

vs2017-view-designer

Step 7

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

<Button Content="Display" HorizontalAlignment="Center" Click="Button_Click"/>

The Button will be used to trigger a Click Event called Button_Click

Step 8

From the Menu choose View and then Code

vs2017-view-code

Step 9

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

private async void Button_Click(object sender, RoutedEventArgs e)
{
	ContentDialog dialog = new ContentDialog()
	{
		Title = "Custom Dialog",
		MaxWidth = this.ActualWidth,
		PrimaryButtonText = "Close",
		Content = new TextBlock
		{
			Style = (Style)App.Current.Resources["SubheaderTextBlockStyle"],
			Text = "Hello World",
		}
	};
	await dialog.ShowAsync();
}

The Button_Click is an Event that will be triggered when the Button is Clicked, within this is a ContentDialog with the Content set to a TextBlock using a System Style and displayed with ShowAsync

Step 10

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 11

Once the Application has started running tap the Display Button to show the Custom Dialog and Close to dismiss it.

uwp-ran-custom-dialog

Step 12

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

vs2017-close

Creative Commons License

Universal Windows Platform – Tutorials – Set One


Setup and Start

Setup and Start

Set One


Hello World

Hello World

Command Bar

Command Bar

Data Input

Data Input

Image Rotate

Image Rotate

Lucky Dice

Lucky Dice

Lucky Lotto

Lucky Lotto

Noughts and Crosses

Noughts and Crosses

Memory Game

Memory Game

Touch Game

Touch Game

Playing Cards

Playing Cards

Web Browser

Web Browser

RSS Reader

RSS Reader

Text Editor

Text Editor

Rich Editor

Rich Editor

Task Editor

Task Editor

Draw Editor

Draw Editor

Slide Player

Slide Player

Media Player

Media Player

Audio Recorder

Audio Recorder

Video Recorder

Video Recorder

Custom Button

Custom Button

Custom Slider

Custom Slider

Clock Control

Clock Control

Carousel Control

Carousel Control

Wrap Control

Wrap Control

Dial Control

Dial Control

Flip Control

Flip Control

Expand Control

Expand Control

Location

Location

Tiles

Tiles

Toasts

Toasts

Agent

Agent

Source Code

Source Code

Universal Windows Platform – Agent

Agent demonstrates how to create a Background Task that implements IBackgroundTask to display a Toast Notification when the Time Zone is changed

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 Agent and select a Location and then select Ok to create the Project
vs2017-new-project-agent

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 has been created, from the Menu choose File, Add then New Project…

vs2017-file-add-new-project

Step 6

From New Project choose Visual C# from Installed, Templates then choose Windows Runtime Component (Universal Windows) and then type in the Name as Agent.Background and then select Ok to create the Project

vs2017-new-project-agent-background

The Windows Runtime Component (Universal Windows) Project type allows various types of Components to be created for use with a Universal Windows Project

Step 7

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

Step 8

Once the Project is created from the Solution Explorer select Class1.cs from the Agent.Background Project

vs2017-mainpage

Step 9

After the Class has been selected in Properties set the File Name to Trigger when changed select Yes when You are renaming a file. Would you also like to perform a rename in this project of all references to the code element ‘Class1’?” is displayed

vs2017-properties-agent-background

Step 10

Then in the Code View for Trigger.cs next to public sealed class Trigger the following should be entered:

<sourcecode language="csharp"]
: Windows.ApplicationModel.Background.IBackgroundTask
[/sourcecode]

Also while in the Code View inside public sealed class Trigger : IBackgroundTask { … } the following should be entered:

public void Run(Windows.ApplicationModel.Background.IBackgroundTaskInstance taskInstance)
{
	try
	{
		string value =
			Windows.Storage.ApplicationData.Current.LocalSettings.Values.ContainsKey("value") ?
			(string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["value"] :
			string.Empty;
		Windows.Data.Xml.Dom.XmlDocument xml =
			Windows.UI.Notifications.ToastNotificationManager
			.GetTemplateContent(Windows.UI.Notifications.ToastTemplateType.ToastText02);
		xml.GetElementsByTagName("text")[0].InnerText = "Time Zone Changed";
		xml.GetElementsByTagName("text")[1].InnerText = value;
		Windows.UI.Notifications.ToastNotificationManager.CreateToastNotifier().Show(
			new Windows.UI.Notifications.ToastNotification(xml));
	}
	catch
	{

	}
}

In the Trigger.cs there is the usage of an Interface for IBackgroundTask. The Run Method takes an IBackgroundTaskInstance as part of the requirements of the Interface, within the LocalSettings of the Application and then a ToastNotificationManager is used to create a ToastNotification when the Background Agent is triggered.

Step 11

Once done select from the Menu, Build, then Build Solution

vs2017-build-build-solution

Step 12

In the Solution Explorer select MainPage.xaml in the Agent Project

vs2017-mainpage-agent

Step 13

Once done select from the Menu, Project, then Add Reference…

vs2017-project-add-reference

Step 14

From the Reference Manager window select Projects then Solution and then make sure that Agent.Background is Checked then select Ok to add the reference

vs2017-reference-manager-agent

Step 15

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

vs2017-project-add-new-item

Step 16

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 17

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

using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Storage;

public class Library
{
    private IBackgroundTaskRegistration _registration;

    public void Save(string value)
    {
        ApplicationData.Current.LocalSettings.Values["value"] = value;
    }

    public bool Init()
    {
        if (BackgroundTaskRegistration.AllTasks.Count > 0)
        {
            _registration = BackgroundTaskRegistration.AllTasks.Values.First();
            return true;
        }
        else
        {
            return false;
        }
    }

    public async Task<bool> Toggle()
    {
        if (BackgroundTaskRegistration.AllTasks.Count > 0)
        {
            _registration = BackgroundTaskRegistration.AllTasks.Values.First();
            _registration.Unregister(true);
            _registration = null;
            return false;
        }
        else
        {
            try
            {
                await BackgroundExecutionManager.RequestAccessAsync();
                BackgroundTaskBuilder builder = new BackgroundTaskBuilder
                {
                    Name = typeof(Agent.Background.Trigger).FullName
                };
                builder.SetTrigger(new SystemTrigger(SystemTriggerType.TimeZoneChange, false));
                builder.TaskEntryPoint = builder.Name;
                builder.Register();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}

In the Library.cs there are using statements to include the necessary functionality. There is a Member for IBackgroundTaskRegistration and the Init Method is used to get the Background Agent if it’s already running. The Save Method has IBackgroundTaskRegistration to help Register the Background Task it will also set the LocalSettings for “value” and the Toggle Task will either Unregister it if it’s already running or it will RequestAccessAsync to create a Background Task with the BackgroundTaskBuilder with a SystemTrigger of SystemTriggerType.TimeZoneChange and then will Register it.

Step 18

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library-agent

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:

<TextBox Margin="50" VerticalAlignment="Top" Name="Value"/>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="Save" Label="Save" Click="Save_Click"/>
	<AppBarButton Name="Toggle" Icon="Play" Label="Start Agent" Click="Toggle_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a TextBox to enter the text that will be shown in a Toast Notification by the Background Task. The second block of XAML is the CommandBar which contains the Save and Toggle options to manage the Background Task.

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 SetToggle(bool value)
{
	if (value)
	{
		Toggle.Icon = new SymbolIcon(Symbol.Stop);
		Toggle.Label = "Stop Agent";
	}
	else
	{
		Toggle.Icon = new SymbolIcon(Symbol.Play);
		Toggle.Label = "Start Agent";
	}
}

protected override void OnNavigatedTo(NavigationEventArgs e)
{
	SetToggle(library.Init());
}

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

private async void Toggle_Click(object sender, RoutedEventArgs e)
{
	SetToggle(await library.Toggle());
}

Below the MainPage() Method an instance of the Library Class is created. The SetToggle Method is used to update the state of the Toggle AppBarButton, the OnNavigatedTo Event handler will use the Init from the Library Class along with SetToggle to get the current status of the Background Agent. The Save_Click Method will set the contents of the TextBox to the Save Method of the Library Class and Toggle_Click will trigger the Toggle Method of the Library Class.

Step 23

In the Solution Explorer select Package.appxmanifest

vs2017-manifest-agent

Step 24

From the Menu choose View and then Designer

vs2017-view-designer

Step 25

Then in the Package.appxmanifest select Declarations and then Select Background Tasks from the drop-down list, then select Add then make sure that System Event is Checked and the Entry point is set to Agent.Background.Trigger.

vs2017-declarations-agent

Step 26

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 27

After the Application has started running you can then type some text then select Save and can select Start Agent

run-agent

Step 28

Then in Windows 10 select Start, Settings, then Time & Language and then change the Time zone this will cause the text entered from the Application to appear in a Toast Notification or you can then within the Application select Stop Agent to end the Background Task.

ran-agent

Step 29

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

vs2017-close

Creative Commons License