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:
- 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.
- Windows 10 (Recommended)
- 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,
- using Newtonsoft.Json;
- public class Connection {
- public static readonly string EndpointUri = "https://xamstudcosmos.documents.azure.com:443/";
- public static readonly string PrimaryKey = "r03kRnNeyU3Bij7b9TZgsrkoKoU2ERdWM2d2jMAaaKWFClSJobyC8SyXmeazwKEwm8c2UhEjCNDU9NhI4grEFQ==";
- public static readonly string DatabaseName = "StudentDB";
- public static readonly string CollectionName = "Student";
- }
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
- public class StudentDetail {
- [JsonProperty(PropertyName = "id")]
- public string Id {
- get;
- set;
- }
- [JsonProperty(PropertyName = "name")]
- public string Name {
- get;
- set;
- }
- [JsonProperty(PropertyName = "Age")]
- public string Age {
- get;
- set;
- }
- }
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:
- using System.Threading.Tasks;
- using XamFormStudCos.Model;
- public interface IDocumentDBService {
- Task CreateDatabaseAsync(string databaseName);
- Task CreateDocumentCollectionAsync(string databaseName, string collectionName);
- Task < List < StudentDetail >> GetStoreInfoAsync();
- Task SaveStudentDetailAsync(StudentDetail stud, bool isNewstudent);
- Task DeleteStudentAsync(string id);
- }
Step 7
Add the DocumentDBService Class for implementing IDocumentDBService interface
Add the following Namespaces and code in DocumentDBService.cs
- using System.Threading.Tasks;
- using XamFormStudCos.Model;
- using Microsoft.Azure.Documents;
- using Microsoft.Azure.Documents.Client;
- using Microsoft.Azure.Documents.Linq;
- using System.Diagnostics;
- class DocumentDBService: IDocumentDBService {
- public List < StudentDetail > Items {
- get;
- private set;
- }
- DocumentClient client;
- Uri collectionLink;
- public DocumentDBService() {
- client = new DocumentClient(new Uri(Connection.EndpointUri), Connection.PrimaryKey);
- collectionLink = UriFactory.CreateDocumentCollectionUri(Connection.DatabaseName, Connection.CollectionName);
- }
- public async Task CreateDatabaseAsync(string databaseName) {
- try {
- await client.CreateDatabaseIfNotExistsAsync(new Database {
- Id = databaseName
- });
- } catch (DocumentClientException ex) {
- Debug.WriteLine("Error: ", ex.Message);
- }
- }
- public async Task CreateDocumentCollectionAsync(string databaseName, string collectionName) {
- try {
- await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(Connection.DatabaseName), new DocumentCollection {
- Id = collectionName
- }, new RequestOptions {
- OfferThroughput = 400
- });
- } catch (DocumentClientException ex) {
- Debug.WriteLine("Error: ", ex.Message);
- }
- }
- public async Task DeleteStudentAsync(string id) {
- try {
- await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(Connection.DatabaseName, Connection.CollectionName, id));
- } catch (DocumentClientException ex) {
- Debug.WriteLine("Error: ", ex.Message);
- }
- }
- async Task DeleteDocumentCollection() {
- try {
- await client.DeleteDocumentCollectionAsync(collectionLink);
- } catch (DocumentClientException ex) {
- Debug.WriteLine("Error: ", ex.Message);
- }
- }
- async Task DeleteDatabase() {
- try {
- await client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(Connection.DatabaseName));
- } catch (DocumentClientException ex) {
- Debug.WriteLine("Error: ", ex.Message);
- }
- }
- public async Task < List < StudentDetail >> GetStudentAsync() {
- Items = new List < StudentDetail > ();
- try {
- var query = client.CreateDocumentQuery < StudentDetail > (collectionLink).AsDocumentQuery();
- while (query.HasMoreResults) {
- Items.AddRange(await query.ExecuteNextAsync < StudentDetail > ());
- }
- } catch (DocumentClientException ex) {
- Debug.WriteLine("Error: ", ex.Message);
- }
- return Items;
- }
- public async Task SaveStudentDetailAsync(StudentDetail student, bool isNewItem) {
- try {
- if (isNewItem) {
- await client.CreateDocumentAsync(collectionLink, student);
- } else {
- await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(Connection.DatabaseName, Connection.CollectionName, student.Id), student);
- }
- } catch (DocumentClientException ex) {
- Debug.WriteLine("Error: ", ex.Message);
- }
- }
- }
Step 8
Add the StudentDetailManager Class.
Add the following Namespaces and code in StudentDetailManager.cs.
- using System.Threading.Tasks;
- using XamFormStudCos.Model;
- using XamFormStudCos.Controller;
- public class StudentDetailManager {
- IDocumentDBService documentDBService;
- public StudentDetailManager(IDocumentDBService service) {
- documentDBService = service;
- }
- public Task CreateDatabase(string databaseName) {
- return documentDBService.CreateDatabaseAsync(databaseName);
- }
- public Task CreateDocumentCollection(string databaseName, string collectionName) {
- return documentDBService.CreateDocumentCollectionAsync(databaseName, collectionName);
- }
- public Task < List < StudentDetail >> GetStoreInfoAsync() {
- return documentDBService.GetStoreInfoAsync();
- }
- public Task SaveStudentDetailAsync(StudentDetail student, bool isNewItem = false) {
- return documentDBService.SaveStudentDetailAsync(student, isNewItem);
- }
- public Task DeleteStudentAsync(StudentDetail student) {
- return documentDBService.DeleteStudentAsync(student.Id);
- }
- }
Step 9
Add the following Namespaces and code in App.xaml.cs.
- using XamFormStudCos.Controller;
- using XamFormStudCos.View;
- public static StudentDetailManager StudentDetailManager {
- get;
- private set;
- }
- public App() {
- InitializeComponent();
- StudentDetailManager = new StudentDetailManager(new DocumentDBService());
- MainPage = new NavigationPage(new StudentList());
- }
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.
- <ContentPage.ToolbarItems>
- <ToolbarItem Text="Add" Order="Primary" Clicked="OnItemAdded" /> </ContentPage.ToolbarItems>
- <ListView x:Name="SList" ItemSelected="OnItemselected">
- <ListView.ItemTemplate>
- <DataTemplate>
- <TextCell Text="{Binding Name}" Detail="{Binding Age}" /> </DataTemplate>
- </ListView.ItemTemplate>
- </ListView>
Add the following Namespaces and code in StudentList.xaml.cs
- using XamFormStudCos.Model;
- protected override async void OnAppearing() {
- base.OnAppearing();
- await App.StudentDetailManager.CreateDatabase(Constants.DatabaseName);
- await App.StudentDetailManager.CreateDocumentCollection(Constants.DatabaseName, Constants.CollectionName);
- var data = await App.StudentDetailManager.GetStoreInfoAsync();
- StdList.ItemsSource = data;
- }
- async void OnItemAdded(object sender, EventArgs e) {
- await Navigation.PushAsync(new StudentDetails(true) {
- BindingContext = new StudentDetail {
- Id = Guid.NewGuid().ToString()
- }
- });
- }
- async void OnItemselected(object sender, SelectedItemChangedEventArgs e) {
- if (e.SelectedItem != null) {
- await Navigation.PushAsync(new EditStudent() {
- BindingContext = e.SelectedItem as StudentDetail
- });
- }
- }
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.
- <ContentPage.Content>
- <StackLayout Margin="20" VerticalOptions="StartAndExpand">
- <Label Text="Name" />
- <Entry Text="{Binding Path=Name}" Placeholder="Enter Student Name" />
- <Label Text="Age" />
- <Entry Text="{Binding Path=Age}" />
- <Button Text="Save" Clicked="OnSaveClicked" />
- <Button Text="Cancel" Clicked="OnCancelClicked" /> </StackLayout>
- </ContentPage.Content>
Add the following Namespaces and code in StudentDetail.xaml.cs
- using XamFormStudCos.Model;
- bool isNewItem;
- public StudentDetails(bool isNew) {
- InitializeComponent();
- isNewItem = isNew;
- }
- async void OnSaveClicked(object sender, EventArgs e) {
- var student = (StudentDetail) BindingContext;
- await App.StudentDetailManager.SaveStudentDetailAsync(student, isNewItem);
- await Navigation.PopAsync();
- }
- async void OnCancelClicked(object sender, EventArgs e) {
- await Navigation.PopAsync();
- }
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,
- <StackLayout Padding="10" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
- <Grid>
- <Label Text="Name" Grid.Row="0" Grid.Column="0" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />
- <Entry Text="{Binding Name}" Grid.Row="0" Grid.Column="1" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />
- <Label Text="Age" Grid.Row="2" Grid.Column="0" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" />
- <Entry Text="{Binding Age}" Grid.Row="2" Grid.Column="1" HorizontalOptions="Start" WidthRequest="100" VerticalOptions="Center" /> </Grid>
- <Button Text="Update" HorizontalOptions="FillAndExpand" BackgroundColor="Blue" TextColor="White" Clicked="Update_Clicked" />
- <Button Text="Delete" HorizontalOptions="FillAndExpand" BackgroundColor="Blue" TextColor="White" Clicked="OnDeleteClicked" />
- <Button Text="Cancel" HorizontalOptions="FillAndExpand" BackgroundColor="Blue" TextColor="White" Clicked="OnCancelClicked" /> </StackLayout>
Add the following Namespaces and code in EditStudent.xaml.cs
- using XamFormStudCos.Model;
- async void Update_Clicked(object sender, System.EventArgs e) {
- var student = (StudentDetail) BindingContext;
- await App.StudentDetailManager.SaveStudentDetailAsync(student);
- await Navigation.PopAsync();
- }
- async void OnDeleteClicked(object sender, EventArgs e) {
- bool accepted = await DisplayAlert("Confirm", "Are you Sure ?", "Yes", "No");
- if (accepted) {
- var student = (StudentDetail) BindingContext;
- await App.StudentDetailManager.DeleteStudentAsync(student);
- await Navigation.PopAsync();
- }
- }
- async void OnCancelClicked(object sender, EventArgs e) {
- await Navigation.PopAsync();
- }
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.