Quick Start - Mobile Applications for Windows Phone

As you all know the whole world is fall in love with mobiles and now everyone follows mobiles as a trend. And thus we (for developers) have several (namely iOS, Android, Windows Phone, Blackberry etc) platforms out there through which can reach us to users' hand by leveraging our app. But wait, i said several platforms, which means we have to also learn several things we have a lot of hard work todo, as each platform speaks it's own language. Well, that's right but hang up with me, there are solutions out there which can provide you a unified platform to learn so that you write once and leverage it to every major platform.
So, in this article series i am gonna show how can you make hybrid and native apps and deploy it on their platforms. Let's have a fun :)

Windows Phone 8.1

I have decide to start this series from windows phone as its gainning the market and as a .net developer this is our first step to jump in. I will be using visual studio 2013 with windows phone 8.1 sdk which you can download from
http://dev.windows.com/en-us. I have already installed it so let's start creating our first project.

In order to make this series of articles useful, i will make a book listing app for which we will be using xml data which i have taken from MSDN.
Ok, so that's all for infos, now i will create project in visual studio 2013 by choosing menu options i.e File -> New -> Project -> Visual C# -> Store Apps -> Windows Phone Apps. 

Windows-Phone-New-Project-Dialog

In the new project dialog i will choose Pivot App template. By choosing pivot app template, visual studio will generte several files for us. The reason that i choose this template becuase i think to get started (in any platform), its good that we start to modify existing things. Later, if you master the technology then you can start creating apps from scratch. 

At this point if you explore the project Data Model folder, you will see that it uses json file and a model (SampleDataItem.cs) class to use this file in app. But i am gonna create my own class for querying the xml data from an xml file. So, i will create a class called AppData.cs in DataModel folder. Inside AppData class, i will create a method which will get the xml data from an xml file (that i will create next) and we will parse it using LINQ to XML.

        private async Task<XDocument> LoadXMLDocument(string fileName)
        {
            var fileURL = "ms-appx:///DataModel/" + fileName;
            var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(fileURL, UriKind.Absolute));
            IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);
            var xDoc = XDocument.Load(readStream.AsStreamForRead());
            return xDoc;
        }

Notice that windows store apps files can be acces via URI and also notice that i am using the new .Net 4.5 async and await keywords for async reading the file. Also make sure that you add reference to System.IO dll file and as we as add a using namespace. I will craete another class which will hold our data after deserializing data from xml file with the following properties;

    public class Book
    {
        public string Id { get; set; }
        public string Author { get; set; }
        public string Title { get; set; }
        public string Genre { get; set; }
        public decimal Price { get; set; }
        public string PublishDate { get; set; }
        public string Description { get; set; }
    }

Next as i want to make sure that the data which i will load from xml file, should be loaded once therefore i will follow a singelaton pattern and create a static method and property that will expose the data to the app. 

        
        private static AppData data = new AppData();
        private readonly List<Book> _localCache = new List<Book>();

        public List<Book> BooksList
        {
            get { return this._localCache; }
        }

As you can see i have create an instance of this class in the exact class so that no one else could create an instance outside of this (singelton) class. And then i have a created property BooksList which will simply return local cache data (loaded only once). Now i will expose this data to the outside for use;

        public static async Task<List<Book>> GetBooks()
        {
            await data.GetData()
                .ConfigureAwait(continueOnCapturedContext:false);
            return data.BooksList;

        }
        private async Task GetData()
        {
            if (this._localCache != null && this._localCache.Count > 0)
                return;
            try
            {
                string fileName = "books.xml";
                var xDoc = await LoadXMLDocument(fileName)
                                .ConfigureAwait(continueOnCapturedContext: false);
                var books = xDoc.Root
                            .Elements("book")
                            .Select(x => new Book
                            {
                                Id = x.Attribute("id").Value,
                                Author = x.Element("author").Value,
                                Title = x.Element("title").Value,
                                Genre = x.Element("genre").Value,
                                Price = Convert.ToDecimal(x.Element("price").Value),
                                PublishDate = x.Element("publish_date").Value,
                                Description = x.Element("description").Value
                            })
                            .ToArray();
                foreach (var book in books)
                {
                    this._localCache.Add(book);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
Notice that as i am using async operation, i have also told to compiler that we are not in UI thread by channing ConfigureAwait(continueOnCapturedContext:false). Now as i have the code to call, i have already create a file called books.xml and imported the xml data from msdn (see the top section of the article). 
In the solution explorer i will now open the PivotPage.xaml file (code behind .cs) and update the NavigationHelper_Loadstate method as following;
        private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            var model = await AppData.GetBooks();
            this.DefaultViewModel["Books"] = model;
        }
And in the xaml file i will add now this defaultviewmodel as a datacontext as;
    DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
and i will update the pivot control and listview with the following;
<Pivot x:Uid="Pivot" Title="MY APPLICATION" x:Name="pivot" 
               CommonNavigationTransitionInfo.IsStaggerElement="True">
            <!--Pivot item one-->
            <PivotItem
                x:Uid="PivotItem1"
                Margin="19,14.5,0,0"
                Header="first"
                DataContext="{Binding Books}"
                CommonNavigationTransitionInfo.IsStaggerElement="True">
                <!--Double line list with text wrapping-->
                <ListView
                    ItemsSource="{Binding}"
                    IsItemClickEnabled="True"
                    ItemClick="ItemView_ItemClick"
                    ContinuumNavigationTransitionInfo.ExitElementContainer="True">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Margin="0,0,0,9.5">
                                <TextBlock
                                    Text="{Binding Title}"
                                    TextWrapping="Wrap"
                                    Pivot.SlideInAnimationGroup="1"
                                    CommonNavigationTransitionInfo.IsStaggerElement="True"
                                    Style="{ThemeResource ListViewItemTextBlockStyle}"
                                    Margin="0,0,19,0"/>
                                <TextBlock
                                    Text="{Binding Author}"
                                    TextWrapping="WrapWholeWords"
                                    Pivot.SlideInAnimationGroup="2" 
                                    CommonNavigationTransitionInfo.IsStaggerElement="True" 
                                    Style="{ThemeResource ListViewItemContentTextBlockStyle}"
                                    Margin="0,0,19,0"/>
                            </StackPanel>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </PivotItem>
        </Pivot>
i don't need the second pivot so i have already remove that. Now i will run the project and see the result;
final-result
As you can see the data which we bind it to the defaultviewmodel (which is basicallly a dicationary) is showing on our screen now. For demo purposes i didn't include all properties but only author and title but you got the idea of how we can bind the data to the viewmodel. 
So, that's it for windows phone, next we will make the same demo for android using xamarin. 

Source Files


5.0 1

Existing reviews

Complex but quite easy
I have been looking for windows phone development from ages but your tutorial make it simple and awesome its really easy sir thanks for putting your efforts
From: Guest | Date: 10/21/2014 9:13 AM
Was this review helpful? Yes / No (1/0)


Write your own review
Bad Excellent