Xamarin Forms and Azure Easy Tables (as easy as 1 2 3)

Posted by seven.srikanth@gmail.com at 28-05-2018 17:30:44 in Article



 Overview

Hi Guys, we are about to discuss Xamarin.Forms with Azure Appservices Easy Tables, great front-end apps need great back-end and there is tons of solution or options of doing it, But today we will see how Azure has done a great job making it relatively easy for developers to connect on back-end service without coding it.

Getting Started

Now lets create a Mobile App Service in Azure Portal, Go ahead by clicking "Mobile App" as shown in a screenshot below. Now click create. Name your app accordingly, in our case we named it "conversationapp". If you have no existing resource you can create new one or you can use your existing one. Now click create. Now click "Easy Tables" in order for us to create table. You will notice that, you will need to configure your easy tables as it has detected that no database has been created for use in your easy tables. Now click the highlighted link below to create a new database. Click add to create database. Now name your database, in our example we name it "conversationdb". You can select pricing accordingly, in our case we use free since this is for testing purpose. But in production we should use a more appropriate capacity according to our app's scaling need. We also gonna need to create a server for our db, in our case we use the location "East Asia". When you are done with creating a database, you are now ready to initialize App Service to use easy tables. Now click Initialize App. Now go and create a table named "Message", we make it more simple as possible. You can create as many tables depending on your app. We can also set table relationship when it needs to, be aware to editing deleting columns created by Azure tables that might cause an issue with syncing. And that's it for the App Service.

Creating our app to Connect With Easy Tables

Now that our app service is ready to rock in roll, we can now create our app to connect with easy tables. First create a new Xamarin.Forms project and name it "ConversationApp". Create model for Message -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConversationApp.Models
{
public class Message
{
public string Id { get; set; }
public string Sender { get; set; }
public string Messagetext { get; set; }
public string UserImageUrl { get; set; }
}
- Creata ViewModel for ConversationPage and name it "ConversationPageViewModel" -
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using ConversationApp.Models;
using Xamarin.Forms;
namespace ConversationApp.ViewModels
{
public class ConversationPageViewModel : INotifyPropertyChanged
{
private ObservableCollection<Message> _messages;
private string _userName;
private string _textMessage;
private ICommand _sendMessageCommand;
public event PropertyChangedEventHandler PropertyChanged;
public ConversationPageViewModel()
{
Messages = new ObservableCollection<Message>();
Messages.Add(new Message {Messagetext = "Hello", Sender = "Sender", UserImageUrl = "me_user.png"});
}
public ObservableCollection<Message> Messages
{
get { return _messages; }
set
{
_messages = value;
OnPropertyChanged("Messages");
}
}
public string UserName
{
get { return _userName; }
set
{
_userName = value;
OnPropertyChanged("UserName");
}
}
public string TextMessage
{
get { return _textMessage; }
set
{
_textMessage = value;
OnPropertyChanged("TextMessage");
}
}
public ICommand SendMessageCommand
{
get { return _sendMessageCommand = _sendMessageCommand ?? new Command(() =>
{
}); }
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
- Create a new Page and name it ConversationPage.xaml -
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:ConversationApp.ViewModels;assembly=ConversationApp"
x:Class="ConversationApp.Pages.ConversationPage">
<ContentPage.BindingContext>
<viewModels:ConversationPageViewModel></viewModels:ConversationPageViewModel>
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout Orientation="Vertical"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<ListView ItemsSource="{Binding Messages}"
Margin="10"
HasUnevenRows="True"
IsPullToRefreshEnabled="True"
IsRefreshing="{Binding IsRefreshing }">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
Orientation="Horizontal">
<Image Source="{Binding UserImageUrl}"></Image>
<StackLayout Orientation="Vertical">
<Label Text="{Binding Messagetext, StringFormat='Message: {0}'}"></Label>
<Label Text="{Binding Sender, StringFormat='Sender: {0}'}"></Label>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackLayout VerticalOptions="End" HorizontalOptions="FillAndExpand">
<Entry Placeholder="Please enter you name.." Text="{Binding UserName}"></Entry>
<Entry Placeholder="Please enter message.." Text="{Binding TextMessage}"></Entry>
<Button Text="Send" Command="{Binding SendMessageCommand}"></Button>
</StackLayout>
</StackLayout>
</ContentPage.Content>
</ContentPage>
view raw ConversationPage.cs hosted with ❤ by GitHub
- Now create our AzureService client class to make a sync calls to our easy tables, but before that, we will need to install nuget packages for MobileServiceClient in our PCL and Platform projects as shown below.

Initialize the Azure Mobile Client

Add the Azure Mobile Client SDK initialization code in the platform projects. For iOS, the following code must be added to the FinishedLaunching method of the AppDelegate class:
Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init(); SQLitePCL.CurrentPlatform.Init(); For Android, add the following to the OnCreate method of your MainActivity: Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init(); We will now create AzureDataService , the following are the code -
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConversationApp.Models;
using Microsoft.WindowsAzure.MobileServices;
using Microsoft.WindowsAzure.MobileServices.SQLiteStore;
using Microsoft.WindowsAzure.MobileServices.Sync;
namespace ConversationApp.Services
{
public class AzureDataService
{
private MobileServiceClient _mobileServiceClient = new MobileServiceClient("http://conversationapp.azurewebsites.net");
IMobileServiceSyncTable<Message> _messageTable;
public async Task Initialize()
{
if (_mobileServiceClient?.SyncContext?.IsInitialized ?? false)
return;
const string path = "syncstore.db";
//setup our local sqlite store and intialize our table
var store = new MobileServiceSQLiteStore(path);
store.DefineTable<Message>();
await _mobileServiceClient.SyncContext.InitializeAsync(store, new MobileServiceSyncHandler());
//Get our sync table that will call out to azure
_messageTable = _mobileServiceClient.GetSyncTable<Message>();
}
public async Task<IEnumerable<Message>> GetMessages()
{
await Initialize();
await SyncMessage();
return await _messageTable.ToEnumerableAsync();
}
public async Task AddMessage(Message msg)
{
await Initialize();
await _messageTable.InsertAsync(msg);
await SyncMessage();
}
public async Task SyncMessage()
{
try
{
await _messageTable.PullAsync("allMessage", _messageTable.CreateQuery());
await _mobileServiceClient.SyncContext.PushAsync();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
- We will now be able to run our Xamarin project, please make sure to make platform project as a startup. It should look like this. You should be able to see the data you sync in Azure Easy Tables, without a sweat :D Please check the full source code here.

Wrapping Up

Azure App Services provides more flexibility for mobile development integrating Authentication, Notification and that what makes it a developer centric tool. To learn more of this please check our Xamarin Blog  https://blog.xamarin.com . Please dont hesitate to leave a message if you have clarification or question. Thats all.
Original Author: 
Source: http://winstongubantes.blogspot.in/2017/02/xamarinforms-and-azure-easy-tables-as.html

Tags: Xamarin Forms and Azure Easy Tables (as easy as 1 2 3)



0 Comments
Login to comment.

Recent Comments

Be the first to Comment. You can ask a Query or Share your toughts or Just say thanks.