Best Alarm Apps in Windows Store.


Windows store like the android app store is populated by a lot of junk apps that don’t work. For the past few days, I was searching for a decent alarm application and I found that very few of the alarm application actually work. The main problem is that the alarm apps stop running the moment you visit another app.

So here I am going to document the best Alarm Apps in Windows 8 and the various pros and cons.

1. Smart Metro Alarm

Key features:

1. Multiple Alarms can be set and stored forever. No limit on alarms stored

2. Snoozing, repeating and alarms that repeat on specific days are supported

3. Night Mode to be used as a night stand clock.

4. Stopwatch that works even if the app is closed.

5. Snapped View works properly.

Pros: All the above features actually work. I have bought this alarm and the developer keeps updating this app every week. Alarms ring properly and stopwatch works fine. .The biggest feature is that the alarms actually work even if the lock screen is on or the app isn’t running.

Cons: Overtly simplistic UI.UI could be improved

Rating 8/10

Link

2. Sunrise Clock

Key features:

1. Multiple Alarms can be set and stored forever. No limit on alarms stored

2. Night mode.

3. Choice of 5 beautiful background picture.

4. Very attractive UI

5. Works in snapped mode.

Pros: Very nice UI. Has the concept of sunrise, so if you keep the alarm app on and go to sleep it will simulate a sunrise with time but, if you are like me you will be too sleepy to notice. Over all the app works great as long as you keep it open. You can choose from 5 different sounds

Cons: The app doesn’t work, when the lock screen is on or you are seeing another app. The alarm unfortunately doesn’t ring when any other app is open. So if you by chance fall asleep without opening the app then your alarms won’t ring. A very serious problem. And also no option of snoozing.

Rating 5/10

Link

3. HD Alarm Clock

A bit pricey alarm clock with heavily customizable features.

Key features:

1. Multiple Alarms can be set and stored forever. No limit on alarms stored

2. Choose your own alarm tone.

3. Very nice UI

4. Obstacles for deep sleeper.

5. News are shown in one screen.

6. Beautiful themes and work well.

Pros: All the features work as expected. One cool thing is obstacles that are put in place during an alarm

Con: The alarm stops working if the app isn’t running or the lock screen is on. The only problem that seriously impairs the functionality.

Rating: 7/10

Overall winner: Metro Smart Alarm

Advertisements

Exception Handling in Task Based Parallel programming.


As you had learnt in the previous posts, Tasks are executed asynchronously and parallel. Now what happens when there is an exception? How and where is it thrown?

This blog post answers all the above questions

1. What happens when an exception occurs?

When a task causes an exception, it first terminates the Task .E is caught,saved as a part of an AggregateException ae and stored in object’s Exception property

.Now, we know, that I synchronous programming, the exception propagates upward to the caller from the callee.

But in synchronous programming, the scenario is different. Here if the exception is unhandled, it is re thrown at a later time.

2. What do you mean by ‘Later Time’?

The exception AE is rethrown when it encounters .result,.Wait or WaitAll Task functions.The exception if not handled or touched, is rethrown when the task object is garbage collected.

3. What is the proper way to handle exceptions ?

   1: Task<int> T_1 = Task<int>.Factory.StartNew(() => { 

   2:                 //throw new ArithmeticException();

   3:                 //do something awesome that generates an exception

   4:                 return 1;

   5:             });

   6:             try

   7:             {

   8:  

   9:                     int a=    T_1.Result;

  10:             }

  11:             catch (AggregateException AE)

  12:             {

  13:                 AE = AE.Flatten();

  14:                 foreach (Exception ae in AE.InnerExceptions)

  15:                 {

  16:                     //handle each Exception ae

  17:                 }

  18:  

  19:             }

4. What is AggregateException ?

.NET throws all the exception wrapped in a single Exception called Aggregate Exception. Now as we know, that each task can create many subtasks, which again can lead to exceptions. So an aggregate Exception returned by a task, contains all the exception returned by the subtasks.

Consider this scenario, Task A creates Task B and Task C, and in doing so Task A is considered the parent of both Task B and Task C. These relationships come into play primarily in regard to lifetimes. A Task isn’t considered completed until all its children have completed, so if you used Wait on Task A, that instance of Wait wouldn’t return until both B and C had also completed.  So what happens if both throws an exception. Then both the exceptions are wrapped in an aggregate Exception and rethrown.

5 .How do we access the individual exceptions ?

We access it through the Aggregrate Exceptions class. But it might happen that the child of the parent’s task, spawns more child tasks which throws exception. Hence we can see a tree forming,whose leaves are exceptions.

By default, AggregateExceptions retains this hierarchical structure, which can be helpful when debugging because the hierarchical structure of the contained aggregates will likely correspond to the structure of the code that threw those exceptions. However, this can also make aggregates more difficult to work with in some cases. To account for that, the Flatten method removes the layers of contained aggregates by creating a new AggregateException that contains the non-AggregateExceptions from the whole hierarchy.

6. What is observing Exceptions ?

Now, as we said unhandled Exceptions will be rethrown during garbage collection. To avoid that ,there are 4 methods you can “observe” the exceptions or in other words allow the exceptions to be rethrown so that you can handle it.

Calling .Wait, .Result or .WaitAll on tasks will allow the task to re throw the exceptions. [task.waitany does not throw any exceptions)

Access tasks’ Exception property after completion of task.

Subscribe to TaskScheduler.UnobservedTaskException

Accessing the exception property after completion of the task will not re throw the exception. If the exception property is not null, then you would know that an exception was generated. Even if you don’t handle it, the compiler won’t rethrow during garbage collection as you have observed the exception

Asynchronous programming Deep Dive part 2


 

Picking up from where I left off , I had promised to show you the code behind “both” button .The initial code is

   1: WebResponse Response = getResponse("http://feeds.bbci.co.uk/news/world/rss.xml?edition=uk#");

   2:             int bbc =Int32.Parse( processBBCNews(Response).ToString());

   3:      

   4:  WebResponse Response1 = getResponse("https://news.google.com/news/feeds?ned=in&topic=h&output=rss");

   5:             int gn =Int32.Parse(  processGoogleNews(Response1).ToString());

   6:                      

   7:             int time_stop = System.Environment.TickCount;

   8:             //Computing the difference between the number of posts

   9:             textBox3.Text = (Math.Abs(bbc - gn)).ToString();

Now, the reduction in time can be felt the most in this part. Because we will designate 2 different threads to work on the 2 services.

Now to do this,if we blindly follow the previous method, we will end up with this .

   1: int time_start = System.Environment.TickCount;

   2:             Task<WebResponse> T1 = Task<WebResponse>.Factory.StartNew(()=>{

   3:             WebResponse Response = getResponse("http://feeds.bbci.co.uk/news/world/rss.xml?edition=uk#");

   4:                 return Response;

   5:                 });

   6:            

   7:             Task<WebResponse> T2 = Task<WebResponse>.Factory.StartNew(()=>{

   8:             WebResponse Response = getResponse("https://news.google.com/news/feeds?ned=in&topic=h&output=rss");

   9:             

  10:             return Response;

  11:              });

  12:            Task<int> T1_next = T1.ContinueWith((antecedent) =>

  13:             {

  14:                 int gn = Int32.Parse(processGoogleNews(antecedent.Result).ToString());

  15:                 return gn;

  16:             },

  17:             TaskScheduler.FromCurrentSynchronizationContext());

  18:            Task<int> T2_next = T2.ContinueWith((antecedent) =>

  19:             {

  20:                 int bbc = Int32.Parse(processBBCNews(antecedent.Result).ToString());

  21:                 return bbc;

  22:             },

  23:                 TaskScheduler.FromCurrentSynchronizationContext()

  24:             );

  25:            

  26:               //Computing the difference between the number of posts

  27:             textBox3.Text = (Math.Abs(T1_next.Result - T2_next.Result)).ToString();

  28:           

  29:             int time_stop = System.Environment.TickCount;

  30:             label3.Text = (time_stop - time_start).ToString(); 

But this will not run. Infact this will freeze your application indefinitely? Why so?

The reason being, T1_next.Result executes before , T1 is actually finished . Now this is straight forward as we know that <task_name>.Result implicitly calls Task.Wait() and hence, it will freeze the UI thread and wait for the results.

But at the same time after T1 finishes, T1_next will be invoked, which is waiting at the local queue to be run on the UI thread. While the UI thread isn’t finished because it’s waiting for T1_next. Thus we have a deadlock. Always watch out for such deadlock, when you are dealing with synchronization contexts. So we need to do away with the waiting .

We need to change our code a bit

 

   1: int time_start = System.Environment.TickCount;

   2:             Task<ListBox> T1 = Task<ListBox>.Factory.StartNew(()=>{

   3:             WebResponse Response = getResponse("http://feeds.bbci.co.uk/news/world/rss.xml?edition=uk#");

   4:                 //Instead of returning the response we send the response to another processing function which does not update the UI thread

   5:             ListBox bbc = processBBCNews_new(Response);

   6:             Thread.Sleep(2000);

   7:             //The processing function returns a listbox 

   8:                 return bbc;

   9:                 });

  10:            

  11:             Task<ListBox> T2 = Task<ListBox>.Factory.StartNew(()=>{

  12:             WebResponse Response = getResponse("https://news.google.com/news/feeds?ned=in&topic=h&output=rss");

  13:  

  14:             ListBox gn = processGoogleNews_new(Response);

  15:             return gn;

  16:              });

  17:             //The trick is to wait for both T1 and T2 without blocking the UI thread                      

  18:             Task[] arr = { T1, T2 };

  19:             TaskFactory tf = new TaskFactory();

  20:             //Continue when all acts like a call back ,and does not fire wait on the UI thread,hence the UI is still responsive

  21:             tf.ContinueWhenAll(arr, (a) => {

  22:                 int count = 0, count1 = 0;

  23:                 

  24:                 foreach (string item in T1.Result.Items)

  25:                 {

  26:                     //The listbox returned is iterated to add those values to the UI listbox 

  27:                     count++;

  28:                     listBox1.Items.Add(item);

  29:                 }

  30:                 foreach (string item in T2.Result.Items)

  31:                 {

  32:                     count1++;

  33:                     listBox2.Items.Add(item);

  34:                 }

  35:                 //Computing the difference between the number of posts

  36:                 textBox3.Text = (Math.Abs(count1 - count)).ToString();

  37:                 int time_stop = System.Environment.TickCount;

  38:                 label3.Text = (time_stop - time_start).ToString();

  39:             

  40:             },new CancellationToken(),TaskContinuationOptions.None,TaskScheduler.FromCurrentSynchronizationContext());

If you go through the code,you would see I have used a continueWhenAll method.I have explained the reason.If you want to know more visit .

As I had promised, I have uploaded the entire app code here.

Requesting Lock Screen Access In Windows 8


In Windows 8,Lock Screen has been made an elite area of the apps.If your app is on the users lock screen you have the elite privilege of time triggering your background task and push notification trigger.

But even if you don’t have the lock screen access,you can still use the system trigger and maintenance trigger for triggering your tasks.

So how do you ask for lock screen access?

var status = BackgroundExecutionManager.GetAccessStatus();
 if (status == BackgroundAccessStatus.Unspecified || status == BackgroundAccessStatus.Denied)
                status = await BackgroundExecutionManager.RequestAccessAsync();
            string result;
            switch (status)
            {
                case BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity:
                    result = "This app is on the lock screen and 
has access to Always-On Real Time Connectivity.";
                    break;
                case BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity:
                    result = "This app is on the lock screen and 
has access to Active Real Time Connectivity.";
                    break;
                case BackgroundAccessStatus.Denied:
                    result = "This app is not on the lock screen.";
                    break;
                case BackgroundAccessStatus.Unspecified:
                    result = "The user has not yet taken any action. 
This is the default setting and the app is not on the lock screen.";
                    break;
            }

Now if you try and debug this with a breakpoint .You might end up with an error that looks like

An unhandled exception of type ‘System.Exception’ occurred in mscorlib.dll Additional information: Element not found. (Exception from HRESULT: 0x8002802B (TYPE_E_ELEMENTNOTFOUND))

.

There is nothing to worry about though.

There are two bugs that can be  when accessing for a lockscreen access. First one, if you have breakpoint on RequestAccessAsync line, then the execution will fail because your application is not running in foreground (you are in Visual Studio, not in your app) and the lockscreen dialog cannot find main windows of your app.

Another problem occurs when running in Simulator – every call on GetAccessStatus throws an exception, because this call is basically not allowed in Simulator.

If you want to debug this, then place your breakpoint after the GetAccessStatus call and test it on Local machine and it should just work.

A caveat while using this make sure that you call this from the UI thread .Type library errors can be induced when a call needs to marshaled to another thread. Be very sure that you only run this code on the program’s main UI thread.

Implementing Logout using Facebook C# SDK


Nothing, much to say basically.This post is the result of my frustration about how little has been said about log out using the Facebook C# SDK.

The best way is to have the login and the log out implemented using the same webview. Atleast that is what I did.Another thing that I noticed is unless you closed the webview, it wouldn’t log out. So for my windows 8 store app,I immediately closed the app after logging out.Hope this works for you.

 

Here is the code.

 var oauth = new Facebook.FacebookClient(Constants.accessToken);
            
            var logoutParameters = new Dictionary<string, object>
                  {
                      {"access_token", Constants.accessToken},
                      { "next", "http://www.google.com" }
                  };

            var logoutUrl = oauth.GetLogoutUrl(logoutParameters);
            return new Uri(logoutUrl.AbsoluteUri);

Navigate to the uri and in the onloadcompleted event,close or dispose the webview.Your user will be logged out

MVVM in Windows 8 using GridView Part 1.


There will be two parts to this article. First we will talk about the MVVM pattern in general and how its implemented in Windows 8 and then we will specify it for GridView .

MVVM and MVC…,hows it related ?

Without going in to much detail.I am going to write

  • Model = what it is.
  • View = what it looks like.
  • Controller = what it does.

MVVM – The controller is replaced with a view model. the view model sits below the UI layer. The view model exposes the data and command objects that the view needs. You could think of this as a container object that view goes to to get its data and actions from. The view model pulls its data from the model(s) below.The key thing to remember is that you have one and only one ViewModel per view. The view model communicates with the model (business logic, services whatever below it).

Now lets start with the Model .I will just put a boiler plate code and you can reuse it for your good.The model is the actual data that is stored

  class Model : INotifyPropertyChanged
    {

        private string title;

        public string Title
        {
            get { return title; }
            set { title = value; OnPropertyChanged("Title"); }
        }
        private int demoValue;

        public int DemoValue
        {
            get { return demoValue; }

            set { demoValue = value; OnPropertyChanged("Year"); }
        }
public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
}

Now for the Model View

 class MovieViewModel : INotifyPropertyChanged
    {
private List<Model> modelList;

        public  List<Model> ModelList
        {
            get { return modelList;}
            set { 
                modelList= value;
                OnPropertyChanged("ModelList");
            }
        }
private RelayCommand _showDataCommand;

        public ICommand ShowDataCommand
        {
            get
            {
                if (_showDataCommand; == null)
                {
                    _showDataCommand= new RelayCommand(
                        param => getMoviePoster(),
                        param => (true),this

                    );
                }
                return _showDataCommand;
            }

public async void saveMoviePoster()
        {
            Model a = new Model();
            a.Title = "Hello";
            a.DemoValue = 1;
            Model a1 = new Model();
            a1.Title = "World";
            a1.DemoValue = 2;
            List<Model> temp = new List<Model>();
            temp.Add(a);
            temp.Add(a1);
            ModelList= temp;
      }
public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        }

}

The RelayCommand class

class RelayCommand:ICommand
    {
        private ViewModel _ViewModel;
        readonly Action<object> _execute;
        readonly Predicate<object> _canExecute;
        }

        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");

            _execute = execute;
            _canExecute = canExecute;
            this._ViewMode=_ViewModel;
        }

        public bool CanExecute(object parameter)
        {
            return true;
            //if no net connection return false
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
                  _execute(""); 
            }

        }

Finally the View

<DataTemplate x:Key="StandardItemTemplate">
            <StackPanel Orientation="Vertical" Width="350" Height="350">

                <TextBlock Text="{Binding Title}" TextWrapping="Wrap" 
  HorizontalAlignment="Stretch" Margin="5,5,5,5" FontSize="13"/>
                <TextBlock Text="{Binding Value}" TextWrapping="Wrap"
 FontSize="11" HorizontalAlignment="Stretch" Margin="5,5,5,5"/>

            </StackPanel>
        </DataTemplate>

 <GridView x:Name="gv_view" ItemsSource="{Binding MoviesList}"
 ItemTemplate="{StaticResource StandardItemTemplate}"   />
 <Button x:Name="btn_showData" Command="{Binding ShowDataCommand}"  Content="show" />

 

Now the code behind the View ,that is mainpage.xaml.cs

public sealed partial class MainPage : Page
    {
        ViewModel _ViewModel;
        public MainPage()
        {
            _ViewModel = new ViewModel();
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            gv_view.DataContext = _ViewModel;  

        }
}

 

I will explain the flow in my next post.Till then feel free to use my code.

Convert image to byte array in windows 8,win RT


Windows RT has  very limited imaging capabilities.And there are very few examples on how to convert an image into a byte array and how to save it in a disk.Here is the code for doing that

StorageFile outputFile = await savePicker.PickSaveFileAsync();
using (IRandomAccessStream outputStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
{
outputStream.Size = 0;
Guid encoderId = BitmapEncoder.BmpEncoderId;
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, outputStream);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream1);
 PixelDataProvider pixelProvider = await decoder.GetPixelDataAsync();
 byte[] pixels = pixelProvider.DetachPixelData();
  await encoder.FlushAsync();

First we use the file picker ,which is like the savefiledialog where the user enters the details of the file , the user wants to save.

Then we use the IRandomAccessStream  to open the output file for writing.Now its important to set the size of the outputstream to zero because the user might select an existing file.Then we use the GUID encoder to set the encoding we want.

You have option for PNG,BMP and JPG . So you can convert your image into any of the 3 types.

Next we create a BitmapEncoder ,When you create a BitmapEncoder, it provides access to data on the container and the first frame.

The BitmapDecoder class implements IBitmapFrame. It provides access to container data as well as data from the first frame. This allows applications to accomplish most common scenarios without needing to retrieve a separate BitmapFrame.

WinRT introduces PixelDataProvider class for ease of getting information on pixels.From there we can get the byte array of the image.Now to save the image we simply call encoder.FlushAsync(); on the encoder.This is how you can save an image from the stream