How to use Tessnet2 library

This article has the goal to show how to use the Tessnet2 library.

Tessnet2 is a .NET 2.0 Open Source OCR assembly using Tesseract engine. Download binary here.

Another important thing for Tessnet2 work is get the languages packages, get it here for the languages you want. For the sample we are use english language.

Let’s start the sample.

Create one console aplication:
console aplication

Then copy the folder with binaries and languages packages to the same folder.
Note: Don´t forget unzip the languanges packages until have the tessdata folder with eng.DangAmbigs, eng.freq-dawg, eng.inttemp, eng.normproto, eng.pffmtable, eng.unicharset, eng.user-words and eng.word-dawg files.
The aspect should be something like:

ocr test folder

Now add the Tessnet2 reference to the project, do a right click in References > Add References > Browse> Select the folder with C:\OCRTest\tessnet2\Release64\tessnet2_64.dll and click Ok.

After add the reference for System.Drawing:
reference

Now we need configure the project to compile in x64, for it Right Click in project> Properties>Build> Platform target

configs

 

 

In Program.cs add the following code:

static void Main(string[] args)
        {
            try
            {
                var image = new Bitmap(@"C:\OCRTest\number.jpg");
                var ocr = new Tesseract();
                ocr.SetVariable("tessedit_char_whitelist", "0123456789"); // If digit only
                //@"C:\OCRTest\tessdata" contains the language package, without this the method crash and app breaks
                ocr.Init(@"C:\OCRTest\tessdata", "eng", true); 
                var result = ocr.DoOCR(image, Rectangle.Empty);
                foreach (Word word in result)
                    Console.WriteLine("{0} : {1}", word.Confidence, word.Text);

                Console.ReadLine();
            }
            catch (Exception exception)
            {

            }
        }

and run the application, this give an error:

error

to solve this go to directory and change the App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

 

 

For the test:
test
the result is:
result

Source code here.

Cimbalino Windows Phone Toolkit Samples

This article has the goal to exposes all samples related with Cimbalino Toolkit

How to use Cimbalino Windows Phone Toolkit Background – ScreenInfoService

This samples has the goal to show how to use Cimbalino Windows Phone Toolkit Background – ScreenInfoService.

Introduction

Cimbalino Windows Phone Toolkit is a set of useful and powerful items that will help you build your Silverlight applications for Windows Phone. The Toolkit is divided in projects which deliver different features. The base project (Cimbalino.Phone.Toolkit) contains base MVVM services, some very useful converters, helper classes and extension methods, and the bindable Application Bar behaviour.

Cimbalino.Phone.Toolkit.Background is a MVVM compatible services for background agents.

Building Sample
This packages is available in Nuget Package Manager (for both targets) and can be installed, for more details see: How to install Cimbalino Windows Phone Toolkit packages.

The sample for this article uses MVVM Light for help in MVVM pattern implementation, for more details see:

Let’s start!

We should register each service in ViewModelLocator, as following:

  using Cimbalino.Phone.Toolkit.Services;
    using GalaSoft.MvvmLight.Ioc;
    using Microsoft.Practices.ServiceLocation;

    /// <summary>
    /// This class contains static references to all the view models in the
    /// application and provides an entry point for the bindings.
    /// </summary>
    public class ViewModelLocator
    {
        /// <summary>
        /// Initializes a new instance of the ViewModelLocator class.
        /// </summary>
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);


            if (!SimpleIoc.Default.IsRegistered<IScreenInfoService>())
            {
                SimpleIoc.Default.Register<IScreenInfoService, ScreenInfoService>();
            }

            SimpleIoc.Default.Register<MainViewModel>();
        }

        public MainViewModel MainViewModel
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }
        
        public static void Cleanup()
        {
            // TODO Clear the ViewModels
        }
    }

Then we should implement the MainViewModel as following:

   /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// The _screen information service
        /// </summary>
        private readonly IScreenInfoService _screenInfoService;

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        /// <param name="screenInfoService">
        /// The screen Info Service.
        /// </param>
        public MainViewModel(IScreenInfoService screenInfoService)
        {
            _screenInfoService = screenInfoService;
        }

        public int ScaleFactor
        {
            get
            {
                return _screenInfoService.ScaleFactor;
            }
        }

        public string Resolution
        {
            get
            {
                if (_screenInfoService.Resolution == ScreenInfoServiceResolution.HD720p)
                {
                    return "HD720p";
                }
                if (_screenInfoService.Resolution == ScreenInfoServiceResolution.WVGA)
                {
                    return "WVGA";
                }
                if(_screenInfoService.Resolution==ScreenInfoServiceResolution.WXGA)
                {
                    return "WXGA";
                }
                return "Unknown";
            }
        }
    }

for connect view model with the page we should add the ViewModelLocator instance in App.xaml:

    <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True"  />

and add the binding in main page like:

  DataContext="{Binding MainViewModel, 
                        Source={StaticResource Locator}}"

The MainPage.xaml can be the following:

<phone:PhoneApplicationPage x:Class="CimbalinoSample.MainPage"
                            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                            xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
                            xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
                            DataContext="{Binding MainViewModel,
                                                  Source={StaticResource Locator}}"
                            FontFamily="{StaticResource PhoneFontFamilyNormal}"
                            FontSize="{StaticResource PhoneFontSizeNormal}"
                            Foreground="{StaticResource PhoneForegroundBrush}"
                            Orientation="Portrait"
                            SupportedOrientations="Portrait"
                            shell:SystemTray.IsVisible="True"
                            mc:Ignorable="d">

    <!--  LayoutRoot is the root grid where all page content is placed  -->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <!--  TitlePanel contains the name of the application and page title  -->
        <StackPanel x:Name="TitlePanel"
                    Grid.Row="0"
                    Margin="12,17,0,28">
            <TextBlock Margin="12,0"
                       Style="{StaticResource PhoneTextTitle2Style}"
                       Text="Cimbalino Sample" />
            <TextBlock Margin="9,-7,0,0"
                       Style="{StaticResource PhoneTextTitle2Style}"
                       Text="ScreenInfoService" />
        </StackPanel>

        <!--  ContentPanel - place additional content here  -->
        <Grid x:Name="ContentPanel"
              Grid.Row="1"
              Margin="12,0,12,0">
            <TextBlock>
                Scale Factor:<Run Text="{Binding ScaleFactor}" />
            </TextBlock>
            <TextBlock Margin="0,41,0,-41">
                Resolution:<Run Text="{Binding Resolution}" />
            </TextBlock>

        </Grid>

    </Grid>

</phone:PhoneApplicationPage>

How to use Cimbalino Windows Phone Toolkit Background – StorageService

This samples has the goal to show how to use Cimbalino Windows Phone Toolkit Background – StorageService.

Introduction

Cimbalino Windows Phone Toolkit is a set of useful and powerful items that will help you build your Silverlight applications for Windows Phone. The Toolkit is divided in projects which deliver different features. The base project (Cimbalino.Phone.Toolkit) contains base MVVM services, some very useful converters, helper classes and extension methods, and the bindable Application Bar behaviour.

Cimbalino.Phone.Toolkit.Background is a MVVM compatible services for background agents.

Building Sample
This packages is available in Nuget Package Manager (for both targets) and can be installed, for more details see: How to install Cimbalino Windows Phone Toolkit packages.

The sample for this article uses MVVM Light for help in MVVM pattern implementation, for more details see:

Let’s start!

We should register each service in ViewModelLocator, as following:

 using Cimbalino.Phone.Toolkit.Services;
    using GalaSoft.MvvmLight.Ioc;
    using Microsoft.Practices.ServiceLocation;

    /// <summary>
    /// This class contains static references to all the view models in the
    /// application and provides an entry point for the bindings.
    /// </summary>
    public class ViewModelLocator
    {
        /// <summary>
        /// Initializes a new instance of the ViewModelLocator class.
        /// </summary>
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            if (!SimpleIoc.Default.IsRegistered<IStorageService>())
            {
                SimpleIoc.Default.Register<IStorageService, StorageService>();
            }

            if (!SimpleIoc.Default.IsRegistered<ICameraCaptureService>())
            {
                SimpleIoc.Default.Register<ICameraCaptureService, CameraCaptureService>();
            }

            SimpleIoc.Default.Register<MainViewModel>();
        }

        public MainViewModel MainViewModel
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }

        public static void Cleanup()
        {
            // TODO Clear the ViewModels
        }
    }

Then we should implement the MainViewModel as following:

using System.IO;
    using System.Threading.Tasks;
    using System.Windows.Input;
    using System.Windows.Media.Imaging;
    using Cimbalino.Phone.Toolkit.Extensions;
    using Cimbalino.Phone.Toolkit.Services;
    using GalaSoft.MvvmLight;
    using GalaSoft.MvvmLight.Command;

    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// The storage service
        /// </summary>
        private readonly IStorageService _storageService;

        /// <summary>
        /// The camera capture service
        /// </summary>
        private readonly ICameraCaptureService _cameraCaptureService;

        /// <summary>
        /// The image source
        /// </summary>
        private BitmapImage _imageSource;

        /// <summary>
        /// The text
        /// </summary>
        private string _text;

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        /// <param name="storageService">The storage service.</param>
        /// <param name="cameraCaptureService">The camera capture service.</param>
        public MainViewModel(IStorageService storageService, ICameraCaptureService cameraCaptureService)
        {
            _storageService = storageService;
            _cameraCaptureService = cameraCaptureService;

            WriteTextCommand = new RelayCommand(WriteText);
            ReadTextCommand = new RelayCommand(ReadText);
            WriteImageCommand = new RelayCommand(WriteImage);
            ReadImageCommand = new RelayCommand(ReadImage);
        }

        /// <summary>
        /// Gets or sets the image source.
        /// </summary>
        /// <value>
        /// The image source.
        /// </value>
        public BitmapImage ImageSource
        {
            get { return _imageSource; }
            set { Set("ImageSource", ref _imageSource, value); }
        }

        /// <summary>
        /// Gets the read image command.
        /// </summary>
        /// <value>
        /// The read image command.
        /// </value>
        public ICommand ReadImageCommand { get; private set; }

        /// <summary>
        /// Gets the read text command.
        /// </summary>
        /// <value>
        /// The read text command.
        /// </value>
        public ICommand ReadTextCommand { get; private set; }

        /// <summary>
        /// Gets or sets the text.
        /// </summary>
        /// <value>
        /// The text.
        /// </value>
        public string Text
        {
            get { return _text; }
            set { Set("Text", ref _text, value); }
        }

        /// <summary>
        /// Gets the write image command.
        /// </summary>
        /// <value>
        /// The write image command.
        /// </value>
        public ICommand WriteImageCommand { get; private set; }

        /// <summary>
        /// Gets the show message box command.
        /// </summary>
        /// <value>
        /// The show message box command.
        /// </value>
        public ICommand WriteTextCommand { get; private set; }

        /// <summary>
        /// Converts to bitmap image.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <returns></returns>
        public static BitmapImage ConvertToBitmapImage(byte[] image)
        {
            var bitmapImage = new BitmapImage();
            var memoryStream = new MemoryStream(image);
            bitmapImage.SetSource(memoryStream);
            return bitmapImage;
        }

        public void ReadImage()
        {
           var result = _storageService.ReadAllBytes("image.jpg");
            ImageSource = ConvertToBitmapImage(result);
        }

        /// <summary>
        /// Reads the text.
        /// </summary>
        /// <returns></returns>
        private void ReadText()
        {
            Text = _storageService.ReadAllText("Text.txt");
        }

        /// <summary>
        /// Results the image.
        /// </summary>
        /// <param name="obj">The object.</param>
        private void ResultImage(Microsoft.Phone.Tasks.PhotoResult obj)
        {
            _storageService.WriteAllBytes("image.jpg", obj.ChosenPhoto.ToArray());
        }

        /// <summary>
        /// Writes the image.
        /// </summary>
        private void WriteImage()
        {
            ImageSource = null;
            _cameraCaptureService.Show(ResultImage);
        }

        /// <summary>
        /// Writes the text.
        /// </summary>
        private void WriteText()
        {
            Text = string.Empty;
            _storageService.WriteAllText("Text.txt", "This is a text.");
        }
    }

for connect view model with the page we should add the ViewModelLocator instance in App.xaml:

    <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True"  />

and add the binding in main page like:

  DataContext="{Binding MainViewModel, 
                        Source={StaticResource Locator}}"

The MainPage.xaml can be the following:

 

<phone:PhoneApplicationPage x:Class="CimbalinoSample.MainPage"
                            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                            xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
                            xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
                            DataContext="{Binding MainViewModel,
                                                  Source={StaticResource Locator}}"
                            FontFamily="{StaticResource PhoneFontFamilyNormal}"
                            FontSize="{StaticResource PhoneFontSizeNormal}"
                            Foreground="{StaticResource PhoneForegroundBrush}"
                            Orientation="Portrait"
                            SupportedOrientations="Portrait"
                            shell:SystemTray.IsVisible="True"
                            mc:Ignorable="d">

    <!--  LayoutRoot is the root grid where all page content is placed  -->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <!--  TitlePanel contains the name of the application and page title  -->
        <StackPanel x:Name="TitlePanel"
                    Grid.Row="0"
                    Margin="12,17,0,28">
            <TextBlock Margin="12,0"
                       Style="{StaticResource PhoneTextTitle2Style}"
                       Text="Cimbalino Sample" />
            <TextBlock Margin="9,-7,0,0"
                       Style="{StaticResource PhoneTextTitle2Style}"
                       Text="StorageService" />
        </StackPanel>

        <!--  ContentPanel - place additional content here  -->
        <Grid x:Name="ContentPanel"
              Grid.Row="1"
              Margin="12,0,12,0">
            <Image Height="243"
                   VerticalAlignment="Bottom"
                   Source="{Binding ImageSource}"
                   Stretch="Uniform" />
            <Button Height="82"
                    VerticalAlignment="Top"
                    Command="{Binding WriteTextCommand}"
                    Content="Write text" />
            <Button Height="82"
                    Margin="0,82,0,0"
                    VerticalAlignment="Top"
                    Command="{Binding ReadTextCommand}"
                    Content="Read text" />
            <TextBlock Width="436"
                       Margin="10,182,0,424"
                       HorizontalAlignment="Left"
                       Text="{Binding Text}"
                       TextWrapping="Wrap" />
            <Button Margin="0,238,0,317"
                    Command="{Binding WriteImageCommand}"
                    Content="Write Image" />

            <Button Margin="0,312,0,243"
                    Command="{Binding ReadImageCommand}"
                    Content="Read Image" />

        </Grid>

    </Grid>

</phone:PhoneApplicationPage>

How to use Cimbalino Windows Phone Toolkit Background – AsyncStorageService

This samples has the goal to show how to use Cimbalino Windows Phone Toolkit Background – AsyncStorageService.

Introduction

Cimbalino Windows Phone Toolkit is a set of useful and powerful items that will help you build your Silverlight applications for Windows Phone. The Toolkit is divided in projects which deliver different features. The base project (Cimbalino.Phone.Toolkit) contains base MVVM services, some very useful converters, helper classes and extension methods, and the bindable Application Bar behaviour.

Cimbalino.Phone.Toolkit.Background is a MVVM compatible services for background agents.

Building Sample
This packages is available in Nuget Package Manager (for both targets) and can be installed, for more details see: How to install Cimbalino Windows Phone Toolkit packages.

The sample for this article uses MVVM Light for help in MVVM pattern implementation, for more details see:

Let’s start!

We should register each service in ViewModelLocator, as following:

 using Cimbalino.Phone.Toolkit.Services;
    using GalaSoft.MvvmLight.Ioc;
    using Microsoft.Practices.ServiceLocation;

    /// <summary>
    /// This class contains static references to all the view models in the
    /// application and provides an entry point for the bindings.
    /// </summary>
    public class ViewModelLocator
    {
        /// <summary>
        /// Initializes a new instance of the ViewModelLocator class.
        /// </summary>
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            if (!SimpleIoc.Default.IsRegistered<IAsyncStorageService>())
            {
                SimpleIoc.Default.Register<IAsyncStorageService, AsyncStorageService>();
            }

            if (!SimpleIoc.Default.IsRegistered<ICameraCaptureService>())
            {
                SimpleIoc.Default.Register<ICameraCaptureService, CameraCaptureService>();
            }

            SimpleIoc.Default.Register<MainViewModel>();
        }

        public MainViewModel MainViewModel
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }

        public static void Cleanup()
        {
            // TODO Clear the ViewModels
        }
    }

Then we should implement the MainViewModel as following:

using System.IO;
    using System.Threading.Tasks;
    using System.Windows.Input;
    using System.Windows.Media.Imaging;
    using Cimbalino.Phone.Toolkit.Extensions;
    using Cimbalino.Phone.Toolkit.Services;
    using GalaSoft.MvvmLight;
    using GalaSoft.MvvmLight.Command;

    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// The async storage service
        /// </summary>
        private readonly IAsyncStorageService _asyncStorageService;

        /// <summary>
        /// The camera capture service
        /// </summary>
        private readonly ICameraCaptureService _cameraCaptureService;

        /// <summary>
        /// The image source
        /// </summary>
        private BitmapImage _imageSource;

        /// <summary>
        /// The text
        /// </summary>
        private string _text;

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        /// <param name="asyncStorageService">The asynchronous storage service.</param>
        /// <param name="cameraCaptureService">The camera capture service.</param>
        public MainViewModel(IAsyncStorageService asyncStorageService, ICameraCaptureService cameraCaptureService)
        {
            _asyncStorageService = asyncStorageService;
            _cameraCaptureService = cameraCaptureService;

            WriteTextCommand = new RelayCommand(async () => await WriteText());
            ReadTextCommand = new RelayCommand(async () => await ReadText());
            WriteImageCommand = new RelayCommand(WriteImage);
            ReadImageCommand = new RelayCommand(async () => await ReadImage());
        }

        /// <summary>
        /// Gets or sets the image source.
        /// </summary>
        /// <value>
        /// The image source.
        /// </value>
        public BitmapImage ImageSource
        {
            get { return _imageSource; }
            set { Set("ImageSource", ref _imageSource, value); }
        }

        /// <summary>
        /// Gets the read image command.
        /// </summary>
        /// <value>
        /// The read image command.
        /// </value>
        public ICommand ReadImageCommand { get; private set; }

        /// <summary>
        /// Gets the read text command.
        /// </summary>
        /// <value>
        /// The read text command.
        /// </value>
        public ICommand ReadTextCommand { get; private set; }

        /// <summary>
        /// Gets or sets the text.
        /// </summary>
        /// <value>
        /// The text.
        /// </value>
        public string Text
        {
            get { return _text; }
            set { Set("Text", ref _text, value); }
        }

        /// <summary>
        /// Gets the write image command.
        /// </summary>
        /// <value>
        /// The write image command.
        /// </value>
        public ICommand WriteImageCommand { get; private set; }

        /// <summary>
        /// Gets the show message box command.
        /// </summary>
        /// <value>
        /// The show message box command.
        /// </value>
        public ICommand WriteTextCommand { get; private set; }

        /// <summary>
        /// Converts to bitmap image.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <returns></returns>
        public static BitmapImage ConvertToBitmapImage(byte[] image)
        {
            var bitmapImage = new BitmapImage();
            var memoryStream = new MemoryStream(image);
            bitmapImage.SetSource(memoryStream);
            return bitmapImage;
        }

        public async Task ReadImage()
        {
            var result = await _asyncStorageService.ReadAllBytesAsync("image.jpg");
            ImageSource = ConvertToBitmapImage(result);
        }

        /// <summary>
        /// Reads the text.
        /// </summary>
        /// <returns></returns>
        private async Task ReadText()
        {
            Text = await _asyncStorageService.ReadAllTextAsync("Text.txt");
        }

        /// <summary>
        /// Results the image.
        /// </summary>
        /// <param name="obj">The object.</param>
        private async void ResultImage(Microsoft.Phone.Tasks.PhotoResult obj)
        {
            await _asyncStorageService.WriteAllBytesAsync("image.jpg", obj.ChosenPhoto.ToArray());
        }

        /// <summary>
        /// Writes the image.
        /// </summary>
        private void WriteImage()
        {
            ImageSource = null;
            _cameraCaptureService.Show(ResultImage);
        }

        /// <summary>
        /// Writes the text.
        /// </summary>
        private async Task WriteText()
        {
            Text = string.Empty;
            await _asyncStorageService.WriteAllTextAsync("Text.txt", "This is a text.");
        }
    }

for connect view model with the page we should add the ViewModelLocator instance in App.xaml:

    <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True"  />

and add the binding in main page like:

  DataContext="{Binding MainViewModel, 
                        Source={StaticResource Locator}}"

The MainPage.xaml can be the following:

<phone:PhoneApplicationPage x:Class="CimbalinoSample.MainPage"
                            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                            xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
                            xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
                            DataContext="{Binding MainViewModel,
                                                  Source={StaticResource Locator}}"
                            FontFamily="{StaticResource PhoneFontFamilyNormal}"
                            FontSize="{StaticResource PhoneFontSizeNormal}"
                            Foreground="{StaticResource PhoneForegroundBrush}"
                            Orientation="Portrait"
                            SupportedOrientations="Portrait"
                            shell:SystemTray.IsVisible="True"
                            mc:Ignorable="d">

    <!--  LayoutRoot is the root grid where all page content is placed  -->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <!--  TitlePanel contains the name of the application and page title  -->
        <StackPanel x:Name="TitlePanel"
                    Grid.Row="0"
                    Margin="12,17,0,28">
            <TextBlock Margin="12,0"
                       Style="{StaticResource PhoneTextTitle2Style}"
                       Text="Cimbalino Sample" />
            <TextBlock Margin="9,-7,0,0"
                       Style="{StaticResource PhoneTextTitle2Style}"
                       Text="AsyncStorageService" />
        </StackPanel>

        <!--  ContentPanel - place additional content here  -->
        <Grid x:Name="ContentPanel"
              Grid.Row="1"
              Margin="12,0,12,0">
            <Image Source="{Binding ImageSource}" Height="243" 
                   Stretch="Uniform"
                   VerticalAlignment="Bottom" />
            <Button Height="82"
                    VerticalAlignment="Top"
                    Command="{Binding WriteTextCommand}"
                    Content="Write text" />
            <Button Height="82"
                    Margin="0,82,0,0"
                    VerticalAlignment="Top"
                    Command="{Binding ReadTextCommand}"
                    Content="Read text" />
            <TextBlock Width="436"
                       Margin="10,182,0,424"
                       HorizontalAlignment="Left"
                       Text="{Binding Text}"
                       TextWrapping="Wrap" />
            <Button Margin="0,238,0,317"
                    Command="{Binding WriteImageCommand}"
                    Content="Write Image" />

            <Button Margin="0,312,0,243"
                    Command="{Binding ReadImageCommand}"
                    Content="Read Image" />

        </Grid>

    </Grid>

</phone:PhoneApplicationPage>

 

How to use Cimbalino Windows Phone Toolkit – ApplicationSettingsService

This samples has the goal to show how to use Cimbalino Windows Phone Toolkit Background – ApplicationSettingsService.

Introduction

Cimbalino Windows Phone Toolkit is a set of useful and powerful items that will help you build your Silverlight applications for Windows Phone. The Toolkit is divided in projects which deliver different features. The base project (Cimbalino.Phone.Toolkit) contains base MVVM services, some very useful converters, helper classes and extension methods, and the bindable Application Bar behaviour.

Cimbalino.Phone.Toolkit.Background is a MVVM compatible services for background agents.

Building Sample
This packages is available in Nuget Package Manager (for both targets) and can be installed, for more details see: How to install Cimbalino Windows Phone Toolkit packages.

The sample for this article uses MVVM Light for help in MVVM pattern implementation, for more details see:

Let’s start!

We should register each service in ViewModelLocator, as following:

using System.Windows;

    using Cimbalino.Phone.Toolkit.Services;

    /// <summary>
    /// This class contains static references to all the view models in the
    /// application and provides an entry point for the bindings.
    /// </summary>
    public class ViewModelLocator
    {
        /// <summary>
        /// Initializes a new instance of the ViewModelLocator class.
        /// </summary>
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            if (!SimpleIoc.Default.IsRegistered<IApplicationSettingsService>())
            {
                SimpleIoc.Default.Register<IApplicationSettingsService, ApplicationSettingsService>();
            }

            SimpleIoc.Default.Register<MainViewModel>();
        }

        public MainViewModel MainViewModel
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }

        public static void Cleanup()
        {
            var viewModelLocator = (ViewModelLocator)Application.Current.Resources["Locator"];
            viewModelLocator.MainViewModel.Cleanup();
        }
    }

Then we should implement the MainViewModel as following:

 

using Cimbalino.Phone.Toolkit.Services;
    using GalaSoft.MvvmLight;

    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// The application settings service
        /// </summary>
        private readonly IApplicationSettingsService _applicationSettingsService;

        /// <summary>
        /// The content
        /// </summary>
        private string _content;

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel(IApplicationSettingsService applicationSettingsService)
        {
             Content = "Off";
            _applicationSettingsService = applicationSettingsService;
            PropertyChanged += MainViewModel_PropertyChanged;
        }

        /// <summary>
        /// Gets or sets the content.
        /// </summary>
        /// <value>
        /// The content.
        /// </value>
        public string Content
        {
            get
            {
                return _content;
            }
            set
            {
                Set("Content", ref _content, value);
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether [is checked].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is checked]; otherwise, <c>false</c>.
        /// </value>
        public bool IsChecked
        {
            get
            {
                return _applicationSettingsService.Get<bool>("IsGPSOn");
            }
            set
            {
                _applicationSettingsService.Set("IsGPSOn", value);
                _applicationSettingsService.Save();
                RaisePropertyChanged("IsChecked");
            }
        }

        /// <summary>
        /// Handles the PropertyChanged event of the MainViewModel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.PropertyChangedEventArgs"/> instance containing the event data.</param>
        public void MainViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsChecked")
            {
                Content = IsChecked ? "On" : "Off";
            }
        }

        public override void Cleanup()
        {
            base.Cleanup();
            PropertyChanged -= MainViewModel_PropertyChanged;
        }
    }

for connect view model with the page we should add the ViewModelLocator instance in App.xaml:   

    <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True"  />

and add the binding in main page like: 

  DataContext="{Binding MainViewModel, 
                        Source={StaticResource Locator}}"

The MainPage.xaml can be the following:

<phone:PhoneApplicationPage x:Class="CimbalinoSample.MainPage"
                            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                            xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
                            xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
                            xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
                            FontFamily="{StaticResource PhoneFontFamilyNormal}"
                            FontSize="{StaticResource PhoneFontSizeNormal}"
                            Foreground="{StaticResource PhoneForegroundBrush}"
                            Orientation="Portrait"
                            DataContext="{Binding MainViewModel, 
                                                  Source={StaticResource Locator}}"
                            SupportedOrientations="Portrait"
                            shell:SystemTray.IsVisible="True"
                            mc:Ignorable="d">

    <!--  LayoutRoot is the root grid where all page content is placed  -->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <!--  TitlePanel contains the name of the application and page title  -->
        <StackPanel x:Name="TitlePanel"
                    Grid.Row="0"
                    Margin="12,17,0,28">
            <TextBlock Margin="12,0"
                       Style="{StaticResource PhoneTextTitle2Style}"
                       Text="Cimbalino Sample" />
            <TextBlock Margin="9,-7,0,0"
                       Style="{StaticResource PhoneTextTitle2Style}"
                       Text="ApplicationSettingsService" />
        </StackPanel>

        <!--  ContentPanel - place additional content here  -->
        <Grid x:Name="ContentPanel"
              Grid.Row="1"
              Margin="12,0,12,0">
            <toolkit:ToggleSwitch Header="GPS" 
                                  Content="{Binding Content}" 
                                  IsChecked="{Binding IsChecked, Mode=TwoWay}" />
        </Grid>

    </Grid>

</phone:PhoneApplicationPage>

 

SQLite for Windows Store Apps Sample [Windows 8.1]

This article has the goal to show a sample about SQLite database for Windows Store Apps (Windows 8.1).

Before start we need to install the SQLite for Windows Runtime (Windows 8.1).

Go to Tools> Extensions and Updates…> Online> and search by SQLite for Windows Runtime (Windows 8.1) and install it.
extensions

Then we need to configure the solution for a specific architectures.

Right click in solution > Properties >Configuration Properties and select an architecture, for example x86.
configuration

Now we can add the reference for SQLite for Windows Runtime (Windows 8.1) and Visual C++ Runtime Package.

Do a right click in Reference>Add References…>Windows>Extensions and select SQLite for Windows Runtime (Windows 8.1) and Visual C++ Runtime Package.
references

 

Now we can start the sample, which uses MVVM Ligh.

Let’s start!

In App.xaml.cs define the property for connection:

        /// <summary>
        /// Gets or sets the connection.
        /// </summary>
        /// <value>
        /// The connection.
        /// </value>
        public static SQLiteAsyncConnection Connection { get; set; }

and create the database when the application starts, if the database not exists:

 protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            var rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
                DataService.CreateDbAsync();
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }

 

which DataService.CreateDbAsync is the following:

        /// <summary>
        /// Creates the DB.
        /// </summary>
        public static async void CreateDbAsync()
        {
            App.Connection = new SQLiteAsyncConnection("UniversityDB.db");

            var universityTask = App.Connection.CreateTableAsync<University>();
            var studentTask = App.Connection.CreateTableAsync<Student>();

            await Task.WhenAll(new Task[] { universityTask, studentTask });
        }

We should register each service in ViewModelLocator, as following:

 using GalaSoft.MvvmLight.Ioc;

    using Microsoft.Practices.ServiceLocation;

    using SQLLiteSample.Service;

    using SQLiteSampleForWindowsStore.Service;

    /// <summary>
    /// This class contains static references to all the view models in the
    /// application and provides an entry point for the bindings.
    /// </summary>
    public class ViewModelLocator
    {
        /// <summary>
        /// Initializes a new instance of the ViewModelLocator class.
        /// </summary>
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            if (!SimpleIoc.Default.IsRegistered<IDataService>())
            {
                SimpleIoc.Default.Register<IDataService, DataService>();
            }

            if (!SimpleIoc.Default.IsRegistered<INavigationService>())
            {
                SimpleIoc.Default.Register<INavigationService, NavigationService>();
            }

            if (!SimpleIoc.Default.IsRegistered<IMessageBoxService>())
            {
                SimpleIoc.Default.Register<IMessageBoxService, MessageBoxService>();
            }

            SimpleIoc.Default.Register<MainViewModel>();
            SimpleIoc.Default.Register<EditUniversityViewModel>();
            SimpleIoc.Default.Register<CreateUniversityViewModel>();
            SimpleIoc.Default.Register<SeeStudentsViewModel>();
            SimpleIoc.Default.Register<EditStudentViewModel>();
            SimpleIoc.Default.Register<CreateStudentViewModel>();
        }

        /// <summary>
        /// Gets the edit student view model.
        /// </summary>
        /// <value>
        /// The edit student view model.
        /// </value>
        public EditStudentViewModel EditStudentViewModel
        {
            get
            {
                return ServiceLocator.Current.GetInstance<EditStudentViewModel>();
            }
        }

        /// <summary>
        /// Gets the create student view model.
        /// </summary>
        /// <value>
        /// The create student view model.
        /// </value>
        public CreateStudentViewModel CreateStudentViewModel
        {
            get
            {
                return ServiceLocator.Current.GetInstance<CreateStudentViewModel>();
            }
        }

        /// <summary>
        /// Gets the main.
        /// </summary>
        public MainViewModel Main
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }

        /// <summary>
        /// Gets the edit university view model.
        /// </summary>
        public EditUniversityViewModel EditUniversityViewModel
        {
            get
            {
                return ServiceLocator.Current.GetInstance<EditUniversityViewModel>();
            }
        }

        /// <summary>
        /// Gets the create university view model.
        /// </summary>
        public CreateUniversityViewModel CreateUniversityViewModel
        {
            get
            {
                return ServiceLocator.Current.GetInstance<CreateUniversityViewModel>();
            }
        }

        /// <summary>
        /// Gets the see students view model.
        /// </summary>
        /// <value>
        /// The see students view model.
        /// </value>
        public SeeStudentsViewModel SeeStudentsViewModel
        {
            get
            {
                return ServiceLocator.Current.GetInstance<SeeStudentsViewModel>();
            }
        }

        public static void Cleanup()
        {
            // TODO Clear the ViewModels
        }
    }

Where IDataService represents a service that allow to manage the database operations.

The interface is the following:

  public interface IDataService
    {
        /// <summary>
        /// Deletes the student.
        /// </summary>
        /// <param name="selectedStudent">The selected student.</param>
        /// <returns></returns>
        Task DeleteStudentAsync(Student selectedStudent);

        /// <summary>
        /// Deletes the university.
        /// </summary>
        /// <param name="selectedUniversity">The selected university.</param>
        /// <returns></returns>
        Task DeleteUniversityAsync(University selectedUniversity);

        /// <summary>
        /// Loads the studentby id.
        /// </summary>
        /// <param name="guid">The GUID.</param>
        /// <returns></returns>
        Task<Student> LoadStudentbyIdAsync(string guid);

        /// <summary>
        /// The load student.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        Task<IList<Student>> LoadStudentsAsync();

        /// <summary>
        /// Loads the students by university.
        /// </summary>
        /// <param name="University">The university.</param>
        /// <returns></returns>
        Task<IList<Student>> LoadStudentsByUniversityAsync(University University);

        /// <summary>
        /// Loads the university.
        /// </summary>
        /// <returns></returns>
        Task<IList<University>> LoadUniversitiesAsync();

        /// <summary>
        /// The load university by id.
        /// </summary>
        /// <param name="guid">
        /// The guid.
        /// </param>
        /// <returns>
        /// The <see cref="University"/>.
        /// </returns>
        Task<University> LoadUniversityByIdAsync(string guid);

        /// <summary>
        /// The save student.
        /// </summary>
        /// <param name="newStudent">
        /// The new student.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        Task SaveStudentAsync(Student newStudent);

        /// <summary>
        /// Saves the university.
        /// </summary>
        /// <param name="newUniversity">The new university.</param>
        /// <returns></returns>
        Task SaveUniversityAsync(University newUniversity);

        /// <summary>
        /// Updates the student.
        /// </summary>
        /// <param name="selectedStudent">The selected student.</param>
        /// <returns></returns>
        Task UpdateStudentAsync(Student selectedStudent);

        /// <summary>
        /// Updates the university.
        /// </summary>
        /// <param name="selectedUniversity">The selected university.</param>
        /// <returns></returns>
        Task UpdateUniversityAsync(University selectedUniversity);

        /// <summary>
        /// Loads the students by university async.
        /// </summary>
        /// <param name="guid">The GUID.</param>
        /// <returns></returns>
        Task<IList<Student>> LoadStudentsByUniversityAsync(Guid guid);
    }

and its implementation is:

   public class DataService : IDataService
    {
        /// <summary>
        /// Creates the DB.
        /// </summary>
        public static async void CreateDbAsync()
        {
            App.Connection = new SQLiteAsyncConnection("UniversityDB.db");

            var universityTask = App.Connection.CreateTableAsync<University>();
            var studentTask = App.Connection.CreateTableAsync<Student>();

            await Task.WhenAll(new Task[] { universityTask, studentTask });
        }

        /// <summary>
        /// Deletes the student.
        /// </summary>
        /// <param name="selectedStudent">The selected student.</param>
        /// <returns>The <see cref="Task" />.</returns>
        public async Task DeleteStudentAsync(Student selectedStudent)
        {
            await App.Connection.DeleteAsync(selectedStudent);
        }

        /// <summary>
        /// Deletes the university.
        /// </summary>
        /// <param name="selectedUniversity">The selected university.</param>
        /// <returns>The <see cref="Task" />.</returns>
        public async Task DeleteUniversityAsync(University selectedUniversity)
        {
           var students = await LoadStudentsByUniversityAsync(selectedUniversity);
           await App.Connection.RunInTransactionAsync(async (SQLiteConnection connection) =>
           {
               foreach (var student in students)
               {
                   DeleteStudentAsync(student);
               }

               App.Connection.DeleteAsync(selectedUniversity);
           }); 
        }

        /// <summary>
        /// Loads the studentby id.
        /// </summary>
        /// <param name="guid">The GUID.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">Student not found.</exception>
        public async Task<Student> LoadStudentbyIdAsync(string guid)
        {
            var result = await App.Connection.QueryAsync<Student>(string.Format("select * from Student where Id='{0}'", guid));
            return result.FirstOrDefault();
        }

        /// <summary>
        /// The load student.
        /// </summary>
        /// <returns>
        /// The <see cref="Task" />.
        /// </returns>
        public async Task<IList<Student>> LoadStudentsAsync()
        {
            return await App.Connection.Table<Student>().ToListAsync();
        }

        /// <summary>
        /// Loads the students by university.
        /// </summary>
        /// <param name="university">The university.</param>
        /// <returns></returns>
        public async Task<IList<Student>> LoadStudentsByUniversityAsync(University university)
        {
            return await LoadStudentsByUniversityAsync(university.Id);
        }

        /// <summary>
        /// The load university.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task<IList<University>> LoadUniversitiesAsync()
        {
            return await App.Connection.Table<University>().ToListAsync();
        }

        /// <summary>
        /// The load university by id.
        /// </summary>
        /// <param name="guid">
        /// The guid.
        /// </param>
        /// <returns>
        /// The <see cref="University"/>.
        /// </returns>
        /// <exception cref="Exception">
        /// </exception>
        public async Task<University> LoadUniversityByIdAsync(string guid)
        {
            var result = await App.Connection.QueryAsync<University>(string.Format("select * from University where Id='{0}'", guid));
            return result.FirstOrDefault();
        }

        /// <summary>
        /// The save student.
        /// </summary>
        /// <param name="newStudent">The new student.</param>
        /// <returns>
        /// The <see cref="Task" />.
        /// </returns>
        public async Task SaveStudentAsync(Student newStudent)
        {
            await App.Connection.InsertAsync(newStudent);
        }

        /// <summary>
        /// Saves the university.
        /// </summary>
        /// <param name="newUniversity">The new university.</param>
        /// <returns>The <see cref="Task" />.</returns>
        public async Task SaveUniversityAsync(University newUniversity)
        {
            await App.Connection.InsertAsync(newUniversity);
        }

        /// <summary>
        /// Updates the student.
        /// </summary>
        /// <param name="selectedStudent">The selected student.</param>
        /// <returns>The <see cref="Task" />.</returns>
        public async Task UpdateStudentAsync(Student selectedStudent)
        {
            var existingContact = await App.Connection.FindAsync<Student>(s => s.Id == selectedStudent.Id);
            if (existingContact != null)
            {
                await App.Connection.UpdateAsync(selectedStudent);
            }
        }

        /// <summary>
        /// Updates the university.
        /// </summary>
        /// <param name="selectedUniversity">The selected university.</param>
        /// <returns>The <see cref="Task" />.</returns>
        public async Task UpdateUniversityAsync(University selectedUniversity)
        {
            var existingContact = await App.Connection.FindAsync<University>(u => u.Id == selectedUniversity.Id);
            if (existingContact != null)
            {
                await App.Connection.UpdateAsync(selectedUniversity);
            }
        }

        /// <summary>
        /// The load student by university.
        /// </summary>
        /// <param name="guid">
        /// The guid.
        /// </param>
        /// <returns>
        /// The <see>
        ///         <cref>IList</cref>
        ///     </see>
        ///     .
        /// </returns>
        public async Task<IList<Student>> LoadStudentsByUniversityAsync(Guid guid)
        {
            var result = await App.Connection.QueryAsync<Student>(string.Format("select * from Student where UniversityId='{0}'", guid));
            return result.ToList();
        }
    }
}

The complete sample can be found here.
Source Code Files

  • ViewModelLocator.cs has the ViewModelLocator class that help to binding the view model with the view.
  • MainViewModel.cs has the MainViewModel class that represents the view model for main page.
  • CreateStudentViewModel.cs has the CreateStudentViewModel class that represents the view model for the  create student page.
  • CreateUniversityViewModel.cs has the CreateUniversityViewModelclass that represents the view model for the create university page.
  • EditStudentViewModel.cs has the EditStudentViewModel that represents the view model for edit student page.
  • EditUniversityViewModel.cs has the EditUniversityViewModel that represents the view model for edit university page.
  • SeeStudentsViewModel.cs has the SeeStudentsViewModel that represents the view model for see students page.
  • MainPage.xaml and MainPage.xaml.cs represents the main page.
  • CreateStudentPage.xaml represents the create student page.
  • CreateUniversityPage.xaml  represents the create university page.
  • EditStudentPage.xaml  represents the edit student page.
  • EditUniversityPage.xaml represents the edit university page.
  • SeeStudentsPage.xaml represents the see student page.

 Source code:

https://github.com/saramgsilva/MyMSDNSamples/tree/master/src

SQLite for Windows Phone Sample

This article has the goal to show a sample about SQLite database for Windows Phone.

Before start is recommended to read the following article: Using the SQLite database engine with Windows Phone 8 apps

This sample uses MVVM Light and Cimbalino Windows Phone Toolkit. See more about it in:

Let’s start the sample:

In App.xaml.cs define the property for connection:

    /// <summary>
        /// Gets or sets the connection.
        /// </summary>
        /// <value>
        /// The connection.
        /// </value>
        public static SQLiteAsyncConnection Connection { get; set; }

and create the database when the application starts, if the database not exists:

private async void Application_Launching(object sender, LaunchingEventArgs e)
        {
            try
            {
                await ApplicationData.Current.LocalFolder.GetFileAsync("UniversityDB.db");
                Connection = new SQLiteAsyncConnection("UniversityDB.db");
            }
            catch (FileNotFoundException)
            {
                DataService.CreateDbAsync();
            }
        }

which DataService.CreateDbAsync is the following:

/// <summary>
        /// Creates the DB.
        /// </summary>
        public static async void CreateDbAsync()
        {
            App.Connection = new SQLiteAsyncConnection("UniversityDB.db");

            var universityTask = App.Connection.CreateTableAsync<University>();
            var studentTask = App.Connection.CreateTableAsync<Student>();

            await Task.WhenAll(new Task[] { universityTask, studentTask });
        }

We should register each service in ViewModelLocator, as following:

using Cimbalino.Phone.Toolkit.Services;

    using GalaSoft.MvvmLight.Ioc;

    using Microsoft.Practices.ServiceLocation;

    using SQLLiteSample.Service;

    /// <summary>
    /// This class contains static references to all the view models in the
    /// application and provides an entry point for the bindings.
    /// </summary>
    public class ViewModelLocator
    {
        /// <summary>
        /// Initializes a new instance of the ViewModelLocator class.
        /// </summary>
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            if (!SimpleIoc.Default.IsRegistered<IDataService>())
            {
                SimpleIoc.Default.Register<IDataService, DataService>();
            }

            if (!SimpleIoc.Default.IsRegistered<INavigationService>())
            {
                SimpleIoc.Default.Register<INavigationService, NavigationService>();
            }

            if (!SimpleIoc.Default.IsRegistered<IMessageBoxService>())
            {
                SimpleIoc.Default.Register<IMessageBoxService, MessageBoxService>();
            }

            SimpleIoc.Default.Register<MainViewModel>();
            SimpleIoc.Default.Register<EditUniversityViewModel>();
            SimpleIoc.Default.Register<CreateUniversityViewModel>();
            SimpleIoc.Default.Register<SeeStudentsViewModel>();
            SimpleIoc.Default.Register<EditStudentViewModel>();
            SimpleIoc.Default.Register<CreateStudentViewModel>();
        }

        /// <summary>
        /// Gets the edit student view model.
        /// </summary>
        /// <value>
        /// The edit student view model.
        /// </value>
        public EditStudentViewModel EditStudentViewModel
        {
            get
            {
                return ServiceLocator.Current.GetInstance<EditStudentViewModel>();
            }
        }

        /// <summary>
        /// Gets the create student view model.
        /// </summary>
        /// <value>
        /// The create student view model.
        /// </value>
        public CreateStudentViewModel CreateStudentViewModel
        {
            get
            {
                return ServiceLocator.Current.GetInstance<CreateStudentViewModel>();
            }
        }

        /// <summary>
        /// Gets the main.
        /// </summary>
        public MainViewModel Main
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }

        /// <summary>
        /// Gets the edit university view model.
        /// </summary>
        public EditUniversityViewModel EditUniversityViewModel
        {
            get
            {
                return ServiceLocator.Current.GetInstance<EditUniversityViewModel>();
            }
        }

        /// <summary>
        /// Gets the create university view model.
        /// </summary>
        public CreateUniversityViewModel CreateUniversityViewModel
        {
            get
            {
                return ServiceLocator.Current.GetInstance<CreateUniversityViewModel>();
            }
        }

        /// <summary>
        /// Gets the see students view model.
        /// </summary>
        /// <value>
        /// The see students view model.
        /// </value>
        public SeeStudentsViewModel SeeStudentsViewModel
        {
            get
            {
                return ServiceLocator.Current.GetInstance<SeeStudentsViewModel>();
            }
        }

        public static void Cleanup()
        {
            // TODO Clear the ViewModels
        }
    }

Where IDataService represents a service that allow to manage the database operations. The interface is the following:

  using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;

    using SQLLiteSample.Model;

    /// <summary>
    /// The data service interface
    /// </summary>
    public interface IDataService
    {
        /// <summary>
        /// Deletes the student.
        /// </summary>
        /// <param name="selectedStudent">The selected student.</param>
        /// <returns></returns>
        Task DeleteStudentAsync(Student selectedStudent);

        /// <summary>
        /// Deletes the university.
        /// </summary>
        /// <param name="selectedUniversity">The selected university.</param>
        /// <returns></returns>
        Task DeleteUniversityAsync(University selectedUniversity);

        /// <summary>
        /// Loads the studentby id.
        /// </summary>
        /// <param name="guid">The GUID.</param>
        /// <returns></returns>
        Task<Student> LoadStudentbyIdAsync(string guid);

        /// <summary>
        /// The load student.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        Task<IList<Student>> LoadStudentsAsync();

        /// <summary>
        /// Loads the students by university.
        /// </summary>
        /// <param name="University">The university.</param>
        /// <returns></returns>
        Task<IList<Student>> LoadStudentsByUniversityAsync(University University);

        /// <summary>
        /// Loads the university.
        /// </summary>
        /// <returns></returns>
        Task<IList<University>> LoadUniversitiesAsync();

        /// <summary>
        /// The load university by id.
        /// </summary>
        /// <param name="guid">
        /// The guid.
        /// </param>
        /// <returns>
        /// The <see cref="University"/>.
        /// </returns>
        Task<University> LoadUniversityByIdAsync(string guid);

        /// <summary>
        /// The save student.
        /// </summary>
        /// <param name="newStudent">
        /// The new student.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        Task SaveStudentAsync(Student newStudent);

        /// <summary>
        /// Saves the university.
        /// </summary>
        /// <param name="newUniversity">The new university.</param>
        /// <returns></returns>
        Task SaveUniversityAsync(University newUniversity);

        /// <summary>
        /// Updates the student.
        /// </summary>
        /// <param name="selectedStudent">The selected student.</param>
        /// <returns></returns>
        Task UpdateStudentAsync(Student selectedStudent);

        /// <summary>
        /// Updates the university.
        /// </summary>
        /// <param name="selectedUniversity">The selected university.</param>
        /// <returns></returns>
        Task UpdateUniversityAsync(University selectedUniversity);

        /// <summary>
        /// Loads the students by university async.
        /// </summary>
        /// <param name="guid">The GUID.</param>
        /// <returns></returns>
        Task<IList<Student>> LoadStudentsByUniversityAsync(Guid guid);
    }

and its implementation is:

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;

    using SQLite;

    using SQLLiteSample.Model;

    /// <summary>
    /// The data service
    /// </summary>
    public class DataService : IDataService
    {
        /// <summary>
        /// Creates the DB.
        /// </summary>
        public static async void CreateDbAsync()
        {
            App.Connection = new SQLiteAsyncConnection("UniversityDB.db");

            var universityTask = App.Connection.CreateTableAsync<University>();
            var studentTask = App.Connection.CreateTableAsync<Student>();

            await Task.WhenAll(new Task[] { universityTask, studentTask });
        }

        /// <summary>
        /// Deletes the student.
        /// </summary>
        /// <param name="selectedStudent">The selected student.</param>
        /// <returns>The <see cref="Task" />.</returns>
        public async Task DeleteStudentAsync(Student selectedStudent)
        {
            await App.Connection.DeleteAsync(selectedStudent);
        }

        /// <summary>
        /// Deletes the university.
        /// </summary>
        /// <param name="selectedUniversity">The selected university.</param>
        /// <returns>The <see cref="Task" />.</returns>
        public async Task DeleteUniversityAsync(University selectedUniversity)
        {
            var students = await LoadStudentsByUniversityAsync(selectedUniversity);
            await App.Connection.RunInTransactionAsync(async (SQLiteConnection connection) =>
            {
                foreach (var student in students)
                {
                    DeleteStudentAsync(student);
                }

                App.Connection.DeleteAsync(selectedUniversity);
            }); 
        }

        /// <summary>
        /// Loads the studentby id.
        /// </summary>
        /// <param name="guid">The GUID.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">Student not found.</exception>
        public async Task<Student> LoadStudentbyIdAsync(string guid)
        {
            var result = await App.Connection.QueryAsync<Student>(string.Format("select * from Student where Id='{0}'", guid));
            return result.FirstOrDefault();
        }

        /// <summary>
        /// The load student.
        /// </summary>
        /// <returns>
        /// The <see cref="Task" />.
        /// </returns>
        public async Task<IList<Student>> LoadStudentsAsync()
        {
            return await App.Connection.Table<Student>().ToListAsync();
        }

        /// <summary>
        /// Loads the students by university.
        /// </summary>
        /// <param name="university">The university.</param>
        /// <returns></returns>
        public async Task<IList<Student>> LoadStudentsByUniversityAsync(University university)
        {
            return await LoadStudentsByUniversityAsync(university.Id);
        }

        /// <summary>
        /// The load university.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task<IList<University>> LoadUniversitiesAsync()
        {
            return await App.Connection.Table<University>().ToListAsync();
        }

        /// <summary>
        /// The load university by id.
        /// </summary>
        /// <param name="guid">
        /// The guid.
        /// </param>
        /// <returns>
        /// The <see cref="University"/>.
        /// </returns>
        /// <exception cref="Exception">
        /// </exception>
        public async Task<University> LoadUniversityByIdAsync(string guid)
        {
            var result = await App.Connection.QueryAsync<University>(string.Format("select * from University where Id='{0}'", guid));
            return result.FirstOrDefault();
        }

        /// <summary>
        /// The save student.
        /// </summary>
        /// <param name="newStudent">The new student.</param>
        /// <returns>
        /// The <see cref="Task" />.
        /// </returns>
        public async Task SaveStudentAsync(Student newStudent)
        {
            await App.Connection.InsertAsync(newStudent);
        }

        /// <summary>
        /// Saves the university.
        /// </summary>
        /// <param name="newUniversity">The new university.</param>
        /// <returns>The <see cref="Task" />.</returns>
        public async Task SaveUniversityAsync(University newUniversity)
        {
            await App.Connection.InsertAsync(newUniversity);
        }

        /// <summary>
        /// Updates the student.
        /// </summary>
        /// <param name="selectedStudent">The selected student.</param>
        /// <returns>The <see cref="Task" />.</returns>
        public async Task UpdateStudentAsync(Student selectedStudent)
        {
            var existingContact = await App.Connection.FindAsync<Student>(s => s.Id == selectedStudent.Id);
            if (existingContact != null)
            {
                await App.Connection.UpdateAsync(selectedStudent);
            }
        }

        /// <summary>
        /// Updates the university.
        /// </summary>
        /// <param name="selectedUniversity">The selected university.</param>
        /// <returns>The <see cref="Task" />.</returns>
        public async Task UpdateUniversityAsync(University selectedUniversity)
        {
            var existingContact = await App.Connection.FindAsync<University>(u => u.Id == selectedUniversity.Id);
            if (existingContact != null)
            {
                await App.Connection.UpdateAsync(selectedUniversity);
            }
        }

        /// <summary>
        /// The load student by university.
        /// </summary>
        /// <param name="guid">
        /// The guid.
        /// </param>
        /// <returns>
        /// The <see cref="IList"/>.
        /// </returns>
        public async Task<IList<Student>> LoadStudentsByUniversityAsync(Guid guid)
        {
            var result = await App.Connection.QueryAsync<Student>(string.Format("select * from Student where UniversityId='{0}'", guid));
            return result.ToList();
        }
    }

The complete sample can be found here.

Source Code Files

  • ViewModelLocator.cs has the ViewModelLocator class that help to binding the view model with the view.
  • MainViewModel.cs has the MainViewModel class that represents the view model for main page.
  • CreateStudentViewModel.cs has the CreateStudentViewModel class that represents the view model for the  create student page.
  • CreateUniversityViewModel.cs has the CreateUniversityViewModelclass that represents the view model for the create university page.
  • EditStudentViewModel.cs has the EditStudentViewModel that represents the view model for edit student page.
  • EditUniversityViewModel.cs has the EditUniversityViewModel that represents the view model for edit university page.
  • SeeStudentsViewModel.cs has the SeeStudentsViewModel that represents the view model for see students page.
  • MainPage.xaml and MainPage.xaml.cs represents the main page.
  • CreateStudentPage.xaml represents the create student page.
  • CreateUniversityPage.xaml  represents the create university page.
  • EditStudentPage.xaml  represents the edit student page.
  • EditUniversityPage.xaml represents the edit university page.
  • SeeStudentsPage.xaml represents the see student page.