Category: Guide

Home / Category: Guide

Usually a desktop platform has a lot of available resources so many developers tend to avoid to improve the quality of their code.On a mobile platform the resources are quite limited and improving the code could make a huge difference. It can transform a slow and annoying app in a great fast and great one.Today, using the code I’ve written for one of my app Tv Series Time Manager, we are going to see how improving the code can make a huge difference in the loading time of your apps.

LINQ
LINQ

Improve your code – LINQ is your friend

Tv Series time manager allows you to keep track of your preferred tv series.It uses a public API to get information about all the TV Series created. As you can imagine there are thousands and thousands of Tv Series so we need to handle lists of thousands of items.Every time we launch the app, it searches online updated about the Tv Series you are following (new episodes, release dates, and so on). This can be a quite intensive task as the API we need to call returns a JSON file with more than 34000 items.The first time I’ve written the updated method I had this code:

var localTvShows = LocalData.GetAllTvShows(); 
var remoteUpdatedTime = await WsData.GetUpdatedShows(); 
foreach (var info in remoteUpdatedTime) 
{ 
    var show = localTvShows.FirstOrDefault(x => x.id == info.Key); 
    if (show != null && info.Value > show.updated) 
    { 
        updateRequired = true; 
        break; 
    } 
}

            if (UpdateRequired)
            {
                foreach (var info in remoteUpdatedTime)
                {
                    var show = localTvShows.FirstOrDefault(x => x.id == info.Key);
                    if (show != null && info.Value > show.updated)
                    {
                        var remoteserie = await WsData.GetShow(show.id);
                        SqlHelper.SyncSerie(show, remoteserie);
                        var episodeList = await WsData.GetEpisodes(show.id);
                        SqlHelper.SyncEpisodes(show.idLocal, episodeList);
                    }
                }
            }

I load the local Tv Show followed by the user and the remote Tv Series with the corresponding update time.Inside the first foreach I check if I need to update the local Tv Series.In case I have to update a Tv Series, I use a second foreach to update every local TV Series inside the local Sql database. (To add SQLite database to your app, you can read this tutorial)The code worked pretty well but I wasn’t satisfied by the loading time so I started to look for a way to improve the performances and here I discovered once more that LINQ is our friend.

The new code with LINQ

I decided to use LINQ to evaluate if I have to update a tv series, so I’ve written the code replacing the old one with this:

var seriesToUpdate = from remoteTime in remoteUpdatedTime
                join localShow in localTvShows 
                    on remoteTime.Key equals localShow.id
                where remoteTime.Key == localShow.id && remoteTime.Value > localShow.updated
                select localShow;

            if (seriesToUpdate.Any())
            {
                foreach (var show in seriesToUpdate)
                {
                    var remoteserie = await WsData.GetShow(show.id);
                    SqlHelper.SyncSerie(show, remoteserie);
                    var episodeList = await WsData.GetEpisodes(show.id);
                    SqlHelper.SyncEpisodes(show.idLocal, episodeList);
                }
            }

Speed Test

Now it’s time to see if the new code is really better than the first (Obviously it is 🙂 ). To do so, I’ve divided the code in two parts.

  • Evaluate if an update is required (Part A)
  • Update the Tv Series (Part B).

To give you the idea of how much time we can save, I’ve enclosed both the code in a for statement repeating the it for 100 times. These are the result:

Part A

  • OLD CODE:  Elapsed Time: 1077 ms
  • NEW CODE: Elapsed Time:   225 ms

Part B

  • OLD CODE:  Elapsed Time:  590 ms
  • NEW CODE: Elapsed Time:   122 ms

Total

  • OLD CODE:  Elapsed Time:  1667 ms
  • NEW CODE: Elapsed Time:    347 ms

Looking at the time spent by the old and new code we  went from 1667 ms to 347 ms, saving 1320 ms. The difference is HUGE.From the point of view of a user, saving almost 1.5 seconds makes a massive difference, maybe the difference between keeping your app or uninstalling it.

Conclusion

A mobile device has a limited amount of resources and users don’t like to spend time waiting in front of a loading screen. Even the most useful app, if not optimized will be uninstalled by the users. This is why it’s really important to optimize your code.Today we have seen that with a good use LINQ  we can massively reduce the time used by our code.If you like the article, comment and share it!

Admob for Xamarin made easy

May 6, 2019 | Guide, Plugin, Tutorial | 23 Comments

In this tutorial I’ll show you how to monetize your Xamarin apps with AdMob using my MTAdmob plugin.

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

To help you to speed up your Xamarin development, I’ve created a set of plugins, one of them is MTAdmob. Thanks to this plugin you can add Admob banners and Insterstitials in just few lines of code. It couldn’t be easier than that and I’ll show you.

Install the plugin

First of all, right click on your Xamarin solution and select “Manage Nuget packages for Solution”

manage nuget

Visual Studio will open a new screen where you can search and install one or more nuget packages. In this case we can search for the MTAdmob plugin. Searching for MarcTron will show you all my packages (I’m sure you can find other useful plugins that I’ve written), and we can select the MTAdmob plugin as showed in the next image.

It’s very important that you install the plugin in your PCL/.Net standard project and in your platform projects (Android, iOS, UWP).

After the Admob plugin is installed we can add banners and insterstitials to our projects.

Add Ads to our project

With version 1.0 the MTAdmob plugin supports banner and interstitials for Android and iOS. If you would like to see the plugin supporting also the UWP platform, let me now and I’ll add the support in a new version.

As I’ve said we can add Banners and Interstitials Admob ads to our project. Let’s start with the Banners

How to add an Admob Banner

An Admob banner is just a view inside our page. It means that we can add it using XAML or C#. First of all let’s see how to add an Admob banner using XAML.

Add an Admob Banner with XAML

In MTAdmob to use an Admob banner I’ve created a custom control called AdView, so to use it we can use this code:

<?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:controls="clr-namespace:MarcTron.Plugin.Controls;assembly=Plugin.MtAdmob"
             x:Class="Test.MTAdmob.MainPage">

<StackLayout>
    <Label Text="Let's test an Admob Banner!" 
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand" />
    <!-- Place the Admob controls here -->
    <controls:AdView></controls:AdView>
</StackLayout>

In this example we have created a StackLayout with 2 controls: a label and an AdView (our Admob banner). Easy! Isn’t it???

The AdView control is basically a View so you can use all the properties you can think of like: HorizontalOptions, VerticalOptions, IsVisible…

In addition to these properties, I’ve added in AdView two other properties: AdsId and PersonalizedAds.

AdsId: Allows you to add the Banner Id (you can find it in your Admob account)

PersonalizedAds: This allow you to use non personalized ads. For example in case of GPDR. Of course it’s better to use personalized Ads.

To use these properties you can update the previous code to:

<controls:AdView PersonalizedAds="true" AdsId="xxxxxxxxxxxxxxxxxx"></controls:AdView>

Add an Admob Banner with C#

In case you don’t write your pages with XAML or you write your UI in C# or you want to add your view only in some cases, you can add your Admob Banner using this code:

using MarcTron.Plugin;
...
AdView ads = new AdView();

Of course you need to attach this View to your layout, but you know how to do it (If not, feel free to ask).

To use the custom properties you can change the previous code to:

...
AdView ads = new AdView();
ads.AdsId = "xxx";
ads.PersonalizedAds = true;

Also in this case, to add an Admob banner is INCREDIBILY EASY!!!

Global Custom Properties

As you have seen, the properties AdsId and PersonalizedAds belong to a single AdView. It means that you have to set them for every Admob Banner.

To make things even easier I’ve added the option to set these properties only once. To do so, you can use this C# code:

CrossMTAdmob.Current.UserPersonalizedAds = true;
CrossMTAdmob.Current.AdsId = "xxxxxxxxxxxxxxxx";

In this case all your Admob banner will show personalized ads and will have the same Id.

If you set local and global properties, the local ones will have higher priority.

Use of Banner Events

I’ve added 4 events to the Admob banner that you could find nice to have. These events are:

  • AdsClicked When a user clicks on the ads
  • AdsClosed When the user closes the ads
  • AdsImpression Called when an impression is recorded for an ad.
  • AdsOpened When the ads is opened

To use these events you can write this code:

AdView myAds = new AdView();
myAds.AdsClicked += MyAdsAdsClicked;
myAds.AdsClosed += MyAds_AdVClosed;
myAds.AdsImpression += MyAds_AdVImpression;
myAds.AdsOpened += MyAds_AdVOpened;

Of course you can use these events also if you have declared your AdView in your XAML code.

Admob Interstitials

Now that we know how to add Admob banners using my plugin MTAdmob, let’s see how we can add Admob Interstitials. If possible, to add an Admob interstitial is even easier. You just need a single line of code. Don’t you believe me? Look here how to show an Admob interstitial:

CrossMTAdmob.Current.ShowInterstitial("ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx");

I told you!!! That’s it!!! With that line of code you have just showed an Interstitial in you app. Of course you need to replace that string with the Insterstitial ID you can find in your Admob account.

Events for Interstitials

There 3 events that you can use with Interstitials:

OnInterstitialLoaded        When it's loaded
OnInterstitialOpened        When it's opened      
OnInterstitialClosed        When it's closed

Rewarded Video

From version 1.1 the plugin supports the amazing Rewarded Video too.

To show a rewarded video you just need a single line of code:

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

Events for Rewarded videos

There are 7 events that you can use with the Rewarded video Ads:

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

Initialization

Before you can use the Admob banners and Interstitials, you need to initialize it. You need to do it only once so it makes sense to initialize it onside the OnCreate method in Android and FinishedLaunching in iOS.

In your Android project add this line in your OnCreate method:

MobileAds.Initialize(ApplicationContext, "ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx");

In your iOS project add this line in your FinishedLaunching method:

MobileAds.Configure("ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx");

ANDROID PROJECT (IMPORTANT)

In your AndroidManifest you should add these lines:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application android:label="Test.MTAdmob.Android">
    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>
    <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />
</application>

Some useful links

Conclusion

This Admob MTAdmob plugin is incredibly easy to use but in case you need help, or you want to suggest a new feature or for any other reason, write me.

Android SDK Setup with Xamarin

May 4, 2019 | Guide | No Comments

As you know is very important to keep your system updated and this of course is valid for the Android SDK.You should alway use the lasted available Android components.The Official Xamarin Documentation is not very clear on how to configure properly the Android SDK, so here is what you should do to obtain the best from your Xamarin.Android projects.First of all you should really install the Xamarin Android SDK Manager instead of the classic SDK Manager.Probably the most important reason to do so is that since version 25.2.3 of the Android SDK Tools package, Google replaced the UI Manager with a command line utility. I really don’t know why, but I know that the Xamarin Android SDK Manager is a very good tool. So I really suggest you to download it.As stated in the official Xamarin website, the requirements are:

  • Visual Studio 2017 community edition or higher. Visual Studio 2017 version 15.5 or later is required. (I’ll suggest you to use the latest version 15.6)
  • Xamarin for Visual Studio version 4.5.0 or later.
  • Java Development Kit 8 (the JDK 9 is not supported yet inXamarin.Android)

The Xamarin Android SDK Manager is not compatible with Visual Studio 2015. You can add the Xamarin SDK Manager using the Visual Studio Installer: 

Visual Studio Installer
Install the Xamarin SDK Manager

Be sure to select the Xamarin SDK Manager and install it.If you launch again Visual Studio 2017 and click on Tools > Android > Android SDK Manager, the Xamarin Android SDK Manager will be launched instead of the Google Android SDK Manager.

Android sdk manager
Xamarin SDK Manager

Here there are two tabs: Platforms and Tools.

Platforms

Inside the first Tab you can download and install the platforms you want to support. You don’t need to install all the platforms, you just need to install the most recent one and the lowest that you still want to support.So if you want to support the platforms from Android 4.1, just install the Android SDK Platform 16 (Android 4.1) and the Android SDK Platform 16 (Android Oreo 8.1).

Tools

From the Tools Tab, you should always try to update the tools to the latest version:

Android Tools
Use always the latest available tools

So you should install:

  • Android SDK Tools 26.1.1
  • Android SDK Platform-Tools 27.0.1
  • Android SDK Build-Tools 27.0.3

I also suggest you to install the Android emulator is case you want to try your app on multiple devices. The latest available version is:

  • Android Emulator 27.1.12

I’ll update this guide every time there will be an updated component so I suggest to bookmark/follow this page.

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