Tag Archive : Android

/ Android

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 | 10 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.

Xamarin eXpert is proud to present you a new amazing tool to create the icons for your apps for free and with a single click of your mouse: iconsgenerator.com

App icons generator

How it works

The app icons generator, allow to generate the icon for your app and all the icon set for the button, tabs and other UI components.

App icon

Drag your icon over the grey box with the text: “Drag and drop your icon here”. You will see a preview of your image. Now press the “Download” button to download your icons.

After extracting the zip file, you can simply copy the Android icons in your Android project and the iOS icons in your iOS project. The iOS icons contain also the Contents.json file so if you copy the icons and this file inside your Assets.xcassets folder, Xamarin (or xcode) will automatically recognize all the icons for the different sizes (so cool!).

Thanks to iconsgenerator.com, the process of creating the icons for your Android and iOS project will take only few seconds.

Icon Set

Iconsgenerator.com allows you to generate also the icons for your UI elements (buttons, tabs…). As you know, you shouldn’t have a single size icon but you should have different sizes according to the phone/tablet screen. In android you should create 5 icons for each image and they should go under these folder:

  • drawable-mdpi,
  • drawable- hdpi,
  • drawable- xhdpi,
  • drawable- xxhdpi,
  • drawable- xxxhdpi.

Under iOS, you should have 3 icons for each image with the names written with this logic:

The process can be quite laborious and long but thanks to
iconsgenerator.com, it will require just few seconds.

Drag your icon over the grey box with the text: “Drag and drop your icon here”. You will see a preview of your image. If you want you can change the name of your icons. Now press the “Download” button to download your icons. In just a second you will have all the 8 icons resized for your Android and iOS project.

all for FREE…

Yes, it’s right…the tool is completely free. Use it as mush as you like, for all the times you need.

If you want, it would be nice if you could share this article and talk about
iconsgenerator.com.

Then, if you feel generous, you can buy me a coffee going here: Buy me a coffee.

If you need help to use the tool, or you have suggestions to improve it, write a comment here or send me an e-mail.

Thank you for your support.

Microsoft has released a new preview version of the new Visual Studio 2019.

The good thing is that it can be installed without affecting your current Visual Studio installation, so if you want to try it now, you can install it for free from here.

We love Visual Studio but in particular we love Xamarin, so let’s see what are the news related to it:

Build and Deploy time

It seems that this new version of Visual Studio brings a massive improvement in Build and Deploy time.

According to Pierce Boggan: “Incremental build times in the Visual Studio 2019 Preview for the SmartHotel360 app are 29.66% better than the Visual Studio 2017 version 15.8 release, and deployment times are over twice as fast

STEPVISUAL STUDIO 2017 VERSION 15.8VISUAL STUDIO 2019 PREVIEW 2DELTA
First Build01:04.2000:50.13-21.95%
Incremental Build (XAML Change)00:10.6200:07.47-29.66%
Deploy (XAML Change)00:09.0300:04.44-50.83%

Considering that we spend most of our days building and deploying apps, even few seconds are more than appreciated and here we are talking about 30%. Not bad!

Enhanced Fast Deployment for Android

Visual Studio 2019 Preview 2 adds support for enhanced fast deployment. It means that it will generate a new APK only when necessary.

To enable this feature, add these lines to your Android file project:

<PropertyGroup>   
<AndroidFastDeploymentType>Assemblies:Dexes</AndroidFastDeploymentType> 
</PropertyGroup>

Xamarin.Forms

In Visual Studio 2019 we can use a property panel to help us writing our XAML files. We just need to select a control and all its properties will appear in the property panel.

XAML IntelliSense

Visual Studio 2019 has a better IntelliSense and will include IntelliCode that will recommend us the common items putting them on top of the completion list according to the context.

Designers

The Android designer adds support for Android Pie (9.0) while now IntelliSense is supported for Android XML files.

The iOS Designer adds support to render custom controls that need to load native dynamic libraries or frameworks.

What else

Visual Studio 2019 produces faster Android Apps with smaller APKs thanks to d8 and r8.

To enable these two features add these lines to your Android project file:

d8:

<PropertyGroup>   
<AndroidDexTool>d8</AndroidDexTool>
</PropertyGroup>

r8:

<PropertyGroup>   
<AndroidLinkTool>r8</AndroidLinkTool>
</PropertyGroup>

Visual Studio 2019 also adds the Xamarin Forms Shell Template.

There are many other improvements to Visual Studio 2019, so I’ll suggest you to try it and maybe give your feedback to Microsoft.

What do you think about Visual Studio 2019 Preview 2? Tell us writing a comment…

On September 2013 I released Safe Photo a native application for Android that allows you to hide pictures on your phone.

The app was quite successful with over 100.000 downloads and an impressive rating of 4.1.

During these years I’ve stopped to write native apps to concentrate entirely on Xamarin. So the logic consequence of that is that I’ve now created a new version of the app with Xamarin.Forms: Safe Photo 2.

Get it on Google Play
Get the app on Google Play Store

The idea behind the app is always the same: Safe Photo 2 will allow you to hide your secret pictures behind the security of the app.

Features

  • Protect the photos on your smartphone or tablet
  • Take new photos directly from the application, they will be protected automatically
  • Import photos from the public gallery (then delete them from the public gallery)
  • Protect your privacy with a numeric password
  • Organise your photos in galleries
  • Share your photos with whoever you want and how you want
  • The application can run on an external memory card so you will not consume the internal memory of your smartphone
  • Your photos are invisible also connecting the phone to a PC
  • Delete one or more images or galleries in one click
  • Compatible with smartphones and tablets
  • And it’s free

Gallery

Xamarin : How the app is made

To store all the data, Safe Photo 2 uses a SQLite database and of course the app uses the Sqlite Plugin For Xamarin And Windows (Nuget package).

The app also uses a Google Admob to show ads as banners and interstitials. As soon as possible I’ll create a package to easily add Admob to your Xamarin applications. If you prefer to write code yourself instead of using the plugin, I’ll also add a tutorial on how to add Admob on Xamarin.Android, Xamarin.iOS and Ads on UWP.

The app also uses some Dependency Services to execute some code on the native platforms. We use them to

  • Share a picture
  • Save, Copy and delete Files
  • Implement banners and interstitials for Admob

Do you want to know more about the app code or about Xamarin? Let me know and I’ll tell you more.

Have you seen how amazing are the Admob Rewarded video Ads? If you are creating a game or an app, the Rewarded Videos are something you should add to your app.

UPDATE: I’ve added on github the source code of a project to test this Admob plugin. You can find it here: https://github.com/marcojak/TestMTAdmob

Do you think that are difficult to implement and it takes hours of your time? WRONG!

Thanks to my plugin MarcTron.Admob (https://www.nuget.org/packages/MarcTron.Admob) you can add Rewarded Videos with a single line of code!!!

Exactly!!! Install the MarcTron.Admob free plugin and in less than few seconds you can show Rewarded Videos in your Android and iOS apps!

HOW (It’s super easy!!!)

  • Install the MarcTron.Admob plugin in your projects (.netstandard, Android and iOS).
  • That’s it! No other things to do!!!

Now, if you want to show a rewarded video you just have to write this code:

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

Of course remember to replace the xxx with your video ID that you can find on your Google Admob page.

EVENTS

We all love events 🙂 If you love them as well. There are 7 events that you can use with Rewarde Videos:

OnRewarded                          When the user gets a reward
OnRewardedVideoAdClosed             When the ads is closed
OnRewardedVideoAdFailedToLoad       When the ads fails to load
OnRewardedVideoAdLeftApplication    When the users leaves the application
OnRewardedVideoAdLoaded             When the ads is loaded
OnRewardedVideoAdOpened             When the ads is opened
OnRewardedVideoStarted              When the ads starts

CONCLUSION

We have just seen how to add Rewarded Videos (with the plugin you can add Banners and Interstitials as well) in less than few seconds.

Basically it’s a dream 🙂 But it’s all TRUE!

USEFUL LINKS

Now here some links that you can use:

A detailed tutorial on how to use the plugin: https://www.xamarinexpert.it/blog/admob-made-easy/

The nuget package link:

https://www.nuget.org/packages/MarcTron.Admob

The bitbucket project site to report/view issues:

https://bitbucket.org/marcojak81/mtadmob/issues

Github test project to try the plugin: https://github.com/marcojak/TestMTAdmob

Microsoft has now released a new update for Visual Studio 2019. Let see what news we are and if there are improvements for Xamarin (Yes, there are…Yes!!!!)

As usual I’ll copy here Microsoft Release notes (it’s quite long, so I’ll keep only the important part) and then we’ll see the improvements for Xamarin. I’ve added in bold the parts related to Xamarin.

Release Notes Visual Studio 2019 version 16.1

IDE

  • Visual Studio IntelliCode is now generally available and comes installed with any workload that supports C#, C++, TypeScipt/JavaScript, or XAML.
  • We have added Per-Monitor Awareness support.
  • New codefixes are available for C#.
  • Most Recently Used has been added to Visual Studio Search.

Performance

  • You can now experience optimizations to improve the solution load time of very large solutions.
  • Template authors can add custom tags to their templates.
  • There is now CodeLens support for custom UI.
  • We have provided updates to Language Server Protocol implementation.
  • We have updated behavior for switching between solutions, folders, and other views.

C++

  • In-editor documentation for CMake has been added.
  • Use Windows Subsystem for Linux with C++ natively in Visual Studio, and AddressSanitizer for Linux projects and WSL.
  • We have made improvements and modified colorization in C++ Quick Info tooltips.
  • We have implemented new C++ Code Analysis quick fixes.

F#

  • We have released more performance improvements and a bulk of bug fixes for F# and F# tooling.

.NET

  • New .NET productivity features include one-click code cleanup on projects and solutions, a new toggle block comment keyboard shortcut, refactoring to move types to other namespaces.
  • You can now clone code from an SSH URI through the clone screen in the start window.
  • .NET Productivity additions in this release include intellisense completion for unimported types, toggling single-line comment/uncomment, exporting naming styles to editorconfig, and a new code style setting for preferring usings inside/outside namspaces.
  • We have implemented .NET SDK tooling additions primarily around supporting WinForms and WPF projects for .NET Core 3.0 along with bug fixes and performance improvements.
  • Visual Studio SDK v16.0 has been released to NuGet.
  • A preview of the XAML Designer for .NET Core 3.0 WPF development is available.

Xamarin

  • Default Android Experience for Xamarin now supports API 28.
  • Xamarin.Forms XAML recommendations for design time attributes.

Top Issues Fixed in Visual Studio 2019 version 16.1

  • Cannot navigate to the symbol under the caret in ASP.NET MVC Projects.
  • Resx editor doesn’t render.
  • Xamarin.iOS cannot find the application manifest. Please ensure the project contains a manifest file named ‘Info.plist”.
  • nmake environment missing path to NETFX tools.
  • Clicking on a ASP.NET Core project in solution opening the project .csproj file.
  • Assembly reference is removed from project after running app referencing library.

Details of What’s New in Visual Studio 2019 version 16.1

IDE

  • IntelliCode is now generally available and comes installed with any workload that supports C#, C++, TypeScipt/JavaScript, or XAML.
  • Use the start window to clone code from an online repository through SSH.
Clone with SSH on start window

Clone with SSH on start window

  • Visual Studio IntelliCode is installed by default when you install a workload that supports C#, XAML, or C++.
    • C# and XAML base models will be on by default.
    • Preview features, such as custom model training and argument completion, can be enabled via Tools > Options > IntelliCode.
  • Added Per-Monitor Awareness support
  • New codefixes available for C#.
  • Added Per-Monitor Awareness support for WinForms based PropertyBrowser window of Visual Studio. Requires .NET Framework 4.8 RTM version installed on the machine.

Debugger

  • Source Link can now use Windows Authentication to support on-premises TFS Source Control.
  • Added nuget.org symbol server to the list of default symbol servers

Project

  • The button for switching the Solution Explorer view will now consistently show you a dropdown menu of all possible views.
Solution switching

Solution view switching

  • Improved the loading time for very large solutions. The improvement varies based on the size of the solutions.
  • Removed the Convert dialog under File > Convert. This feature was previously deprecated in Visual Studio 2015.
  • Updated the validation rules for the task.vs.json and launch.vs.json schemas, and added descriptions for the properties.
  • Added support for Linux remote debugging using a custom program via launch.vs.json.

Editor

  • Visual Studio Search will now display on focus the three most recently used actions invoked through Visual Studio Search, as shown in this sample mockup. (Note: icons and specific line items have not been fully updated in this mock-up.)
Visual Studio Search

.NET Productivity

  • There is now experimental intellisense completion for unimported types! You now receive intellisense suggestions for types in dependencies in your project even if you have not yet added the import statement to your file. You must turn this option on in Tools > Options > Text Editor > C# > Intellisense.
Intellisense completion for unimported types

Intellisense completion for unimported types

  • Toggle Single Line Comment/Uncomment is now available through the keyboard shortcut (Ctrl+K,/). This command will add or remove a single line comment depending on whether your selection is already commented.
  • You can now export naming styles with the “Generate editorconfig” button located in Tools > Options > Text Editor > C# > Code Style.
  • You can now use a new editorconfig code style rule to require or prevent usings inside a namespace. This setting will also be exported when you use the “Generate editorconfig” button located in Tools > Options > Text Editor > C# > Code Style.
Editorconfig rule for usings outside/inside namespaces

Editorconfig rule for usings outside/inside namespaces

Tools Options setting for usings inside/outside namespace

Tools Options setting for usings inside/outside namespace

  • The Find All References “Kind” column now has more filter options and is aware of namespaces and types.
Find All References Kind column has more filter options

Find All References Kind column has more filter options

  • We have added a codefix for split/merge if statements.
Split or merge if statements

Split or merge if statements

  • We have added a codefix for wrapping binary expressions.
Wrap binary expressions

Wrap binary expressions

  • A regex completion list can now be accessed through the intellisense menu (Ctrl + space) when inside a regex string. These completions also include an in-line description of what the suggestion does.
Regex completion offered in Intellisense with (Ctrl + space)

Regex completion

  • We have added a codefix for unsealing a class.
Unseal a class codefix

Unseal a class

  • You can now use one-click code cleanup for projects and solutions. You can right-click on projects or the solution in the Solution Explorer and select ‘Run Code Cleanup’.
Right-click to run code cleanup over the entire solution

Right-click to run code cleanup over the entire solution

You will see a dialog box while cleanup is applied to each file

You will see a dialog box while cleanup is applied to each file

  • You can now use a refactoring dialog to move type to namespace or folder. Place your cursor in the class name and type (Ctrl + .) to open the quick actions and refactorings menu and select ‘Move to namespace.’ This launches a dialog where you can select the target namespace you would like to move the type to.
Place cursor in class name and type (Ctrl+.) to view refactorings

Place cursor in class name and type (Ctrl+.) to view refactorings

Select the destination namespace

Select the destination namespace

  • Toggle Block Comment/Uncomment is now available through the keyboard shortcut (Ctrl+Shift+/) or through Edit > Advanced > Toggle Block Comment. This command will add or remove block comments depending on what you have selected.
Toggle block comment with (Ctrl+Shift+/)

Toggle block comment with (Ctrl+Shift+/)

  • There is now a codefix for making readonly struct fields writable. Place your cursor in the struct name, type (Ctrl+.) to open the quick actions and refactorings menu, and select ‘Make readonly fields writable.’
  • The codefix to add a private field from a constructor and vice versa is easier to discover and will show when any portion of the field name is selected. This refactoring now also offers all possible constructors.

XAML Designer Preview for .NET Core 3.0 WPF development

  • There is an early preview of the XAML Designer for developers building .NET Core 3.0 WPF applications in Visual Studio. Many design-time features will be unavailable at this time. Since this is an early preview, if you encounter issues such as crashes, please submit Visual Studio feedback for the team to improve the experience going forwards.
  • With each update to Visual Studio 2019, we will continue implementing more of the features that were previously available in the XAML Designer for .NET Framework WPF applications.

Xamarin

  • We have updated the default Android Experience to API 28 for templates, device creation, installers, and more.
  • IntelliSense on Windows now shows recommendations for design-time attributes when writing Xamarin.Forms XAML.

Changes related to Xamarin

As we have seen, there are 2 main changes. The first one is relative to Android, now everything is updated to API 28, so we should find updated Android templates.

The second change is relative to IntelliSense, now it should give us better recommendations when we write our Xamarin.Froms XAML files.

A very annoying bug has been fixed in Xamarin.iOS: Xamarin.iOS cannot find the application manifest. Please ensure the project contains a manifest file named ‘Info.plist”.

That was quite a bad bug and the only way to resolve it was to unload and reload the iOS project. Fortunately now Microsoft has fixed it so…..Yeahhh!

Are you going to update Visual Studio? I’m doing it right now!

For a list of all changes, please visit this page: https://docs.microsoft.com/en-gb/visualstudio/releases/2019/release-notes#16.1.0

N.B. The images were taken from the page above. So the copyright belongs to them

Xamarin.Forms 4.0 is finally out

May 22, 2019 | News | No Comments

Every release of Xamarin.Forms improves the performances and adds new features. It has been a long time since the first Xamarin.Forms came out. That version was very basic and to be honest not very great. Then Xamarin.Forms 2 came out and it was better, finally something that could be used for a production app. When Xamarin.Forms 3 came out, it was great, better performances, new features. Xamarin.Forms 3 has been a great tool to create amazing multiplatform apps and now Xamarin.Forms 4.0 promises even more, again better performances and new features. Let’s see together the main news of this release.

The Shell

Shell is a new way to create our apps. First of all it allows us to add easily flyouts and menus to our apps. It also adds the concept of URI navigation.

That’s great but what is even better is that it uses “fast renderers” (see later). To use the shell, on Visual Studio 2019 starting a new Xamarin.Forms app, you can select the Shell template. To get more info about Shell, you can use this documentation:

Android Fast Renderers

Android Fast Renderers were introduced in Xamarin.Forms 2.4 but disabled by default. The idea behind them is to reduce the number of views required to render a particular control. Honestly you could see improved performances so now they are enabled by default. This means that you will notice better perfomances with the enw Xamarin.Forms.

Image Source Unification

From Xamarin.Forms 3.5, they have introduced the FontImageSource to use the font glyphs but was not possible to use it everywhere. From version 4.0using ImageSource you can use them wherever you want.

Accessibility

From Xamarin Forms 4.0 we can now control the focus order directly in X.F. To do this, we can use the TabIndex property available on any VisualElement.

Conclusion

I will personally test Xamarin.Forms 4.0 and in particular the Shell to see how great that is. I will also test the new navigation pattern (URI Navigation) to see if there are improvements here. I will also evaluate the new performances to see if the app can be faster or more fluid.

And what do you think about Xamarin.Forms 4.0?