Akavache losing data in Xamarin.iOS

Akavache Logo
Akavache Logo - Image from https://github.com/reactiveui/Akavache

Today I am sharing an issue that I believe many have faced and probably tried resolving a lot. The issue is mostly seen when using Akavache in Xamarin.iOS (even when using Xamarin.Forms). The issue is this:

When using the App either in Simulator or Device, we try to use say Akavache’s BlobCache to store some data. During the runtime of the App, we tend to read the data back from the BlobCache and play with it. However, the real reason we use BlobCache is that we want to store some data like UserInformation, etc. to persist during App restarts.

But we see that the information is lost during the App restarts.

The main reason behind this is the Akavache is built to be used on top of SQLite. However, if the required plugin or rather the NuGet package is not found, the data is then persisted temporarily as the SQLite is not initialized for use with Akavache.

In order to fix this, I installed the NuGet Package SQLitePCLRaw.bundle_e_sqlite3 in all the projects.

The moment it got installed, I could see that my data was getting cached and persisted during the App restarts. I hope it helps.

Do ensure that you are initializing the Application Name:

BlobCache.ApplicationName = "AkavacheExperiment";

Happy Coding!

Page Navigation using Messaging Center

Messaging Center
Messaging Center- Image used from https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/messaging-center

MessagingCenter doesn’t need any introduction in this world of Xamarin. As the name suggests, it is clearly used for Messages. Now the question arises What Messages? Are these Chats? Who is Sending? Who is Receiving? etc…etc…etc…

Let’s look at the gist of Messaging Center from here:
The publish-subscribe pattern is a messaging pattern in which publishers send messages without having knowledge of any receivers, known as subscribers. Similarly, subscribers listen for specific messages, without having knowledge of any publishers. You can read more about the common explanation here. If you are still not aware of MessagingCenter, then kindly read this Documentation on MessagingCenter.

We know that while using MessagingCenter, there are two actors in the scene, Publisher and Subscriber. Now, what happens is that the Subscriber subscribes for a specific message and performs an action whenever the Publisher publishes the desired message.

Now let’s look at the use case for this:
We always see this question arising wherein the developers are trying to perform operations on Page Navigation from the ViewModel like Navigation.PushAsync, Navigation.PushModalAsync, Navigation.PopAsync or Navigation.PopModalAsync etc. However, we all know that the Navigation property is only accessible as part of the Page.

The sole reason behind using frameworks like MVVM is to isolate the View from ViewModel. Consider the scenario where we have a ListView and in its header is the Add Button. Now, this Add Button is bound to the Add Command in the ViewModel which needs to perform the function call of Navigation.PushModalAsync().

So here when we think about performing operations like PushModalAsync, the challenge is that we cannot just go ahead and use the Navigation object unless we store the Root/Parent page somewhere in another variable, etc.

If you create a New Blank Xamarin.Forms App with Master Page, you will get a templated App with few lines of code.
In your MainPage constructor, you can try this:

public partial class MainPage : MasterDetailPage
{
    Dictionary MenuPages = new Dictionary();
    public MainPage()
    {
        InitializeComponent();
        MasterBehavior = MasterBehavior.Popover;

        //Subscribing to the Message NavTo
        MessagingCenter.Subscribe("AppName", "NavTo", async (sender, arg) =>   
        {
            await NavigateFromMenu(arg);
        });
    }
 
    public async Task NavigateFromMenu(int id)
    {
        if (!MenuPages.ContainsKey(id))
        {
            switch (id)
            {
                case (int)MenuItemType.Home:
                    MenuPages.Add(id, new NavigationPage(new HomePage()));
                    break;
                case (int)MenuItemType.About:
                    MenuPages.Add(id, new NavigationPage(new AboutPage()));
                    break;
                case (int)MenuItemType.Add:
                    MenuPages.Add(id, new NavigationPage(new AddPage()));
                    break;
            }
        }

        var newPage = MenuPages.ContainsKey(id) ? MenuPages[id] : null;
        if (newPage != null && Detail != newPage)
        {
            Detail = newPage;
            IsPresened = false;
        }
    }
} 

Now we can send the Message from our MainViewModel like this:

private void AddCommand(object obj)
{
    MessagingCenter.Send<string, int>("AppName", "NavTo", (int)MenuItemType.Add);
    //MenuItemType is an Enum.
}

In the above example, the AddCommand sends a Message of NavTo with the Add Parameter. The main page which is already subscribed to this will try to Navigate based on the parameters provided.

As shown above, you can easily perform Page Navigation using MessagingCenter.

Happy Coding!!!




MessagingCenter is Everywhere

Messaging Center
Messaging Center- Image used from https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/messaging-center

Did you know that the concept of MessagingCenter is seen everywhere even in our daily life? Before moving into this, I would recommend reading this Documentation on MessagingCenter.

MessagingCenter primarily consist of Publisher and Subscriber.
Publisher’s job is to keep on publishing messages.
Subscriber’s job is to subscribe to specific messages and perform some action whenever a desired message is published.

Let’s look at this mechanism and how we see it in our daily life…
Think of it in this way, you as a user of Mobile Phones, are always subscribed to the Notifications that are delivered to your device. A notification sound is like a message which triggers you to check your Phone. It’s like your Device is communicating with you through a specific Sound. For example, if the sound is that of your ring-tone you will always check your Phone for Incoming Calls. In this scenario, your Phone is the Publisher and you are the Subscriber.

Not just this, you are given a Name by Birth and whenever even in the crowd you hear your name even though there are people discussing someone else you immediately react to it. It’s like you are inherently Subscribed to your Name and anything followed through as arguments to the action that needs to be performed.

I believe this was just a simple explanation that popped up in my mind while explaining to a friend of mine.

Happy Coding!!!

Building a Phone Dialler for Families and Friends using Xamarin – Part 2

Hello, people, I am back to talk more into the developments of my App. I am trying to name the App as Family Dialler. In case you have any better name, please do reach out or comment below. If any of you are a designer, please do help me with the look and feel of this App.

Family Dialler

Well, the App is now working to some extent in Debugging Mode. I am first working on a skeleton of the App with the minimum designs and layouts. I am doing this to test the functionalities that are required to go further with the App requirements.

NuGet Packages

I am listing some of the NuGet packages that I have come across and using them or am thinking of using in the future (as the App progresses). I have been maintaining a list of these packages and will keep on updating the same in a post published earlier.

I can access the Contacts as we speak and can perform the basic CRUD operations on my favorite contacts. Looking forward to finishing some more things đŸ™‚

Building a Phone Dialler for Families and Friends using Xamarin – Part 1

The idea was to create a Phone Dialler where I can mark my folks (friends and families) as Favorites. You might think that we already have similar functionality available in our current Dialer, so why re-invent the wheel.

However, the way I want to do is that we have a different kind of implementation and that the dialer is something that intrigues me. So let’s see how far I can go into.

Now, in order to achieve this, obviously I will use my favorite IDE i.e., Visual Studio and the technology would be Xamarin.

The Basic Functionality

Let’s try to examine the blocks involved in this kind of App and the basic requirements in order to achieve this. Definitely, we can have other services that can be attached to it at a later point in time but then let’s keep the options to a basic minimum for now.
For the App to work, I would need to access the Phone Contacts as well as Call Logs. The App should have existing Contacts accessed from the Device, Call Logs to access the History, as well as an SQLite DB to maintain the favorites. Let’s not forget the Dialer Pad for dialing numbers directly.

  • Permissions:
    • Access Phone Contacts (Read and Write)
    • Access Call Logs (Read and Write)

To build the UI, we can always make use of ListViews, MasterDetail Pages, etc., to render the desired UI. I will definitely make use of the NuGet packages to get some faster results.

I have already started pushing in my code to GitHub. Once the Code is ready in terms of basic functionality, I will make it public, but for now, let’s hang onto it.

NuGet Packages for Xamarin

Well, since I have been working on lots of Xamarin stuffs, I thought it’s sometimes best to list down the NuGet packages that are really amazing and helps you create the boiler plate of your App in a much easier and faster way.

The NuGet Packages

Let’s look at the worthy NuGet packages which are worth looking into.

NameDescriptionPlatforms
Acr.UserDialogsA cross platform library that allows you to call for standard user dialogs from a shared/portable libraryXamarin.Android Xamarin.iOS UWP Xamarin.Forms
SQLiteNetExtensionsSQLite-Net Extensions is a very simple ORM that provides cascade operations, one-to-one, one-to-many, many-to-one, many-to-many, inverse and text-blobbed relationships on top of the sqlite-net library.Xamarin.Forms
Rg.Plugins.PopupPlugin for Xamarin Forms. Allows you to open any page as a popup. Xamarin.Forms
Xamarin.Forms.DebugRainbows Adds a very colorful debug mode to each of your ContentPages that lets you immediately see where all of your elements are located. Xamarin.Forms
AkavacheAn asynchronous, persistent key-value store for desktop and mobile applications on .NETXamarin.Forms

I will keep updating this list as I keep encountering on these stuffs. Feel free to let me know if there are some I have missed.

Happy Coding!

ContentResolver for Xamarin.Forms

We often face some challenges when working with Xamarin.Forms.
In a similar instance, I faced one when trying to read Contacts. I found myself in a fix because the data that I had received for an Image was basically a URI with type content://

The data retrieved from the Contact for a Thumbnail was something like this:
content://com.android.contacts/contacts/29059/photo

Obviously, Xamarin.Forms is fully equipped to deal with any sort of ImageSource that comes in its ways, except something that is directly a platform specific.

In order to render this, I went ahead with DependencyServices.
Here’s my implementation for this:

IContentImageService.cs
public interface IContentImageService
{
    Stream GetImageUri(string contentUri);
}
ContentResolverMethods.cs
[assembly: Xamarin.Forms.Dependency(typeof(ContentResolverMethods))]
namespace YourNamespace.Droid.Dependencies
{
    public class ContentResolverMethods : IContentImageService
    {
        public Stream GetImageUri(string contentUri)
        {
            var uri = Android.Net.Uri.Parse(contentUri);
            return Android.App.Application.Context.ContentResolver.OpenInputStream(uri);
        }
    }
}

Now in order to use this, you can always invoke the method implemented in Android using DependencyServices from within the Xamarin.Forms Project which is either a .NetStandard, Shared or a PCL based project

var stream = DependencyService.Get<IContentImageService>().GetImageUri(imageUri);
return ImageSource.FromStream(() => stream);

Happy Coding!

Disable Screenshot in App

Many a times we have seen App which detect and won’t allow us to take screenshots. So as an App developer on Xamarin, it’s quiet intriguing to know how to achieve that. Turns out, it’s just a line of code that would allow us to achieve that.

this.Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);

Setting up the Flags for Window Manager does the job. Now just add this in a Blank Android App and test it out. You will see that it works just like that.

Happy Coding!

Xamarin.Forms Label Renderer for Displaying many lines

I am back again with a post on Xamarin.Forms Custom Renderer. My earlier post was on the creation of a Custom Renderer for Entry.

Well, this time, we are going to solve something different which might not have been faced by many users. Sometimes, it happens that you want to display some lines of Text to the user like Read Me or just some Random text. For instance, consider the following code snippet:

<Label Text="{Binding SomeText}" HorizontalOptions="Fill">

Here, when the App is run, the text will be filled in the Label. However, if the number of lines crosses 100, the text will get clipped. In case, you want some more lines, you can always create a Custom Renderer for Label.

You can try to create something like this:

In Android

public class CustomLabelRenderer: LabelRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);
        Control.SetMaxLines(500);
    }
}

In iOS

public class CustomLabelRenderer : LabelRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);

        if (Control != null)
        {
            UILabel label = Control;
            label.Lines = 500;
        }
    }
}

Hope this helps someone.

Happy Coding!