Using SQLite database in Xamarin.Android

I started to define development tasks to be done within MoneyBack project in the coming days (maybe I’ll even publish my Trello board soon 🙂 ) and it turned out that each functionality the app is going to offer needs persistent storage (e.g. to store people, payments, events etc.). The obvious choice is the local database in which I could store my entities and application’s data. In this post, I’d like to show you how quickly and easily SQLite database can be added and started to be used in Xamarin.Android project using SQLite.NET and Visual Studio 2017.

What is SQLite?

SQLite is an open-source database engine, which allows to store data in SQL structures. The whole database is stored in a single file, which makes it easily manageable on mobile devices. It’s lightweight, small and easily portable. It’s also prepared to work on multiple platforms. There are some limitations in contrast to “classic” SQL database engines, including:
  • OUTER join syntax is not fully supported
  • for altering tables, only “RENAME” and “ADDCOLUMN” operations are available
  • writing to views is impossible (views are read-only).
SQLite database can be easily operated using SQLite.NET ORM library available to download and install via Nuget. Let’s see how to do it.

Installing SQLite.NET package

In order to install SQLite.NET package, simply open Android.Xamarin solution in Visual Studio, open Package Manager Console and type the following command:
install-package Sqlite-Net
After few seconds, two files are added to our project:
SQLiteNetFiles
Files added by SQLite.NET
It means we’re all set 🙂

Entity definition

We have SQLite ORM ready to use. Now we need to define our first entity. In case of MoneyBack, I decided to start with defining Person (plural: People) entity. First thing we need to do is to define entity class. I created “Entities” folder for that and added the following class file: .gist table { margin-bottom: 0; } Just a class, in which we define basic properties of a Person – Name, LastName, PhoneNumber and Email. As we are designing a database entities, we also need to have keys for each of them – in this case we add Id property, and decorate it with two attributes:
  • PrimaryKeyAttribute – marks the column as PRIMARY KEY
  • AutoIncrementAttribute – marks the column with AUTO_INCREMENT (unique number is generated when a new record is added into a table).

read more...

Simple habits for better productivity

It’s been a really tough week, so today I have a non-technical post for you. I’m going to move on with the project this weekend, so I can put some technical stuff here tomorrow. If you don’t really care about productivity, organization of your days, planning of tasks to be done during next X days, this post is for you. I totally didn’t care as well, but I felt a bit disorganized, I knew I could do more or at least be conscious of what I’m able to do and what I’m not. Finally, without studying anything like GTD, I managed to introduce few simple habits to my everyday life that make my life easier, allow to complete some tasks faster and make me aware of what I have to do and when. I’d like to share those manners with you – maybe you’ll also find them helpful.

Write everything down

I heard from many people promoting better life organization, that writing things down is a very important step in being more productive. I definitely confirm. Writing things down cleans up your brain – it makes you not thinking about something you have to do – you just write it down and you are sure you’ll take care of it when the time comes. Such brain-liberty is very powerful. You can use your brain to think about the activity you’re actually working on at the moment, not having many “background” topics taking your brain’s “resources”. Of course, you need to find a place in which you store your notes (or tasks – whatever you call it). For me, such place must meet the following requirements:
  • be easy and fast to use in every situation
  • be accessible from every place, on every device
  • synchronizing across multiple devices
  • allowing to set deadlines for each task
  • giving a possibility to group tasks

read more...

Solving performance issues with dotTrace

If you’ve ever had any performance issues with your .NET applications, you may find this writing interesting. In this post I’d like to present to you a tool produced by JetBrains – dotTrace, showing how using only one of its functionalities can help in finding causes of performance issues in .NET applications.

Performance issue on production

Months ago some of your colleagues implemented an application and delivered it to the Customer. The app is “Countries and Cities Manager”, which is used by some administrator working in local government unit. That’s how it looks:
Countries and Cities Manager
That’s cool, isn’t it ? This “administration panel” allows to add a new city to the country. User fills name of the city and provides ISO code of the country considered. You may think “who would ever use it and for what?”. True. But first of all, this is just an example 🙂 , and secondly, imagine that Russia annexes some big European country. What happens then ? User administrating local government system must use your manager application to insert hundreds or thousands of new cities in Russia. Gotcha! The next day you receive a ticket in your company’s issues tracking system. Taking into consideration that an average number of cities in east-European countries is ~600, the ticket’s priority is set to “Blocking”. The description of the issue is:
  1. User fills the “City” and “Country ISO Code”, clicks “Add city”
  2. Waits for 10 seconds…
  3. Waits for 20 seconds…
  4. Waits for 30 seconds…
  5. Error message received:
    ISO not found
  6. User corrects “RU” to “RUS”
  7. Waits for 10 seconds…
  8. Waits for 20 seconds…
  9. Waits for 30 seconds…
  10.  City added!
  11. Scenario repeats for each new city to be added. Performance is unacceptable.

read more...

Xamarin – Android Activities

Today we’re going to take a look at Android’s most basic and in the same time most important concept, which is an Activity. To create even the simplest “HelloWorld” app one should know what are the Activities and how to work with them.

What is an Activity ?

The simplest, an Activity is a single screen in Android application. The concept of Activities is unusual in programming and it’s specific to Android platform.

Every Activity in Xamarin consists of two components:

  • UI (XML) – layout with user controls defined
  • Code (C#) – implementing the behavior
Let’s consider email client application – it’d probably have several Activities: “New email”, “List of emails”, “Email details”, “Settings” – notice all of them having both UI and behavior. We’d probably need “Email sending service”, which doesn’t necessarily need UI, so it wouldn’t be created as an Activity, but rather as a separate class realizing concrete task. As we can already see, every Android app contains several Activities:
activities
Android app composed of Activities, source: elearning.xamarin.com
In most programming platforms, the application has a static method which is called on the application’s startup. This is not the case in Android – do you remember our MainActivity class from the previous post ? It’s decorated with ActivityAttribute which registers the Activity within the Android system, but what’s more important by having MainLauncher attribute’s property set to true it tells the system it’s the startup Activity for the application within which it’s registered. It means nothing more than when our app is launched, Android creates MainActivity as the first one from all Activities in our application. Apart from that, OS operates the MainActivity as all other Activities.

Activities Back Stack

Android app starts its own Activities from other Activities. It may also start Activities that are defined by different apps, e.g. your Android app can offer a possibility to send an email. You don’t have to implement your own email sending client for that – it’s possible to use already existing email sending Activities (using Android Intents, which we’ll also cover one day) registered within another apps installed in the system which expose such “external calling” possibility. Then, this external app launches looking as if it was the part of your application. This is very powerful! When your email is finally sent, you are redirected back to your app from which you triggered email’s sending. How is that possible? In order to ensure such way of functioning, Android keeps all the Activities needed to perform a certain job (even if they come from different apps) in the same task. The “scope” of a task (when new task is created, what Activities it contains etc.) depends, among others, on Android version (e.g. starting from Android 7.0 many apps can be started in multiple windows in the same time on a single screen – in that case, the system keeps a separate task for each window). Within a particular task, several Activities are started. Each started Activity is pushed to the Activities Back Stack. The Activity being on the top of the stack has focus (is visible to the user). The previous Activities remain on the stack, but are stopped or even destroyed by Android system in certain cases (few more words about it in the next chapter). Activities Back Stack is a LIFO objects structure: when user presses Back button

read more...

Hello Xamarin World – first steps

This time I want to say “Hello” to Xamarin world.

First thing that needs to be done before starting Xamarin development, is obviously the installation of all necessary components.

In this post I want to share my feelings about the installation (not without issues of course), configuration of my Xamarin Android solution and deployment process to the device.

read more...

MoneyBack – requirements, functionalities and technologies

Hello again 🙂 It’s been a short while, WROC# conference was held in the meantime (it was great, by the way), but it’s time to write again. Write about DSP. More precisely: about MoneyBack, my project for the competition.

Today I’d like to share with you my idea for the application – what I require from it, what functionalities I imagine it to have and what technologies I want to use. This is going to be rather short post, I don’t want to spend too much time on imagining the functionalities (I rather prefer to start working on it). It won’t be much detailed also, just a high-level overview of what I imagine my project to look like.

read more...

Hello DajSiePoznac2017 !

Today I’d like to say “hello” to the programming competition Daj Sie Poznac 2017 (en. Get Noticed)  which I decided to take part in. For those who don’t know, DSP is organized by Maciej Aniserowicz, the owner of devstyle.pl blog, and it’s already its third edition this year.

Basic concept of DSP

Long story short, the main concept behind DSP is to develop an open-source project of any kind, in any technology, in the same time sharing your knowledge and project’s development processes by blogging about it. The competition lasts for 3 months – from March to May – during which at least 10 weeks must be spent on project’s development and blogging. At least 2 blog posts per week must be written, from which one must be about the project itself, and the other may be on any IT-related topic. As the project is open-source, source code is stored on public Git repository on GitHub.

read more...

ASUS Zenbook UX310UA – .NET programmer’s review

Time to wake this blog up 😉

It’s been a loooonger while since the last post. I hope to get this blog into motion in the next few weeks/months (Daj Się Poznać 2017 is coming…), however to begin with I’m writing not strictly technical/programming post today.

Need for a new laptop

Few months ago I started to look for a new laptop. Previously I’ve had Lenovo Y580 with Intel Quad-Core, SSD drive and additional graphics card, which was very performant and enough to what I use the computer for. It had one disadvantage – size (15″) and weight (~3kg with battery inside). I’ve started my Master’s degree studies on weekends, so it was unhandy to carry it the whole day. I needed a computer to be light, packable into backpack and strong enough for my programming tasks. Then I found ASUS Zenbook UX310UA with the following specs:

read more...

Building Windows Services using Topshelf

Hello again 🙂 Visibly this is going to be my first technical post here. I hope you’ll find it useful.

Windows Services

Recently I came up with a need to create an application, which executes some tasks in the background based on file system’s events. “That’s easy”, one would say. “Build Windows Service app”, he would add. Sure, that was also my first idea.

I think that’s very common that we want to create an application without any GUI, which purpose is just to do something in the background. Moreover we’d like it to be independent from the user running it – we want it to be running all the time, without having to manually launch it – especially when the application is running on customer’s environment, where we can’t be logged in all the time running the application.

Here comes the service – long-running executable with no user interface, which runs in its own Windows session. Such application can be:

  • executed by any user created in the system (e.g. with specific security policies assigned),
  • started automatically when the system launches,
  • automatically restarted in case of errors,
  • at any time started, paused, stopped or restarted.

Even if you’ve never developed any service applications, you are using many of them – check your services.msc to see the list of services currently running in your system.

Topshelf

Visual Studio 2015 provides a template to create Windows Service application and probably I could finish my post here. However, I would like to share with you an even easier way of building services: to do it with Topshelf – a very lightweight open-source library, which purpose it to make services development, debugging and deployment painless. Topshelf allows the developer to focus on service’s functionality, instead of wasting time interacting with .NET Framework’s build-in services support. There is also no more need to install your service using InstallUtil or learn how to attach your Visual Studio debugger to running service to detect issues.

Using Topshelf it’s enough to create console application, add one service class with public Start and Stop methods, configure service’s startup parameters (its name, display name, description etc.) and you’re ready to go. Below we’ll see how to do it.

Creating Windows Service application

After creating console application in Visual Studio, add Topshelf to the project by installing it from Nuget:

Topshelf - Nuget

Adding service class

Then, create service class, which is responsible for executing your service’s logic:

class FileWatcherService
{
   public bool Start()
   {
      // Initialize your service application here
      return true;
   }


   public bool Stop()
   {
      // Executed when the service is stopped
      // Dispose your objects here etc.
      return true;
   }
}

Both of those methods return boolean to indicate that starting/stopping of the service completed successfully.

Adding service configuration

Now we only need to configure the service’s parameters. Topshelf provides HostFactory class which contains Run method, to which we can pass fluently-created set of settings:

  • service class instance,
  • methods to be executed while the service is started/stopped/paused/continued,
  • service’s name, display name, description,
  • start/stop timeouts,
  • startup type (automatic, manual, automatic delayed),
  • and many more.

The set-up code should be put in the Main method of Program.cs. In our case, the simplest configuration could look as follows:

static void Main(string[] args)
{
    HostFactory.Run(serviceConfig =>
    {
        serviceConfig.Service<FileWatcherService>(serviceInstance =>
        {
            serviceInstance.ConstructUsing(() => new FileWatcherService());
            serviceInstance.WhenStarted(execute => execute.Start());
            serviceInstance.WhenStopped(execute => execute.Stop());
        });

        serviceConfig.SetServiceName("FileWatcherService");
        serviceConfig.SetDisplayName("File Watcher Service");
        serviceConfig.SetDescription("Service monitoring local folders for file system events");
        serviceConfig.StartAutomatically();

    });
}

read more...

Hello!

Hello everyone 🙂

If someone ever reads this post, this is just a “hello” message to you all. I’ve decided to start my blog today as sometimes I would like to store and (potentially) share some of my ideas somewhere, so I thought it would be a nice idea to have one place in which I can put them.

Now I need to spend some time configuring all the stuff here. Then I will try to post my first insights 🙂