Search

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Saturday, December 28, 2019

How to Prevent memory leak and Profiling in Xamarin applications


Mobile Application planning, development, testing and  deployment go well as per the customer estimation but after a while the client was clamoring that the app is getting slower and slower when it was continuously being used up to the point where it will just crash suddenly but most of the developer unaware why it’s like this. In this article, you are going to learn how to use prevent memory leak and profiler in Xamairn Application. 

Garbage Collection:

We all know that in the .NET world we have a very good friend called Garbage Collector. Basically, it is responsible on freeing up the used memory. As simple as it sounds, whether you are in a Desktop, Web or especially mobile where there are two worlds one is Managed and the other one is the native part which at times Garbage Collection is not enough to reclaim those used memories the cause of the slowdown Mobile app is due to Memory Leaks.

Beware of common memory leak sources:

You do incorrect memory management wherein an object is stored in memory but cannot be accessed by the running code, it’s always causing a memory leak in mobile application. We all Knows what we can’t do but still we are doing as like below image, Same in Mobile Development also we all knows what can’t do, but still we are doing same mistake
I suggest to be extra careful when using below C# feature, and proactively check for memory leaks with techniques like the last best practice.
  • Events, delegates or Messaging Centers in .NET are notorious for causing memory leaks. You can innocently subscribe to an event, causing a damaging memory leak without even suspecting. 
  • Custom control and Unknown Nuget package are event registered, such as Loaded, will not be unloaded until all events are unregistered. Always remember to unregister your events when you don't need them anymore and we are not sure all the objects or disposed.
  • Images is a classical .net GC-Java GC problem when GC isn't aware of image size and won't release reference unless it is Disposed.
  • Static variables, collections, and static events in-particular should always look suspicious. Remember that all static variables are GC Roots, so they are never collected by the GC.
  • Caching functionality in mobile apps is necessary, any type of caching mechanism can easily cause memory leaks. By storing cache information in-memory, eventually, it will fill up and cause an OutOfMemory exception. 
  • Bindings can be dangerous. The rule of thumb is to always bind to a DependencyObject or to a INotifyPropertyChanged object. When you fail to do so, Xamarin will create a strong reference to your binding source (meaning the ViewModel) from a static variable, causing a memory leak
  • Threads that never terminate – The Live Stack of each of your threads is considered a GC Root. This means that until a thread terminates, any references from its variables on the Stack will not be collected by the GC. This includes Timers as well. If your Timer’s Tick Handler is a method, then the method’s object is considered referenced and will not be collected. 

Preventing Memory Leaks:

Enterprise Mobile application knows memory leaks are like overloaded people in a Bus or train. You might not notice when there are few of them, but you always make sure people enter in the bus with very limited and identify bus capacity based on that you need to allow the people into the bus. In Mobile application you should define to developer with strike rule and TODO List and make sure your code review taken care following option for prevent memory leaks 

Using Statement:

Xamairn Mobile application constantly uses unmanaged resources. The .NET framework itself relies heavily on unmanaged code for internal operations, optimization. Anytime you use StreamsGraphics, or Files for example, you are probably executing unmanaged code. The using statement transforms the code into a try / finally statement behind the scenes, where the Dispose method is called in the finally clause.
public void CreateFile()
{
    using (var stream = new FileStream(@"\Document\SomeFile.txt",
                                       FileMode.OpenOrCreate))
    {
        // do stuff

    }// stream.Dispose() will be called even if an exception occurs


Dispose pattern:

You implement a Dispose method to release unmanaged resources used by your application. The .NET garbage collector does not allocate or release unmanaged memory. The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object.Finalize override. Learn more MSDN portal .
public void Dispose()
{
   // Dispose of unmanaged resources.
   Dispose(true);
   // Suppress finalization.
   GC.SuppressFinalize(this);
}


Test for memory leaks:

It’s a great practice to proactively test for memory leaks. And it’s not that hard. Here’s a short pattern you can use in the unit testing project.
[Test]
void MemoryLeakTest()
{
  var weakRef = new WeakReference(leakyObject)
  // Ryn an operation with leakyObject
  GC.Collect();
  GC.WaitForPendingFinalizers();
  GC.Collect();
  Assert.IsFalse(weakRef.IsAlive);
}


Getting Started Profiling:

Xamarin Profiler is a great tool created by Microsoft wherein it gives developers ways to profile or collect telemetry with your Mobile Applications using Visual Studio. It can also be paired with native profilers, like Xcode Instruments and Android Profiler, to ensure better app behavior and performance. The main function of the profiler is to collect and displays information about the Mobile App wherein the Developer can pinpoint, analyze and optimize areas in their application for a smooth experience by end users. There are different ways the Xamarin Profiler can help us like statistical.
The Xamarin Profiler has many features Allocation, Cycles, Data presented on each screen and Time profiler. It’s a graphical interface for the Mono log profiler, and supports profiling for following platform in Windows and mac machine.
  • Android, iOS, tvOS, and Mac applications on Mac
  • Android, iOS, and tvOS applications on Windows.
In this section, will learn common profiling scenarios and analyze and optimize iOS and Android applications.

Prerequisites:

We need Visual Studio Enterprise subscriber to unlock Profiler feature in either Visual Studio Enterprise on Windows or Visual Studio for Mac on a Mac. Download install following package in your mac or windows machine.
After successful installation, let get satrt use Profiling in Xamarin iOS and android application. Integrate Profiling is very simple steps, you need changes Project Property options in iOS and Android Project. 
Create new Xamairn Forms project using Visual Studio and Select iOS and Android platform is supported and follow below two steps for enabling the profiling in iOS and Android Project.

Android:

In Android Project, Right click on project > Select property > Select “Android Options” > Select options “Enable developer instrumentation”.


iOS:

In iOS Project, Right click on Project > Select Property > Select “iOS Debug” Options and check the check box “Enable Profiling”.


Start the Xamarin Profiler:

Step 1: Build and run the application in iOS or Android. 
Step 2: In Visual Studio menu, Select Analyze or Tools main menu > Select Xamarin Profiler and open the Profiler and make sure before open profiler, the application needs to be built at least once in order to start a profiling session.
The Xamarin Profiler comes with following instruments: 
  • All Instruments
  • Allocations. 
  • Time Profiler. 
Once you have selected a Allocations options and you can also configure some options of how the memory profiling will proceed. You can either customize the frames, frequency or either select from the presets as shown below image.
Once you have clicked the Start Profiling button it will automatically launch your selected application on the selected device and you will be greeted with this window
In that above image denoted number with green marked and detail info below 
  • No 1 - Represents the actual graph of the Memory consumption with respect to time.
  • No 2 - Represents the different data categorized on your selected tab.
  • No 3 -Represents the information (Object name, count, size) displayed based on the selected tab.
  • No 4 - Represent the real time display of information based on the current snapshot.
  • No 5 - Represents the Selected device and the Application that is currently running.

Snapshots:

Snapshots pane displays information about memory snapshots. To generate these while profiling a live application, click the Camera button in the toolbar at each point that you'd like to see what memory is retained and released. You can then click each snapshot to explore what is happening under the hood. Note that snapshots can only be taken when live profiling an app.

Time Profiler

The Time Profiler instrument measures exactly how much time is spent in each method of an application. The application is paused at regular intervals and a stack trace is run on each active thread. And Call Tree options will show amount of time spent in each method.
I hope you enjoyed for learning profiling and prevent memory leak issue. Let me state that Profilers are not only for memory leaks but also can be used in code optimization. Finally moving forward maybe you can also adapt or put in your development routine the profiling of your mobile applications.

Summary

I hope this article gave you some value to you, let we take a new year’s resolution is better memory management while doing C# programing. Please leave your feedback/query using the comments box, and if you like this article, please share it with your friends





Friday, September 27, 2019

Just spend 15 min to complete Xamarin and Azure Functions Challenge

****The challenge begins 23 September 2019, and ends on 23 October 2019.*****
I have successfully completed the Xamairn Azure Function Challenge and the goal of the challenge is to create a serverless Azure Function and connect it to a Xamarin mobile app. You can refer one of my previous article for Building Serverless Mobile App With Azure Functions Using Xamarin.Forms.
Are you interested to do? if xamairn setup is ready in your machine, then spend only 15 min for completing the challenge, otherwise it required some prerequisites installation setup.


Challenge Prize:

  • Ten (10) Grand Prizes: Each winner will receive Microsoft Surface Headphones
  • One Thousand (1,000) Prizes: Each winner will receive a 3-month Xbox Game Pass
Prerequisites:
  • You can use any Windows or macOS for development.
  • On Windows, Download and install Visual Studio 2019 Community (i.e. free) with the Xamarin workload using our Xamarin-optimized installer. 
  • On macOS, Download and install Visual Studio 2019 Community for Mac.
  • To deploy and run your Azure Functions, you first need an Azure account. You can sign up for a FREE account here.
Start the Azure Functions Challenge:
Task 1: Clone Xamarin Azure Challenge project from github repository.
Task 2:  On Windows Machine, refer here for publish the Azure function or if mac machine, refer here for publish the Azure function 
Task 3: Configure the Azure function to the Azure portal. 
Task 4: Configure the Xamarin App.
Task  5: Run the Xamarin application using iOS or Android Platform .
Congratulations:
Provide the Basic your information, accept the terms and click on submit. You've successfully completed the Xamarin Azure Challenge. You will get email very shortly. All the best 

Thursday, September 26, 2019

Building a Cross Platform MVVM Pattern with ReactiveUI and Xamarin.Forms


As a Mobile Developer, when we start a new project, we always search and speak about application architecture. One of the most common choices in Xamarin.Forms is MVVM, this is due to the small amount of work to implement it, if we use ReactiveUI, we can additionally write applications in a reactive manner. It’s a time to check reactive UI how we can implement in Xamairn Forms project.
Reactive Extensions have been around for many years, and is available to most development environments. In this post, we are specifically going to look at Rx in terms of .NET development in Xamarin Forms. 
Rx is just a library for composing asynchronous, and event-based code with observables, and configuring it via LINQ. You can use LINQ to define criteria of when you want to perform an action, on the event. Rx can do more, but we will only look at the very basics in this post.
ReactiveUI allows you to combine the MVVM pattern with Reactive Programming using such features, as WhenAnyValue, ReactiveCommand, ObservableAsPropertyHelper, Binding and WhenActivated.
Create New Xamarin.Forms Application
In order to learn the ReactiveUI, let’s start creating a new Xamarin.Forms project using Visual Studio 2019 or VS for Mac. When using Visual Studio 2019 on a Windows machine, you will need to pair the mac machine for run and build the iOS platform.


Open Visual Studio 2019 >>Create a New Project or select "Open Recent Application" and the available templates will appear on a Windows like below. Select Xamarin.Form app and click on “Next”


ReactiveUI Nuget Package:
To implement ReactiveUI in our applications we will need to install the library. 
Step 1: Right click on Project and Click on Manage NuGet Packages for Solution option. 
Step 2: Search for “ReactiveUI.XamForms”.
Step 3: Install it for all of our projects with each platform. 


Create ViewModel :
ReactiveUI syntax for read-write properties is to notify Observers that a property has changed. Otherwise we would not be able to know when it was changed.
  • In cases when we don't need to provide for two-way binding between the View and the ViewModel, we can use one of many ReactiveUI Helpers, to notify Observers of a changing read-only value in the ViewModel.
  • RaiseAndSetIfChanged fully implements a Setter for a read-write property on a ReactiveObject, using CallerMemberName to raise the notification and the ref to the backing field to set the property.
  • ReactiveCommand is a Reactive Extensions and asynchronous aware implementation of the ICommand interface. ICommand is often used in the MVVM design pattern to allow the View to trigger business logic defined in the ViewModel
Let we create following property and command in the following ViewModel 
using System;
using System.Threading.Tasks;
using ReactiveUI;
using System.Reactive;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Reactive.Linq;

namespace ReactiveUIXamarin.ViewModel
{
    public class MainPageViewModel: ReactiveObject
    {
        private string _result;
        public string Result
        {
            get => _result;
            set => this.RaiseAndSetIfChanged(ref _result, value);
        }
        private string _username;
        public string UserName
        {
            get => _username;
            set => this.RaiseAndSetIfChanged(ref _username, value);
        }
        private string _password;
        public string Password
        {
            get => _password;
            set => this.RaiseAndSetIfChanged(ref _password, value);
        }
        private string _address;
        public string Address
        {
            get => _address;
            set => this.RaiseAndSetIfChanged(ref _address, value);
        }
        private string _phone;
        public string Phone
        {
            get => _phone;
            set => this.RaiseAndSetIfChanged(ref _phone, value);
        }
        public ReactiveCommand<Unit, Unit> RegisterCommand { get; }

        public MainPageViewModel()
        {
            RegisterCommand = ReactiveCommand
                .CreateFromObservable(ExecuteRegisterCommand);
        }

        private IObservable<Unit> ExecuteRegisterCommand()
        {
            Result = "Hello" + UserName + " Registration Success";
            return Observable.Return(Unit.Default);
        }
    }
  
}


Create UI View:
ReactiveUI allows you to create views using two different approaches. The recommended approach is using type-safe ReactiveUI bindings that can save you from memory leaks and runtime errors. The second approach is using XAML markup bindings.
The following sample UI created by recommended approach using type-safe ReactiveUI .
<rxui:ReactiveContentPage
  x:Class="ReactiveUIXamarin.MainPage"
  x:TypeArguments="vm:MainPageViewModel"          
  xmlns:vm="clr-namespace:ReactiveUIXamarin.ViewModel;assembly=ReactiveUIXamarin"
  xmlns:rxui="clr-namespace:ReactiveUI.XamForms;assembly=ReactiveUI.XamForms"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core" 
  xmlns="http://xamarin.com/schemas/2014/forms"
    ios:Page.UseSafeArea="true">
    <StackLayout>
        <Entry x:Name="Username" Placeholder="Username"/>
        <Entry x:Name="Password" Placeholder="Password"  />
        <Entry x:Name="Address" Placeholder="Address"  />
        <Entry x:Name="Phone" Placeholder="Phone Number" />
        <Button x:Name="Register" Text="Register" TextColor="White" BackgroundColor="Gray" />
        <Label x:Name="Result" />
    </StackLayout>
</rxui:ReactiveContentPage>


  • ContentPage should inherit from ReactiveContentPage<TViewModel> and we are going to use ReactiveUI Binding to bind our ViewModel to our View. 
  • Reactive binding is a cross platform way of consistently binding properties on your ViewModel to controls on your View. 
  • The ReactiveUI binding has a few advantages over the XAML based binding. The first advantage is that property name changes will generate a compile error rather than runtime errors.
  • One important think needs to follows while Binding, always dispose bindings via WhenActivated, or else the bindings leak memory.
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using ReactiveUIXamarin.ViewModel;
using ReactiveUI.XamForms;
using System.Reactive.Disposables;

namespace ReactiveUIXamarin
{

    public partial class MainPage : ReactiveContentPage<MainPageViewModel>
    {
        public MainPage()
        {
            InitializeComponent();
            ViewModel = new MainPageViewModel();

            // Setup the bindings.
            // Note: We have to use WhenActivated here, since we need to dispose the
            // bindings on XAML-based platforms, or else the bindings leak memory.
            this.WhenActivated(disposable =>
            {
                this.Bind(ViewModel, x => x.UserName, x => x.Username.Text)
                    .DisposeWith(disposable);
                this.Bind(ViewModel, x => x.Password, x => x.Password.Text)
                    .DisposeWith(disposable);
                this.Bind(ViewModel, x => x.Address, x => x.Address.Text)
                   .DisposeWith(disposable);
                this.Bind(ViewModel, x => x.Phone, x => x.Phone.Text)
                   .DisposeWith(disposable);
                this.BindCommand(ViewModel, x => x.RegisterCommand, x => x.Register)
                  
                    .DisposeWith(disposable);
                this.Bind(ViewModel, x => x.Result, x => x.Result.Text)
                   .DisposeWith(disposable);
            });
        }
    }
}


Output:
You can download the source code from github repository. When you run the application in an iPhone device, you will get the following output and click on Register, it will show the confirmation message like below screen.
Summary
This article has demonstrated and covers a little bit of what you can do when you combine the power of Reactiveui in Xamarin.Forms. I hope this article will help you to get started with awesome Framework.