Building a .NET Mobile Application

Introduction

 
In my first two articles, we first looked at the four common types of .NET applications we may find out in the field. We briefly discussed these four types of applications and then in the second article, we looked at the design and architecture at a high level which would apply to all these applications in general terms. Next, we build the first type of application, the .NET desktop application. After that, we built the .NET web application and then the moved this web application to the cloud. Today, we will look to create a mobile application using Xamarin forms.

Requirements for building this application

 
In this article, we will be using the same solution used for building the web application. We will re-use the data source and the data access layer. Furthermore, we will create a Xamarin forms front-end to communicate with the data access layer and display the employee record on the screen. So, let's begin.

The Data Source and Data Access Layer

 
We will be using the same data source and data access layer as used by the web application. The only thing to note here is that in the web application, we were running the data access layer API from Visual Studio 2019, which runs it from a localhost URL. In this scenario, we will be using an Android emulator to run the front end application, so we cannot use “localhost” as running the web API from IIS express. This does not allow remote connections and the emulator runs as a separate virtual machine and makes a remote connection. Hence, after some investigation, I found that the best solution is to deploy the data access layer into IIS and access it from there. Therefore, there would be a small URL change in the business logic layer from where we make a call to the data access layer web API service.
 

The Business Logic Layer

 
The same business logic layer will be used as used by the web application. However, there is one small point to note here. The Xamarin Forms application is a .NET standard 2.0 application and this cannot set a reference to our previous business logic layer project, as that was built using the .NET Core 3.1 platform. Hence, we need to convert the business logic layer to standard 2.0 which would then be available for consumption by either .NET framework, .NET Core, and .NET Standard. I decided not to change the existing business logic layer application and create a new one using the .NET standard 2.0 platform. The rest remains the same as before. This will then be referenced by the front end Xamarin application.
 
 
The code is below:
  1. using System;  
  2.   
  3. namespace EmployeeBALStd  
  4. {  
  5.     public class EmployeeUI  
  6.     {  
  7.         public int Employee_ID { getset; }  
  8.         public string Employee_Name { getset; }  
  9.         public int Age { getset; }  
  10.         public string Address { getset; }  
  11.         public DateTime Date_Joining { getset; }  
  12.         public DateTime? Date_Leaving { getset; }  
  13.     }  
  14. }  
  1. using System.Collections.Generic;  
  2. using System.Threading.Tasks;  
  3.   
  4. namespace EmployeeBALStd  
  5. {  
  6.     public interface IEmployeeBAL  
  7.     {  
  8.         Task<List<EmployeeUI>> GetAllEmployees();  
  9.     }  
  10. }  
  1. using System.Net.Http;  
  2. using System.Threading.Tasks;  
  3. using Newtonsoft.Json;  
  4.   
  5.   
  6. namespace EmployeeBALStd  
  7. {  
  8.     public class EmployeeBAL : IEmployeeBAL  
  9.     {  
  10.         public async Task<List<EmployeeUI>> GetAllEmployees()  
  11.         {  
  12.             using (var client = new HttpClient())  
  13.             {  
  14.                 client.BaseAddress = new Uri("http://192.168.0.12/EmployeeWebApi/api/");  
  15.                 var result = await client.GetAsync("values");  
  16.                 var response = await result.Content.ReadAsStringAsync();  
  17.                 var parsedValue = response.Replace("\"""");  
  18.                 var data = JsonConvert.DeserializeObject<List<EmployeeStore>>(parsedValue);  
  19.   
  20.                 var employeesUI = data.Select(e => new EmployeeUI  
  21.                 {  
  22.                     Employee_ID = e.Employee_ID,  
  23.                     Employee_Name = e.First_Name + " " + e.Last_Name,  
  24.                     Age = GetAge(e.Date_Birth),  
  25.                     Address = e.Street_Address + ", " + e.City + ", " + e.Province,  
  26.                     Date_Joining = e.Date_Joining,  
  27.                     Date_Leaving = e.Date_Leaving  
  28.                 }).ToList();  
  29.                 return employeesUI;  
  30.             }  
  31.         }  
  32.   
  33.         private int GetAge(DateTime Birth_Date)  
  34.         {  
  35.             return Convert.ToInt32(((DateTime.Now - Birth_Date).TotalDays) / 365);  
  36.         }  
  37.   
  38.         public class EmployeeStore  
  39.         {  
  40.             public int Employee_ID;  
  41.             public string First_Name;  
  42.             public string Last_Name;  
  43.             public DateTime Date_Birth;  
  44.             public string Street_Address;  
  45.             public string City;  
  46.             public string Province;  
  47.             public DateTime Date_Joining;  
  48.             public DateTime? Date_Leaving;  
  49.         }  
  50.     }  
  51. }  

The Presentation Layer

 
We now look at the presentation layer, which we will build using the Xamarin forms template. We start by creating a new project as below:
 
 
 
We will name this project “EmployeeMobile”. Once completed we will see three projects added to our solution. These are shown below:
  1. EmployeeMobile
  2. EmployeeMobile.Android
  3. EmployeeMobile.iOS
The first is the main project where we will de designing our front end using Xamarin XAML. The other two projects are for features specific to Android and iOS. We will explore these in some future articles. For now, we will design our simple front end in the first project. As we will be running the application on an Android emulator, we would need to add this and ensure it is working fine. We start by adding the latest Android emulator. We click on “Open Android Device Manager” from the toolbar and get the below result:
 
 
Here, you see I have added the “Pixel Pie 9.0- API 28” emulator. If there are issues when running an application using the emulator, click on the following.
 
Tools -> Android -> Restart Adb server
 
Now, we add the “EmployeeDetailsVM” class which will be the view model for the main page. We will be using the MVVM pattern here just as we did in the desktop application.
 
The code for the View Model and View is shown below:
  1. using System.Linq;  
  2. using System.Threading.Tasks;  
  3. using EmployeeBALStd;  
  4. using System.ComponentModel;  
  5.   
  6. namespace EmployeeMobile  
  7. {  
  8.     public class EmployeeDetailsVM : INotifyPropertyChanged  
  9.     {  
  10.         public event PropertyChangedEventHandler PropertyChanged;  
  11.   
  12.         private EmployeeUI _employee;  
  13.         public EmployeeUI Employee  
  14.         {  
  15.             get => _employee;  
  16.             set  
  17.             {  
  18.                 _employee = value;  
  19.                 if (PropertyChanged != null)  
  20.                 {  
  21.                     PropertyChanged(thisnew PropertyChangedEventArgs("Employee"));  
  22.                 }  
  23.             }  
  24.         }  
  25.   
  26.         public EmployeeDetailsVM()  
  27.         {  
  28.             SetValues().GetAwaiter();  
  29.         }  
  30.   
  31.         public async Task SetValues()  
  32.         {  
  33.             var employeeBAL = new EmployeeBAL();  
  34.             var employees = await employeeBAL.GetAllEmployees();  
  35.             Employee = employees.FirstOrDefault();  
  36.         }  
  37.   
  38.     }  
  39. }  
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:d="http://xamarin.com/schemas/2014/forms/design"  
  5.              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  6.              xmlns:local="clr-namespace:EmployeeMobile;assembly=EmployeeMobile"  
  7.              mc:Ignorable="d"  
  8.              x:Class="EmployeeMobile.MainPage">  
  9.       
  10.     <StackLayout>  
  11.          
  12.         <Grid HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand">  
  13.             <Grid.BindingContext>  
  14.                 <local:EmployeeDetailsVM />  
  15.             </Grid.BindingContext>  
  16.             <Grid.RowDefinitions>  
  17.                 <RowDefinition Height="*" />  
  18.                 <RowDefinition Height="*" />  
  19.                 <RowDefinition Height="*" />  
  20.                 <RowDefinition Height="*" />  
  21.                 <RowDefinition Height="*" />  
  22.                 <RowDefinition Height="*" />  
  23.                 <RowDefinition Height="*" />  
  24.             </Grid.RowDefinitions>  
  25.             <Grid.ColumnDefinitions>  
  26.                 <ColumnDefinition Width="Auto" />  
  27.                 <ColumnDefinition Width="*" />  
  28.             </Grid.ColumnDefinitions>  
  29.   
  30.             <Label Text="Employee Details" Grid.Row="0" Grid.Column="0" FontSize="Medium" />  
  31.   
  32.             <Label Text="Employee ID" Grid.Row="1" Grid.Column="0" />  
  33.             <Label Text="{Binding Employee.Employee_ID}" Grid.Row="1" Grid.Column="1" />  
  34.             <Label Text="Employee Name" Grid.Row="2" Grid.Column="0" />  
  35.             <Label Text="{Binding Employee.Employee_Name}" Grid.Row="2" Grid.Column="1" />  
  36.             <Label Text="Age" Grid.Row="3" Grid.Column="0" />  
  37.             <Label Text="{Binding Employee.Age}" Grid.Row="3" Grid.Column="1" />  
  38.             <Label Text="Address" Grid.Row="4" Grid.Column="0" />  
  39.             <Label Text="{Binding Employee.Address}" Grid.Row="4" Grid.Column="1" />  
  40.             <Label Text="Date of joining" Grid.Row="5" Grid.Column="0" />  
  41.             <Label Text="{Binding Employee.Date_Joining, StringFormat='{0:MMMM dd, yyyy}'}}" Grid.Row="5" Grid.Column="1" />  
  42.             <Label Text="Date of leaving" Grid.Row="6" Grid.Column="0" />  
  43.             <Label Text="{Binding Employee.Date_Leaving, StringFormat='{0:MMMM dd, yyyy}'}}" Grid.Row="6" Grid.Column="1" />  
  44.         </Grid>  
  45.   
  46.     </StackLayout>  
  47.   
  48. </ContentPage>  
 Now when we run the application from the “EmployeeMobile.Android” project we see the application in the Android emulator:
 
 

Summary

 
In this article, we built a simple .NET mobile application using Xamarin forms. We reused the business logic layer, data access layer, and the data store. Hence, we saw how we can build re-usable units of the application which are ready to scale as required and then build different types of front-end applications to serve different platforms. I hope this series of articles provided a basic introduction of the different types of .NET applications that can be created. The learning does not stop here, and I encourage you to further explore each of the applications and make an even better overall design and architecture layout. 


Similar Articles