Search

Xamarin Profiler and Memory Management

App memory management has become one of the key priorities for any developer today. With new-gen energy-efficient processors launching every day &  operating systems shifting towards efficient power usage along with sleek UI experience, today’s developers face a challenge of developing apps that are sleek & efficient in memory management along with an intelligent tool to check memory leakage proactively. In this article, I will be covering two major topics i.e. xamarin profiler (Part 1) and memory management (Part 2). Part 1: Xamarin Profiler Introduction to Xamarin Profiler: Xamarin Profiler is a tool developed by Microsoft that helps the developers to analyze the app's behavior, and its memory allocations with the help of a visual studio. It is a graphical interface that supports doing profiling in android, ios, tvos, mac applications in mac and android, ios, tvos applications in windows.  Why use a profiler: We all know that sometimes we don't properly dispose of the objects and therefore the garbage collector will not collect them and remove them from the memory.   In other words, with the help of the profiler, we can check memory leaks that are being held by objects which should ideally be disposed of.  Before that, let's understand how the operating system manages the memory. There are two types of memory, native memory and managed memory. All the ios and android related objects like views, example buttons, text views fall into the native memory and the dot net-related objects, for example, subscriptions, event handlers, threads go into managed memory. Whenever there is a process, the operating system gives a small piece of this memory chunk to xamarin mono. So in order to check the memory allocations of managed memory, we need a profiler.  Garbage Collector: Before getting started with the profiler, let's understand what a garbage collector is. The garbage collector collects the disposed objects and frees up the memory.  As I discussed above there are two memory worlds in the operating system, native memory, and managed memory. Sometimes garbage collectors cannot do their job, because some of the dot net objects may be holding reference to native objects or vice versa. In such cases, it is difficult to understand where the memory leak is happening. So this is where the profiles come into the picture.  Prerequisites: Visual Studio (Mac or Windows) Enterprise license Device or emulator Download And Installation: Step 1: Download and install the profiler for windows from the below link https://docs.microsoft.com/en-us/xamarin/tools/profiler/?tabs=macos#download-and-install Step 2: Click on the Next button on the window Step 3: Click on the checkbox to agree to the license agreement and click next.  Step 4: Choose the destination folder where you want to install the xamarin profiler and click next again.  Step 5: Click on the install button and wait until the installation completes.  Now that we have successfully installed the profiler, we will have to launch it. But before that, we have to enable profiling in our app. Let's discuss that in the next section. Launching Profiler From Visual Studio: Select android project, right-click and select properties, Build ---> Android Debug---> Android options ---> Enable Developer Instrumentation Once the above step is completed, open visual studio and load your application and keep the app in default debugging mode. Now go to Analyze---> Xamarin Profiler. Once you click on xamarin profiler, the profiler starts profiling automatically.In case you don't see the xamarin profiler option, check the troubleshooting guide in the below link. Xamarin Profiler Troubleshooting - Xamarin Deep Dive Into Profiler Instruments: Xamarin profiler consists of three main instruments for profiling and they are allocations, cycles and time profiler. Let us understand how each of them works. 1. Allocations: Allocations chart is at the top of the profiler as shown in the below figure. Allocations represent the amount of memory being collected by the garbage collector at regular intervals of time during profiling. This instrument uses three data views that help the developer to understand how much of the memory is being used and released. Allocations: This represents the memory allocated by the classes and their associated methods. When you select a class, it shows the memory allocated to that particular classCall Tree: This displays the call tree of the threads used in the application. In other words, it shows the memory allocated to each thread.  Snapshots: This section displays what memory is retained and released. To generate this information, you need to click on the camera button on the toolbar as shown in the below figure. The snapshots information can be captured only during live profiling.  2. Time Profiler: This instrument represents the amount of time taken by each method in the application. The application is paused at regular intervals and a stack trace is run on each thread. 3. Cycles: We often never dispose of the objects as sometimes they will be holding a reference to other objects. The cycles instrument represents the cycle of these objects in the application.  Part B: Memory Management: Introduction: When it comes to a mobile application or a website, it is always necessary to ensure proper management of objects and resources to avoid sluggishness when using the app. If not taken care of, it would lead to slow performance and crashes when used continuously. In this article, I will discuss how to prevent memory leaks and improve the performance of the app. Common Memory Leaks: Memory leaks can be very dangerous because they lead to crashes if allocated memory is full. They can show down the app performance and sometimes make it unresponsive. Let us see a few of the common memory leaks that we make while developing our applications. Subscribing or registering to event handlers, delegates and messaging centers can cause memory leaks if not unsubscribed and unregistered at the right place.  Using views, example  buttons and images cause a memory leak because the garbage collector does not collect them until they are disposed of. Caching mechanisms to store data can cause out of memory exceptions because the memory keeps filling up and the app crashes. Threads should be used carefully because any reference objects will not be collected by the garbage collector.  Using static variables, events are GC roots and are not collected by the garbage collector.  Using bindings can cause memory leaks. So always bind to the dependency object or INotifyPropertyChanged to avoid memory leaks. Avoid using bindings in unnecessary places. Steps for preventing memory leaks: Below are a few approaches to avoid memory leaks. They not only improve the performance of the app, but also reduce the work done by the CPU. Let’s discuss them one by one.  1. Use of Asynchronous operations: We can use asynchronous operations to many of our functions especially for long-running tasks. Asynchronous operations do not block the UI thread and ensure a smooth transition of user interactions. To enable asynchronous operations, dot net provides async and await keywords which can be used to call asynchronous APIs.  2. Reducing the application size: In order to reduce the application size, we need to understand the compilation process of each platform.  Android uses a just-in-time (JIT) compiler to convert to an intermediate language. Windows uses a built-in-time compiler to convert to an intermediate language. Ios uses an ahead-of-time compiler to convert to ARM assembly language.  For all of these platforms, appropriate linker options should be selected in order to strip off the unused framework class. By default, in xamarin the linker is disabled. We need to enable the correct linker so that during the run time, the application determines which members, types are used and removes the unused types. To understand how to select an appropriate linker, go through the below link Cross-Platform Performance - Xamarin 3. Optimizing image assets: Images are the most expensive resources an application can have as we use them at high resolutions and they occupy a lot of memory. We need to optimize images based on the phone resolution by having different resolutions and fit them based on the phone size. For example, use a small resolution image if you are using it in a listview rather than a big image that fits a full screen because there is a lot of CPU wastage to decode them to smaller sizes. Also, use the images only when required and release them when not in use. 4. Profilers: Profiler is a great tool to analyze the application behavior and check for memory leaks. They can also be combined with native instruments to check memory allocations of native objects. I hope you already know how to use them as we have discussed xamarin profilers in PART- A. 5. Test for memory leaks in the app: It is always best practice to test memory leaks for every function you do. Below is the sample code to test memory leaks. [Test]         void MemoryLeakTest()         {            var weakReference = new WeakReference(leakyObject)             GC.Collect();             GC.WaitForPendingFinalizers();             GC.Collect();             Assert.IsFalse(weakReference.IsAlive);         } 6. Unsubscribe from events: It is always best practice to unsubscribe from events to dispose of them so that the garbage collector does its job. We often forget to do that and this leads to memory leaks as the object is still holding the reference and keeps it alive. This has to be taken care of whenever using threads, messaging center, event handlers, and delegates. Below is the sample code to unsubscribe from events and dispose of them public class EventDemo     {         public event EventHandler DemoEvent;         public void OnMyEventFires()         {             if (DemoEvent != null)             {                 DemoEvent(this, EventArgs.Empty);             }         }     }     public class SubscriberDemo : IDisposable     {         readonly EventDemo  eventDemo;       public SubscriberDemo(EventDemo  _eventDemo)        {           eventDemo = _eventDemo;             eventDemo.DemoEvent += OnDemoEventFires;         }         void OnDemoEventFires(object sender, EventArgs e)         {             Debug.WriteLine("The publisher notified the subscriber of an event");         }        public void Dispose()         {             eventDemo.DemoEvent -= OnDemoEventFires;       }     }Using Dispose Pattern: The dispose method is used to release unmanaged resources. Our garbage collector does not allocate or release unmanaged memory. The pattern for releasing these objects is called a dispose pattern. In order to use the dispose method, you need to inherit your class with IDisposableInterface.  Below is the code snippet showing how to use dispose method.   public void Dispose()      {          // Dispose of unmanaged resources.          Dispose(true);          // Suppress finalization.          GC.SuppressFinalize(this);      } Using Statement: Whenever working with files, steam readers, graphics in .Net framework, we create a lot of unmanaged code. By implementing the using statement, the code is transformed into a try/finally statement behind the scenes and the dispose method is called at the final clause. So ensure that you implement “using statement” whenever necessary.  public void CreateFile()      {          using (var stream = new FileStream(@"\Document\YourFile.txt",                                             FileMode.OpenOrCreate))          {              // do your stuff              }// stream.Dispose()       } Size Reduction Techniques: Below are a few approaches to reduce the application size. Always generate the build in release mode. Make sure the LLVM compiler is used. Enable the appropriate linker in each project (Link all for ios projects and Link all assemblies for android projects) Reduce the number of architectures to avoid FAT binary being produced. Reducing Web Service Communication: We often make multiple calls over the web in order to transfer and receive data. This communication uses more network bandwidth and drains the phone's battery. As a result, there is a performance hit on our application. There are a few approaches that can help us here. The JSON format is always preferred as it uses lesser bandwidth while sending and receiving data over the network. Using data transfer objects (DTO) during data transfer between the mobile application and web service because more data can be transferred in a single remote call; thereby reducing the number of network calls. Once the web service call is made, it is preferred to cache the data locally instead of requesting the server multiple times. One more approach to reduce the network bandwidth is to compress data before transferring it over the network. However this might increase the CPU usage and drain the battery. Therefore this approach must be carefully evaluated before using it.  Conclusion: To sum up the things we have covered, we now know what causes memory leaks, how to prevent them and how to use xamarin profiler to find memory allocations, improve application performance and do code optimization. So let us adapt to a routine to bring out these practices while building mobile applications.  I hope this article helps you and saves a lot of time. Please do share your feedback and let me know if you have any queries. 
Xamarin Profiler and Memory Management
Mounika
Mounika

Mounika Rajapuram

Module Lead

Mounika calls herself a dynamic professional with expertise in developing mobile applications for iOS and Android. With C# and Xamarin as primary areas of expertise, she also likes to dwell in doodle art in her pastime.

Posts by Mounika Rajapuram

Xamarin Profiler and Memory Management

App memory management has become one of the key priorities for any developer today. With new-gen energy-efficient processors launching every day &  operating systems shifting towards efficient power usage along with sleek UI experience, today’s developers face a challenge of developing apps that are sleek & efficient in memory management along with an intelligent tool to check memory leakage proactively. In this article, I will be covering two major topics i.e. xamarin profiler (Part 1) and memory management (Part 2). Part 1: Xamarin Profiler Introduction to Xamarin Profiler: Xamarin Profiler is a tool developed by Microsoft that helps the developers to analyze the app's behavior, and its memory allocations with the help of a visual studio. It is a graphical interface that supports doing profiling in android, ios, tvos, mac applications in mac and android, ios, tvos applications in windows.  Why use a profiler: We all know that sometimes we don't properly dispose of the objects and therefore the garbage collector will not collect them and remove them from the memory.   In other words, with the help of the profiler, we can check memory leaks that are being held by objects which should ideally be disposed of.  Before that, let's understand how the operating system manages the memory. There are two types of memory, native memory and managed memory. All the ios and android related objects like views, example buttons, text views fall into the native memory and the dot net-related objects, for example, subscriptions, event handlers, threads go into managed memory. Whenever there is a process, the operating system gives a small piece of this memory chunk to xamarin mono. So in order to check the memory allocations of managed memory, we need a profiler.  Garbage Collector: Before getting started with the profiler, let's understand what a garbage collector is. The garbage collector collects the disposed objects and frees up the memory.  As I discussed above there are two memory worlds in the operating system, native memory, and managed memory. Sometimes garbage collectors cannot do their job, because some of the dot net objects may be holding reference to native objects or vice versa. In such cases, it is difficult to understand where the memory leak is happening. So this is where the profiles come into the picture.  Prerequisites: Visual Studio (Mac or Windows) Enterprise license Device or emulator Download And Installation: Step 1: Download and install the profiler for windows from the below link https://docs.microsoft.com/en-us/xamarin/tools/profiler/?tabs=macos#download-and-install Step 2: Click on the Next button on the window Step 3: Click on the checkbox to agree to the license agreement and click next.  Step 4: Choose the destination folder where you want to install the xamarin profiler and click next again.  Step 5: Click on the install button and wait until the installation completes.  Now that we have successfully installed the profiler, we will have to launch it. But before that, we have to enable profiling in our app. Let's discuss that in the next section. Launching Profiler From Visual Studio: Select android project, right-click and select properties, Build ---> Android Debug---> Android options ---> Enable Developer Instrumentation Once the above step is completed, open visual studio and load your application and keep the app in default debugging mode. Now go to Analyze---> Xamarin Profiler. Once you click on xamarin profiler, the profiler starts profiling automatically.In case you don't see the xamarin profiler option, check the troubleshooting guide in the below link. Xamarin Profiler Troubleshooting - Xamarin Deep Dive Into Profiler Instruments: Xamarin profiler consists of three main instruments for profiling and they are allocations, cycles and time profiler. Let us understand how each of them works. 1. Allocations: Allocations chart is at the top of the profiler as shown in the below figure. Allocations represent the amount of memory being collected by the garbage collector at regular intervals of time during profiling. This instrument uses three data views that help the developer to understand how much of the memory is being used and released. Allocations: This represents the memory allocated by the classes and their associated methods. When you select a class, it shows the memory allocated to that particular classCall Tree: This displays the call tree of the threads used in the application. In other words, it shows the memory allocated to each thread.  Snapshots: This section displays what memory is retained and released. To generate this information, you need to click on the camera button on the toolbar as shown in the below figure. The snapshots information can be captured only during live profiling.  2. Time Profiler: This instrument represents the amount of time taken by each method in the application. The application is paused at regular intervals and a stack trace is run on each thread. 3. Cycles: We often never dispose of the objects as sometimes they will be holding a reference to other objects. The cycles instrument represents the cycle of these objects in the application.  Part B: Memory Management: Introduction: When it comes to a mobile application or a website, it is always necessary to ensure proper management of objects and resources to avoid sluggishness when using the app. If not taken care of, it would lead to slow performance and crashes when used continuously. In this article, I will discuss how to prevent memory leaks and improve the performance of the app. Common Memory Leaks: Memory leaks can be very dangerous because they lead to crashes if allocated memory is full. They can show down the app performance and sometimes make it unresponsive. Let us see a few of the common memory leaks that we make while developing our applications. Subscribing or registering to event handlers, delegates and messaging centers can cause memory leaks if not unsubscribed and unregistered at the right place.  Using views, example  buttons and images cause a memory leak because the garbage collector does not collect them until they are disposed of. Caching mechanisms to store data can cause out of memory exceptions because the memory keeps filling up and the app crashes. Threads should be used carefully because any reference objects will not be collected by the garbage collector.  Using static variables, events are GC roots and are not collected by the garbage collector.  Using bindings can cause memory leaks. So always bind to the dependency object or INotifyPropertyChanged to avoid memory leaks. Avoid using bindings in unnecessary places. Steps for preventing memory leaks: Below are a few approaches to avoid memory leaks. They not only improve the performance of the app, but also reduce the work done by the CPU. Let’s discuss them one by one.  1. Use of Asynchronous operations: We can use asynchronous operations to many of our functions especially for long-running tasks. Asynchronous operations do not block the UI thread and ensure a smooth transition of user interactions. To enable asynchronous operations, dot net provides async and await keywords which can be used to call asynchronous APIs.  2. Reducing the application size: In order to reduce the application size, we need to understand the compilation process of each platform.  Android uses a just-in-time (JIT) compiler to convert to an intermediate language. Windows uses a built-in-time compiler to convert to an intermediate language. Ios uses an ahead-of-time compiler to convert to ARM assembly language.  For all of these platforms, appropriate linker options should be selected in order to strip off the unused framework class. By default, in xamarin the linker is disabled. We need to enable the correct linker so that during the run time, the application determines which members, types are used and removes the unused types. To understand how to select an appropriate linker, go through the below link Cross-Platform Performance - Xamarin 3. Optimizing image assets: Images are the most expensive resources an application can have as we use them at high resolutions and they occupy a lot of memory. We need to optimize images based on the phone resolution by having different resolutions and fit them based on the phone size. For example, use a small resolution image if you are using it in a listview rather than a big image that fits a full screen because there is a lot of CPU wastage to decode them to smaller sizes. Also, use the images only when required and release them when not in use. 4. Profilers: Profiler is a great tool to analyze the application behavior and check for memory leaks. They can also be combined with native instruments to check memory allocations of native objects. I hope you already know how to use them as we have discussed xamarin profilers in PART- A. 5. Test for memory leaks in the app: It is always best practice to test memory leaks for every function you do. Below is the sample code to test memory leaks. [Test]         void MemoryLeakTest()         {            var weakReference = new WeakReference(leakyObject)             GC.Collect();             GC.WaitForPendingFinalizers();             GC.Collect();             Assert.IsFalse(weakReference.IsAlive);         } 6. Unsubscribe from events: It is always best practice to unsubscribe from events to dispose of them so that the garbage collector does its job. We often forget to do that and this leads to memory leaks as the object is still holding the reference and keeps it alive. This has to be taken care of whenever using threads, messaging center, event handlers, and delegates. Below is the sample code to unsubscribe from events and dispose of them public class EventDemo     {         public event EventHandler DemoEvent;         public void OnMyEventFires()         {             if (DemoEvent != null)             {                 DemoEvent(this, EventArgs.Empty);             }         }     }     public class SubscriberDemo : IDisposable     {         readonly EventDemo  eventDemo;       public SubscriberDemo(EventDemo  _eventDemo)        {           eventDemo = _eventDemo;             eventDemo.DemoEvent += OnDemoEventFires;         }         void OnDemoEventFires(object sender, EventArgs e)         {             Debug.WriteLine("The publisher notified the subscriber of an event");         }        public void Dispose()         {             eventDemo.DemoEvent -= OnDemoEventFires;       }     }Using Dispose Pattern: The dispose method is used to release unmanaged resources. Our garbage collector does not allocate or release unmanaged memory. The pattern for releasing these objects is called a dispose pattern. In order to use the dispose method, you need to inherit your class with IDisposableInterface.  Below is the code snippet showing how to use dispose method.   public void Dispose()      {          // Dispose of unmanaged resources.          Dispose(true);          // Suppress finalization.          GC.SuppressFinalize(this);      } Using Statement: Whenever working with files, steam readers, graphics in .Net framework, we create a lot of unmanaged code. By implementing the using statement, the code is transformed into a try/finally statement behind the scenes and the dispose method is called at the final clause. So ensure that you implement “using statement” whenever necessary.  public void CreateFile()      {          using (var stream = new FileStream(@"\Document\YourFile.txt",                                             FileMode.OpenOrCreate))          {              // do your stuff              }// stream.Dispose()       } Size Reduction Techniques: Below are a few approaches to reduce the application size. Always generate the build in release mode. Make sure the LLVM compiler is used. Enable the appropriate linker in each project (Link all for ios projects and Link all assemblies for android projects) Reduce the number of architectures to avoid FAT binary being produced. Reducing Web Service Communication: We often make multiple calls over the web in order to transfer and receive data. This communication uses more network bandwidth and drains the phone's battery. As a result, there is a performance hit on our application. There are a few approaches that can help us here. The JSON format is always preferred as it uses lesser bandwidth while sending and receiving data over the network. Using data transfer objects (DTO) during data transfer between the mobile application and web service because more data can be transferred in a single remote call; thereby reducing the number of network calls. Once the web service call is made, it is preferred to cache the data locally instead of requesting the server multiple times. One more approach to reduce the network bandwidth is to compress data before transferring it over the network. However this might increase the CPU usage and drain the battery. Therefore this approach must be carefully evaluated before using it.  Conclusion: To sum up the things we have covered, we now know what causes memory leaks, how to prevent them and how to use xamarin profiler to find memory allocations, improve application performance and do code optimization. So let us adapt to a routine to bring out these practices while building mobile applications.  I hope this article helps you and saves a lot of time. Please do share your feedback and let me know if you have any queries. 
8490
Xamarin Profiler and Memory Management

App memory management has become one of the key pr... Read More

Introduction to Xamarin Forms- Shell

Xamarin Forms Shell reduces the complexity of mobile application development by providing the fundamental features that most mobile applications require. Shell has a declarative application structure and can easily create a consistent, dynamic, customized, and featured filled UI. In other words, shell is a new replacement for every one of your Xamarin forms pages.It provides out of the box infrastructure to deliver Xamarin forms features, a simplified navigation system, and customization.Advantages of Shell:Common navigation user experience Supports URI based navigation (navigation to any page in the application) Integrated search handler Allows a single place to describe the visual hierarchy Reduces memory consumption Increases the rendering speed Prerequisites:Xamarin forms shell is available in Xamarin forms 4.0.0 and supports completely on Android and iOS. It is partially available, and is in the experimental phase on UWP. In order to use it in UWP applications, the below code needs to be added in the App class before calling Forms.Initglobal::Xamarin.Forms.Forms.SetFlags("Shell_UWP_Experimental");Getting Started: Shell Requirements   The specialty of shell is to have a built-in container that includes a flyout menu, tab page, and navigation page. So let's create a demo app having these features. Visual studio also provides a shell template. But let's add shell to our blank Xamarin forms application for better understanding. Firstly create a blank Xamarin forms project in visual studio and name it “MovieBookingApp”. In this demo app, we are going to have two categories of movies i.e. comedy movies and thriller movies. With these two categories, let's create tabbed pages and a flyout menu. Now let's add a new content page with code-behind class to our project and name it as “MainShell”. Change a contentPage to Shell in the XAML page. It should look like the below code.  Once the above step is done, similarly change the content page to shell in MainShell.xaml.cs. Our code-behind class has to inherit from Shell.using System; using System.Collections.Generic; using Xamarin.Forms; namespace MovieBookingApp {     public partial class MainShell : Shell     {         public MainShell()         {             InitializeComponent();         }     } }In the App.xaml.cs constructor, add the below code. Here we are making MainShell the root page. Once done, run the code to ensure your project builds successfully.public App()         {             InitializeComponent();             MainPage = new MainShell();         }Flyout Menu: The flyout menu is also called a side drawer or hamburger menu. We have seen multiple applications having a flyout menu. A flyout menu consists of a header which is optional, menu items(optional), and flyout items as shown in the below picture.To create the flyout menu, add the below code in MainShell.xaml and you will see the flyout menu coming up after running the project.                                 We can set the background color to the flyout menu, which is a bindable property:Shell.Flyout.BackgroundColor= Color.RedTo customise the flyout menu items, by adding the optional header, or adding an icon please read about it in the below link https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/shell/flyout Tabbed Bar: The navigation in Xamarin forms shell can take place through tabs and does not make use of flyout navigation. In this case, each tab bar can consist of a single shellcontent object or multiple such objects; and each object represents a single content page. The reference image is shown below. Let's create a tab bar. Add two new content pages with code-behind class to the project and name them “Comedy Movies” and Thriller Movies. Since we don't want a flyout menu here, we are going to disable it as mentioned below.   FlyoutBehavior="Disabled"Add the below code to create the tab bar.                        
8571
Introduction to Xamarin Forms- Shell

Xamarin Forms Shell reduces the complexity of mobi... Read More

Integrating Realm with Xamarin (Includes Realm Sync)

When it comes to mobile applications with database support, the first thing that comes to mind is SQLite. However, there are a few drawbacks with SQLite such as no support for data encryption and low performance when dealing with large data.In this article, we take a closer look at Realm, a non-relational database and a solid replacement for SQLite and core data. It is quite efficient and works seamlessly even with a large amount of data.Why use RealmEasy to use Provides data synchronization Fast and Efficient Provides Encryption of data Ways of using Realm Using realm locally: This creates a local file in your mobile app. Using realm cloud: The data lives in realm cloud and will be synchronized with the local database. In this article I will show how to integrate realm in the Xamarin Forms project. I will also show how to use realm as local database(Part-1) and realm cloud(Part-2) Prerequisites Visual Studio 2015 Update2 or higher for windows Visual Studio for Mac 7.0 or higher Part-1: Using Realm Local Database Firstly, create a Xamarin Forms project in Visual Studio for Windows or Mac. Go to the NuGet packages and install the realm package in all your solutions. Always prefer to install the latest one. It automatically adds fodyweavers.xml. If not added, please add it manually in all your projects.  Go to PCL project>—>Right click—>Add—>New File—>XML File—>FodyWeavers.xml Go to Android project>—>Right click—>Add—>New File—>XML File—>FodyWeavers.xml Go to iOS project>—>Right click—>Add—>New File—>XML File—>FodyWeavers.xml Add the below code in the fileFodyWeavers.xml        Let's create a model  public class Animals: RealmObject  {          public string Name { get; set; }          public int Age { get; set; }  } Opening Realms  Opening a Realm can be done by instantiating a new Realm object.  // Get a Realm instance   var realm = Realm.GetInstance(); Note: If nothing is passed, it creates the default realm. You can add realm name as below var realm = Realm.GetInstance(“Animals”); This will create realm db with “Animals” name To add/delete/update or do any operation of realm, first you need a Realm instance. 1) Add elements var _realm = Realm.GetInstance();  Add elements  _realm.Write(() =>                      {                          var entry = new Todo{ Name = “Dog”, Age =3 };                          _realm.Add(entry);                      }); 2) Delete elements  var param = _realm.All().First(b => b.Name == “Dog”);   using (var trans = _realm.BeginWrite())                   {                       _realm.Remove(param);  trans.Commit();                   }   3) Update elements  _realm.Write(() =>                      {  param.Name = “Cat”;                          _realm.Add(param);                      }); Part-2: Using Realm Cloud Now let's see how to use realm cloud. The setup is still the same. Here we need a few more additional steps. 1) Create an account in realm cloud at https://cloud.realm.io/ (one-month free trial account).  2) Create an instance in realm cloud by clicking on create an instance This instance ID will be further used for authentication  There are two types of Realm sync Full Sync: All the data present in the cloud will be synced locally Query Based Sync: Only partial data i.e the result set that is queried will be synced into the local copy. Here I am going to show you how to use full sync as Realm recommends using Full sync. Client Authentication:  Realm supports two types of authentication Simple Authentication: To simply get started one can use simple authentication which uses username, password and other one is anonymous login. JWT Authentication: It is recommended to use JWT Authentication for a better experience. The below code shows how to use simple authentication with username and password.  var authUrl = new Uri("https://myinstance.cloud.realm.io");  var credentials = Credentials.UsernamePassword(username, password, createUser: false);  var user = await User.LoginAsync(credentials, authUrl); To authenticate, you must supply a server URL. This is the base URL for your server, such as https://myinstance.cloud.realm.io Note: Here “myinstance" would be the instance id that you generated while creating your account  Create Realm through realm studio or through code. If the realm has not been created, while calling the realm instance it will automatically create. If you have already created through realm studio, you can just call the instance. Example: public static string realmPath = "realms://instanceId/realmname; Here the realm path consists of instanceId followed by realm name. Something like this public static string realmPath = "realms://instanceId/Animals; Now let’s login and call realm instance public async Task GetInitialize() { await StartLoginCycle(); } private async Task StartLogin() { do { await Task.Yield(); } while (!await LogIn()); }//Call the login methodprivate async Task LogIn() { try { user = User.Current; if (user == null) { var username = "DevUser"; //Pass your username var password = “User123"; //Pass the password var credentials = Realms.Sync.Credentials.UsernamePassword(username, password); /// Log in as the user. user = await User.LoginAsync(credentials, new Uri(RealmConnectionString.AuthUrl)); } Debug.Assert(user != null); Console.WriteLine("Login successful."); await GetDataFromRealm(); return true; } catch (Exception ex) { ///await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK"); return false; } }//Call or create realm instance: public static async Task GetDataFromRealm() {                  var configuration = new FullSyncConfiguration(new Uri(realmPath, UriKind.Absolute), user);                  Var   _realm = await Realm.GetInstanceAsync(configuration);               var param = _realm.All();  //Adding/updating/deleting operations are same as above  } ConclusionIn the above sections, we have seen how to integrate realm local db and realm cloud into your xamarin forms project. You will also be able to perform operations like adding items, updating items and deleting items (showed in Part-1). These code snippets are the same for realm local database and realm cloud. You can find how to use linq queries in the below reference link. However, few features are not supported such as: groupby, union, intersect, distinct,except,  select, selectmany, join, group join, concat, skipwhile, take, skip and takewhile.  Note: Opening the realm instance asynchronously for the first time is recommended. Once the data is synchronized, the instance should be called synchronously.  You can also download realm studio, create a realm file, and add the data. This helps to minimize the code in your application.   Below are a few reference links that might help with further information Using realm with xamarin: https://realm.io/docs/dotnet/latest/ Linq support: https://realm.io/docs/dotnet/latest/api/linqsupport.html Realm Encryption: https://realm.io/docs/dotnet/latest/#encryption 
6627
Integrating Realm with Xamarin (Includes Realm Syn...

When it comes to mobile applications with database... Read More