Building Serverless Mobile App With Azure Functions Using Xamarin.Forms

Introduction

Azure Functions is a solution for easily running small pieces of code in the cloud. We can create, execute, and test our custom logic function without creating a VM or web application and also without needing to install any software or infrastructure to run the function. In this article, we'll learn how to implement Azure Functions and directly call through HTTP from Xamarin.Forms application.

Serverless Mobile App

Create Azure Functions

I have explained about different ways to create basic Azure Functions in my previous article. You can refer to any of the below articles for creating new Azure Functions.
Serverless Mobile App

  1. Getting Started With Azure Functions Using Azure Free Trial Account
  2. How To Create And Test Azure Functions Using Azure Portal
  3. Getting Started With Microsoft Azure Functions Using Visual Studio 2017

Create New Xamarin Forms Client Application

We need to create a new blank Xamarin.Forms application and add a new XAML page. You can refer to my previous article for setting up and creating new Xamarin.Forms application.

If you have already installed VS on your machine, open Visual Studio >> Create New Project ( Ctrl +Shift +N) >> Select Cross-Platform Template >> Select Blank Xamarin Forms Application >> Provide Project name and press OK.

 The Solution will be created with all the platform and PCL projects.

Serverless Mobile App

Design portable UI

The UI will have a few elements on the screen. Entry control for providing user input value and label for print output text .

  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.              x:Class="AzureFunctionsDemo.MainPage">  
  5. <StackLayout>    
  6.   <!--Title text-->  
  7. <Label Text ="Building Serverless Mobile App with Azure Functions using Xamarin Forms" HorizontalOptions="Center" TextColor="Green" FontSize="30" />  
  8.   <!--Provide Input Parameter to Azure Functions-->   
  9.   <Entry TextColor="Green" x:Name="txtname" Placeholder =" Enter Your Name" />  
  10.   <!--Click On Button For Communicate to Azure Functions-->  
  11.     <Button Text="Connect to Azure Functions"  Clicked="OnButtonClicked" />  
  12.   <!--Activity Indicator will show progress of client and Azure connection and excution-->   
  13.   <ActivityIndicator x:Name="waitindicator" IsVisible ="false"  
  14.                            Color="Black" />  
  15.   <!--Output label-->  
  16. <Label x:Name="lblname" HorizontalOptions="Center" TextColor="Green" FontSize="30" />  
  17. </StackLayout>  
  18. </ContentPage>  

Create Aure Functions Helper Class

It's time to integrate Azure Functions into the Mobile Applciation. Now, you can add Newtonsoft.JSON from portable project. Right click on Portable Project >  Manage NuGet Packages > select Newtonsoft.Json from Browse tab > click on Install.

Serverless Mobile App

Create Uri custom extension method for appending the query string.

  1. public static class Common  
  2.     {  
  3.         /// <summary>  
  4.         /// BuildQueryString  
  5.         /// </summary>  
  6.         /// <param name="uri"></param>  
  7.         /// <param name="parameters"></param>  
  8.         /// <returns></returns>  
  9.         public static Uri BuildQueryString(this Uri uri, Dictionary<string, string> parameters)  
  10.         {  
  11.             var stringBuilder = new StringBuilder();  
  12.             string str = "?";  
  13.             foreach (KeyValuePair<string, string> item in parameters)  
  14.             {  
  15.                 stringBuilder.Append(str + item.Key + "=" + item.Value);  
  16.                 str = "&";  
  17.             }  
  18.   
  19.             return new Uri(uri + stringBuilder.ToString());  
  20.         }     
  21.     } 

We have already created Get Azure Functions, before writing C# code, copy functions URL of Azure portal and write the HTTP get client method as per below. The HTTP Client will automatically be included in the latest .NET Framework.

  1. using Newtonsoft.Json;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Net.Http;  
  6. using System.Text;  
  7. using System.Threading.Tasks;  
  8.  namespace AzureFunctionsDemo  
  9. {  
  10.    public class AzureFunctionHelper  
  11.     {  
  12.         // Remember to paste below your Azure Function url copied before in the Portal:  
  13.         const string AZURE_FUNCTION_URL = "https://devenvexefunctiondemo.azurewebsites.net/api/HttpTriggerCSharp1";  
  14.         // Remember to paste below your Azure Function Key copied before in the Portal:  
  15.         const string AZURE_CODE = "fnNK7ncbR3QKAgMgXAaV1gnPMgaPaqUTH3mbv7gi9nM9zt7yJImeng==";  
  16.         /// <summary>  
  17.         ///Get Azure Functions  
  18.         /// </summary>  
  19.         /// <typeparam name="T"></typeparam>  
  20.         /// <param name="name"></param>  
  21.         /// <returns></returns>  
  22.   
  23.         public async Task<object> GetAsync<T>(string value)  
  24.         {  
  25.             var httpClient = new HttpClient();  
  26.             Dictionary<string, string> query = new Dictionary<string, string>();  
  27.             query["code"] = AZURE_CODE;  
  28.             query["name"] = value;  
  29.             Uri uri = new Uri(AZURE_FUNCTION_URL).BuildQueryString(query);  
  30.             var content = await httpClient.GetStringAsync(uri);  
  31.             return JsonConvert.DeserializeObject(content);  
  32.         }  
  33.   
  34.     } 

Now, you can start calling GetAsync method from MainPage.xaml.cs file.

  1. using System;  
  2. using Xamarin.Forms;  
  3.   
  4. namespace AzureFunctionsDemo  
  5. {  
  6.     public partial class MainPage : ContentPage  
  7.     {  
  8.         public MainPage()  
  9.         {  
  10.             InitializeComponent();  
  11.         }  
  12.         async void OnButtonClicked(object sender, EventArgs args)  
  13.         {  
  14.             //Show Wait indicator  
  15.             waitindicator.IsVisible = true;  
  16.             waitindicator.IsRunning = true;  
  17.             //Calling Azure Function  
  18.              AzureFunctionHelper oazurehelper = new AzureFunctionHelper();  
  19.             var value = await oazurehelper.GetAsync<string>(txtname.Text);  
  20.             //print azure fucntion return value  
  21.             lblname.Text = value.ToString();  
  22.             //Disable wait Indicator after loading output   
  23.             waitindicator.IsVisible = false;  
  24.             waitindicator.IsRunning = false;  
  25.   
  26.         }  
  27.     }  
  28. }   

We have completed all the code for consuming Azure Functions from Xamarin. Now, we can select the platform and press F5. The output looks like below.

Serverless Mobile App

Serverless Mobile App

Summary

You have learned from here how to create an Azure Function without its own server. Azure Functions is directly called through HTTP from Xamarin.Forms application.

If you have any questions/ feedback/ issues, please write in the comment box.


Similar Articles