best practices for windows 8 & phone app performance
TRANSCRIPT
Windows 8 and phone app
performance
Virtualization
Virtualization is the creation of a virtual (rather than actual) version of something.
Virtual Machine.
Logical Drives.
“Existing in essence or effect though not in actual fact.”
Data Virtualization
Data virtualization is a methodology that takes a layered approach to dealing with huge volumes of data from disparate sources.
The amount of memory the rendered items in the collection use and the space it takes to store the data displayed.
Use of Lazy Loading…
Lazy Loading
Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed
In Easy Way “Data is only loaded when required”
Like a lazy person who move only when he needed.
Why we need lazy loading
Below are the requirement of lazy loading:
Minimize start up time of the application which improve performance of app.
Application consumes less memory because of on-demand loading which improve efficiency of app.
Unnecessary database command execution is avoided.
Only a disadvantage is that code will becomes complicated. As we need to do checks if the loading is needed or not, there is a slight decrease in performance.
“But the advantages are far more than the disadvantages”
Have a look.. Use :
public Lazy<ObservableCollection<Songs>> _Songlist = null;
_Songlist = new Lazy<ObservableCollection<Songs>>(() => this.LoadData());
this.grd_view.ItemsSource = _Songlist.Value;
public ObservableCollection<Songs> LoadData()
{
if (SongList == null)
songList = new ObservableCollection<Songs>();
for (int i = 1; i < 100000; i++)
{
SongList.Add(new Songs() { IndexValue = i, NameValue = i.ToString(), Color = "Assets/Square71x71Logo.scale-240.png" });
}
return SongList;
}
What is Eager Loading
Eager Loading is opposite of Lazy Loading.
It loads the related data in scalar and navigation properties along with query result at first shot.
In Easy Way “Strongly wanting to do or have something”
Eager Loading – “do all the work in advance”
Have a look..
using (var context = new BloggingContext())
{
// Load all blogs and related posts
var blogs1 = context.Blogs
.Include(b => b.Posts)
.ToList();
// Load one blogs and its related posts
var blog1 = context.Blogs
.Where(b => b.Name == "ADO.NET Blog")
.Include(b => b.Posts)
.FirstOrDefault();
// Load all blogs and related posts
// using a string to specify the relationship
var blogs2 = context.Blogs
.Include("Posts")
.ToList();
// Load one blog and its related posts
// using a string to specify the relationship
var blog2 = context.Blogs
.Where(b => b.Name == "ADO.NET Blog")
.Include("Posts")
.FirstOrDefault();
}
Incremental loading
“A small adjustment made toward an end result”
Incremental loading techniques in most cases do not significantly impact the total loading time for all the items compared to simple data binding
Incremental loading is used when moving data from one repository (Database) to another.
Non-incremental loading would be when the destination has the entire data from the source pushed to it.
How to implement.. Content container Changing. ( ShowsScrollingPlaceholders property to
true.)
Blend Behavior Changing.
public interface ISupportIncrementalLoading
The ISupportIncrementalLoading interface has these methods. It also inherits methods from the Object class.
LoadMoreItemsAsync()
The ISupportIncrementalLoading interface has these properties.
HasMoreItems (Read only)
Have a lookhttps://msdn.microsoft.com/library/windows/apps/Hh701916https://msdn.microsoft.com/en-in/library/windows/Apps/dn535964.aspx
Using the IncrementalUpdateBehavior to add incremental loading
Must add a reference to the Behaviors SDK (XAML).
Must add reference in xaml page.
xmlns:Interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:Core="using:Microsoft.Xaml.Interactions.Core“
Add phases for Incremental loading. <Interactivity:Interaction.Behaviors>
<Core:IncrementalUpdateBehavior Phase="2"/>
</Interactivity:Interaction.Behaviors>
Continue…
<GridView.ItemTemplate> <DataTemplate> <Grid HorizontalAlignment="Left" Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <StackPanel Orientation="Horizontal" Margin="10,10,0,0"> <Grid> <Image Source="ms-appx:///Assets/placeHolderImage.png" Height="100" Width="60" VerticalAlignment="Center" Margin="0,0,10,0"/> <Image Source="{Binding ImageUri}" Height="100" Width="60" VerticalAlignment="Center" Margin="0,0,10,0"> <Interactivity:Interaction.Behaviors> <Core:IncrementalUpdateBehavior Phase="3"/> </Interactivity:Interaction.Behaviors> </Image> </Grid> <StackPanel Margin="0,0,0,0" Orientation="Vertical"> <TextBlock Text="{Binding Title}" TextWrapping="Wrap" Foreground="{StaticResource ApplicationForegroundThemeBrush}" FontSize="14.667" FontWeight="Light" Width="100" VerticalAlignment="Center" HorizontalAlignment="Left" FontFamily="Segoe UI"> <Interactivity:Interaction.Behaviors> <Core:IncrementalUpdateBehavior Phase="1"/> </Interactivity:Interaction.Behaviors> </TextBlock> <TextBlock Text="{Binding Category}" TextWrapping="Wrap" Foreground="{StaticResource ApplicationForegroundThemeBrush}" FontSize="14.667" FontWeight="Light" Width="100" MaxHeight="20" VerticalAlignment="Center" HorizontalAlignment="Left"> <Interactivity:Interaction.Behaviors> <Core:IncrementalUpdateBehavior Phase="2"/> </Interactivity:Interaction.Behaviors> </TextBlock> <HyperlinkButton Content="{Binding Link}" NavigateUri="{Binding Link}"> <Interactivity:Interaction.Behaviors> <Core:IncrementalUpdateBehavior Phase="2"/> </Interactivity:Interaction.Behaviors> </HyperlinkButton> </StackPanel> </StackPanel> </Grid> </DataTemplate></GridView.ItemTemplate>
Best Practices for window 8 and phone performance.
Best Practices for window 8 and phone performance.
Common experience is app startup performance.
Time of less than one second to start to be excellent, less than 5 seconds to be good, and greater than 5 seconds to be poor.
Use asynchronous APIs
An asynchronous API ensures that your active execution thread never blocks for a significant amount of time
Offload work to background threads
Explicitly say when you want to run your app code on a background thread. In C#C# and Visual Basic you can accomplish this by passing code to Task.Run.
Continue..
Best Practices for window 8 and phone performance.
Example:public class Example{ // ... private async void NextMove_Click(object sender, RoutedEventArgs e) { await Task.Run(() => ComputeNextMove()); // Update the UI with results }
private async Task ComputeNextMove() { // ... } // ...}
Best Practices for window 8 and phone performance.
Make animations smooth.
Don't animate a WebView or MediaElement.
Web content within a WebView control is not directly rendered by the XAML framework and it requires extra work to be composed with the rest of the scene. This extra work introduce synchronization issues.
Try to use the animation library.
Windows.UI.Xaml.Media.Animation
Best Practices for window 8 and phone performance.
Minimize suspend/resume time (XAML)
Windows 8 process lifetime system can suspend or terminate an app for a variety of reasons.
If programmer designed this process to quickly return an app to the state user won’t be aware that the app ever stopped running
Best Practices for window 8 and phone performance.
Help to minimize suspend/resume time Avoid unnecessary termination.
App can be suspended when user moves it to the background.
when the system enters a low power state.
At raises of suspending event and we have up to 5 seconds to save its data. If the suspending event handler doesn't complete within 5 seconds, the system assumes the app has stopped responding and terminates it.
Continue..
Best Practices for window 8 and phone performance.
Serialize only when necessary
Many apps serialize all their data on suspension. (try to avoid).
Should use the LocalSettings store instead of serializing the data in case of small amount of setting.
Choices of serialization technology for .NET
System.Xml.Serialization.XmlSerializer,
XmlSerializer has the lowest serialization and deserialization times.
System.Runtime.Serialization.DataContractSerializer,
SuspensionManager class that uses DataContractSerializer to save and restore session and navigation state.
Best Practices for window 8 and phone performance.
Release resources
Certain objects, such as files and devices, occupy a large amount of memory.
During suspension, an app release handles to these objects and recreate them when needed.
Load, store, and display large sets of data efficiently
Two key performance factors that you pay attention.
Use UI virtualization to create only visible items.
Amount of time spent on the UI thread creating items.
Data virtualization
The amount of memory the rendered items in the collection use and the space it takes to store the data displayed.
It chances a suspended app gets terminated rises with the amount of memory used by the active app.
“High memory use degrades the experience for all apps on the system”
Implement UI virtualization
Doesn't perform UI virtualization
<ListView> <ListView.ItemsPanel> <ItemsPanelTemplate> <StackPanel/> </ItemsPanelTemplate> </ListView.ItemsPanel></ListView>
Support UI virtualization.
<ListView> <ListView.ItemsPanel> <ItemsPanelTemplate> <ItemsStackPanel/> </ItemsPanelTemplate> </ListView.ItemsPanel></ListView>
panel is replaced with a panel that supports
UI virtualization.
Use ItemsStackPanel or ItemsWrapGrid to get item virtualization. The framework automatically does this for all apps that use the default ItemsPanel.
Implement UI virtualization
ListView doesn't perform UI virtualization
<ScrollViewer VerticalScrollMode="Enabled"> <ListView/></ScrollViewer>
ListView performs UI virtualization
<ScrollViewer VerticalScrollMode="Enabled"> <ListView Height="400" /></ScrollViewer>
ScrollViewer gives the ListView as much
vertical space as it needs during layout,
the ListView uses only 400 pixels
Optimize media resources (Video)
Media files are some of the most common and expensive resources apps typically use. you must remember to release the handle to media as soon as the app is finished using it.
Ensure to close if used any.
RandomAccessStream.
IInputStream.
Video
Display full screen video playback when possible.
Display deactivation and conserving power.
DisplayRequest.RequestActive.
DisplayRequest.RequestRelease.
Optimize media resources (Video)
Here are some situations when you should release the display request:
Video playback is paused, for example by user action, buffering, or adjustment due to limited bandwidth.
Playback stops. For example, the video is done playing or the presentation is over.
A playback error has occurred. For example, network connectivity issues or a corrupted file.
Optimize media resources (Images)
Scale images to the appropriate size Images are now captured at very high resolutions. It use more CPU memory to decoding the image data and more memory after
it’s loaded from disk. No use of decoding and saving a high resolution image in memory if it will
never be displayed at its native size.
<Image Source="ms-appx:///Assets/highresCar.jpg" Width="300" Height="200"/> <!-- BAD CODE DO NOT USE.-->
<Image> <Image.Source> <BitmapImage UriSource="ms-appx:///Assets/highresCar.jpg" DecodePixelWidth="300" DecodePixelHeight="200"/> <!– USE DECODED PIXELS--> </Image.Source></Image>
Optimize media resources (Images)
Use GetThumbnailAsync for thumbnails.
FileOpenPicker picker = new FileOpenPicker();picker.FileTypeFilter.Add(".bmp");picker.FileTypeFilter.Add(".jpg");picker.FileTypeFilter.Add(".jpeg");picker.FileTypeFilter.Add(".png");picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
StorageFile file = await picker.PickSingleFileAsync();
StorageItemThumbnail fileThumbnail = await file.GetThumbnailAsync(ThumbnailMode.SingleItem, 64);
BitmapImage bmp = new BitmapImage();bmp.SetSource(fileThumbnail);
Image img = new Image();img.Source = bmp;
What’s New in VS 2013 for window store & Phone app.
Visual Studio languages Team Foundation and Application Lifecycle Management
.NET Framework 4.5.1 ASP.NET 4.5.1
What’s New in VS 2013 for window store & Phone app.
In Visual studio 2013 with update 2, portable class library supports.
You can use Windows Runtime APIs in portable libraries that target Windows 8.1, Windows Phone 8.1, and Windows Phone Silverlight 8.1.
You can include XAML (Windows.UI.XAML types) in portable libraries when you target Windows 8.1 or Windows Phone 8.1. The following XAML templates are supported: Blank Page, Resource Dictionary, Templated Control, and User Control.
You can create a portable Windows Runtime component ( .winmd file) for use in Store apps that target Windows 8.1 and Windows Phone 8.1.
You can retarget a Windows Store or Windows Phone Store class library like a Portable Class Library.
What’s New in VS 2013 for window store & Phone app.
Azure Mobile Services Connect Windows Store apps to Azure Mobile Services.
Use Azure Mobile Services and Windows Push Notification services to add push notifications to your app.
Create and view Azure Mobile Services by using the JavaScript backend or the .NET backend based on Web API.
Update table scripts and custom APIs for Azure Mobile Services.
Window store apps
In Visual studio 2013 you can create.
Create universal apps .
Windows and Windows Phone 8.1 at the same time, and share code, user controls, styles, strings and other assets between them.
Create a hub-style app.
Create a Windows Store app that displays content in a horizontally panning view and engages users by providing a variety of ways to access content
Generate app bundles.
It reduce the size of the app that users download.
New controls and control updates
New Controls
AppBar controls
AppBarButton, AppBarToggleButton, and AppBarSeparator
App bar buttons
App bar buttons differ from standard buttons in several ways: Their default appearance is a circle instead of a rectangle.
You use the Label and Icon properties to set the content instead of the Content property. The Content property is ignored.
The button's IsCompact property controls its size.
Have a look:
<AppBarButton Label="BitmapIcon" Click="AppBarButton_Click">
<AppBarButton.Icon>
<BitmapIcon UriSource="ms-appx:///Assets/globe.png"/>
</AppBarButton.Icon>
</AppBarButton>
DatePicker
Windows 8.1 introduces a new control for XAML that lets a user set a localized date in your app: the DatePicker control
Modified as you need with
little effort
<DatePicker DayFormat="{}{day.integer} ({dayofweek.abbreviated})" YearVisible="False"/>
Introduce Flyout for button
A Flyout displays lightweight UI (called a flyout) that either is informational or requires user interaction.
Display Information on
button
<Button Content="Empty cart"> <Button.Flyout> <Flyout> <StackPanel> <TextBlock Style="{StaticResource BasicTextStyle}">All items will be removed. Do you want to continue?</TextBlock> <Button Click="DeleteConfirmation_Click">Yes, empty my cart</Button> </StackPanel> </Flyout> </Button.Flyout></Button>
Hub style<Hub Header="News">
<HubSection MinWidth="600" Header="Latest">
<DataTemplate>
<Grid>
<TextBlock Text="The most recent news will be here."
Style="{ThemeResource BodyTextBlockStyle}" />
</Grid>
</DataTemplate>
</HubSection>
<HubSection Header="Sports" IsHeaderInteractive="True"
Background="#444444" MinWidth="250">
<DataTemplate>
<StackPanel>
<TextBlock Text="Sports news goes here."
Style="{ThemeResource BodyTextBlockStyle}" />
<TextBlock Text="Click the header to go to the Sports page."
Style="{ThemeResource BodyTextBlockStyle}" />
</StackPanel>
</DataTemplate>
</HubSection>
</Hub>
Introduce Hyperlink element
<RichTextBlock Width="200" Style="{StaticResource BasicRichTextStyle}"> <Paragraph>Hyperlinks let you give readers a visual hint that certain text links to other content. <Hyperlink Navigate Uri="http://dev.windows.com">Read more on the Windows Dev Center</Hyperlink> ... Text in a Hyperlink element is treated like the rest of the text and participates in line breaking. </Paragraph></RichTextBlock>
MenuFlyout
A new control for XAML that lets you temporarily show a list of commands
MenuFlyoutItem—Performing an immediate action.
ToggleMenuFlyoutItem—Switching an option on or off.
MenuFlyoutSeparator—Visually separating menu items.
<Button Content="Options"> <Button.Flyout> <MenuFlyout> <MenuFlyoutItem Text="Reset" Click="Reset_Click"/> <MenuFlyoutSeparator/> <ToggleMenuFlyoutItem Text="Shuffle" IsChecked="{Binding IsShuffleEnabled, Mode=TwoWay}"/> <ToggleMenuFlyoutItem Text="Repeat" IsChecked="{Binding IsRepeatEnabled, Mode=TwoWay}"/> </MenuFlyout> </Button.Flyout></Button>
SettingsFlyout
A new control for XAML that lets you easily create app settings flyouts that reflect the proper design guidelines and behaviors.
Has a header section with back button
With HeaderBackground and HeaderForeground.
Has a content section.
Show or ShowIndependent method, and dismiss it by calling its Hide method.
Add app icon also
TimePicker control
<TimePicker ClockIdentifier="24HourClock" Header="24 hour clock"/>
<TimePicker x:Name=arrivalTimePicker Header="Arrival Time" MinuteIncrement="15"/>
<TimePicker x:Name=arrivalTimePicker Header="Arrival Time"/>
New updates in existing controls &
Custom controls
Thanks
Created by: Arun Singh Rawat Will be continue to next session…