Customized Azure Cosmos DB With Xamarin.Forms Application (Student Detail) For Android And UWP

Azure Cosmos DB is a globally distributed, multi-model database service. With Azure Cosmos DB, we can develop document, key-value, wide-column, and graph databases by using popular APIs and programming models. More details can be found here:  https://docs.microsoft.com/en-us/azure/cosmos-db/introduction. Here the customization sample is Student Details. Student details in the cloud with mobile is an emerging requirement for the education environment.

Reading this article, you will learn how to develop customized (Student APP) Azure Cosmos DB with Xamarin Forms application using Android and UWP in XAML and Visual C# - cross-platform application development.

The following important tools are required for developing UWP:

  1. Microsoft Azure Subscription (https://azure.microsoft.com ) or you can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments.
  2. Windows 10 (Recommended)
  3. Visual Studio 2017 Community (https://www.visualstudio.com/downloads/ )

Now we can discuss step by step app development.

For Creating Student Azure Cosmos DB database,

Step 1

Login to your Microsoft Azure Subscription Account in https://azure.microsoft.com (Free Trial also there), or you can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments. In this article, we discuss with Microsoft Azure subscription.

Step 2

For Creating Azure Cosmos DB Account (xamstudcosmos), Please refer to Step 2 in How To Create And Use Azure Cosmos DB In Xamarin.Forms Application For Android

 

Step 3

For adding Student Collection,  go to DataExplorer in your xamstudcosmos account, and click New Collection, and set the values Database id, Collection id, Storage capacity, Partition key, and Throughput.

 

Now, the new StudentDB with Student collection is added:

 

Copy the URI and Key, based on your access (Read or Read Write) from xamstudcosmos Account ->Keys option,

 

Now we can develop our Xamarin Forms Application.

Step 1

Open Visual Studio 2017 -> Start -> New Project-> Select Cross-Platform (under Visual C#->Cross Platform ->Mobile App(Xamarin.Forms)-> Give a Suitable Name for your App (XamFormStudCos) ->OK.

 

Step 2

Select the Cross Platform template as Blank APP ->Set Platform as Android, iOS and UWP and code sharing strategy as Shared Project, Afterwards, Visual Studio creates projects (Portable, Droid,iOS, UWP)

 

Step 3

Add the Microsoft.Azure.DocumentDB.Core Reference, Right Click the Solution (XamFormStudCos)-> Select Manage NuGet packages for Solution.

Browse and Install the Reference

 

Step 4

Add Connection.cs class for xamstudcosmos Account (CosmosDB),

 

Add the following Namespace and code in Connection.cs,

  1. using Newtonsoft.Json;  
  2. public class Connection {  
  3.     public static readonly string EndpointUri = "https://xamstudcosmos.documents.azure.com:443/";  
  4.     public static readonly string PrimaryKey = "r03kRnNeyU3Bij7b9TZgsrkoKoU2ERdWM2d2jMAaaKWFClSJobyC8SyXmeazwKEwm8c2UhEjCNDU9NhI4grEFQ==";  
  5.     public static readonly string DatabaseName = "StudentDB";  
  6.     public static readonly string CollectionName = "Student";  
  7. }  

Step 5

Here, we are using MVC, So, first Create Model Folder and Add the StudentDetail Class for data Model:

 

Add the following code in StudentDetail.cs

  1. public class StudentDetail {  
  2.     [JsonProperty(PropertyName = "id")]  
  3.     public string Id {  
  4.         get;  
  5.         set;  
  6.     }  
  7.     [JsonProperty(PropertyName = "name")]  
  8.     public string Name {  
  9.         get;  
  10.         set;  
  11.     }  
  12.     [JsonProperty(PropertyName = "Age")]  
  13.     public string Age {  
  14.         get;  
  15.         set;  
  16.     }  
  17. }  

Step 6

Next, Create Controller Folder and Add the IDocumentDBService Interface for DocumentDB,

 

Add the following Namespace and code in IDocumentDBService.cs for all DB operations:

  1. using System.Threading.Tasks;  
  2. using XamFormStudCos.Model;  
  3. public interface IDocumentDBService {  
  4.     Task CreateDatabaseAsync(string databaseName);  
  5.     Task CreateDocumentCollectionAsync(string databaseName, string collectionName);  
  6.     Task < List < StudentDetail >> GetStoreInfoAsync();  
  7.     Task SaveStudentDetailAsync(StudentDetail stud, bool isNewstudent);  
  8.     Task DeleteStudentAsync(string id);  
  9. }  

Step 7

Add the DocumentDBService Class for implementing IDocumentDBService interface

 

Add the following Namespaces and code in DocumentDBService.cs

  1. using System.Threading.Tasks;  
  2. using XamFormStudCos.Model;  
  3. using Microsoft.Azure.Documents;  
  4. using Microsoft.Azure.Documents.Client;  
  5. using Microsoft.Azure.Documents.Linq;  
  6. using System.Diagnostics;  
  7. class DocumentDBService: IDocumentDBService {  
  8.     public List < StudentDetail > Items {  
  9.         get;  
  10.         private set;  
  11.     }  
  12.     DocumentClient client;  
  13.     Uri collectionLink;  
  14.     public DocumentDBService() {  
  15.         client = new DocumentClient(new Uri(Connection.EndpointUri), Connection.PrimaryKey);  
  16.         collectionLink = UriFactory.CreateDocumentCollectionUri(Connection.DatabaseName, Connection.CollectionName);  
  17.     }  
  18.     public async Task CreateDatabaseAsync(string databaseName) {  
  19.         try {  
  20.             await client.CreateDatabaseIfNotExistsAsync(new Database {  
  21.                 Id = databaseName  
  22.             });  
  23.         } catch (DocumentClientException ex) {  
  24.             Debug.WriteLine("Error: ", ex.Message);  
  25.         }  
  26.     }  
  27.     public async Task CreateDocumentCollectionAsync(string databaseName, string collectionName) {  
  28.         try {  
  29.             await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(Connection.DatabaseName), new DocumentCollection {  
  30.                 Id = collectionName  
  31.             }, new RequestOptions {  
  32.                 OfferThroughput = 400  
  33.             });  
  34.         } catch (DocumentClientException ex) {  
  35.             Debug.WriteLine("Error: ", ex.Message);  
  36.         }  
  37.     }  
  38.     public async Task DeleteStudentAsync(string id) {  
  39.         try {  
  40.             await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(Connection.DatabaseName, Connection.CollectionName, id));  
  41.         } catch (DocumentClientException ex) {  
  42.             Debug.WriteLine("Error: ", ex.Message);  
  43.         }  
  44.     }  
  45.     async Task DeleteDocumentCollection() {  
  46.         try {  
  47.             await client.DeleteDocumentCollectionAsync(collectionLink);  
  48.         } catch (DocumentClientException ex) {  
  49.             Debug.WriteLine("Error: ", ex.Message);  
  50.         }  
  51.     }  
  52.     async Task DeleteDatabase() {  
  53.         try {  
  54.             await client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(Connection.DatabaseName));  
  55.         } catch (DocumentClientException ex) {  
  56.             Debug.WriteLine("Error: ", ex.Message);  
  57.         }  
  58.     }  
  59.     public async Task < List < StudentDetail >> GetStudentAsync() {  
  60.         Items = new List < StudentDetail > ();  
  61.         try {  
  62.             var query = client.CreateDocumentQuery < StudentDetail > (collectionLink).AsDocumentQuery();  
  63.             while (query.HasMoreResults) {  
  64.                 Items.AddRange(await query.ExecuteNextAsync < StudentDetail > ());  
  65.             }  
  66.         } catch (DocumentClientException ex) {  
  67.             Debug.WriteLine("Error: ", ex.Message);  
  68.         }  
  69.         return Items;  
  70.     }  
  71.     public async Task SaveStudentDetailAsync(StudentDetail student, bool isNewItem) {  
  72.         try {  
  73.             if (isNewItem) {  
  74.                 await client.CreateDocumentAsync(collectionLink, student);  
  75.             } else {  
  76.                 await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(Connection.DatabaseName, Connection.CollectionName, student.Id), student);  
  77.             }  
  78.         } catch (DocumentClientException ex) {  
  79.             Debug.WriteLine("Error: ", ex.Message);  
  80.         }  
  81.     }  
  82. }  

Step 8

Add the StudentDetailManager Class.

 

Add the following Namespaces and code in StudentDetailManager.cs.

  1. using System.Threading.Tasks;  
  2. using XamFormStudCos.Model;  
  3. using XamFormStudCos.Controller;  
  4. public class StudentDetailManager {  
  5.     IDocumentDBService documentDBService;  
  6.     public StudentDetailManager(IDocumentDBService service) {  
  7.         documentDBService = service;  
  8.     }  
  9.     public Task CreateDatabase(string databaseName) {  
  10.         return documentDBService.CreateDatabaseAsync(databaseName);  
  11.     }  
  12.     public Task CreateDocumentCollection(string databaseName, string collectionName) {  
  13.         return documentDBService.CreateDocumentCollectionAsync(databaseName, collectionName);  
  14.     }  
  15.     public Task < List < StudentDetail >> GetStoreInfoAsync() {  
  16.         return documentDBService.GetStoreInfoAsync();  
  17.     }  
  18.     public Task SaveStudentDetailAsync(StudentDetail student, bool isNewItem = false) {  
  19.         return documentDBService.SaveStudentDetailAsync(student, isNewItem);  
  20.     }  
  21.     public Task DeleteStudentAsync(StudentDetail student) {  
  22.         return documentDBService.DeleteStudentAsync(student.Id);  
  23.     }  
  24. }  

Step 9

Add the following Namespaces and code in App.xaml.cs.

  1. using XamFormStudCos.Controller;  
  2. using XamFormStudCos.View;  
  3. public static StudentDetailManager StudentDetailManager {  
  4.     get;  
  5.     private set;  
  6. }  
  7. public App() {  
  8.     InitializeComponent();  
  9.     StudentDetailManager = new StudentDetailManager(new DocumentDBService());  
  10.     MainPage = new NavigationPage(new StudentList());  
  11. }  

Step 10

Next, Create View Folder and Add the StudentList Xaml Page for Viewing all student lists.

 

Add Toolbar item with Add and ListView item for Viewing student list.

  1. <ContentPage.ToolbarItems>  
  2.     <ToolbarItem Text="Add" Order="Primary" Clicked="OnItemAdded" /> </ContentPage.ToolbarItems>  
  3. <ListView x:Name="SList" ItemSelected="OnItemselected">  
  4.     <ListView.ItemTemplate>  
  5.         <DataTemplate>  
  6.             <TextCell Text="{Binding Name}" Detail="{Binding Age}" /> </DataTemplate>  
  7.     </ListView.ItemTemplate>  
  8. </ListView>  

Add the following Namespaces and code in StudentList.xaml.cs

  1. using XamFormStudCos.Model;  
  2. protected override async void OnAppearing() {  
  3.     base.OnAppearing();  
  4.     await App.StudentDetailManager.CreateDatabase(Constants.DatabaseName);  
  5.     await App.StudentDetailManager.CreateDocumentCollection(Constants.DatabaseName, Constants.CollectionName);  
  6.     var data = await App.StudentDetailManager.GetStoreInfoAsync();  
  7.     StdList.ItemsSource = data;  
  8. }  
  9. async void OnItemAdded(object sender, EventArgs e) {  
  10.     await Navigation.PushAsync(new StudentDetails(true) {  
  11.         BindingContext = new StudentDetail {  
  12.             Id = Guid.NewGuid().ToString()  
  13.         }  
  14.     });  
  15. }  
  16. async void OnItemselected(object sender, SelectedItemChangedEventArgs e) {  
  17.     if (e.SelectedItem != null) {  
  18.         await Navigation.PushAsync(new EditStudent() {  
  19.             BindingContext = e.SelectedItem as StudentDetail  
  20.         });  
  21.     }  
  22. }  

Step 11

Add the StudentDetails Xaml Page for adding New Student Detail.

 

For adding a new student, Add Label, Entry, and Button controls with click event method.

  1. <ContentPage.Content>  
  2.     <StackLayout Margin="20" VerticalOptions="StartAndExpand">  
  3.         <Label Text="Name" />  
  4.         <Entry Text="{Binding Path=Name}" Placeholder="Enter Student Name" />  
  5.         <Label Text="Age" />  
  6.         <Entry Text="{Binding Path=Age}" />  
  7.         <Button Text="Save" Clicked="OnSaveClicked" />  
  8.         <Button Text="Cancel" Clicked="OnCancelClicked" /> </StackLayout>  
  9. </ContentPage.Content>  

Add the following Namespaces and code in StudentDetail.xaml.cs

  1. using XamFormStudCos.Model;  
  2. bool isNewItem;  
  3. public StudentDetails(bool isNew) {  
  4.     InitializeComponent();  
  5.     isNewItem = isNew;  
  6. }  
  7. async void OnSaveClicked(object sender, EventArgs e) {  
  8.     var student = (StudentDetail) BindingContext;  
  9.     await App.StudentDetailManager.SaveStudentDetailAsync(student, isNewItem);  
  10.     await Navigation.PopAsync();  
  11. }  
  12. async void OnCancelClicked(object sender, EventArgs e) {  
  13.     await Navigation.PopAsync();  
  14. }  
Step 12

Add the EditStudent Xaml Page for EditStudent (Update, Delete) Detail.

 

For Editing a student, Add Label, Entry and Button controls with click event method,

  1. <StackLayout Padding="10" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">  
  2.     <Grid>  
  3.         <Label Text="Name" Grid.Row="0" Grid.Column="0" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />  
  4.         <Entry Text="{Binding Name}" Grid.Row="0" Grid.Column="1" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />  
  5.         <Label Text="Age" Grid.Row="2" Grid.Column="0" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />  
  6.         <Entry Text="{Binding Age}" Grid.Row="2" Grid.Column="1" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" /> </Grid>  
  7.     <Button Text="Update" HorizontalOptions="FillAndExpand" BackgroundColor="Blue" TextColor="White" Clicked="Update_Clicked" />  
  8.     <Button Text="Delete" HorizontalOptions="FillAndExpand" BackgroundColor="Blue" TextColor="White" Clicked="OnDeleteClicked" />  
  9.     <Button Text="Cancel" HorizontalOptions="FillAndExpand" BackgroundColor="Blue" TextColor="White" Clicked="OnCancelClicked" /> </StackLayout>  

Add the following Namespaces and code in EditStudent.xaml.cs

  1. using XamFormStudCos.Model;  
  2. async void Update_Clicked(object sender, System.EventArgs e) {  
  3.     var student = (StudentDetail) BindingContext;  
  4.     await App.StudentDetailManager.SaveStudentDetailAsync(student);  
  5.     await Navigation.PopAsync();  
  6. }  
  7. async void OnDeleteClicked(object sender, EventArgs e) {  
  8.     bool accepted = await DisplayAlert("Confirm""Are you Sure ?""Yes""No");  
  9.     if (accepted) {  
  10.         var student = (StudentDetail) BindingContext;  
  11.         await App.StudentDetailManager.DeleteStudentAsync(student);  
  12.         await Navigation.PopAsync();  
  13.     }  
  14. }  
  15. async void OnCancelClicked(object sender, EventArgs e) {  
  16.     await Navigation.PopAsync();  
  17. }  

Step 12

Enable the Build and Deploy option for both Android and UWP Projects in Configuration Manager,

 
Set Multiple Start Up Projects. 
 
 

Step 13

Build and Run the project XamFormStudCos in Android emulator and UWP.

 

After Clicking add in Android and UWP.

 

After Save button is clicked, both Android and UWP:

 

 

After adding 3 students the new document is added with ids in Azure Cosmos DB account:
 

After selecting the item, edit Page for both Android and UWP - Update:

 

After Update button is clicked, both Android and UWP:

 

After Selecting the item, Clicked the delete button in editstudent Page for both Android and UWP:

After Delete confirmation, both Android and UWP:

 

After Performing all the operations, the values of StudenDB in Azure Cosmos DB account:

 

Summary

Now you have successfully tested Customized Azure Cosmos DB In Xamarin Forms application with Android and UWP using Visual C# and Xamarin.


Similar Articles