© Gerald Versluis 2017

Gerald Versluis, Xamarin.Forms Essentials, https://doi.org/10.1007/978-1-4842-3240-8_8

8. Using Good Libraries That Are Already Out There

Gerald Versluis

(1)Sittard, The Netherlands

Throughout this book I have mentioned that there are a lot of good libraries out there. Some of them I have mentioned by name, others I didn’t mention at all. This chapter lists a couple of libraries that come in very handy in various scenarios.

For each library, I will give you a brief overview of what it does and provide links to the project web site.

I once more want to emphasize that installing a NuGet often means that you have to install it on the shared project and the platform project. While I am writing this book, we are also in the transition from PCL libraries to .NET Standard libraries. There are some libraries that do not support .NET Standard yet or the other way around; they have dropped support for PCLs already. Be sure to check your requirements before you get yourself into trouble halfway there.

To overcome the dropped support of the .NET Standard library, you could install an older version of the NuGet. However, realize that you are not working with the latest version and it could contain bugs or not have implemented the latest features. Use it as a last resort.

FreshMvvm

I have mentioned this library a couple of times. This is my favorite MVVM framework for Xamarin.Forms to date. This framework by Michael Ridland is very lightweight and adds just the right number of missing features. With the built-in IoC container, setting up dependency injection is a breeze.

Since I have already written a lot about implementing FreshMvvm, I won’t go over it again here, but be sure to check it out. There are many more possibilities than the things I have shown you.

The project can be found on GitHub at https://github.com/rid00z/FreshMvvm .

Refit

Another library I mentioned in the previous chapter is Refit by Paul Betts. This library is super handy for getting rid of all the repeated code you have to write for communicating with your REST API backend. By simply defining the outline of your API in an interface, the rest of the code is generated for you!

The features I have shown you in Chapter 7 just start to scratch the surface. This is enough to get you started, but don’t be fooled into thinking that is all. If you want more advanced scenarios, it’s all supported. I have yet to find a missing feature and I have built an app or two with this.

The source code and documentation for this project can be found at https://github.com/paulcbetts/refit .

Polly

One library that I didn’t mention yet is Polly. This library takes error handling to the next level. Things like retry mechanisms with incremented intervals, defining policies, circuit breaking, fallbacks, and timeouts are all in here. All of this goodness is very easy to implement with the fluent syntax.

This kind of functionality comes in rather handy if you're working with connections that aren’t always stable, like with mobile devices. You might want to retry a request a couple of times before handing the error to your user.

Especially when used together with other smart mechanisms like Akavache, which you will see next, this can be a very powerful library to provide a good user experience, even when things start to go bad.

The project can be found on GitHub at https://github.com/App-vNext/Polly .

Akavache

This library is all about caching and storing key-value data. The most I’ve used it for is caching. You can very easily implement this library in your services in the app, to provide the user with cached data while fetching live data in the background. That way, the user is never presented with an empty screen, which provides for a better user experience.

We use this library in the HIBP app. You can see the full code at https://github.com/jfversluis/been-pwned/blob/master/src/BeenPwnedApp/Core/Services/BeenPwnedService.cs , but I also provide the relevant snippet in Listing 8-1.

Listing 8-1 Sample Implementation of Working with Akavache
internal IObservable<IEnumerable<Breach>> GetAllBreaches(bool force = false)
{
        var cache = BlobCache.LocalMachine;
    return cache.GetAndFetchLatest("breaches", async () => await _pwnedClient.GetAllBreaches(),
        offset =>
        {
            //If there is no network connection available, always return false so that the user will get cached data if available
            if (CrossConnectivity.Current.IsConnected)
            {
                TimeSpan elapsed = DateTimeOffset.Now - offset;
                var invalidate = (force || elapsed > new TimeSpan(24, 0, 0));
                return invalidate;
            }
            else
                return false;
        });
}

This method retrieves all the breaches in the system. We use the GetAndFetchLatest method to call on the cache store. This method takes three parameters. The first is a string, which specifies the key to store the retrieved values. Second is the method that will be used to retrieve the actual data. Lastly, there is the method to determine whether new data is to be fetched. You can implement logic to determine if your data is still relevant, or if it has to be invalidated. It’s as easy as that!

By returning the IObservable type, we can hook into the callback on our PageModel and update the data whenever it comes in. This way, the user gets it without probably even noticing.

Details for all of this can be found at https://github.com/akavache/Akavache .

Fusillade

Another library by Paul Betts is Fusillade. He calls it “an opinionated HTTP library for mobile development”.

You can use this library to optimize your calls to the backend. Basically, it provides a set of HttpMessageHandlers that makes handling web requests more efficient and therefore more responsive.

The things Fusillade can do for you include:

  • Automatic deduplication of requests: Imagine that you’re building a social media app and each item in the list can have the same avatar and username of certain users. Fusillade will detect the same request to that avatar and execute it only once, saving a lot of unnecessary requests.

  • Limiting requests: Requests are limited to four at a time by default. This limits the pressure on the—sometimes limited—network connection.

  • Prioritizing requests: You can implement some mechanics to let Fusillade know if a load has been initiated from the background or by a user. In the latter case, the request will be rendered more important and is prioritized over others.

  • Speculative requests: You can implement a pre-load mechanism for certain requests that you expect the user to click on so it will load faster, simply because it is already loaded. You can specify the amount of maximum content to be pre-loaded.

So, all in all, pretty powerful stuff. It can be somewhat tricky to implement, but it can also help you get that last bit of optimization.

This project is found on GitHub at https://github.com/paulcbetts/Fusillade .

Settings

There are quite a few libraries by James Montemagno, a former Xamarin, now Microsoft, employee. The whole list of plugins he has been writing or contributing to can be found at https://github.com/jamesmontemagno/Xamarin.Plugins .

Xam.Plugins.Settings is one of them. As you might have guessed, this plugin is all about settings. It can be used to store all kinds of application settings for your users. You can also do this by using Application.Current.Properties and leveraging the .NET configuration engine, but this plugin uses the native way for each platform.

When you install it, you will be presented with a helper class that has some boilerplate code, as shown in Listing 8-2.

Listing 8-2 Helper Class As Provided by the Settings Plugin
public static class Settings
{
    private static ISettings AppSettings
    {
        get
        {
            return CrossSettings.Current;
        }
    }


    #region Setting Constants

    private const string SettingsKey = "settings_key";
    private static readonly string SettingsDefault = string.Empty;


    #endregion

    public static string GeneralSettings
    {
        get
        {
            return AppSettings.GetValueOrDefault(SettingsKey, SettingsDefault);
        }


        set
        {
            AppSettings.AddOrUpdateValue(SettingsKey, value);
        }
    }
}

You can see that this is very easy to extend. Just add a new property for each setting that you want and, by simply setting a value, it is directly saved. You can also bind directly to the properties in this class from your user interface to have the users configure their settings.

Note that only simple types are supported.

This project is hosted on GitHub at https://github.com/jamesmontemagno/SettingsPlugin .

Connectivity

Seeing that we have talked about the network connection on a mobile device a couple of times now, it seems that is important. And it is! That’s why I did not want to keep this plugin from you. It’s called Xam.Plugin.Connectivity , also by James Montemagno.

With this library, you can check whether you have a connection and if you can reach certain hosts. It also allows you to hook into the event of the connection status changing. Before, I talked about how to handle failed requests and recover. With this connectivity library, you can check beforehand if a connection is available and working and inform your users proactively.

You have seen it in action in Listing 8-1. There is a line that reads: CrossConnectivity.Current.IsConnected. With this simple line, you can determine if the device is connected. If it’s not, the code doesn’t even bother trying the request. This is also very helpful when you’re updating your UI, by informing your user to check their connection.

The source and documentation for this library can be found at https://github.com/jamesmontemagno/ConnectivityPlugin .

PropertyChanged.Fody

Just like with Refit, implementing the INotifyPropertyChanged interface will create a lot of similar code in your project as well. You saw this in Chapter 5.

To be able to omit a lot of this code and make it more readable, you can use the PropertyChanged.Fody library. You drop in this library and have your classes implement the INotifyPropertyChanged interface. The code for triggering the UI update is generated automatically at runtime for your properties with a setter. There are also a lot of attributes available that you can use on your properties to influence the generated code. For instance, you can use the AlsoNotifyFor attribute to trigger the update for another property that needs to be updated in conjunction with the first one.

You can read all about this project at https://github.com/Fody/PropertyChanged .

FFImageLoading

Loading, showing, and transforming images can be a difficult task. With FFImageLoading (Fast & Furious Image Loading), working with images is easy.

This library is capable of a lot. At the very core, it can be used to cache images. Downloading images from the web can involve expensive calls. By caching these images, you can cut back on loading times and data usage of your app. Another thing that is not uncommon when working with images is excessive memory usage. When you squeeze in images that are too big, your app will eat up the memory and become unusable. With FFImageLoading, you can downsample your images to the right size, and it will not use excessive memory.

Usage is easy; you just install the library—remember: on all your projects—and use the CachedImage element instead of the normal Image element. And that is it for the basic usage. On the CachedImage element, you now have a lot of properties at hand to optimize viewing your pictures. On top of that, you also get placeholders for when the image is loading or when an error occurs while loading and much more.

You can also install the separate Transformations package. With this package, you can apply all kinds of transformations to your image. Think of transformations like blurring, creating a circular image, or converting an image to grayscale. You can even add your own transformation if it isn’t supplied by default. It is used in the “been pwned” app as well, as it supports SVG images.

The GitHub repository for this library can be found at https://github.com/luberda-molinet/FFImageLoading .

UserDialogs

In Forms, you can only spawn a dialog directly from a page. This is a problem, because we want all our logic to happen in the PageModel. That is where UserDialogs, by Allan Ritchie, comes in. With the UserDialogs plugin, you can create dialogs with a static class from anywhere in your code. It doesn’t stop there. It also provides you with confirmation boxes, toasts, and other kinds of dialogs that aren’t supported by Xamarin.Forms directly.

Actually, there isn’t much more to say about it. It just works!

Find the GitHub at https://github.com/aritchie/userdialogs .

FormsCommunityToolkit

I have talked a bit about effects, converters, and behaviors. These can be used for accessing native properties, converting data binding values, and applying logic to elements, respectively. While custom implementations of these concepts are very easy to do, it’s not recommended to duplicate it into all of your projects.

The FormsCommunityToolkit tries to unify some of the most implemented effects, converters, and behaviors.

For example, in this package you can find effects to remove the border on an Entry or disable the autocorrect functionality. These are things that aren’t supported by Xamarin.Forms out of the box. If you want custom colors on your Switch control, this is the library for you.

There are behaviors for validating an e-mail address or numeric values and turning events into commands. Or what about the hex-to-color converter, or maybe you want your text to be converted to uppercase letters. All of these features are included in this package for you to use, and much, much more. If there is anything you’re missing, the developers gladly accept pull requests for anything.

I have contributed a thing or two to this library, so I would be happy to know if you like it!

This toolkit can be found on GitHub at https://github.com/FormsCommunityToolkit/FormsCommunityToolkit .

Other Tooling

Besides all the libraries that are out there, there is also tooling that allows you to be more productive. The following subsections describe some of the tooling options that is available.

MFractor

This one I mentioned earlier; it’s MFractor by Matthew Robbins. This tool helps you fill the gaps that IntelliSense sometimes leaves when working with Xamarin and especially with XAML. It will notice missing properties in your PageModels or detect that it is of the wrong type and generate a converter for you.

Where it really helps is with the import wizard for images. It resizes images to the right dimensions and names them appropriately for all the different platforms. It is such a wonderful tool!

It has a free version, which is great, but to support Matthew , I suggest getting the paid version. It is money well spent. He is not paying me to say this, I swear!

As I am writing this book, only a Mac version is available for Visual Studio for Mac, but I know they are working hard to support Windows as well. By the time you are reading this, it may already be released. For the latest information, visit https://www.mfractor.com/ .

Third-Party XAML Previewers

Nowadays, Xamarin.Forms has a XAML previewer incorporated in Visual Studio. It isn’t perfect yet, but it helps a lot. While the default previewer was absent, some people have taken it upon themselves to create their own. They all offer mostly the same functionality, so there is no point in describing them all in detail. These previewers can save you some time! Instead of having to move an element pixel-by-pixel or change just a shade of that one color and then rebuild and run your whole app just to see it’s still not right, you can now see changes happening live.

The two most notable XAML preview tools are these:

Xamarin Live Player

Another great “tool” is the recently introduced Xamarin Live Player by the team at Xamarin. You install this app on your physical device from the app store. Then you can see a preview of your app, right on your phone while you’re working on it.

You start your project, scan a QR code with your phone. From that point on, every change you make is instantly available on your phone to review. This makes debugging on a physical device a whole lot easier. At the time of writing this book, the tool is in preview.

Everything about the Xamarin Live Player can be found at https://www.xamarin.com/live .

Summary

There is a very active and awesome community for Xamarin and Xamarin.Forms. Because of these smart and driven people, there is a lot of content already out there for you to use. If you need a custom control or need to access native device functionality, see if someone else has created a solution first. Chances are that there is already someone who has created something for you, ready to use. If you miss anything, they are open for suggestion and participation on their open-source projects.

This chapter showed you a handful of great libraries that I use in my almost every project. But this is just the tip of the iceberg. I hope you found it useful to get a glimpse and are eager to implement these into your own apps. Note that not all of these libraries are specific to Xamarin. You can use them in your other .NET applications as well.

In the next chapter, we look into the future. I describe in some detail what is to be expected of the next major version of Xamarin. Maybe the new version will already be out by the time you are reading this. If so, you can treat them as features you can use today!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.166.113