step-into-windows-10-uwp.pdf

Embed Size (px)

Citation preview

  • 8/19/2019 step-into-windows-10-uwp.pdf

    1/71

     

    Step into Windows 10 UWPThis free book is provided by courtesy of  C# Corner and Mindcracker Network and

    its authors. Feel free to share this book with your friends and co-workers. Please

    do not reproduce, republish, edit or copy this book.

    Suresh M

    Windows Phone Mobile App Developer,

    C# Corner MVP

    http://windowsapptutorials.wordpress.com 

    http://www.c-sharpcorner.com/http://windowsapptutorials.wordpress.com/http://windowsapptutorials.wordpress.com/http://windowsapptutorials.wordpress.com/http://www.c-sharpcorner.com/

  • 8/19/2019 step-into-windows-10-uwp.pdf

    2/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

    Table of Content 

    Part 1: Quick Introduction 

    Part 2: Requirements for Windows 10 UWP Development 

    Part 3: Life cycle of windows 10 Part 4: Writing your first Windows 10 UWP APP 

    Part 5: Show Message Dialog in Windows 10 

    Part 6: Windows 10 Application Bar 

    Part 7: Change Apps Title Bar Colour and Enable Back Button in Windows 10 UWP 

    Part 8: Windows 10 Split View-Hamburger Menu 

    Part 9: Send E-mail and SMS in windows 10 

    Part 10: Map control to show your current location and get the street address using GPS Co-

    ordinates in Windows 10 UWP 

    Part 11: 3D Map for Windows 10 UWP Part 12: File Picker in Windows 10 UWP 

    Part 13: Pick text file in Windows 10 UWP 

    Part 14: Drag and Drop functionality instead of File Picker in Windows 10 UWP 

    Part 15: Local Data Base SQLite for Windows 10 UWP 

    Part 16: Consume web service using HttpClient to POST and GET json data in Windows 10 UWP 

    Part 17: HTTP Live Streaming in Windows 10 

    Part 18: Background File Downloader for Windows 10 UWP 

    Part 19: RSS Reader in Windows 10 UWP App 

    Part 20: Sensors in Windows 10 UWP App Part 21: Set Specific Device Family XAML Views In Windows 10 UWP 

    Part 22: Drawing and Inking Using New InkCanvas Control for Windows 10 UWP App 

    Part 23: Disable screen capture in Windows 10 UWP

  • 8/19/2019 step-into-windows-10-uwp.pdf

    3/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

    Part 1: Quick Introduction

    Microsoft announced Windows 10 would be final windows version. It would evolve and changelike other software products but it will only get updates, because the fact that all windows

    platforms (mobile, desktop, Tab and Xbox etc.) has combined to a single Universal Platform

    means all have same OS (kernel), now it’s just Windows on phone. So, if you develop app for

    windows 10 it would run on all devices running windows 10 like Mobiles, Xbox, etc. Hope you

    got the idea of "Universal" word in UWP.

    Windows 10 is evolving as a rapid growth technology nowadays. In this book we are going to

    learn basic things of Windows 10 application development.

    Universal Windows Platform provides the common application platform and lets the developersbuild an app available on all the devices that runs on Windows 10 OS.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    4/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

    Part 2: Requirements for Windows 10 UWP Development 

    In this part we are going to see the requirements for developing Windows 10 applications and

    SDK used to develop Windows 10 apps.

    Hardware Requirements

      RAM: More than 4GB

      Hard Disk: Minimum 12GB Free space

      Virtual machine in Hyper-V

    Software Requirements

      OS: Windows 10 64-bit (Microsoft Recommended)

      Microsoft Visual Studio 2015 pro or community (Community edition is free)

      Writing your first Windows 10 application

      Windows 10 Emulator

  • 8/19/2019 step-into-windows-10-uwp.pdf

    5/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

    Part 3: Life cycle of Windows 10 

    In this part we are going to see the life cycle of Windows UWP 10 app.

    In Windows 10 the life cycle of App have three states.

      Running

      Suspended

      Not Running (Terminated)

    Running

    If the app running you get events, which you can access it in App.cs file.

    If you start the application it activates and comes to running state.

    If you run another application the other apps goes to background and waits for use to switch

    back to that app after certain time interval it moves to suspended state. These state considered

    as the app going to terminate (closed) state. Same process goes on until the system encounters

    low memory.

    Suspended 

    When the application move to the background or the device enters to the low power state, the

    application suspends automatically. While pushing the application to the background, the

    system waits for few seconds to make sure that the user switches back to the application

    immediately. After a few seconds time interval, the system automatically moves the application

    to the suspended state.

    Based on the system available memory, the system want to keep a number of suspended appsinto the memory to make sure the user can quickly switch back to the application. The app

    always resides in memory as long as your system has available memory to execute. If your

    available memory is low, the system automatically removes the unused application from

    memory.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    6/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

    We can resume a suspended application from background and bring it to the foreground thread.

    During the state transition, it loads the application data if you already saved during the

    suspension state.

    Not Running (Terminated) there is no event handler with the app termination. We can check

    whether the app got terminated earlier through the activation event.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    7/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

    Part 4: Writing Your First Windows 10 UWP App 

    In this part we are going to see how to create a new UWP project.

    Let’s start creating a new Windows 10 Blank App template with C# as language and then deployto run the app on Local Machine and Windows Mobile Emulator.

    After successful installation (If you face problem in installation contact me) start Visual Studio

    2015 and select new project to create new Windows 10 application. Name it “HelloWorldWin10”

    or as your wish like shown below.

    Click Ok to create new app. Now you can see your app like below.

    Open the MainPage.Xaml file in Visual Studio and add TextBlock in the existing grid. Set the Text

    property of the TextBlock to Hello World Windows 10 as in the following code.

     

    Welcome to Windows 10 

     

    Now time to run the app, by default, you will see that the solution is set to Debug and the

    platform is set to x86. The Start Debugging button will also be set to “Local Machine” by default.

    x86 will work for both mobile emulator and local machine. If you want to run this on the

    Windows Mobile device, you will have to set this as “Mobile Emulator”. 

  • 8/19/2019 step-into-windows-10-uwp.pdf

    8/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

    Click the Start Debugging button with the “Local Machine” option to deploy to run the app on

    the local machine.

    In design time itself you can see the different device view looks like the following:

    Now see the output for different device deployment.

    Windows 10 Mobile.

    Windows 10 Tab 

  • 8/19/2019 step-into-windows-10-uwp.pdf

    9/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

    Windows 10 Desktop

    Note: For Source Code. 

    https://gallery.technet.microsoft.com/How-to-develop-apps-for-869aaaafhttps://gallery.technet.microsoft.com/How-to-develop-apps-for-869aaaafhttps://gallery.technet.microsoft.com/How-to-develop-apps-for-869aaaafhttps://gallery.technet.microsoft.com/How-to-develop-apps-for-869aaaaf

  • 8/19/2019 step-into-windows-10-uwp.pdf

    10/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

    Part 5: Show Message Dialog in Windows 10 

    In this part we are going to see how to show a message dialog in your Windows 10 apps on the

    desktop and mobile devices using C# and XAML. The MessageDialog class is available in

    Windows 10. We now have a Universal Windows Platform (UWP).

    Create new Windows 10 UWP app and name it as you wish. Now go to Mainpage.Xaml and

    paste the following XAML code to create a button for showing message dialog.

     

    Now our design page looks like the following screen:

    Now go to code behind page and write the following code on button click event.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    11/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            1

    private async void Showbutton_Click(object sender, RoutedEventArgs e)

    {

    MessageDialog showDialog = new MessageDialog("Hi Welcome to Windows 10");

    showDialog.Commands.Add(new UICommand("Yes")

    {

    Id = 0 });

    showDialog.Commands.Add(new UICommand("No")

    {

    Id = 1 

    });

    showDialog.DefaultCommandIndex = 0;

    showDialog.CancelCommandIndex = 1;

    var result = await showDialog.ShowAsync();

    if  ((int) result.Id == 0)

    {

    //do your task 

    }else 

    {

    //skip your task 

    }

    }

    Create an instance of the MessageDialog with the Message and Title if required.

    UICommands are added to the commands collection of the dialog. Default Command index is set

    to 0 for (Yes) button to invoke user hit the enter key and the Cancel Command index is set to 1

    for (No) button to invoke user hit the Escape or No button.

    Use ShowAsync() method to show the dialog and check the result containing command id and

    perform the yes or no task.

    Now run your app with Local Machine, Mobile and Simulator to see the output as in the

    following image.

    Local Machine

  • 8/19/2019 step-into-windows-10-uwp.pdf

    12/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            1

     

    Mobile

  • 8/19/2019 step-into-windows-10-uwp.pdf

    13/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            1

     

    Simulator

    Simulator and Mobile

    Part 6: Windows 10 Application Bar 

    The App bar is designed to expose application commands to the user. There are two types of

    app bar you can use.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    14/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            1

      TopAppBar

      BottomAppBar

    You can put any control that you like into the app bar.

     

     

     

     

     

     

     

     

    Application Bar for Bottom,

     

     

     

     

     

     

     

  • 8/19/2019 step-into-windows-10-uwp.pdf

    15/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            1

       

     

     

     

     

     

     

     

     

     

     

      

     

     

     

     

    The app bar should be outside the grid control.

    You can minimize and maximize the app bar by default using the IsOpen="True" IsSticky="True" .

    To minimize the app bar set IsOpen property to false, by default it will be false.

    You can create the App Bar using C# code also using the following code:

    AppBar myAppBar = new AppBar(); myAppBar.IsOpen = true;

    var content = new StackPanel { Orientation = Orientation.Horizontal }; 

    content.Children.Add(new Button { Content = "Button1"});

    content.Children.Add(new Button { Content = "Button2" });

    myAppBar.Content = content;this.BottomAppBar = myAppBar;

    Application Bar is placed in the following screen at only bottom or top and both.

    If you are developing app for Windows 10 mobile place the app bar in bottom to find out easily.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    16/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            1

     

    Now run the app and see the output like the following:

  • 8/19/2019 step-into-windows-10-uwp.pdf

    17/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            1

    Part 7: Change Apps Title Bar Colour and Enable Back Button In Windows 10 UWP

    In this part we are going to see how to change the default application title bar colour in

    Windows 10 UWP.

    In Windows 10 by default the white title bars is available for all apps, sometimes we need to

    change for better UI. Using UI ViewManagement class we can get the application UI properties.

    So, I am going to get the title bar properties and change the colour using the following code:

    var appView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView();

    appView.TitleBar.BackgroundColor = Colors.LightBlue;

    appView.TitleBar.ButtonBackgroundColor = Colors.LightBlue;

    appView.TitleBar.ForegroundColor = Colors.White;

    appView.TitleBar.ButtonForegroundColor = Colors.White;

    Place this code in app launching event in App.xaml.cs file as in the following code. Full code

    looks like the following code:

    Now run the app and see the title bar it looks like the following image:

  • 8/19/2019 step-into-windows-10-uwp.pdf

    18/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            1

     

    Enable back button in the app title bar Windows 10 UWP 

    In Windows 10 UWP the back button is disabled by default. If you need back button in the

    application title bar you need to enable it. I will show how to enable this button.

    Write the following code to enable the back button.

    var view = SystemNavigationManager.GetForCurrentView(); view.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;

    Firstly, get the current view and enable the back button.

    Now create event handler for handling the back button click.

    view.BackRequested += View_BackRequested; 

    Add the following method to handle the back button click.

    private void View_BackRequested(object sender, BackRequestedEventArgs e)

    {

    //do your task 

    }

    The full source code looks like the following:

    var view = SystemNavigationManager.GetForCurrentView(); view.AppViewBackButtonVisibility =

    AppViewBackButtonVisibility.Visible; view.BackRequested += View_BackRequested;

    private void View_BackRequested(object sender, BackRequestedEventArgs e)

  • 8/19/2019 step-into-windows-10-uwp.pdf

    19/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            1

    {

    //do your task 

    }

    Now run the app and see the output looks like the following image:

  • 8/19/2019 step-into-windows-10-uwp.pdf

    20/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            1

    Part 8: Windows 10 Split View-Hamburger Menu 

    In this part we are going to see how to create SplitView/Hamburger menu in Windows UWP 10

    app.

    The new control SplitView added in Windows 10 and is used to display side menu. Many of them

    call it hamburger menu. Two things we need to know “Pane” and “Content”. 

    Pane 

    These properties contain the menu buttons in your app.

    Content 

    The page content goes in this area.

     

     

    //Add your menu here

     //Add your content here

     

    Using “IsPaneOpen” property you can set true or false, true for open and false to close. 

    Now create a new Windows 10 project and give proper name. After that open

    Your Mainpage.xaml  and you can see the empty grid control as in the following screenshot:

  • 8/19/2019 step-into-windows-10-uwp.pdf

    21/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            2

     

    Delete this grid and paste the following code:

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    In the above code we are creating the button in menu and styling to hamburger menu. We don’t

    need to add icons for button just change the font family to “Segoe MDL2 Assets” and set the

    content (cheat code) as your wish to see more icons cheat sheet codes.

    For example, I set the content as “E700;” and it looks like the following image,

  • 8/19/2019 step-into-windows-10-uwp.pdf

    22/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            2

     

    Now you can create button as your need. Here, I create 4 buttons for sample.

    Finally, go to code behind page and I have one button click event to close and open the split

    view. In handler we simply want to set pane to close if it is open and vice versa like the following

    code:

    private void HamburgerButton_Click(object sender, RoutedEventArgs e)

    {

    MyMenu.IsPaneOpen = !MyMenu.IsPaneOpen;

    }

    private void button3_Click(object sender, RoutedEventArgs e)

    {

    Frame.Navigate(typeof (Page1))

    }

    Now run the app and see the excepted output like the following screen:

  • 8/19/2019 step-into-windows-10-uwp.pdf

    23/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            2

     

  • 8/19/2019 step-into-windows-10-uwp.pdf

    24/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            2

    Part 9: Send E-mail and SMS in windows 10 

    In this part we are going to see how to show email and SMS compose task to send an email and

    SMS in Windows 10.

    Create new Windows 10 project.

    Now create two buttons: one id for sending email and another for sending SMS.

    To send E-mail 

    Firstly, we are going to see how to send email. Write the following code:

    private async void ComposeEmail(Contact Torecipient, string messageBody)

    {

    var to = Torecipient.Emails.FirstOrDefault < Windows.ApplicationModel.Contacts.ContactEmail > 

    ();

    var emailRecipient = new Windows.ApplicationModel

    .Email.EmailRecipient(to.Address);

    EmailMessage objEmail = new EmailMessage();

    objEmail.Subject = "Suresh";

    objEmail.To.Add(emailRecipient);

    await EmailManager.ShowComposeNewEmailAsync(objEmail);

    }

    You can attach files also while sending email to attach the files write the following code before

    composing the email task.

    var stream = Windows.Storage.Streams. RandomAccessStreamReference .CreateFromFile(attachment);  

    var attachment = new Windows.ApplicationModel.Email.EmailAttachment( attachment.Name,

    stream);

    emailMessage.Attachments.Add(attachment);

    To send SMS 

    To send an SMS write the following code:

    private async void ComposeSMS(Contact toContatc, string message)

    {

    var chatMessage = new Windows.ApplicationModel

    .Chat.ChatMessage();

    chatMessage.Body = message;

  • 8/19/2019 step-into-windows-10-uwp.pdf

    25/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            2

      var phone = toContatc.Phones.FirstOrDefault < Windows.ApplicationModel.Contacts.ContactPhone >

    ();

    chatMessage.Recipients.Add(phone.Number);

    await Windows.ApplicationModel.Chat.ChatMessageManager

    .ShowComposeSmsMessageAsync(c hatMessage);

    }

  • 8/19/2019 step-into-windows-10-uwp.pdf

    26/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            2

    Part 10: Map control to show your current location and get the street address

    using GPS Co-ordinates in Windows 10 UWP 

    In this part we are going to see how to use map control and get the current GPS co-ordinates

    street address in Windows 10 UWP app.

    Create new Windows 10 project and choose the map control from toolbox list.

    Geo Location API allows easy to access the current location of device. Here we will see how to

    get the longitude and latitude co-ordinates of the device.

    Firstly, enable the location capabilities to allow the device to access the location like the

    following screen:

    Next add the following namespace in you code page:

    using Windows.Devices.Geolocation; using Windows.Services.Maps;

  • 8/19/2019 step-into-windows-10-uwp.pdf

    27/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            2

    Create new instance for Geolocator using that we can retrieve the position of our device. Then

    add the location coordinate points to our map control.

    Write the following code to set your position to the map control.

    var geolocator = new Geolocator();

    var position = await geolocator.GetGeopositionAsync();  

    mymap.Center = position.Coordinate.Point; 

    mymap.ZoomLevel = 15;

    Set the map zoom level according to your needs and you will get the co-ordinates of the current

    position.

    Next we are going to get the current street address of the position using the coordinates.

    You will get the following details also:

     

    BuildingFloor

      BuildingName

      BuildingRoom

      BuildingWing

      Continent

      Country

      CountryCode

      District

     

    FormattedAddress

      Neighborhood

      PostCode

      Region

      RegionCode

      Street

      StreetNumber  Town

    Write the following code to get the address of the street.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    28/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            2

    var mapLocation = await

    MapLocationFinder.FindLocationsAtAsync(position.Coordinate.Point); if

    (mapLocation.Status == MapLocationFinderStatus.Success)

    {

    string address = mapLocation.Locations[0].Address.StreetNumber + " " + 

    mapLocation.Locations[0].Address.Street;

    }

    else 

    {

    dialog.Content = "Not Found";

    }

    Now run the app and see the output like the following screen:

  • 8/19/2019 step-into-windows-10-uwp.pdf

    29/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            2

     

    Part 11: 3D Map for Windows 10 UWP 

    In this part we are going to see how to show 3-D map in Windows 10 UWP App.

    In normal map we only have an option to show the map in Satellite or Ariel view but in Windows

    10 we have option to show 3D map. It’s very easy to implement 3D map in Universal App.

    Now we are going to see how to create a map control to display the map normally and then set

    the map control to show the map in 3D. Map control with 3D helps the user to view the location

    at any angle.

    Let’s create new Windows 10 Universal Windows app.

    Firstly, enable the app capabilities “Location” to allow your app to access the location. Open

    “Package.appxmanifest” file and enable location like below. 

    Next go to your MainPage.XAML and add the following xmlns:

    xmlns:maps="using:Windows.UI.Xaml.Controls.Maps" 

    Add the MapControl using the following xaml code:

  • 8/19/2019 step-into-windows-10-uwp.pdf

    30/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            2

    Now go to code behind page and follow the below steps.

    Firstly, check the map supports 3D.

    Set the map style Aerial3DwithRoads or Aerial3D as your wish. Then set the position latitude andlongitude finally call the TrySetSceneAsync  method by passing map scene.

    The full code looks like below.

    private async void my3dMap_Loaded(object sender, RoutedEventArgs e)

    {

    if (my3dMap.Is3DSupported)

    {

    my3dMap.Style =

    MapStyle.Aerial3DWithRoads;

    BasicGeoposition geoposition = new 

    BasicGeoposition(); geoposition.Latitude =8.4875;

    geoposition.Longitude = 76.9525;

    Geopoint location = new Geopoint(geoposition);

    MapScene mapScene = MapScene.CreateFromLocationAndRadius(location,500, 150, 70); await my3dMap.TrySetSceneAsync(mapScene);

    }

    }

  • 8/19/2019 step-into-windows-10-uwp.pdf

    31/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            3 

     

    Now run the app and you can see the following output:

    Note: It is showing warning message MapServiceToken not specified for that we need to get the

    token from Bing map development Center.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    32/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            3 

     

    Part 12: File Picker in Windows 10 UWP 

    In this part we are going to see the FileOpenPicker in Windows 10 application.

    In Windows 10 we have OpenFileDialog which opens a dialog to pick the files. Here we are going

    to pick the image file in Windows 10.

    Create new Windows 10 project and create a button and image control to perform FilePicker

    operation.

    Firstly, create a new instance for FileOpenPicker as in the following snippet:

    FileOpenPicker openPicker = new FileOpenPicker();

    Next, we have to set file picker ViewMode, you could ignore this, but if you would like to add,

    there are two options such as List and Thumbnail. Here, I am going to set thumbnail.

    openPicker.ViewMode = PickerViewMode.Thumbnail;

    Then set the suggested location as your wish I am going to set default location as picture library.

    openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;

    We need to add FileTypeFilter , mandatory fields you should add. It requires at least one type.

    The FileTypeFilter  is a readonly collection. We would be able to add values. Here I am setting

    filter type for png and jpg images.

    openPicker.FileTypeFilter.Add( ".jpg");

    openPicker.FileTypeFilter.Add( ".png");

    Finally, we are going to show the file picker dialog as in the following code and we have the

    option to select single or multiple file selection.

    For single file selection:

    StorageFile file = await openPicker.PickSingleFileAsync();

    For multiple file selection:

  • 8/19/2019 step-into-windows-10-uwp.pdf

    33/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            3 

    StorageFile file = await openPicker.PickMultipleFilesAsync();

    Finally, we are going to set the selected image stream to empty image control.

    if (file!=null)

    {

    var stream = await file.OpenAsync(Windows.Storage. FileAccessMode.Read); var image = new BitmapImage(); 

    image.SetSource(stream);imageView.Source =

    image; 

    }

    else 

    {

    // }

    The whole code looks like the following code:

    private async void openBtn_Click(object sender, RoutedEventArgs e)

    {

    FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode =

    PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation =

    PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".jpg");

    openPicker.FileTypeFilter.Add(".png");

    StorageFile file = await openPicker.PickSingleFileAsync();

    if (file!=null)

    {

    var stream = await file.OpenAsync(Windows.Storage. FileAccessMode.Read); var

    image = new BitmapImage(); 

    image.SetSource(stream);

    imageView.Source = image; }

    else 

    {

    // 

    }

  • 8/19/2019 step-into-windows-10-uwp.pdf

    34/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            3 

    }

    For multiple file selection,

    foreach(var files in filelist)

    {

    var stream = await file.OpenAsync(Windows.Storage. FileAccessMode.Read); var image = newBitmapImage(); 

    image.SetSource(stream);

    yourimagelist.Add(image);

    }

    Finally, run your app and you can see the following output:

  • 8/19/2019 step-into-windows-10-uwp.pdf

    35/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            3 

    Part 13: Pick text file in windows 10 

    In this part we are going to see how to open text file using FileOpenPicker in Windows 10

    application.

    In Windows 10 we have OpenFileDialog which opens a dialog to pick the files. Here we are going

    to pick the text file in Windows 10.

    Create new Windows 10 project and create a button and image control to perform File Picker

    operation.

    Firstly, create a new instance for FileOpenPicker as in the following code snippet:

    FileOpenPicker openPicker = new FileOpenPicker(); 

    Next, we have to set file picker ViewMode, you could ignore this, but if you would like to add,

    there are two options, such as List and Thumbnail. Here I will set thumbnail.

    openPicker.ViewMode = PickerViewMode.Thumbnail;

    Then set the suggested location as you wish. I am going to set default location as document

    library.

    openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; 

    We need to add FileTypeFilter; it is a mandatory field that you should add. It requires at leastone type.

    The FileTypeFilter is a readonly collection. We would be able to add values.

    Here I am setting filter type for .txt files.

    openPicker.FileTypeFilter.Add(".txt");

    Finally, we are going to show the file picker dialog as in the following code snippet and we have

    the option to select single or multiple file selection.

    StorageFile file = await openPicker.PickSingleFileAsync(); 

    Finally, we are going to read the selected file using stream and assign it to textblock.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    36/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            3 

    private async void buttonPick_Click(object sender, RoutedEventArgs e)

    {

    FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode =

    PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation =

    PickerLocationId.DocumentsLibrary; openPicker.FileTypeFilter.Add(".txt");StorageFile file = await openPicker.PickSingleFileAsync();

    if (file != null)

    {

    var stream = await file.OpenAsync(Windows.Storage. FileAccessMode.Read); using

    (StreamReader reader = new StreamReader(stream.AsStream()))  

    {

    textBlockShow.Text = reader.ReadToEnd();

    }

    }

    else 

    {

    }

    }

    Now run debug and run the app and you can see the following output:

  • 8/19/2019 step-into-windows-10-uwp.pdf

    37/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            3 

     

    Part 14: Drag and Drop functionality instead of File Picker in Windows 10 

    In this part we are going to see drag-and-drop functionality in Windows 10 UWP app.

    In Windows 10 platform, a new drag-and-drop functionality was introduced to WindowsUniversal apps for scenarios such as dragging image or document from your local machine

    straight into your app. It allows us developers to support more intuitive experiences. Drag and

    drop is a good way to transfer data within an application or between applications using a

    standard gesture.

    Let’s see how simple it is to drag and drop image from your local system desktop into your 

    Windows 10 Universal apps.

    Steps: 

    Create new Windows 10 blank project and give suitable name.

    Open your MainPage.XAML page and go to xaml code area in that create one StackPanel and

    allow drop property to true. Attach an event handler to Drop and DropOver event, which will be

  • 8/19/2019 step-into-windows-10-uwp.pdf

    38/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            3 

    used to handle an event of dropping image or document on the stackpanel. DropOver will be

    used to allow image copying while it's dragged over the stackpanel.

    Add an Image object inside to show the image which was dropped.

    Full source code looks like the following,

     

     

     

     

     

     

    Now go to code behind page and write the following code in drop and dragover event handler.

    private async void StackPanel_Drop(object sender, DragEventArgs e)

    {

    if (e.DataView.Contains(StandardDataFormats.StorageItems))

    {

    var items = awaite.DataView.GetStorageItemsAsync();if (items.Any())

    {var storeFile= items[0] as StorageFile; varbitmapImage = new

    BitmapImage(); 

    bitmapImage.SetSource( await 

    storeFile.OpenAsync(FileAccessMode.Read));dragedImage.Source = bitmapImage; 

    }

    }

    }

    private void StackPanel_DragOver(object sender, DragEventArgs e)

    {

    e.AcceptedOperation = DataPackageOperation.Copy;

    }

  • 8/19/2019 step-into-windows-10-uwp.pdf

    39/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            3 

     

    When image is being dragged over the stackpanel the DragOver event handler will be fired in

    that event. I am going to allow copying the dragged image.

    When the photo gets dropped the drop event will be fired and here I will take it rom the

    StorageItems collection and set the source for draggedImage image.

    You can set the caption also for better user experience for that change the dragover event code

    like the following:

    private void StackPanel_DragOver(object sender, DragEventArgs e)

    {

    e.AcceptedOperation = DataPackageOperation.Copy;

    e.DragUIOverride.Caption = "You are dragging a image";

    e.DragUIOverride.IsCaptionVisible = true;e.DragUIOverride.IsContentVisible = true;

    }

    Now run the app and you can see the following output:

    While drag the image in to stackpanel.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    40/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            3 

    After dropped into the stackpanel

    Part 15: Local Data Base SQLite for Windows 10 UWP

    In this part we are going to learn how to create local DB for Windows 10 app and perform the

    CRUD (Create Read Update and Delete) operation in Windows 10 database.

    See the step by step implementation.

    Introduction

    SQLite is a lightweight database used for mobile local storages.

    Create new UWP project.

    Setup SQLite environment.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    41/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            4 

    Install SQLite-UAP extensions form NuGet Package Manager as in the following screenshot:

    Next, install SQLite.Net-PCL extension from NuGet Package:

    Now, we are going to the following areas:

      How to perform SQLite CRUD operations.

      How to bind SQLite data to a ListBox

    Design the UI as in the following:

  • 8/19/2019 step-into-windows-10-uwp.pdf

    42/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            4 

    XAML Code

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    Now write the following code in your corresponding button click events.

    I am going to create one Student DB with Students Table with id, Name, Address and Mobile so

    first design the table as in the following:

  • 8/19/2019 step-into-windows-10-uwp.pdf

    43/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            4 

    public class Students 

    {

    [SQLite.Net.Attributes.PrimaryKey,SQLite.Net.Attributes.AutoIncrement] public int Id { get; set; }

    public string Name { get; set; } public string Address { get; set;

    } public string Mobile { get; set;

    } public Students()

    {

    }

    public Students(string name, string address, string mobile)

    {

    Name =

    name;

    Address =

    address;

    Mobile =

    mobile; 

    }

    }

    Create DB 

    public static void CreateDatabase()

    {

    var sqlpath = 

    System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Pat

    h, "Studentdb.sqlite");

    using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(newSQLite.Net.Platform.WinRT. SQLitePlatformWinRT(), sqlpath)) 

    {

    conn.CreateTable();

    }

    }

    Insert New Student details

    public void Insert(Students objContact)

    {

  • 8/19/2019 step-into-windows-10-uwp.pdf

    44/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            4 

     var sqlpath = 

    System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,

    "Studentdb.sqlite");

    using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(newSQLite.Net.Platform.WinRT. SQLitePlatformWinRT(), sqlpath)) 

    {

    conn.RunInTransaction(() =>

    {

    conn.Insert(objContact);

    });

    }

    }

    Retrieve the specific contact from the database.

    // Retrieve the specific contact from the database. public

    Students ReadContact(int contactid) 

    {

    var sqlpath = 

    System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,

    "Studentdb.sqlite");

    using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(newSQLite.Net.Platform.WinRT. SQLitePlatformWinRT(), sqlpath)) 

    {

    var existingconact = conn.Query("select * from Students whereId =" + contactid).FirstOrDefault();

    return existingconact;

    }

    }

    Read all student details

    //Read All Student details public ObservableCollection ReadAllStudents()

    {

    var sqlpath = 

    System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,

    "Studentdb.sqlite");

  • 8/19/2019 step-into-windows-10-uwp.pdf

    45/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            4 

     

    using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(newSQLite.Net.Platform.WinRT. SQLitePlatformWinRT(), sqlpath)) 

    {

    List myCollection = conn.Table().ToList(); ObservableCollection StudentsList = new 

    ObservableCollection(myCollection);  

    return StudentsList;

    }

    }

    Update student details

    //Update student detaisl 

    public void UpdateDetails(string name)

    {

    var sqlpath = 

    System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,

    "Studentdb.sqlite");

    using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new

    SQLite.Net.Platform.WinRT. SQLitePlatformWinRT(), sqlpath)) 

    {

    var existingconact = conn.Query("select * from Students where

    Name =" + name).FirstOrDefault();if (existingconact != null)

    {

    existingconact.Name = name;

    existingconact.Address =

    "NewAddress";

    existingconact.Mobile =

    "962623233";

    conn.RunInTransaction(() => 

    {

    conn.Update(existingconact);

    });}

    }

    }

  • 8/19/2019 step-into-windows-10-uwp.pdf

    46/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            4 

     

    Delete all student or delete student table

    //Delete all student or delete student table public

    void DeleteAllContact(){

    var sqlpath = 

    System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,

    "Studentdb.sqlite");

    using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new

    SQLite.Net.Platform.WinRT. SQLitePlatformWinRT(), sqlpath)) 

    {

    conn.DropTable

    ();

    conn.CreateTable(); conn.Dispose(); 

    conn.Close();

    }

    }

    Delete specific student

    //Delete specific student 

    public void DeleteContact(int Id)

    {

    var sqlpath = 

    System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,

    "Studentdb.sqlite");

    using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(newSQLite.Net.Platform.WinRT. SQLitePlatformWinRT(), sqlpath)) 

    {

    var existingconact = conn.Query("select * from Studentdb where

    Id =" + Id).FirstOrDefault();if (existingconact != null)

    {

    conn.RunInTransaction(() =>

    {

    conn.Delete(existingconact);

  • 8/19/2019 step-into-windows-10-uwp.pdf

    47/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            4 

    });

    }

    }

    }

    Now run the app with different devices and you will get the output as in the following:

    Here I have tested with Windows 10 Simulator.

    For source code. 

    https://code.msdn.microsoft.com/Local-Data-Base-SQLite-for-5e6146aahttps://code.msdn.microsoft.com/Local-Data-Base-SQLite-for-5e6146aahttps://code.msdn.microsoft.com/Local-Data-Base-SQLite-for-5e6146aahttps://code.msdn.microsoft.com/Local-Data-Base-SQLite-for-5e6146aa

  • 8/19/2019 step-into-windows-10-uwp.pdf

    48/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            4 

    Part 16: Consume web service using HttpClient to POST and GET json data in

    Windows 10 UWP

    In this part we will see how to consume a REST service in Windows 10. Before that we will

    introduce REST services.

    REST is a resource that implements a uniform interface using standard HTTP GET, POST, PUT

    methods that can be located by URI.

    Windows 10 UWP supports basic get and post web requests using the following two APIs:

      System.Net.Http.HttpClient

     

    Windows.Web.Http.HttpClient.

    The System.Net.Http.HttpClient  was introduced in .NET 4.5. In Windows 10 this API has changed

    to top layer of Windows.Web.Http.HttpClient . The supported OS and programming languages

    are as follows:

    API  OS Versions  Supported

    Languages 

    System.Net.Http.HttpClient Windows Phone 8

    onwards

    .NET

    languages 

    Windows.Web.Http.HttpClient Windows, WindowsPhone 8.1 onwardsAll 

    Both of this APIs are available in UWP. Select which one you need.

    If you are going to develop native UI or pass specific SSL certificates for Authentication then use

    Windows.Web.Http.HttpClient  API.

    If you are going to develop app with cross platform, such as iOS, Android, then use

    System.Net.Http.HttpClient. This API supports Xamarin IOS and Android development.

    Now see how to consume REST service in Windows 10 app using System.Net.Http.HttpClient. 

    Create new windows 10 project 

    For POST JSON data write the following code.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    49/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            4 

    URI is the url you are going to POST JSON data.

    Here, I will create runtime JSON data using dynamic and ExpandoObject , using this you can

    create JSON string at runtime instead of creating classes.

    Json.Net is used to serialize the runtime dynamic object values to JSON data.

    Create new instance for HttpClient  and HttpResponseMessage.

    public async void POSTreq()

    {

    Uri requestUri = new Uri("https://www.userauth");//replaceyour Url dynamic dynamicJson = new ExpandoObject();

    dynamicJson.username ="[email protected]".ToString();

    dynamicJson.password = "9442921025";string json = "";

     json = Newtonsoft.Json.JsonConvert.SerializeObject(dynamicJson);

    var objClint = new System.Net.Http.HttpClient(); 

    System.Net.Http.HttpResponseMessage respon = await objClint.PostAsync(requestUri,new StringContent(json,System.Text.Encoding.UTF8,"application/json"));

    string responJsonText = await respon.Content.ReadAsStringAsync();

    }

    For GET json response write the following code:

    public async void GetRequest()

    {

    Uri geturi = new Uri("http://api.openweathermap.org/data/2.5/weather?q=London"); //replace your url 

    System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

    System.Net.Http.HttpResponseMessage responseGet = await 

    client.GetAsync(geturi); string response = await

    responseGet.Content.ReadAsStringAsync();  

    }

    Now run the app and see the excepted output:

  • 8/19/2019 step-into-windows-10-uwp.pdf

    50/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            4 

    Part 17: HTTP Live Streaming in Windows 10 

    Microsoft finally released live streaming API support in Windows 10 UWP. Before that we need

    third party API Windows Phone Streaming Media Assistance. But it will arrive in UWP.

    Windows.Media.Streaming.Adaptive namespace: It helps to play over live http media

    streaming.

    This namespace definition support many kinds of different adaptive streaming protocols, such as

    Http Live Streaming or HLS is a protocol for streaming media content that is segmented into

    several small files, each of them in different sizes and qualities to enable the content

    disseminating an adaptive rate depending on the quality of the connection.

    This returns AdaptiveMediaSourceCreationResult  which includes the source and whether the

    manifest was able to be downloaded or what error occurred. Remember that you enabled theInternetClient  capability in your appxmanifest file.

    Now see the steps how it works.

    Create new Windows 10 project and go to MainPage.xaml page design view to design.

    Add Media control to play the streamed videos and use the following code to design media

    control:

     

    Next add two app bar controls to Play and Pause the streaming.

     

     

     

     

     

  • 8/19/2019 step-into-windows-10-uwp.pdf

    51/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

           5 

       

     

     

    Next go to code behind page and write the following code to stream the video:

    var streamUri = new Uri(""); //replace your URL

    var streamResponse = await AdaptiveMediaSource.CreateFromUriAsync(streamUri);  if

    (streamResponse.Status == AdaptiveMediaSourceCreationStatus .Success) 

    liveMedia.SetMediaStreamSource(streamResponse.MediaSource);  

    else 

    {

    //not found 

    }

    Before set the media source check the status property to verify that everything went correct

    otherwise skip it.

    By default it will start play the stream if you want to pause writes the following code:

    private void pausBtn_Click(object sender, RoutedEventArgs e)

    {

    liveMedia.Pause();

    }

    If you want to play again write the following code:

    private void playBtn_Click(object sender, RoutedEventArgs e)

    {

    liveMedia.Play();

    }

    You can play around the media control like the following function pause, play, mute, unmute

    and volume increase, etc.

    Now run the app and check the output look like the below video. Here I am going to stream thelive news channel.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    52/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

           5 

    Part 18: Background File Downloader for Windows 10 UWP

    In this part we are going to see how background files downloading work in Windows 10 UWP

    app.

    A background transfer is used for long-term transfer or downloads operations such as video,

    music, and images. For that time user will allow play around your app don’t stop the user to

    wait.

    BackgroundDownloader class will help you to transfer or download the files from the server

    event the app is running in foreground. If the user exits the app, the download will continue in

    the background. You can check when the app is relaunched.

    Let’s see the steps how to download files from server. 

    Create new Windows 10 project and give a suitable name.

    Design your xaml page. Here I will create one textbox to enter your download url then textblock

    for showing the status and one button to start the download XAML Code

     

     

     

     

     

     

     

     

     

     

     

     

  • 8/19/2019 step-into-windows-10-uwp.pdf

    53/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

           5 

    Next we need to ensure that your app has the capability to access the internet. To enable the

    capability follow the below steps.

    Double click your package.aapmainfest file in you solution explorer and enable the internet

    client like the following screenshot:

    Next go to code behind page and write the following code:

    DownloadOperation downloadOperation;  

    CancellationTokenSourcecancellationToken; 

    Windows.Networking.BackgroundTransfer.BackgroundDownloader backgroundDownloader =new Windows.Networking.BackgroundTransfer.BackgroundDownloader();

    public MainPage()

    {

    this.InitializeComponent();

    }

    public async void Download()

    FolderPicker folderPicker = new FolderPicker(); 

    folderPicker.SuggestedStartLocation = PickerLocationId.Downloads;

    folderPicker.ViewMode = PickerViewMode.Thumbnail;

    folderPicker.FileTypeFilter.Add("*");

    StorageFolder folder = await folderPicker.PickSingleFolderAsync();

  • 8/19/2019 step-into-windows-10-uwp.pdf

    54/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

           5 

     if (folder != null)

    {

    StorageFile file = await folder.CreateFileAsync("NewFile.jpg", 

    CreationCollisionOption.GenerateUniqueName);Uri durl = new Uri(linkBox.Text.ToString());

    downloadOperation = backgroundDownloader.CreateDownload(durl, file);

    Progress progress = new 

    Progress(progressChanged);

    cancellationToken = new CancellationTokenSource();

    try 

    {

    Statustext.Text = "Initializing...";

    await downloadOperation.StartAsync().AsTask(cancellationToken.Token, progress); 

    }

    catch (TaskCanceledException)

    {

    downloadOperation.ResultFile.DeleteAsync(); downloadOperation = null;

    }

    }

    private void progressChanged(DownloadOperation downloadOperation)

    {

    int progress = (int)(100 * ((double)downloadOperation.Progress.BytesReceived / (double)downloadOperation.Progress.TotalBytesToReceive));

    Statustext.Text = String.Format("{0} of {1} kb. downloaded - %{2} complete.",

    downloadOperation.Progress.BytesReceived / 1024,downloadOperation.Progress.TotalBytesToReceive / 1024, progress);

    switch (downloadOperation.Progress.Status)

    {

    case BackgroundTransferStatus.Running:

    {

    break;

    }

    case BackgroundTransferStatus.PausedByApplication:

    {

    break;

  • 8/19/2019 step-into-windows-10-uwp.pdf

    55/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

           5 

    }

    case BackgroundTransferStatus.PausedCostedNetwork:

    {

    break;

    }case BackgroundTransferStatus.PausedNoNetwork:

    {

    break;

    }

    case BackgroundTransferStatus.Error:

    {

    Statustext.Text = "An error occuredwhile downloading."; break;

    }

    }

    if (progress >= 100)

    {

    downloadOperation = null;

    }

    }

    private void downloadBtn_Click(object sender, RoutedEventArgs e)

    {

    Download();

    }

    }

    Created a new DownloadOperation and CancellationTokenSource object using the

    BackgroundDownloader  class when passed the required StorageFile location and download URI

    values and call the CreateDownload  method to download the file.

    In the above code user first select the location to store the file and start the download and

    register a method to receive progress updates.

    Progress class helps you to track the downloading progress and you can get how much bytes

    received.

    Now run the app and see the output like the following screen. Here I am going to download the

    Google logo.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    56/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

           5 

     

  • 8/19/2019 step-into-windows-10-uwp.pdf

    57/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

           5 

    Part 19: RSS Reader in Windows 10 UWP App 

    In this part we are going to see the how to perform RSS Reader in Windows 10 application.

    Create new Windows 10 project and give suitable name.

    In windows 10 default SyndicationClient helps you to feed RSS service.

    Design view will be designed as like the following XAML code:

     

     

     

     

     

       

     

     

     

     

     

     

     

     

     

     

      

     

     

     

     

     

  • 8/19/2019 step-into-windows-10-uwp.pdf

    58/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

           5 

       

     

    Now go to code behind and create new instance of SyndicationClient  and SyndicationFeed .

    SyndicationClient client = new SyndicationClient();

    SyndicationFeed feed = await client.RetrieveFeedAsync(uri);

    Using RetrievedFeedAsync pass the url which you want to feed.

    Using foreach you can manipulate the feed items:

    oreach (SyndicationItem item in feed.Items)

    {

    list.Items.Add(item);}

    Here I create one helper class to perform RSS feed.

    The full source code should be like this

    private async void load(ItemsControl list, Uri uri)

    {

    SyndicationClient client = new SyndicationClient(); SyndicationFeed feed = await 

    client.RetrieveFeedAsync(uri); if (feed != null)

    {foreach (SyndicationItem item in feed.Items)

    {

    list.Items.Add(item);

    }

    }

    }

    public void Go(ref ItemsControl list, string value)

    {

    try 

    {

    load(list, new Uri(value));

    }

    catch 

  • 8/19/2019 step-into-windows-10-uwp.pdf

    59/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

           5 

    {

    }

    list.Focus(FocusState.Keyboard);

    }

    private void feedClick_Click(object sender, RoutedEventArgs e) 

    {

    helperRSS.Go(ref  Display, Value.Text);

    }

    Now run the application and enter your RSS feed Url in the given textbox. Here I am going to

    feed my C# Corner articles.

    Output

  • 8/19/2019 step-into-windows-10-uwp.pdf

    60/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

           5 

    Part 20: Sensors in Windows 10 UWP App 

    Windows 10 SDK comes with lots of new sensors which helps the users to keep health fit to

    know what the user needs. The new list of sensors can be seen below:

      Altimeter

      Activity Sensor

      Barometer

      Pedometer

      Proximity Sensor

    Let’s see the sensor in detail. 

    To access the sensors API add the following namespace first,

    using Windows.Devices.Sensors;

    Altimeter 

    Altimeter helps to measure the relative altitude i.e. changes in elevation. The Altimeter has an

    event called ReadingChanged  and triggered whenever a new value is sensed by the Altimeter

    sensor. ReportInterval  property is used to set the time interval at which the sensor has to

    report.Sample code

    public void GetAltimeter()

    {

    Altimeter getAltiude = Altimeter.GetDefault(); 

    AltimeterReading reading =

    getAltiude.GetCurrentReading(); 

    getAltiude.ReportInterval = 100;

    getAltiude.ReadingChanged += GetAltiude_ReadingChanged;

    }

    private void GetAltiude_ReadingChanged(Altimeter sender, AltimeterReadingChangedEventArgs args)

    {

    AltimeterReading readingvalues = args.Reading;

    }

  • 8/19/2019 step-into-windows-10-uwp.pdf

    61/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            6 

    Activity Sensor 

    ActivitySensor will help to detect the user’s activity based on the user motion context. These

    sensors help to detect the motion of user either walking, running and idle etc. This sensor set to

    idle state when the device is without any movement and also you can get the details up to 30

    days.

    Sample code to get the activity reading:

    public async void GetActivity()

    {

    ActivitySensor activity =await ActivitySensor.GetDefaultAsync();  

    var reading = await activity.GetCurrentReadingAsync();  

    activity.ReadingChanged += new 

    TypedEventHandler(ReadingCh anged);

    private void ReadingChanged(ActivitySensor sender, ActivitySensorReadingChangedEventArgsargs)

    {

    ActivitySensorReading readingActivity = args.Reading;

    }

    To get the last 30 days details:

    DateTimeOffset last30days = DateTime.Today.AddDays(-30);

    var details = await ActivitySensor.GetSystemHistoryAsync(last30days); foreach (var values in details)

    {

    string newvalue = values.Activity.ToString();

    }

    var trigger = new

    Windows.ApplicationModel.Background.ActivitySensorTrigger(100);

    trigger.SubscribedActivities.Add(ActivityType.InVehicle);

    Barometer 

    The Barometer is help’s to measure the atmospheric pressure. The Barometer API has an Event

    handler ReadingChanged which gets a new value is sensed by the sensor. The ReportInterval

  • 8/19/2019 step-into-windows-10-uwp.pdf

    62/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            6 

    property is used to set the interval at which the sensor has to report. GetCurrentReading

    method is used to gets the current reading for the barometer.

    Sample Code 

    public async void getBarometer()

    {

    Barometer barometerValues = Barometer.GetDefault(); 

    BarometerReading reading =

    barometerValues.GetCurrentReading(); var getPressure =

    reading.StationPressureInHectopascals; 

    barometerValues.ReportInterval = 150;

    barometerValues.ReadingChanged +=

    Barometer_ReadingChanged;

    }

    private void Barometer_ReadingChanged(Barometer sender, BarometerReadingChangedEventArgsargs)

    {

    string values = args.Reading.ToString();

    }

    Pedometer 

    Pedometer help’s you to count the user’s steps in walking and running and you can access

    history details for up to 30 days.

    Pedometer sensor comes with Windows Phone 10 and also in Microsoft Band.

    Sample Code 

    public async void pedometer()

    {

    Pedometer readings = await Pedometer.GetDefaultAsync();  readings.ReportInterval = 100; 

    readings.ReadingChanged += Readings_ReadingChanged;

    }

    private void Readings_ReadingChanged(Pedometer sender, PedometerReadingChangedEventArgs args)

    {

    PedometerReading readvalues = args.Reading;

    if (readvalues.StepKind == PedometerStepKind.Walking)

  • 8/19/2019 step-into-windows-10-uwp.pdf

    63/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            6 

    {

    var walkingsteps = readvalues.CumulativeSteps;

    }

    else if (readvalues.StepKind == PedometerStepKind.Running)

    {var runningSteps = readvalues.CumulativeSteps;

    }

    public async void gettingHistory()

    {

    var history = await Pedometer.GetSystemHistoryAsync(DateTime.Now.AddDays(-30));

    }

    To get the last 30 days or any days you can get it from GetSystemHistoryAsync  method by

    passing the date this sensor mainly used to detect weather the user has intentionally touched

    the display or not.

    Proximity Sensor 

    Proximity sensor help to detect the presence of the object it supports short and long range.

    You can notify this we use turn off the display during phone call.

    Sample Code

    ProximitySensor sensor;public void GetProximityStatus()

    {

    DeviceWatcher watch;

    watch = DeviceInformation.CreateWatcher(ProximitySensor.GetDeviceSelector());watch.Added += Watch_Added; 

    watch.Start();

    ProximitySensorReadingreading = sensor.GetCurrentReading(); sensor.ReadingChanged += Sensor_ReadingChanged; 

    }

    private void Sensor_ReadingChanged(ProximitySensor sender, ProximitySensorReadingChangedEventArgsargs)

    {

    ProximitySensorReading readStatus = args.Reading;

    }

  • 8/19/2019 step-into-windows-10-uwp.pdf

    64/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            6 

     

    private void Watch_Added(DeviceWatcher sender, DeviceInformation args)

    {

    ProximitySensor identified = 

    ProximitySensor.FromId(args.Id); sensor = identified;}

    Part 21: Set Specific DeviceFamily XAML Views In Windows 10 UWP 

    In this part we are going to see how to set different XAML page for specific device family.

    The new Universal Windows Platform introduced a new feature DeviceFamily specific views(UI)

    which allows developers to define specific XAML page for specific device families (Desktop,

    Mobile.etc).

    If we want to have different view for different device families. There are three ways to set

    specific device family XAML view.

    Let's see the steps 

    Firstly, Using DeviceFamily-Type folder,

    Create new Windows 10 blank project and give a suitable name.

    This method is the most common way to perform this task. Create a new folder in your project,

    called “DeviceFamily-Type”. The type is the name of the device family type 

    (Mobile, Team, Desktop, IoT).

    So in our sample I have created mobile specific view and it looks like the following screen:

    In our sample we will create a new folder called DeviceFamily-Mobile for specific view on mobile

    device.

    Let us take the MainPage.XAML in the project, with blue background we want this specific XAML

    view for a mobile device family.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    65/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            6 

    The next step would be adding a XAML view called the same as the page so in this case,

    MainPage.xamlwill be added into the folder DeviceFamily-Mobile and looks like the following:

    This MainPage.XAML won't have any code-behind, it will use the code-behind of the main

    MainPage.xaml.cs file.

    Now run the app on a mobile device it will load the XAML from DeviceFamily-

    Mobile/MainPage.xaml. For any other device family type, it will load the MainPage.xaml fromthe main folder.

    Change the grid background colour to green like below code

     

     

    Second one is DeviceFamily-Type in file name,

    The second method to perform the same thing is to create a new XAML View with, again, the

    same name, but with DeviceFamily-Type extension in our MainPage, it would mean adding a

    new XAML view file called MainPage.DeviceFamily-Mobile.xaml to the main folder and looks like

    below screen.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    66/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            6 

     

    Depending on the device family, one of the two XAML files will get loaded.

    Now run the app in desktop and mobile and see the output looks like the following screen:

    Mobile view

    Desktop view

    Part 22: Drawing and Inking Using New InkCanvas Control for Windows 10 UWP

    App 

  • 8/19/2019 step-into-windows-10-uwp.pdf

    67/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            6 

    In this part we will see how to capture user input and save it as image.

    Windows 10 introduced built-in InkCanvas control to capture the user input. I am going to show

    the use of InkCanvas control to capture the user touch input and save it as image.

    In Windows 8.1 apps you had to create a Canvas, listen to input events, and render your own

    strokes, but in Windows 10 use the built-in InkCanvas control to immediately capture use input.

    This control allows user to quickly enable inking for user and easily expand its functionality by

    accessing the InkCanvas’s InkPresenter property. InkPresenter can be used to configure a

    collection of user input through touch or mouse input.

    Let’s see the steps to perform this operation. 

    Create a new windows 10 UWP app. Once successful created, go to MainPage.XAML page and

    write the following code to design your page.

    The control looks like the following image:

    Next got to code behind page and write the following code.

    Firstly, create new instance for InkPresenter.

    InkPresenter myPresenter = myCanvas.InkPresenter;

  • 8/19/2019 step-into-windows-10-uwp.pdf

    68/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            6 

     

    Next define the input device type for Canvas control to let the control accepts inputs from those

    devices.

    Pen, Mouse and Touch.

    myPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Pen

    |Windows.UI.Core.CoreInputDeviceTypes.Mouse|Windows.UI.Core.CoreInputDeviceTypes. Touch; 

    Set the pen colour, pencil tip shape and size.

    myAttributes.Color = Windows.UI.Colors.Crimson;myAttributes.PenTip = PenTipShape.Circle;

    myAttributes.Size = new Size(2, 5);

    The whole code on canvas pointer pressed event looks like the following:

    private void myCanvas_PointerPressed(object sender, PointerRoutedEventArgs e)

    {

    InkPresenter inkPresenter = myCanvas.InkPresenter; inkPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Pen 

    |Windows.UI.Core.CoreInputDeviceTypes.Mouse|Windows.UI.Core.CoreInputDeviceTypes.Touch; 

    InkDrawingAttributes myAttributes = inkPresenter.CopyDefaultDrawingAttributes(); myAttributes.Color = Windows.UI.Colors.Crimson; 

    myAttributes.PenTip = PenTipShape.Circle;myAttributes.PenTipTransform =

    System.Numerics.Matrix3x2.CreateRotation((float)Math.PI /

    4); myAttributes.Size = new Size(2, 5);

    inkPresenter.UpdateDefaultDrawingAttributes(myAttributes

    );

    }

    Next save this ink into image,

    private async void savebtn_Click(object sender, RoutedEventArgs e)

    {

    var savePicker = new FileSavePicker(); 

  • 8/19/2019 step-into-windows-10-uwp.pdf

    69/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            6 

    savePicker.SuggestedStartLocation =

    Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;

    savePicker.FileTypeChoices.Add( "PNG", new 

    System.Collections.Generic. List { ".png" });

    StorageFile file = await savePicker.PickSaveFileAsync();  if (null != file)

    {

    try 

    {

    using (IRandomAccessStream stream = await

    file.OpenAsync(FileAccessMode.ReadWrite))

    {

    await myCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);

    }

    }

    catch (Exception ex)

    {

    }

    }

    }

    Now change the InkPresenter processing mode to erase to delete the ink:

    myCanvas.InkPresenter.InputProcessingConfiguration.Mode =InkInputProcessingMode.Erasing;

    Erase button click event looks like below:

    private void erasebtn_Click(object sender, RoutedEventArgs e)

    {

    myCanvas.InkPresenter.InputProcessingConfiguration.Mode =InkInputProcessingMode.Erasing;

    }

  • 8/19/2019 step-into-windows-10-uwp.pdf

    70/71

     

    ©2016 C# CORNER.

    SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 

            6 

     

    Now run the app and see the output looks like the following screen.

  • 8/19/2019 step-into-windows-10-uwp.pdf

    71/71

     

           7 

    Part 23: Disable screen capture in Windows 10 UWP 

    In this part we are going to see how to disable screen capture in Windows 10 app.

    If you are develop any security apps, sometimes we will need to disable to take screenshots ofyour app. This feature was available in Windows 10 app.

    You need to call the View Management class get the current view screen.

    Finally set the screen capture Boolean value to false like the following code.

    Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().IsScreenCaptureEna bled =

    false; 

    For more sample and articles follow:

     

    https://windowsapptutorials.wordpress.com/   http://www.c-sharpcorner.com/members/suresh-m27 

    https://windowsapptutorials.wordpress.com/https://windowsapptutorials.wordpress.com/https://windowsapptutorials.wordpress.com/