Upload
dinhtruc
View
247
Download
0
Embed Size (px)
Citation preview
Universal Windows Applications
What is UWP
Creating UI-apps with XAML
Different devices and capabilities
TopicsUnderstanding UWP• Architecture• UWP-platforms and devices• Languages• Visual Studio
Getting started• Hello world• XAML and Code Behind• Application properties
UI-Basics • XAML and databinding• Routed events• Working with collections
Navigation• Navigation-model of UWP-
application• Implementing navigation
2UWA-DevelopmentCopyright Tieturi, 2016
Ui-techniques• UI-design guidelines• Copy-paste and drag and
drop• Using graphics and
multimedia• Working with animations• Briefing to advanced UI-
techiques
Multithreading• Multithreaded concepts• async methods
Accessing user data• Accessing user-directories• Operating with files• Contacts and Calendar
Accessing remote data• Briefing to web services• SOAP and XML• REST and JSON
Application lifecycle• Lifecycle events• Suspend - Resume
Accessing the device• Device capabilities• Sensors• Camera• Location and maps
Security• Overview of security
techniques on UWP
Distributing apps• Packaging• Installing• Publishing process
Understanding UWPEvolution of Windows-platforms and techniques
Evolution of Windows platform
• First versions were 16-bit DOS-extenders
• 9x - series targeted 32-bit workstations
• The “true” evolution path started with NT-series• Even though the NT-versioning is currently
seldom seen
• Windows Server -products also have the “NT”-versioning, current Windows Server 2016 being also NT 10.0
Copyright Tieturi, 2016 UWA-Development 4
DOS-extenders
1985 - Windows 1.011993- Windows 3.2
9x-series
1995 - Windows 952000 - Windows ME
NT-series
1994 - Windows NT 3.51996 - Windows NT 4.0
2000 - Windows 2000 (NT 5.0)2001 - Windows XP (NT 5.1)
2007 - Windows Vista (NT 6.0)2009 - Windows 7 (NT 6.1)2012 - Windows 8 (NT 6.2)
2013 - Windows 8.1 (NT 6.3)2015 - Windows 10 (NT 10.0)
Win32-API provides the basics for development on Windows platform
.NET Framework
• Abstraction layer on top of operating system
• Common language runtime• Type system• Memory management• JIT-compilation• Security• Etc
• Huge class-library• I/O, Collections, Threads,
XML, Databases, Web Apps, Web Services etc
• You shouldn’t access Win32-API• Use framework provided
features instes
OS (Win32 API)
Common Language Runtime
Class Library
Assembly (.exe or .dll)• Contains bytecode
Source code (Any .Net -language)
Compiled
UsesUnmanaged(.exe or .dll)
• Binary code
C/C++
.NET -applications Traditional apps
5UWA-DevelopmentCopyright Tieturi, 2016
Framework versions• Version 1.0 (2002), 1.1 (2003), 2.0 (2005)
• Visual Studio 2005
• Version 3.0 (2007)
• Versio 3.5 (2007/2008)
• Visual Studio 2008
• Included in Windows 7 and Windows Server 2008 R2
• Versio 4 (2010)
• Visual Studio 2010
• Version 4.5 (2012)
• Visual Studio 2012
• Included in Windows 8 and Windows Server 2012 versioissa
• Version 4.51 (2013)
• Visual Studio 2013
• Included in Windows 8.1 and Windows Server 2012 R2
• Version 4.6 (2015)
• Visual Studio 2015
• Included in Windows 10
Some features of 3.x
• WPF (Windows Presentation Foundation)
• WCF (Windows Communication Foundation)
• WF (Workflow Foundation)
• LinQ (Language integratedquery)
Some features of 4.x
• TPL (Task Parallel Library)
• Dynamic languages
6UWA-DevelopmentCopyright Tieturi, 2016
.NET Core -what is it
What a heck is happening?
• Some technologies evolve so that they are no longer backward compatible with previous versions• They are not even more but at least to some extent just a subset
• Target is to have a true cross-platform environment
• Thus a “restart” in versioning
• So basically we are having• .NET Core 1.0, new cross-platform version of .NET Framework
• ASP.NET Core 1.0, surprisingly can use either .NET Core 1.0 or “old framework” 4.6• ASP.NET Core includes ASP.NET MVC and Web API, so no longer separate
versioning
• Entity Framework Core 1.0
7UWA-DevelopmentCopyright Tieturi, 2016
.NET Core technologies
• Core FX• Base class library (open source)• Basically System.* -classes• Runs on both Framework 4.6 and Core 1.0
• Core CLR• Cross-platform runtime• Based on Silverlight runtime
• DNX• .NET Execution environment• Cross-platform SDK & Runtime-environment• Basically built for web-apps, but can be used for other types of
applications also (console applications)
8UWA-DevelopmentCopyright Tieturi, 2016
Project on/with DNX
• Just a folder containing project.json• Interestingly json format was chosen for project description
instead of xml
• Project.json describes the supported frameworks• And their dependencies
• All files in the folder belong to the project• Unless excluded in the project.json
• Package distribution via NuGet• Also implement NuGet-packages
9UWA-DevelopmentCopyright Tieturi, 2016
Embedded and mobile evolution
• Windows CE -family is on the background of embedded devices
• Windows Mobile made it possible to implement apps in .NET-techniques
• Now Microsoft is branding operating systems under Windows 10• Home, Pro, Enterprise
• Mobile, Mobile Enterprise
• IoT Core, IoT Enterprise, IoT Mobile Enterprise
Copyright Tieturi, 2016 UWA-Development 10
Windows CE1996 - CE 1.0
2000 - Pocket PC2003 - Windows Mobile 20032013 - Windows Embedded
Compact 2013
CE + .NET (compact…)
2005 - Windows Mobile 52007 - Windows Mobile 6
2008 - Windows Mobile 6.12009- Windows Mobile 6.52010 - Windows Phone 72012 - Windows Phone 8
2014 - Windows Phone 8.1
UWP
2015 - Windows 10 Mobile
What is UWP
• Universal Windows Platform• Next stage of evolution for WinRT (Windows Runtime) introduced for
Windows 8.1• Targets Windows 10.x on various devices
• Single uniform set of APIs• Device independent WinRT API• Builds on Net.Core.UniversalWindowsPlatform• Device dependent Win32 and .NET APIs• Possible native compilation
• Single application package than can run on multiple devices• Unified tools• Unified codebase• Unified distribution
Copyright Tieturi, 2016 UWA-Development 11
So where are we?• We are working with Windows 10
• Preferably Anniversary Update (10.0.14393.0)
• We can build Universal Windows Applications• Targeting selected device families
• We can benefit from uniform programming model for all platforms• And still take advantage of device specific features
• UWA APIs replaces• Win32 API that became huge and inconsistent• NET Framework that also became huge and somewhat inconsistent• Separate models for mobile development
Copyright Tieturi, 2016 UWA-Development 12
1985 - 2000
Win(32) API -development
2000 - 2015.NET Development with separate tools
for Mobile
2015 - 2030
UWA-development
Device families
• Desktop• Mobile• XBox• IoT
• Internet of Things
• IoT headless• Internet of Things without UI
• HoloLens• Virtual reality -glasses
Copyright Tieturi, 2016 UWA-Development 13
Universal
Desktop Mobile Xbox IoT HoloLens
Device family gives a foundation for the OS.
Universal Device Family is inherited by other Device
Families: API declared there is available everywhere.
Your app may target any (or several) device families. Including the Universal
Device Family.
APIs
• Windows Runtime see: https://msdn.microsoft.com/en-us/library/windows/apps/br211377.aspx
• Device Families see: https://msdn.microsoft.com/en-us/library/windows/apps/dn706139.aspx
Copyright Tieturi, 2016 UWA-Development 14
Getting started
What is needed
• You will need Windows 10 as OS for your development machine• API is under rapid development, big changes between versions
• You will need Visual Studio• With UWA-development components
• The development mode needs to be enabled• Sidebar - Settings - Update & Security - For Developers
• Finally you may wish to download separate sets of emulators
Copyright Tieturi, 2016 UWA-Development 16
Visual Studio
Visual Studio has a project templates under C# - Windows -Universal
• Blank App• Basic application with UI
• Class library• Basic dll for Universal Windows Applications
• Can only be used from .NET-languages
• Windows Runtime Component• Produces metadata (winmd) so that the component can be
consumed from any supported language
• And project templates for Unit- and UI-testing
Copyright Tieturi, 2016 UWA-Development 17
The project files - Blank App• Project.json
• Dependencies, runtimes
• Package.appxmanifest• Packaging configuration• Most important application meta data
• App.xaml and code behind in App.xaml.cs• Application entry
• MainPage.xaml and code behind in MainPage.xaml.cs• UI for the main page
• Properties - AssemblyInfo.cs• Basically version information
• Properties - Default.rd.xml• Runtime Directives for .NET-native
• Assets-folder• Logos, images
Copyright Tieturi, 2016 UWA-Development 18
Don’t forget Project-properties !
Exercise - Hello world
• Create a blank Universal Windows Application• Study the files created
• Drag a TextBlock component from the Toolbox into desingsurface of MainPage.xaml• Change the Text-property into “Hello world”• Notice that you may view the design surface as it appears on different
devices
• Run the application• On local machine• One of the emulators
• Can you figure out how to change the text in the title bar of the main window?
• Spend some time going through the App.xaml.cs
Copyright Tieturi, 2016 UWA-Development 19
TargetDeviceFamily
• Package.appxmanifest describes the supported device/OS platform• You may target “Windows.Universal” which is default and just
specify the minimum OS-version (10.0.0.0)
• Or you may target only selected devices (“Windows.Desktop”, “Windows.Mobile”,”Windows.Xbox”, “Windows.Iot”) and specify minimum OS-version for each
• Or you may target “Windows.Universal” with specific OS-version, but still specify other targets with other OS-versions
• Read more:• https://msdn.microsoft.com/library/windows/apps/dn986903
Copyright Tieturi, 2016 UWA-Development 20
Devices specific XAMLs
You must be careful with the naming
• If you have MyPage.xaml you may also create • MyPage.DeviceFamily-Desktop.xaml• MyPage.DeviceFamily-Mobile.xaml• Etc
• Alternatively (Preferably) you may have folders for device families• DeviceFamily-Desktop -folder may contain MyPage.xaml and
other xamls targeting the desktop• DeviceFamily-Mobile -folder may contain MyPage.xaml and
other xamls targeting Mobile devices• Etc
Copyright Tieturi, 2016 UWA-Development 21
Application lifecycle
• Highly device and OS-specific states
Copyright Tieturi, 2016 UWA-Development 22
Running in Foreground
Running in Background
Suspended
Running in BackgroundActivate
LeavingBackgroundEnteringBackground
SuspendingResuming
OnLaunched
OnActivated
OnBackgroundActivated
Launching the application
• When user starts or switches to the application OnLaunched method is called• Not just “Start the application”
• LaunchActivatedEventArgs.PreviousExecutionState• NotRunning - First launch after reboot
• Suspended - Application is resuming
• Terminated - Application was suspended and then terminated
• ClosedByUser - User had forced the application to terminate
• Running - Application was already running
Copyright Tieturi, 2016 UWA-Development 23
Activating the application
• On occasions the OS may activate the application• Causing a call to OnActivated -method
• More precise activation methods also exist• OnCachedFileUpdaterActivated
• OnFileActivated
• OnFileOpenPickerActivated
• OnFileSavePickerActivated
• OnSearchActivated
• OnShareTargetActivated
Copyright Tieturi, 2016 UWA-Development 24
We’ll take a look into some of these later on during the course
Saving system resources
• Previously only OnLaunched and OnActivated were available• And Suspended + Resumed
• Now the recommendation is that UI-Resources should be constructed in LeavingBackground -handler• If you target late enough operating system (Anniversary Update)
• EnteringBackground should at least stop possible animations and also possibly release other UI-resources
• It is possible that you application does some work while in background, but in most cases EnteringBackground is also the location where you might want to save the state of the application• And resume the state on LeavingBackground
Copyright Tieturi, 2016 UWA-Development 25
Memory management• The OS may tell the application how much memory it may consume
• Windows.System.MemoryManager.AppMemoryUsageLimitChanging -event• Also AppMemoryUsageIncreased, AppMemoryUsageDecreased
• If you fail to follow your memory usage limit the OS may suspend or terminate the application
Copyright Tieturi, 2016 UWA-Development 26
private void OnMemoryUsageLimitChanging(object sender,
AppMemoryUsageLimitChangingEventArgs e) {
// If app memory usage is over the limit, reduce usage within 2 seconds
// so that the system does not suspend the app
if (MemoryManager.AppMemoryUsage >= e.NewLimit) {
DoSomethingToReduceMemoryUsage(e.NewLimit);
}
}
UI-design for different screen sizes• The platform uses effective pixels, not physical pixels
• Automatic scaling• You should “snap” to grid of 4x4 pixels for best scaling results
• You may design different XAMLs for different device families• Little clumsy but unlimited options• You may (if you truly wish) also have a separate code for different
device families
• You may specify breakpoints on screen widths and triggers for device families• Recommended breakpoints 320epx, 720epx and 1024epx• And alter the layout based on those
• And of course you may use different containers to provide “fluid” layouts• Mostly available for ItemsControls• You can also create your custom containers
Copyright Tieturi, 2016 UWA-Development 27
Deployment
• After throrough testing…
• You may package your application with Visual Studio• Right-click project on Solution Explorer - Strore - Create App
Packages
• You have two distribution options• Upload to store
• Developer Account is required
• Sideloading• Just install to a separate device
• Sideload applications option must be enabled
Copyright Tieturi, 2016 UWA-Development 28
Exercise - Targeting different devices
• Modify Package.appxmanifest• Target only Windows.Desktop, test to launch in emulator• Target both Windows.Desktop and Windows.Mobile• Test to launch in both• Change the MinVersion to a higher than available, test
• Create MainPage.DeviceFamily-Desktop.xaml and MainPage.DeviceFamily-Mobile.xaml• Make the UI appear a little different for both• Test in the emulator and local machine
• Add EnteredBackground- and LeavingBackground- event handlers• Use Debug.WriteLine to display some info on debug output on each handler
• Extra• Modify the images in Assets-folder so that you can see which image is used
where
Copyright Tieturi, 2016 UWA-Development 29
UI-BasicsUI-patterns
Basic XAML-techniques
MVVM and Databinding
UI-patterns
• Model-View-Controller• Decouples the user interface from the data
model
• Most suitable for Web development
• Model-View-Presenter• Evolves the MVC pattern for event-driven
applications
• Most suitable for forms-over-data development
• Introduces databinding
• Model-View-ViewModel• Evolves from the MVP pattern
• Most suitable for WPF and UWA applications
• More loosely coupled
Controller
Model View
Selects
ActionCreates
Presenter
Model View
Update
ActionUpdateNotify
Databinding
Uses
ViewModel
Model View
NotifyBindingCommandsUpdate
Notify
31UWA-DevelopmentCopyright Tieturi, 2016
MVVM - View, Binder and ViewModel
• MVVM is a pattern created by Microsoft especially for WPF-applications• Now-a-days used on other platforms also
• Like any pattern can actually be implemented in many ways
• The key idea is the abstraction of data- and command-binding to xaml• Basis for WPF- and UWA-programming• Deep understanding of xaml and binding mechanisms provided by it are needed
• ViewModel provides the data to the view in format it is easily used in the ui: Mediator, Adapter
• Objects should/could implement INotifyPropertyChanged• Collections should/could implement INotifyCollectionChanged (or inherit ObservableCollection)
• CodeBehind may implement UI-logic associated with the view• ViewModel also may contain logic, but it should be view -independent
View(UI)
Binder(xaml)
ViewModel Model
CodeBehind(Page-class)
TheView
32UWA-DevelopmentCopyright Tieturi, 2016
MVVM - ViewModel and Model
THERE IS NOT JUST ONE STRAIGHT-FORWARD, ALWAYS TO USE SOLUTION
• At runtime the model is represented by collection of objects holding the data application is to maintain
• Some abstraction is needed on how the model is generated• Factories, Repositories• If data is stored into a database or available through web services DAO-pattern is very convenient
• The ViewModel shouldn’t create the model-objects but ask them from a “third-party”• And most likely we end up with having Data Transfer Objects (Value Objects) holding the data
• The ViewModel requests data from DAO-objects getting multiple DTOs • ViewModel then constructs (or operates as) mediator providing services that combine the
manipulation of otherwise unrelated DTOs
Storage
Persistent,Valid representationof model
ViewModelViewDAO
DAODAO
Abstractionof storage
DTODTO
DTOMediator
Runtime snapshot of the model
33UWA-DevelopmentCopyright Tieturi, 2016
Role of XAML
• The XAML describes the view• How should it look like
• The XAML also describes the databinding• What data is presented, how it is presented
• The XAML also describes event handling• OnClick etc, View-specific actions
• The XAML also describes commanding• Application wide and ViewModel -related actions
• The XAML can also describe some behaviors for the view• Animations are a good example
34UWA-DevelopmentCopyright Tieturi, 2016
Describing the UI• The XAML is used to describe the UI
• We need the root-element• And quite a few XML-namespaces declared
• And we describe the UI for the root element
• Quite a few of the controls available inherit ContentControl• Very complicated content can be designed for those
<Page x:Class="WpfTests.MainPage“ . . . ><Grid>
<Calendar HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" /><Button x:Name="button" Margin="25,183,0,0" Width="135">
<StackPanel Orientation="Horizontal"><Ellipse Width="20" Height="20" Fill="Red" /><TextBlock Text="Press me" />
</StackPanel></Button>
</Grid></Page>
MainWindow.xaml
35UWA-DevelopmentCopyright Tieturi, 2016
Events• Event handling is quite straight-forward
• Event is described in XAML, the handler is implemented to Page-class
• Just remember that events traverse the control-hierarchy, routed events• EventHandlers process the event, handled from top-most control downwards
<Button x:Name="button" . . . Click="button_Click" MouseMove="ButtonMouseMove" ><StackPanel Orientation="Horizontal"><Ellipse Width="20" Height="20" Fill="Red" /><TextBlock x:Name="buttonLabel" Text="PressMe" MouseMove="LabelMouseMove" />
</StackPanel></Button><Label x:Name="labelInfo" Content="Label" . . . /><Label x:Name="buttonInfo" Content="Label" . . . />
MainWindow.xaml
private void LabelMouseMove(object sender, MouseEventArgs e){
labelInfo.Content = "Move "+e.GetPosition(buttonLabel).X;e.Handled = true; // Now ButtonMouseMove will not be called
}
36UWA-DevelopmentCopyright Tieturi, 2016
Databinding• Databinding is one of the strongest features available to us
• Sadly sometimes ignored and misused
• We have• Binding target => Attribute of an element is described with binding• Binding source => Property of an object providing the data• Type conversion, in many cases automatic• Two-way, One-way, One-time
<TextBox x:Name="textBox1" Text="{Binding ElementName=slider1,Path=Value}" . . ./><Slider x:Name="slider1" Minimum="0" Maximum="20" . . ./>
<TextBox x:Name="textBox2"Text="{Binding ElementName=slider2,Path=Value,Mode=OneWay}" . . ./>
<Slider x:Name="slider2" Minimum="0" Maximum="20" . . ./>
<TextBox x:Name="textBox4"Text="{Binding ElementName=slider4,Path=Value,Mode=OneTime}" . . ./>
<Slider x:Name="slider4" Minimum="0" Maximum="20" Value="10" . . ./>
MainWindow.xaml (Different binding modes between UI-elements)
37UWA-DevelopmentCopyright Tieturi, 2016
Binding to properties of the page• Suppose the window class has
public string data {get; set;}
• You can set the DataContext for selected element to point to the Page-object• Constructor: this.DataSource=this;
• OR XAML (Page-attribute)DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}"
And binding becomes much simpler
<TextBox Text="{Binding Path=data}" . . ./>
38UWA-DevelopmentCopyright Tieturi, 2016
Setting DataContext to custom object
• Often you should create a new object-type to contain data for your ui (the ViewModel)• Instead of adding huge number of
properties to you Window-class
• Then you can set the DataContext-property to point to a new object of your class• On window or any other container
• Of course the object can also be instantiated and the DataContext be set in the constructor
class MyData{
public string data { get; set; }
public MyData(){
data = "Hello";}
}
<!-- local namespace --> <Page.DataContext>
<local:MyData /></Page.DataContext>
OR
public MainPage(){
DataContext=new MyData();InitializeComponent();
}
39UWA-DevelopmentCopyright Tieturi, 2016
Notifications
• To reflect changes of data to UI the model objects need to provide a PropertyChanged-event
class MyData : INotifyPropertyChanged{
public event PropertyChangedEventHandler PropertyChanged;
private string data = "";public string Data{
get { return data; }set{
data = value;if (PropertyChanged!=null)
PropertyChanged(this, new PropertyChangedEventArgs(“Data"));}
}}
MyData.cs
40UWA-DevelopmentCopyright Tieturi, 2016
Exercise - Calculator
• Create a new page “CalculatorPage”• Three TextBoxes: figure1, figure2, result• Button calculate
• Modify App.xaml.cs so that CalculatorPage is displayed at startup• Can you figure out how to build navigation between the initial HelloWorld-
page and CalculatorPage?
• Create calculate-click event-handler• Retrieve two figures and display the sum in result textbox
• Create Calculation-class holding Fig1, Fig2 and Result-properties• Implement the class in such a manner that you may use it as a ViewModel
for your calculator• Describe Calculation object as DataContext for the CalculatorPage• Use databinding in the xaml to the properties of Calculation object• When completed you should in fact be able to remove the original event
handler
Copyright Tieturi, 2016 UWA-Development 41
Navigation
Implementing navigation
• Designing the navigation is not an easy task• How to organize the data and the views for easy and natural access?
• How to accomplish the above in various devices
• We don’t (typically) use menus extensively• Context menus and other types of popup menus can be used
(Flyouts)
• Application may have some sort of navigation bar• Self-implemented with SplitView
• Pivot provides a tabbed ui• Than can also be scrolled
• Actual navigation through a Frame-object• (Window.Current.Content as Frame).Navigate(typeof(SomePage));
Copyright Tieturi, 2016 UWA-Development 43
Menu with flyout• Flyouts are popups that may contain anything
• Also menus
• Flyouts can be described • as separate resources• With flyout property for an element
Copyright Tieturi, 2016 UWA-Development 44
<Button Content=“Menu" . . .><Button.Flyout>
<MenuFlyout Placement="Bottom" ><MenuFlyoutItem Text="Hello" Click="HelloClicked" />
</MenuFlyout></Button.Flyout>
</Button>
Pivot
• Pivot has tabs which can display separate views
• Pivot element contains PivotItems for each view• Views may also be “scrolled” horizontally
• The view may be• Declared in the xaml for the page
• For example a grid within PivotItem
• Defined as a separate page• <local:PageName /> within PivotItem
Copyright Tieturi, 2016 UWA-Development 45
AppBar and CommandBar• Page may have Page.TopAppBar and Page.BottomAppBar• Content may be anything but typically AppBar or
CommandBar• Both contain a toggle button (three dots) to expand the bar contents
• Both may contain anything but typically• AppBarButton:s or AppBarToggleButton:s or AppBarSeparators
Copyright Tieturi, 2016 UWA-Development 46
<Page.TopAppBar><AppBar >
<TextBlock Text="Hello" /></AppBar>
</Page.TopAppBar><Page.BottomAppBar>
<CommandBar><CommandBar.Content>
<Grid/></CommandBar.Content><AppBarButton Icon="Accept" Label="appbarbutton"/><AppBarButton Icon="Cancel" Label="appbarbutton"/>
</CommandBar></Page.BottomAppBar>
Navigation panel with SplitView• Implementing the navigation panel might require some
work….
• This example opens the actual navigation options when the ToggleButton is checked
Copyright Tieturi, 2016 UWA-Development 47
<SplitView HorizontalAlignment="Left"Height="620" Margin="10,10,0,0"VerticalAlignment="Top"DisplayMode="CompactOverlay"IsPaneOpen="{Binding ElementName=MenuToggle, Path=IsChecked}"CompactPaneLength="50" OpenPaneLength="150" Width="350">
<SplitView.Pane><StackPanel Orientation="Horizontal" VerticalAlignment="Top">
<ToggleButton x:Name="MenuToggle"FontFamily="Segoe MDL2 Assets" Content=""Width="50" Height="50" Background="Transparent"/>
<StackPanel Orientation="Vertical"> <!-- Navigation options --><Button Content="First" /><Button Content="Second" />
</StackPanel></StackPanel>
</SplitView.Pane><local:Page1 VerticalAlignment="Top" /> <!-- This is the content -->
</SplitView>
Exercise
• Create a new project “NavTests” into your solution
• Add a button with a MenuFlyout to the MainPage
• From a MenuFlyout you should be able to navigate • To a page displaying a pivot with 2-3 tabs of content
• Experiment with different ways of displaying the content
• To a page displaying Top and Bottom AppBars• Again add some navigation to the Bottom AppBarButtons
• To a page displaying a SplitView• Just try to display some information in the Pane and Content of the
SplitView
• Closer you get to some kind of navigation pane the better
Copyright Tieturi, 2016 UWA-Development 48
Working with collectionsAnd item templates
Having a collection in the model
• Data binding can be done towards any IEnumerable• How ever the UI will not automatically know if items are added,
deleted or replaced in the collection
• INotifyCollectionChanged describes the event that should be fired when collection changes
• ObservableCollection is a convenience-class implementing INotyfyCollectionChanged• Provides List-like operations, but doesn’t implement IList• Can be instantiated from any IEnumerable• Easy to use, and misuse…
List<Person> personList =. . .;ObservableCollection<Person> col=new ObservableCollection<Person>(personList);
50UWA-DevelopmentCopyright Tieturi, 2016
How to use ObservableCollection
• Not all collections in the ViewModel need to be Observable, analyze your need
• Don’t replace the collection, modify the contents• Events are subscribed from a specific instance• OK, clearing and then adding huge number of items is not a
good idea either
• You can use LINQ against ObservableCollection but the returned collection is not Observable
• Don’t modify in background thread• Modifications cause events that should be processed in the
main thread
• So quite a few design considerations….
51UWA-DevelopmentCopyright Tieturi, 2016
Design considerations
Who is responsible of creating the observables?
• The view requires observables so the ViewModel should provide them• But not all objects need to be observable
• Depending on the data source the Model might readily provide observables or just plain value objects
• Should the model objects know when they are updated?
• Kind of makes us think that the ViewModel should capsulate the objects into observables, but
• This would lead into dublicate definition of value-objects
• The basic rule should be: Each tier should provide easy to use service interface to the next tier -> Simplify the work at upper levels and let them concentrate on the logic
Debate exists but the authors opinion is that DA-tier should provide observables to the ViewModel
• Perhaps even give alternatives: GetPerson, GetObservablePerson, GetPersonList, GetObservablePersonList
View(UI)
ViewModel(BL)
Model(DA)
52UWA-DevelopmentCopyright Tieturi, 2016
Item templates• Item-template describes how the contents of an object should be shown
• ItemTemplate holds or refers to DataTemplate describing the UI
<ListBoxItemsSource="{Binding Source={StaticResource personVM}, Path=Persons}“ . . .><ListBox.ItemTemplate>
<DataTemplate><StackPanel Orientation="Horizontal">
<Label Content="{Binding Path=Name}" /><Label Content="{Binding Path=Email}" />
</StackPanel></DataTemplate>
</ListBox.ItemTemplate></ListBox>
Sample with ListBox
53UWA-DevelopmentCopyright Tieturi, 2016
Exercise• Create a new project “PersonApp” into your solution• Add Person-class having few properties
• Id, Firstname,Lastname, Email…
• Add PersonDAO-class to your solution• Holds a static list of few persons• Methods: GetAll, Get(id), Save(Person), Create(Person), Delete(Person)• We will be using this later on to access data from different sources
• Create PersonViewModel-class• Add property Persons (pointing to the list)• Add property Current (pointing to the currently selected person)
• Design your ui to display a list of persons and a form having edit fields for the persons properties• On desktop these should appear side by side• On mobile list shoud be initial view, when person is selected the form should
appear
Copyright Tieturi, 2016 UWA-Development 54
Some XAML-techniques
Resources
• Resources are just objects reusable on several occasions
• Can be defined at• Application context
• Page context
• Element context
• Resources may be referenced• Statically: Resolved when XAML is parsed
• Dynamically: When resource is actually needed at runtime
• Should the Application declare a resource for the ViewModel-object?• Most often at least partially, but can be debated
56UWA-DevelopmentCopyright Tieturi, 2016
Resources in App.xaml• All the resources that are used between views should be described
in App.xaml• Unless of course a view-specific instance of the resource-type is needed
<Application x:Class="WpfTests.App"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:WpfTests"xmlns:sys="clr-namespace:System;assembly=mscorlib"StartupUri="MainWindow.xaml">
<Application.Resources><SolidColorBrush x:Key="blueBrush" Color="Blue"/><SolidColorBrush x:Key="whiteBrush" Color="White"/><sys:Double x:Key="myValue">100</sys:Double><local:PersonVM x:Key="personVM" /><local:DateToAgeConverter x:Key="ageConverter" />
</Application.Resources></Application>
App.xaml
57UWA-DevelopmentCopyright Tieturi, 2016
Styles• Styles are also resources• Again styles that are used across the views should be defined in
App.xaml• Both of the following are not applied
• When x:Key is set an element may use the style by binding the Style-property to “{StaticResource [x:Key]}”
• When x:Key is not set the style is used for all elements of TargetType
<Style TargetType="TextBlock"><Setter Property="FontSize" Value="24" />
</Style>
<Style x:Key="warningColor" TargetType="TextBlock"><Setter Property="Foreground" Value="Red" />
</Style>
Styles in resources
58UWA-DevelopmentCopyright Tieturi, 2016
Style inheritance• Problem on previous slide
• All labels have spefic font• Except those that choose the “warningBkr” -style
• Styles can inherit definitions of other styles
• BasedOn-attribute
<Style TargetType="TextBlock" x:Key="labelBase"><Setter Property="FontSize" Value="24" />
</Style>
<Style x:Key="warningColor" TargetType="TextBlock" BasedOn="{StaticResource labelBase}"><Setter Property="Foreground" Value="Red" />
</Style>
<Style TargetType="TextBlock" BasedOn="{StaticResource labelBase}"></Style>
Style inheritance
59UWA-DevelopmentCopyright Tieturi, 2016
Templates• Styles can also be used for describing templates for the controls
• How they should appear
<Style TargetType="Button"><Setter Property="Template">
<Setter.Value><ControlTemplate TargetType="Button">
<Grid><Ellipse Fill="Blue"/><ContentPresenter VerticalAlignment="Center"
HorizontalAlignment="Left"/></Grid>
</ControlTemplate></Setter.Value>
</Setter></Style>
All buttons should be displayd as blue ellipses
60UWA-DevelopmentCopyright Tieturi, 2016
Exercise
• Add some styles to App.xaml
• Use them in your Person-view
• Try implementing a template for your some of your controls
Copyright Tieturi, 2016 UWA-Development 61
Some other featuresCommanding, converters
Commanding
• Commanding offers more separation on object invoking the command and object executing the command• Several sources for single action
• UI understands if the command can be invoked
• Several components know how to invoke commands• Buttons
• Menus
• Actions that manipulate ViewModel should be declared as commands
• Actions that manipulate the View can be handled as events
63UWA-DevelopmentCopyright Tieturi, 2016
Command in ViewModel
• The ViewModel may contain properties that implement ICommand• Variations exist on how to implement
public ICommand SaveCommand { get; private set; }
public MyViewModel(){
SaveCommand = new SaveCommandHandler((obj) => {MessageBox.Show("Executing save");});}
private class SaveCommandHandler : ICommand{
private Action<object> action;
public SaveCommandHandler(Action<object> act){action = act;
}
public void Execute(object parameter){
action(parameter);}
. . .} <!-- DataContext must be MyViewModel -->
<Button Command="{Binding SaveCommand}” . . . />
64UWA-DevelopmentCopyright Tieturi, 2016
Converters
• Data binding nearly always passes through a converter• Integer property to a content string• Implicit or explicit
• Sadly the Visual Studio designer is not very comfortable with the converters
<TextBox x:Name="textBox1" HorizontalAlignment="Left" Margin="58,181,0,0“TextWrapping="Wrap" VerticalAlignment="Top"Text="{Binding Path=BirthDate, Converter={StaticResource AgeConverter}}"/>
Using converter with data binding
Binding target
Property
Binding source
Property
65UWA-DevelopmentCopyright Tieturi, 2016
Converters
Custom converter• Often the same result can be achieved by implementing a
calculated property to a ViewModel
• But if same conversion is needed in several ViewModel-objects then custom converter can be reused
class DateToAgeConverter : IValueConverter{
public object Convert(object value, Type targetType, object parameter, string language){
DateTime dt = (DateTime)value;return DateTime.Now.Year - dt.Year; // OK, not exact
}
public object ConvertBack(object value, Type targetType, object parameter, string lang){
return new DateTime(DateTime.Now.Year - int.Parse(value.ToString()), 1, 1);}
}
Converting birthdate to age (not a complete solution)
66UWA-DevelopmentCopyright Tieturi, 2016
Exercise
• Add “New” and “Create” buttons to the UI• New just clears the fields
• Create adds the Person to the list (data is read from the fields)
• Use Commanding
• Also try implementing• Save
• Delete
• Also experiment with a converter• For example the AgeConverter demonstrated previously
Copyright Tieturi, 2016 UWA-Development 67
Advanced XAML-techniques
Custom controls
• You can create custom controls• To define common view-independent logic to code behind
• To avoid repeating same constructs in the views XAML
• WPF-provides other, more lightweight, features also• Control templates
• Styles, triggers
• Item templates
• If you end up writing custom control you may• Inherit UserControl, new building block to UI
• Inherit Control, perhaps more precise customization
• Inherit FrameworkElement, direct rendering
69UWA-DevelopmentCopyright Tieturi, 2016
Dependency properties• Your custom control may publish traditional properties
• But you should use Dependency properties instead• Reduced memory footprint, if the value remains at default object
specific value is not stored• Value inheritance from parent elements• Automatic change notifications
public static readonly DependencyProperty FullNameProperty
= DependencyProperty.Register("Fullname",
typeof(string),typeof(PersonControl),
new PropertyMetadata("Fullname"));
public string Fullname
{
get { return (string)GetValue(FullNameProperty); }
set { SetValue(FullNameProperty, value); }
}
Declaring dependency property
70UWA-DevelopmentCopyright Tieturi, 2016
Exercise
• Create LabelEdit User control• Combines Label and TextBox
• Use Dependency Properties for properties• Label : Text shown in the Label-part
• Text: Text shown in TextBox
• Can you figure out how to generate Change-event when contents of the TextBox change.
Copyright Tieturi, 2016 UWA-Development 71
Animations• Resources or EventTriggers may contain Storyboard-elements
• Launched from code or automatically from an event
• StoryBoard contains DoubleAnimation -elements• Which property of which element is changed from what to what at specified timespan
• StoryBoard may also contain ObjectAnimationUsingKeyFrames-elements• Some other animation elements also exist
<Storyboard x:Key="Anim"><DoubleAnimation Storyboard.TargetName="mylabel"
Storyboard.TargetProperty="(Canvas.Top)"From="20" To="200"Duration="0:0:5" AutoReverse="True"/>
<DoubleAnimation Storyboard.TargetName="mylabel"Storyboard.TargetProperty="Opacity"From="0.0" To="1.0"Duration="0:0:3" />
<ObjectAnimationUsingKeyFramesStoryboard.TargetProperty="Opacity"Storyboard.TargetName="myellipse"><DiscreteObjectKeyFrame KeyTime="0:0:1" Value="0.0"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
Storyboard
72UWA-DevelopmentCopyright Tieturi, 2016
Visual states
• You may specify visual states to your page• Within visual state use StoryBoard to change layout
• Trigger visual state at the event handler• Window SizeChanged -event
• More on the subject• https://msdn.microsoft.com/fi-fi/windows/uwp/layout/layouts-
with-xaml
Copyright Tieturi, 2016 UWA-Development 73
Exercise
• Implement calculator• Three text boxes, sum of figures entered should be
automatically displayed
• Show a rectangle by each TextBox• When the value changes the width of the rectangle should be
the same as the value entered
• Declare animation so that the width changes to target value in two seconds
• Use Visual states so that when viewing landscape the text boxes appear side by side, when viewing portrait they appear on top of each other
Copyright Tieturi, 2016 UWA-Development 74
Multithreaded apps
Multithreaded programming• With threads an application (process) executes several
operations simultaneously• Several methdods in simultaneous execution• Threads require some resources (stack)
• Each application has the main thred• Execution point that is started from Main• Additional threads may be started
• Framework on top of operating system schedules executablethreads to give impression of simultaneous execution• In any given system there are most likely hundreds of executable
threads
• Threads most often ”hide” waiting a resource• Wait response from server• Wait for file operation to complete• etc
76UWA-DevelopmentCopyright Tieturi, 2016
Asynchronous programming
• Typical programming is synchronous• We make calls to methods and wait for the return value
• In asynchronous programming we start the operation (in background thread) without waiting for return value• The return value may often be queried later on either throuh
polling for it or with a callback-mechanism
• Many of the multithreaded solutions may beimplemented more simply and trustworthy withasynchronous models• A short-running algorithm whose return value we require but
don’t expect to be immediately available
77UWA-DevelopmentCopyright Tieturi, 2016
Parallel
• In parallel programming one operation is broken into pieces which are given to separete processors (cores) to execute• Overall execution time is reduced since several cores are used
to accomplish the final result
• The above given is perhaps the most precise descriptionof parallel programming model in .Net, though in theoryparallel execution may also be distributed betweendevices
78UWA-DevelopmentCopyright Tieturi, 2016
Thread safety
• Several threads may access common variable or resource
• Thread safety means that all threads should always seevalid state for the variable (or resource)• Don’t read half written information
• The state should’t change during a logical operation entity• The same as in database transactions
• Variables local to the thread function are always safe
• The parameter given to the thread function may beproblematic
• Use of common objects must be designed
• Use of static members must be designed
79UWA-DevelopmentCopyright Tieturi, 2016
Volatile
• In multiprocessor environments a value for a variable maybe located in the processor cache• A thread doesn’t see the value changed by a thread executing
under different processor
• Volatile –keyword may be used in variable declaration to ”force” the changes immediately available for all threads• Basic types and references
• If the volatile –keyword is not used for variabledeclaration you may use VolatileRead and VolatileWritefrom Thread-class to ensure use of the latest value for thevariable
80UWA-DevelopmentCopyright Tieturi, 2016
Interlocked
• Even the simplest operations are not thread safe:a=a+b;
• Other threads may change the values for operands in middleof calculation or perhaps just query the value for a-variablethat already should have been increased
• Interlocked class provides atomic methods for simpleoperations
Interlocked.Add(ref a,b);
• Increment
• Decrement
• Exchange
• CompareExchange
81UWA-DevelopmentCopyright Tieturi, 2016
Synchronization
• Through synchronization you affect the scheduler• Forbid simultaneous execution of code blocks• Wait for something to happen• Allow certain number of simultaneous threads
• Carefull design and implementation of synchronization is imperative in multithreaded applications
• The design of synchronization logic may be quitechallenging• Protect a resource from simultaneus use• The protection must be bullet-proof or extremely random
problems occur• At the same time dead-locks must be avoided
82UWA-DevelopmentCopyright Tieturi, 2016
Lock• Most simple and common method of synchronization
• Similar to critical section on some environments
• Any object common to several threads may operate as a lock• One thread owns the lock, other threads wait for it to be released• All threads need to ”see” the lock-object, be cafefull not to use the
same lock for different purposes
class LockIt
{
decimal value;
private Object myLock = new Object();
public void Decrease(decimal amount)
{
lock (myLock)
{
// One thread at a time may own myLock
if (amount < value) value -= amount;
}
}
}
83UWA-DevelopmentCopyright Tieturi, 2016
ReaderWriterLockSlim• ReaderWriterLock-object provides separate Reader- and Writer- locks
• Any number of ReaderLocks may be given
• When WriterLock is requested all other locks must be released
public class Coordinates
{
private int x, y;
ReaderWriterLock rwLock = new ReaderWriterLock();
public void GetCoordinates(out int x, out int y)
{
rwLock.EnterReadLock();
x = this.x;
y = this.y;
rwLock.ExitReadLock();
}
public void SetCoordinates(int x, int y)
{
rwLock.EnterWriteLock();
this.x = x;
this.y = y;
rwLock.ExitWriteLock();
}
}
84UWA-DevelopmentCopyright Tieturi, 2016
Synchronization objects
• Mutex• Mutex is very similar to lock, only one thread may own the mutex
• Request the lock with WaitOne, release with ReleaseMutex
• In most cases lock-object can be used in synchronization within oneapplication
• Mutex may be named => Interprocess synchronization• One process creates the mutex and gives the name• Other processes may open the same mutex
• AutoResetEvent, ManualResetEvent• Event signals that something has happened• Wait with WaitOne• Set and Reset change the state of the Event• The state of AutoResetEvent is automatically changed to non-signaled
when a thread is released from its wait
85UWA-DevelopmentCopyright Tieturi, 2016
Synchronization objects• Semaphore
• Resource counter, initial value given upon construction
• Successful WaitOne decreases the counter
• When counter is zero WaitOne waits until other threadsrelease the semaphore
• EventWaitHandle• The naming for ManualResetEvent and AutoResetEvent is
done through EventWaitHandle
// One application creates
EventWaitHandle eh = new EventWaitHandle(false, EventResetMode.ManualReset, @“MyEvent");
// Others open
EventWaitHandle ev = EventWaitHandle.OpenExisting(@“MyEvent");
86UWA-DevelopmentCopyright Tieturi, 2016
Task Parallel Library (TPL)
• Simplifies implementation of parallel and multithreadedapplications
• More performant applications
• ThreadPool is used in background (yes, we are stillimplementing theads)• More precise control of threading
• The lightweight synchronization objects and thread safecollections came with TPL
• Lazy classes for lazy initialization
• Dataflow-blocks for inter-thread communication
87UWA-DevelopmentCopyright Tieturi, 2016
Multithreaded programming in UWA
• All the features of multithreaded programming are available• ThreadPool
• Asynchronous delegates
• Tasks
• Async-methods
• With one complication• All UI manipulation must be done in the main thread
• We also have BackgroundWorker• Signals process to the main thread
• Easily attached to a progress bar for example
88UWA-DevelopmentCopyright Tieturi, 2016
Using BackgroundWorker
• Benefit of the background worker is that it can report progress in event driven manner
private void button_Click(object sender, RoutedEventArgs e){
BackgroundWorker bw = new BackgroundWorker();bw.WorkerReportsProgress = true;bw.ProgressChanged += (o,we) => {myProgress.Value = we.ProgressPercentage; };bw.DoWork += (o, xe) => {
for (int i = 0; i < 100; i++){
// Do something relevant herebw.ReportProgress(i);
}};
bw.RunWorkerAsync();}
Background worker (not implemented in most beautiful manner)
89UWA-DevelopmentCopyright Tieturi, 2016
Using ThreadPool• ThreadPool may be used to execute a method in background• But also for scheduled operations
• ThreadPoolTimer.CreateTimer, CreatePeriodicTimer
• Dispatcher must be used to transfer UI-manipulation to the main thread
Copyright Tieturi, 2016 UWA-Development 90
private void button2_Click(object sender, RoutedEventArgs e){
ThreadPool.RunAsync(x =>{
for(int i = 0; i < 100; i++){
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => textBox1.Text = i.ToString());
}});
}
TreadPool, Dispatcher
Task-class• Tasks may be used to implement threads in
”traditional” manner
void TaskMethod()
{
Debug.WriteLine(“Running task");
}
void StartTasks()
{
Task t = new Task(TaskMethod);
t.Start();
Task.Run(() => TaskMethod());
Parallel.Invoke(TaskMethod);
}
91UWA-DevelopmentCopyright Tieturi, 2016
Parameters and return values• A task may have a return value
• Querying the Result-property blocks until the return valueis available
• Lambdas may be used for passing parameterstatic double TaskMethod(double a, double b)
{
// Do some time consuming calculations and finally
return a + b;
}
static public void Main(string[] args)
{
Task<double> t = Task.Run(() => TaskMethod(5,4));
Console.WriteLine(“In a second " + t.Result);
}
92UWA-DevelopmentCopyright Tieturi, 2016
TaskFactory• TaskFactory-class provides flexibility and versatile
operations for manipulating tasks
• Most recommended when tasks are widely used
• Can be instantiated but more often a factory is used
static public void Main(string[] args)
{
// Previous task-method without parameters
Task.Factory.StartNew(TaskMethod);
// Method with parameters and return value
Task<double> t=Task.Factory.StartNew<double>(() => TaskMethod2(6, 7));
Console.WriteLine(“Result " + t.Result);
}
93UWA-DevelopmentCopyright Tieturi, 2016
Using async-methods
• Surprisingly async-methods are great to use in UWA-applications
private async void button_Click(object sender, RoutedEventArgs e){
label.Content = "Starting async";string s = await DoTheJob();label.Content = s;
}
private async Task<string> DoTheJob(){
Task<string> t = Task.Run(() => ActualJob(2000));string ret = await t;return ret;
}
private string ActualJob(int sleep){
// Doing the actual workreturn "Done with async";
}
Async event handler and async methods
94UWA-DevelopmentCopyright Tieturi, 2016
Exercise
• Implement PI-calculation to your calculator
• Background thread calculates PI
• The number of iterarions and current estimate should be displayed in UI• Which method would you use for the thread?
• Alternative: Ask the user for number of iterations and only display the result after all iterations are done• Which method would you use now?
Copyright Tieturi, 2016 UWA-Development 95
User dataUser directories
Operating with files
Contacts and Calendar
FileAccess• File-access in UWA is built using asynchronous methods
• Application working directory is accessible through Windows.Storage.ApplicationData.LocalFolder• And also TemporaryFolder, SharedLocalFolder, LocalSettings…
Copyright Tieturi, 2016 UWA-Development 97
async private void button_Click(object sender, RoutedEventArgs e){
StorageFolder fld=Windows.Storage.ApplicationData.Current.LocalFolder;StorageFile fd = await fld.CreateFileAsync("data.txt");await FileIO.WriteTextAsync(fd, "Hello world");
}
Create a text-file into LocalFolder
User directories• Application must declare capabilities to access various user folders
• Package.appxmanifest, graphical ui, Capabilities-tab
• Folders available are found from the members of KnownFolders• DocumentsLibrary• PicturesLibrary• MusicLibrary• VideosLibrary• And also AppCaptures, PlayLists, RecordedCalls etc
Copyright Tieturi, 2016 UWA-Development 98
async private void button_Click(object sender, RoutedEventArgs e){
StorageFolder fld=KnownFolders.PicturesLibrary;IReadOnlyList<StorageFile> files=await fld.GetFilesAsync();foreach (StorageFile f in files){
listBox.Items.Add(f.Name);}
}
List images from the PicturesLibrary in a listbox
Serialization into the stream
• A stream may also be opened into a StorageFile
• Serialization may be done into the stream• Binary serialization [Serializable] -classes
• XML-serialization
• Json-serialization
Copyright Tieturi, 2016 UWA-Development 99
async private void button_Click(object sender, RoutedEventArgs e){
StorageFolder fld = Windows.Storage.ApplicationData.Current.LocalFolder;StorageFile fd = await fld.CreateFileAsync("data.xml",
CreationCollisionOption.ReplaceExisting);Stream s = await fd.OpenStreamForWriteAsync();XmlSerializer ser = new XmlSerializer(typeof(MyData));ser.Serialize(s, new MyData());s.Flush();
}
Serialize data in XML-format
JSON Serialization, Deserialization
Copyright Tieturi, 2016 UWA-Development 100
async private void jsonSerialize_Click(object sender, RoutedEventArgs e){
StorageFolder fld = Windows.Storage.ApplicationData.Current.LocalFolder;StorageFile fd = await fld.CreateFileAsync("data.json",
CreationCollisionOption.ReplaceExisting);Stream s = await fd.OpenStreamForWriteAsync();DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(MyData));ser.WriteObject(s, new MyData());s.Flush();s.Dispose();
}
async private void deserializeBoth_Click(object sender, RoutedEventArgs e){
StorageFolder fld = Windows.Storage.ApplicationData.Current.LocalFolder;StorageFile fd = await fld.GetFileAsync("data.json");Stream s = await fd.OpenStreamForReadAsync();DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(MyData));MyData data=ser.ReadObject(s) as MyData;listBox.Items.Add(data.data);s.Dispose();
StorageFile fd2 = await fld.GetFileAsync("data.xml");Stream s2 = await fd2.OpenStreamForReadAsync();XmlSerializer ser2 = new XmlSerializer(typeof(MyData));MyData data2 = ser2.Deserialize(s2) as MyData;listBox.Items.Add(data2.data);s2.Dispose();
}
Using picker• FileOpenPicker may be used to allow the user select a file
Copyright Tieturi, 2016 UWA-Development 101
async private void selectFile_Click(object sender, RoutedEventArgs e){
var picker = new Windows.Storage.Pickers.FileOpenPicker();picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List;picker.SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;picker.FileTypeFilter.Add(".xml");picker.FileTypeFilter.Add(".json");StorageFile file = await picker.PickSingleFileAsync();if (file != null){
// Access file read/write}else{
// Cancelled}
}
Launching for selected file• You may specify file associations in the Package.appxmanifest
• Declarations - File association• Must specify Display name and name (descriptive “category”)• Icon would be nice• Content type for example application/json• File type (extension) for example .mydata
Copyright Tieturi, 2016 UWA-Development 102
protected override void OnFileActivated(FileActivatedEventArgs args){
StorageFile f=args.Files[0] as StorageFile;Debug.WriteLine(f.Name);// Most likely create a new frame to process data read from the file// If reusing existing make sure to clear previous data
}
Contacts• ContactPicker may be used to allow user select contacts
• Contacts-capability must be enabled in Package.appxmanifestfor full access to contacts
Copyright Tieturi, 2016 UWA-Development 103
async private void Contacts_Click(object sender, RoutedEventArgs e){
ContactPicker cp = new ContactPicker();cp.SelectionMode = ContactSelectionMode.Fields;cp.DesiredFieldsWithContactFieldType.Add(ContactFieldType.Email);Contact c = await cp.PickContactAsync();Debug.WriteLine(c.Emails.Count+","+c.FirstName+" "+c.LastName);
ContactStore cm=await ContactManager.RequestStoreAsync();var cls=await cm.FindContactListsAsync();foreach(var l in cls){
Debug.WriteLine(l.Id);var b=await l.GetContactReader().ReadBatchAsync();foreach(var cc in b.Contacts){
Debug.WriteLine(cc.FullName);}
}}
Exercise
• Add an option to save your ViewModel into a json file with extension .pson
• Also add an option to open existing .pson -file
• Add a file association to launch your application when pson-file is selected from file manager• Implement launch to the possibly existing frame
• Save a file to your ApplicationData-folder containing the name of the last pson-file opened
• When application is launched reread the previous pson-file
• Add an option to export all contacts to a pson-file
Copyright Tieturi, 2016 UWA-Development 104
Remote dataWeb services
SOAP and XML
REST and JSON
Web services
Copyright Tieturi, 2016 UWA-Development 106
SOAP• Kind of a function calls over network,
remote procedure call technology
• XML-document describing the method to be executed is passed to the server
• Server executes the requested method
• Response is again formatted into XML
• WSDL (xml) describes the interface available
• Well suited for application integration (EAI or B2B)
REST• Data manipulation over internet
• Uses four methods of HTTP-protocol
• GET to query data
• PUT to modify data
• POST to create data
• DELETE obviously to….
• The URL identififies the data item or entity to be manipulated
• The format in which data is presented can be choosen freely (JSON or XML)
• Good choice for web clients (JavaScript) and unknown client types
Services to other applications over internet with two flawors:
SOAP• Soap client for UWA-application is implemented in similar manner as traditional
.NET-application• Right-click References on Solution Explorer and Add new service reference• You need access to the wsdl of the web service
• Only asynchronous calls are available
• Testing in the emulator is not very straight forward• Firewall may block the calls• IIS express doesn’t serve all IP-addresses, add binding to
[SolutionFolder]\.vs\config\applicationhost.config, for example:<binding protocol="http" bindingInformation="*:8000:*" />• Make the call to the ip seen by the emulator
Copyright Tieturi, 2016 UWA-Development 107
EndpointAddress ep = new EndpointAddress("http://172.16.80.1:8000/PersonsService.asmx");
ServiceReference1.PersonsServiceSoapClient.EndpointConfiguration epc;epc = new ServiceReference1.PersonsServiceSoapClient.EndpointConfiguration();
ServiceReference1.PersonsServiceSoapClient c = new ServiceReference1.PersonsServiceSoapClient(epc,ep);
var p = await c.GetPersonAsync();listBox.Items.Add(p.Body.GetPersonResult.FirstName);
REST• If your restful services provide Swagger-metadata it is rather easy again to
create skeletons to make calls• Again in asynchronous manner
• If metadata is not available you will need to revert to HttpClient
Copyright Tieturi, 2016 UWA-Development 108
HttpClient httpClient = new HttpClient();Uri requestUri = new Uri("http://172.16.80.1:9000/api/books");HttpResponseMessage httpResponse = new HttpResponseMessage();httpResponse = await httpClient.GetAsync(requestUri);httpResponse.EnsureSuccessStatusCode();string responseString = await httpResponse.Content.ReadAsStringAsync();Debug.WriteLine(responseString);
var ser=new DataContractJsonSerializer(typeof(Book[]));byte[] ba = Encoding.UTF8.GetBytes(responseString);MemoryStream ms = new MemoryStream(ba);Book[] data=ser.ReadObject(ms) as Book[];foreach(Book o in data){
Debug.WriteLine(o.title);}
Exercise
• Follow your instructors lead to create a web application that publishes a SOAP-based web service• GetPersons returning a list of Person-objects
• Modify your UWA-application to populate the ViewModelfrom the web service call
• Add also a Web API -controller to your web application that also serves List of Person-objects
• Modify UWA-application to populate the ViewModel from the REST-call• Use HttpClient
Copyright Tieturi, 2016 UWA-Development 109
Accessing the deviceDevice capabilities
Sensors
Camera
Location and Maps
Device capabilities• Capabilities must be enabled in Package.appxmanifest
• If targeting multiple devices you must also check if the required API-is present
Copyright Tieturi, 2016 UWA-Development 111
bool isHardwareButtonsAPIPresent =
Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"); if (isHardwareButtonsAPIPresent) {
Windows.Phone.UI.Input.HardwareButtons.CameraPressed += HardwareButtons_CameraPressed; }
Sensors
• Sensors that are available include• Accelerometer (movement, linear)
• Orientation (portrait, landscape)
• Compass (current heading)
• Gyrometer (movement, angular or rotation)
• Inclinometer (pitchs, roll, yaw)
• Light
• All sensors are used in similar manner• Query the sensor with GetDefault-method
• Register eventhandler to catch sensor values
Copyright Tieturi, 2016 UWA-Development 112
Orientation• OriatationSensor
• Access to full matrix of orientation
• Simple orientation sensor• Gain easy access to rotation (“Rotated270DegreesCounterclockwise”)
Copyright Tieturi, 2016 UWA-Development 113
OrientationSensor orientationSensor;SimpleOrientationSensor simpleOrientation;
public MainPage(){
this.InitializeComponent();orientationSensor = OrientationSensor.GetDefault();simpleOrientation = SimpleOrientationSensor.GetDefault();if (orientationSensor!=null) orientationSensor.ReadingChanged +=
new TypedEventHandler<OrientationSensor, OrientationSensorReadingChangedEventArgs>(ReadingChanged);if (simpleOrientation!=null) simpleOrientation.OrientationChanged +=
new TypedEventHandler<SimpleOrientationSensor, SimpleOrientationSensorOrientationChangedEventArgs> (OrientChanged);
}
private void ReadingChanged(OrientationSensor sender, OrientationSensorReadingChangedEventArgs args){
Debug.WriteLine("Reading changed " + DateTime.Now.Ticks+", "+args.Reading.RotationMatrix.M11);}
private void OrientChanged(SimpleOrientationSensor s, SimpleOrientationSensorOrientationChangedEventArgs args){
Debug.WriteLine("Simplechanged " + DateTime.Now.Ticks + ", " + args.Orientation);}
Camera• Capturing images and video from camera is very straight-
forward
• Just launch CaptureUI and it returns you a file
• The file is stored in appdata-folder so most likely you will need to move it somewhere else
Copyright Tieturi, 2016 UWA-Development 114
async private void button_Click(object sender, RoutedEventArgs e){
CameraCaptureUI captureUI = new CameraCaptureUI();captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;captureUI.PhotoSettings.CroppedSizeInPixels = new Size(200, 200);StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);if (photo != null)
Debug.WriteLine(photo.Path);}
Location and maps• To access maps you must create an authentication key at
https://www.bingmapsportal.com/• Use authentication key for MapControl and MapService
• Location capability must be enabled in Package.appxmanifest• And still access to location must be separately asked from user
Copyright Tieturi, 2016 UWA-Development 115
async private void button2_Click(object sender, RoutedEventArgs e){
GeolocationAccessStatus accessStatus = await Geolocator.RequestAccessAsync();if (accessStatus == GeolocationAccessStatus.Allowed){
Geolocator geolocator = new Geolocator();Geoposition pos = await geolocator.GetGeopositionAsync();MapIcon mapIcon1 = new MapIcon();mapIcon1.Location = pos.Coordinate.Point;mapIcon1.NormalizedAnchorPoint = new Point(0.5, 1.0);mapIcon1.Title = "Now here";mapIcon1.ZIndex = 0;mapCtrl.MapElements.Add(mapIcon1);
}}
Get current location, place icon
MapControl
• When you have a MapControl on your UI• You may center on selected location
• Zoom
• Show landmarks
• Etc
Copyright Tieturi, 2016 UWA-Development 116
private void button1_Click(object sender, RoutedEventArgs e){
BasicGeoposition veikkola = new BasicGeoposition() {Latitude = 60.2699809,Longitude = 24.4373972
};mapCtrl.Center = new Geopoint(veikkola);mapCtrl.ZoomLevel = 12;mapCtrl.LandmarksVisible = true;
}
Show specific location
Exercise
• Experiment with the sensors of your choise
• Try to store a “profile photo” to your Pictures-folder
• Add a MapControl to your UI• Show the map of selected location (Lat,Long)
• Add a MapIcon to the Map
Copyright Tieturi, 2016 UWA-Development 117
SecuritySecurity Overview
Security with UWA
• The platform provides quite a few features for security• From users point of view: does application have access to sensitive
data of other applications• Authentication: quite a few possibilities• Secure store for credentials• Encryption
• Careful evaluation of security requirements is needed• Confidentiality
• What data needs to be protected and how
• Integrity• How to ensure data validity in all cases
• Availability• Is remote data needed and how well it is accessed• But also devices supported, performance and usability on different devices
Copyright Tieturi, 2016 UWA-Development 119
Authentication• Authentication on desktop joined in domain is automatic
• But you might still need to handle association to specific accounts
• Credential Locker• Windows.Security.Credentials.PasswordVault• Secure storage for credentials• After successful login credentials to the service don’t need to be re-
entered
• Microsoft Passport + Windows Hello• Windows Hello is a biometric authentication mechanism built into
Windows 10• Microsoft Passport links the authentication to either Azure Active
Directory Account or Microsoft Account associated with user in Windows Settings
• Smart card -based authentication• Certificate based authentication
Copyright Tieturi, 2016 UWA-Development 120
Cryptography
• To protect data you’ll need• DataProtectionProvider-class
• CryptographicBuffer
• Protection can be done based on multiple factors• AD security principal (User or Group)
• X.509 Certificate (Certificate owner)
• Symmetric key
• Credentials entered
Copyright Tieturi, 2016 UWA-Development 121
That’s itOk, quite a few topics introduced
After analyzing the requirements for your application you most likely need to study topics related to your application
more deeply
Any final questions?