How to access localhost from Android emulator and iOS simulator?

Being lucky to develop a backend and a Xamarin.Forms clients on your own? Sooner or later you will have to debug the API calls and it might become painful. Unless, you will follow the next rules:

  1. Configure your API URL to run on 127.0.0.1 instead of a localhost:

    // .NET Core Web.Api example
    public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .UseUrls(“http://127.0.0.1:5001“)
    .Build();

  2. Configure your Xamarin.Forms API consumer to have a conditional URL base:

    string apiUrl = null;
    if (Device.RuntimePlatform == Device.Android)
    apiUrl = “http://10.0.2.2:5001/api“;
    else if (Device.RuntimePlatform == Device.iOS)
    apiUrl = “http://localhost:5001/api“;
    else
    throw new UnsupportedPlatformException();

The problem with Android emulator is that it maps 10.0.2.2 to 127.0.0.1, not to localhost. However, the iOS Simulator uses the host machine network.

That should be it!
Happy debugging!

IKnowThatFlag quiz game build with Xamarin.Forms

Many years ago when I was at high school, I wrote a bot for a web browser flags quiz game, where a flag of a random country and 4 different country names where shown to the player. It was fun!

So I created the same game for iOS and Android using Xamarin.Forms just for fun. It is open source and available on github:

demo

This is what you get when an engineer creating a game without a designer. Luckily you can contribute if you have an idea on how to improve the UI/UX or if you want to add new features. I had a couple of them in my head:

  • Achievements
  • Learning game mode (without time or a game over)
  • [X] game mode – where the flag image is covered by some objects that the player has to remove and/or etc.

If you are new to Xamarin.Forms or MVVM I would recommend to check the source code, it is touching the next interesting topics:

  • MVVM
    • Fody
    • ViewModel first navigation
  • Animations
  • Custom fonts
  • IOC

Otherwise you are free to use the source code as you wish since it is under MIT license.

Converting JSON file to a SQLite database

When it comes to a data storage for your application, there are multiple options. Depends on your needs you may choose a JSON file or a proper SQLite database. Some times you may need to convert a JSON to SQLite DB and that is the topic of the current post.

First idea that you may get is to solve the problem in code. Well, we are developers and we are best in it after all. However, SQLite CLI is powerful enough to solve our issue or at least to solve it partly. SQLite CLI supports multiple data sources but not JSON. We will have to convert JSON to CSV and depending on the data structure it could be complex or an easy task to do. Here you could write some code or use an existing solutions (google it) in order to make the conversion happen.

The interesting part is the data import itself and it’s pitfalls. I had to replace a ‘,’ separator by “|” since the SQLite CLI ignored my quoted nested commas. Another thing to keep in mind that leading and trailing spaces are not ignored and they are a part of the value. You can define the table scheme before the import or alter it after the import, depends on your needs. For doing it before you just have to create a table manually, otherwise you will have to use the SQLite CLI or a SQLite browser to alter an auto-generated table.

Let’s take a look on a simple case where we will import a CSV file with a custom separator without defining the table scheme before the import.
CSV contents:

A|B|C
1|2|3
4|5|6
SQLite CLI:
sqlite3 dummy.db
SQLite version 3.19.3 2017-06-27 16:48:08
Enter “.help” for usage hints.
sqlite> .mode csv
sqlite> .separator |
sqlite> .import dummy.csv ABC
sqlite> select * from ABC;
1|2|3
4|5|6
sqlite>
As you see it is quite simple. The first argument is the output file, in our case it is a “dummy.db”. The rest are basically dot-commands that define the input mode “csv”, the separator “|”, the data source “dummy.csv” and the table name to import the data  to “ABC”.
It is very easy and intuitive to use. I would recommend to get familiar with the SQLite CLI just to know what it is capable of in order to save your time and nerves.

The beginners guide to Stack Overflow

Stack Overflow is the largest, most trusted online community for developers to learn, share​ ​their programming ​knowledge, and build their careers.

This is the official definition of this website, and I have nothing to add or remove from it. Being an official member for 4 years and 11 months, according to my profile data, I spent many hours on C#, Android, Xamarin and Xamarin.Forms tags and I am worried.

It seems like the quality of the questions is decreasing and decreasing. The most popular question is “How to deserialise a JSON” with all its variations or “I have a problem” and a screenshot. This kind of questions have been always asked, however lately it feels like an epidemy.

What goes on the internet stays on the internet.

The questions we ask, the answers we make are publicly visible and can be used to measure our competency. Beside that, please always keep in mind that someone is going to spend time on trying to solve our issues. Let’s respect the community.

Before posting a new question please make sure that:

  • The question haven’t been asked before.
  • The title and the description should be easy to understand and to follow.
  • Do not post screenshots of exceptions, logs or stack-traces. Share them as a plain text instead.
  • Do post screenshots or images to demonstrate the problem you are trying to solve, if you think it is necessary.
  • Always provide code snippets or describe how did you try to solve the problem yourself.
  • Re-read your question at least 2-3 times before posting it.

Before answering a question please make sure that:

  • The question haven’t been answered before. In case it was answered already just mark the question as a duplicate.
  • You fully understand the question and see the problem. If in doubt ask questions in comments or start a chat.
  • Always let the authors fix their own code. Describe the solution in plain text unless code is really necessary or unless the author is a total beginner.
  • Review the code and suggest improvements beside the answered question.
  • Downvote or vote to close only for a good reason.
  • Do not answer with a link, instead share the main piece of the information in addition to a link so if the link will die there will be still a short reference.

I believe that following those simple rules we will make Stack Overflow a greater place.

“DeepClean” is a must have Visual Studio extension for macOS

Yesterday I shared with you a command to recursively delete /bin, /obj and /packages directories. While this command is helpful, it might be a pain to use. Since you have to keep a terminal window opened and in general switch context from your IDE to terminal and etc.

A simple solution would be to execute this command without leaving the IDE at all, however in this case I had to extend the IDE itself. Thats how DeepClean extension was born. I am planning to write a proper post about how to extend visual studio for mac a bit later. So stay tuned.

Currently the extension does 2 simple things:
– Deleting /bin & /obj dirs
– Deleting /packages dir – after this you will have to restore the nuget packages, otherwise the solution wont build

You are welcome to download, test and contribute on github.
Please keep in mind that this extension is making it’s first steps, please make sure you have a back up of your code before using it!

Quickly delete “bin”, “obj” and “packages” directories under a .NET solution

Recently had to update some old Xamarin.Forms project to the latest and greatest XF and very quickly I realised that it is not going to be an easy task, since I had to manually manipulate the csproj files to remove the old nuget dependencies. I found myself going thru multiple projects multiple times in order to delete the “bin”, “obj” & “packages” directories to fix the miscellaneous build errors and I came up with a very simple script to recursively delete delete the “bin”, “obj” & “packages” directories:

# Recursively find and delete "bin", "obj" and "packages" dirs
# Backup your code before using this script, I am not responsible for any data loss. Please use it wisely.
find . -iname "bin" -o -iname "obj" -o -iname "packages" | xargs rm -rf

Backup your code before using this script, I am not responsible for any data loss. Please use it wisely.

To use this script: open a terminal in your solution’s root directory and copy paste the script above. Keep in mind that “bin” & “obj” directories will be regenerated after the next build, however “packages” directory will appear again only after restoring nuget packages for the solution.

Android emulators stopped working on macOS 10.13 (High Sierra)

Recently I updated my macOS to High Sierra however this broke my android emulators. Non of them started and logs showed something like:

Failed to open vm 3
Failed to create HAX VM
No accelerator found.
failed to initialize HAX: Invalid argument

As the logs states there is a problem with HAXM, and to be more specific a time for update has come. To solve the issue simply download the latest and greatest version of HAXM and restart your mac.

Avoid using a wildcard (*) when building mssql views

Using a wildcard while building a View can be very convenient if you have to return all the columns from a table:

CREATE VIEW View_Fruit
AS
SELECT f.*
FROM [dbo].[MyFruitsDb].[Fruit] as f
WHERE DeletedAt IS NULL

Seems legit and easy, however there is one thing to keep in mind, just because you are using a wildcard does not mean that your View will be automatically updated when your table schema is changed. In other words, if you will add one additional column on [dbo].[Fruit] table, you will have to regenerate the view, by simple replacing CREATE by ALTER in the T-SQL script demonstrated above in order to include this new column in the view.

Depends on your development cycle, you may prefer replacing the wildcard by a list of the columns you want to return. This way when you will compare your development DB to staging or production DB schemas you will see that you forgot to add a new column, otherwise schema comparison will results a 0 changes. Tricky.

As a rule of thumb I would avoid using wildcards, as life shows it may take time to discover that a wildcard is used in a View and that it has to be regenerated in order to solve an unexpected bug.

Installing Xamarin components

Xamarin components are easy to install, all you have to do is to download a zip, extract the content and to reference the dlls in your project. This would work if you download the component manually from components gallery. Same thing can be done using Visual Studio in a more robust way via ‘Components’ under the targeting platform projects. Either way, the component will be downloaded and installed only for a specific project.

Sometimes it might be useful to keep the component in cache, so it will be available globally. This is where the XAM file extension comes into play. Generally speaking, it is just an archive, you can change the file extension to zip and use it in a regular way, or vice versa change zip to xam.

Regardless of your OS you have to download xamarin-component.exe.
On Windows execute the next command:

xamain.component.exe install <component.xam>

On MacOS execute the next command with the same executable:

mono xamain.component.exe install <component.xam>

If the command executed successfully, you should see the installed component:

Screen Shot 2017-11-14 at 21.20.30

Please note the “Included in this project” and “Installed on this machine”. Components under the second section will be always there unless you will clean the cache. On MacOS the components will be installed under ‘~/Library/Caches/Xamarin’. Please let me know where the cached components are stored on Windows.