App development

Building apps? This is the stuff about that

Windows Store app Development Snack: Dealing with Async warnings

Submitted by Robert MacLean on Thu, 10/18/2012 - 09:50

For more posts in this series, see the series index.

In this post I am going to look at a side effect you find a lot with when using the new async modifiers: compiler warnings. While this post is in my Windows Store app dev series, it applies equally well to development on .NET 4.5 with ASP.NET, WCF, WPF etc… really anywhere you use Async.

CS1998

warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

Cause: You have specified the async modifier on a method, but you are not using the await keyword anywhere in the method.

This is a warning you should be investigating because it is there for one of two reasons:

  • You have async on the method, but do not need it – so remove it.
  • You have async on the method, because you need it & you forgot to use the await keyword! So time to fix up the code.

CS4014

warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

Cause: You are calling a method which has the async modifier & returns a task – yet you are not awaiting on that method call.

This maybe be showing you a place where you forgot the await keyword so very important to check these out too. However these can come up when you intentionally do not use the await keyword. For example, you have decided to call a method and you know it will run async and none of the code following it needs to work with the result.

Microsoft has a great page on this compiler warning which goes into far more detail, especially regarding Exceptions that is worth reading.

You may think the solution here is to suppress this warning:

#pragma warning disable 4014
            AwesomeAsync();
#pragma warning restore 4014

Which I think is not a bad solution, as it does show clear intent by the author of the code that they are aware of the issue and are intentionally ignoring it. However it is not a good solution either, forget to restore it or get the warning number wrong in the restore and you have unintentionally suppressed large parts of your code base.

The better solution is just to assign the result (a task) of the method to a variable:

var ᛘ = AwesomeAsync();

You may not like these extra variables lying around – but remember the compiler is pretty smart, it will remove them for you at compile time if they are not needed. The following images are firstly the code I used in one of my apps, and then the code as it was compiled to (I used the awesome Reflector to see the compiled code) and note the t variable is gone!

Clipboard01=3Clipboard01=2

Lastly you maybe wondering why I am using ᛘ as my variable name – because it is hard to type. I want to ensure that no one starts using that variable unless they have a good reason and so this odd character means that the moment you need that variable you will likely give it a good name and use it properly with thought. It also is one character so takes up minimal code space. Lastly because it is so unique it does make it easy to identify the purpose when reading code (meta data in the letters) so no comment is needed. If you have feedback on this usage, I would love to hear it in the comments below!

Windows Store app Development Snack: Debugging Share Target experiences

Submitted by Robert MacLean on Wed, 10/17/2012 - 11:22

imageFor more posts in this series, see the series index.

The debugging experience for Windows Store apps is FANTASTIC – you have all these great tools in Visual Studio when you are running your application, but what about for scenarios where you need to debug when your app isn’t running.

For example when you are a Share Target, as the Share Source is the running application while the Share Target is launched by Windows when the user selects the target – and if you need to debug the target how do you do that?

The trick is hidden in the project settings, under the Debug section. There is an option called Do not launch, but debug my code when it starts which if you enable and then press F5, Visual Studio will jump into debug mode but not run any code. Then when Windows launches your code, say in the share target Visual Studio will attach to it automatically and enable that FANTASTIC debugging experience!

Windows Store app Development Snack: Changing the application theme from dark to light

Submitted by Robert MacLean on Tue, 10/16/2012 - 09:45

For more posts in this series, see the series index.

imageYou may have seen in Visual Studio & Blend the option to change the Windows Theme from dark (the default) to light. The problem is that is a runtime it seems to make zero difference and there is no way in Windows 8 to change it (like we had with Windows Phone).

The solution to this is to change it in the App.xaml file – but going to the Application node (the very first one) and adding RequestedTheme="Light" to switch to the light theme or RequestedTheme="Dark" to switch to the dark theme.

image

This will have a massive impact on the overall appearance of your application!

image

A word of warning – you may also see the runtime property for this under App.Current.RequestedTheme and assume you can change it at runtime, however that will raise a NotSupportedException. What you can do is set it on start-up, so if you want to change it “dynamically” the user will need to restart the app for the change to be applied (Microsoft has a sample to show this).

image

Lastly an interesting tidbit from the documentation on this:

This property is ignored if the user is running in high contrast mode.

Windows Store app Development Snack: Simulator tips & tricks

Submitted by Robert MacLean on Mon, 10/15/2012 - 11:55

imageFor more posts in this series, see the series index.

The Windows Simulator is a great tool for developing Windows Store apps but you maybe missing out on some great features of it.

Resolution

imageThere is a little screen on the toolbar which is used to change the resolution & size of screen. It is important to test on different sizes of screens & resolution combinations as that will influence the DPI of the screen and that will have impacts on your application (Microsoft has a good post on those).

However you may want to just work with a bigger simulator sometimes – well you can but placing the mouse on the any corner and dragging the simulator bigger or smaller!

Screenshots

image

One of the best features of the tool is the built in screen shot capabilities which you can access by pressing the camera button on the toolbar. This will capture the entire screen and and place the file (by default) into C:\Users\<username>\Pictures\Windows Simulator. It does not capture any of the simulator chrome so it is perfect for using when uploading to the store.

However sometimes you do not want a specific file, you just want to capture the screenshot to memory (say to paste into a presentation) you can click on the simulator and then press ALT+Print Screen. It will produce the same screenshot as if you used the toolbar button but place it into the clipboard, rather than a file.

Finally the resolution of the screenshot is based on the resolution of the simulator.

Windows Key

image

On the bottom of the simulator (by default) is the Windows hardware key and if you rotate the simulator the key moves to the relevant location. You may find that it tends to disappear when it is placed on the left hand side (counter clockwise rotate from the start location) – because that is where the toolbar is. 

The Windows key is there still, it has just merged with the toolbar itself and can be found now in the last position under the question mark button: image

Windows Store app Development Snack: Feedback links in your app

Submitted by Robert MacLean on Fri, 10/12/2012 - 09:34

imageFor more posts in this series, see the series index.

Something I have started to do with my applications is to make it easy for the people who use the applications to send feedback – since that is the best way to improve it is based on the feedback of those who use it. The question then becomes, how to I collect this feedback?

I could put some screen in the application but I decided to rather have a simpler method for this – email. All I need now is a way to launch the email program and ideally have my email address & subject prefilled – which is not possible with the share source experience.

The solution to this is something we have used for a long time before Windows 8 – protocol handlers, and in particular mailto.

So how do you launch a protocol handler in a Windows Store app – the same way you launch a web page, the Launcher.LaunchUriAsync method.

The usage of protocol handlers does open a lot of possibilities too for sharing between Windows Store apps & Windows desktop apps!

Windows Store app Development Snack: Async & Sharing

Submitted by Robert MacLean on Thu, 10/11/2012 - 09:30

For more posts in this series, see the series index.

Here is an interesting issue, you need to implement a Share Source but to do the sharing you need it to be an async call. So what do you do? You can add the async & await modifiers but it won’t work correctly. The solution is to use the deferral which is given to you in the arguments of the event and when you are done you call the Complete method on it to indicate that you are done with all the async goodness:

async void App_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
    var deferral = args.Request.GetDeferral();

    // async code with await keyword here

    deferral.Complete();
}

Windows 8 and how it breaks applications in South Africa!

Submitted by Robert MacLean on Wed, 10/10/2012 - 12:18

Before I start thank you to Mike Geyser for for bringing this up on Twitter.

Recently I wrote about what is the correct way to display currency in South Africa, which was meant as an interest post rather than anything related to Windows 8 or development – but it seems to be serendipitous in it’s timing. The post referred to the currency format and how you should use a comma to separate Rands & Cents. Windows has always (at least as far back as Windows 98) respected this as the correct currency format in South Africa.

Here you can see Windows 7 (left) and Windows 8 (right) have the same settings.

windows7currencywindows8currency

However with Windows 8, Microsoft have decided to be correct everywhere so if you compare the number format settings in Windows 7 (left) it uses a full stop where Windows 8 (right) uses a comma for number formatting.

windows7numberwindows8number

The problem is that the number format setting is used in .NET for parsing which means that all numeric code parsing code will break in Windows 8 if you have the South African formatting set!

var testOne = Decimal.Parse("10.2"); // works in Windows 7 and before - exception in Windows 8
var testTwo = Decimal.Parse("10,2"); // works in Windows 8 but fails in Windows 7 and before

The exception that will be raised is: System.FormatException: Input string was not in a correct format.

To be fair, Microsoft has said you should never write code like that, you should always provide the culture settings when parsing (this code always works):

var rightWay = Decimal.Parse("10.2", CultureInfo.InvariantCulture);

There are also two other ways to handle this:

CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
var anotherWay = Decimal.Parse("10.2");

In summary when going to Windows 8, make sure you properly test your applications and you test them on the culture that the users will use.

Windows Store app Development Snack: What do you get from being a lock screen app?

Submitted by Robert MacLean on Wed, 10/10/2012 - 11:29

For more posts in this series, see the series index.

When you start with development of Windows Store apps, you may want to run tasks in the background and an important aspect of that is deciding if you want to be a lock screen app or not.  Microsoft has a guide on this, which is ESSENTIAL reading so this post should be seen as a cheat sheet for a portion of that document.

Triggers

Background tasks kick off on a trigger so what triggers can lock screen & non-lock screen apps use. Non-lock screen apps can run background tasks based on

Background task trigger type

Trigger event

When the background task is triggered

MaintenanceTrigger

MaintenanceTrigger

It’s time for maintenance background tasks.

SystemEventTrigger

InternetAvailable

The Internet becomes available.

SystemEventTrigger

LockScreenApplicationAdded

An app tile is added to the lock screen.

SystemEventTrigger

LockScreenApplicationRemoved

An app tile is removed from the lock screen.

SystemEventTrigger

NetworkStateChange

A network change such as a change in cost or connectivity occurs.

SystemEventTrigger

OnlineIdConnectedStateChange

Online ID associated with the account changes.

SystemEventTrigger

ServicingComplete

The system has finished updating an application.

SystemEventTrigger

SessionDisconnected

The session is disconnected.

SystemEventTrigger

SmsReceived

A new SMS message is received by an installed mobile broadband device.

SystemEventTrigger

TimeZoneChange

The time zone changes on the device (for example, when the system adjusts the clock for daylight saving time).

Lock screen apps can use those and much more, the extra triggers for lock screen apps are

Background task trigger type

Trigger event

When the background task is triggered

ControlChannelTrigger

ControlChannelTrigger

On incoming messages on the control channel.

PushNotificationTrigger

PushNotificationTrigger

A raw notification arrives on the WNS channel.

SystemEventTrigger

ControlChannelReset

A network channel is reset.

SystemEventTrigger

SessionDisconnected

The session is disconnected.

SystemEventTrigger

UserAway

The user becomes absent.

SystemEventTrigger

UserPresent

The user becomes present.

TimeTrigger

TimeTrigger

A time event occurs.

CPU

Now we know when the background task will happen, how much CPU can background task consume during it’s execution is also affected by lock screen & non-lock screen.

Before we look at the table there is three things to know:

  • This is per app – NOT per background task!
  • Think of the refresh period as the point were we get filled up with more resources. So you can run multiple background tasks and they all consume from the pool of resources. At the refresh period the bucket is filled & any unused time will be lost.
  • CPU second is not the same as a real second. A CPU second is the amount of time that is consumed by the CPU – so if you are doing I/O (like a download) then it is not counted.

CPU resource quota

Refresh period

Lock screen app

2 CPU seconds

15 minutes

Non-lock screen app

1 CPU second

2 hours

Bandwidth

In a similar way to CPU the amount of data you can consume is also effected by being a lock screen app, but in addition to that the average speed of your internet also effects the amount of data. There is another difference to CPU, rather than one bucket – there is two:

  • Small period: The shorter amount of time and has a small amount it can be downloaded.
  • Day: The max per day – so accumulation of all the smaller ones cannot exceed this.

The table below has 1Mb & 10Mb as the average speed options but you could think of them as 1Mb = WiFi and 10Mb plugged into a network. These amounts are the top end, so if the network is slow you get less.

Average throughput Lock screen apps Non-lock screen apps
Every 15min Per day Every 2 hours Per day
1Mb/s 0.469Mb 4.69Mb 0.625Mb 7.5Mb
10Mb/s 4.69Mb 450Mb 6.25Mb 75Mb

Global Pool

Above we have looked at the resource constraints for CPU & bandwidth but what happens if that isn’t enough? Windows has a global pool of additional CPU & bandwidth resources that are shared system wide. This means that if you need 2.5CPU seconds you will likely get it! However the global pool is shared across all the apps, so it is not guaranteed (the above resources we have looked at are guaranteed). So if you have some abusive apps that use it, then your app may not get anything from the global pool. The global pool is replenished every 15min.

You can test your app works with an empty global pool, and you really should do this, by turning it off in the registry

Value name

Type

Default value

Description

HKEY_LOCAL_MACHINE\ SOFTWARE\Microsoft\Windows NT\CurrentVersion\BackgroundModel\Policy\CpuEnableGlobalPool

DWORD

1

Controls the CPU global pool. A value of zero disables CPU global pool.

HKEY_LOCAL_MACHINE\ SOFTWARE\Microsoft\Windows NT\CurrentVersion\BackgroundModel\Policy\NetEnableGlobalPool

DWORD

1

Controls the network global pool. A value of zero disables network global pool.

Control channel

Taken from Staying connected in the background.

The network trigger feature supports two possible resource types for a push notification or keep-alive network trigger:

  • Hardware slot - Allows the app to use background network notifications even in low-power or connected-standby mode.
  • Software slot - Allows the app to use background network notifications but not in low-power or connected-standby mode.

This notion of slot is integral to the network trigger and is not required for WNS.

One of the options to specify while registering for the network trigger feature is the hardware or software slot resource type. This resource type capability provides a way for your app to be triggered by an incoming notification even if the device is in low power mode. By default, a software slot is selected if the developer does not specify an option. A software slot allows your app to be triggered when the system is not in connected standby. This is the default on most computers.

On the other hand, a hardware slot allows your app to be triggered at all times including when the system is in connected standby. Only systems with network devices that support connected standby will have a hardware slot. Note that the app cannot be triggered through a software or hardware slot when the system is in Sleep or Hibernate mode, or is shut down.

An app can create and use a maximum of 5 network triggers. There is also an additional system limitation on number of network triggers that specify hardware slots. The first 3 lock screen apps that register for a hardware slot for a network trigger can use a maximum of 3 hardware slots per app. Any other lock screen apps beyond the first three apps registered for hardware slots are limited to only software slots for their network triggers.

Windows Store app Development Snack: Debugging a background task

Submitted by Robert MacLean on Tue, 10/09/2012 - 08:42

For more posts in this series, see the series index.

So you have created your background task and now you want to test it – do you wait for 15min and hope it runs? Nah – there is an easier way (which is unfortunately hard to find).

First launch your app as normal and then while it is running swop to VS (this is where multiple monitors is fantastic) and you should see the Debug  Location toolbar.

image

if you do not see it then right click on the toolbar/menu area and you will be able to enable it.

image

This toolbar is very useful to test Suspend & Shutdown scenarios for your application but what is not obvious is that if you click the little arrow next to the suspect button – all your registered background tasks will be listed there. You can then click it to kick it off immediately! Great for testing.

image

Pin-a-note

Submitted by Robert MacLean on Tue, 10/09/2012 - 08:06

Board Pin-190x190-100borderDo you wish you could stick a note to your start screen? NOW YOU CAN!

Pin-a-note, allows you to store your notes in this fantastic application, and then pin any to the start screen so you can easily seen them at any point!

Compared to the sticky notes gadget that is in Windows, this has some advantages & disadvantages – you have less text space but you save considerable memory, but notes automatically sync to all your devices and you can have non-pinned notes kept in the app too.

Download

This app is also in the Apptivate competition so please go there and vote for it by clicking the image below:

apptivate

Video

Screenshots

screenshot_10022012_205444screenshot_10022012_205502screenshot_10022012_205517screenshot_10022012_205607

Pin-a-Note makes use of icons created by the awesome (& free) Metro Studio 2.


Updates

16 October 2012

  • When you click edit/add the keyboard moves to the text field - allowing you to type straight away!
  • Hitting enter in the text box could be used to add/update the note!
  • Selecting a note will make AppBar visible if it currently isn't.
  • Clicking pin will show the progress ring while we render the note.
  • Included a training popup to help people get started!
  • Included an easy way to provide feedback.
  • Minor internal tweaks.