Developing Mobile Apps with Xamarin and Azure

By: Admin

Xamarin, a recent addition to Microsoft’s list of products, allows developers to build apps using a single code base with close-to-native appearance and performance. Up to 95% of the code can be reused across all three platforms. As long as you are proficient in C# and XAML, you can build a mobile app in Xamarin.

developing mobile apps with xamarin and azure

NOTE: You can read about the comparison between native vs hybrid vs Xamarin in this article.

Xamarin allows the opportunity to develop apps using native UI or shared UI using Xamarin Forms.

If you need to create a native app for Android or iOS, you can use Xamarin.Android or Xamarin.iOS.

Xamarin Forms

Xamarin Forms is a cross-platform user interface (UI) toolkit that allows developers to easily create mobile UIs for Android, iOS and Windows Mobile. To create a UI in Xamarin, you can either use a code-based approach or you can use an XAML-based approach.

Here, I’ll show you how to build a Xamarin app for reminders and tasks.

To store the to-do items, we will create an Azure-based mobile app service, where we will consume a service and store the items in a database of choice (here, SQL Server).

Let’s walk through how to create a backend service for the mobile app. You will need an Azure subscription to create and host a mobile app service.

Azure Mobile App Service

Login to the Azure portal: go to the Azure portal. You will be redirected to the Azure portal dashboard.

Click ‘New‘ on the top left corner of the screen.

Process begin

Choose Web + Mobile and select Mobile App.

choosing app type

Enter a unique name for your app service. Select your subscription, and enter a resource group name. Choose the app service plan and location. On the next screen, select Create New and enter an app service plan name. To avoid lagging, choose the location nearest to you. Choose the pricing tier based on your requirements. Since this is a demo app, I have chosen the free tier.

NOTE: it’s important to create a resource group for each unique app service. Once you’re ready to deploy the solution, you can easily remove the resource group to avoid any errors and unexpected billing.

Pricing tier

Click OK to create. After validating your request, Azure will start deploying your mobile app and you will see a notification that the deployment succeeded.  (To check the status of your deployment, click the bell icon on the top right corner of the page. It will open the notifications screen.)

Click “Pin to Dashboard” to easily access the app service in the future. Click “Go to resource”.

View resource

On the App Service, click “Quickstart” on the left side menu. Then choose “Xamarin.Forms.

Xamarin.forms

On the next screen, select the alert shown below: You will need a database in order to complete this Quickstart. Click here to create one.

Create DB

Click “+ Add” on the second screen. This will open a new screen. Choose SQL Database as the type, click “Configure required settings.” Then click “Create a new database.” Enter a database name. Choose a target server to add the SQL database, click “Create a new server.” Enter a unique server name, and the server admin username and password. Choose a location nearest to you. Click “Select.Create new DB

Choose a pricing tier. In this example, we chose basic, which offers 5 DTU and is enough for development purposes. Then click “Select.” Choose a connection string name for connecting to the SQL database. Select “OK.

choose connection string

Choose “C#” as the backend language and click “Download” to download the Azure mobile app backend service.

Choose “CREATE A NEW APP” and click “Download” in the below section to download a preconfigured Xamarin.Forms mobile application.

new app creation

If we look at the downloaded files, it will contain Runtime and Xamarin_Forms added to the service name we created earlier. The “{app-name}_Runtime.zip” file contains the Azure mobile app sample code and “{app-name}_Xamarin_Forms.zip” file contains the Xamarin mobile application.

View files

Extract the compressed zip folders. Open the “{app-name}_Runtime” folder and double-click the “{app-name}.sln” solution file.

Browsing solution files

The solution already contains to-do items in the application backend logic. To connect to the database, on the Azure portal dashboard page, choose the resource group name we used earlier.

Azure portal dashboard

On the next screen, choose the SQL database we created earlier.

SQL database

Click “Connection strings” from the left menu.

Connection string

From the screen under the ADO.NET tab, copy the connection string.

copy string

In Visual Studio, open web.config. Find the ConnectionStrings element and replace the existing connection string with the one copied from the Azure portal.

Web config changes

To learn more about how Entity Framework Code First Model is used to create a database and update tables, I have additional resources listed at the bottom of this blog.

Now, let’s publish the solution so that we can use the to-do items service from the Xamarin mobile application!

From Solution Explorer, right-click on the project and from the popup menu, click publish.

publishing the solution

From the publish screen, choose “Microsoft Azure App Service” –>“Select Existing” and then click “Publish.

Azure App Service

 

Log into your Microsoft account.

Account Login

From the list, choose your created app service and click “OK”. Visual Studio will start publishing your app.

Creating app service

After publishing, you will be redirected to the app service in a browser.

Extract the file “{app-name}_Xamarin_Forms.zip” and open the “{app-name}_Xamarin_Forms.sln” solution file. In Visual Studio, open Solution Explorer, right click on the solution and click “Restore NuGet Packages.” This will take some time to pull all the required NuGet packages.

NuGet packages

Right click on “{app-name}.Android” or “{app-name}.UWP” as the startup. Build the project and run to see the output. Here are the sample outputs from both Android and UWP respectively.

Output1Output2

Start coding in Xamarin. Happy Hacking!

 

—– NEW BLOG —–

Entity Framework Code First Model

In Entity Framework (EF in short), you can create database tables and use the EF Database First model generator to generate model classes. This generates the edmx file (an XML file) which defines a conceptual model, a storage model and the mapping between these models. It also holds information for the ADO.NET Entity Data Model Designer to render a model graphically.

EFC First model

In the database first model, the database tables, any change that needs to be done (for example adding a new column) will need a new query to update the table.

ALTER TABLE dbo.[User] ADD CreatedOn DateTime

After the query execution, update the edmx again to reflect the changes back to the data models.

Query execution

 

Now let’s dive deeper into how to use EF Code First Model.

For this demo, I’ve created a new ASP.NET Core MVC application.

  • If you’re targeting a regular ASP.NET MVC application, you need to install Install-Package EntityFramework using the Package Manager console.
  • If you’re targeting the new ASP.NET Core MVC application, you need to install Install-Package Microsoft.EntityFrameworkCore.SqlServer using the Package Manager console.

You can also use the NuGet Package Manager to install the above packages.

NOTE: Both the packages support Code First Model, but also differs in the functional aspects. For the complete list of supported features, click here.

Code first model

To keep things simple, I created a simple Context that inherits from DbContext and uses a localdb to store the data.

public class SampleContext : DbContext

{

public DbSet<Blog> Blogs { get; set; }

public DbSet<Post> Posts { get; set; }

 

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

{

optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");

}

 

public class Blog

{

public int BlogId { get; set; }

public string Url { get; set; }

public int Rating { get; set; }

public List<Post> Posts { get; set; }

}

 

public class Post

{

public int PostId { get; set; }

public string Title { get; set; }

public string Content { get; set; }

 

public int BlogId { get; set; }

public Blog Blog { get; set; }

}

}

I also created two classes, Blog and Posts, with a one-to-many relationship between blog and posts.

The first command that needs to be executed is to enable migrations if any code changes can be added back to the database.

Add-Migration

To run this command using the package manager console, use the Add-Migration command followed by a word.

Migration command

Create a new migration with the specified name.

public partial class First : Migration

{

protected override void Up(MigrationBuilder migrationBuilder)

{

migrationBuilder.CreateTable(

name: "Blogs",

columns: table => new

{

BlogId = table.Column<int>(type: "int", nullable: false)

.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),

Rating = table.Column<int>(type: "int", nullable: false),

Url = table.Column<string>(type: "nvarchar(max)", nullable: true)

},

constraints: table =>

{

table.PrimaryKey("PK_Blogs", x => x.BlogId);

});

 

migrationBuilder.CreateTable(

name: "Posts",

columns: table => new

{

PostId = table.Column<int>(type: "int", nullable: false)

.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),

BlogId = table.Column<int>(type: "int", nullable: false),

Content = table.Column<string>(type: "nvarchar(max)", nullable: true),

Title = table.Column<string>(type: "nvarchar(max)", nullable: true)

},

constraints: table =>

{

table.PrimaryKey("PK_Posts", x => x.PostId);

table.ForeignKey(

name: "FK_Posts_Blogs_BlogId",

column: x => x.BlogId,

principalTable: "Blogs",

principalColumn: "BlogId",

onDelete: ReferentialAction.Cascade);

});

 

migrationBuilder.CreateIndex(

name: "IX_Posts_BlogId",

table: "Posts",

column: "BlogId");

}

 

protected override void Down(MigrationBuilder migrationBuilder)

{

migrationBuilder.DropTable(

name: "Posts");

 

migrationBuilder.DropTable(

name: "Blogs");

}

}

}

Run the Add-migration command to generate the class above.

To update the database, use the Update-database command.

update the database

Then, create the database (if it doesn’t exist) and create the tables.

Create database and tables

Let’s modify the post class and update the database.

public class Post

{

public int PostId { get; set; }

public string Title { get; set; }

public string Content { get; set; }

public DateTime PostedDate { get; set; }

 

public int BlogId { get; set; }

public Blog Blog { get; set; }

}

I added PostedDate property to the post class. Now, run the add-migration command once again to generate a new migration.

public partial class second : Migration

{

protected override void Up(MigrationBuilder migrationBuilder)

{

migrationBuilder.AddColumn<DateTime>(

name: "PostedDate",

table: "Posts",

type: "datetime2",

nullable: false,

defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));

}

 

protected override void Down(MigrationBuilder migrationBuilder)

{

migrationBuilder.DropColumn(

name: "PostedDate",

table: "Posts");

}

}

Let’s update the database using update-database command.

Update-Database Command

To learn more about the code first model works under the hood, click here to watch the screencast.

To learn how to use a code-first model in a team environment and learn about its limitations, watch this video.

 

What are you looking for?

Join our newsletter list of over 5,000 innovators and receive an email update every other month

Copyright © 2018 alligatortek. All rights reserved.