As we know, WinJS applications are built using HTML/JS/CSS. And for a complete application, we will need async operations like sqlite database operations, web-service calls, and other native XML read-write, and File read-write which cannot be done directly in WinJS applications.
So we have to use Windows Runtime Component to access Native C# methods as discussed in my previous article: WinJS application with Windows Runtime Component to access native C# code.
For SQLite operation, we have to use Class Library.
Step 1
Firstly create a WinJS project.
Step 2
We need to do following things as discussed in my previous blog. Please have a look at my previous article.
- Add a Windows Runtime Component project and name it ‘WinRuntimes’
- Delete default class ‘Class1.cs’
- Add a new class and name it ‘Service’
- Add WinRuntimes reference in WinJS project
- Build the project
Step 3
After you are done with adding Runtime Component, we have to add Class Library for SQLite.
Click File, Add, New Project, Visual C#, Windows, Class Library (Windows 8.1). Name it SQLiteLibrary and click OK.
Step 4
Now we have to add a reference ’SQLite for Windows Runtime’ and ‘sqlite-net’ in Class Library. For this, Right Click on Reference and Manage Nuget Packages
From the Nuget package manager, we have to install two things:
- sqlite-net
- SQLite for Windows Runtime (Alternatively, you can download this from here.Install it and restart Visual Studio)
Step 5
After downloading and installing sqlite libraries, we have to add reference in Class Library:
Step 6
We need to change the Build Configuration to x86.
Go to Build > Configuration Menu and change Any CPU to x86 inside Active solution platform.
Step 7
In WinRuntimes project, right click on References and Add project SQLiteLibray as reference.
Step 8
Now in the WinJS (SQLiteOperations) project add reference of WinRuntimes. Right Click on References and add WinRuntimes as reference.
Step 9
Add a script.js file and reference it in default.html:
Now in default.html, lets add following things:
- Button to create a database
- Button to insert into database
- Two input fields to insert data into database
- Button to read from database
- Button to update
- Button to delete
Complete HTML code:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title>SQLiteOperations</title>
-
- <link href="//Microsoft.WinJS.2.0/css/ui-dark.css" rel="stylesheet" />
- <script src="//Microsoft.WinJS.2.0/js/base.js"></script>
- <script src="//Microsoft.WinJS.2.0/js/ui.js"></script>
-
- <link href="/css/default.css" rel="stylesheet" />
- <script src="/js/default.js"></script>
- <script src="js/script.js"></script>
- </head>
- <body>
- <p>SQLite Operations</p>
- <button onclick="createDatabase()">Create Database</button>
- <br />
- <br />
- <input placeholder="Country Name" id="name" />
- <input placeholder="Capital City" id="city"/>
- <button onclick="insertRecords()">Insert into Database</button>
- <br />
- <br />
- <button onclick="readDatabase()">Read from Database</button>
- <br />
- <div id="content"></div>
- <br />
- <br />
- <button onclick="updateRecord()">Update records</button>
- <br />
- <br />
- <button onclick="deleteRecord()">Delete records from Database</button>
- <br />
- <br />
- </body>
- </html>
Step 10
We add a Database class in WinRuntimes project and we write all our CRUD operations code where we have respective IAsyncOperation for Create, Read, Update, Insert and Delete operations.
Creating Database
- [Table("Countries")]
- public sealed class Country
- {
- [PrimaryKey, AutoIncrement]
- public int id { get; set; }
-
- public string Name { get; set; }
-
- public string CapitalCity { get; set; }
-
- }
- public IAsyncOperation<string> CreateDatabase()
- {
- return CreateDatabaseHelper().AsAsyncOperation();
- }
- private async Task<string> CreateDatabaseHelper()
- {
- try
- {
- SQLiteAsyncConnection connection = new SQLiteAsyncConnection(dbName);
- await connection.CreateTableAsync<Country>();
- return "success";
- }
- catch (Exception ex)
- {
- return "fail";
- }
- }
Inserting into Database
- public IAsyncOperation<string> InsertRecords(string countryName, string capitalCity)
- {
- return InsertRecordsHelper(countryName, capitalCity).AsAsyncOperation();
- }
- private async Task<string> InsertRecordsHelper(string countryName, string capitalCity)
- {
- try
- {
- SQLiteAsyncConnection connection = new SQLiteAsyncConnection(dbName);
- var Country = new Country()
- {
- Name = countryName,
- CapitalCity = capitalCity
- };
- await connection.InsertAsync(Country);
- return "success";
- }
- catch (Exception ex)
- {
- return "fail";
- }
- }
Reading from Database
- public IAsyncOperation<string> ReadDatabase()
- {
- return ReadDatabaseHelper().AsAsyncOperation();
- }
- private async Task<string> ReadDatabaseHelper()
- {
- try
- {
- string countryName = string.Empty;
- string capitalCity = string.Empty;
- SQLiteAsyncConnection dbCon = new SQLiteAsyncConnection(dbName);
- var result = await dbCon.QueryAsync<Country>("Select * from Countries LIMIT 1");
- foreach (var item in result)
- {
- countryName = item.Name;
- capitalCity = item.CapitalCity;
- }
-
- return countryName + "," + capitalCity;
- }
- catch (Exception ex)
- {
- return "fail";
- }
- }
Updating records
- public IAsyncOperation<string> UpdateDatabase()
- {
- return UpdateDatabaseHelper().AsAsyncOperation();
- }
- private async Task<string> UpdateDatabaseHelper()
- {
- try
- {
- SQLiteAsyncConnection dbCon = new SQLiteAsyncConnection(dbName);
- var Country = await dbCon.Table<Country>().Where(country => country.Name.StartsWith("France")).FirstOrDefaultAsync();
-
- if (Country != null)
- {
- Country.CapitalCity = "Paris";
- await dbCon.UpdateAsync(Country);
- }
- return "success";
- }
- catch (Exception ex)
- {
- return "fail";
- }
- }
Complete Code Snippet for Database class
Step 11
In script.js, we create a database object of Database class and call the respective function for Create, Read, Update, Delete. Here we use the then function to achieve asynchronous programming.
Complete code snippet for script.js is:
- var database = new WinRuntimes.Database();
-
- function createDatabase() {
- database.createDatabase().then(function (response) {
- if (response == 'success') {
- var msg = new Windows.UI.Popups.MessageDialog("Successfully created!", "Success");
- msg.showAsync();
- }
- else {
- var msg = new Windows.UI.Popups.MessageDialog("Database creation failed", "Failed");
- msg.showAsync();
- }
- });
- }
-
- function insertRecords() {
- var countryName = document.getElementById("name").value;
- var cityName = document.getElementById("city").value;
- database.insertRecords(countryName, cityName).then(function(response) {
- if (response == 'success') {
- var msg = new Windows.UI.Popups.MessageDialog("Successfully inserted!", "Success");
- msg.showAsync();
- }
- else {
- var msg = new Windows.UI.Popups.MessageDialog("Insert failed", "Failed");
- msg.showAsync();
- }
- });
- }
-
- function readDatabase() {
- database.readDatabase().then(function (response) {
- document.getElementById("content").innerHTML = response;
- });
- }
-
- function updateRecord() {
- database.updateDatabase().then(function (response) {
- if (response == 'success') {
- var msg = new Windows.UI.Popups.MessageDialog("Update success!", "Success");
- msg.showAsync();
- }
- else {
- var msg = new Windows.UI.Popups.MessageDialog("Update failed", "Failed");
- msg.showAsync();
- }
- });
- }
-
- function deleteRecord() {
- database.deleteRecord().then(function (response) {
- if (response == 'success') {
- var msg = new Windows.UI.Popups.MessageDialog("Delete success!", "Success");
- msg.showAsync();
- }
- else {
- var msg = new Windows.UI.Popups.MessageDialog("Delete failed", "Failed");
- msg.showAsync();
- }
- })
- }
Step 12
Run the application. Your application is ready to use SQLite database as a local storage. This is how we interact with the Class Library and Windows Runtime Component with the WinJS project which is built under HTML/JS/CSS.