step-into-windows-10-uwp.pdf



Comments



Description

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 1 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 Coordinates 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 ©2016 C# CORNER. SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 2 Part 1: Quick Introduction Microsoft announced Windows 10 would be final windows version. It would evolve and change like 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 developers build an app available on all the devices that runs on Windows 10 OS. ©2016 C# CORNER. SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 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 ©2016 C# CORNER. REPUBLISH. . SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE. CHANGE OR COPY.3 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. the system waits for few seconds to make sure that the user switches back to the application immediately.    Running Suspended Not Running (Terminated) Running If the app running you get events. ©2016 C# CORNER. the system want to keep a number of suspended apps into the memory to make sure the user can quickly switch back to the application. After a few seconds time interval. Suspended When the application move to the background or the device enters to the low power 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. SHARE THIS DOCUMENT AS IT IS. the system automatically moves the application to the suspended state. If your available memory is low. CHANGE OR COPY. REPUBLISH.In this part we are going to see the life cycle of Windows UWP 10 app. The app always resides in memory as long as your system has available memory to execute. the application suspends automatically. which you can access it in App. Based on the system available memory. Same process goes on until the system encounters low memory. In Windows 10 the life cycle of App have three states. If you start the application it activates and comes to running state. While pushing the application to the background. the system automatically removes the unused application from memory.PLEASE DO NOT REPRODUCE. These state considered as the app going to terminate (closed) state.cs file. 4 Part 3: Life cycle of Windows 10 . SHARE THIS DOCUMENT AS IT IS. CHANGE OR COPY. REPUBLISH.©2016 C# CORNER. it loads the application data if you already saved during the suspension state. During the state transition. 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. 5 We can resume a suspended application from background and bring it to the foreground thread.PLEASE DO NOT REPRODUCE. . you will see that the solution is set to Debug and the platform is set to x86. Open the MainPage. 6 Part 4: Writing Your First Windows 10 UWP App .272. <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <TextBlock Margin="79. Name it “HelloWorldWin10” or as your wish like shown below. Set the Text property of the TextBlock to Hello World Windows 10 as in the following code. you will have to set this as “Mobile Emulator”.Xaml file in Visual Studio and add TextBlock in the existing grid. The Start Debugging button will also be set to “Local Machine” by default. Now you can see your app like below. Let’s start creating a new Windows 10 Blank App template with C# as language and then deploy to run the app on Local Machine and Windows Mobile Emulator. by default. CHANGE OR COPY.335">Welcome to Windows 10</TextBlock> </Grid> Now time to run the app. ©2016 C# CORNER.PLEASE DO NOT REPRODUCE. REPUBLISH. SHARE THIS DOCUMENT AS IT IS. Click Ok to create new app.109. If you want to run this on the Windows Mobile device. 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.In this part we are going to see how to create a new UWP project. x86 will work for both mobile emulator and 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 Tab ©2016 C# CORNER.PLEASE DO NOT REPRODUCE. Windows 10 Mobile. SHARE THIS DOCUMENT AS IT IS. CHANGE OR COPY. REPUBLISH. 7 Click the Start Debugging button with the “Local Machine” option to deploy to run the app on the local machine. . ©2016 C# CORNER. CHANGE OR COPY.8 Windows 10 Desktop Note: For Source Code. SHARE THIS DOCUMENT AS IT IS. REPUBLISH.PLEASE DO NOT REPRODUCE. . 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. Now go to Mainpage. We now have a Universal Windows Platform (UWP). 9 Part 5: Show Message Dialog in Windows 10 . ©2016 C# CORNER. <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center"> <Button x:Name="Showbutton" Click="Showbutton_Click" Content="Show Message Dialog"/> </StackPanel> Now our design page looks like the following screen: Now go to code behind page and write the following code on button click event. SHARE THIS DOCUMENT AS IT IS. The MessageDialog class is available in Windows 10. REPUBLISH. CHANGE OR COPY.Xaml and paste the following XAML code to create a button for showing message dialog.PLEASE DO NOT REPRODUCE. Create new Windows 10 UWP app and name it as you wish. PLEASE DO NOT REPRODUCE. showDialog. RoutedEventArgs e) { MessageDialog showDialog = new MessageDialog("Hi Welcome to Windows 10"). Now run your app with Local Machine.Create an instance of the MessageDialog with the Message and Title if required. Local Machine ©2016 C# CORNER.ShowAsync(). if ((int) result. Mobile and Simulator to see the output as in the following image.Commands. SHARE THIS DOCUMENT AS IT IS.CancelCommandIndex = 1.DefaultCommandIndex = 0. 10 private async void Showbutton_Click(object sender.Add(new UICommand("Yes") { Id = 0 }). REPUBLISH. Use ShowAsync() method to show the dialog and check the result containing command id and perform the yes or no task.Commands.Id == 0) { //do your task } else { //skip your task } } . UICommands are added to the commands collection of the dialog. showDialog. showDialog. CHANGE OR COPY. showDialog. var result = await showDialog.Add(new UICommand("No") { Id = 1 }). 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. PLEASE DO NOT REPRODUCE. REPUBLISH.11 Mobile ©2016 C# CORNER. . CHANGE OR COPY. SHARE THIS DOCUMENT AS IT IS. 12 Simulator Simulator and Mobile Part 6: Windows 10 Application Bar The App bar is designed to expose application commands to the user.PLEASE DO NOT REPRODUCE. There are two types of app bar you can use. ©2016 C# CORNER. CHANGE OR COPY. . REPUBLISH. SHARE THIS DOCUMENT AS IT IS. com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.PLEASE DO NOT REPRODUCE.openxmlformats.microsoft.TopAppBar> Application Bar for Bottom.BottomAppBar> <AppBar IsOpen="True" IsSticky="True"> <StackPanel Orientation="Horizontal"> <AppBarButton Name="Button1" Icon="Add" Label="Add"></AppBarButton> <AppBarButton Name="Button2" Icon="Remove" Label="Remove"></AppBarButton> </StackPanel> </AppBar> </Page.TopAppBar> <AppBar> <StackPanel Orientation="Horizontal"> <AppBarButton Name="Button3" Icon="Add" Label="Add"></AppBarButton> <AppBarButton Name="Button4" Icon="Remove" Label="Remove"></AppBarButton> </StackPanel> </AppBar> </Page. <Page.MainPage" xmlns="http://schemas. CHANGE OR COPY.BottomAppBar Full source code looks like the following: <Page x:Class="AppBarDemo.com/expression/blend/2008" xmlns:mc="http://schemas. . REPUBLISH.com/winfx/2006/xaml" xmlns:local="using:AppBarDemo" xmlns:d="http://schemas. SHARE THIS DOCUMENT AS IT IS.microsoft.org/markup-compatibility/2006" mc:Ignorable="d"> <Page.TopAppBar> <AppBar> <StackPanel Orientation="Horizontal"> <AppBarButton Name="Button3" Icon="Add" Label="Add"> ©2016 C# CORNER. <Page.microsoft.TopAppBar BottomAppBar 13   You can put any control that you like into the app bar. myAppBar. this.BottomAppBar = myAppBar. To minimize the app bar set IsOpen property to false.TopAppBar> <Page.BottomAppBar> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> </Grid> </Page> The app bar should be outside the grid control. CHANGE OR COPY.Add(new Button { Content = "Button1"}). REPUBLISH.Content = content.Children. SHARE THIS DOCUMENT AS IT IS. ©2016 C# CORNER.Add(new Button { Content = "Button2" }). content. 14 </AppBarButton> . var content = new StackPanel { Orientation = Orientation. content.Children.PLEASE DO NOT REPRODUCE. You can minimize and maximize the app bar by default using the IsOpen="True" IsSticky="True". You can create the App Bar using C# code also using the following code: AppBar myAppBar = new AppBar(). by default it will be false. If you are developing app for Windows 10 mobile place the app bar in bottom to find out easily. Application Bar is placed in the following screen at only bottom or top and both.BottomAppBar> <AppBar IsOpen="True" IsSticky="True"> <StackPanel Orientation="Horizontal"> <AppBarButton Name="Button1" Icon="Add" Label="Add"> </AppBarButton> <AppBarButton Name="Button2" Icon="Remove" Label="Remove"> </AppBarButton> </StackPanel> </AppBar> </Page.Horizontal }. myAppBar.IsOpen = true.<AppBarButton Name="Button4" Icon="Remove" Label="Remove"> </AppBarButton> </StackPanel> </AppBar> </Page. .PLEASE DO NOT REPRODUCE. CHANGE OR COPY. SHARE THIS DOCUMENT AS IT IS. REPUBLISH.15 Now run the app and see the output like the following: ©2016 C# CORNER. SHARE THIS DOCUMENT AS IT IS. sometimes we need to change for better UI.TitleBar. appView.TitleBar. Using UI ViewManagement class we can get the application UI properties.ButtonForegroundColor = Colors.LightBlue. So. REPUBLISH.ApplicationView.TitleBar.PLEASE DO NOT REPRODUCE.GetForCurrentView(). In Windows 10 by default the white title bars is available for all apps.ButtonBackgroundColor = Colors. Place this code in app launching event in App.xaml.White.LightBlue.cs file as in the following code. appView.TitleBar.ViewManagement.UI.In this part we are going to see how to change the default application title bar colour in Windows 10 UWP. 16 Part 7: Change Apps Title Bar Colour and Enable Back Button In Windows 10 UWP . CHANGE OR COPY.White. appView. Full code looks like the following code: Now run the app and see the title bar it looks like the following image: ©2016 C# CORNER.ForegroundColor = Colors. appView. I am going to get the title bar properties and change the colour using the following code: var appView = Windows.BackgroundColor = Colors. REPUBLISH. Write the following code to enable the back button.AppViewBackButtonVisibility = AppViewBackButtonVisibility.GetForCurrentView(). view.AppViewBackButtonVisibility = AppViewBackButtonVisibility. Firstly. view. BackRequestedEventArgs e) ©2016 C# CORNER. view. .BackRequested += View_BackRequested.GetForCurrentView(). private void View_BackRequested(object sender. BackRequestedEventArgs e) { //do your task } The full source code looks like the following: var view = SystemNavigationManager. CHANGE OR COPY. view. get the current view and enable the back button. var view = SystemNavigationManager.Visible.Visible.BackRequested += View_BackRequested. SHARE THIS DOCUMENT AS IT IS. Add the following method to handle the back button click. If you need back button in the application title bar you need to enable it. Now create event handler for handling the back button click.17 Enable back button in the app title bar Windows 10 UWP In Windows 10 UWP the back button is disabled by default.PLEASE DO NOT REPRODUCE. private void View_BackRequested(object sender. I will show how to enable this button. SHARE THIS DOCUMENT AS IT IS. CHANGE OR COPY. REPUBLISH.18 { //do your task } Now run the app and see the output looks like the following image: ©2016 C# CORNER. .PLEASE DO NOT REPRODUCE. CHANGE OR COPY.Content> </SplitView> Using “IsPaneOpen” property you can set true or false. 19 Part 8: Windows 10 Split View-Hamburger Menu . SHARE THIS DOCUMENT AS IT IS.In this part we are going to see how to create SplitView/Hamburger menu in Windows UWP 10 app.Pane> //Add your menu here </SplitView.Pane> <SplitView. Now create a new Windows 10 project and give proper name. Content The page content goes in this area. Many of them call it hamburger menu.PLEASE DO NOT REPRODUCE.xaml and you can see the empty grid control as in the following screenshot: ©2016 C# CORNER. <SplitView> <SplitView. REPUBLISH. Pane These properties contain the menu buttons in your app. true for open and false to close. Two things we need to know “Pane” and “Content”.Content> //Add your content here </SplitView. The new control SplitView added in Windows 10 and is used to display side menu. After that open Your Mainpage. I set the content as “&#E700."> </Button> <Button x:Name="button3" Content="Next Page" Click="button3_Click"> </Button> </StackPanel> </SplitView." Click="HamburgerButton_Click" /> <Button x:Name="button1" FontFamily="Segoe MDL2 Assets" Content="&#xE70F.Pane> <SplitView. .Content> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <TextBlock Text="Hamburger Menu Demo" TextAlignment="Center" VerticalAlignment="Center"> </TextBlock> </Grid> </SplitView. SHARE THIS DOCUMENT AS IT IS. CHANGE OR COPY.” and it looks like the following image."> </Button> <Button x:Name="button2" FontFamily="Segoe MDL2 Assets" Content="&#xE723.Pane> <StackPanel Background="Gray"> <Button x:Name="HamburgerButton" FontFamily="Segoe MDL2 Assets" Content="&#xE700. ©2016 C# CORNER.PLEASE DO NOT REPRODUCE. 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.20 Delete this grid and paste the following code: <SplitView x:Name="MyMenu" DisplayMode="CompactOverlay" IsPaneOpen="False" CompactPaneLength="50" OpenPaneLength="150"> <SplitView.Content> </SplitView> In the above code we are creating the button in menu and styling to hamburger menu. REPUBLISH. Here. go to code behind page and I have one button click event to close and open the split view. RoutedEventArgs e) { MyMenu. Finally. RoutedEventArgs e) { Frame. . SHARE THIS DOCUMENT AS IT IS. I create 4 buttons for sample. } private void button3_Click(object sender. REPUBLISH.IsPaneOpen.Navigate(typeof(Page1)) } Now run the app and see the excepted output like the following screen: ©2016 C# CORNER.21 Now you can create button as your need. 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.IsPaneOpen = !MyMenu.PLEASE DO NOT REPRODUCE. CHANGE OR COPY. PLEASE DO NOT REPRODUCE. REPUBLISH. CHANGE OR COPY. . SHARE THIS DOCUMENT AS IT IS.22 ©2016 C# CORNER. EmailAttachment( attachment. string messageBody) { var to = Torecipient.Email.ApplicationModel .ContactEmail > (). string message) { var chatMessage = new Windows. To send E-mail Firstly. emailMessage. objEmail.FirstOrDefault < Windows. await EmailManager. var stream = Windows. To send SMS To send an SMS write the following code: private async void ComposeSMS(Contact toContatc. Create new Windows 10 project. stream).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.RandomAccessStreamReference.ShowComposeNewEmailAsync(objEmail). chatMessage.EmailRecipient(to.Address). } You can attach files also while sending email to attach the files write the following code before composing the email task.Attachments. SHARE THIS DOCUMENT AS IT IS.To. objEmail.Add(emailRecipient).Chat.ApplicationModel. 23 Part 9: Send E-mail and SMS in windows 10 .ChatMessage().Subject = "Suresh".Emails. var emailRecipient = new Windows.Body = message.ApplicationModel. var attachment = new Windows. we are going to see how to send email.PLEASE DO NOT REPRODUCE. Now create two buttons: one id for sending email and another for sending SMS. ©2016 C# CORNER.Streams.Add(attachment). CHANGE OR COPY.Name.Storage. REPUBLISH. EmailMessage objEmail = new EmailMessage(). Write the following code: private async void ComposeEmail(Contact Torecipient.ApplicationModel .Contacts.Email.CreateFromFile(attachment). Phones. chatMessage.ApplicationModel.ApplicationModel.} ©2016 C# CORNER. SHARE THIS DOCUMENT AS IT IS.Contacts. .ShowComposeSmsMessageAsync(c hatMessage).ChatMessageManager . CHANGE OR COPY.ContactPhone > ().PLEASE DO NOT REPRODUCE. await Windows.Recipients.FirstOrDefault < Windows.Chat. 24 var phone = toContatc.Add(phone. REPUBLISH.Number). Devices. 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.Maps. CHANGE OR COPY. ©2016 C# CORNER. using Windows. REPUBLISH. 25 Part 10: Map control to show your current location and get the street address using GPS Co-ordinates in Windows 10 UWP .Geolocation. Firstly. SHARE THIS DOCUMENT AS IT IS.Services. Create new Windows 10 project and choose the map control from toolbox list. Here we will see how to get the longitude and latitude co-ordinates of the device.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.PLEASE DO NOT REPRODUCE. Geo Location API allows easy to access the current location of device. Next we are going to get the current street address of the position using the coordinates. Set the map zoom level according to your needs and you will get the co-ordinates of the current position. mymap. var geolocator = new Geolocator().ZoomLevel = 15.Point. REPUBLISH. 26 Create new instance for Geolocator using that we can retrieve the position of our device.Center = position.GetGeopositionAsync(). 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. mymap. CHANGE OR COPY. ©2016 C# CORNER. SHARE THIS DOCUMENT AS IT IS. .Coordinate. var position = await geolocator.PLEASE DO NOT REPRODUCE. Then add the location coordinate points to our map control.Write the following code to set your position to the map control. Point).Coordinate.FindLocationsAtAsync(position.Locations[0].Street.Content = "Not Found".StreetNumber + " " + mapLocation. } Now run the app and see the output like the following screen: ©2016 C# CORNER.string address = mapLocation. CHANGE OR COPY.Address. } else { dialog. 27 var mapLocation = await MapLocationFinder. REPUBLISH.Status == MapLocationFinderStatus.Address.PLEASE DO NOT REPRODUCE. SHARE THIS DOCUMENT AS IT IS. if (mapLocation.Success) { .Locations[0]. Map control with 3D helps the user to view the location at any angle. CHANGE OR COPY. enable the app capabilities “Location” to allow your app to access the location. .Xaml. Next go to your MainPage. Firstly.28 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. 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.appxmanifest” file and enable location like below. SHARE THIS DOCUMENT AS IT IS. It’s very easy to implement 3D map in Universal App. REPUBLISH. 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.Maps" Add the MapControl using the following xaml code: <maps:MapControl x:Name="my3dMap" Loaded="my3dMap_Loaded"></maps:MapControl> ©2016 C# CORNER. Open “Package.XAML and add the following xmlns: xmlns:maps="using:Windows.PLEASE DO NOT REPRODUCE.Controls.UI. Let’s create new Windows 10 Universal Windows app. Geopoint location = new Geopoint(geoposition).4875. Set the map style Aerial3DwithRoads or Aerial3D as your wish.Is3DSupported) { my3dMap.Longitude = 76.Firstly. geoposition.TrySetSceneAsync(mapScene).9525. await my3dMap.Aerial3DWithRoads.Style = MapStyle. The full code looks like below. BasicGeoposition geoposition = new BasicGeoposition(). 500. RoutedEventArgs e) { if (my3dMap. REPUBLISH.PLEASE DO NOT REPRODUCE. CHANGE OR COPY. 70). SHARE THIS DOCUMENT AS IT IS.Latitude = 8. . private async void my3dMap_Loaded(object sender. 29 Now go to code behind page and follow the below steps. MapScene mapScene = MapScene.CreateFromLocationAndRadius(location. 150. check the map supports 3D. geoposition. Then set the position latitude and longitude finally call the TrySetSceneAsync method by passing map scene. } } ©2016 C# CORNER. .30 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. REPUBLISH.PLEASE DO NOT REPRODUCE. CHANGE OR COPY. ©2016 C# CORNER. SHARE THIS DOCUMENT AS IT IS. FileTypeFilter. SHARE THIS DOCUMENT AS IT IS.PicturesLibrary. It requires at least one type.jpg"). Here. Firstly.Add(".SuggestedStartLocation = PickerLocationId.ViewMode = PickerViewMode. Create new Windows 10 project and create a button and image control to perform FilePicker operation.Add(". Here we are going to pick the image file in Windows 10. For multiple file selection: ©2016 C# CORNER.FileTypeFilter.PLEASE DO NOT REPRODUCE. . Next.PickSingleFileAsync(). We need to add FileTypeFilter. I am going to set thumbnail. openPicker. We would be able to add values. you could ignore this. openPicker.Thumbnail. Here I am setting filter type for png and jpg images.png"). openPicker.31 Part 12: File Picker in Windows 10 UWP In this part we are going to see the FileOpenPicker in Windows 10 application. The FileTypeFilter is a readonly collection. 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. mandatory fields you should add. For single file selection: StorageFile file = await openPicker. Finally. Then set the suggested location as your wish I am going to set default location as picture library. CHANGE OR COPY. there are two options such as List and Thumbnail. but if you would like to add. openPicker. REPUBLISH. In Windows 10 we have OpenFileDialog which opens a dialog to pick the files. create a new instance for FileOpenPicker as in the following snippet: FileOpenPicker openPicker = new FileOpenPicker(). we have to set file picker ViewMode. RoutedEventArgs e) { FileOpenPicker openPicker = new FileOpenPicker().OpenAsync(Windows.Read).Add(". var image = new BitmapImage().SetSource(stream).Add(".PickMultipleFilesAsync(). StorageFile file = await openPicker.Source = image. openPicker.ViewMode = PickerViewMode.PLEASE DO NOT REPRODUCE. } else { // } ©2016 C# CORNER. image.OpenAsync(Windows. openPicker. we are going to set the selected image stream to empty image control.Read).png"). } else { // } The whole code looks like the following code: private async void openBtn_Click(object sender.FileAccessMode.Thumbnail. .SuggestedStartLocation = PickerLocationId.Storage. 32 StorageFile file = await openPicker. openPicker.SetSource(stream).FileAccessMode. if(file!=null) { var stream = await file.Storage. REPUBLISH.FileTypeFilter. image.PicturesLibrary.jpg").Finally.PickSingleFileAsync().Source = image. CHANGE OR COPY. SHARE THIS DOCUMENT AS IT IS. var image = new BitmapImage(). imageView. imageView. openPicker.FileTypeFilter. if(file!=null) { var stream = await file. . } Finally.PLEASE DO NOT REPRODUCE. var image = new BitmapImage(). image. run your app and you can see the following output: ©2016 C# CORNER.OpenAsync(Windows. SHARE THIS DOCUMENT AS IT IS. yourimagelist. CHANGE OR COPY.SetSource(stream).Add(image).Read). REPUBLISH.Storage.FileAccessMode.33 } For multiple file selection. foreach(var files in filelist) { var stream = await file. FileTypeFilter. The FileTypeFilter is a readonly collection. openPicker. it is a mandatory field that you should add. Finally. In Windows 10 we have OpenFileDialog which opens a dialog to pick the files. SHARE THIS DOCUMENT AS IT IS. create a new instance for FileOpenPicker as in the following code snippet: FileOpenPicker openPicker = new FileOpenPicker(). We would be able to add values. Here I am setting filter type for . Create new Windows 10 project and create a button and image control to perform File Picker operation. We need to add FileTypeFilter. It requires at least one type. we have to set file picker ViewMode. Finally. CHANGE OR COPY. StorageFile file = await openPicker.PickSingleFileAsync().ViewMode = PickerViewMode.Thumbnail. Then set the suggested location as you wish.txt files. we are going to read the selected file using stream and assign it to textblock. I am going to set default location as document library. openPicker. openPicker.In this part we are going to see how to open text file using FileOpenPicker in Windows 10 application. Firstly.txt").Add(". ©2016 C# CORNER.DocumentsLibrary. Here I will set thumbnail. you could ignore this. Next. Here we are going to pick the text file in Windows 10. such as List and Thumbnail.PLEASE DO NOT REPRODUCE. 34 Part 13: Pick text file in windows 10 .SuggestedStartLocation = PickerLocationId. REPUBLISH. there are two options. but if you would like to add. 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. OpenAsync(Windows.Storage. 35 private async void buttonPick_Click(object sender.DocumentsLibrary.txt"). openPicker. CHANGE OR COPY.Thumbnail.Text = reader.if (file != null) { var stream = await file.PickSingleFileAsync(). REPUBLISH.ReadToEnd(). openPicker. using (StreamReader reader = new StreamReader(stream. } } else { } } Now run debug and run the app and you can see the following output: ©2016 C# CORNER. SHARE THIS DOCUMENT AS IT IS.ViewMode = PickerViewMode. StorageFile file = await openPicker. openPicker.FileAccessMode.AsStream())) { textBlockShow.FileTypeFilter. RoutedEventArgs e) { FileOpenPicker openPicker = new FileOpenPicker().PLEASE DO NOT REPRODUCE.SuggestedStartLocation = PickerLocationId.Add(". .Read). Open your MainPage. . SHARE THIS DOCUMENT AS IT IS. REPUBLISH.36 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. Steps: Create new Windows 10 blank project and give suitable name. Let’s see how simple it is to drag and drop image from your local system desktop into your Windows 10 Universal apps. which will be ©2016 C# CORNER.XAML page and go to xaml code area in that create one StackPanel and allow drop property to true.PLEASE DO NOT REPRODUCE. a new drag-and-drop functionality was introduced to Windows Universal apps for scenarios such as dragging image or document from your local machine straight into your app. In Windows 10 platform. Attach an event handler to Drop and DropOver event. CHANGE OR COPY. 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. REPUBLISH. .StorageItems)) { var items = await e.410"> </StackPanel> <Image x:Name="dragedImage" Margin="0.0.AcceptedOperation = DataPackageOperation. DropOver will be used to allow image copying while it's dragged over the stackpanel. DragEventArgs e) { if (e. SHARE THIS DOCUMENT AS IT IS.GetStorageItemsAsync(). 37 used to handle an event of dropping image or document on the stackpanel. if (items.0.0.235.PLEASE DO NOT REPRODUCE.SetSource(await storeFile.Read)).0"> </Image> </Grid> Now go to code behind page and write the following code in drop and dragover event handler.Source = bitmapImage. <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <StackPanel Drop="StackPanel_Drop" DragOver="StackPanel_DragOver" AllowDrop="True" Background="#FF6C5C5C" BorderBrush="#FF3619F1" Margin="0. CHANGE OR COPY. bitmapImage.Contains(StandardDataFormats. Full source code looks like the following.DataView. } } } private void StackPanel_DragOver(object sender.Copy.OpenAsync(FileAccessMode.DataView. var bitmapImage = new BitmapImage().Add an Image object inside to show the image which was dropped. DragEventArgs e) { e. dragedImage. } ©2016 C# CORNER.Any()) { var storeFile= items[0] as StorageFile. private async void StackPanel_Drop(object sender. DragUIOverride. ©2016 C# CORNER.IsCaptionVisible = true. 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. SHARE THIS DOCUMENT AS IT IS. 38 When image is being dragged over the stackpanel the DragOver event handler will be fired in that event. e.DragUIOverride.PLEASE DO NOT REPRODUCE.Caption = "You are dragging a image". REPUBLISH.Copy. I am going to allow copying the dragged image. e.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.AcceptedOperation = DataPackageOperation.IsContentVisible = true. } Now run the app and you can see the following output: While drag the image in to stackpanel. . CHANGE OR COPY.DragUIOverride. DragEventArgs e) { e. e. 39 After dropped into the stackpanel . See the step by step implementation.PLEASE DO NOT REPRODUCE.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. CHANGE OR COPY. ©2016 C# CORNER. SHARE THIS DOCUMENT AS IT IS. REPUBLISH. Introduction SQLite is a lightweight database used for mobile local storages. Create new UWP project. Setup SQLite environment. install SQLite. we are going to the following areas:   How to perform SQLite CRUD operations.Net-PCL extension from NuGet Package: Now. SHARE THIS DOCUMENT AS IT IS.Next.PLEASE DO NOT REPRODUCE. CHANGE OR COPY. How to bind SQLite data to a ListBox Design the UI as in the following: ©2016 C# CORNER. 40 Install SQLite-UAP extensions form NuGet Package Manager as in the following screenshot: . REPUBLISH. I am going to create one Student DB with Students Table with id.ColumnDefinitions> <Grid.ItemTemplate> <DataTemplate> <TextBlock x:Name="ee" Text="{Binding Name}" FontSize="14"></TextBlock> </DataTemplate> </ListView. .RowDefinitions> <Button x:Name="CreateDBbutton" Grid.Row="2" Content="Read Students List" Width="300" Click="read_Click" HorizontalAlignment="Center"></Button> <Button x:Name="update" Grid. REPUBLISH.PLEASE DO NOT REPRODUCE.Row="0" Content="Create Local Database" HorizontalAlignment="Center" VerticalAlignment="Top" Click="button_Click" /> <Button x:Name="create" Grid.ColumnDefinitions> <ColumnDefinition></ColumnDefinition> </Grid. Name.Row="1" Content="Create New Students" HorizontalAlignment="Center" Click="create_Click"></Button> <Button x:Name="read" Grid.Row="3" Content="Update Details" Width="300" Click="update_Click" HorizontalAlignment="Stretch"></Button> <ListView x:Name="allstudents" HorizontalAlignment="Stretch" Grid.41 XAML Code <Grid Background="#FFF589E2"> <Grid.ItemTemplate> </ListView> </Grid> Now write the following code in your corresponding button click events. SHARE THIS DOCUMENT AS IT IS.Row="4"> <ListView.RowDefinitions> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid. CHANGE OR COPY. Address and Mobile so first design the table as in the following: ©2016 C# CORNER. sqlpath)) { conn. } public Students() { .PLEASE DO NOT REPRODUCE. } } Create DB public static void CreateDatabase() { var sqlpath = System.Net. SQLite. set.Storage. set.Pat h. SHARE THIS DOCUMENT AS IT IS.Net. } public string Address { get. Address = address.Platform.} public Students(string name. "Studentdb. 42 public class Students { [SQLite.SQLitePlatformWinRT().sqlite").IO. } } Insert New Student details public void Insert(Students objContact) { ©2016 C# CORNER. } public string Name { get.ApplicationData.SQLiteConnection(new SQLite. Mobile = mobile. set. using (SQLite.CreateTable<Students>().Attributes.Net. } public string Mobile { get. string mobile) { Name = name.AutoIncrement] public int Id { get.LocalFolder.Attributes.Net. string address.PrimaryKey. CHANGE OR COPY.Path. set.Current. REPUBLISH.Combine(Windows.Net.SQLiteConnection conn = new SQLite.WinRT. using (SQLite.Storage.SQLitePlatformWinRT().RunInTransaction(() => { conn.ApplicationData.Platform.Path.Storage.WinRT.SQLiteConnection conn = new SQLite.SQLiteConnection conn = new SQLite. public Students ReadContact(int contactid) { var sqlpath = System. REPUBLISH.Path.PLEASE DO NOT REPRODUCE. sqlpath)) { var existingconact = conn.SQLitePlatformWinRT().IO. sqlpath)) { conn. "Studentdb.LocalFolder.SQLiteConnection(new SQLite.WinRT.Net. using (SQLite.Insert(objContact). 43 var sqlpath = System.Current.SQLiteConnection(new SQLite.Path.Current.Storage.Net.Combine(Windows. } } Read all student details //Read All Student details public ObservableCollection<Students> ReadAllStudents() { var sqlpath = System.Current.Net. return existingconact. "Studentdb. }).LocalFolder. ©2016 C# CORNER. CHANGE OR COPY.sqlite").Query<Students>("select * from Students where Id =" + contactid).ApplicationData.Path.Net.ApplicationData. // Retrieve the specific contact from the database.Net.FirstOrDefault().Platform.Net.IO.Combine(Windows.LocalFolder.Combine(Windows. SHARE THIS DOCUMENT AS IT IS. .Path.Path.IO. "Studentdb.sqlite").sqlite"). } } Retrieve the specific contact from the database. Mobile = "962623233".Storage.ApplicationData.SQLitePlatformWinRT().Table<Students>().Net.SQLitePlatformWinRT(). SHARE THIS DOCUMENT AS IT IS.sqlite").Update(existingconact). sqlpath)) { List<Students> myCollection = conn.Net.Name = name.Query<Students>("select * from Students where Name =" + name). using (SQLite.Net.LocalFolder.FirstOrDefault().Path. } } } ©2016 C# CORNER.ToList<Students>(). sqlpath)) { var existingconact = conn.Path. if (existingconact != null) { existingconact.Net.WinRT.RunInTransaction(() => { conn.Net.Combine(Windows. "Studentdb. REPUBLISH.Address = "NewAddress".SQLiteConnection(new SQLite. }). CHANGE OR COPY. ObservableCollection<Students> StudentsList = new ObservableCollection<Students>(myCollection).} Update student details //Update student detaisl public void UpdateDetails(string name) { var sqlpath = System.Current.PLEASE DO NOT REPRODUCE.IO. return StudentsList. existingconact. existingconact. 44 using (SQLite. } . conn.Net.WinRT.Platform.SQLiteConnection conn = new SQLite.Platform.SQLiteConnection(new SQLite.SQLiteConnection conn = new SQLite. WinRT.Storage.Current.ApplicationData.LocalFolder. 45 Delete all student or delete student table .Net. sqlpath)) { var existingconact = conn.Platform.Path. ©2016 C# CORNER. if (existingconact != null) { conn. CHANGE OR COPY.Close().sqlite").Delete(existingconact). using (SQLite.Path.RunInTransaction(() => { conn.DropTable<Students> (). conn.Path.SQLitePlatformWinRT().Net.Query<Students>("select * from Studentdb where Id =" + Id). sqlpath)) { conn.CreateTable<Student s>(). REPUBLISH.SQLiteConnection conn = new SQLite.WinRT. "Studentdb.//Delete all student or delete student table public void DeleteAllContact() { var sqlpath = System.Combine(Windows.SQLiteConnection conn = new SQLite.IO.Combine(Windows.SQLiteConnection(new SQLite.SQLiteConnection(new SQLite.Dispose().Path.FirstOrDefault().Current.Storage.PLEASE DO NOT REPRODUCE.Net. conn. SHARE THIS DOCUMENT AS IT IS.SQLitePlatformWinRT().Net. "Studentdb.IO. conn.Platform.sqlite").ApplicationData.Net.LocalFolder. } } Delete specific student //Delete specific student public void DeleteContact(int Id) { var sqlpath = System. using (SQLite.Net. For source code. REPUBLISH. } } } 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. ©2016 C# CORNER.46 }). . CHANGE OR COPY. SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE. REST is a resource that implements a uniform interface using standard HTTP GET.HttpClient. If you are going to develop native UI or pass specific SSL certificates for Authentication then use Windows. Now see how to consume REST service in Windows 10 app using System.HttpClient. The System. The supported OS and programming languages are as follows: API OS Versions System. If you are going to develop app with cross platform. then use System. REPUBLISH.HttpClient.HttpClient API.Http.NET 4. PUT methods that can be located by URI.Http.Web.HttpClient Windows.Web.Net. This API supports Xamarin IOS and Android development.Net. Create new windows 10 project For POST JSON data write the following code.5.1 onwards Supported Languages . such as iOS.Http. POST.Net.HttpClie nt Windows Phone 8 onwards Windows. Windows 10 UWP supports basic get and post web requests using the following two APIs:   System.Http.NET languages All Both of this APIs are available in UWP.Net. Android.Http.Http.Web. Before that we will introduce REST services. SHARE THIS DOCUMENT AS IT IS. In Windows 10 this API has changed to top layer of Windows.HttpClient was introduced in .PLEASE DO NOT REPRODUCE.Http. Select which one you need.Net. 47 Part 16: Consume web service using HttpClient to POST and GET json data in Windows 10 UWP . CHANGE OR COPY. ©2016 C# CORNER.Http.HttpClient.HttpClient Windows. Windows Phone 8.Http.In this part we will see how to consume a REST service in Windows 10.Web. 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");//replace your 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: ©2016 C# CORNER. SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 48 URI is the url you are going to POST JSON data. 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 the InternetClient 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: <Grid> <MediaElement x:Name="liveMedia" /> </Grid> Next add two app bar controls to Play and Pause the streaming. <Page.BottomAppBar> <AppBar IsOpen="True"> <StackPanel Orientation="Horizontal"> <AppBarButton Name="playBtn" Click="playBtn_Click" Icon="Play" Label="Play"></AppBarButton> <AppBarButton Name="pausBtn" Click="pausBtn_Click" Icon="Pause" Label="Pause"></AppBarButton> ©2016 C# CORNER. SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 49 Part 17: HTTP Live Streaming in Windows 10 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 the live news channel. ©2016 C# CORNER. SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY. 50 </StackPanel> </AppBar> </Page.BottomAppBar> A background transfer is used for long-term transfer or downloads operations such as video. 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 <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid. Design your xaml page. 51 Part 18: Background File Downloader for Windows 10 UWP . Let’s see the steps how to download files from server.PLEASE DO NOT REPRODUCE. If the user exits the app. CHANGE OR COPY. For that time user will allow play around your app don’t stop the user to wait. REPUBLISH. the download will continue in the background. BackgroundDownloader class will help you to transfer or download the files from the server event the app is running in foreground. SHARE THIS DOCUMENT AS IT IS.In this part we are going to see how background files downloading work in Windows 10 UWP app. music.RowDefinitions> <TextBox x:Name="linkBox" Height="20" Width="200" Grid. You can check when the app is relaunched.Row="0" HorizontalAlignment="Left"> </TextBox> <TextBlock x:Name="Statustext" Height="30" Grid.RowDefinitions> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="Auto"></RowDefinition> </Grid.Row="2" Content="Download" Click="downloadBtn_Click" HorizontalAlignment="Center" VerticalAlignment="Top" /> </Grid> ©2016 C# CORNER.Row="1" HorizontalAlignment="Center" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" /> <Button x:Name="downloadBtn" Height="30" Grid. Create new Windows 10 project and give a suitable name. and images. InitializeComponent(). CancellationTokenSource cancellationToken.FileTypeFilter.BackgroundDownloader(). SHARE THIS DOCUMENT AS IT IS. To enable the capability follow the below steps.Double click your package. 52 Next we need to ensure that your app has the capability to access the internet. ©2016 C# CORNER. public MainPage() { this. StorageFolder folder = await folderPicker.Thumbnail. CHANGE OR COPY. .SuggestedStartLocation = PickerLocationId. } public async void Download() FolderPicker folderPicker = new FolderPicker(). folderPicker.PickSingleFolderAsync().BackgroundDownloader backgroundDownloader = new Windows. folderPicker. folderPicker.Add("*").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.ViewMode = PickerViewMode.BackgroundTransfer.Networking. REPUBLISH.BackgroundTransfer.Downloads.PLEASE DO NOT REPRODUCE. Windows.Networking. } } private void progressChanged(DownloadOperation downloadOperation) { int progress = (int)(100 * ((double)downloadOperation.BytesReceived / (double)downloadOperation.Progress. REPUBLISH. } catch (TaskCanceledException) { downloadOperation. file)."..Text = String. } case BackgroundTransferStatus.Progress.StartAsync().Token. progress). Progress<DownloadOperation> progress = new Progress<DownloadOperation>(progressChanged).BytesReceived / 1024. progress). downloadOperation = backgroundDownloader.Progress. switch (downloadOperation. downloadOperation = null.Text = "Initializing. SHARE THIS DOCUMENT AS IT IS. .CreateDownload(durl..Text. CHANGE OR COPY.ResultFile. Statustext.TotalBytesToReceive)).PausedByApplication: { break.GenerateUniqueName). downloaded .".PLEASE DO NOT REPRODUCE. downloadOperation.DeleteAsync( ).Status) { case BackgroundTransferStatus.try { Statustext.ToString()). CreationCollisionOption.jpg".Progress. 53 if (folder != null) { StorageFile file = await folder.Running: { break. cancellationToken = new CancellationTokenSource().Progress.TotalBytesToReceive / 1024. ©2016 C# CORNER.CreateFileAsync("NewFile. downloadOperation.AsTask(cancellationToken. Uri durl = new Uri(linkBox.Format("{0} of {1} kb. await downloadOperation.%{2} complete. } case BackgroundTransferStatus.Error: { Statustext.break. } } 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. 54 } case BackgroundTransferStatus.Text = "An error occured while downloading. } } if (progress >= 100) { downloadOperation = null. RoutedEventArgs e) { Download().PausedNoNetwork: { . 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.". CHANGE OR COPY. Here I am going to download the Google logo.PLEASE DO NOT REPRODUCE. } } private void downloadBtn_Click(object sender. REPUBLISH. break. SHARE THIS DOCUMENT AS IT IS. } case BackgroundTransferStatus.PausedCostedNetwork: { break. ©2016 C# CORNER. 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. SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE.55 ©2016 C# CORNER. REPUBLISH. . CHANGE OR COPY. RowDefinitions> <Grid.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock TextWrapping="Wrap" Text="{Binding Path=Title.Row="0"></Button> <ScrollViewer Grid.56 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.Text}" /> </StackPanel> </DataTemplate> </ItemsControl. . Design view will be designed as like the following XAML code: <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid> <Grid.ItemTemplate> </ItemsControl> </ScrollViewer> <ProgressRing x:Name="testring" Grid. Create new Windows 10 project and give suitable name.PLEASE DO NOT REPRODUCE. CHANGE OR COPY.Row="2"></ProgressRing> ©2016 C# CORNER.ColumnSpan="2" Margin="20" BorderThickness="0"> <ItemsControl Name="Display"> <ItemsControl. REPUBLISH.Row="0" Name="Value" Margin="20" VerticalAlignment="Center" /> <Button x:Name="feedClick" Click="feedClick_Click" Content="Feed" Grid. In windows 10 default SyndicationClient helps you to feed RSS service.ColumnDefinitions> <ColumnDefinition></ColumnDefinition> <ColumnDefinition Width="Auto"></ColumnDefinition> </Grid.Column="0" Grid.Row="1" Grid. SHARE THIS DOCUMENT AS IT IS.ColumnDefinitions> <TextBox Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> <RowDefinition Height="*" /> </Grid.Column="1" Grid. string value) { try { load(list. } catch ©2016 C# CORNER.RetrieveFeedAsync(uri). REPUBLISH. Using RetrievedFeedAsync pass the url which you want to feed. SHARE THIS DOCUMENT AS IT IS. CHANGE OR COPY.Items.Items.Items) { list. SyndicationFeed feed = await client. new Uri(value)). Uri uri) { SyndicationClient client = new SyndicationClient().RetrieveFeedAsync(uri). The full source code should be like this private async void load(ItemsControl list.57 </Grid> </Grid> Now go to code behind and create new instance of SyndicationClient and SyndicationFeed.Items) { list. SyndicationClient client = new SyndicationClient().PLEASE DO NOT REPRODUCE. } Here I create one helper class to perform RSS feed. .Add(item). SyndicationFeed feed = await client. if (feed != null) { foreach (SyndicationItem item in feed.Add(item). } } } public void Go(ref ItemsControl list. Using foreach you can manipulate the feed items: oreach (SyndicationItem item in feed. Value. RoutedEventArgs e) { helperRSS. } private void feedClick_Click(object sender. SHARE THIS DOCUMENT AS IT IS. Output ©2016 C# CORNER.PLEASE DO NOT REPRODUCE. CHANGE OR COPY.Keyboard). .Text). Here I am going to feed my C# Corner articles. } Now run the application and enter your RSS feed Url in the given textbox.Focus(FocusState.58 { } list.Go(ref Display. REPUBLISH. getAltiude.PLEASE DO NOT REPRODUCE.Sample code public void GetAltimeter() { Altimeter getAltiude = Altimeter. The Altimeter has an event called ReadingChanged and triggered whenever a new value is sensed by the Altimeter sensor. } ©2016 C# CORNER. changes in elevation.ReadingChanged += GetAltiude_ReadingChanged. getAltiude. } private void GetAltiude_ReadingChanged(Altimeter sender. CHANGE OR COPY.e. 59 Part 20: Sensors in Windows 10 UWP App . using Windows. To access the sensors API add the following namespace first.Reading. Altimeter Altimeter helps to measure the relative altitude i.Windows 10 SDK comes with lots of new sensors which helps the users to keep health fit to know what the user needs. AltimeterReadingChangedEventArgs args) { AltimeterReading readingvalues = args.Sensors. The new list of sensors can be seen below:      Altimeter Activity Sensor Barometer Pedometer Proximity Sensor Let’s see the sensor in detail.GetCurrentReading().GetDefault(). REPUBLISH.ReportInterval = 100. SHARE THIS DOCUMENT AS IT IS.Devices. ReportInterval property is used to set the time interval at which the sensor has to report. AltimeterReading reading = getAltiude. InVehicle). CHANGE OR COPY.60 Activity Sensor ActivitySensor will help to detect the user’s activity based on the user motion context. foreach (var values in details) { string newvalue = values.ReadingChanged += new TypedEventHandler<ActivitySensor.ActivitySensorReadingChangedEventArgs>(ReadingC h anged). SHARE THIS DOCUMENT AS IT IS. These sensors help to detect the motion of user either walking.Background. The Barometer API has an Event handler ReadingChanged which gets a new value is sensed by the sensor. var details = await ActivitySensor.Add(ActivityType.Activity. var reading = await activity. This sensor set to idle state when the device is without any movement and also you can get the details up to 30 days.Reading. Barometer The Barometer is help’s to measure the atmospheric pressure. } To get the last 30 days details: DateTimeOffset last30days = DateTime. .AddDays(-30).GetSystemHistoryAsync(last30days). The ReportInterval ©2016 C# CORNER. running and idle etc.ApplicationModel. activity.SubscribedActivities. } private void ReadingChanged(ActivitySensor sender.PLEASE DO NOT REPRODUCE. trigger.GetDefaultAsync(). } var trigger = new Windows. ActivitySensorReadingChangedEventArgs args) { ActivitySensorReading readingActivity = args. Sample code to get the activity reading: public async void GetActivity() { ActivitySensor activity =await ActivitySensor. REPUBLISH.ToString().Today.ActivitySensorTrigger(100).GetCurrentReadingAsync(). Sample Code public async void getBarometer() { Barometer barometerValues = Barometer. readings. Pedometer sensor comes with Windows Phone 10 and also in Microsoft Band.GetDefault(). Sample Code public async void pedometer() { Pedometer readings = await Pedometer. barometerValues.PLEASE DO NOT REPRODUCE. } 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. REPUBLISH. var getPressure = reading.Reading. BarometerReadingChangedEventArgs args) { string values = args. SHARE THIS DOCUMENT AS IT IS. 61 property is used to set the interval at which the sensor has to report.ReadingChanged += Readings_ReadingChanged. barometerValues. if (readvalues. .GetCurrentReading().ReportInterval = 100.StepKind == PedometerStepKind. GetCurrentReading method is used to gets the current reading for the barometer.Reading. } private void Barometer_ReadingChanged(Barometer sender.Walking) ©2016 C# CORNER.ReportInterval = 150. readings. } private void Readings_ReadingChanged(Pedometer sender.GetDefaultAsync().ReadingChanged += Barometer_ReadingChanged.StationPressureInHectopascals. CHANGE OR COPY. BarometerReading reading = barometerValues. PedometerReadingChangedEventArgs args) { PedometerReading readvalues = args.ToString(). Running) { var runningSteps = readvalues. watch = DeviceInformation. } else if (readvalues.ReadingChanged += Sensor_ReadingChanged.Start(). watch. watch.CreateWatcher(ProximitySensor.GetCurrentReading().GetDeviceSelector()). CHANGE OR COPY.CumulativeSteps. ProximitySensorReadingChangedEventArgs args) { ProximitySensorReading readStatus = args. public void GetProximityStatus() { DeviceWatcher watch.Now. ProximitySensorReading reading = sensor.StepKind == PedometerStepKind. Sample Code ProximitySensor sensor.Reading. } private void Sensor_ReadingChanged(ProximitySensor sender.CumulativeSteps.PLEASE DO NOT REPRODUCE. 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. } public async void gettingHistory() { var history = await Pedometer.AddDays(-30)). SHARE THIS DOCUMENT AS IT IS. REPUBLISH. 62 { . } ©2016 C# CORNER. sensor. } 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.GetSystemHistoryAsync(DateTime.Added += Watch_Added.var walkingsteps = readvalues. 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. SHARE THIS DOCUMENT AS IT IS. Let's see the steps Firstly. The type is the name of the device family type (Mobile. IoT). ©2016 C# CORNER.etc). Mobile. 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.XAML in the project.Id). called “DeviceFamily-Type”. Desktop. sensor = identified. This method is the most common way to perform this task. 63 private void Watch_Added(DeviceWatcher sender. There are three ways to set specific device family XAML view.FromId(args. REPUBLISH. Create a new folder in your project. Let us take the MainPage. 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. CHANGE OR COPY. Create new Windows 10 blank project and give a suitable name. If we want to have different view for different device families. Team. with blue background we want this specific XAML view for a mobile device family. Using DeviceFamily-Type folder. } . DeviceInformation args) { ProximitySensor identified = ProximitySensor.PLEASE DO NOT REPRODUCE. ©2016 C# CORNER.xaml from the main folder. it would mean adding a new XAML view file called MainPage.This MainPage. REPUBLISH. For any other device family type. MainPage. but with DeviceFamily-Type extension in our MainPage.DeviceFamily-Mobile.PLEASE DO NOT REPRODUCE.xaml. CHANGE OR COPY.xaml to the main folder and looks like below screen.xaml.cs file. The second method to perform the same thing is to create a new XAML View with. SHARE THIS DOCUMENT AS IT IS. the same name.xamlwill be added into the folder DeviceFamily-Mobile and looks like the following: . 64 The next step would be adding a XAML view called the same as the page so in this case. it will load the MainPage. again.XAML won't have any code-behind. Now run the app on a mobile device it will load the XAML from DeviceFamilyMobile/MainPage. it will use the code-behind of the main MainPage. Change the grid background colour to green like below code <Grid Background="Green"> </Grid> Second one is DeviceFamily-Type in file name. SHARE THIS DOCUMENT AS IT IS.PLEASE DO NOT REPRODUCE. . CHANGE OR COPY. 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 ©2016 C# CORNER.65 Depending on the device family. REPUBLISH. 1 apps you had to create a Canvas. CHANGE OR COPY. . This control allows user to quickly enable inking for user and easily expand its functionality by accessing the InkCanvas’s InkPresenter property. In Windows 8. InkPresenter can be used to configure a collection of user input through touch or mouse input. Once successful created.XAML page and write the following code to design your page. 66 In this part we will see how to capture user input and save it as image.0. create new instance for InkPresenter.Windows 10 introduced built-in InkCanvas control to capture the user input. Create a new windows 10 UWP app. InkPresenter myPresenter = myCanvas. and render your own strokes. ©2016 C# CORNER.InkPresenter. Let’s see the steps to perform this operation.PLEASE DO NOT REPRODUCE. but in Windows 10 use the built-in InkCanvas control to immediately capture use input. Firstly. listen to input events.10"> </InkCanvas> The control looks like the following image: Next got to code behind page and write the following code. I am going to show the use of InkCanvas control to capture the user touch input and save it as image. REPUBLISH. SHARE THIS DOCUMENT AS IT IS. <InkCanvas x:Name="myCanvas" PointerPressed="myCanvas_PointerPressed" PointerMoved="myCanvas_PointerMoved" PointerReleased="myCanvas_PointerReleased" Margin="0.10. go to MainPage. Crimson. The whole code on canvas pointer pressed event looks like the following: private void myCanvas_PointerPressed(object sender.UI.Circle.UI.CoreInputDeviceTypes. ©2016 C# CORNER.InputDeviceTypes = Windows.Size = new Size(2.Color = Windows. InkDrawingAttributes myAttributes = inkPresenter. 5).UI. .PenTipTransform = System. Touch.Numerics. myAttributes.Core.PI / 4). inkPresenter.Mouse|Windows.CreateRotation((float)Math. } Next save this ink into image. Mouse and Touch. myAttributes.Pen |Windows.Matrix3x2.Circle.InkPresenter.InputDeviceTypes = Windows. myAttributes.PenTip = PenTipShape. CHANGE OR COPY.UpdateDefaultDrawingAttributes(myAttributes ).PLEASE DO NOT REPRODUCE. PointerRoutedEventArgs e) { InkPresenter inkPresenter = myCanvas. Touch. myAttributes. inkPresenter.Core.Pen.CoreInputDeviceTypes.Size = new Size(2.Colors.Color = Windows.UI.Pen |Windows. private async void savebtn_Click(object sender.Crimson. REPUBLISH.PenTip = PenTipShape.Core.CoreInputDeviceTypes. 5). myAttributes. RoutedEventArgs e) { var savePicker = new FileSavePicker().UI. myPresenter.UI. Set the pen colour.Core. myAttributes.CoreInputDeviceTypes. 67 Next define the input device type for Canvas control to let the control accepts inputs from those devices.Core. myAttributes.Mouse|Windows.CopyDefaultDrawingAttributes(). SHARE THIS DOCUMENT AS IT IS.CoreInputDeviceTypes.UI.CoreInputDeviceTypes.Colors. pencil tip shape and size.Core.UI. SHARE THIS DOCUMENT AS IT IS.} } } Now change the InkPresenter processing mode to erase to delete the ink: myCanvas.PickerLocationId. StorageFile file = await savePicker.Add("PNG".PickSaveFileAsync(). savePicker.OpenAsync(FileAccessMode. if (null != file) { try { using (IRandomAccessStream stream = await file.ReadWrite)) { await myCanvas.PLEASE DO NOT REPRODUCE.SuggestedStartLocation = Windows. 68 savePicker. RoutedEventArgs e) { myCanvas.StrokeContainer.Storage.SaveAsync(stream).PicturesLibrary. CHANGE OR COPY. REPUBLISH.FileTypeChoices.png" }).InkPresenter.Pickers. } ©2016 C# CORNER.InputProcessingConfiguration.InkPresenter.Generic. new System.InputProcessingConfiguration. Erase button click event looks like below: private void erasebtn_Click(object sender.Erasing. } } catch (Exception ex) { .Collections.InkPresenter.Erasing.Mode = InkInputProcessingMode.Mode = InkInputProcessingMode.List<string> { ". 69 Now run the app and see the output looks like the following screen. . SHARE THIS DOCUMENT AS IT IS. CHANGE OR COPY. REPUBLISH.PLEASE DO NOT REPRODUCE. ©2016 C# CORNER. IsScreenCaptureEna bled = false.GetForCurrentView().com/ http://www. CHANGE OR COPY.PLEASE DO NOT REPRODUCE.In this part we are going to see how to disable screen capture in Windows 10 app. 70 Part 23: Disable screen capture in Windows 10 UWP .c-sharpcorner.wordpress. sometimes we will need to disable to take screenshots of your app. For more sample and articles follow:   https://windowsapptutorials. You need to call the View Management class get the current view screen.ApplicationView. This feature was available in Windows 10 app. If you are develop any security apps. REPUBLISH. SHARE THIS DOCUMENT AS IT IS. Finally set the screen capture Boolean value to false like the following code.com/members/suresh-m27 ©2016 C# CORNER.ViewManagement. Windows.UI.
Copyright © 2024 DOKUMEN.SITE Inc.