Thursday, August 28, 2014

Introduction of SQLlite a modern local database engine for windows Store app & Windows Phone App

As mobile computing becoming part our life, smart phone, tablet are eating up the market share of traditional desk top, laptop computer market, the software runs in these mobile devices ( apps) also taking up software product market share. Even my 7 years daughter knows how to search apps , install apps and use apps in both iPad and Surface. Sure enough, a good database engine for these apps would be a great help for modern app developers.

As it is now, none of these traditional desktop database engines can be used in any of these mobile platforms (iOS, Android, Windows 8, WP 8). Through my research, I found a local database engine that can be used in all these platforms and the best of it is : it is free! and more, it is open source ! That is SQLite ( read as SQL Light).
http://www.sqlite.org/ is its official site, you can find all you need about SQLite here. For example, you can find all its language syntax on this section of the site http://www.sqlite.org/lang.html

Its official description read as "SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine."

More specific resources on individual platform are also widely available. I am going to list a few here :





As my research has been focused on Windows Store App development using C# XAML, I spent most of my research time on SQLite on Windows 8 and windows 8.1 in windows store app using C# and XAML, though I did have a "Hello, word!" app running in my Samsung Galaxy 10 and read lots material and articles on Objective C. However, the difference among these platforms are mostly how to get the engine and how to interact with it in your own language. Even they are different languages in different platform. (android uses JDK, ADK and Java; iOS uses Objective-C and iOS SDK; windows app uses Windows library and Windows Phone SDK and C#) Believe me or not, the code looks very similar, they are all C#/Java/C like kind of languages. The key differences is the API in different SDKs.

For IDE wise, In android you use Eclipse ( freely downloadable); in iOS you use XCode ( freely downloadable in apple Mac store, but you must have a Mac computer, like you have to have a windows OS computer to develop android or windows store app); for windows platform, of course, you use Visual Studio ( express edition is also free)

Specific on Window platform, there are 3 different hardware architectures, X86, X64 and ARM. SQLite for windows are offered in the form of PCL ( Potable Class Library) that means the same library can be used in 3 different architectures. This is very important, as when you develop a store app, you want your app able to run in windows 64 bit and 32 bit OS, and also you want your app runs in window RT OS like surface or surface 2.

Okay, coming back to SQLite. the syntax of SQLite in these platforms are identical, the only difference is in different platform there are different packages in different languages to make your programming with SQLite more enjoyable. From now on, my introduction on SQLite will be focus on using SQLite in Windows store app. As it is an introduction article, I will touch on the following topics

1) where to get it

2) how to create tables

3) how CRUD are done in SQLite database

4) how to support transaction

Okay let's get it started. some logistics first. In order to develop Windows 8.0 store app, you need have a computer with Window 8.0 and Visual Studio 2012 installed. In order to develop window 8.1 store app you need to have Windows 8.1 and Visual Studio 2013 installed. for Visual Studio, any edition will do, including Express Edition. Express Edition of Visual Studio is freely available from Microsoft site. Besides the tool, you need to have app developer license. At this moment, it is free. With the developer license you can develop store apps and run the app in your local computer. If you want to publish your app to the store, or deploy your app to other devices ( side loading) or publish it to your corporate app store, you need to have an windows store account. , which is about $50 a year for individual. ( much lower than that in iOS platform) about $500 an year for company account ( I am not exactly sure about the figures, please do not hold me on those.)

1. how to get SQLite

once you have all these ironed out, you are set to go for creating your first app. Fire up your Visual Studio and select your project type as <Windows Store>, pick one of the app template, give it a name and click Ok. after a second you will have a windows store project that is runnable.


now, we have a windows store app project, and we need to add SQLite component to the project.

under <Tool> click on <Extensions and Updates> you will be presented with Extensions and Updates window.

Type SQLite in search box, click on <Search>, you will get one or two entries depends on your OS version




Click on <Install> you will get the database engine installed to your Visual Studio.

go back to Visual Studio, under <tool><Library package Manager> click on <Manage NuGet packages for solution>, you will be presented with Manage Nuget package. on the left site of the window, select nugget.org and search for SQLite on the right. you will get window show below:


click install on sqlite-net, which is a client library for SQLite. it is highly recommended to install this package. since you are here you might want to play around in Nuget package manager, you could find lots of goodies free. ( this is new since Visual studio 2012)

once you are done with that, your project will have a reference to SQLite for Windows Runtime (Windows 8.1) and another reference to Microsoft Visual C++ 2013 Runtime Package for Windows and have 2 files added to your projects: (SQLite.cs and SQLiteAsync.cs). With that you can declare that you got SQLite for your project and you are ready to explore the world of SQLite.


2. how to create / access database ( start from now you will see some C# or SQL code )

protected readonly SQLiteAsyncConnection _connection;

var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, dbName);

_connection = new SQLiteAsyncConnection(dbPath);

SQLiteAsyncConnection will open the database with the db name specified, if the database does not exist, it will create one for you.

3. how to create tables

there are 2 ways to create tables, you can pick up one of them for that meets your need:

simple one first.

await _connection.CreateTableAsync<Module>();

where Module is a class with some SQLite attributes on it

public class Module

{

[PrimaryKey, AutoIncrement]

public int Id { get; set; }

[Column("Title")]

public string Title { get; set; }

[Column("Description")]

public string Description { get; set; }

[Ignore]

public List<Word> Words { get; set; }

more complex way:

await _connection.ExecuteAsync(SQLScripts.Tables.Create.Module);

where module is a string with SQLite create table script as following:

CREATE TABLE IF NOT EXISTS Module (

Id INTEGER PRIMARY KEY AUTOINCREMENT,

Title TEXT NOT NULL,

Description TEXT NOT NULL

IsFavorite INTEGER NOT NULL CHECK (IsFavorite = 0 or IsFavorite = 1),

ProductId TEXT NULL,

@"OfferId INTEGER NULL

the first way is simple, but if you want to have complete control on the table schema, SQL script will offer better control

4. how to drop tables

await _connection.DropTableAsync<Word>();

await _connection.DropTableAsync<Module>();

5. how to insert rows to the table

there most common 2 ways of inserting rows are as following:

connection.InsertAll(lesson.LessonWords); and

connection.Insert(lesson);

6. how to update row in the table

similar to insert, there are 2 common ways to update rows in table.

connection.Update(module);

connection.UpdateAll(module.WordsToBeUpdated);

7. how to delete

connection.Delete(module);

from 4 to 7 , module, lesson are the instances of classes with SQLite attributes similar to the one I show above in Module class, WordsToBeUpdated and (lesson.LessonWords are instances of list <T> of the similar class.

8. how to run queries

connection.Execute(SQLScripts.Procedures.DeleteLessonWord);

9. how to support transaction

await _connection.RunInTransactionAsync((SQLiteConnection connection, List<Module> modules ) =>

{

foreach (var module in modules)

{

Save(module, connection);

}

});

_connection.RunInTransaction(() =>

{

var affectedRow = _connection.Insert(row);

if (affectedRow > 0)

{

row.CascadeId();

_connection.InsertAll(row.LessonWords);

};

});

As you can see there are 2 files, SQLite.cs and SQLiteASync. For almost all functionalities there are 2 versions, one is for async and one is for sync. For example, we have DropTableAsync we also have DropTable, the difference is the connection object, for async we use SQLiteAsyncConnection for non async we use SQLiteConnection

Recommended further reading topics could be indexing, foreign key, constraint, triggers.

Develop Window Store App using C#, XAML in Visual Studio 2013

In C# 5.0 and Window store app, the 2 most important characteristics are ( in my opinion)

XAML, MVVM pattern and asynchronous programming

In Window store app, you no longer have the window form like we have in Visual Studio 2010 or earlier. XAML is the only choice.  The project template prepared you with full implementation of MVVM.  Event programming in UI become the history in the past, Command and Command Binding is the way to go. The C# code is less coupled with the UI element as never before. It is so much so that all UI elements in the page do not have names. This is the evidence that the C# code we have do not access these UI elements at all.
with this design, you could have a design team solely working on UI and a development team solely working on the business logic and they can work together in the same codebase.  if you are tired of doing programming , here is an opportunity for you, be a user experience designer with XAML, most likely you want to work with Blend more than Visual Studio. the market demand for XAML designer is huge. I am sure you will make some good money by just doing that. If you like I could deduct an article to XAML and Blend  in my future writing.    Enough talking here, let me show you some XAML code. a note here  all XAML code shown here are hand-written by me, without using drag and drop in IDE or Blend, so it is not as colorful or active as it should be. but it is good enough to present you the usage of MVVM and binding concept here.
  <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
          DataContext="{Binding Lesson}"
          d:DataContext="{d:DesignData Source=/Data/SampleEditLesson.json, Type=ViewModel:EditLessonViewModel}">
        <Grid.ChildrenTransitions>
            <TransitionCollection>
                <EntranceThemeTransition/>
            </TransitionCollection>
        </Grid.ChildrenTransitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <!-- Back button and page title -->
        <Grid Grid.Row="0" >
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="120"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Button x:Name="backButton" Margin="39,59,39,0" Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}"
                        Style="{StaticResource NavigationBackButtonNormalStyle}"
                        VerticalAlignment="Top"
                        AutomationProperties.Name="Back"
                        AutomationProperties.AutomationId="BackButton"
                        AutomationProperties.ItemType="Navigation Button"/>
            <TextBlock x:Name="pageTitle" Text="{Binding ModuleTitle}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1"
                        IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>          
        </Grid>
        <Grid Grid.Row="2">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="150"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="50"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="70"/>             
            </Grid.RowDefinitions>
            <TextBlock Grid.Row="0" Grid.Column="0" Text="Title" Margin="10,10,10,10"  Style="{StaticResource BodyTextBlockStyle}" HorizontalAlignment="Right" VerticalAlignment="Center"/>
            <TextBox x:Name="txtTitle"  Grid.Row="0" Grid.Column="1" Margin="10,10,50,10"  Grid.ColumnSpan="3" Height="25"  Text="{Binding Title, Mode=TwoWay}"/>
            <TextBlock Grid.Row="1" Grid.Column="0" Text="Description" Margin="10,10,10,0"  Style="{StaticResource BodyTextBlockStyle}" HorizontalAlignment="Right" VerticalAlignment="Top"/>
            <TextBox Grid.Row="1" Grid.Column="1" Margin="10,10,50,10"  Grid.ColumnSpan="3" Height="100" Text="{Binding  Description, Mode=TwoWay}" VerticalAlignment="Top"/>
            <GridView Grid.Column="1" Grid.Row="2" Width="auto" ItemsSource="{Binding Words, Mode=TwoWay}" SelectedItem="{Binding SelectedWord, Mode=TwoWay}" CanDragItems="True" AllowDrop="True" CanReorderItems="True">
                <GridView.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Spelling}" Width="100" Style="{StaticResource TitleTextBlockStyle}" Margin="10,0,10,0" HorizontalAlignment="Center"/>
                    </DataTemplate>
                </GridView.ItemTemplate>
            </GridView>
            <StackPanel Grid.Column="2" Grid.Row="2" Orientation="Vertical" VerticalAlignment="Center">
                <Button Content="Add All" Width="120" HorizontalAlignment="Center" Margin="0,10,0,10" Command="{Binding AddAllWordsCommand}"/>
                <Button Content="Add" Width="120" HorizontalAlignment="Center" Margin="0,10,0, 10" Command="{Binding AddWordCommand}"/>
                <Button Content="Remove" Width="120" HorizontalAlignment="Center" Margin="0,10,0, 10" Command="{Binding RemoveWordCommand}"/>
                <Button Content="Remove All" Width="120" HorizontalAlignment="Center" Margin="0,10,0, 10" Command="{Binding RemoveAllWordsCommand}"/>
            </StackPanel>
            <GridView Grid.Column="3" Grid.Row="2" ItemsSource="{Binding AvaiableWords, Mode=TwoWay}" SelectedItem="{Binding SelectedAvaiableWord, Mode=TwoWay}" CanDragItems="True" AllowDrop="True" CanReorderItems="True">
                <GridView.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Width="100" Text="{Binding Spelling}" Style="{StaticResource TitleTextBlockStyle}" Margin="10,0,10,0" HorizontalAlignment="Center"/>
                    </DataTemplate>
                </GridView.ItemTemplate>
            </GridView>
            <StackPanel Grid.Column="1" Grid.Row="3" Orientation="Horizontal" Grid.ColumnSpan="3" HorizontalAlignment="Center">
                <Button Content="Done" Width="150"  Margin="10,10,20,10" Command="{Binding SaveCommand}"/>
                <Button Content="Delete" Width="150"  Margin="20,10,10,10" Command="{Binding DeleteCommand}"/>
            </StackPanel>
        </Grid>
    </Grid>

pay attention to the highlighted parts, the first highlighted potation,  the code links the XAML segment with a ViewModel class by assign the an instance of the ViewModel to its data context.     the following 2 lines says the following

DataContext="{Binding Lesson}"
d:DataContext="{d:DesignData Source=/Data/SampleEditLesson.json, Type=ViewModel:EditLessonViewModel}">

1) the DataContext of the Grid is set  to a property of the page with the name of Lesson,
2) in design time, you will get the sample data from a Jason file and de-serialized into an object with the type of  EditLessonViewModel
with those 2 lines, you will have the data in design time to see your design effect  and all public members of the ViewModel is accessible with the grid. In runtime, one line in code behind will set the stage right. then you will see it dancing.
 this.DefaultViewModel["Lesson"] = viewModel;

the second highlighted potation, you will see there is no event handlers in these buttons, all you see is a binding for the Command attribute. I am sure you realized that all UI elements does not have names, ( you could have them name or id if you want to do UI to UI blinding , but not to be used in C# code. I have some example for that as well)
in this pattern I could  hand over a dummy ViewModel class to the UX designer ( stop calling it UI, the new term is UX ; User Experience). he or she could make the app dancing without real business logic in place.  this is specifically useful when it comes to prototyping in the early  stage of the project.  let me stop here, If there are some interest, I could deduct an article on MVVM and how to make it work.
ok, enough said about XAML and MVVM pattern, let’s see some C# code ( or VB.Net code), after all, we are programmers, writing program code… The second characteristic in VS 2013 and C# 5.0 is asynchronous programming.  if you look at any commercial product or professionally developed window program, you will find no matter how long lasting the operation is, the UI is still response to your mouse and keyboard. (MIBAM is an exception). the key for that happen is asynchronous programming . prior to Visual Studio 2012 ( there are something to say about Visual Studio 2010, if you are interested, please let me know), all we do is to create a delegate and a call back delegate and invoke the delegate, when the operation is completed, the callback delegate will be invoked. I did that in 2004 on a project when I worked as an consultant in MCS. trust me, it is very difficult to code, and much more difficult to testing. that is how we did in the past. in Visual Studio 2012, Microsoft introduced 2 new key words in language Async and await. with those 2 new magic words asynchronous programming become something “a cave man can do it”. enough talking, let me show you some code:

    public async Task CreateDatabaseAsync()
        {
           await _connection.ExecuteAsync(SQLScripts.Create.Module);
           await _connection.ExecuteAsync(SQLScripts.Create.Word);
           await _connection.ExecuteAsync(SQLScripts.Create.Lesson);
           await _connection.ExecuteAsync(SQLScripts.Create.LessonWord);
        }
the counter part of the synchronous version would be something like
public void CreateDatabase()
        {
            _connection.Execute(SQLScripts.Create.Module);
            _connection.Execute(SQLScripts.Create.Word);
            _connection.Execute(SQLScripts.Create.Lesson);
            _connection.Execute(SQLScripts.Create.LessonWord);
        }

you can see there is no delegate involved, the code is very similar to what we are doing,  let me explain these 2 magic words in some level of detail:
when you add await in a method call, you mean to tell .Net runtime, that, when this call is made, you want to have the control back to you and when it completed, you want to be notified with the result.
when you add  async to a method, ( a sub in VB), you are telling your consumer that this method is awaitable
the naming conversion MS recommend is the name the Asyn class and members with Async suffix.
Beside this 2 magic words, there is a new library call TPL (Task Parallel Library) , with TPL, lots of things can be done in parallel to make use of multiple-core processer and multiple  CPU hardware architecture. ( the server I have at home is has 2 of qual-core CPUs workstation) . if there are some interest, I could deduct some articles on Async programming or TPL.

 let me show you some more complex snippets before concluding this article:

. private async Task SaveAsync(Module module, ModulePersistOptions options)
        {
            await _connection.RunInTransactionAsync((SQLiteConnection connection) =>
            {
                InsertOrReplace(module, connection);
                if (module.Lessons.Count == 0)
                {
                    if ((options & ModulePersistOptions.CreateAllWordsLesson) == ModulePersistOptions.CreateAllWordsLesson)
                    {
                        Insert(DataGenerator.PopulateLesson(module, string.Format("{0} All Words", module.Description), module.Title), connection);
                    }
                    if ((options & ModulePersistOptions.CreateDiffcultLesson) == ModulePersistOptions.CreateDiffcultLesson)
                    {
                        Insert(DataGenerator.PopulateLesson(module, string.Format("{0} Diffcult Words Only", module.Description), module.Title, 5), connection);
                    }
                }
            });       
         
          
        }

what I shown you here is just a tip of an iceberg, There are much more interesting topics in Window store app and Visual Studio 2013. SQLite,  Microsoft Ads SDK, TTS, MS Azure Mobile service

Implement Toast Notification using Windows Azure Notification Hubs

For a people knows nothing about notification or Service Hub like me, a few hours is all you need to implement Toast Notification for your windows Store app.

"Getting Started with Notification Hubs" is the step by step documentation together with the concept explanation.  similar documentations are also provided for iOS and Android

click here for the documentation

one thing to add on the code shown in the example is that you better add internet connection check before you make call to the notification API, failed in doing so would cause your app throwing exception.

I found that out with some heavy price. thought to pass my experience on here so that you would not  go through what I did in my project.

running windows phone emulator on windows 8.1 installed on mac bootcamp

Like most of Mobile app developers, I do both windows Store apps and iOS apps. So it is nature that I get a Mac Book and Dual boot windows and Mac OS with Bootcamp.

It is also nature for a window store app developer to extended to Windows Phone app development, after all it is the same C# code and the same XAML stuff.  so I did.

as the documentation said, get the tools installed, I got Visual Studio 2013 Update 3 installed without issue. however when I try to install Windows Phone 8.1 Emulators, I got problem, the following is the screen shot I got.


it complains that the Visualization is not enabled in the BIOS level.  as we are running windows OS under Bootcamp, it is must be something not done write in Bootcamp.

it must be something about how Mac Book handles Visualization with BootCamp.

After some research I found the following walk around, (not solution, I believe the real solution should be from Apple to fix the problem in Boot camp)

1. Boot into Mac OS
2. Got to <Preference> then <Startup Drive>
3. Select Bootcamp partition and click on <Restart>


4. The box will boot with Windows 8.x with Visualization is not enabled
5. Then you can installed Windows Phone 8.1 Emulators without problem


 
 
6. when I first time running windows Phone emulator, it complain that the emulator need to have permission to modify Hyper-V network settings. all it takes is click on <retry> to run the emulator in elevated mode. in another word, run the emulator as local administrator.


7. after that, you will see the beautiful windows Phone emulator.
 

8. The catch here is, everything you want to run WP emulator, you need to boot your windows from <Startup Disks> in Mac OS.

Resolve the “‘Microsoft.Advertising.WinRT.UI.winmd’ contains duplicate types names”

Error 1 The .winmd file 'Microsoft.Advertising.WinRT.UI.winmd' contains duplicate type names. Type 'Microsoft.Advertising.WinRT.UI.XamlAdControl_XamlTypeInfo.XamlMetaDataProvider' is already registered with the in-process server 'CLRHost.dll'. SpellingWords.Test'

Resolve the "'Microsoft.Advertising.WinRT.UI.winmd' contains duplicate types names"
Posted on 27/12/2012<http://blog.webrox.fr/?p=43> by poppyto<http://blog.webrox.fr/?author=1>

Hi everybody,
I recently had an issue with the Microsoft Advertising SDK for WinRT.
I can't compile without an error (I found a tip – remove reference/compile/add reference/compile – but I can't compile for making an app package).
The famous error is :
error APPX1712: The .winmd file 'Microsoft.Advertising.WinRT.UI.winmd' contains duplicate type names. Type 'Microsoft.Advertising.WinRT.UI.AdControl' is already registered with the in-process server 'CLRHost.dll'.
1>C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\AppxPackage\Microsoft.AppXPackage.Targets(803,9): error APPX1712: The .winmd file 'Microsoft.Advertising.WinRT.UI.winmd' contains duplicate type names. Type 'Microsoft.Advertising.WinRT.UI.XamlAdControl_XamlTypeInfo.XamlMetaDataProvider' is already registered with the in-process server 'CLRHost.dll'.
What the hell is ? It's just a bogous statment, my project is maybe not typical : I use some library, and it seems the compiler does not like that.
HOW TO RESOLVE ?

I found a lot of posts on The Internet and non solve this issue. I spent a lot of time to find this :
1. Open with notepad the SDKManifest.xml in C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0\ExtensionSDKs\MSAdvertisingXaml\8.1\SDKManifest.xml with administrator rights
2. Edit this line <File Reference = "Microsoft.Advertising.WinRT.UI.winmd" >
3 .Modify by <File Reference = "Microsoft.Advertising.WinRT.UI.winmd" Implementation="Microsoft.Advertising.WinRT.UI.winmd" >
4. Recompile and enjoy
That's all, everything works perfect after that
EDIT

Unfortunately, this works and certification kit is happy !

App manifest is missing required element '/Package/Extensions/Extension/InProcessServer/ActivatableClass'

Like most of programmers, I like to keep my tools updated with the latest updates and SPs. when I started doing Windows Phone app development, I updated my Visual Studio 2013 to Update 3.

To my surprise, last night when I try to build my Windows store app solution, I got this build error with my unit test project.

However,  when I go to my other box without Update 3 installed to build the same solution, it builds without error.

I searched high and low with no luck.  After a few hours research, try and error. I finally figured it out.  in case you run into the same problem, I post this article on my blog.

This is a sample of  Package/Extensions/Extension/InProcessServer/ActivatableClass

<Extension Category="windows.activatableClass.inProcessServer">
      <InProcessServer>
        <Path>Microsoft.Samples.DllServerAuthoring.dll</Path>
        <ActivatableClass ActivatableClassId="Microsoft.Samples.DllServerAuthoring.Toaster" ThreadingModel="both" />
      </InProcessServer>
</Extension>
It is meant to tell how in process service is started and what is the starting point.

Yes, it is related to Update 3 for sure. as a matter of fact, it builds without error on Visual Studio 2013 without Update3. but it is also related to how is the project referenced.

It turned out that that unintentionally, I added reference in the test project to the  windows store app itself.  As it is not a class library project, Visual Studio took it as an In Process Service, so it ask how the service is started.

when I removed the reference to the store project, the solution builds without error.


Yes, Update 3 made Visual Studio 2013 smarter. one thing for sure, it supports In Process Service. evidentially, it does check if you added service components into your project as reference and asking you to specific starting point if you do.

Good Job, Update 3 ! however,  it would save a few hours of my time if some kind of documentation would be made available.

Provide Mutiple Language Support For Windows Store App and Windows Phoone App

Windows 8.x supports a host of languages from Afrikaans to Yoruba including Chinese, Japanese and Vietnamese.  Click the link for the list of languages supported
And Windows app stores are in business in more than a dozen countries.

The market in windows store app is big, if you make your apps support multiple languages, your app’s revenue could be multiplied.
Well, Microsoft did some good job in making your app supporting multiple language easy and painless.

This tutorial will show you how easy to make your app supports multiple languages.
First of all, you want your apps be popular, so you want to support the languages in which they generate the most downloads. Without challenges, English is your first choice. The question is what is after English. If you search “Most Influential Languages in the World” or “List of languages by number of native speakers” you will get different list.  Let’s say you have made your decision on which languages to support beyond English and let’s get into on how to implement it in your app.
Click this link for the language codes used in Microsoft Windows system. Take a few examples here:

en-US:  English United Statesen-GB : English United Kingdom
es-MX: Spanish Mexico
es           : Spanish
fr             : French
fr-CA     : French Canada

From here you can tell it consist 2 parts, language and region. The priority on how the resource is used is in the following order:
1.       The resource associated with the specific language and specific region
2.       The resource associated with the specific language
3.       The resource associated with the default language, in most of cases, English United States.

In Windows Store app and Windows Phone app, there are 2 ways to reference language specific resource. One is in XAML, the other is in .Net programming languages like C# or VB.Net. Let me get to them one by one.
1.       How to reference resource with Multilanguage support in XAML

In your windows store app project or windows Phone project, add folders naming after the language code.  For example, en-US for English United Standard, and zh-Hans for Chinese China.

Then add a resource file named Resources.resw in each of them. (In my experience, I like to work on English resource first and then make a copy of the resource file and paste it to the other language folder and change the content of each resource. In this way, I do not need to type the resource key multiple times. I find this way would save time and reduce human errors. )

For the resource to be referred in XAML, the resource key should be named in the pattern of <Element Uid>.<Property Name>. Take an example, you want a resource to be used on Content property of a button with the Uid as ButtonDownload, the key should be ButtonDownload.Content. Then you provide the text value in the respective language accordingly.  When this is done, the resource is ready to be used in XAML. All it takes is adding x:Uid attribute to your XAML element . The following is an example:

<Button x:Uid="ButtonDownload" Grid.Row="3"…./>

Once you have completely externalized all your language specific resource from XAML into the resource file and changed your XAML to include x:Uid  attribute. You are more than 50% done no matter how many languages you plan to support.
The next step is to create folders following the language code and copy your English version of the resource file into these folders, and change the resource values accordingly.

How to reference resource with Multilanguage support in Code

The first step is to add a folder named Strings and add a folder named “en-US” for English United States. And add a resource file named Resources.resw. then you start to add resource into the resource file based on key value pair.

We will look at how in code these resource is referred.

protected  ResourceLoader MessagesResource = new ResourceLoader();

this line establishes the resource loader, if your resource file is named different from “Resources”, you could provide the name of the resource file to the constructor.

MessagesResource.GetString(“resource key”) will get you the resource value based your current language setting of the OS.

Similarly, after you externalized all your resource form your .Net code, into the resource file, all you need to do is create folders under Strings folder and copy the English version of the resource file to these folders and change the value of the resource to is specific language content.

File Picking for Windows Phone App


If you  try to use file picker in Windows Phone App in the same way you did in Windows Store App, you would likely meet with some difficulties.

 One of the example is in Windows Phone 8.1 Hello World app,  you can get the resource from this link

When you are done with your code for picking up a photo to display the photo as following:


var openPicker = new FileOpenPicker()

            {
                SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                ViewMode = PickerViewMode.Thumbnail
            };
            openPicker.FileTypeFilter.Clear();
            openPicker.FileTypeFilter.Add(".bmp");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".jpg");
            var photo = await openPicker.PickSingleFileAsync();
            if (photo != null)
            {
                var fileStream = await photo.OpenAsync(Windows.Storage.FileAccessMode.Read);
                var bitmapImage = new BitmapImage();
                bitmapImage.SetSource(fileStream);
                displayImage.Source = bitmapImage;
            }

The code builds, but when the code executed to await openPicker.PickSingleFileAsync() you will get an exception with following message:

{System.Exception: The request is not supported. (Exception from HRESULT: 0x80070032)
   at Windows.Storage.Pickers.FileOpenPicker.PickSingleFileAsync()

you would have no idea on what is going on here, Maybe Microsoft could do better job in vetting  its Hello Word App for Windows Phone 8.1.

This link  from MSDN provided some good explanation how to do file picking.

In this article, it said  in Windows Store App, you use PickSingleFileAsync, PickSaveFileAsync and PickSiingleFolderAsync. However for Windows Phone app, you should use PickSingleFileAndContinue, PickSaveFileAndContinue and PickFolderAndContinue

 Bingo, it ends up that we should use PickSingleFileAndContinue instead of PickSingleFileAsync.

Now let’s see how PickSingleFileAndContinue works. One thing I want to get you be prepared, it is much complicated PickSingleFileAsync.

First of all,  I would like to refresh you on Windows Phone (Windows Store)Application life cycle as following:
 

When PickSingleFileAndContinue is called, you app is suspended into Suspended mode and then terminated to NotRunning state, when the user is done with his or her file picking operation,  the app will be reactivated to running state.

When the app is activated, the app’s OnActivated event is fired. You need to add the event handler in your Application class.  Most likely it is part of the code behind file for App.XAML

        protected async override void OnActivated(IActivatedEventArgs args)
        {
            base.OnActivated(args);
            var rootFrame = CreateRootFrame();
            await RestoreStatusAsync(args.PreviousExecutionState);
            if (rootFrame.Content == null)
            {
                rootFrame.Navigate(typeof(MainPage));
            }
            if (rootFrame.Content is PhotoPage)
            {
               var photoPage = rootFrame.Content as PhotoPage;
                if (args is FileOpenPickerContinuationEventArgs)
                {
                   photoPage.ContinueFileOpenPicker(args as FileOpenPickerContinuationEventArgs);
                }
            }
        }

Here CreateRootFrame and RestoreStatusAsync are 2 private methods. I will show the code for them at the bottom of this post.

What it does is get the previous page when the app is suspended. And then check to see if the argument is FileOpenPickerContinuationEventArgs. If so call a method in the page’s code behind class.

Now let’s see how it is handled in the page level and how to access the file that the user picked.

        public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
        {
            if (args.Files != null)
            {
                var file = args.Files.FirstOrDefault();
                 var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
                // Set the image source to the selected bitmap.
                 var bitmapImage = new BitmapImage();
                 bitmapImage.SetSource(fileStream);
                 displayImage.Source = bitmapImage;
            }
        }

 
The file the user picked is in the Argrment.Files collection. In this case, as I used PickSingleFileAndContinue,so there should be only one file, if you use PickMultipleFilesAndContinue, you will have multiple files in this collection.

All you need to do is to open the file and steam and create a bitmapImage with the stream file then use it as the source for the Image element in your XAML.   

The following are the rest of the code needed for the app to work: 

        private Frame CreateRootFrame()
        {
            var rootFrame = Window.Current.Content as Frame;
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame {Language = Windows.Globalization.ApplicationLanguages.Languages[0]};
                // Set the default language
                rootFrame.NavigationFailed += OnNavigationFailed;
                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
            return rootFrame;
        }

        private async Task RestoreStatusAsync(ApplicationExecutionState previousExecutionState)
        {
            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (previousExecutionState == ApplicationExecutionState.Terminated)
            {
                // Restore the saved session state only when appropriate
                try
                {
                    await SuspensionManager.RestoreAsync();
                }
                catch (SuspensionManagerException)
                {
                    //Something went wrong restoring state.
                    //Assume there is no state and continue
                }
            }
        }




in conclusion. you will find you need to break your logic into 2 blocks, one is launch the file picker the other is the logic to get the result. in between, you need to put some code in OnActiviated event handler. Comparing to PickSingleFileAsync, you just need to put your logic in various places.
 


 
 
 
 
 

        private void OnNavigationFailed(object sender, NavigationFailedEventArgs e)

        {

            throw new Exception("Failed to load Page " + e.SourcePageType.FullName);

        }