Windows phone and windows store

Working with Timers in Windows Phone

by Paul Wade

Alarms are accurate only within a range of one minute. In other words, the notification can be launched up to one minute after it was scheduled. For more information about Alarms – MSDN

The problem

I see a ton of timers in the windows phone market place and a ton that have disclaimers similar to “Due to a windows phone limitation the timer is only accurate to one minute”. Most refer to this as a limitation. Of course the system timer wasn’t meant to do this. Timers of thirty seconds, one minute fifteen seconds, or even fifteen minutes and ten seconds just don’t work, at least not accurately. The problem is the ScheduledActionService which is what manages these timers is only accurate to the minute, in the interest of battery life and CPU time.

The Classes

There are two options that work outside of your application. Both options have the same accuracy with a few minor differences in options. Both also use the ScheduledActionService class.

  1. Alert
    1. Always displays “Alarm” in the title. Launches app with no startup URI.
  2. Reminder
    1. You specify a title and description. Launches to a URI in your app you specify.

For my example I am using the Alert class but below you can see screen shots of the two options and how they differ slightly in UI.

Keeping your timer internal until the user exits using the dispatcher timer

Look here’s the deal. Unless you limit the user to picking whole minute times; 1, 2, 3, 4, 5, etc. Your best bet is to stick with an internal timer while your app is running. For this I use the Dispatcher timer and guess what this isn’t accurate either. To keep the UI responsive the Dispatcher timer can be delayed, you can’t simple subtract a second on each tick. To work around this I do some simple DateTime comparison.

Start time = When the user pressed start

UserTimespan = the time the user picked (I.E. one minute twenty seconds)

On each tick of the timer I do a simple check to see if I should sound an alert.

 private DispatcherTimer ExampleTimer;
         private DateTime StartTime;
         private TimeSpan UserTimespan;

        void ExampleTimer_Tick(object sender, EventArgs e)
       {
           if((StartTime - DateTime.Now) >= UserTimespan)
           {}  //alert play sound update ui.
        }

But my user turned their volume down

Well we can’t force audio to play on the phone outside of the user’s volume settings. Here’s a tip. Use the VibrateController to buzz the phone. The user will feel this or hear it if the phone is on a hard surface. You could also block the lock screen while your app is running and flash something on the screen to get their attention.

Here’s the vibrate code.


VibrateController.Default.Start(TimeSpan.FromMilliseconds(500));

Let’s create the timer on exit

This is an easy one. Working with the ScheduledActionService and Alerts and Reminders is really easy once you try it. Create your class and make sure to provide a name for your action so you can get to it later. Set your recurrence, this could be once a week, once a month or none which is what we are doing since this is not a recurring alarm. The begin time is self-explanatory I think but the expiration maybe not. The expiration time just means you know what if it’s in this case two minutes past time x then remove this timer from the list. You should use this as we don’t want to leave junk timers in the user’s phone.

Below is my method for creating the Alert. I call this from the app.cs methods Application_Deactivated, and Application_Closing.

 private void CreateAlarm()
 

  {
 

  //Here I am finding my alarm and removing it if needed.
 

  if (ScheduledActionService.Find("KitchenTimerAlarm") != null)
 

 ScheduledActionService.Remove("KitchenTimerAlarm");
 

  //The timer isnt running so lets get out of here.
 

  if (currentValue == null || !currentValue.HasValue)
 

  return;
 

  //Create the alarm with its name in the contructor
 

 var alarm = new Alarm("KitchenTimerAlarm")
 

 {
 

  //This is a one time alarm
 

  RecurrenceType = RecurrenceInterval.None,
 

  //Works off of a datetime. so I take Now and add the remaining timer in.
 

 BeginTime = DateTime.Now.Add(currentValue.Value),
 

  //if the timer is late lets cancel it after two minutes. This will remove it from the Scheduled Action Service
 

  ExpirationTime = DateTime.Now.Add(currentValue.Value).AddMinutes(2)
 
  };
 

  //Finally add it into the service
 
  ScheduledActionService.Add(alarm);
 

  }

Windows Store apps and the Authentication Broker

by Paul Wade

“The web authentication broker is the broker or facilitator between your app and authentication. It consists of a set of APIs, a broker, and a web host. Your app uses the APIs to communicate with the broker. The broker creates a new web host process in a separate app container. The broker communicates with the app, assembles the user interface (UI), and controls the lifecycle of the web authentication host. The web authentication host renders the pages from the online provider’s website.” – MSDN

 

I recently built a Kanban task board for windows store that uses an agile project management system as its back end, for those unfamiliar with OnTime by Axosoft I highly recommend you check it out.

http://www.ontimenow.com/

They have a great Restful API to work with and like almost any of these today makes use of OAuth. OAuth is so prevalent these days it comes built into ASP.NET MVC templates and is as simple to setup as uncommenting some lines of code and entering your tokens from the providing application. In MVC you can add an authentication provider this way as quickly as you can register your app in their portal.

The question though is how do I do this in a windows store application? I am going to provide a high level overview of how to make use of OAuth in your windows store application but if you would like a more in depth look at how this all works MSDN has a great article about it here.

First and foremost you will want to bring in the namespace: Windows.Security.Authentication.Web. You can add this code by the way where ever it makes sense in your application, for example if you are using MVVM you can do this in a view model. Next we need to figure out what our OAuth server is. Lets get started by heading over to http://developer.ontimenow.com/authentication/authorization-code They have provided a nice site to view their API documentation we can see that we will need a client id to get started with this.

Uri callback = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
Uri resulturi;

var authUrl = new UriBuilder("http://yourontimeurl.com");
authUrl.Path += "auth";

// Add OAuth2 parameters
authUrl.Query = string.Format("response_type=code&client_id={0}&redirect_uri={1}&scope=read%20write",
WebUtility.UrlEncode("Your client id guid"),
WebUtility.UrlEncode(callback.ToString())
);

Above I am simply formatting the URL we are going to request from. Notice the redirect_uri parameter. The auth broker is going to listen for a specific URI in its browser window so by providing the redirect in this case you tell the folks at Axosoft where to redirect with your new auth token. So

  1. Request Auth, and tell me where to push your browser to when im done.
  2. The browser is pushed to the url you specified and the auth broker knows its job is done and can move on.

You need to make sure when you add these parameters to your string format you use urlencode otherwise your uri will be improperly formatted. Now that we have our request URI we get to use the auth broker.

 WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, authUrl.Uri);

            if (result.ResponseStatus != WebAuthenticationStatus.UserCancel |
                Uri.TryCreate(result.ResponseData, UriKind.Absolute, out resulturi))
            {
               var token = new WwwFormUrlDecoder(resulturi.Query).GetFirstValueByName("code");
                await Login(token);
            }

 

Now we await our auth request while the user enters their data and allows or denies our application. Once done the provider will redirect to a given redirect URI, in the case of OnTime we are telling them where to send it in the request. One the result returns we can check the response status to make sure the user didn’t just cancel out and we can try to parse the return URI. It should contain our request token which will let us get an access token to send with our future requests to the service. That’s it, as far as the web auth broker is concerned we are done the UI portion of OAuth is complete. The user has been sent to the providers website entered their username and password and told the provider to allow our application to connect. The provider then returned to us a request token which we can use to finalize our authentication and get an access token to use for future requests.

Hope this helps!

 

 

 


Silverlight 3 Out of Browser Support

by Paul Wade

In its third version Silverlight finally has out of browser support. This allows developers to easily create a desktop and web application with one set of code. Not only does this provide a productivity increase for developers it also provides a better user experience for the end user and options such as offline support.

The following new properties were added to simplify out of browser support.
1: //Check for updates and download and install.
2: Application.Current.CheckAndDownloadUpdateCompleted += new CheckAndDownloadUpdateCompletedEventHandler(Current_CheckAndDownloadUpdateCompleted);
3: Application.Current.CheckAndDownloadUpdateAsync();
4:
5: //Is your application running OOB
6: bool IsOOB = Application.Current.IsRunningOutOfBrowser;
7:
8: //Network status
9: bool IsConnected = NetworkInterface.GetIsNetworkAvailable();

Mostly these are just basic static properties but something as simple as knowing whether or not the network is available will make providing automatic offline data caching a possibility.

Also an asynchronous method “Application.Current. “CheckAndDownloadUpdateAsync” will automatically check to see if the clients application is up to date. Microsoft has left it up to the developer to determine when and where this check is performed. This method browses to the originating URL and looks for differences in the XAP file. If a difference is found it will automatically download and install the latest version and when complete raise an event you can then prompt the user to restart the application at which point they will be running the latest version.


Theme by Ali Han | Copyright 2014 Fluent Coding | Powered by WordPress