Author: Marco Troncone

Home / Author: Marco Troncone

With Xamarin Forms it’s definitely possible to create great apps for Android, iOS and Windows: Safe Notes is clearly an example.

As you can see from the gallery, Safe Notes keeps your notes safe using a password and does it in a very stylish way.

Key Features

* Password protection. Protect your notes and checklist with password and lock the whole notepad app with your PIN.

* Offline access. Access your notes even without internet connection.

* Autosave. The notepad will save your notes automatically while you edit them.

* Tags. Organise your notes and to do list with labels to find them easily.

* Search function. Easy search notes and filter tags.

* Preferred Notes. Set note importance.

* Fast memo. Import text data directly from another source. Copy and paste from your phone to your note.

* Simple and intuitive user experience. Create. Edit. Delete.

* Photo support. Add photos and images to your secure notes.

* Colours. Use colours to categorise notes by importance, tags or subject or just make your notepad more fun.

* Tick the completed tasks.

* Share. Send and share individual note to yourself or another contact if you need.

* Unlimited text size.

* Multi languages.

* Off-line security. You are the only one that knows your password and everything that you write and save it is stored only on your phone instead of app and database. You don’t have to trust any other third-party as nobody else have access to it. Nothing is stored online where someone could potentially read it. 100% privacy protection.

* Free (Safe Notes is a free app and ads supported).

Download it from the Stores

Android: https://play.google.com/store/apps/details?id=com.HighTouch.SafeNotes

iOS: To be released

Windows: To be released

MTAdmob is now Open Source

October 16, 2019 | News, Plugin | No Comments

MTAdmob is probably the easiest and best plugin to add Google Admob to your Xamarin Android and iOS apps.

You can add Banners, Interstitials and Rewarded Videos to your app with a single line of code.

And now MTAdmob is Open Source so if you want to know how it works or if you want to contribute to it, you can go on

https://github.com/marcojak/MTAdmob

and have a look or maybe send a pull request with some new features.

Again if you need a tutorial, you can have a look at

https://www.xamarinexpert.it/admob-made-easy/

Have a suggestion or a comment? Write it here or on:

https://github.com/marcojak/MTAdmob

https://bitbucket.org/marcojak81/mtadmob

Screenshots Generator

Today I’ve updated IconsGenerator adding a new feature: the Mockup Generator to create mockups for the Google Play Store and the Apple AppStore.

The link for the tool is: http://www.iconsgenerator.com/Home/ScreenshotGenerator

How it works

This new tool will allow you to save quite a lot of time to create the artworks needed to publish your Apps on the stores.

The idea is incredibly easy, you upload a screenshot of your app and the website will let you download a Zip file containing 2 artworks, one for Android and the other for iOS.

But as usual images are better than thousands words, so let see what we can do:

An Example

I’m creating a new app with Xamarin.Forms called Safe Notes and I’m almost ready to publish it. So the first thing to do is to take a screenshot of my app:

Safe notes

Now I just have to drag my screenshot on Screenshots Generator:

IconsGenerator.com: Screenshots Generator

chose the platforms I want (Android and iOS) and then press the Download button. The tool will generate a zip file containing the mockups for Android and iOS:

Now I just need to upload these screenshots to the Google Play Store and Apple AppStore.

Thanks to this tool a task that could take a long time, is reduced to an operation of just few seconds. I think this tool is amazing (Just like Xamarin) and I hope you like it too. If so please, share it.

MarcTron.Admob version 1.4.3 is here

October 7, 2019 | Plugin | No Comments

UPDATE: It seems there is a problem with Xamarin.Google.iOS.MobileAds version 7.47.0 that doesn’t allow you to compile your code. If this happens, downgrade Xamarin.Google.iOS.MobileAds to version 7.38.0

I’eve just released the new version of the best and most complete Google Admob plugin for Xamarin (Android and iOS).

The changes for this version are:

  •      Added Consent option to iOS
  •      Updated Xamarin.Google.iOS.MobileAds to 7.47.0

With this new version it is possible to decide if use personalised Ads or not on iOS.

In addition to this, the new version of Xamarin.Google.iOS.MobileAds should solve some issues with iOS 13.

How to use the plugin

With MarcTron.Admob you can add Banners, Interstitials and Rewarded Videos to your apps with a single line of code.

First of all, install the plugin from Nuget: https://www.nuget.org/packages/MarcTron.Admob/ . Remember to install it in you shared project and in your Android and iOS projects.

After installing it, in your Android project open your AndroidManifest.xaml and inside the application tag insert this code:

    <meta-data android:name="com.google.android.gms.ads.APPLICATION_ID"
               android:value="ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx"/>

Remember to use your actual ApplicationID (you can find it in you Admob dashboard).

If on iOS you have problems displaying your ads, install the Xamarin.Google.iOS.MobileAds plugin (it should be installed automatically but sometimes you have to do it manually).

Add a Banner

To add a Banner, in your XAML add the code:

<controls:MTAdView/>

remember to add this line in your XAML:

xmlns:controls="clr-namespace:MarcTron.Plugin.Controls;assembly=Plugin.MtAdmob"

That’s it.

If you have problems showing the Ads, try to set the style in App.xaml:

<OnIdiom x:TypeArguments="x:Double" x:Key="AdsHeight" Phone="50" Tablet="90"/>
            <Style TargetType="controls:MTAdView">
                <Setter Property="HeightRequest" Value="{StaticResource AdsHeight}"/>
            </Style>

Interstitials

You can add an Insterstitial with a single line of code:

CrossMTAdmob.Current.ShowInterstitial();

To load a new one:

CrossMTAdmob.Current.LoadInterstitial("xx-xxx-xxx-xxxxxxxxxxxxxxxxx/xxxxxxxxxx");

Rewarded Video

You can show a Rewarded video with a single line of code:

CrossMTAdmob.Current.ShowRewardedVideo();

To Load a Rewarded Video you can use this line:

CrossMTAdmob.Current.LoadRewardedVideo("xx-xxx-xxx-xxxxxxxxxxxxxxxxx/xxxxxxxxxx");

There is so much more

There are many other things you can do with this great plugin for Admob. You can find the full documentation here: https://www.xamarinexpert.it/admob-made-easy/

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.

Microsoft today has released Visual Studio 2017 version 15.6!

Visual Studio
Visual Studio 2017

Release Note

  • We improved solution load performance by optimizing design time build.
  • We’ve added installation progress details on Visual Studio Installer.
  • You can pause your installation and resume at a later time.
  • We streamlined the update process so the notification takes you directly to the Installer.
  • Non-administrators can create a VS layout.
  • We added a new shortcut for Edit.Duplicate in the keyboard mapping.
  • We made significant improvements to the F# language and tools, particularly for .NET Core SDK projects.
  • The C++ compiler optimizes your code to run faster through improved optimizations.
  • C++ Mapfile generation overhead is reduced in full linking scenarios.
  • Debug options are available for Embedded ARM GCC support.
  • We added strong name signing on CoreCLR for the C# compiler.
  • Visual Studio Tools for Xamarin has lots of new productivity updates for iOS and Android developers.
  • Python no longer requires a completion DB, and Anaconda users have support for conda.
  • The Performance Profiler’s CPU Usage Tool can display logical call stacks for asynchronous code.
  • The CPU Usage tool displays source line highlighting and async/await code with logical ‘Call Stack Stitching’.
  • The debugger supports thread names set via SetThreadDescription APIs in dump debugging.
  • Snapshot Debugging can be started from the Debug Target dropdown for ASP.NET applications.
  • We’ve launched the initial implementation of Navigate to decompiled sources for .NET code navigation.
  • New enhancements for Configure Continuous Delivery include support for TFVC, Git authentication over SSH, and containerized projects.
  • You can now click on the Continuous Delivery tile in Team Explorer to configure automated build and deployments for your application.
  • Team Explorer supports Git tags and checking out pull request branches.
  • Service Fabric Tooling for the 6.1 Service Fabric release is now available.
  • The Windows 10 Insider Preview SDK can be installed as an optional component.
  • File versions for a number of Visual Studio executables now reflect the minor release.
  • Test Explorer has a hierarchy view and real time test discovery is now on by default.
  • We have added support for testing Win10 IoT Core applications.
  • Visual Studio Build Tools supports TypeScript and Node.js.
  • ClickOnce Tools support signing application and deployment manifests with CNG certificate.
  • You can access Azure resources such as Key Vault using your Visual Studio accounts.

And the Top issued fixed:

  • Visual Studio may freeze or crash when running on a pen-enabled machine.
  • Resizing of windows is not reliable.
  • .NET Core Projects containing special characters fail to restore NuGet packages or build.
  • Test Explorer Default Architecture not remembered.
  • Solution Explorer does not remain pinned after closing Visual Studio.
  • Regular UI freezes during debug session.
  • File names revert to lower case when re-opening a project.
  • Mouse cursor sticks on the Pointer (Hand) icon.
  • VSIXAutoUpdate crashes on scheduled task.
  • Start-up generates “We’ve noticed that a tool window ‘Error List’ is slowing Visual Studio.” alert.
  • Quick Launch no longer displays results after toggling to full screen.
  • XAML Activity designer throws OutOfMemoryException due to failed assembly reference resolution.
  • Cannot Stop/Cancel Debugged Unit Tests when using Selenium WebDriver.
  • When using the /quiet switch, vsixinstaller.exe does not exit at the end of installation.

This is the official page to get more info: https://docs.microsoft.com/en-us/visualstudio/releasenotes/vs2017-relnotes

About Xamarin in this release:

Visual Studio Tools for Xamarin

This release includes Xamarin.iOS 11.8 and Xamarin.Android 8.2.

Live XAML Previewing with the iOS Simulator

The Xamarin Live Player enables developers to continuously deploy, test, and debug their apps using just Visual Studio and an iOS or Android device. Visual Studio 2017 version 15.5 added support to enable developers to preview real-time XAML changes directly in the Android emulator without requiring a recompile or redeploy. This release brings this functionality to the Remoted iOS Simulator for Windows.

Many modern apps require a secure authentication for users and Azure Active Directory Authentication Library (ADAL) enables application developers to authenticate users to cloud or on-premises Active Directory (AD). Here I show two different ways to add ADAL to a Xamarin.Forms project.

The short way: MTADAL Plugin

This is a plugin I have created to add ADAL to all my projects and I’ve decided to make it freely available to everyone.The plugin page here: http://www.xamarinexpert.it/plugins/mt-adal/A tutorial to use the plugin is here: http://www.xamarinexpert.it/2018/03/01/adal-made-easy/

Authentication with MTADAL Nuget package
MTADAL Nuget package

This plugin is really easy to use. You just need to install it in your projects (PCL/.NetStandard and platform projects) and write:

AuthenticationResult data = await MTADAL.Current.Authenticate(Authority, GraphResourceUri, ClientId, ReturnUri);

That’s it. Basically in less than a minute you are ready to authenticate your users.

The long way: Write the authentication code

In case you don’t want to use the MTADAL plugin, you can write the code by yourself in your projects.The first thing you need to do is install the ADAL nuget package in your projects (https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/)

Authentication with ADAL package
ADAL package

In our PCL/.NetStanrdard project we need to add this interface:

public interface IAuthenticator
{
    Task<AuthenticationResult> Authenticate(string authority, string resource, string clientId, string returnUri);
    void Logout(string authority);
    bool hasLoginData(string authority);
}

and when we want to authenticate a user we need to use this code:

var auth = DependencyService.Get<IAuthenticator>();
            AuthenticationResult data = await auth.Authenticate(App.Authority, App.GraphResourceUri, App.ClientId, App.ReturnUri);

Before we can authenticate the users, we need to add the code in each of the platform project we need the authentication (eg. Android, iOS, UWP):

Android

Here we need to implement the interface created in our PCL/.NetStandard project.

[assembly: Dependency(typeof(Authenticator))]

namespace YOURNAMESPACE
{
    public class Authenticator : IAuthenticator
    {
        public async Task<AuthenticationResult> Authenticate(string authority, string resource, string clientId, string returnUri)
        {
            try
            {
                var authContext = new AuthenticationContext(authority);
                if (authContext.TokenCache.ReadItems().Any()) 
                    authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
                var uri = new Uri(returnUri);
                var platformParams = new PlatformParameters((Activity) Forms.Context);
                var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);
                return authResult;
            }
            catch (Exception ecc)
            {
                return null;
            }
        }

        public bool hasLoginData(string authority)
        {
            var authContext = new AuthenticationContext(authority);
            return authContext.TokenCache.ReadItems().Any();
        }

        public void Logout(string authority)
        {
            var authContext = new AuthenticationContext(authority);
            if (authContext.TokenCache.ReadItems().Any()) authContext.TokenCache.Clear();
        }
    }
}

We need to register the class with DependencyService otherwise the code will not work. We can register the class adding this line before the namespace:[assembly: Dependency(typeof(Authenticator))]Don’t forget it otherwise the authentication will not work!Inside your MainActivity class you also need to add this code:

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
        }

This will intercept the result from the ADAL activity and will allow you to conclude successfully the authentication.

iOS

We need to add the class to our iOS project:

[assembly: Dependency(typeof(Authenticator))]

namespace YOURNAMESPACE
{
    class Authenticator : IAuthenticator
    {
        public async Task<AuthenticationResult> Authenticate(string authority, string resource, string clientId, string returnUri)
        {
            try
            {
                var authContext = new AuthenticationContext(authority);
                if (authContext.TokenCache.ReadItems().Any())
                    authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
                var controller = UIApplication.SharedApplication.KeyWindow.RootViewController;
                var uri = new Uri(returnUri);
                var platformParams = new PlatformParameters(controller);
                var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);
                return authResult;
            }
            catch (Exception ecc)
            {
                return null;
            }
        }

        public bool hasLoginData(string authority)
        {
            var authContext = new AuthenticationContext(authority);
            return authContext.TokenCache.ReadItems().Any();
        }

        public void Logout(string authority)
        {
            var authContext = new AuthenticationContext(authority);
            if (authContext.TokenCache.ReadItems().Any()) authContext.TokenCache.Clear();
        }
    }
}

This class is the only thing you need to authenticate your users on iOS.Again, remember to add the line[assembly: Dependency(typeof(Authenticator))]

UWP

We need to add the class to our UWP project:

[assembly: Dependency(typeof(Authenticator))]

namespace YOURNAMESPACE
{
    public class Authenticator : IAuthenticator
    {
        public async Task<AuthenticationResult> Authenticate(string authority, string resource, string clientId, string returnUri)
        {
            try
            {
                var authContext = new AuthenticationContext(authority);
                if (authContext.TokenCache.ReadItems().Any())
                    authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
                var uri = new Uri(returnUri);
                var platformParams = new PlatformParameters(PromptBehavior.Auto, false);
                var authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);
                return authResult;
            }
            catch (Exception ecc)
            {
                return null;
            }
        }

        public void Logout(string authority)
        {
            var authContext = new AuthenticationContext(authority);
            if (authContext.TokenCache.ReadItems().Any()) authContext.TokenCache.Clear();
        }

        public bool hasLoginData(string authority)
        {
            var authContext = new AuthenticationContext(authority);
            return authContext.TokenCache.ReadItems().Any();
        }
    }
}

This class is the only thing you need to authenticate your users on UWP.Again, remember to add the line[assembly: Dependency(typeof(Authenticator))]

Summary

It’s incredibly easy to authenticate users in a Xamarin.Forms projects. You can do it in 2 ways:

  1.  Use the MTADAL Plugin
  2.  Install the ADAL Plugin, add then interface and add the classes above for each of your platform projects!

You want to create a mobile multi platform app and you really like C#.Xamarin is the perfect solution for you and if you don’t have any major experience with native mobile development, Xamarin.Forms is just a day-dream.So let’s see how we can create our first Xamarin.Forms projects and how it works.

Create the Project

From Visual Studio 2017 create a New project…Under “Visual C#” select “Cross-Platform” (1) then select “Cross-Platform App (Xamarin.Forms)” (2), choose name and location for your project (3) and press Ok (4).Now we need to configure our project. In this case we start with a Blank app that is perfect to explain how a Xamarin.Forms solution works. Under Platform choose the platforms you need. In this case I’ve chosen Android, iOS, Windows (UWP). Under UI Technology select Xamarin.Forms and under “Code Sharing Strategy” choose .NET Standard.After we press ok, Visual Studio will take several seconds (or minutes according to your machine) to create your solution.Inside the Solution Explorer we see now that we have a .NET Standard project (our common library, where we are going to write almost all our code), and Android project, an iOS project and a UWP project. The projects are already working so if we try to run one of the projects (Android, iOS, UWP) this is what we get:That’s brilliant, few second and we already have a working project for Android, iOS and UWP.Now it’s time to understand how a Xamarin.Forms project works so we are going now to analyze the projects we have in our solution.

.NET Standard

This is common project shared by all the other projects. It’s here that we are going to write our app. Here we write the UI and the logic and if our project it’s easy enough, we don’t need to write code in the other projects of our solution.Inside our project there are 2 file, App.xaml and MainPage.xaml. App.xaml is the entry point of our .NetStandard project. From this file Xamarin loads the first Page of the app and usually we initialize other parts of the project like Resources, Databases and so on.Now let’s see the structure of the code-behind file App.xaml.cs

using Xamarin.Forms;

namespace Tutorial01
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            MainPage = new Tutorial01.MainPage();
        }

        protected override void OnStart()
        {
            // Handle when your app starts

        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}

Inside the constructor we initialize the XAML file with “InitializeComponent()” and load the first page with “MainPage = new Tutorial01.MainPage();”.As you have seen, MainPage is the actual page displayed on-screen, so every time we want to change a page, we need to assign a new value to MainPage (We’ll see that there are also other ways to do it).OnStart is called when the app is started. OnSleep and OnResume are called every time the app appears and goes in background.Now it’s time for the MainPage file. This is the page that will be displayed when we will launch the app. This is the XAML file:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"             
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"             
             xmlns:local="clr-namespace:Tutorial01"             
             x:Class="Tutorial01.MainPage">
    <Label Text="Welcome to Xamarin.Forms!"            
           VerticalOptions="Center"            
           HorizontalOptions="Center" />
</ContentPage>

What we have here is a ContentPage and inside a single element, a Label with text (“Welcome to Xamarin.Forms!”) and alignment options, so where are saying that we want to show that text at the centre of the screen (we have seen it before).And this is the code-behind file:

using Xamarin.Forms;

namespace Tutorial01
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
    }
}

We see that MainPage inherits from a ContentPage (as the XAML file) and inside the constructor we need to call InitializeComponent to load the XAML file.Because the app does nothing, this file is basically empty otherwise here you can add the logic of your page (unless you want to follow an MVVM approach…I’ll add a link here as soon as the MVVM guide is ready).

Android Project

Let’s see the structure of the project:Inside the Resources folder you will add all your resources like images, styles and native layouts.MainActivity is the entry point of your Android app:

namespace Tutorial01.Droid
{
    [Activity(Label = "Tutorial01", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true,
        ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;
            base.OnCreate(bundle);
            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new App());
        }
    }
}

Inside the method OnCreate we need to initialize Xamarin.Forms and load the .NetStandard project.Usually you don’t have to edit this file unless you have to load external plugins or intercept events like OnActivityResult (when you launch another activity, after it terminates you’ll get the result here) or OnResume (when the app goes in foreground).

iOS Project

Let’s see the structure of the project:Inside the Resources folder you will add all your resources like images or storyboards (you are not going to use them in Xamarin.Forms).The AppDelegate file is the entry point of your iOS app:

namespace Tutorial01.iOS
{ // The UIApplicationDelegate for the application. This class is responsible for launching the
    // User Interface of the application, as well as listening (and optionally responding) to
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());
            return base.FinishedLaunching(app, options);
        }
    }
}

Inside the method FinishedLaunching we need to initialize Xamarin.Forms and load the .NetStandard project.Usually you don’t have to edit this file unless you have to load external plugins.

UWP Project

Let’s see the structure of the project:This project seems a bit more complicated as it has two file: App.xaml and MainPage.xaml. In UWP, Xamarin.Forms is initialized inside the App.xaml file.

protected override void OnLaunched(LaunchActivatedEventArgs e) {
    Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == null) { 
        ... 
        Xamarin.Forms.Forms.Init(e); 
        ...
    } 
    ...
}

There is a lot of code but don’t worry, probably you will never have to edit it. The only thing to remember is that here the Xamarin Forms library is initialized.The MainPage.xaml is extremely simple:

namespace Tutorial01.UWP
{
    public sealed partial class MainPage
    {
        public MainPage()
        {
            this.InitializeComponent();
            LoadApplication(new Tutorial01.App());
        }
    }
}

The only thing we do here is to load our .Net Standard project.

Recap

During this tutorial we have seen the structure of a Xamarin.Forms project: When we create a new Xamarin.Forms project, Visual Studio creates for us:

  • .NetStandard project where we write the logic and the UI of our app
  • a project per each platform we want our app on.

We need to write code in these platform projects only if we need to initialize a plugin, write a custom renderer (I’ll write a tutorial for Custom Renderers) or in general write code for a particular platform.

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.

Let’s see how we can make the Active Directory authentication incredibly easy for your Xamarin projects.

To help you to speed up your Xamarin development, I’ve created a set of plugins, one of them is MTADAL. Thanks to this plugin you can authenticate users in your projects with a single line of code.

A couple of useful link you can find useful

Nuget link: https://www.nuget.org/packages/MarcTron.ADAL\

Project website: https://www.xamarinexpert.it/Plugin/MTADALh

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

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

Add the Active Directory Plugin

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…”

manage nuget

Manage the Nuget packages

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

MTADAL Nuget package

The Plugin will take care to install for you also the Nuget package Microsoft.IdentityModel.Clients.ActiveDirectory so you need to accept the Microsoft License.

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.

Nuget package installed successfully

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

Authenticate your users

Inside the Button_OnClicked method, you can see the only line of code you need to authenticate the user:

AuthenticationResult data = await MTADAL.Current.Authenticate(Authority, GraphResourceUri, ClientId, ReturnUri);
using System;
using MarcTron.Plugin.ADAL;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Xamarin.Forms;

namespace YOURNAMESPACE
{
    public partial class MainPage : ContentPage
    {
        public const string ClientId = "YOUR CLIENT ID";
        public static readonly string ReturnUri = "YOUR RETURN URI";
        public const string GraphResourceUri = "YOUR Graph Resource Uri";
        private const string AadInstance = "YOUR AAD Instance";
        private const string Tenant = "YOUR TENANT";
        public static readonly string Authority = $"{AadInstance}{Tenant}";

        public MainPage()
        {
            InitializeComponent();
        }

        private async void Button_OnClicked(object sender, EventArgs e)
        {
            AuthenticationResult data = await MTADAL.Current.Authenticate(Authority, GraphResourceUri, ClientId, ReturnUri);

            if (data != null)
                await DisplayAlert("MTADAL", "Hello " + data.UserInfo.GivenName, "Ok");
        }
    }
}

Of course you need to set Authority, GraphResourceUri, ClientId, ReturnUriaccording to your Active Directory credentials.

If we run this simple code and we insert the correct email and password this is what we seeAuthentication completed! And with only a single line of code!

USAGE ON ANDROID

To use this plugin on Android, add the following line inside the OnCreate method of your MainActivity:

MTADAL.Current.Init(this);

Add that line just after the Xamarin Forms initialization

Xamarin.Forms.Forms.Init(this, bundle);

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

%d bloggers like this: