First Windows 10 Universal Application – jump start

First Windows 10 Universal Application – jump start

Win10AppMain

Short introduction

Windows 10 is released and everyone can start creating Universal Windows Applications! 🙂

I have described Windows 10 platform in previous post that you can find here.

Universal Windows Application – what does it really mean?!

It means that you can create one application that will run on many different devices. For example you can create app that will be run on phones, tablets, PC and Xbox…

Great opportunity and chance to reach million users using Windows 10.

In this tutorial I will show what is the structure of the application project and after that we will create simple quiz game for Windows 10!

What do I need to start?

1) Windows 10 operating system – can be neither Education edition or Enterprise

2) Visual Studio 2015 Comminity (for free) or higher

Ready?!

1) Launch Visual Studio 2015:

firstWin1

2) From “File” menu select “New” and then “Project”:

firstWin2

3) In this step you must select “Blank App (Universal Windows) template to create project for Windows 10 Universal Application:

There are also three fields to fill:

– Name: this one is connected with the name of your project – in my case I’ve created it as “FirstWindows10App”

-Location: this is the location of your project (where it will be located on disc)

-Solution name: here you can give the name for the Solution – this is the place where you can add more than one project (you can add many projects to one Solution). In my case this is “FirstWindows10AppSolution”

firstWin3

4) Before we can start developing, we must turn on “Developer Mode” in Windows10. This allows us to create and test our apps on our machine.

Below you can also find screenshoots with steps.

  1. a) Click “Go to settings for developers”
  2. b) Choose “Developer mode” radio buton
  3. c) Accept the question about turning on developer mode
  4. d) After that click “Ok” buton

firstWin4

firstWin5

firstWin6

firstWin7

firstWin8

firstWin9

Great, you have created your first Windows 10 Universal Application project!

Now it is time to see what interesting is there (look at the image above).

On the left site of Visual Studio you can see that our Solution “FirstWindows10AppSolution” is created.

Notice that in Solution there is our application project named “FirstWindows10App” – let go through the structure of it!

Project structure

1) Properties: in this section you can find the information about newly created application. There are two sections:
  1. a) General:

– Assembly name – that one is for naming the DLL component of your app

– Default namespace – this is just the namespace for the app code that will be written (standard C# namespace)

b) Targeting:

As you can read in my previous article here, Windows 10 has different structure than previous Windows operating systems.

Now it is a platform that will be developed – so there is common sets of API that can be used for creating application that runs on each device with Windows 10.

– Target version – this is the version of Universal Windows Platform sets of API with which our application works for sure and is written using them

– Min version – this is minimum version of Universal Windows Platform sets of API that we know that our application will work with

firstWin10

2) References: in this section we can add some additional DLL references to our project (for example some libraries from Nuget):

Note that there are some references already added – for example Universal Windows reference or Microsoft.Application Insights (I will describe it later below).

firstWin11

3) Assets: in this section you add everything connected graphical design of your application:

This is the place where you must add splashscreen graphic, store logo, tiles, lockscreen graphic etc.

firstWin12

4) App.xaml: This is the base file connected with design of our application – here you can define for example theme for your app:

There is also declaration that we will use XAML(Extensible Application Markup Language) language in our application.

firstWin13

5) App.xaml.cs: This is base class for our application. There you can find code connected with launching and lifecycle of the application:

I will describe now what is the structure of this class and what exactly the code there is doing.

firstWin14

a) public App() – this is the main constructor of our application. There are events connected with app lifecycle and operations that should be started when application is launched:

firstWin15

firstWin16

 Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(  
 Microsoft.ApplicationInsights.WindowsCollectors.Metadata |  
 Microsoft.ApplicationInsights.WindowsCollectors.Session);   

I will not describe fragment with “Microsoft.ApplicationInsights…” – this is another big topic. I just want you to know that Application Insights are tools for measuring bugs, errors and performance of your application. When creating new project, Application Insights are added automaticly. You can read more here.

Fragment below is responsible for preparing UI for the app before it is started:

this.InitializeComponent();  

Fragment below is connected with suspending our application. When it suspends we can react in method described below:

this.Suspending += OnSuspending;  

 

b) OnSuspending – in this method below we can react when application is suspending. “Deferral” variable here is a very small amount of time for taking some actions before app is suspended. For example we can save something to local database:

 {  
   var deferral = e.SuspendingOperation.GetDeferral();  
   // Save application state and stop any background activity  
   deferral.Complete();  
}  

c) OnLaunched method – in this method we can implement all actions connected with start of our application. I have added comments to code below so you can track it:

protected override void OnLaunched(LaunchActivatedEventArgs e)  
{  
#if DEBUG  
// This is for checking the frames while debugging our application. If we debug it application will also have small black rectangle on the layout to show frames while for example enlarging our app:  
if (System.Diagnostics.Debugger.IsAttached)  
{  
this.DebugSettings.EnableFrameRateCounter = true;  
}  
#endif  
// Every Universal Windows Application has the same structure with reference to design:  
// 1) There is the Window of the application – every app has only one Window  
// 2) In window there is a Frame – every app has only one Frame  
// 3) In the Frame there can be multiple Pages – we will see how Page structure looks like later  
// So, we are retrieving Frame from Window:  
Frame rootFrame = Window.Current.Content as Frame;  
// Do not repeat app initialization when the Window already has content,  
// Just ensure that the window is active. If Frame is null we must construct new structure:  
if (rootFrame == null)  
{  
// Create a Frame to act as the navigation context and navigate to the first page  
rootFrame = new Frame();  
// Connect to event that is responsible for loading Page erros:  
rootFrame.NavigationFailed += OnNavigationFailed;  
// We can also check the previus state of our application. For example check why app was closed:  
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)  
{  
// Load state from previously terminated application:  
}  
// Place the frame in the current Window:  
Window.Current.Content = rootFrame;  
}  
if (rootFrame.Content == null)  
{  
// When the navigation stack isn’t restored navigate to the first page,  
// configuring the new page by passing required information as a navigation  
// parameter  
rootFrame.Navigate(typeof(MainPage), e.Arguments);  
}  
// Ensure the current window is active:  
Window.Current.Activate();  
}  

d) This method is responsible for reaction after Page fails to load:

 void OnNavigationFailed(object sender, NavigationFailedEventArgs e)  
  {  
   throw new Exception(“Failed to load Page ” + e.SourcePageType.FullName);  
  }  
firstWin17

firstWin18

6) ApplicationInsights.config: this is configuration file for Application Insights described above:

firstWin19

7) FirstWindows10App_TemporaryKey.pfx: this is certificate for your application. Generally speaking this confirms that you app is safe and has no viruses. You can read more here.

 

8) MainPage.xaml: This is the most exciting part of the project! There you create layout for your application. You can see how it will look like on different devices using “Designer”:

As you can see in the screenshot below, there are two options for creating UI for our application:

a) We can create UI using XAML language (right site of the Visual Studio):

firstWin20

b) We can also create UI for the app using “drag and drop” methos. Toolbox will help us. Please see the screen below:

firstWin21

9) MainPage.xaml.cs: Every Page besided of XAML design has “Code behind” class that supports events connected with UI actions. For example we can react when user is clicking the buton:

firstWin22

10) Package.appxmanifest: Every Universal Windows Application has its own manifest. This is the file where among others you can declare the capabilities of your app (internet access etc…):

a) Application section – There you can declare the display name of your application, select default language, add description of your app and select supported rotations for the app (landscape, portrait etc.):

firstWin23

b) Visual Assets section – there you define the graphics for your app like store logo, splashscreen and tiles:

firstWin24

c) Capabilities section – every Universal Windows Application has capabilities. For example if I want my app to have Internet connection I must mark “Internet(Client)” capability:

firstWin25

d) Packaging section – there you can find package name for your application (it is used when you want to associate app with Windows Store):

firstWin26

Those sections above are the most important for this moment.

11) project.json: in this file there is declaration of nuget dependencies that are used in our project. It is replacement for packages.config file (you can read more here):

firstWin27

Thats it! Now you are familiar with Universal Windows Application project structure!
It is the high time to create our first application – quiz game.
Below you can fin information how to do it.
1) Firstly download graphics materials, I have uploaded tchem to my OneDrive here.

Add them to Assets folder (you can just drag them):

firstWin28

2) Open MainPage.xaml file and paste below code exactly like in the picture:
<grid background="”#FFEEE8E8″">  
<grid.rowdefinitions>  
<rowdefinition height="”93*”/">  
<rowdefinition height="”85*”/">  
<rowdefinition height="”142*”/">  
</rowdefinition></rowdefinition></rowdefinition></grid.rowdefinitions>  
<img horizontalalignment="”Center”" verticalalignment="”Center”" grid.row="”0″" source="”Assets/Images/mainLogo.jpg”" margin="”32,0,33,170.11″" grid.rowspan="”2″/">  
<button x:name="”playButton”" content="”START”" horizontalalignment="”Center”" grid.row="”2″" verticalalignment="”Bottom”" background="”{x:Null}”" borderbrush="”#FF00ADEF”" margin="”0,0,0,100″" click="”playButton_Click”/">  
<textbox x:name="”userNameTextBox”" header="”Player" name:”="" horizontalalignment="”Center”" grid.row="”1″" width="”200″" textwrapping="”Wrap”" verticalalignment="”Center”" background="”{x:Null}”" foreground="”#FF00ADEF”" fontfamily="”Segoe" wp="" black”="" borderbrush="”#FF00ADEF”/">  
  
</textbox></button>
</grid>  
firstWin29
3) Now open MainPage.xaml.cs file (remember – code behind for the page):

Add below code exactly like in the pictrue:

 private void playButton_Click(object sender, RoutedEventArgs e)  
  {  
   string playerName = userNameTextBox.Text;  
   Frame.Navigate(typeof(GamePage), playerName);  
  }    
 firstWin30
4) Now we must add some new Pages to our application:

Right click on the project and select “New item” -> “Add”. Type “GamePage” as the name of the Page like in the picture below:

firstWin31

firstWin32

firstWin33

 5) Open GamePage.xaml and paste below code exactly like in the picture:
<grid background="”#FFEEE8E8″">  
<grid.rowdefinitions>  
<rowdefinition height="”163*”/">  
<rowdefinition height="”137*”/">  
<rowdefinition height="”124*”/">  
<rowdefinition height="”217*”/">  
</rowdefinition></rowdefinition></rowdefinition></rowdefinition></grid.rowdefinitions>  
<img x:name="”logoImage”" horizontalalignment="”Center”" verticalalignment="”Top”" source="”Assets/Images/microsoft-logo.png”" margin="”146,30,147,0″/" height="”100″">  
<textbox x:name="”answerTextBox”" header="”Answer:”" horizontalalignment="”Center”" grid.row="”1″" width="”200″" textwrapping="”Wrap”" verticalalignment="”Center”" background="”{x:Null}”" foreground="”#FF00ADEF”" fontfamily="”Segoe" wp="" black”="" borderbrush="”#FF00ADEF”/">  
<button x:name="”answerButton”" content="”ANSWER”" horizontalalignment="”Center”" grid.row="”2″" verticalalignment="”Center”" background="”{x:Null}”" borderbrush="”#FF00ADEF”" click="”answerButton_Click”">  
<textblock x:name="”GameResultTextBlock”" horizontalalignment="”Center”" grid.row="”3″" text="”Result…”" verticalalignment="”Center”" fontsize="”18″" foreground="”#FF00ADEF”" visibility="”Collapsed”/">  
</textblock></button><button x:name="”nextButton”" content="”NEXT”" horizontalalignment="”Center”" grid.row="”3″" verticalalignment="”Bottom”" background="”{x:Null}”" borderbrush="”#FF00ADEF”" visibility="”Collapsed”" click="”nextButton_Click”">  
  
</button></textbox>
</grid>  
6) Now open GamePage.xaml.cs file and paste below code exactly like in the picture:

Paste it after class declaration (class GamePage… ):

string _playerName;  
Dictionary<string, string=""> _brandsDictionary;  
string _actualBrand;  
string _answer;  
public GamePage()  
{  
this.InitializeComponent();  
InitializeGame();  
}  
   
private void InitializeGame()  
{  
_brandsDictionary = new Dictionary<string, string="">();  
_brandsDictionary.Add(“Microsoft”, “Assets/Images/microsoft-logo.png”);  
_brandsDictionary.Add(“Office”, “Assets/Images/office-logo.png”);  
_brandsDictionary.Add(“Windows”, “Assets/Images/windows-logo.png”);  
_brandsDictionary.Add(“Windows phone”, “Assets/Images/windowsPhone-logo.png”);  
logoImage.Source = new BitmapImage(new Uri(“ms-appx:///” + _brandsDictionary[“Microsoft”]));  
_actualBrand = _brandsDictionary.Keys.ElementAt(0);  
}  
   
protected override void OnNavigatedTo(NavigationEventArgs e)  
{  
_playerName = (string)e.Parameter;  
}  
private void answerButton_Click(object sender, RoutedEventArgs e)  
{  
CheckAnswer();  
}  
private void CheckAnswer()  
{  
_answer = answerTextBox.Text;  
if (_answer.Equals(_actualBrand))  
{  
GameResultTextBlock.Text = _playerName + ” good answer!”;  
GameResultTextBlock.Visibility = Visibility.Visible;  
nextButton.Visibility = Visibility.Visible;  
_brandsDictionary.Remove(_actualBrand);  
if (_brandsDictionary.Count == 0)  
Frame.Navigate(typeof(EndGamePage), _playerName);  
}  
else  
{  
GameResultTextBlock.Text = _playerName + ” try again!”;  
GameResultTextBlock.Visibility = Visibility.Visible;  
answerTextBox.Text = “”;  
}  
}  
private void nextButton_Click(object sender, RoutedEventArgs e)  
{  
PlayNextGame();  
}  
private void PlayNextGame()  
{  
answerTextBox.Text = “”;  
GameResultTextBlock.Visibility = Visibility.Collapsed;  
nextButton.Visibility = Visibility.Collapsed;  
_actualBrand = _brandsDictionary.Keys.ElementAt(0);  
logoImage.Source = new BitmapImage(new Uri(“ms-appx:///” + _brandsDictionary[_actualBrand]));  
}  
</string,></string,>    
firstWin34
7) Lets add one more and last Page to our project:

Right click on the project and select “New item” -> “Add”. Type “EndGamePage” as the name of the Page like in the picture below:

firstWin35

firstWin36

firstWin37

 8) Open EndGamePage.xaml and paste below code exactly like in the picture:
<grid background="”#FFEEE8E8″">  
<textblock x:name="”winnerTextBlock”" horizontalalignment="”Center”" textwrapping="”Wrap”" text="”Winner”" verticalalignment="”Center”" foreground="”#FF00ADEF”" fontweight="”Bold”" fontsize="”20″/">  
<button x:name="”playAgainButton”" content="”PLAY" again”="" horizontalalignment="”Center”" margin="”0,100,0,0″" verticalalignment="”Center”" borderbrush="”#FF00ADEF”" click="”playAgainButton_Click”/">  
</button></textblock></grid>     
firstWin38
9) Now open EndGamePage.xaml.cs file and paste below code exactly like in the picture:
 { 
  _winner = (string)e.Parameter;  
  winnerTextBlock.Text = _winner + ” is winner!”;  
 }  
  private void playAgainButton_Click(object sender, RoutedEventArgs e)  
 {  
 Frame.Navigate(typeof(MainPage));  
 Frame.BackStack.Clear();    
firstWin39
Done! Now we must Build our project. Look below how to do it:

firstWin40

After building our project we can finally launch it!

How? That is very easy. Select “Local Machine” buton at the top just like in the picture below.

It will start your application on your computer:

firstWin41

firstWin42

firstWin43

 Your Universal Windows Application is finished! You can now play the quiz game! But wait… Maybe you would like to play your game on mobile?

Look below how to do it:

When you click on the arrow on the right site of the “Local Machine” button you will see other device options to choose.

Select “Mobile Emulator 5″ ” and click the button again:

firstWin44

firstWin45

firstWin46

Great! Now your Universal Windows Application is running on the phone.

Sum up

Great job. You have created your first Universal Windows Application.

This one can be launched on phone, tablet, pc, xbox…

Windows 10 gives great opportunity to create one application that runs on every Windows 10 device.

I hope that you enjoyed this tutorial.

You can also download quiz game project from my GitHub here.

Have fun!

Advertisements