Thought to make a post for the presentation I made in Columbus Windows App Developer User group back in March this year.
should you find it interesting, you could drop me a note, I could conduct a presentation in your user group or other setting...
http://thewindowsdeveloperusergroup.com/2014/02/24/march-2014-meetup/
Abstract:
Developer to developer. In this session, Peter Lu shares his lessons learnt (success/failure) during the design & development of his new Windows Store app from scratch. Discussion points will include creativity, design, technology choices and engineering prospects. Expect a full-on technology walkthrough as Peter shares his thoughts/work with SSML (Text To Speech), SQLite, MVVM pattern, multi-language support, Web API with EF, Live Tile, In-app Purchases, Search, Toast notification using Notification hubs, Secondary tiles & overall use of Windows Azure.
Speaker Bio:
Peter Lu is a .NET application developer since .NET 1.0. Peter holds all kinds of Microsoft developer certifications since 2001, with the last certification being Microsoft Certified Technology Specialist in C# 4.0. Peter works for HP Enterprise as .NET Enterprise Application Architect during daytime. Peter has been working with Windows Store app development since March 2013 and started working on a Windows 8.1 Store App since July 2013. This first Windows 8.1 app, named the Spelling Champion, was published back in Jan 2014 and is ready for a public walkthrough of the code & engineering choices made, while Peter is already working on the second release of the app. While working as application architect at his day job and doing Windows development in his spare time, Peter also actively blogs on topics related to software technology and software engineering.
Windows Store App and Windows Phone App Development
Thursday, September 4, 2014
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
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.
"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
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.
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 !
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.
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.
Subscribe to:
Posts (Atom)