Windows 10 Development – Quick Guide ”; Previous Next Windows 10 Development – Introduction This tutorial is designed for people who want to learn how to develop Windows 10 applications. In this tutorial, we are going to learn − Windows 10 application development Updates of the new OS released by Microsoft New features for the developers in the updates A lot of interesting app scenarios are now possible that were not available to us in the first release. Microsoft has not only added new APIs, they have also extended the existing APIs. Universal Windows app A Universal Windows app was first introduced in Windows 8 as the Windows Runtime, which was built upon the Universal Application Platform. Now, in Windows 10, the name of the Universal Application Platform has been changed to Universal Windows Platform (UWP). You can build modern and fully immersive apps by targeting Windows 10 devices for Windows Store such as PC, tablet, phone, etc. In Windows 10, you can easily develop applications to reach all the devices supported on Windows 10 with just − One API set One app package And one store The Universal Windows Platform also supports different screen sizes and different interaction models such as touch pad, mouse & keyboard, a game controller, or a pen. Characteristics of UWP apps Here are some of the characteristics of Universal Windows apps, which make it superior to Windows 10. You can target device families and not OS like Windows 8.1. Apps are packaged and distributed using the .AppX packaging format, which ensures that your apps can be deployed and updated seamlessly. You can submit your application to the Windows store and it will make it available on all device families, or only those devices you choose. You can easily manage all your apps for Windows devices in one place. You can limit the availability of your application to the particular device family. The core APIs of Universal Windows Platform (UWP) are the same across all Windows device families. So your app can run on all Windows 10 devices if it is uses only the core APIs. With the help of Extension SDKs, you can light up your application for particular devices. Development Choices Universal Windows applications can be created in any of the following languages − C# or Visual Basic with XAML JavaScript with HTML C++ with DirectX and/or XAML You can also write components in one language and use them in an application that is developed in another language. Windows 10 Development – UWP Windows Runtime (WinRT) is a platform-homogeneous application architecture, which supports development in C++/CX, C#, VB.NET and JavaScript. WinRT applications natively support both the x86 and ARM architectures. Some important features are. It was first introduced in Windows Server 2012 in September 2012. WinRT APIs provide access to all core platform features using JavaScript, C#, Visual Basic, and C++. WinRT components support multiple languages and APIs such as native, managed and scripting languages. Universal Windows Platform (UWP) A Universal Windows app is built upon Universal Windows Platform (UWP), which was first introduced in Windows 8 as the Windows Runtime. In Windows 10, Universal Windows Platform (UWP) was introduced, which further advances the Windows Runtime (WinRT) model. In Windows 8.1, WinRT, for the first time, was aligned between Windows Phone 8.1 applications and Windows 8.1 applications with the help of Universal Windows 8 apps to target both Windows phone and Windows application using a shared codebase. Windows 10 Unified Core, which is known as Windows Core now, has reached to a point where UWP, now, provides a common app platform available on every device that runs on Windows 10. UWP not only can call the WinRT APIs that are common to all devices, but also APIs (including Win32 and .NET APIs) that are specific to the device family that the app is running on. Devices Supported by Windows 10 Windows 8.1 and Windows Phone 8.1 apps target an OS; either Windows or Windows Phone. Windows 10 applications do not target an OS but they target one or more device families. Device families have their own APIs as well, which add functionality for that particular device family. You can easily determine all the devices, within a device family, on which your applications can be installed and run from the Windows Store. Here is the hierarchical representation of the device family. Advantages of UWP Universal Windows Platform (UWP) provides a handful of things for developers. They are − One Operating System and One Unified Core for all the devices. One App Platform to run the applications across every family. One Dev Center to submit application and dashboard. One Store for all the devices. Setup for UWP Development The following steps need to be followed to start creating your own Universal Windows Platform (UWP) apps for Windows 10. Windows 10 OS − UWP apps need the latest version of Windows to develop. You can also develop UWP applications on Windows 8.1 but there is no support for UI designer Window. Windows 10 developer tools − In Visual studio 2015, you can design, code, test, and debug your UWP apps. You can download and install the free Microsoft Visual Studio Community 2015 from https://dev.windows.com/en-us/downloads Enable development mode for Windows 10 − Go to Start > Settings. Select Update & security. Then select “For developers”. Click on the Developer mode For UWP apps, it is important to test your applications on devices. Register as an app developer − You can start developing apps, but to submit your apps to the store, you need a developer account. You can create your developer account here https://msdn.microsoft.com/enus/library/windows/apps/bg124287.aspx After following the above steps, you are now ready to start the development of a Universal Windows Platform (UWP) application. Windows 10 Development – First App In this chapter, we will be creating our first simple application “Hello world” in Universal Windows Platform (UWP) using XAML and C# on Windows 10. We will demonstrate how a single UWP application
Category: windows10 Development
Windows10 Dev – Background Execution ”; Previous Next The Universal Windows Platform (UWP) introduces new mechanisms, which allow the applications to perform some functionality while the application is not running in the foreground. UWP also increases the ability of the applications to extend their execution time in the background for Background Tasks and Triggers. Background execution is the real complementary tail to the application lifecycle. Important features of Background Tasks are − A background task is triggered by a system or time event and can be constrained by one or more conditions. When a background task is triggered, its associated handler runs and performs the work of the background task. A background task can run even when the app that registered the background task is suspended. They are part of the standard application platform and essentially provide an app with the ability to register for a system event (trigger). When that event occurs, they run a predefined block of code in the background. System triggers include events such as changes in network connectivity or the system time zone. Background Execution is not guaranteed, so it is not suitable for critical functions and features. The OS has a limitation as to how many background tasks can run at the same time. So even when trigger is fired and conditions are met, the task can still not run. Create and Register Background Task Create a background task class and register it to run when your app is not in the foreground. You can run code in the background by writing classes that implement the IBackgroundTask interface. The following sample code shows a very basic starting point for a background task class. public sealed class MyBackgroundTask : IBackgroundTask { public void Run(IBackgroundTaskInstance taskInstance){ // write code } } You can request access for background task as follows. var access = await BackgroundExecutionManager.RequestAccessAsync(); switch (access) { case BackgroundAccessStatus.Unspecified: break; case BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity: break; case BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity: break; case BackgroundAccessStatus.Denied: break; default: break; } To build and register the background task, use the following code. var task = new BackgroundTaskBuilder { Name = “My Task”, TaskEntryPoint = typeof(BackgroundStuff.MyBackgroundTask).ToString() }; var trigger = new ApplicationTrigger(); task.SetTrigger(trigger); task.Register(); await trigger.RequestAsync(); Let us understand a simple example of background task by following all the below given steps. Create a new blank UWP project ‘UWPBackgroundDemo’ and add one button in the XAML file. <Page x:Class = “UWPBackgroundDemo.MainPage” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:local = “using:UWPBackgroundDemo” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable = “d”> <Grid Background = “{ThemeResource ApplicationPageBackgroundThemeBrush}”> <Button x:Name = “button” Content = “Button” HorizontalAlignment = “Left” Margin = “159,288,0,0” VerticalAlignment = “Top” Click = “button_Click”/> </Grid> </Page> Given below is the button click event implementation in which the background task is registered. using System; using Windows.ApplicationModel.Background; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace UWPBackgroundDemo { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private async void button_Click(object sender, RoutedEventArgs e) { var access = await BackgroundExecutionManager.RequestAccessAsync(); switch (access){ case BackgroundAccessStatus.Unspecified: break; case BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity: break; case BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity: break; case BackgroundAccessStatus.Denied: break; default: break; } var task = new BackgroundTaskBuilder { Name = “My Task”, TaskEntryPoint = typeof(BackgroundStuff.MyBackgroundTask).ToString() }; var trigger = new ApplicationTrigger(); task.SetTrigger(trigger); var condition = new SystemCondition(SystemConditionType.InternetAvailable); task.Register(); await trigger.RequestAsync(); } } } Now create another project, but this time select Windows Runtime Component (Universal Windows) from the menu and give the name Background stuff to this project. Given below is the C# code. which contains MyBackgroundTask class implantation and it will run the background task. using Windows.ApplicationModel.Background; using Windows.UI.Notifications; namespace BackgroundStuff { public sealed class MyBackgroundTask : IBackgroundTask { public void Run(IBackgroundTaskInstance taskInstance) { SendToast(“Hi this is background Task”); } public static void SendToast(string message) { var template = ToastTemplateType.ToastText01; var xml = ToastNotificationManager.GetTemplateContent(template); var elements = xml.GetElementsByTagName(“Test”); var text = xml.CreateTextNode(message); elements[0].AppendChild(text); var toast = new ToastNotification(xml); ToastNotificationManager.CreateToastNotifier().Show(toast); } } } To make this project accessible in the UWPBackgroundDemo project, right click on References > Add References in Solution Explorer and add BackgroundStuff project. Now, let us go to the Package.appxmanifest file of UWPBackgroundDemo project and add the following information in Declarations tab. First build the Background stuff project, then build and execute the UWPBackgroundDemo project. When the above code is compiled and executed, you will see the following window. When you click the button, it will run the background task and will show a notification at the right end of your window. Print Page Previous Next Advertisements ”;
Windows 10 – File Management
Windows10 Development – File Management ”; Previous Next In any application, one of the most important thing is the data. If you are .net developer, you might know about the isolated storage and the same concept follows through the Universal Windows Platform (UWP) applications. File Locations These are the areas where your application can access the data. The application contains some area, which is private to that particular application and is inaccessible to the others, but there are many other areas, where you can store and save your data inside a file. Given below are the brief descriptions of each folder. S.No. Folder & Description 1 App package folder Package manager installs all the app’s related files into the App package folder, and app can only read data from this folder. 2 Local folder Applications store local data into a local folder. It can store data up to the limit on the storage device. 3 Roaming folder Setting and properties related to application is stored in roaming folder. Other devices can also access data from this folder. It has limited size up to 100KB per application. 4 Temp Folder Use of temporary storage and there is no guarantee that it will still be available when your application runs again. 5 Publisher Share Shared storage for all the apps from the same publisher. It is declared in app manifest. 6 Credential Locker Used for secure storage of password credential objects. 7 OneDrive OneDrive is free online storage that comes with your Microsoft account. 8 Cloud Store data on the cloud. 9 Known folders These folders already known folders such as My Pictures, Videos, and Music. 10 Removable storage USB storage device or external hard drive etc. File Handling APIs In Windows 8, new APIs were introduced for file handling. These APIs are located in the Windows.Storage and Windows.Storage.Streams namespaces. You can use these APIs instead of the System.IO.IsolatedStorage namespace. By using these APIs, it will be easier to port your Windows Phone app to the Windows Store, and you can easily upgrade your applications to future versions of the Windows. To access local, roaming or temp folders, you need to call these APIs − StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFolder roamingFolder = ApplicationData.Current.RoamingFolder; StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder; To create a new file in a local folder use the following code − StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFile textFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); Here is the code to open the newly created file and write some content in that file. using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite)) { using (DataWriter textWriter = new DataWriter(textStream)){ textWriter.WriteString(contents); await textWriter.StoreAsync(); } } You can open the same file again, from the local folder as shown in the code given below. using (IRandomAccessStream textStream = await textFile.OpenReadAsync()) { using (DataReader textReader = new DataReader(textStream)){ uint textLength = (uint)textStream.Size; await textReader.LoadAsync(textLength); contents = textReader.ReadString(textLength); } } To understand how the reading and writing of the data works, let us have a look at a simple example. Given below is the XAML code in which different controls are added. <Page x:Class = “UWPFileHandling.MainPage” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:local = “using:UWPFileHandling” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable = “d”> <Grid Background = “{ThemeResource ApplicationPageBackgroundThemeBrush}”> <Button x:Name = “readFile” Content = “Read Data From File” HorizontalAlignment = “Left” Margin = “62,518,0,0” VerticalAlignment = “Top” Height = “37” Width = “174” Click = “readFile_Click”/> <TextBox x:FieldModifier = “public” x:Name = “textBox” HorizontalAlignment = “Left” Margin = “58,145,0,0” TextWrapping = “Wrap” VerticalAlignment = “Top” Height = “276” Width = “245”/>. <Button x:Name = “writeFile” Content = “Write Data to File” HorizontalAlignment = “Left” Margin = “64,459,0,0” VerticalAlignment = “Top” Click = “writeFile_Click”/> <TextBlock x:Name = “textBlock” HorizontalAlignment = “Left” Margin = “386,149,0,0” TextWrapping = “Wrap” VerticalAlignment = “Top” Height = “266” Width = “250” Foreground = “#FF6231CD”/> </Grid> </Page> Given below is the C# implementation for different events and also the implementation of the FileHelper class for reading and writing data to the text file. using System; using System.IO; using System.Threading.Tasks; using Windows.Storage; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace UWPFileHandling { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public partial class MainPage : Page { const string TEXT_FILE_NAME = “SampleTextFile.txt”; public MainPage(){ this.InitializeComponent(); } private async void readFile_Click(object sender, RoutedEventArgs e) { string str = await FileHelper.ReadTextFile(TEXT_FILE_NAME); textBlock.Text = str; } private async void writeFile_Click(object sender, RoutedEventArgs e) { string textFilePath = await FileHelper.WriteTextFile(TEXT_FILE_NAME, textBox.Text); } } public static class FileHelper { // Write a text file to the app”s local folder. public static async Task<string> WriteTextFile(string filename, string contents) { StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFile textFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite)){ using (DataWriter textWriter = new DataWriter(textStream)){ textWriter.WriteString(contents); await textWriter.StoreAsync(); } } return textFile.Path; } // Read the contents of a text file from the app”s local folder. public static async Task<string> ReadTextFile(string filename) { string contents; StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFile textFile = await localFolder.GetFileAsync(filename); using (IRandomAccessStream textStream = await textFile.OpenReadAsync()){ using (DataReader textReader = new DataReader(textStream)){ uint textLength = (uint)textStream.Size; await textReader.LoadAsync(textLength); contents = textReader.ReadString(textLength); } } return contents; } } } When the above code is compiled and executed, you will see the following window. Now, you write something in the textbox and click “Write Data to File” button. The program will write the data into the text file in a local folder. If you click on “Read Data from File” button, the program will read the data from the same text file, which is located in the local folder and will display it on the text block. Print Page Previous Next Advertisements ”;
Windows 10 – APP Services
Windows 10 Development – Services ”; Previous Next In this chapter, we will be learning about how UWP apps can help or provide services to another Universal Windows Platform (UWP) applications. Actually, this chapter is an extension of the chapter Background execution and is a special case of it. In Windows 10, an app service is a way or mechanism for an app to provide services to other apps. An app service works in the form of a background task. Foreground apps can call an app service in another app to perform tasks in the background. App services are like web services but app services are used on Windows 10 device. Universal Windows Platform (UWP) applications can interact with another UWP application in various ways − URI association using LaunchUriAsync File association using LaunchFileAsync Launch for results using LaunchUriForResultsAsync App services The first three ways are used when both the applications are foreground, but the App services are used in background task and in that case client application must be in foreground and available to use App service. App services are very beneficial in applications where non-visual services are provided e.g. a bar code scanner in which a foreground app will take the image and send those bytes to the app services to identify the bar code. To understand all these concepts, let us create a new UWP project with the name AppServiceProvider in Microsoft Visual Studio 2015. Now in the Package.appmenifest file, add the following information. To create an app service, which can be invoked by foreground applications, let us add a new Windows Runtime Component project to the solution with MyAppService name, because app services are implemented as a background task. Add a reference to the MyAppService project in the AppServiceProvider project. Now delete the class1.cs file from MyAppService project and add a new class with the inventory name, which will implement the IBackgrounTask interface. The IBackgrounTask interface has only one method “Run” which needs to be implemented for background Task. public sealed class Inventory : IBackgroundTask { public void Run(IBackgroundTaskInstance taskInstance) { } } When the background task is created, Run() method is called and when Run method completes, then background tasks are terminated. To stay upto a background task, to serve requests, the code takes a deferral. The app services code is in OnRequestedReceived(). In this example, an index for an inventory item passes to the service, to retrieve the name and the price of the specified inventory item. private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { // Get a deferral because we use an awaitable API below to respond to the message } Given below is the complete implementation of Inventory class in C#. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel.AppService; using Windows.ApplicationModel.Background; using Windows.Foundation.Collections; namespace MyAppService{ public sealed class Inventory : IBackgroundTask { private BackgroundTaskDeferral backgroundTaskDeferral; private AppServiceConnection appServiceconnection; private String[] inventoryItems = new string[] { “Robot vacuum”, “Chair” }; private double[] inventoryPrices = new double[] { 129.99, 88.99 }; public void Run(IBackgroundTaskInstance taskInstance) { this.backgroundTaskDeferral = taskInstance.GetDeferral(); taskInstance.Canceled += OnTaskCanceled; var details = taskInstance.TriggerDetails as AppServiceTriggerDetails; appServiceconnection = details.AppServiceConnection; appServiceconnection.RequestReceived += OnRequestReceived; } private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { var messageDeferral = args.GetDeferral(); ValueSet message = args.Request.Message; ValueSet returnData = new ValueSet(); string command = message[“Command”] as string; int? inventoryIndex = message[“ID”] as int?; if (inventoryIndex.HasValue && inventoryIndex.Value >= 0 && inventoryIndex.Value < inventoryItems.GetLength(0)) { switch (command) { case “Price”: { returnData.Add(“Result”, inventoryPrices[inventoryIndex.Value]); returnData.Add(“Status”, “OK”); break; } case “Item”: { returnData.Add(“Result”, inventoryItems[inventoryIndex.Value]); returnData.Add(“Status”, “OK”); break; } default: { returnData.Add(“Status”, “Fail: unknown command”); break; } } else { returnData.Add(“Status”, “Fail: Index out of range”); } } await args.Request.SendResponseAsync(returnData); messageDeferral.Complete(); } private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason){ if (this.backgroundTaskDeferral != null) { // Complete the service deferral. this.backgroundTaskDeferral.Complete(); } } } } Let us create a client app by adding a new blank UWP project ClientApp and add one button, one text box and two textblocks as shown below in the XAML file. <Page x:Class = “ClientApp.MainPage” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:local = “using:ClientApp” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable = “d”> <Grid Background = “{ThemeResource ApplicationPageBackgroundThemeBrush}”> <TextBlock HorizontalAlignment = “Left” Text = “Enter Item No.” Margin = “52,40,0,0” TextWrapping = “Wrap” VerticalAlignment = “Top” Height = “32” Width = “268”/> <Button x:Name = “button” Content = “Get Info” HorizontalAlignment = “Left” Margin = “255,96,0,0” VerticalAlignment = “Top” Click = “button_Click”/> <TextBox x:Name = “textBox” HorizontalAlignment = “Left” Margin = “52,96,0,0” TextWrapping = “Wrap” VerticalAlignment = “Top” Width = “168”/> <TextBlock x:Name = “textBlock” HorizontalAlignment = “Left” Margin = “52,190,0,0” TextWrapping = “Wrap” VerticalAlignment = “Top” Height = “32” Width = “268”/> </Grid> </Page> Given below is the button-click event implementation in which App services are requested. using System; using Windows.ApplicationModel.AppService; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace ClientApp { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { private AppServiceConnection inventoryService; public MainPage() { this.InitializeComponent(); } private async void button_Click(object sender, RoutedEventArgs e){ // Add the connection. if (this.inventoryService == null) { this.inventoryService = new AppServiceConnection(); this.inventoryService.AppServiceName = “com.microsoft.inventory”; this.inventoryService.PackageFamilyName = “bb1a8478-8005-46869923-e525ceaa26fc_4sz2ag3dcq60a”; var status = await this.inventoryService.OpenAsync(); if (status != AppServiceConnectionStatus.Success) { button.Content = “Failed to connect”; return; } } // Call the service. int idx = int.Parse(textBox.Text); var message = new ValueSet(); message.Add(“Command”, “Item”); message.Add(“ID”, idx); AppServiceResponse response = await this.inventoryService.SendMessageAsync(message); string result = “”; if (response.Status == AppServiceResponseStatus.Success) { // Get the data that the service sent to us. if (response.Message[“Status”] as string == “OK”) { result = response.Message[“Result”] as string; } } message.Clear(); message.Add(“Command”, “Price”); message.Add(“ID”, idx); response = await this.inventoryService.SendMessageAsync(message); if (response.Status == AppServiceResponseStatus.Success){ // Get the data that the service sent to us. if (response.Message[“Status”] as string == “OK”) { result += ” : Price = ” + “$”+ response.Message[“Result”] as string; } } textBlock.Text
Windows 10 – Networking
Windows 10 Development – Networking ”; Previous Next Nowadays, you will see many applications, which have somehow integrated with web services or other devices on a network. Fetching online weather content, latest news, chatting or peer-to-peer games are some examples which use network services. These apps are built using a wide variety of networking APIs. In Windows 10, the networking APIs are improved in terms of their speed and memory performances as well as the capabilities and flexibility they provide to the developers. Capabilities In order to network, you must add appropriate capability elements to your app manifest. If no network capability is specified in your app”s manifest, your app will have no networking capability, and any attempt to connect to the network will fail. The following are the most-used networking capabilities. S.No. Capability & Description 1 internetClient Provides outbound access to the Internet and networks in public places, like airports and coffee shop. Most apps that require Internet access should use this capability. 2 internetClientServer Gives the app inbound and outbound network access from the Internet and networks in public places like airports and coffee shops. 3 privateNetworkClientServer Gives the app inbound and outbound network access at the users’ trusted places, like home and work. To define one or more capabilities in your app manifest file, look at the image given below. The Universal Windows Platform (UWP) contains a large set of networking APIs by targeting the following − Querying the connectivity status of the device and connecting to the peer devices. Communicating with REST web services and Downloading large media files in the background Networking Technologies In Universal Windows Platform (UWP), the following networking technologies are available for the developers, which can be used in many different situations. Sockets Sockets are used when you want to communicate with another device with your own protocol. You can use both, Windows.Networking.Sockets and Winsock to communicate with other devices as a Universal Windows Platform (UWP) app developer. Windows.Networking.Sockets has the advantage of being a modern API, designed for use by UWP developers. If you are using cross-platform networking libraries or other existing Winsock code, then use Winsock APIs. The following code shows how to create a socket listener. try { //Create a StreamSocketListener to start listening for TCP connections. Windows.Networking.Sockets.StreamSocketListener socketListener = new Windows.Networking.Sockets.StreamSocketListener(); //Hook up an event handler to call when connections are received. socketListener.ConnectionReceived += SocketListener_ConnectionReceived; //Start listening for incoming TCP connections on the specified port. You can specify any port that”s not currently in use. await socketListener.BindServiceNameAsync(“1337”); } catch (Exception e) { //Handle exception. } The following code shows the implementation of the SocketListener_ConnectionReceived event handler. private async void SocketListener_ConnectionReceived( Windows.Networking.Sockets.StreamSocketListen er sender, Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args){ //Read line from the remote client. Stream inStream = args.Socket.InputStream.AsStreamForRead(); StreamReader reader = new StreamReader(inStream); string request = await reader.ReadLineAsync(); //Send the line back to the remote client. Stream outStream = args.Socket.OutputStream.AsStreamForWrite(); StreamWriter writer = new StreamWriter(outStream); await writer.WriteLineAsync(request); await writer.FlushAsync(); } WebSocket The WebSockets protocol provides a fast and secure two-way communication between a client and a server over the web. Universal Windows Platform (UWP) developers can use the MessageWebSocket and StreamWebSocket classes to connect with servers that support the Websocket protocol. Important features are − Under the WebSocket Protocol, data is transferred immediately over a full-duplex single socket connection. It allows messages to be sent and received from both endpoints in real time. WebSockets are ideal for use in real-time gaming where instant social network notifications and up-to-date displays of information (game statistics) need to be secure and use fast data transfer. The following code shows how to send and receive messages on a secure connection. MessageWebSocket webSock = new MessageWebSocket(); //In this case we will be sending/receiving a string so we need to set the MessageType to Utf8. webSock.Control.MessageType = SocketMessageType.Utf8; //Add the MessageReceived event handler. webSock.MessageReceived += WebSock_MessageReceived; //Add the Closed event handler. webSock.Closed += WebSock_Closed; Uri serverUri = new Uri(“wss://echo.websocket.org”); try { //Connect to the server. await webSock.ConnectAsync(serverUri); //Send a message to the server. await WebSock_SendMessage(webSock, “Hello, world!”); } catch (Exception ex) { //Add code here to handle any exceptions } The following code shows the event implementation, which will receive a string from a connected WebSocket. //The MessageReceived event handler. private void WebSock_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args){ DataReader messageReader = args.GetDataReader(); messageReader.UnicodeEncoding = UnicodeEncoding.Utf8; string messageString = messageReader.ReadString( messageReader.UnconsumedBufferLength); //Add code here to do something with the string that is received. } HttpClient HttpClient and Windows.Web.Http namespace APIs, provide ability to the developer to send and receive information using the HTTP 2.0 and HTTP 1.1 protocols. It can be used to − communicate with a web service or a web server. Upload or download a number of small files. Stream the content over the network. The following code shows how to send a GET request using Windows.Web.Http.HttpClient and Windows.Web.Http.HttpResponseMessage. //Create an HTTP client object Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true, //especially if the header value is coming from user input. string header = “ie”; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception(“Invalid header value: ” + header); } header = “Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)”; if (!headers.UserAgent.TryParseAdd(header)) { throw new Exception(“Invalid header value: ” + header); } Uri requestUri = new Uri(“http://www.contoso.com”); //Send the GET request asynchronously and retrieve the response as a string. Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage(); string httpResponseBody = “”; try { //Send the GET request httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); } catch (Exception ex) { httpResponseBody = “Error: ” + ex.HResult.ToString(“X”) + ” Message: ” + ex.Message; } Print Page Previous Next Advertisements ”;
Windows 10 – First App
Windows 10 Development – First App ”; Previous Next In this chapter, we will be creating our first simple application “Hello world” in Universal Windows Platform (UWP) using XAML and C# on Windows 10. We will demonstrate how a single UWP application created in Visual Studio can be run and executed on any Windows 10 device. Let us start creating the App by following the steps given below. Launch Visual Studio 2015. Click on the File menu and select New > Project. The following New Project dialog window will be displayed. You can see the different types of templates on the left pane of the dialog box. In the left pane, you can see the tree view. Select Universal template from Templates > Visual C# > Windows. From the center pane, select the Blank App (Universal Windows) template Give a name to the project by writing UWPHelloWorld in the Name field. Click OK to create a new UWP project. You can see the newly created project in the Solution Explorer. This is a blank app but it contains many files, which is the minimum requirement for any UWP application. MainPage.xaml and MainPage.xaml.cs run when you execute your application. By default, MainPage.xaml file contains the following information. <Page x:Class = ”UWPHellowWorld.MainPage” xmlns = ”http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = ”http://schemas.microsoft.com/winfx/2006/xaml” xmlns:local = ”using:UWPHellowWorld” xmlns:d = ”http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = ”http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable = ”d”> <Grid Background = ”{ThemeResource ApplicationPageBackgroundThemeBrush}”> </Grid> </Page> Given below is the default information available in MainPage.xaml.cs. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace UWPHellowWorld { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage(){ this.InitializeComponent(); } } } Let us add some Text Blocks, a textbox, and a button as shown in the XAML code below. <Page x:Class = ”UWPHellowWorld.MainPage” xmlns = ”http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = ”http://schemas.microsoft.com/winfx/2006/xaml” xmlns:local = ”using:UWPHellowWorld” xmlns:d = ”http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = ”http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable = ”d”> <Grid Background = ”{ThemeResource ApplicationPageBackgroundThemeBrush}”> <StackPanel HorizontalAlignment = ”Center”> <TextBlock Text = ”Hello, world!” Margin = ”20” Width = ”200” HorizontalAlignment = ”Left”/> <TextBlock Text = ”Write your name.” Margin = ”20” Width = ”200” HorizontalAlignment = ”Left”/> <TextBox x:Name = ”txtbox” Width = ”280” Margin = ”20” HorizontalAlignment = ”Left”/> <Button x:Name = ”button” Content = ”Click Me” Margin = ”20” Click = ”button_Click”/> <TextBlock x:Name = ”txtblock” HorizontalAlignment = ”Left” Margin = ”20”/> </StackPanel> </Grid> </Page> Given below is the click-event button in C#. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace UWPHellowWorld { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private void button_Click(object sender, RoutedEventArgs e) { if (txtbox.Text != “”) txtblock.Text = “Hello: “ + txtbox.Text; else txtblock.Text = “You have not write your name”; } } } In the UWP project, device preview option is available on the Design Window, with the help of which you can change the layout easily, to fit into the screen size of all the devices in a device family you are targeting for your application. You can run and test your app either on a local machine, a simulator or an emulator, or on a remote device. You can select the target device from the following menu as shown below − Let us run the above code on a local machine and you will see the following window. Now, write any name in the text box and click the button Click Me. Now, if you want to test your app on an emulator, you can select a particular emulator from the menu and execute your application. You will see the following emulator − We recommend you to execute the above application with different devices. Print Page Previous Next Advertisements ”;
Windows 10 – Store
Windows 10 Development – Store ”; Previous Next The benefit of Windows Store for developers is that you can sell your application. You can submit your single application for every device family. The Windows 10 Store is where applications are submitted, so that a user can find your application. In Windows 8, the Store was limited to application only and Microsoft provides many stores i.e. Xbox Music Store, Xbox Game Store etc. In Windows 8, all these were different stores but in Windows 10, it is called Windows Store. It is designed in a way where users can find a full range of apps, games, songs, movies, software and services in one place for all Windows 10 devices. Monetization Monetization means selling your app across desktop, mobile, tablets and other devices. There are various ways that you can sell your applications and services on Windows Store to earn some money. You can select any of the following methods − The simplest way is to submit your app on store with paid download options. The Trails option, where users can try your application before buying it with limited functionality. Add advertisements to your apps with Microsoft Advertising. Microsoft Advertising When you add Ads to your application and a user clicks on that particular Ad, then the advertiser will pay you the money. Microsoft Advertising allows developers to receive Ads from Microsoft Advertising Network. The Microsoft Advertising SDK for Universal Windows apps is included in the libraries installed by Visual Studio 2015. You can also install it from visualstudiogallery Now, you can easily integrate video and banner Ads into your apps. Let us have a look at a simple example in XAML, to add a banner Ad in your application using AdControl. Create a new Universal Windows blank app project with the name UWPBannerAd. In the Solution Explorer, right click on References Select Add References, which will open the Reference Manager dialog. From the left pane, select Extensions under Universal Windows option and check the Microsoft Advertising SDK for XAML. Click OK to Continue. Given below is the XAML code in which AdControl is added with some properties. <Page x:Class = “UWPBannerAd.MainPage” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:local = “using:UWPBannerAd” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” xmlns:UI = “using:Microsoft.Advertising.WinRT.UI” mc:Ignorable = “d”> <Grid Background = “{ThemeResource ApplicationPageBackgroundThemeBrush}”> <StackPanel HorizontalAlignment = “Center”> <UI:AdControl ApplicationId = “d25517cb-12d4-4699-8bdc-52040c712cab” AdUnitId = “10043121” HorizontalAlignment = “Left” Height = “580” VerticalAlignment = “Top” Width = “800”/> </StackPanel> </Grid> </Page> When the above code is compiled and executed on a local machine, you will see the following window with MSN banner on it. When you click this banner, it will open the MSN site. You can also add a video banner in your application. Let us consider another example in which when the Show ad button is clicked, it will play the video advertisement of Xbox One. Given below is the XAML code in which we demonstrate how a button is added with some properties and events. <Page x:Class = “UWPBannerAd.MainPage” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:local = “using:UWPBannerAd” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” xmlns:UI = “using:Microsoft.Advertising.WinRT.UI” mc:Ignorable = “d”> <Grid Background = “{ThemeResource ApplicationPageBackgroundThemeBrush}”> <StackPanel HorizontalAlignment = “Center”> <Button x:Name = “showAd” Content = “Show Ad” HorizontalAlignment = “Left” Margin = “138,296,0,0” VerticalAlignment = “Top” FontSize = “48” Click = “showAd_Click”/> </StackPanel> </Grid> </Page> Given below is the click event implementation in C#. using Microsoft.Advertising.WinRT.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace UWPBannerAd { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { InterstitialAd videoAd = new InterstitialAd(); public MainPage() { this.InitializeComponent(); } private void showAd_Click(object sender, RoutedEventArgs e) { var MyAppId = “d25517cb-12d4-4699-8bdc-52040c712cab”; var MyAdUnitId = “11388823”; videoAd.AdReady += videoAd_AdReady; videoAd.RequestAd(AdType.Video, MyAppId, MyAdUnitId); } void videoAd_AdReady(object sender, object e){ if ((InterstitialAdState.Ready) == (videoAd.State)) { videoAd.Show(); } } } } When the above code is compiled and executed on a local machine, you will see the following window, which contains a Show Ad button. Now, when you click on the Show Ad button, it will play the video on your app. Print Page Previous Next Advertisements ”;
Windows 10 – Data Binding
Windows 10 Development – Data Binding ”; Previous Next Data binding is a mechanism in XAML application, which provides a simple and easy way for Windows Runtime apps using partial classes to display and interact with data. The management of data is entirely separated from the way data is displayed in this mechanism. Data binding allows the flow of data between UI elements and data object on user interface. When a binding is established and the data or your business model changes, then it reflects the updates automatically to the UI elements and vice versa. It is also possible to bind, not to a standard data source, but rather to another element on the page. Data binding can be − One-way data binding Two-way data binding Element Binding One-way Data Binding In one-way binding, the data is bound from its source, (the object that holds the data) to its target (the object that displays the data). Let us have a look at a simple example of one way data binding. Given below is the XAML code in which four text blocks are created with some properties. <Page x:Class = “OneWayDataBinding.MainPage” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:local = “using:OneWayDataBinding” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable = “d”> <Grid Background = “{ThemeResource ApplicationPageBackgroundThemeBrush}”> <StackPanel Name = “Display”> <StackPanel Orientation = “Horizontal” Margin = “50, 50, 0, 0”> <TextBlock Text = “Name: ” Margin = “10” Width = “100”/> <TextBlock Margin = “10” Width = “100” Text = “{Binding Name}”/> </StackPanel> <StackPanel Orientation = “Horizontal” Margin = “50,0,50,0”> <TextBlock Text = “Title: ” Margin = “10” Width = “100”/> <TextBlock Margin = “10” Width = “200” Text = “{Binding Title}” /> </StackPanel> </StackPanel> </Grid> </Page> The Text properties of two text blocks are set to “Name” and “Title” statically, while the other two Text properties of the text blocks are bind to “Name” and “Title” which are class variables of Employee class as shown below. using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace OneWayDataBinding { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage(){ this.InitializeComponent(); DataContext = Employee.GetEmployee(); } } public class Employee { public string Name { get; set; } public string Title { get; set; } public static Employee GetEmployee() { var emp = new Employee() { Name = “Waqar Ahmed”, Title = “Development Manager” }; return emp; } } } In the Employee class, we have variables Name and Title and one static method in which the employee object is initialized and will return that employee object. Therefore, we are binding to the property, Name and Title, but we have not yet selected the object to which the property belongs. The easy way is to assign an object to DataContext, whose properties we are binding in the MainPage Constructor. When you run this application, you can immediately see in your MainWindow that you have successfully bound to the Name and Title of that Employee object. Two-way Data Binding In Two-Way Binding, the user is able to modify the data through the user interface and have that data updated in the source. For example, if the source changes while the user is looking at the view, you want the view to be updated. Let us have a look at the below given example in which two labels, two text boxes and one button are created with some properties and events. <Page x:Class = “TwoWayDataBinding.MainPage” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:local = “using:TwoWayDataBinding” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable = “d”> <Grid Background = “{ThemeResource ApplicationPageBackgroundThemeBrush}”> <Grid.RowDefinitions> <RowDefinition Height = “Auto” /> <RowDefinition Height = “Auto” /> <RowDefinition Height = “*” /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width = “Auto” /> <ColumnDefinition Width = “200” /> </Grid.ColumnDefinitions> <TextBlock Name = “nameLabel” Margin = “200,20,0,0”>Name:</TextBlock> <TextBox Name = “nameText” Grid.Column = “1” Margin = “10,20,0,0” Text = “{Binding Name, Mode = TwoWay}”/> <TextBlock Name = “ageLabel” Margin = “200,20,0,0” Grid.Row = “1”>Age:</TextBlock> <TextBox Name = “ageText” Grid.Column = “1” Grid.Row = “1” Margin = “10,20,0,0” Text = “{Binding Age, Mode = TwoWay}”/> <StackPanel Grid.Row = “2” Grid.ColumnSpan = “2”> <Button Content = “Display” Click = “Button_Click” Margin = “200,20,0,0”/> <TextBlock x:Name = “txtblock” Margin = “200,20,0,0”/> </StackPanel> </Grid> </Page> We can observe the following − The Text properties of both the text boxes bind to the “Name” and “Age” which are class variables of Person class as shown below. In Person class, we have just two variables − Name and Age, and its object is initialized in the MainWindow class. In XAML code, we are binding to the property − Name and Age, but we have not selected the object to which the property belongs. The easier way is to assign an object to the DataContext, whose properties we are binding in the C# code as shown below in the MainWindowconstructor. using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace TwoWayDataBinding { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { Person person = new Person { Name = “Salman”, Age = 26 }; public MainPage() { this.InitializeComponent(); this.DataContext = person; } private void Button_Click(object sender, RoutedEventArgs e) { string message = person.Name + ” is ” + person.Age + ” years old”; txtblock.Text = message; } } public class Person { private string nameValue; public string Name { get { return nameValue; } set { nameValue = value; } } private double ageValue; public double Age { get { return ageValue; } set { if (value != ageValue) { ageValue = value; } } } } } When the above code is compiled and executed, you will see the following window. Click the Display button. Let us change the Name and Age and
Windows 10 – Adaptive Design
Windows 10 Development – Adaptive Design ”; Previous Next In Windows 10, Universal Windows Platform (UWP) applications will now run on a number of device families such as − Desktop device family − Tablets, laptops, PCs Mobile device family − Windows Phones, phablets IoT device family − Compact devices such as wearables or household appliances Team device family − Surface hub Each device family has its own screen and window size. So how to design an app that provides a great user experience on several devices with dramatically different screen sizes and different input methods? Designing your application for multiple device families requires some additional consideration, planning, and design. Windows 10 UWP provides a set of built-in features and universal building blocks that make it much easier to design for multiple devices and automatically scale across the different screen and window sizes, supported by the platform controls. New Built-in Features Following are the new features that the developers can use while creating a UWP application. These features are automatic and free. Effective Pixels and Platform Scaling When your UWP application runs on any device supported by Windows 10, then − The system uses an algorithm to normalize the way controls, fonts, and other UI elements are displayed on the screen of a device on which it is currently running. Scaling algorithm, controls the viewing distance and screen density (pixels per inch) to optimize for supposed size (rather than physical size). The scaling algorithm ensures that a 36 px font on Surface Hub 10 feet away is just as readable to the user as a 36 px font on 5”” phone that is a few inches away. Universal Input and Smart Interactions Universal Windows Platform has built-in smart interactions input systems, which understand input for all the devices. For example, when you design a click interaction in your application, then you do not need to know whether the click comes from an actual mouse click or the tap of a finger. The system will do it automatically for you. Universal Building Blocks There are some valuable building blocks, which make it easier to design the applications for multiple device families in Universal Windows Platform (UWP). Universal Controls UWP provides a set of Universal Controls that are guaranteed to work well on all Windows 10 devices. This ‘Universal controls’ list contains common controls like radio button, combobox and text box etc. It also contains some sophisticated controls like grid view and list view that can generate a list of items from a stream of data and a template. Universal Styles UWP app automatically gets a default set of styles that gives you these features − A set of styles that automatically give your app a light or dark theme. Default animations for interactions. Automatic support for high-contrast modes. Automatic support for other languages. Our default styles automatically select the correct font for every language that the Windows supports. You can even use multiple languages in the same app and they will be displayed properly. Print Page Previous Next Advertisements ”;
Windows10 Dev – Connected Experience ”; Previous Next As we already know, in Windows 10 we can create an application which can be executed and run on multiple Windows 10 devices. Let us suppose that we have these different devices and we want to make it feel like that it is one application even though it is running on different devices. In the Universal Windows Platform (UWP), you can run a single application on all Windows 10 devices, and you can give the user a feeling that it is one application. This is known as connecting experience. Important features of connected experience − Windows 10 is the first step to an era of more personal computing where your apps, services and content can move with you across devices, seamlessly and easily. With connected experience, you can easily share your data and personal settings related to that application and it will be available on all devices. In this chapter we will learn − where these shared data or settings will be stored so that it can be available on your devices for that one application. how the user is identified; that it is the same user which is using the same application on different devices. Windows 10 takes a bold step forward. When you login to Windows 10 with either Microsoft account (MSA) or with your enterprise or (work) account, it is assumed that − You have free access to OneDrive for MSA account, and you have access to Active Directory (AD) and Azure Active Directory (AAD), which is a cloud version with your enterprise account. You have access to different applications and resources. The Devices and applications are in roaming state and settings. Roaming in Windows 10 When you logon to a PC, you set some preferences like lock screen or background color or personalize your different kinds of settings. If you have more than one computer or device, which are running on Windows 10, your preferences and settings on one device will be synchronized from cloud, when you login to other devices with the same account. In Windows 10, when you have set or personalized your application settings, then these settings will roam with Roaming APIs available in UWP. When you run the same application again on other device, then it will first retrieve the settings and apply those settings to the application on that device. There is a limit of 100KB for uploading roaming data to the cloud. If this limit exceeds, then synchronization will stop and will just behave like a local folder. The RoamingSettings APIs are exposed as dictionary in which an application can save data. Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings; // Retrivve value from RoamingSettings var colorName = roamingSettings.Values[“PreferredBgColor”].ToString(); // Set values to RoamingSettings roamingSettings.Values[“PreferredBgColor”] = “Green”; When the data changes in RoamingSettings then it fires the DataChanged event, where you can refresh your settings. Windows.Storage.ApplicationData.Current.DataChanged += RoamingDataChanged; private void RoamingDataChanged(Windows.Storage.ApplicationData sender, object args) { // Something has changed in the roaming data or settings } Let us look at an example, in which we will set the background color of the application and these settings will roam with Roaming APIs available in UWP. Given below is the XAML code in which different controls are added. <Page x:Class = “RoamingSettingsDemo.Views.MainPage” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:local = “using:RoamingSettingsDemo.Views” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” mc:Ignorable = “d”> <Grid x:Name = “MainGrid” Background = “{ThemeResource ApplicationPageBackgroundThemeBrush}”> <Grid.RowDefinitions> <RowDefinition Height = “80” /> <RowDefinition /> </Grid.RowDefinitions> <StackPanel Orientation = “Horizontal” VerticalAlignment = “Top” Margin = “12,12,0,0”> <TextBlock Style = “{StaticResource HeaderTextBlockStyle}” FontSize = “24” Text = “Connected Experience Demo” /> </StackPanel> <Grid Grid.Row = “1” Margin = “0,80,0,0”> <StackPanel Margin = “62,0,0,0”> <TextBlock x:Name = “textBlock” HorizontalAlignment = “Left” TextWrapping = “Wrap” Text = “Choose your background color:” VerticalAlignment = “Top”/> <RadioButton x:Name = “BrownRadioButton” Content = “Brown” Checked = “radioButton_Checked” /> <RadioButton x:Name = “GrayRadioButton” Content = “Gray” Checked = “radioButton_Checked”/> </StackPanel> </Grid> </Grid> </Page> C# implementation for RoamingSettings and different events is given below. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The RoamingSettingsDemo Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace RoamingSettingsDemo.Views { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { SetBackgroundFromSettings(); Windows.Storage.ApplicationData.Current.DataChanged += RoamingDataChanged; } protected override void OnNavigatedFrom(NavigationEventArgs e) { Windows.Storage.ApplicationData.Current.DataChanged -= RoamingDataChanged; } private void RoamingDataChanged(Windows.Storage.ApplicationData sender, object args) { // Something has changed in the roaming data or settings var ignore = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () ⇒ SetBackgroundFromSettings()); } private void SetBackgroundFromSettings() { // Get the roaming settings Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings; if (roamingSettings.Values.ContainsKey(“PreferBrownBgColor”)) { var colorName = roamingSettings.Values[“PreferBrownBgColor”].ToString(); if (colorName == “Gray”) { MainGrid.Background = new SolidColorBrush(Colors.Gray); GrayRadioButton.IsChecked = true; } else if (colorName == “Brown”) { MainGrid.Background = new SolidColorBrush(Colors.Brown); BrownRadioButton.IsChecked = true; } } } private void radioButton_Checked(object sender, RoutedEventArgs e){ if (GrayRadioButton.IsChecked.HasValue && (GrayRadioButton.IsChecked.Value == true)) { Windows.Storage.ApplicationData.Current.RoamingSettings. Values[“PreferBrownBgCo lor”] = “Gray”; } else { Windows.Storage.ApplicationData.Current.RoamingSettings. Values[“PreferBrownBgCo lor”] = “Brown”; } SetBackgroundFromSettings(); } } } When the above code is compiled and executed, you will see the following window. Let us choose gray color as the background color and close this app. Now, when you run this app on this device or any other device, you will see that the background color has changed to gray. This shows that the app has successfully retrieved the information of background color change in RoamingSettings. Print Page Previous Next Advertisements ”;