Introduction to the Windows Phone platform


Shared Windows Core

Windows 8 and Windows Phone 8 Share Many Components At The Operating System Level

Shared Core means

• OS components such as the kernel, networking, graphics support, file system and multimedia are the same on both Windows 8 and Windows Phone 8

• Hardware manufacturers work with the same driver model on both platforms

• Windows Phone gets the support for multi-core and other hardware features that Windows has had for years

• These solid, common foundations makes it easier to extend the Windows Phone platform into the future

It doesn’t mean

• Windows 8 and Windows Phone 8 developers work to exactly the same APIs

• (though you will see more commonality as new features are introduced to both platforms in the future)

Windows Phone 8 supports

• Managed app dev using the WP7.1, WP8.0 .NET and WinPRT APIs

• Native app dev using WinPRT and Win32

• Games dev using the WP7.1 XNA framework

• Games dev using Direct3D or DirectX

clip_image002

Since we are going to look at managed app dev , let me point you to the classes you can use for WP 8 development. There are basically two sets of API s

clip_image004

Now which one should you choose ?

Windows phone .NET API

This has full support windows phone 7.1 classes. So if you code using these supported classes, your app will run on WP 7 two. If you have existing app that runs for WP 7.1,you do not have to re-develop from scratch, you can reuse the existing code base. Contains classes and types from the System and Microsoft.Phone namespaces

• There have been new classes added for Windows Phone 8.0, for example

• Microsoft.Phone.Wallet

• Microsoft.Phone.Tasks.ShareMediaTask

• Microsoft.Phone.Tasks.MapsTask

• Microsoft.Phone.Storage.ExternalStorage

• Microsoft.Phone.Networking.Voip

Windows Phone Runtime API

Windows Phone Runtime is a subset of the full WinRT, plus some phone-specific additions. Windows (Phone) Runtime is implemented in C++ and projected into C#, VB.NET, and C++.

You would be using this library typically if you are developing for Windows Phone 8 and Windows RT since the Windows PRT API and the Win RT API has a lot of shared codes.clip_image006

So, it is mostly a matter of choice which class you choose since equivalent classes exist in both the APIs

.NET API

Windows Phone Runtime API

System.IO.IsolatedStorage

Windows.Storage

System.NET.Sockets

Windows.Networking.Sockets

System.Threading.ThreadPool

Windows.System.Threading.ThreadPool

Microsoft.Devices.Sensors

Windows.Devices.Sensors

System.Device.Location

Windows.Devices.GeoLocation

Just to let you know, unlike Windows 8HTML/JS app development isn’t possible for WP 8.But we can use HTML 5 hosted in webview to make cross platform apps.

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.

Windows Phone 8 Application Lifecycle


image

Let’s understand the cycle thoroughly.

1. The phone starts with a clean slate. No app is in memory or in dormant state. The user taps a tile and starts Application A .The Application A while going from the Not running state to the Launched state invokes the “launching “event.

2. Now the App is running .Let’s say a call comes .The dialer will come into focus and our app will be shifted to the background. This is called the dormant state. The app is in memory but it’s not working. Suppose, if we have a note taking app, and the user was taking notes and the call comes. After the call, when the user gets back to the app, the unsaved notes will be visible without any special action by the developer.

3. Whenever the app gets deactivated the deactivating event is invoked.

4. So when does it get tombstone? Well Windows Phone currently can have maximum of 6 apps in dormant state. So the moment a seventh app goes to dormant, our app A which was the first to go into dormant state goes into Tombstone state.

5. Tombstones state basically means that your app is no longer taking any system resources .All unsaved data is lost. For example suppose our user was typing a note in the textbox and presses the home key and then goes onto open 6 other applications. First the app will be shifted to dormant and then finally to tombstone.

6. So we don’t need any special code for keeping state during dormancy. But the important part is that we would never know when the app goes from the dormant to the tombstone state. Hence, whenever our app goes to the dormant state, we should think of it as tomb stoning and put data into isolated storage for keeping state.

7. So when the user navigates back to the app by pressing the back key multiple times or long pressing the back key (task manager) .Our app will come to running state from either tombstone state or deactivated state. Both these cases will result in same function to be invoked “Activating”

8. So how do we know whether our app has been brought to life from tombstone or dormancy?  That can be done by testing e.IsApplicationInstancePreserved . If it’s coming to life from dormancy, then we do not need to do anything special.

9. There is a third case, the case when our app is dormant, but the user launches your app by tapping on tile. Technically tapping on the tile creates a new instance of your app and that is what is done. The unfortunate case is your existing instance of the app which was in dormant state is silently destroyed. Which means the user loses the unsaved data. The “launching” event is invoked

10. The solution is code redundancy! Well sort of, since in both activating and launching event needs to have some sort of parallel code ,as both would involve getting saved data from local storage .

The recommended practice is to save state data as the data changes. For example, the results of a web request can be saved to disk or the application state dictionary (or both) at the moment it arrives from the network. You should not wait until the Deactivated event occurs to store this data. All application lifecycle events enforce a limit of 10 seconds for an application to complete any tasks.

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

Display Image from Stream in Windows 8 and Windows Phone 8


The alternative title could also have been “Converting Stream to  IRandomAccessStream in windows store apps and windows phone 8.”

Frequently we might need to extract an image from a stream and display it in a XAML control,also called Image.

Typically the Stream can come from WebResponse or through any other source.

Stream stream= response1.GetResponseStream();

Where response1 is the WebResponse.Now it’s a daunting task to extract the image from the stream in Windows RT and Windows Phone 8 specially since we do not have access to system.imaging and related namespaces. So how do we go about it ?

Step 1:

Convert Stream to Memory Stream.The reason for this is that later,we need to convert Stream to IRandomAccessStream section.Memory Stream inherits from Stream.Memory Stream is a special class for accessing and storing the data in memory.

The MemoryStream class creates streams that have memory as a backing store instead of a disk or a network connection

MemoryStream ms = new MemoryStream();
 stream.CopyTo(ms);

Step 2:Convert MemoryStream to IRandomAccessStream.

This is the trickiest part as because there is no built in simple of way of doing this.IRandomAccessStream ia windows RT stream for random access of data.While coding,you might need to convert to and fro between .NET streams and Windows RT streams.For doing that,there are extension methods . These are AsInputStream and AsOutputStream .The problem with AsInputStream is that it converts a Stream to an IInputStream.  What we need is a Stream converted to an IRandomAccessStream

Lets see how this is done,

We implement an user defined function for doing so

 

 public static async Task<IRandomAccessStream> ConvertToRandomAccessStream(MemoryStream memoryStream)
        {
            var randomAccessStream = new InMemoryRandomAccessStream();
            var outputStream = randomAccessStream.GetOutputStreamAt(0);
            var dw = new DataWriter(outputStream);
            var task = Task.Factory.StartNew(() => dw.WriteBytes(memoryStream.ToArray()));
                await task;
                await dw.StoreAsync();
                await outputStream.FlushAsync();
            return randomAccessStream;
        }

What this basically does is creates a new InMemoryRandomAccessStream which implements IRandomAccessStream.Then we point to the location in the output stream at which to begin through the GetOutputStreamAt function..Then we create the Datawriter and manually asynchronously copy the data from the memory stream to the output stream and store it.

step 3:

we set the source of the bitmapImage

IRandomAccessStream a1 = await ConvertToRandomAccessStream(ms);
await bitmapImage.SetSourceAsync(a1);

Step 4: Finally

imageBox1.Source = bitmapImage;

We set the source property of the XAML image control and set it to the bitmap image.

Here’s the consolidated code.

Stream stream= response1.GetResponseStream();
BitmapImage bitmapImage= new BitmapImage();
MemoryStream ms = new MemoryStream();
 stream.CopyTo(ms);
 IRandomAccessStream a1 = await ConvertToRandomAccessStream(ms);
 await bitmapImage.SetSourceAsync(a1);
 imageBox1.Source = bitmapImage;