This article provide sample code for developer to access Azure Services with Microsoft Xamarin Cross platform mobile app. This article provide sample code for developer to access Azure Services with Microsoft Xamarin Cross platform mobile app.

Azure Mobile Service

With the Mobile Apps feature of Azure App Service, it is easy to rapidly build cross-platform and native apps for iOS, Android, Windows or Mac. Store app data on cloud or on local device, authenticate users, send push notifications or add your custom backend logic in C#.

You can add structured storage, push notifications, authentication, and more to your Xamarin based mobile application using Microsoft Azure Mobile Apps.

You will create both a new Mobile App backend and a simple Xamarin.Forms app that stores app data in Azure.

Prerequisites

XCode 4.5 and above (for building iOS Apps)

Xamarin Tools

A Windows Azure subscription (Free Trial)

Creating an Azure Mobile Services using C#.NET backend

If you are starting a new project, you can develop an App Service using either the Azure Portal or Visual Studio and that delivers you the entire project stucture of the Services with some sample files. This section will help you use one of these to build a new mobile app backend which hosts a simple API. You can run this locally or publish the project to your cloud-based App Service mobile app.

Defining the model

public class Organization : EntityData { public string College { get ; set ; } public string City { get ; set ; } public string State { get ; set ; } public string League { get ; set ; } public string Conference { get ; set ; } public string Gender { get ; set ; } public string Sport { get ; set ; } public string Organization_Logo { get ; set ; } public string Venue { get ; set ; } }

Create Controller with the needed methods

public class OrganizationController : TableController < Organization > { protected override void Initialize( HttpControllerContext controllerContext) { base .Initialize(controllerContext); SeeUAzureMobileServiceContext context = new SeeUAzureMobileServiceContext (); DomainManager = new EntityDomainManager < Organization >(context, Request); } // GET tables/Organization public IQueryable < Organization > GetAllOrganizations() { return Query(); } // GET tables/Organization/48D68C86-6EA6-4C25-AA33-223FC9A27959 public SingleResult < Organization > GetOrganization( string id) { return Lookup(id); } // PATCH tables/Organization/48D68C86-6EA6-4C25-AA33-223FC9A27959 public Task < Organization > PatchOrganization( string id, Delta < Organization > patch) { return UpdateAsync(id, patch); } // POST tables/Organization public async Task < IHttpActionResult > PostOrganization( Organization item) { Organization current = await InsertAsync(item); return CreatedAtRoute( "Tables" , new { id = current.Id }, current); } // DELETE tables/Organization/48D68C86-6EA6-4C25-AA33-223FC9A27959 public Task DeleteOrganization( string id) { return DeleteAsync(id); } }

Configuration Mobile App Service with the Azure keys & credentials

public static void ConfigureMobileApp ( IAppBuilder app) { HttpConfiguration config = new HttpConfiguration (); //For more information on Web API tracing, see http://go.microsoft.com/fwlink/?LinkId=620686 config.EnableSystemDiagnosticsTracing(); new MobileAppConfiguration () .UseDefaultConfiguration() .ApplyTo(config); // Use Entity Framework Code First to create database tables based on your DbContext Database .SetInitializer( new SeeUAzureMobileServiceInitializer ()); // To prevent Entity Framework from modifying your database schema, use a null database initializer // Database.SetInitializer(null); MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings(); if ( string .IsNullOrEmpty(settings.HostName)) { // This middleware is intended to be used locally for debugging. By default, HostName will // only have a value when running in an App Service application. app.UseAppServiceAuthentication( new AppServiceAuthenticationOptions { SigningKey = ConfigurationManager .AppSettings[ "SigningKey" ], ValidAudiences = new [] { ConfigurationManager .AppSettings[ "ValidAudience" ] }, ValidIssuers = new [] { ConfigurationManager .AppSettings[ "ValidIssuer" ] }, TokenHandler = config.GetAppServiceTokenHandler() }); } app.UseWebApi(config); }

After Creating an Azure Mobile Services using C#.NET backend, we need to build the project and deploy it to Azure server.

Create a Xamarin forms Application.

To implement Azure Mobile Service in Xamarin project, we need to include Azure Mobile Client SDK using package manager of the Development Tool and this SDK will help to communicate with the Azure Service.

Add Application URL which will used by MobileServiceClient object to connect with Azure Service

public static string ApplicationURL = @"URL_TO_AZURE_SERVICE" ;

Now Create Model in Xamarin Forms Application

public class Organization { string id; string college; string city; string state; string league; string conference; string gender; string sport; string organization_Logo; string venue; [ JsonProperty (PropertyName = "id" )] public string Id { get { return id; } set { id = value ; } } [ JsonProperty (PropertyName = "College" )] public string College { get { return college; } set { college = value ; } } [ JsonProperty (PropertyName = "City" )] public string City { get { return city; } set { city = value ; } } [ JsonProperty (PropertyName = "State" )] public string State { get { return state; } set { state = value ; } } [ JsonProperty (PropertyName = "League" )] public string League { get { return league; } set { league = value ; } } [ JsonProperty (PropertyName = "Conference" )] public string Conference { get { return conference; } set { conference = value ; } } [ JsonProperty (PropertyName = "Gender" )] public string Gender { get { return gender; } set { gender = value ; } } [ JsonProperty (PropertyName = "Sport" )] public string Sport { get { return sport; } set { sport = value ; } } [ JsonProperty (PropertyName = "Organization_Logo" )] public string Organization_Logo { get { return organization_Logo; } set { organization_Logo = value ; } } [ JsonProperty (PropertyName = "Venue" )] public string Venue { get { return venue; } set { venue = value ; } } }

Create Manager class for manage insert, retrive, update date in azure tables

public partial class OrganizationManager { static OrganizationManager defaultInstance = new OrganizationManager (); MobileServiceClient client; #if OFFLINE_SYNC_ENABLED IMobileServiceSyncTable <Organization> organizationTable; #else IMobileServiceTable<Organization> organizationTable; #endif public OrganizationManager() { this .client = new MobileServiceClient( Constants.ApplicationURL); #if OFFLINE_SYNC_ENABLED var store = new MobileServiceSQLiteStore("localstore.db"); store.DefineTable<Organization> (); //Initializes the SyncContext using the default IMobileServiceSyncHandler. this.client.SyncContext.InitializeAsync(store); this.organizationTable = client.GetSyncTable<Organization>(); #else this .organizationTable = client.GetTable<Organization>(); #endif } /// <summary> /// Gets the default manager. /// </summary> /// The default manager. public static OrganizationManager DefaultManager { get { return defaultInstance; } private set { defaultInstance = value ; } }

Finally we need to add below Call in all the Platform to init the MobileServic

Call Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init(); in your Xamarin.iOS and Xamarin.Android application.

Contact us for xamarin mobile application development. We have highly experienced team of Xamarin developers at competitive rates with best client experiences!

Image Designed by Freepik