Tag Archive : Windows

/ Windows

Every good app needs to use a database. This database can be local (present in the app itself), or it can be remote (saved somewhere on the internet). The third option (fairly common) is to use both and then use a synchronisation mechanism between the two databases. In the case of a local database, the best possible option for our apps is to use an SQL database and use the SQLite library. This library can be used on mobile phones and PCs and is present on a multitude of different applications.

Use SQLite in Xamarin

In theory (I tell you later a better way) to add and use a SQL database in Xamarin.Forms you need to install the “sqlite-net-pcl” library in your projects (.netstandard, Android, iOS, UWP) and then create Dependencies Services (one for each platform).

The whole procedure is not particularly complicated, but it takes about half an hour. If you multiply half an hour for each project you are going to create, you will see that the amount of time lost becomes considerable.

After so many projects and many lost hours I decided to create and make available for everyone my library based on “sqlite-net-pcl“.

My library is called MtSql and allows you to add a SQL database to Xamarin apps in few seconds and in an extremely easy way. Going from 30 minutes to a few seconds is no small feat so I’ll explain how.

MTSQL

My library works with Xamarin and Windows, so you can use it in practically every project where you need to use a database. As this is a blog about Xamarin, I show you how it works on this platform.

Here are the steps to use a SQLite database in your Xamarin.Forms project.

  • Right click on your solution and select Manage Nuget Packages for Solution
  • Search for “MarcTron” (so you can see my other plugins too 🙂 ) or directly MTSql. Install MarcTron.Sqlite in your projects (.netstandard, Android, iOS, UWP).
  • Finished!!!! You have nothing else to do, right now you are ready to use a SQL database inside your app. Time taken: few seconds 🙂

How to use MTSQL

Now that the library is installed in your solution, we need to tell our app which database to use, so we need to establish a connection with the database. To do this we have several possibilities:

using MarcTron.Plugin;
...

SQLiteConnection conn = MtSql.Current.GetConnection("yourdbname.db3");

in this case we have established a connection with the “yourdbname.db3” database. If we want to create an asynchronous connection, we can instead write:

SQLiteAsyncConnection conn = MtSql.Current.GetConnectionAsync("yourdbname.db3");

Since version 1.2 of MTSql I have created an additional Helper to make everything even easier, so to establish the connection with your database, you can write:

MtSql.Helper.Initialize("yourdbname.db3");

PLEASE NOTE: You must always initialise the database with one of the three previous methods before using it.

In my library, to simplify your life, I’ve created a basic template for the tables in your database. This model is called BaseModel (I write it here just to show it to you):

public class BaseModel
{
    [PrimaryKey]
    public string Id { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime UpdatedAt { get; set; }
}

Using it is very simple. For example, if you have a table called User with a Name field, you can write the class that defines it as:

public class User : BaseModel
{
    public string Name{ get; set; }
}

Doing so your table will have not only the Name field but also a primary Id key and two CreatedAt, UpdatedAt dates, which specify when the data has been created and modified (very useful if you want to sort your tables by creation or update date).

The helper I created has inside a method called Save. This method will deal not only with inserting or updating a record within your tables but also creating a GUID for you (if you have not already created it) and updating the value of CreatedAt and UpdatedAt. FANTASTIC!

PLEASE NOTE: The Save method inserts an object if its primary key value is not present in the table while updating it if its value is already in the table.

You don’t have to use the BaseModel class but I suggest you to do so and now I’ll show you why.

An Example

Now let’s see a quick example to initialise the database, insert an object and then update it:

MtSql.Helper.Initialize("MyDatabase.db3");
MtSql.Helper.CreateTable<User>();

User user = new User() {Name = "Marco"};
MtSql.Helper.Save(user);

user .Name = "Marco Troncone";
MtSql.Helper.Save(user);

In the first line we have initialised the database (Don’t forget it, it is fundamental to do it).

We then created a User table using the User class written above. At this point we created a user and gave him the name Marco.

When we call the method

MtSql.Helper.Save(user);

since user does not have an Id, the Save method will create one automatically (if you want you can assign one yourself) and will add the user to the table, setting CreatedAt and UpdatedAt to the current time.

At this point we try to change the user name and save the change:

user.Name = "Marco Troncone";
MtSql.Helper.Save(user);

This time user has already an Id and this Id is already present in the table, this time the Save method will not add a new object to the table but will update the current object, automatically updating UpdatedAt. Easy right?

Thanks to the MTSql plugin, in exactly 6 lines of code we have initialised our database, created a table, added an object and modified an object.

Other methods inside the Helper

In the previous example, we’ve seen some helper methods (Initialise, CreateTable, Save), let’s see what the other methods we have:

//To insert a single item inside the table
Insert<TType>(TType item);

//To insert multiple items inside the table
InsertAll<TType>(IEnumerable<TType> items);

//To update an item inside the table
Update<TType>(TType item);

//To find an item inside the table
FirstOrDefault<TType>(Expression<Func<TType, bool>> expression);

//To get from the table the item with Id itemId
GetFromId<TType>(string itemId);

//To get from the table the items with parameter quals to value
GetBy<TType>(string parameter, object value);

//To get all the items from the table
GetAll<TType>();

//To delete the item from the table
Delete<TType>(TType item);

//To delete ALL the items from the table. WARNING!!!
DeleteAll<TType>();

//To see if an item exists
Exists<TType>(string itemId);

//To count the number of items in a table
Count<TType>();

The Helper I’ve created has all the main methods to work on your database. If some methods are not available, you can directly access the database (and therefore all its methods) using the command:

MtSql.Helper.Conn

this is a direct link to the database connection and from here you can find all the supported methods.

Conclusions

Creating a database could be a complicated operation but thanks to the MTSql library, creating a database for our Xamarin projects. Forms is incredibly easy. Install the library from Nuget and in a few seconds and a few lines of code, you have a database ready to be used in your Android, iOS and UWP projects.

Do you have any doubts or suggestions? Add a comment below, and if the article and the library were helpful to you, share them.

Sqlite for Xamarin made easy

May 31, 2019 | Plugin, Tutorial | 13 Comments

Let’s see how we can add a Sqlite database to your Xamarin projects in an incredibly easy way.

To help you to speed up your Xamarin development, I?ve created a set of plugins, one of them is MTSQL. Thanks to this plugin you can add a Sqlite database with a single line of code. The plugin is built on top of the Sqlite-net plugin by Frank A. Krueger.

A couple of useful link you can find useful:

Nuget link:https://www.nuget.org/packages/MarcTron.SQL

Project website:http://www.xamarinexpert.it/plugins/mt-sql/

To report any issue:https://bitbucket.org/marcojak81/mtsql

And now let?s see how to integrate the plugin inside your Xamarin Forms solution.

First of all we need to install the plugin. To do that, do a right-click on your solution and click on Manage NuGet Packages for Solution

Now search the package MarcTron.Sqlite, click on it and remember to select all your projects (.Net Standard project + all the main application projects) then click Install.

The Plugin will take care to install for you also the Sqlite-net plugin byFrank A. Krueger.

If everything worked as expected, you will see the version of the plugin next to each of the projects you have selected in the previous step.

Now it’s time to try the plugin to see how easy it is.

Inside the MainPage constructor you can see that the only line of code you need to create your database and open a connection to it is

SQLiteConnection conn = MTSql.Current.GetConnection("YOURDBNAME.db3");

Remember to replace the string with the name you want for your database.

using MarcTron.Plugin.MTSql;
using SQLite;
using Xamarin.Forms;

namespace YOURNAMESPACE
{
    public partial class MainPage : ContentPage
    {
        class TestTable
        {
            [PrimaryKey, AutoIncrement]
            public int Id { get; set; }

            public string name { get; set; }

            public TestTable()
            {
            }

            public TestTable(string name)
            {
                this.name = name;
            }
        }

        public MainPage()
        {
            InitializeComponent(); //The only line you need to create your database.
            SQLiteConnection conn = MTSql.Current.GetConnection("YOURDBNAME.db3"); 

            //This in case you want to use an async connection
            //SQLiteAsyncConnection connAsync = MTSql.Current.GetConnectionAsync();

            //This is just for test...
            //Create the table TestTable
            conn.CreateTable<TestTable>();
            //Insert some elements
            conn.Insert(new TestTable("A"));
            conn.Insert(new TestTable("B"));
            conn.Insert(new TestTable("C"));
            //Verify that the elements are there
            Label1.Text = "Rows:" + conn.Table<TestTable>().Count();
        }
    }
}

As you can see in the image after we obtain a connection to the database, we can create a table and add some elements to it. Just for test I have added 3 items. If everything works as expected we should see inside the text “Rows:3” on screen. And this is exactly what we get launching the app on UWP.

So, thanks to this plugin, you have your Sqlite database inside your app with only 1 line of code.

What do you think? Add your comment at the end of the page.

On September 2013 I released Safe Photo a native application for Android that allows you to hide pictures on your phone.

The app was quite successful with over 100.000 downloads and an impressive rating of 4.1.

During these years I’ve stopped to write native apps to concentrate entirely on Xamarin. So the logic consequence of that is that I’ve now created a new version of the app with Xamarin.Forms: Safe Photo 2.

Get it on Google Play
Get the app on Google Play Store

The idea behind the app is always the same: Safe Photo 2 will allow you to hide your secret pictures behind the security of the app.

Features

  • Protect the photos on your smartphone or tablet
  • Take new photos directly from the application, they will be protected automatically
  • Import photos from the public gallery (then delete them from the public gallery)
  • Protect your privacy with a numeric password
  • Organise your photos in galleries
  • Share your photos with whoever you want and how you want
  • The application can run on an external memory card so you will not consume the internal memory of your smartphone
  • Your photos are invisible also connecting the phone to a PC
  • Delete one or more images or galleries in one click
  • Compatible with smartphones and tablets
  • And it’s free

Gallery

Xamarin : How the app is made

To store all the data, Safe Photo 2 uses a SQLite database and of course the app uses the Sqlite Plugin For Xamarin And Windows (Nuget package).

The app also uses a Google Admob to show ads as banners and interstitials. As soon as possible I’ll create a package to easily add Admob to your Xamarin applications. If you prefer to write code yourself instead of using the plugin, I’ll also add a tutorial on how to add Admob on Xamarin.Android, Xamarin.iOS and Ads on UWP.

The app also uses some Dependency Services to execute some code on the native platforms. We use them to

  • Share a picture
  • Save, Copy and delete Files
  • Implement banners and interstitials for Admob

Do you want to know more about the app code or about Xamarin? Let me know and I’ll tell you more.

Have you ever dreamed to create a 3D game? Or maybe an Augmented Reality app? With Xamarin and UrhoSharp it couldn’t be easier.

UPDATE

The new UrhoSharp tutorial (with source code) is available here:https://www.xamarinexpert.it/blog/urhosharp-tutorial-how-to-create-your-first-project-with-xamarin-forms/

UrhoSharp

UrhoSharp is a lightweight Game Engine suitable for using with C# and F# to create games that run on Android, iOS, Mac, Windows and Unix. The game engine is available as a portable class library, allowing your game code to be written once and shared across all platforms. UrhoSharp is powered by Urho3D (http://urho3d.github.io/), a game engine that has been under development for more than a decade.The idea is the same as Xamarin: you write your code once and your app will run on many different platforms. In this case:

  • Android
  • iOS
  • Mac
  • Windows (WPF and UWP so it will run also on Windows phones)
  • Unix

After several months of silence UrhoSharp has come back strongly with a new release (v.1.8.91) tha fixes many bugs and updates this extremely powerful engine.The biggest news are:

  • Updated to Urho3D 1.7
  • ARKit and ARCore components
  • Fixed major Android and iOS crashes
  • Optional DirectX11 backend for Windows
  • UWP 64bit support (and .NET Native toolchain)

The amazing thing is that with UrhoSharp you can create your 2D/3D games and also create amazing Augmented Reality apps thanks to support to ARKit (iOS) and ARCore (Android).

I’m writing a tutorial on how to use UrhoSharp and I’ll publish it here as soon as it ready.

Meanwhile you can find more info on the official Xamarin website: https://developer.xamarin.com/guides/cross-platform/urhosharp/introduction/

For a beginner’s guide on how to create a Xamarin.Forms app you can read this tutorial: http://www.xamarinexpert.it/2018/03/03/xamarin-forms-a-guide-for-beginners/