26 Jan 2014

Windows Phone 8 App Development Part-2: Developing an App

This article is the part-2 of the series of the article on windows phone 8 app developments -  Quick Start-up guide with best practices. This whole series is in 3 parts:
Part-1: Planning and Environment Setup
Part-2: App Development, best design practices, and some challenges 
Part-3: Testing/QA of the App and the process of publishing it to store
In case if you haven’t checked the part-1, I strongly recommend you to go through it first. 

Now I will discuss about the real app development challenges and some of the best practices to follow.

Language choice

This was one of the first confusion we had – whether to go with XAML/C# or HTML/JS
Although it depends on individual or team’s experience and liking, it seems that XAML/C# is clearly the most preferred choice for app development. I have listed down some of the reasons to choose one:-

XAML/C#: Windows Ecosystem, High Performance (Native), Resolution Independence, Easier UI Binding, Better Object Oriented Programming, Stateful (persistent state), Integration with Expression Blend, Easier debugging, better community knowledge support (coming from earlier Windows 7 days).

HTML5/JS: Multi-Platform, Lesser learning curve, JavaScript language flexibility, Easier styling thru CSS, Powerful query selection for elements, Better integration with Blend, Plugins. 

If you are new to XAML, then I would strongly recommend you to learn few basic concepts such as Xaml markups, Xaml Code behind, events, styles, behavior/triggers, binding (one time, one way, two-way etc)

App templates

There are many app templates available for win 8. 

If you really don’t care about template type, then let’s create a new Project for “Windows Phone Databound App” template.
If need more help, follow this link to create your first app: How to create your first app for Windows Phone

Design Considerations

The Windows phone application can be based on pure XAML or it can leverage the power of any MVVM framework. I always prefer to use MVVM framework with any XAML based application because of many advantages such as easy data binding or event handling, robust design with better SoC (Separation of Concerns), better testability etc.  
MVVM framework popular options: MVVMLight (Easy and very lightweight, good for Phone), Prism (More comprehensive and good for desktop or Windows store apps). 

The recently released free MVVMLight has support for Windows Phone 8. MVVMLight has following advantages:
- Very light weight (just around 50-60Kb in size)
- Inbuilt IoC (SimpleIoc)
- Decoupling of View Model by using publish/subscribe message based communication
- Relay Command: Less code behind.

In case you are new to MVVM pattern, please go through following link to understand it. It is used almost in every XAML app. Few concepts such as view models, data context, command, property change events etc are used extensively. 
Adding MVVMLight to the XAML project: Right click the project and select ‘Manage NuGet Packages’. Search ‘mvvmlight’ and install ‘MVVM Light’ (Toolkit). It will add few files and folders. If needs further help, follow these instructions: How to install MVVM Light Toolkit for Windows Phone

IoC implementation and importance

The SimpleIoc is really a great addition in GalaSoft MVVMLight. In most of the scenarios, view models are singleton objects and which can be easily managed by SimpleIoC and can be accessed anywhere in the application.
public class ViewModelLocator
    {
        /// 
        /// Initializes a new instance of the ViewModelLocator class.
        /// 
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            if (ViewModelBase.IsInDesignModeStatic)
            {
                // Create design time view services and models
                //SimpleIoc.Default.Register();
            }
            else
            {
                // Create run time view services and models
                SimpleIoc.Default.Register();
            }

            SimpleIoc.Default.Register();
        }

        public T GetInstance()
        {
            return ServiceLocator.Current.GetInstance();
        }
        
        public static void Cleanup()
        {
            // TODO Clear the ViewModels
        }
    }

For easy access across application:

public static ViewModelLocator Locator
        {
            get
            {
                if (_locator == null)
                    _locator = new ViewModelLocator();

                return _locator;
            }
        }
Async/Await pattern

Asynchrony proves especially valuable for applications that access the UI thread because all UI-related activity usually shares one thread. Application can stop responding. Async/await is a Tasked-Based Asynchronous Pattern (TAP) which is much easier to implement than Event-based Asynchronous Pattern (EAP) which came in .Net 2.0. We can create an asynchronous method almost as easily as you create a synchronous method. Read more here:  Asynchronous Programming with Async and Await
async private void LoadItems(string query)
        {
            var items = await _data.GetItems(query);

            var itemVMs = items.Select(i => new ItemViewModel { ID = i.ID, LineOne = i.LineOne, LineThree = i.LineThree, LineTwo = i.LineTwo });
            this.Items = new ObservableCollection(itemVMs);
        }
Navigation

Windows Phone supports frame based navigation. The hardware back button makes navigation behave differently than desktop applications. Navigation can be based on “Data Template”, where depending upon current view model we can show view template registered with App resources. Data Template based navigation is quite common in WPF applications.
I suggest to use default frame based navigation. It is hassle free and provides automatic back navigation which is managed by the back stack. 
NavigationService available thru PhoneApplicationPage class (base class of every phone page).
// Navigate to the new page
NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + (MainLongListSelector.SelectedItem as ItemViewModel).ID, UriKind.Relative));

In case you need to handle hardware back button press differently, then follow this:
At App level in App.xaml.cs:
private void RootFrame_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //Some custom logic/ condition
If (true)
e.Cancel = true;
 else {}
        }

Or in page:
protected override void OnBackKeyPress(CancelEventArgs e)
{
    if(MessageBox.Show("Are you sure you want to exit?","Exit?", 
                            MessageBoxButton.OKCancel) != MessageBoxResult.OK)
    {
        e.Cancel = true; 

    }
}
Phone storage

User/App data can be stored in isolated phone storage. It would be good to add a utility class like AppSettings:
public class AppSettings
    {
        IsolatedStorageSettings settings;
        bool isDirty;
        public AppSettings()
        {
            //Get the settings for this application.
            settings = IsolatedStorageSettings.ApplicationSettings;
        }

        /// 
        /// Update a setting value for our application. If the setting does not
        /// exist, then add the setting.
        /// 
        /// 
        /// 
        /// 
        public void AddOrUpdateValue(string Key, Object value)
        {
            if (settings.Contains(Key))
            {
                settings[Key] = value;
            }
            // Otherwise create the key.
            else
            {
                settings.Add(Key, value);
            }
            isDirty = true;
        }

        public bool ContainsKey(string key)
        {
            return settings.Contains(key);
        }

        /// 
        /// Get the current value of the setting, or if it is not found, set the 
        /// setting to the default setting.
        /// 
        /// 
        /// 
        /// 
        /// 
        public T GetValue(string Key)
        {
            if (settings.Contains(Key))
            {
                return (T)settings[Key];
            }
            return default(T);
        }

        /// 
        /// Save the settings to isolated storage.
        /// 
        public void Save()
        {
            if (!isDirty)
                return;
            settings.Save();
            isDirty = false;
        }
    }

It can be added to App class as static field for easy access across application:
public static AppSettings Settings
        {
            get
            {
                if (_settings == null)
                    _settings = new AppSettings();
                return _settings;
            }
        }
Windows Phone Toolkit

An important addition to the default App development ecosystem which has limited no of controls at our disposal. Toolkit has many useful components. To add this: Go to “Manage NuGet Package” and search “toolkit”. Install “Windows Phone Toolkit” from the available packages.
This toolkit has many new controls such as: AutoCompleteBox, ContextMenu, CustomMessageBox, DateTimeConverters, DateTimePickers, ExpanderView, ListPicker, LongListMultiSelector, Map extensions, RatingControl, ToggleSwitch, Navigation transitions.

Application Bar

It is an integral part of your app which enables easy navigation between pages. Add following lines of code with required menu items or icons in any page where you want to provide navigation options.

        
            
            
            
                
                
            
        
    
App bar:

Menu items can be hidden by setting "IsMenuEnabled " flag to false. The app bar can be in minimized state by setting “Mode” as “Minimized”.
Minimized app bar:

Phone page animated transition

It is quite easy to implement by adding following lines of code in page XAML. This is again possible because of toolkit. Even Effects such as SlideInEffect, TiltEffect and TurnstileFeatherEffect are possible thru use of toolkit.

For Page transition effect:

        
            
                
            
            
                
            
        
    
    
        
            
                
            
            
                
            
        
    

User Interface

The phone SDK provides some default theme and icons. It is highly recommended to use them as it matches the overall look and feel of phone. If needed new theme can be added or existing theme styles can be extended. It is good practice to keep these new styles in App XAML or a separate file. Expression blend can be used to efficiently create new styles.

SDK Path: C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0 
ICONs (Dark/Light): C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Icons
Adding custom styles at App level under:

    #FF000000
    #FFFFFFFF
    #666666
    
    40
    12,5,12,0
    
    
    
  
Source Control

I used online visual studio as source control. It is just as easy to configure as we can do in our favorite TFS (Team Foundation Server). A valid Microsoft account is required to access online visual studio. License: The free version supports upto 5 users.
Link: http://www.visualstudio.com/  (Go to 'Visual Studio Online')
Interface:

Source Code

I have developed a windows phone 8 solution which includes most of the best practices discussed above. It would be a great starting point for your application. 
Solution contains following:

Next

In next post - part-3 of this article series, I will discuss about testing/QA of the developed application and the process of publishing it to windows store.

No comments:

Post a Comment