Binding DateTime and TimeSpan to one property

As we know together, it take different properties to record what user input into DatePicker and TimePicker. DatePicker requires DateTime property, and yet TimePicker needs TimeSpan. And let say we have some kind of application form to submit bunch of data, and one property require the user to input complete set of time, from year to hour but we only have one DateTime property to bind into. Of course we can just add TimeSpan to DateTime and we gonna have complete set of DateTime from our DatePicker and TimePicker. But, what if we got bunch of DateTime property to input, we gonna adding TimeSpan to DateTime multiple times, which is ineffective. So, I create a simple custom control to simplify this problem. Let’s take a look.

XAML File

First, we need to create new content view with XAML on it. In XAML file we gonna need three 2 visible items, the DatePicker and TimePicker, and one invisible item, a DatePicker. The function of two first properties is obvious, to enable user input. But the last invisible DateTime will serve special function. I will explain later after we reach the code behind section, for now let see the code for XAML file

TitledDateTimePickerCode2

As you can see, I have one invisible DatePicker that bind to property called SelectedDateTime, we will use this property to bind whatever Date and Time that user input. One thing you need to take note is how I handle property changed in both visible DatePicker and TimePicker. Whenever user change the date or time, it will also change the our main property, SelectedDateTime.

Another thing you may notice is, I’m using custom Custom Date and Time Picker. It’s actually just custom picker with adjustable Font Size. If you curious, you can take a look at my previous post about adjusting font size of Xamarin Form’s Picker. But of course you also can use the original DatePicker and TimePicker from Xamarin Forms. It will works just fine, you just can’t bind the font size.

Code Behind

Now let’s move to the code behind that XAML file. This file actually is just full of properties you wanna bind to this custom control. You can add more properties that fits your needs, like FontColor maybe, or any other properties. But I wanna focus to how I handle property changes in this file. Like I said before, I use DateSelected and PropertyChanged¬†event handler in DatePicker and TimePicker respectively to update SelectedDateTime. But this method has one weakness. If the SelectedDateTime already has value when its bind, the visible DatePicker and TimePicker won’t show it’s value. Before we go any further, let’s take a look at the code.

public partial class TitledDateTimePicker : ContentView
    {
        public TitledDateTimePicker()
        {
            InitializeComponent();
            LabelTitle.BindingContext = this;
            DatePickerContent.BindingContext = this;
            TimePickerContent.BindingContext = this;
        }

        public static BindableProperty SelectedDateTimeProperty =
            BindableProperty.Create(nameof(SelectedDateTime), typeof(DateTime?), typeof(TitledDateTimePicker), DateTime.Now, BindingMode.TwoWay);

        public DateTime? SelectedDateTime
        {
            get => (DateTime?)GetValue(SelectedDateTimeProperty);
            set => SetValue(SelectedDateTimeProperty, value);
        }

        public static BindableProperty TitleProperty =
            BindableProperty.Create(nameof(Title), typeof(string), typeof(TitledDateTimePicker), null, BindingMode.TwoWay);

        public string Title
        {
            get => (string)GetValue(TitleProperty);
            set => SetValue(TitleProperty, value);
        }

        public static BindableProperty DatetimeProperty =
            BindableProperty.Create(nameof(Datetime), typeof(DateTime), typeof(TitledDateTimePicker), DateTime.Today, BindingMode.TwoWay);

        public DateTime Datetime
        {
            get => (DateTime)GetValue(DatetimeProperty);
            set => SetValue(DatetimeProperty, value);
        }

        public static BindableProperty TimespanProperty =
            BindableProperty.Create(nameof(Timespan), typeof(TimeSpan), typeof(TitledDateTimePicker), DateTime.Today.TimeOfDay, BindingMode.TwoWay);

        public TimeSpan Timespan
        {
            get => (TimeSpan)GetValue(TimespanProperty);
            set => SetValue(TimespanProperty, value);
        }

        public static BindableProperty FontSizeProperty =
            BindableProperty.Create(nameof(FontSize), typeof(int), typeof(TitledDateTimePicker), 12, BindingMode.TwoWay);

        public int FontSize
        {
            get => (int)GetValue(FontSizeProperty);
            set => SetValue(FontSizeProperty, value);
        }

        public static BindableProperty IsEditableProperty =
            BindableProperty.Create(nameof(IsEditable), typeof(bool), typeof(TitledEntry), true, BindingMode.TwoWay);

        public bool IsEditable
        {
            get => (bool)GetValue(IsEditableProperty);
            set => SetValue(IsEditableProperty, value);
        }

        void Handle_DateSelected(object sender, DateChangedEventArgs e)
        {
            UpdateSelectedDatime();
        }

        void Handle_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Time")
            {
                UpdateSelectedDatime();
            }
        }

        void Handle_BindingContextChanged(object sender, EventArgs e)
        {
            if (SelectedDateTime.HasValue)
                SetDateTime();
        }

        void UpdateSelectedDatime()
        {
            SelectedDateTime = Datetime.Add(Timespan);
        }

        void SetDateTime()
        {
            Datetime = SelectedDateTime.Value;
            Timespan = SelectedDateTime.Value.TimeOfDay;
        }
    }

As you can see at code above, whenever DateSelected and PropertyChanged fired, means user input date or time, it will update SelectedDateTime. In other hand, BindingContextChanged of my invisible DatePicker do the completely opposites. It will update the DateTime and TimeSpan of the visible DatePicker and TimePicker respectively.

So, when user navigate to a page which use this custom control, and he want to update a DateTime field that has beed set before hand, he will find fields of DatePicker and TimePicker that already set to proper values, because when he navigate to that page, the BindingContextChanged will be triggered. If we don’t do this, the DatePicker will set to default value, which is January 1st, 1990. This why we need that invisible DatePicker, because we need to put that BindingContextChanged event handler somewhere in the code.

How to use it?

Nah, we already have packed up everything we need about Date and Time Selecting in one simple custom control. So, all we need to do is calling it from any pages that need it. This is a simple sample how to do it.

TitledDateTimePickerCode1

 

SQLite and ORM in Xamarin Forms

It’s about a week ago, I was looking for a complete tutorial about how to implement ORM in SQLite in Xamarin Forms. I did find out that there’s already a library called SQLiteNetExtensions that handle this kind of stuff. It’s also has complete documentation with it. Unfortunately, the documentation is not up to date. I was having difficulty to use that library at first, so I look up for other tutorials on the net. But I couldn’t find one that suit my need, a complete and up to date tutorial. This is actually pretty simple thing, but if you don’t know how to do it properly, it will cost you hours of your life before you can make it works. So, this is how I’ve done it.

Note : Nuget packages you need are SQLite.Net-PCL and SQLiteNetExtenstions

Database Strictures

First thing first. Because we’re talking about ORM, let’s have a simple data structure that represent all kind relationships in ORM; OneToMany, ManyToOne, ManyToMany and OneToOne.

public class Department
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }

    public string DepartmentName { get; set; }

    [OneToMany(CascadeOperations = CascadeOperation.All)]
    public List Employees { get; set; }
}

public class Employee
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }

    public string IDCardNumber { get; set; }
    public string EmployeeName { get; set; }

    [ForeignKey(typeof(Department))]
    public int DepartmentID { get; set; }

    [ManyToOne(CascadeOperations = CascadeOperation.All)]
    public Department Deparment { get; set; }

    [ForeignKey(typeof(EmployeeFamily))]
    public int FamilyID { get; set; }

    [OneToOne(CascadeOperations = CascadeOperation.All)]
    public EmployeeFamily Family { get; set; }

    [ManyToMany(typeof(EmployeeBenefit))]
    public List Benefits { get; set; }
}

public class EmployeeFamily
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }

    public string SpouseName { get; set; }
    public string FirstChildName { get; set; }
    public string SecondChildName { get; set; }

    [ForeignKey(typeof(Employee))]
    public int EmployeeID { get; set; }

    [OneToOne(CascadeOperations = CascadeOperation.All)]
    public Employee Employee { get; set; }
}

public class EmployeeBenefit
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }

    public string BenefitName { get; set; }
    public double BenefitValue { get; set; }

    [ManyToMany(typeof(Employee))]
    public List Employees { get; set; }
}

One thing to take a note is make sure you’re using SQLite and SqLiteExtensions.Attributes instead of SQL.Net.Attributes or it’s not gonna works.

Dependency Services

To implement sqlite to Android and iOS, of course we gonna need dependency service classes. But first let create the interface in our PCL project.

public interface ISQLite
{
    SQLite.SQLiteConnection GetSQLiteConnection();
}

Then we move on to Android project. This is how the dependency service class looks like.

public class SQLiteAndroid : ISQLite
{
    public SQLite.SQLiteConnection GetSQLiteConnection()
    {
        var fileName = "testing.db3";
        var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        var path = Path.Combine(documentsPath, fileName);

        var platform = new SQLitePlatformAndroid();
        var connection = new SQLite.SQLiteConnection(path, true);

        return connection;
    }
}

Lastly, we also implement the dependency class to iOS project.

public class SQLiteiOS : ISQLite
{
    public SQLite.Net.SQLiteConnection GetConnection()
    {
        var sqliteFilename = "testing.db3";
        string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        string libraryPath = Path.Combine(documentsPath, "..", "Library");
        var path = Path.Combine(libraryPath, sqliteFilename);
        var platform = new SQLitePlatformIOS();
        var conn = new SQLite.Net.SQLiteConnection(platform, path);
        return conn;
    }
}

Data Context

Next, let’s create a class that will handle all things SQLite related. So when we need to do some operations in SQLite, all we need to do just calling the method in this class. Below this is the sample code of the class, but I don’t include all operations possible, just some important operations for example.

public class EmployeeDataContext
{
    private static EmployeeDataContext instance;

    public static EmployeeDataContext Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new EmployeeDataContext();
            }
            return instance;
        }
    }

    private SQLite.SQLiteConnection connection;

    private EmployeeDataContext()
    {
        connection = DependencyService.Get().GetSQLiteConnection();
        CreateTableIfNotExist();
    }

    private void CreateTableIfNotExist()
    {

        bool isTableNotExist = false;

        try
        {
            var test = connection.Table().FirstOrDefault();
        }
        catch
        {
            isTableNotExist = true;
        }
if (isTableNotExist)
        {
            connection.CreateTable();
        }

    }

    public List GetAllDepartment()
    {
        return ReadOperations.GetAllWithChildren(connection, recursive: true).ToList();
    }

    public void RefreshDepartment(IList listDepartment)
    {
       WriteOperations.DeleteAll(connection, GetAllDepartment(), true);
       WriteOperations.InsertOrReplaceAllWithChildren(connection, listDepartment, true);
    }

    public void DeleteAllDepartment()
    {
        WriteOperations.DeleteAll(connection, GetAllDepartment(), true);
    }

    public void UpdateDepartment(Department department)
    {
        WriteOperations.UpdateWithChildren(connection, department);
    }

    public void UpdateEmployee(Employee employee)
    {
        WriteOperations.UpdateWithChildren(connection, employee);
    }
}

How to use it

Now, everything is ready, let’s see how to use it. You call the methods from view model or directly from code behind.


List listDepartment = new List();
Department department = new Department();
Employee employee = new Employee();

EmployeeDataContext.Instance.GetAllDepartment();
EmployeeDataContext.Instance.RefreshDepartment(listDepartment);
EmployeeDataContext.Instance.UpdateDepartment(department);
EmployeeDataContext.Instance.UpdateEmployee(employee);

Making Enum as Bindable Property

This post is actually just an update from my previous post about Entry with title. I’ve made some enhancement to optimize my titled entry. From several changes, I think this enum bindable property is the most important so I decided to make one post discussing about it. But in this post I will also review some other minor changes. So, Let’s begin.

Additional Properties and methods

I added two additional properties. The first is Text, for binding a text to the entry, and Entry keyboard to binding the type of the keyboard. Those two properties are two most essential features of entry that I previously forgot to add. For Text property, it’s just another simple string binding property, but for the keyboard, it’s little bit different. Because entry’s keyboard has several different types that developer can choose depend on what field the entry’s used for. So, I created an enum bindable property to tackle that issue. This is how the code looks like.

public partial class TitledEntry : ContentView
{
    string placeholder = string.Empty;

    public enum KeyboardEnum
    {
        Default,
        Text,
        Chat,
        Url,
        Email,
        Telephone,
        Numeric,
    }

    public TitledEntry()
    {
        InitializeComponent();

        EntryContent.BindingContext = this;
        LabelTitle.BindingContext = this;
        LabelTitle.Text = string.Empty;
    }

    public static BindableProperty PlaceholderProperty =
        BindableProperty.Create(nameof(Placeholder), typeof(string), typeof(TitledEntry), null, BindingMode.TwoWay);

    public string Placeholder
    {
        get => (string)GetValue(PlaceholderProperty);
        set => SetValue(PlaceholderProperty, value);
    }

    public static BindableProperty TextProperty =
        BindableProperty.Create(nameof(Text), typeof(string), typeof(TitledEntry), null, BindingMode.TwoWay);

    public string Text
    {
        get => (string)GetValue(TextProperty);
        set => SetValue(TextProperty, value);
    }

    public static BindableProperty KeyboardProperty =
        BindableProperty.Create(nameof(KeyboardProperty), typeof(KeyboardEnum), typeof(TitledEntry), KeyboardEnum.Default, BindingMode.TwoWay);

    public KeyboardEnum EntryKeyboard
    {
        get => (KeyboardEnum)GetValue(KeyboardProperty);
        set
        {
            SetValue(KeyboardProperty, value);
            SetKeyboard();
        }
    }

    void Handle_Focused(object sender, FocusEventArgs e)
    {
        LabelTitle.Text = Placeholder;

        if (EntryContent.Text == null || EntryContent.Text.Length == 0)
        {
            placeholder = EntryContent.Placeholder;
            EntryContent.Placeholder = string.Empty;
        }

    }

    void Handle_Unfocused(object sender, FocusEventArgs e)
    {
        if (EntryContent.Text == null || EntryContent.Text.Length == 0)
        {
            EntryContent.Placeholder = placeholder;
            LabelTitle.Text = string.Empty;
        }

    }

    void Handle_TextChanged(object sender, TextChangedEventArgs e)
    {
        var entry = sender as Entry;
        if (!string.IsNullOrEmpty(entry.Text))
        {
            LabelTitle.Text = Placeholder;
        }
    }

    void SetKeyboard()
    {
        switch (EntryKeyboard)
        {
            case KeyboardEnum.Default:
                EntryContent.Keyboard = Keyboard.Default;
                break;
            case KeyboardEnum.Text:
                EntryContent.Keyboard = Keyboard.Text;
                break;
            case KeyboardEnum.Chat:
                EntryContent.Keyboard = Keyboard.Chat;
                break;
            case KeyboardEnum.Url:
                EntryContent.Keyboard = Keyboard.Url;
                break;
            case KeyboardEnum.Email:
                EntryContent.Keyboard = Keyboard.Email;
                break;
            case KeyboardEnum.Telephone:
                EntryContent.Keyboard = Keyboard.Telephone;
                break;
            case KeyboardEnum.Numeric:
                EntryContent.Keyboard = Keyboard.Numeric;
                break;
            default:
                EntryContent.Keyboard = Keyboard.Default;
                break;
        }
    }
}

As you can see at the code, I create similar enum like the original entry’s keyboard and then I created a bindable property for that enum. And then I create the method SetKeyboard¬†to convert my enum to the real keyboard. I know I can use value converter, but I think it’s more simple this way.

Another method that I added is Text Changed event handling for the entry. I use this method to handle if entry text already has value from beginning.  And for note, I also make a change in xaml side. I turned the stack layout into grid to optimize the rendering performance of the xaml.

BindableEnum1