Mocking Xamarin.Essentials

Xamarin.Essentials provides developers with cross-platform APIs for their mobile applications.

If you never heard about Xamarin.Essentials you should get familiar with it as soon as possible! It is a great collection of APIs that is very easy to use and integrate to your projects. You can find more information in the official documentation.

In order to keep the things as simple as possible and easy as possible to pick up for new contributors, all the APIs are written in a static way. The first reaction of developers would be to immediately raise their eyebrows and ask:  “Why so? How are we going to unit test that?”. The answer in most cases is easier than you may think at first. Continue reading “Mocking Xamarin.Essentials”

Dynamically changing the selected tab tint color in Xamarin.Forms

Android

droid

Since Xamarin.Forms 3.1 a TabbedPage.BarSelectedItemColor property has been introduced and we can simply use it to achieve our goal.

XAML:

<TabbedPage
    xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
    android:TabbedPage.BarSelectedItemColor="Red">
</TabbedPage>

C#:

Xamarin.Forms.PlatformConfiguration.AndroidSpecific.TabbedPage.SetBarSelectedItemColor(%tabbedPage%, %color%);

iOS

ios

Unfortunately on iOS we have to implement the solution ourselves. Luckily there is a TintColor property on a UITabBar that we can use. Continue reading “Dynamically changing the selected tab tint color in Xamarin.Forms”

Anatomy of Code snippets in Visual Studio for Mac

Code snippet is a shortcut that can be used to generate a code from a specific template. Example of a built-in code snippet:

Type cw and double press the Tab key will result in Console.Writeline();

Thats a pretty simple example, however we pressed only 4 keys instead of 19 (ignoring the autocompletion of IntelliSense). In more advanced cases it might be a code snippet to generate a BindableProperty or a simple property in a ViewModel that should notify the binding engine about updates. Sounds like we can increase our performance by letting the code snippets generate boring repetitive code for us.

Visual Studio for Mac is shipped with a default code snippets that can be used as a great example. Let’s take a look on the cw code snippet. First let’s open the editor by clicking on Visual Studio > Preferences > Text Editor > Code Snippets. Now select the cw code snippet under C# group:

Screenshot 2018-11-29 at 00.26.55

#1. Shortcut – is the shortcut we have to type in order to generate the code from the template. In this example it is cw (Console.WriteLine).
#2. Group – there are different available groups including F#, Python and Razor.
#3. Variables – on the screenshot #3 appear twice to demonstrate the definition of the $SystemConsoleWriteLine$ variable and its properties.
#4. Default – stands for the default value of the variable. Please note that in order to avoid confusion we should also provide a namespace.
#5. Function – we can apply built-in functions like GetSimpleTypeName("System#Console.WriteLine"). It will make sure to remove the namespace before Console.WriteLine if using System is already in place otherwise it will use the default value (#4). The list of supported functions can be found here.

The template is just a XML file that live in ~/Library/VisualStudio⁩/{version}/Snippets directory, which means that you can easily import and export code snippets that you create.

Earlier today I created a GitHub repository with a couple of handy code snippets for Visual Studio for Mac and especially for Xamarin. You are welcome to check and contribute by sharing your own code snippets!

Notification about an empty ListView in Xamarin.Forms

demo

ListView is one of my favourite UI controls available in Xamarin.Forms. It is mostly easy to use and customise. Just bind a collection of data, define the representation of each item and you are done!

However, there is one pitfall which most of the developers tend to ignore – if the bound collection is empty, the ListView will have nothing to show. Depending on the targeting platform it may look ugly or confusing for the end user.

In this blogpost we will check few possible solutions. One solution will be purely implemented on the ViewModel level and the other one will be a reusable ListView control wrapper.

Continue reading “Notification about an empty ListView in Xamarin.Forms”

Immutable Models in MVVM

10-22-04 025
Source: flickr/ Jeff Attaway

MVVM

The first M stands for Model – an implementation of the application’s domain model that includes a data model along with business and validation logic. Examples of model objects include repositories, business objects, data transfer objects (DTOs), Plain Old CLR Objects (POCOs), and generated entity and proxy objects.

definition source

Immutability

In object-oriented and functional programming, an immutable object(unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.

definition source

Why bother?

Imagine the next simple situation, your application downloads a JSON,  deserialises it to an object and then presents the downloaded data. You would expect the downloaded data to be one-to-one to the data on the remote server, however the data can be accidentally or intentionally mutated. Continue reading “Immutable Models in MVVM”

The ultimate guide to Emojis 🤹‍♂️

 

This slideshow requires JavaScript.

It is very common nowadays to express ourselves by using emojis. Instead of typing few words, we prefer to send one emoji that will express our feelings and emotions. Not sure that the other side will always get what we mean by sending a 🧞 , but that is another story.

In this article we will learn:

  1.  How to use emojis in static content like Labels and Buttons
  2.  How to define and use emoji in XAML only
  3.  How to define and use emoji using C#

Continue reading “The ultimate guide to Emojis 🤹‍♂️”

Entity Framework DB First and Computed Columns

Imagine you have a lovely DB first approach in place. There is a table “Fruits” with a column “WikiLink”. This column is getting populated on insert, using a trigger on the DB level. Can you spot “the” problem here?

Let’s try to understand how EF returns the DB generated entity Id from the DB right after the insert. The code below demonstrates a standard way to insert a new entity with EF:

var fruit = new Fruit { Family = “Rosaceae”, Name = “Apple” };
dbContext.Fruits.Add(fruit);
await dbContext.SaveChangesAsync();
// fruit.Id is auto-generated on the DB level and accessible after insert
// fruid.WikiLink is null

The Id column marked as identity, therefor it is recognised as a value generated on DB level. If you will use a DB profiler you will actually see:

— T-SQL Pseudocode for -> dbContext.Fruits.Add(fruit);
INSERT INTO [dbo].[Fruits] (Family, Name)
VALUES (“Rosaceae”, “Apple”)
SELECT SCOPE_IDENTITY() as Id;

It is insert and select in one query. Now back to our problem with ‘WikiLink’. What we would like to achieve is:

INSERT INTO [dbo].[Fruits] (Family, Name)
VALUES (“Rosaceae”, “Apple”)
SELECT SCOPE_IDENTITY() as Id, WikiLink;

When you use a code first approach, you have an option of explicitly marking an entity’s property as db generated with an attribute:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string WikiLink { get; set; }

However, with DB first approach you don’t have that option, and since there is a trigger behind this column, there is no way for EF to understand that it is generated on the DB level.

Unfortunately, it is not easily solvable with DB first approach. There are a couple of workarounds we could think about:

  1. We can try to manipulate “manually” the auto-generated edmx file and set the “WikiLink” to db computed. Which is a bad idea, because this change will get lost with the next model update as it is being regenerated on each change.
  2. Another option will be to query the DB right after the insert, to get the full row data:

var fruit = new Fruit { Family = “Rosaceae”, Name = “Apple” };
dbContext.Fruits.Add(fruit);
await dbContext.SaveChangesAsync();
await dbContext.Entry(fruit).ReloadAsync()
// fruid.WikiLink is not null anymore

The disadvantage is obvious – additional db query:

— T-SQL Pseudocode for -> dbContext.Fruits.Add(fruit);
INSERT INTO [dbo].[Fruits] (Family, Name)
VALUES (“Rosaceae”, “Apple”)
SELECT SCOPE_IDENTITY() as Id;

— T-SQL Pseudocode for -> await dbContext.Entry(fruit).ReloadAsync()
SELECT FROM * [dbo].[Fruits]
WHERE Id = 99;

However, it could be good enough for some projects.

If you can modify the DB scheme, the solution is quite simple – replace the trigger by a computed column:

— T-SQL Pseudocode for
alter table [dbo].[Fruits]
add [WikiLink] as concat(N’_ttp://mywiki.net/fruits?id=’, Id )

This way you may gain more performance. Since you may have a ‘RowVersion’ column which will be calculated twice because of the trigger. Not to mention that the DB structure is much more readable, compare to unnecessary trigger.

There might be another workarounds for this issue if you don’t have access or you can’t modify the DB. I would like to hear about your experience, so please share via comments.