Wednesday 3 August 2016

Short Notes on Background Task in Windows Universal Apps


Hello All,

Sharing some notes on Background task.

  • Background task allow us to run our code when our app is not in foreground.
               
  • Starting with Windows 10, you no longer need to place an app on the lock screen in order to register background tasks.
  • Background tasks are limited to 30 seconds of wall-clock usage.
  • Respect Cost : Add BackgroundWorkCostValue in run() to get access on priority from system.
            
  • Querying cost can prevent cancellations and incomplete operations.
  • Handle System Cancellations: 
       
  • Use defferal for any asynchronous operations.
  • App can have more than one Background Task.
  • If get the permission then build and register task(add triggers, add system conditions, task.register())
            

Tuesday 2 August 2016

Short Notes on Roaming Settings in Windows Universal Apps

Hello All,

Here are some key points which keep in mind while implementing roaming settings in your app.

1)Roaming settings to store a user's settings, preferences, and session info can be available across multiple devices.

2)Roaming data is associated with a user's Microsoft account and only sync if a user logs into his devices using the same Microsoft account and
 installs the app on several devices.

3)Some kind of files which don't roam are :

  • File types that behave like folders (for example, files with the .zip and .cab extensions)
  • Files that have names with leading spaces
  • Files that have names with these unicode characters:
    e794, e795, e796, e7c7, e816, e817, e818, e81e, e826, e82b, e82c, e831, e832, e83b, e843, e854, e855, e864, e7e2, e7e3, and e7f3
  • File paths (file name + extension) that are longer than 256 characters
  • Empty folders
  • Files with open handles
4)Handle the DataChanged event by updating app data. This event occurs when app data has just finished syncing from the cloud and event only fires if the application is active.

5)Roaming settings are exposed as an dictionary in which application can save data.

       

6)On Windows desktop there is special High Priority Key there is no effect on windows mobile.

7)There's a limit to the amount of app data an app may roam; use RoamingStorageQuota property to get this maximum.

8)Debugging : 
Developer can install application on multiple unlocked devices.
Locking a developer device will trigger the synchronization.
If problem occur--make sure file closed properly,make sure devices can running same version of app.

9)Tips:
Good for app customisation settings,most recent activity,partially completed work.
Synchronisation stops if roaming data >100kb
Bad for syncing large data or "instant syncing" scenarios.
Last writer wins.
Data deleted from cloud if app not used for period of time(~30 days)

Credential Locker in Universal Windows Apps

Hello All,

Sharing some information on Credential Locker in UWP Apps

1) Its an API to store and roam credentials securely (Windows.Security.Credentials).

2) Since it is roamed across the devices,so we don't have to ask user for credentials again on other device running the same app.

3) Benefits: Secure Storage,Credential Isolation and roaming.

4) Credential roam across the trusted devices.

5) Uses public or business cloud according to primary user identity(MSA/AAD(Azure Active directory)).

6) Scenario: If your app connect to services like social networking. By only asking the user for login information once and store it in the Credential Locker between sessions will provide a good user experience.

7) Tips :
Avoid Large data blocks to store.It is best for saving passwords.
Make sure the user has successfully signed in and opted to save passwords before storing them in the Credential Locker.

8)Sample:

      

Live Tiles in Universal Windows Apps

Hello All,

Sharing some information on Live tiles in windows universal apps.

  • Tile would be in 3 states:
Basic State : Contains a plate(container),app logo and short name(text).
Semi-Live State : Contains plate,app logo,short name and badge.
Live state : Contains plate, content(live text information),app logo,short name and badge.

  • Updating tiles:
Scheduled : Set template and tile with "ScheduledTileNotification".Either you define URI in manifest and update your server code so that URI will get updated content from server,which displayed on tile in a scheduled time or you can just write a scheduled notification and provide some bunch of strings/images that you want to update on tile.



Periodic : Pull from URL 30m,60m,6h,12h,24h, accordingly you have to write logic to pull content from an url.

Local: Update from (foreground/background) app.

Push : Use push services and update tile badge.

  • Sample code to update badge count:
void UpdateBageCount(int count)
{
     //make badge schema for tile
     var tileUpdateType = Windows.UI.Notifications.BadgeTemplateType.BadgeNumber;
     var xml = Windows.UI.Notifications.BadgeUpdateManager.GetTemplateContent(tileUpdateType);
     //Update element
     var tileElements = xml.GetElementsByTagName("badge");
     var tileElement = tileElements[0] as Windows.Data.Xml.Dom.XmlElement;
     tileElement.SetAttribute("value", count.ToString());
     //Send update to lock screen      var updateManager = Windows.UI.Notifications.BadgeUpdateManager.CreateBadgeUpdaterForApplication();
     var lockNotification = new Windows.UI.Notifications.BadgeNotification(xml);
     updateManager.Update(lockNotification);
 }
  • Secondary Tile : You can define tiles within your application, and user can also do pin it to start screen.And on tapping this tile from start screen,app opens and user redirects to the page which is associated with this tile as per the code logic.Sample code below :)
           
async void CreateSecondaryTile(string tileId,string displayName,string arguments)
{
  var isPinned = Windows.UI.StartScreen.SecondaryTile.Exists(tileId);
  if (!isPinned)
  {
    var secTile = new Windows.UI.StartScreen.SecondaryTile(tileId)
    {
        DisplayName = displayName,
        Arguments = arguments
    };
    var success = await secTile.RequestCreateAsync();
  }
}
  • Tile Templates : There are over 80 templates available you can choose from.
  • Adaptive Templates : 
Size (TileSmall,TileMedium,TileWide,TileLarge (only for desktop))

<tile> <
visual>
    <binding template="TileMedium">
      ...
    </binding>
    <binding template="TileWide">
      <text hint-style="subtitle">Ravindra Singh</text>
      <text hint-style="captionSubtle">Article on Technet</text>
      <text hint-style="captionSubtle">Check out my article on Technet Wiki</text>
    </binding>
    <binding template="TileLarge">
      ...
    </binding>
  </visual>
</tile>
You can control the branding on the bottom of a live tile (the display name and corner logo) by using the branding attribute on the notification payload. You can choose to display "none," only the "name," only the "logo," or both with "nameAndLogo." Windows Phone doesn't support the corner logo, so "logo" and "nameAndLogo" default to "name" on phone.        Groups and Subgroups:

               

      Images : You can do alignment ,marging, cropping of the image on a tile.
...
<binding template="TileMedium" displayName="Pictures" branding="name">
  <group>
    <subgroup>
      <text hint-align="center">Mon</text>
      <image src="Assets\Apps\MyPics\FrontPic.png" hint-removeMargin="true"/>
      <text hint-align="center">60px</text>
      <text hint-style="captionsubtle" hint-align="center">90px</text>
    </subgroup>
    <subgroup>
      <text hint-align="center">Tue</text>
      <image src="Assets\Apps\MyPics\face.png" hint-removeMargin="true"/>
      <text hint-align="center">66px</text>
      <text hint-style="captionSubtle" hint-align="center">90px</text>
    </subgroup>
  </group>
</binding>
...

Background Image: You can change background image for the tile.
Peek Image : an image with moving animation over the tile title,move from top to bottom of the tile  and displays text information over it(also use hint-overlay on peek image).
 

  • XAMLRenderingBackgroundTask:
This special background task used to be phone-specific, but now it is supported on desktop too. XamlRenderingBackgroundTask allows you to render XAML trees as a bitmap from a background task, often to generate custom tiles. If adaptive can’t achieve what you want on a tile, this is an option.
  • Chaseable Live Tiles :
Apps can now know what tile notifications were displayed on their Tile when the user clicked it. There is new property(arguments) in tile notification payload to pass.That can be captured via argument parameter of OnLaunchedEvent() of the app.

Toast Notifications in Universal Windows apps

Hello All,


Sharing some good collective information on Toast Notifications in Universal Windows Apps.


  • Types:
Glance(Consume) : Toast like "Update Available" or "New features available"
Act(Chase or take action) :
Toast invite you to begin or complete task
The toast is the app's door by chasing(clicking) on it
Additional actions enable users to perform simple task without context switching
  • Toast Templates :
All templates are available which was for Windows phone and store apps, now they have merged together.If existing legacy templates doesn't fulfill your needs so new templates are also available.
Adaptive Templates

  • Sending Toasts:
Scheduled : Set template and tile with "ScheduledToastNotification",toast can also be set to recurring.
Local : Send from foreground/background app
Push : Use push services

void SendToast()
        {
            //Make  toast
            var toastTemplate = ToastTemplateType.ToastText01;
            var xml = ToastNotificationManager.GetTemplateContent(toastTemplate);
            xml.DocumentElement.SetAttribute("launch""Args");
            //setting up value
            var toastText = xml.CreateTextNode("This is Notification Message");
            var elements = xml.GetElementsByTagName("text");
            elements[0].AppendChild(toastText);
            //Showing toast
            var toast = new ToastNotification(xml);
            var toastNotifier = ToastNotificationManager.CreateToastNotifier();
            toastNotifier.Show(toast);
        }


  • Adaptive and Interactive toast :
Create flexible toast notifications with more content and optional inline images without being limited to the previous “toast template catalog”.
Create interactive toast notifications that enable user interaction.

XML
<toast launch="app-defined-string">
  <visual>
    <binding template="ToastGeneric">
      <text>Sample</text>
      <text>This is a simple toast notification example</text>
      <image placement="AppLogoOverride" src="oneAlarm.png" />
    </binding>
  </visual>
  <actions>
    <action content="check" arguments="check" imageUri="check.png" />
    <action content="cancel" arguments="cancel" />
  </actions>
  <audio src="ms-winsoundevent:Notification.Reminder"/>
</toast>
<visual>: Content available for the users to visually see, including text and images;
<actions>: Buttons/inputs the developer wants to add inside the notification;
<audio>: The sound played when the notification pops.




  • New Functionalities:
1) Expanding toasts on mobile
2) More types of activations through actions
3) No more ToastCapable : Now no need to declare capability that app is toast capable or not.
4) Toasts and Tiles can now get in Sync :
 In Windows 10, we added the ability for an app to be notified when the app’s collection of  notifications is changed in any way that’s not caused by the app’s local client.
5)New Notification Setting behaviour : In Windows 10, only after an app sends a first toast notification, will it be added to the Notifications & Actions section of System Settings, from which the user can disable or enable toast notifications for your app at any time.

  • Interactive toast :
    -Various activation types can be set.      
    1)Activation type=foreground
  Tap button>app launches>retrieve args>take actions
 
  2)Activation type =background
  Tap>Task launches>retrieve args>Take actions 
  3)Activation type = protocol
  Tap>Protocol activates>Web/app(as per uri match)

  4)Activation type = system
  Tap>system handles(reminder/alarm)
  • Special Toast Scenarios: scenario="senario name"
       -Alarm
     -Reminder
     -Incomming call

  • Notification Types:
  1. Tile
  2. Badge
  3. Toast
  4. Raw(background Task)
  • WNS :
One service across all devices.
One process to register an app for push.
One tile template to push to Windows&phone apps.
Request Channel Uri>Register with your cloud service >Authenticate & Push notification
References : PushTestServer  and Sample Code 
  • Developers Can do:
Remove one or many notifications.
Tag and group notifications.
Replace a notification with a new one.
Set an expiration on notifications.
Send "Ghost Toast" notifications(only show up in notification center)

Action Center in Universal Windows Apps

  
Action Center is a system area, where user can have setting panel(composite of several system settings) and notifications list grouped by App ordered chronologically inside action center. These are the notification which user has missed to attempt when it received or user has ignored it after swiping left to right on it.  User can access action center : Mobile : Swiping down from top edge of the screen Desktop : Swiping left from right edge of the screen.  App can have maximum 20 notification into their group.It follows the Queue format, last element is flushed out once a new notification is pushed into the group. Ideally expiration date for an notification in action center is 7 days unless an earlier expiration time is specified during the creation of the toast.  

Desktop :  
 Inserting image... 

 Mobile :   
Inserting image...   

There are various Action Center Management APIs are available 
We can do: 
Remove one or many notifications. 
Tag and group notifications. 
Replace a notification with a new one. 
Set an expiration on notifications. 
Send "Ghost Toast" notifications(only show up in notification center)   

void RemoveNotificationHistory() 
{ 
    ToastNotificationHistory tH = ToastNotificationManager.History; 
    tH.Remove("My App toast 1"); 
    tH.RemoveGroup("Whatsapp"); 
} 

  App responsibilities on notification: 
Apps can inform user of 'unread' items in ways(Count on tile,listed in action center). 
App+Action center+Tile(s) must tell a consistent story for good experience. 
-User taps on toast popup or in Action center>App opens at corresponding item? 
-User opens app and reads unread items>Notification in action center removed? 
User dismisses Action Center Notification>Tile badge count changes?    

ToastNotificationHistoryChangesTrigger-
Fires whenever a user dismisses a notification from action center or when an app adds or removes or replace a notification.   Use to trigger a Background task in which you can maintain consistency of un actioned item counts in app state and on tiles. 
  
public sealed class ActionCenterChangedTask : IBackgroundTask 
   { 
       public void Run(IBackgroundTaskInstance taskInstance) 
       { 
         var toastNotifications = ToastNotificationManager.History.GetHistory(); 
           if(toastNotifications!=null) 
           { 
               var toastCount = toastNotifications.Count; 
               if(toastCount == 0) 
               { 
                   BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear(); 
               } 
               else 
               { 
                   XmlDocument xmlBadge = 
                   BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber); 
                   XmlElement badgeElement = (XmlElement)xmlBadge.SelectSingleNode("/badge"); 
                   badgeElement.SetAttribute("value", toastCount.ToString()); 
                   BadgeNotification badgeNotification = newBadgeNotification(xmlBadge); 
                   BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badgeNotification); 
               } 
           } 
       } 
   }