Introduction to Azure App Service

Microsoft Azure has changed significantly in the latest release, showing Microsoft’s intent to improve its services in order to provide the best solutions for its clients. Sara Silva introduces the Azure App Service, a new service that adds features to Microsoft Azure, pointing out the advantages that this service brings to Microsoft clients.

Read the full article here.

Azure Mobile Services: How to change the database

Scope

This article has the goal to show how to change the database associated with an existing Azure Mobile Service.

Introduction

Azure Mobile Services creates a Azure SQL Database for each Azure Mobile Service, this way the database will be connected with it, as we can see in the following image:
azure

In this article, we will see how to replace the database with other database instance.

Description

To change the database from an Azure Mobile Service, wee need to go the Configure separator from the Azure Mobile Service, and at the bottom of the page we will see the following menu:

change database menu

Clicking “Change Database” we will have the following screen
create database

Which allow to create a new database, create a free database (if available) and choose an existing database. After it, we will wait for a while and a new database instance will be related with the Azure Mobile Service:

database changed

If we apply a refresh, the page will load the data and the connection string used to connect to the database will be updated, as we can see in the following image:
connection string

Azure Mobile Services: Q&A and Tips for .Net Backend

Q & A

Which tools & SDK version should I use for .Net Backend?

You should use the last stable version:

  • Visual Studio 2013 Update 4
  • Azure SDK 2.5
  • Last stable Nuget packages

How to avoid assemblies load when the .Net project is updated?

The Azure Mobile Services – .Net Backend uses different Nuget packages and it is not recommended to update all Nuget available in “Update” windows from “Manage Nuget Package”. We should only update Microsoft Azure Mobile Services .NET Backend Entity Framework Extension Nuget package. If something went wrong you should uninstall all packages and then install

For more information see this article.

Which Nuget package should I use if I want to use Azure Storage?

You can use the Microsoft Azure Mobile Services .NET Backend Azure Storage Extension, to avoid this kind of errors:

“Found conflicts between different versions of the same dependent assembly ‘Microsoft.WindowsAzure.Storage’: 4.3.0.0. Please change your project to use version ‘3.1.0.1’ which is the one currently supported by the hosting environment.”

Can I define a Dev and Prod environments?

Yes, you can. To create different environments using the same code you can use transform file as described in this article.

Can I run my services in localhost?

Yes, you can. In development you should use first localhost and after the tests are ok, you can publish it to the Azure. This way, you are not doing “call APIs” to your Azure Mobile Services. For more information see this article (Running the service in localhost).

Can I use a local SQL Server database when the services are running in localhost?

Yes, you can. In local development you can use a local SQL Server database but you must be aware that there are few difference between SQL Azure database and SQL SQL Server database.

Can I use a SQL Azure database when the services are running in localhost?
Yes, you can. To use a SQL Azure database in localhost you must allow your IP to access the database, and this configuration must be done in Azure Portal (in the database separator). For more information see this article (Defining the allowed IP for the database).

How I can see the WebConfig file published in Azure?

To see the WebConfig file published in Azure you should use Kudo. For more information see this article.

How to see the log files in server?

In Azure Portal, it is possible to see the logs from the selected Azure Mobile Service (in Logs separator), but for some reason is need to see the log files, you should use Kudo to get it. For more information see this article and in this article (How to see details about errors).

How can I write my logs?

In you service, you should have a property called Services, provided for example by TableController, which has a property called Log and this way is possible to write logs, and is possible to define the type Error or Information.

Is possible to debug my code which is running in Azure?

Yes, you can deploy to Azure and is possible to debug that version, this way each request by the client application can be catch by the remote debugger. For more information see this article.

How should I manage images in Azure Mobile Services?

In Azure Mobile Service you should not send the image to the backend. You should not save in your SQL Database and you should save all images, videos, etc, in Blob Storage. This way, you need notify the Backend about it and the Backend will provide the information required to upload the image to the blob storage. See more information in Upload images to Azure Storage by using Mobile Services.

 Why CreateAt, UpdateAt and Version are null in my requests?
These properties are called “system properties” and the client application can request it doing something like

var q = todoTable.CreateQuery();

q.Parameters.Add("__systemproperties", "*");

items = await q.Where(todoItem => todoItem.Complete == false).ToCollectionAsync();

Or using the solution provided in: Using the new system properties of Azure Mobile Services Tables from a client application.

Should I use model & dtos or should expose model as dtos?

It depends of the application requirement, but in general it is preferred to use model & dtos because in some cases there are information in database which cannot be public or shared outside, this way dtos only expose the information we need.

Tips

 

Samples

Samples to help developers to use Azure Mobile Services.

 

Microsoft Azure Mobile Service: How to create the Azure Mobile Service in Azure Portal

This article aims to show how to create an Azure Mobile Service in the portal and how to create the Visual Studio 2013 Project.

Microsoft’s Windows App Studio Beta: Connecting a Menu App to Azure Mobile Service

This article aims to connect the Menu App from Windows App Studio with Azure Mobile Service, using .Net back end. It includes the main point each developer must know:

  • Analysis the model;
  • Create a table controller (a service)
  • Validate data
  • Overview about DomainManager class, EntityDomainManager class
  • The Entity Framework’s context
  • Database (connection string, defining the allowed IP for the database, migration, seed)
  • Running the service in localhost
  • Publish and run the service in Azure
  • How to see errors
  • Remote debug

Avoid nightmares using EF First Migration in Azure Mobile Services

Scope

This article has the goal to show how to enable, add and use Entity Framework Code First Migrations in Azure Mobile Services to create and update the database based in the model.

Introduction

Microsoft Azure Mobile Services is an Azure service offering designed to make it easy to create highly-functional mobile apps using Azure. Mobile Services brings together a set of Azure services that enable backend capabilities for your apps.

In Azure Mobile Services, there are different ways to create the database, it can be created manually in SQL Server Management Studio or in Visual Studio, or can be created using Code First Migrations or using IDatabaseInitializer. By default, Azure Mobile Service uses database initializers, like we can see in the WebApiConfig class from the project created:

namespace AzureMobileService
{
    public static class WebApiConfig
    {
        public static void Register()
        {
            // Use this class to set configuration options for your mobile service
            ConfigOptions options = new ConfigOptions();
 
            // Use this class to set WebAPI configuration options
            HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));
 
            // To display errors in the browser during development, uncomment the following
            // line. Comment it out again when you deploy your service for production use.
            // config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
 
            Database.SetInitializer(new MobileServiceInitializer());
        }
    }
 
    public class MobileServiceInitializer : DropCreateDatabaseIfModelChanges<MobileServiceContext>
    {
        protected override void Seed(MobileServiceContext context)
        {
            List<TodoItem> todoItems = new List<TodoItem>
            {
                new TodoItem { Id = Guid.NewGuid().ToString(), Text = "First item", Complete = false },
                new TodoItem { Id = Guid.NewGuid().ToString(), Text = "Second item", Complete = false },
            };
 
            foreach (TodoItem todoItem in todoItems)
            {
                context.Set<TodoItem>().Add(todoItem);
            }
 
            base.Seed(context);
        }
    }
}

Like we can see, the MobileServiceInitializer implements the DropCreateDatabaseIfModelChanges, it is an implementation of IDatabaseInitializer that will DELETE, recreate, and optionally re-seed the database only if the model has changed, since the database was created. If the model doesn’t change we can use it, but Are we sure that the model will not change in future?” this way maybe this solution is not a best solution for create the database.

Note: There are others IDatabaseInitializer that can be used, but the problem is same, data will lost if the model changes.

In this article we will use Entity Framework  – Code First Migrations, that means we create the model first and then create the database based in the model structure, this process happens when we do a deploy, and we will see common issues related with migrations in Azure Mobile Services.

Description

Create a .Net Backend as following:
Figure 1 Creating an Azure Mobile Service
Figure 1 Creating an Azure Mobile Service
After it, create a class diagram like in the Figure 2, to understand the project.

Note: Read more about creating class diagram in the article Class diagram: an easy way to understand code.
Figure 2 The class diagram
Figure 2 The class diagram
This way, we can conclude, by default an Azure Mobile Service has at least the following classes

  • TodoItem – define the model and at the same time the DTO;
  • MobileServiceContext – implement the DbContext from Entity Framework;
  • TodoItemController – define the service to expose CRUD operation to the TodoItem;

And the model defined by TodoItem is the DTO provided by the service defined in the TodoItemController.

Note:

  1. We could create another model but it is not important for the article, this way we will use the model provided by default.
  2. TodoItem implements the EntityData from the Azure Mobile Service SDK and each DTO should implement this class because will be required to use the offline feature provided by Azure Mobile Services and to create a TableController we need it.

Enable Migrations

At this moment we know the model and the DbContext, but before start with the migrations process we need to define the connection string to a NEW database in WebConfig. Now we need to enable the project to have migrations, for it open the “Package Manager Console” as following:

Figure 3 Opening Package Manager Console
Figure 3 Opening Package Manager Console

The following window will be opened:
Figure 4 Package Manager Console
Figure 4 Package Manager Console

To enable migration is required to run “Enable-Migrations” in the “Package Manager Console” and the “Default project” should be selected based in the project that contains the DbContext:

Figure 5 Enable Migrations

Figure 5 Enable Migrations
This operation will result in a new folder, called Migrations with a new class, in the project, like we can see in the Figure 6.

Figure 6 Migrations folder
Figure 6 Migrations folder
The class added, the Configuration, is defined by

    internal sealed class Configuration : DbMigrationsConfiguration<Models.MobileServiceContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(AzureMobileService.Models.MobileServiceContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }

And this class will be responsible to create, update or delete the database depending on the migration provided and it is possible to populate the database with initial data using the seed method. The seed method can be used to create fake data or add initial data in the database, and all developers should aware that method can run more one time, with it is need to verified if the data is not cloned.

Let’s define some data in the Seed method, as following:

    
    internal sealed class Configuration : DbMigrationsConfiguration<Models.MobileServiceContext>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Configuration"/> class.
        /// </summary>
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        /// <summary>
        /// Seeds the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        protected override void Seed(Models.MobileServiceContext context)
        {
            context.TodoItems.AddOrUpdate(
                  p => p.Id,
                  new TodoItem { Id = Guid.NewGuid().ToString(), Text = "Clean the car." },
                  new TodoItem { Id = Guid.NewGuid().ToString(), Text = "Read a book" }
                );
        }
    }

 

Add Migration

Before add the migration all developers should be aware that in the MobileServiceContext class we have the method

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            string schema = ServiceSettingsDictionary.GetSchemaName();
            if (!string.IsNullOrEmpty(schema))
            {
                modelBuilder.HasDefaultSchema(schema);
            }

            modelBuilder.Conventions.Add(
                new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
                    "ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
        }

And in this method will be defined the name of the schema used by the database and the name of the schema is defined in the WebConfig file, as following

  <appSettings>
    <add key="MS_MobileServiceName" value="migrations" />

Where the value “migrations” is the name of the Azure Mobile Service, if the schema name and the Azure Mobile Service’s name does not match the migration, it will fail because of the default user, used by the Azure Mobile Service created, do not have permissions to change the schema name or is possible to get an error saying that the user do not have permission to access the master database.

After it, we can add the migration, and for it we need to run “Add-Migration Initial” in “Package Manager Console”, this command will use the model defined in the project and will compare it with the database, to create the migration.

Figure 7 Adding migration Initial
Figure 7 Adding migration Initial
The result will be something as following:

Figure 8 The migration
Figure 8 The migration

The Initial class will define the migration and the Up method, will create the database and the table “AzureMobileService.TodoItems” and the Down method will do the reverse. The Initial class will be defined by

  public partial class Initial : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "migrations.TodoItems",
                c => new
                    {
                        Id = c.String(nullable: false, maxLength: 128,
                            annotations: new Dictionary<string, AnnotationValues>
                            {
                                { 
                                    "ServiceTableColumn",
                                    new AnnotationValues(oldValue: null, newValue: "Id")
                                },
                            }),
                        Text = c.String(),
                        Complete = c.Boolean(nullable: false),
                        Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion",
                            annotations: new Dictionary<string, AnnotationValues>
                            {
                                { 
                                    "ServiceTableColumn",
                                    new AnnotationValues(oldValue: null, newValue: "Version")
                                },
                            }),
                        CreatedAt = c.DateTimeOffset(nullable: false, precision: 7,
                            annotations: new Dictionary<string, AnnotationValues>
                            {
                                { 
                                    "ServiceTableColumn",
                                    new AnnotationValues(oldValue: null, newValue: "CreatedAt")
                                },
                            }),
                        UpdatedAt = c.DateTimeOffset(precision: 7,
                            annotations: new Dictionary<string, AnnotationValues>
                            {
                                { 
                                    "ServiceTableColumn",
                                    new AnnotationValues(oldValue: null, newValue: "UpdatedAt")
                                },
                            }),
                        Deleted = c.Boolean(nullable: false,
                            annotations: new Dictionary<string, AnnotationValues>
                            {
                                { 
                                    "ServiceTableColumn",
                                    new AnnotationValues(oldValue: null, newValue: "Deleted")
                                },
                            }),
                    })
                .PrimaryKey(t => t.Id)
                .Index(t => t.CreatedAt, clustered: true);
            
        }
        
        public override void Down()
        {
            DropIndex("migrations.TodoItems", new[] { "CreatedAt" });
            DropTable("migrations.TodoItems",
                removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>>
                {
                    {
                        "CreatedAt",
                        new Dictionary<string, object>
                        {
                            { "ServiceTableColumn", "CreatedAt" },
                        }
                    },
                    {
                        "Deleted",
                        new Dictionary<string, object>
                        {
                            { "ServiceTableColumn", "Deleted" },
                        }
                    },
                    {
                        "Id",
                        new Dictionary<string, object>
                        {
                            { "ServiceTableColumn", "Id" },
                        }
                    },
                    {
                        "UpdatedAt",
                        new Dictionary<string, object>
                        {
                            { "ServiceTableColumn", "UpdatedAt" },
                        }
                    },
                    {
                        "Version",
                        new Dictionary<string, object>
                        {
                            { "ServiceTableColumn", "Version" },
                        }
                    },
                });
        }
    }

Run the migration

Now that we have the migration defined we can run the project but the database will not be created, because we did not defined how the project will run the migration or we do not update the database using “Update-Database” or “Update-Database -script” like we can see in the Figure 9

Figure 9 Creating the sql script
Figure 9 Creating the sql script

This operation will create a SQL script that can be used to create or even update the database if the developer would like.

In Azure Mobile Services, we use

    var migrator = new DbMigrator(new Configuration());
    migrator.Update();

 

To run the migration, which will be defined in WebApiConfig.

To avoid the issue about “Not found bootstrapper”, we need to change the WebApiConfig to

    public class WebApiConfig : IBootstrapper
    {
        /// <summary>
        /// Defines the entry point for the application. It is the responsibility of this entry point
        /// to call <see cref="T:Microsoft.WindowsAzure.Mobile.Service.ServiceConfig" /> which will start the configuration of the application.
        /// </summary>
        public void Initialize()
        {
            // Use this class to set configuration options for your mobile service
            ConfigOptions options = new ConfigOptions();

            // Use this class to set WebAPI configuration options
            HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));

            // To display errors in the browser during development, uncomment the following
            // line. Comment it out again when you deploy your service for production use.
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            var migrator = new DbMigrator(new Configuration());
            migrator.Update();
        }
    }

And then we need to change the WebApiApplication, as following

    public class WebApiApplication : System.Web.HttpApplication
    {
        /// <summary>
        /// The _web API configuration
        /// </summary>
        private readonly WebApiConfig _webApiConfig;

        /// <summary>
        /// Initializes a new instance of the <see cref="WebApiApplication"/> class.
        /// </summary>
        public WebApiApplication()
        {
            _webApiConfig = new WebApiConfig();
        }

        /// <summary>
        /// Application_s the start.
        /// </summary>
        protected void Application_Start()
        {
            _webApiConfig.Initialize();
        }
    }

Each developer should be aware when the Initialize method run, each time the application starts, it will create or update the database based in the migrations defined by the current model.

Publishing the services:

Figure 10 publishing the service
Figure 10 publishing the service

Is possible to following the publish process using the “Web Publish Activity”, as we can see in Figure 11

Figure 11  Web Publish Activity
Figure 11 Web Publish Activity

 

Note: When we do the publish the Azure Mobile Service will replace some configuration from WebConfig, if you want to see the final WebConfig see this article.

The browser will be opened, as following:

Figure 12 Azure Mobile Service running
Figure 12 Azure Mobile Service running

And we can request the TodoItems in “try this out”, like we can see in the Figure 13

Figure 13 Try it out
Figure 13 Try it out

Or in the database

Figure 14 Data in database
Figure 14 Data in database

which logs will be

Figure 15 Log
Figure 15 Log

 

Handle errors

 

Changing the model

The backend can change and with it the model can change. If we change the model without create the respective migration we will receive an error like this

“ERROR

Boot strapping failed: executing ‘WebApiConfig’ caused an exception: ‘Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.”

Figure 16 Azure Mobile Service with errors
Figure 16 Azure Mobile Service with errors

Let’s change the model for something as following

 

    public class TodoItem : EntityData
    {
        public string Text { get; set; }

        public string Name { get; set; }

        public bool Complete { get; set; }
    }

After it we need to add a new migration, for it we need to run “Add-Migration SecondMigration” in “Package Manager Console”, as following:

PM> add-migration SecondMigration

Scaffolding migration ‘SecondMigration’.

The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running ‘Add-Migration SecondMigration’ again.

PM>

And the result will be

    public partial class SecondMigration : DbMigration
    {
        public override void Up()
        {
            AddColumn("migrations.TodoItems", "Name", c => c.String());
            DropColumn("migrations.TodoItems", "DueDate");
        }
        
        public override void Down()
        {
            AddColumn("migrations.TodoItems", "DueDate", c => c.DateTime(nullable: false));
            DropColumn("migrations.TodoItems", "Name");
        }
    }

If we change the seed method to

        protected override void Seed(Models.MobileServiceContext context)
        {
            context.TodoItems.AddOrUpdate(
                  p => p.Id,
                  new TodoItem { Id = Guid.NewGuid().ToString(), Text = "Clean the car.", Name = "MyTask"},
                  new TodoItem { Id = Guid.NewGuid().ToString(), Text = "Read a book", Name = "MyHobbies" }
                );
        }

After it we can publish the Azure Mobile Service and the result will be

Figure 16 The data

Figure 16 The data

Developers should be aware that the seed method added new items which has the same “Text” as the first items added but in this case the “Name” is filled. This was a sample from a common issue we can create when populate data during different migrations.

Note: If the connecting string, defined in WebConfig, is not using the correct reference, this process can fail with the following error

PM> add-migration SecondMigration
Unable to generate an explicit migration because the following explicit migrations are pending: [201501162340213_Initial]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
PM>

Deleting the Database

If during the process, we delete the database and then we try to run the services we will get:

Figure
Figure
Figure 16 Logs

This way, the default user, used by the Azure Mobile Service created, do not have permissions to access the master database.

The errors we got with the default user are related with the fact the user only has few permissions for security reasons. Create a database user will avoid this kind of issue.

 

Conclusion

In conclusion, we can conclude that EF CodeFirst Migration is a good way to manage the different changes made in the model and this way any time an Azure Mobile Service is deployed it will create or update the associated database without additional work, with initial data or not.

If we are using the default user to access the database

  • the user cannot access the master to re-create the database
  • the database schema must have the same name as the Azure Mobile Service

If we create a database user to avoid the two last problems, you need to ignore the default connection string (MS_TableConnectionString) and you NEED to create your own connection string (for example: MyTableConnectionString where you need to define all required fields to the database, and should be added the user created to avoid the issues).

 

Personal experience:

I lost so many time with this problem, and at the end I prefer to create and use my own database user to simplify the process, and define my own key to the connection string (which can be defined in configuration panel). In my experience the user changed time to time and it happened to me more than one time. Never found it in documentation….

Source Code

See the source code in Azure Mobile Services Sample.

See Also

MSDN Documentation – Code First Migrations

Azure Mobile Services: How to see the WebConfig file published

Scope

This article has the goal to show how to see the WebConfig file published in Azure Mobile Services.

 Introduction

In Azure Mobile Services is possible to have different environments, for example an application can require the “Dev” and “Prod” environments to allow different versions. To have support to many environments the tips are to use conditional directives and transform files, like is described in the article Azure Mobile Services: How to creating a Dev and Prod environments.

Transform filesFigure 1: Transform Files

In the deployment, based in the build configuration the WebConfig is transformed, like we can see in Figure 2:

PublishingFigure 2: Publishing

The Azure Portal allow to create Azure Mobile Services, monitoring, configure and is possible to see the logs, but for some reason we need to see the WebConfig in server, where is it? In this article we will see how to see it.

Description

Kudu is the engine behind Git deployments in Azure Web Sites, and Azure Mobile Services is not more that an extension of ASP.Net WebApi, this way the deployment used in both is the same.

The Kudu project is available in GitHub in this reference github.com/projectkudu/kudu which wiki has all documentation about it. For each Azure Mobile Service is possible to access its Kudu using something like https://<Azure Mobile Service Base Url>.scm.azure-mobile.net and the Azure Portal credentials.

Let’s use the Menu App Sample, where the Azure Mobile Service is defined in https://mymenuapp.azure-mobile.net/ to access the Kudo page we need to use  https://mymenuapp.scm.azure-mobile.net and we will get something like in Figure 3:

Kudu Main Page
Figure 3:Kudu main page

To see the WebConfig we need to click in “Debug Console” and then we need to choose one of the options, let’s choose “PowerShell” as following:

Selecting PowerShellFigure 4: Selecting PowerShell

The following page will be showed
PowerShell pageFigure 5: PowerShell page

In console do “cd site” and “cd wwwroot” as following in Figure 6:

Navigate to wwwrootFigure 6: Navigate to wwwroot

At the end we will see the follow table

Now is possible to download, edit or delete the WebConfig file, using the options in the left. If we click in edit we will have something like

WebConfig FileFigure 7: WebConfig File

 Conclusion

In conclusion, we can conclude to get the WebConfig in Azure Mobile Service server is very simple and in some cases can be useful, but each developer should be aware the changes made has impact in production.

Azure Mobile Services: How to see the log files in server

Scope

This article has the goal to show how to see the log files from an Azure Mobile Service.

Introduction

In Azure Portal, each Azure Mobile Service has a separator that show all logs registered (Figure 1), and in possible to see the details for each one (Figure2):

The logs

Figure 1: The logs

The log details

Figure 2: The details

This information is very useful and allow to know why the system is down or allow to verify if there is any issue. This page allow to list and see the details for each one, but if we want to export logs, the Azure Portal do not allow it. In this article we will see a solution to get all the log files.

 Description

Kudu is the engine behind Git deployments in Azure Web Sites, and Azure Mobile Services is not more that an extension of ASP.Net WebApi, this way the deployment used in both is the same.

The Kudu project is available in GitHub in this reference github.com/projectkudu/kudu which wiki contains all documentation about it. For each website is possible to access its Kudu using something like https://<Azure Mobile Service Base Url>.scm.azure-mobile.net and the Azure Portal credentials.

Let’s use the Menu App Sample, where the Azure Mobile Service is defined in https://mymenuapp.azure-mobile.net/ to access the Kudo page we need to use https://mymenuapp.scm.azure-mobile.net and we will get
something like in Figure 3:

The Kudu main page
Figure 3: The Kudu main page

To see the log files we need to click in “Debug Console” and then we need to choose one of the options, let’s choose “PowerShell” as following:

Selecting PowerShellFigure 4: Selecting PowerShell

The following page will be showed

Selecting PowerShell
Figure 5: The powershell

Like we can see in the table, we have a LogFiles folder but this contains some logs (logs from Kudu and logs from the application). To see the log, we saw in the Azure Portal, we need to do “cd logfiles” and “cd application” as in the following Figure 6:

Selecting PowerShell
Figure 6: the log file

Using the options in the left we can see the logs and then get it, as following:

Selecting PowerShell
Figure 7: The log file

Conclusion 

In conclusion, we can conclude to get the log files in Azure Mobile Service server is very simple and in some cases can be useful, but each developer should be aware the changes made has impact in the logs separator in the Azure Portal.

Avoid nightmares updating Azure Mobile Services projects

Scope

This article has the goal to show how to update a .Net Backend project from Azure Mobile Services, this mean we will update the references added to the project using Nuget packages.

Introduction

Microsoft Azure Mobile Services is an Azure service offering designed to make it easy to create highly-functional mobile apps using Azure. Mobile Services brings together a set of Azure services that enable backend capabilities for your apps.
When a developer create a .Net Backend project from Azure Mobile Services, it has several Nuget packages installed, for example, if the project is created in Visual Studio 2013 – Update 4, like we can see in the Image 1

Creating the Azure Mobile Service

Image 1 Creating the Azure Mobile Service

The default package files will something like as following:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Autofac" version="3.5.2" targetFramework="net45" />
  <package id="AutoMapper" version="3.2.1" targetFramework="net45" />
  <package id="EntityFramework" version="6.1.1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Cors" version="5.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.Identity.Core" version="2.0.1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Identity.Owin" version="2.0.1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Razor" version="3.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Cors" version="5.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.OData" version="5.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Owin" version="5.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Tracing" version="5.2.2" targetFramework="net45" />
  <package id="Microsoft.Data.Edm" version="5.6.2" targetFramework="net45" />
  <package id="Microsoft.Data.OData" version="5.6.2" targetFramework="net45" />
  <package id="Microsoft.Owin" version="3.0.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.ActiveDirectory" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Cookies" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Facebook" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Google" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Jwt" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.MicrosoftAccount" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.OAuth" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Twitter" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.WindowsAzure.ConfigurationManager" version="2.0.3" targetFramework="net45" />
  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net45" />
  <package id="Owin" version="1.0" targetFramework="net45" />
  <package id="RazorEngine" version="3.4.1" targetFramework="net45" />
  <package id="System.IdentityModel.Tokens.Jwt" version="3.0.2" targetFramework="net45" />
  <package id="System.Spatial" version="5.6.2" targetFramework="net45" />
  <package id="WindowsAzure.MobileServices.Backend" version="1.0.405" targetFramework="net45" />
  <package id="WindowsAzure.MobileServices.Backend.Entity" version="1.0.405" targetFramework="net45" />
  <package id="WindowsAzure.MobileServices.Backend.Tables" version="1.0.405" targetFramework="net45" />
  <package id="WindowsAzure.ServiceBus" version="2.3.4.0" targetFramework="net45" />
</packages>

 

But if we “Manage Nuget Packages” and select “Updates”, the windows will show that there are updates that we can do, like we can see in the Image 2

Manage Nuget Packages - Available updates

Image 2 Manage Nuget Packages – Available Updates

First thing we can try to do is to click in the “Update All” button, that will make sense for the developers, but then we will get something as we can see in the Image 3

Error updating all
Image 3 Error updating all

And is here the nightmares about updating the Nuget packages from Azure Mobile Services start, because, like we can see in the package file, we have 36 Nuget packages installed in the project and is not so easy to understand the dependencies between the different Nuget packages and if we start updating one by one we will get errors as following in the Image 4, with this is not possible to update one by one, but the main Nuget packages and in this article we will see how to avoid this problem.

Azure Mobile Service with errors

Image 4 Azure Mobile Service with errors

It means the reference added to the project is not the same version used by any Nuget and can be hard to understand which is right version.

Description

To understand the Nuget packages and because our project is an Azure Mobile Service project, we can start by analyzing the packages

In the Nuget website we found

• Microsoft Azure Mobile Services .NET Backend 1.0.405

Has the dependencies

• Microsoft Azure Mobile Services .NET Backend Tables 1.0.405

Has the dependencies

• Microsoft Azure Mobile Services .NET Backend Entity Framework Extension 1.0.405

Has the dependencies

This way, we can conclude the Microsoft Azure Mobile Services .NET Backend Entity Framework Extension 1.0.405 Nuget depends on the WindowsAzure.MobileServices.Backend.Tables Nuget and this depend on the WindowsAzure.MobileServices.Backend Nuget. This mean if we update the Microsoft Azure Mobile Services .NET Backend Entity Framework Extension Nuget the references related with Azure Mobile Service will be updated.

In the “Manage Nuget Package” click in update the Microsoft Azure Mobile Services .NET Backend Entity Framework Extension Nuget, as we can see in the Image 5:

Udpdating Nuget
Image 5 Updating Nuget

And then, click “I Accept”

License

Image 6 License

At the end, we will get

Nuget packages updated

Image 7 Nuget packages updated

With this another question can be raised, “Did we update all Nuget packages we can?” and this question can be find by uninstall the Microsoft Azure Mobile Services .NET Backend Entity Framework Extension Nuget, as in the Image 8

Uninstall Nuget
Image 8 Uninstall Nuget

Uninstall this Nuget will request a confirmation to uninstall all dependencies, as in the Image 9, where we will click in “Yes”.

Nuget packages to remove
Image 9 Nuget packages to remove

The result will beThe service running in localhostImage 10 The service running in localhost

And the package file updated to:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Autofac" version="3.5.2" targetFramework="net45" />
  <package id="AutoMapper" version="3.2.1" targetFramework="net45" />
  <package id="EntityFramework" version="6.1.1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Cors" version="5.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.Identity.Core" version="2.0.1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Identity.Owin" version="2.0.1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Razor" version="3.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Cors" version="5.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.OData" version="5.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Owin" version="5.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Tracing" version="5.2.2" targetFramework="net45" />
  <package id="Microsoft.Data.Edm" version="5.6.2" targetFramework="net45" />
  <package id="Microsoft.Data.OData" version="5.6.2" targetFramework="net45" />
  <package id="Microsoft.Owin" version="3.0.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.ActiveDirectory" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Cookies" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Facebook" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Google" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Jwt" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.MicrosoftAccount" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.OAuth" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Twitter" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.WindowsAzure.ConfigurationManager" version="2.0.3" targetFramework="net45" />
  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net45" />
  <package id="Owin" version="1.0" targetFramework="net45" />
  <package id="RazorEngine" version="3.4.1" targetFramework="net45" />
  <package id="System.IdentityModel.Tokens.Jwt" version="3.0.2" targetFramework="net45" />
  <package id="System.Spatial" version="5.6.2" targetFramework="net45" />
  <package id="WindowsAzure.MobileServices.Backend" version="1.0.447" targetFramework="net45" />
  <package id="WindowsAzure.MobileServices.Backend.Entity" version="1.0.447" targetFramework="net45" />
  <package id="WindowsAzure.MobileServices.Backend.Tables" version="1.0.447" targetFramework="net45" />
  <package id="WindowsAzure.ServiceBus" version="2.3.4.0" targetFramework="net45" />
</packages>

Returning back to the “Updates”, we will see the Nuget packages, in the Image 11 that we can update, but for the reasons we saw, it is not possible to update all.

Manage Nuget Packages
Image 11 Manage Nuget Packages

Conclusion

In conclusion, each developer should be aware about the dependencies between Nuget packages and more than one package can depend from the same Nuget package but for different versions, this mean is required to keep the versions used by each one.

Azure Mobile Services: How to creating a Dev and Prod environments

Scope

This article has the goal to show how to create a development and production environment for a .Net Backend from Azure Mobile Services.

Introduction

According the MSDN Documentation,

Microsoft Azure Mobile Services is an Azure service offering designed to make it easy to create highly-functional mobile apps using Azure. Mobile Services brings together a set of Azure services that enable backend capabilities for your apps. Mobile Services provides the following backend capabilities in Azure to support your apps:

  • Client libraries support mobile app development on various devices, including Windows 8, Windows Phone 8, iPhone, and iPad.
  • Simple provisioning and management of tables for storing app data. 
  • Integration with notification services to deliver push notifications to your app.
  • Integration with well-known identity providers for authentication.
  • Precise control for authorizing access to tables.
  • Supports scripts to inject business logic into data access operations.
  • Integration with other cloud services.
  • Supports the ability to scale a mobile service instance.
  • Service monitoring and logging.

This way, Azure Mobile Services will increase the mobile application development and the fact it is available for the main mobile platform is a plus.

In some scenarios, more specific while new features are provided to the mobile applications that is published in the store and used by users, different environment from the Azure Mobile Service can be required, because each version can change or even break the last backend version from Azure Mobile Service and is important to test and keep the production running. Azure Mobile Services allow to test the services in localhost, but not provides a way to have different environments and to create different environments is required to have one Azure Mobile Service for each environment and then create configuration for each one.

Description

To create a development and production environment for a .Net Backend – Azure Mobile Services is required to create a Dev and Prod Backend and then is possible to create the Dev and Prod profiles based in transform files.

Let’s see it in more detail.

Creating the Azure Mobile Services

In Azure Portal, create two .Net Backend – Azure Mobile Service, let’s calling it as following

  • For the development environment:
    • MyAMSDev – the Azure Mobile Service name
    • MyAMSDev_db – the database name
  • For the production environment:
    • MyAMSProd – the Azure Mobile Service name
    • MyAMSProd_db – the database name

In Azure Portal, the result will be azure portal

And

azure portal

Is possible to use the same database, but for it is necessary to use different schemas and if different databases are provided is easier for manage each environment (update or even delete). A Backend that uses Entity Framework migrations will recreate the service from the scrats and with it any time it can be delete, deployed and recreated.

To read more about the steps required to create an Azure Mobile Service, read the following article

How to create the MyMenuApp Azure Mobile Service.

Creating Transform File

In Visual Studio, select the solution and open the context menu as following

azure mobile service

After it, click in Configuration Manager as following

azure mobile service

And then create a new configuration as following

azure mobile service

azure mobile service

In this case, a Dev configuration is defined based in Debug configuration and to the Prod configuration should be used the Release configuration as following

azure mobile service

At this moment, is possible to define Debug, Dev, Prod and Release configuration

azure mobile service

For each configuration is possible to define the conditional compilation. For example, in Dev is possible to have

azure mobile service

In reality it mean, we can do

#if Dev

// for example can fill the database with fake data

#else

// in other environment different from Dev

#endif

To have advantages of this configurations using the Web.Config, let’s add the config transform as following

azure mobile service

Which the result will be

azure mobile service

Now is possible

– To set in the Web.Config, the connection string to the local database, used by the localhost

 <connectionStrings>
    <add name="MS_TableConnectionString1" connectionString="Data Source=LT114925;Initial Catalog=MyAMSLocal;Integrated Security=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" />
   </connectionStrings>

– To set in the Web.Dev.Config, the connection string to the MyAMSDev_db database, used by the Dev environment (or even the localhost!)

      xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>

– To set in the Web.Prod.Config, the connection string to the MyAMSProd_db database, used by the Prod environment

   <connectionStrings>
      <add name="MS_TableConnectionString1"
        connectionString="<connection string from MyAMSProd_db>"
        xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
    </connectionStrings>

And in each deploy the respective configs will be used.

Let’s publish the service to the Azure.

Select the project and using the context menu click in Publish, as following

azure mobile service

Then connect to Azure Mobile Service, using the Azure Account, and select the MyAMSDev as following

azure mobile service

In Settings, set the configuration and the file publish options (only!)

azure mobile service

And then publish it!

Do the same process to Prod, as following

azure mobile service

And then publish it!

Is possible to see the Web Publish Activity that show the publish process

azure mobile service

At this moment, both environment are deployed and running and is not required to define or change each environment in future, only is needed to have attention each one is set before deploy.

Notes

    1. In this case was use the MS_TableConnectionString1 name for define the connection string and the default value MS_TableConnectionString, defined in Azure Portal, will be ignored.

    A developer can to set different connect string or even change the name, but needs to be defined with the same name in all environments.

    1. With the Visual Studio 2013 – update 4 is possible to change the database in Settings separator but in this case it will be ignored!

For more information about the transform file, read the following article

How to: Transform Web.config When Deploying a Web Application Project

Conclusion

In conclusion, creating different environments for a .Net Backend – Azure Mobile Service is an easy task that is a plus in the development, which allow to test new features before it go to production and it allow to make sure the tests done in localhost will keep working in the Azure Mobile Service without to affect the production environment.

 

Resources for client apps that uses the Azure Mobile Services

In the last months, I have been working with Azure Mobile Services, where my focus was  create .Net BackEnd for IOS and Android Developers. For different reason I searched for the right article for each subject or problem and saved it as a curation for share and use later.

Here are the resources focused in each platform

  • Azure Mobile Service for client apps – IOS Developers (Native)
  • Azure Mobile Service for client apps – Android Developers (Native)
  • Azure Mobile Service for client apps – Xamarin Developers
  • Azure Mobile Service for client apps – Windows Developers

Note: in some cases is need to select if we want a .Net or a JS BackEnd.

and is possible to use the start point Azure Mobile Services for Client Apps which contains all references defined above.

 

Enjoy it! 🙂

 

How to integrate Cortana in the Menu App

Scope

This article aims to integrate Cortana in the Menu App.

Introduction

One of the interesting feature in Windows Phone 8.1 is Cortana. Cortana is an intelligent personal assistant, which will help users in basic tasks, like call to a friend, schedule an appointment and others tasks…

Cortana is not available in all languages, for this reason some non-English users changed their devices for support it. For see more about how to have Cortana in our Windows Phone 8.1 devices see the following article.

Integrating Cortana

Cortana will use Voice Commands for interact with the apps, these voice commands are pre-installed in the apps for Cortana knows how to launch each app.

The first step for integrate Cortana, in Menu App, is to define the Voice Command Definition (VCD) file, that represent an xml file with the commands that Cortana will recognize and will match with the app.

For Menu App we will define “Menu” as the name for talk with the Menu App and will define two commands:

  • Show Command – that will allow to choose which menu we want to see: Beverages, Starters, Mains, Desserts and Special Offers;
  • Natural Language Command – that will allow to recognize expression like “I am hungry”, “I want to eat” and “I want to drink”.

In this sample, the VCD is defined for English (en-US) but could be added more languages.

 

The VCD file

 

Here are the VCD file:

<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->xml version="1.0" encoding="utf-8"?&gt;
 
<!-- Be sure to use the new v1.1 namespace to utilize the new PhraseTopic feature -->

    <!-- The CommandSet Name is used to programmatically access the CommandSet -->
    
        <!-- The CommandPrefix provides an alternative to your full app name for invocation -->
        Menu
        <!-- The CommandSet Example appears in the global help alongside your app name -->
         I am hungry 
 
        <command></command>
           Show Mains 
           Show {dictatedShowTerms} 
           Showing in Menu ... 
          
        
      
        <command></command>
             I want to eat 
             {naturalLanguage} 
             Starting Menu ... 
            
        
 
     
        
           Starters 
           Mains 
           Desserts 
           Beverages 
           Special Offers 
         
 
        
             I want to eat 
             I want to drink 
             I am hungry 
         
    

Note: In manifest file, should be check the capability for Microphone.

 

The InstallVoiceCommandsAsync method

Now we defined the commands, we need to install it in the app each time the app starts.

Create the method

private async Task InstallVoiceCommandsAsync()
{
          var storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Cortana.xml"));
          await VoiceCommandManager.InstallCommandSetsFromStorageFileAsync(storageFile);
}

And then call it in the OnNavigationTo from the MainPage:

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
         _dataTransferManager = DataTransferManager.GetForCurrentView();
         _dataTransferManager.DataRequested += OnDataRequested;
         _navigationHelper.OnNavigatedTo(e);
         await MainViewModel.LoadDataAsync();
         if (e.NavigationMode == NavigationMode.New)
         {
             await InstallVoiceCommandsAsync();
         }
}

 

The OnActivated method

 

After it, we need to define what the app will do each time it receive a voice command from Cortana. Cortana when recognize a command for the Menu App will send the data to the Menu App, and the OnActivated method in App.xaml.cs will be called.

Here are the complete code for OnActivated method:

protected override void OnActivated(IActivatedEventArgs args)
       {
           base.OnActivated(args);
         
           if (args.Kind == ActivationKind.VoiceCommand)
           {
               var commandArgs = args as VoiceCommandActivatedEventArgs;
               if (commandArgs != null)
               {
                   SpeechRecognitionResult speechRecognitionResult = commandArgs.Result;
 
                   var voiceCommandName = speechRecognitionResult.RulePath[0];
                   var textSpoken = speechRecognitionResult.Text;
                   
                   switch (voiceCommandName)
                   {
                       case "ShowCommand":
                           if (textSpoken.ToLower().Contains("starters"))
                           {
                               RootFrame.Navigate(typeof (StartersPage));
                           }
                           if (textSpoken.ToLower().Contains("mains"))
                           {
                               RootFrame.Navigate(typeof(Main1Page));
                           }
                           if (textSpoken.ToLower().Contains("desserts"))
                           {
                               RootFrame.Navigate(typeof(DessertsPage));
                           }
                           if (textSpoken.ToLower().Contains("beverages"))
                           {
                               RootFrame.Navigate(typeof(BeveragesPage));
                           }
                           if (textSpoken.ToLower().Contains("special") || 
                               textSpoken.ToLower().Contains("offer"))
                           {
                               RootFrame.Navigate(typeof(MainPage), "SpecialOffers");
                           }
                           break;
                       case "NaturalLanguageCommand":
                           if (textSpoken.ToLower().Contains("eat") ||
                               textSpoken.ToLower().Contains("hungry"))
                           {
                               RootFrame.Navigate(typeof(Main1Page));
                           }
 
                           if (textSpoken.ToLower().Contains("drink"))
                           {
                                RootFrame.Navigate(typeof (BeveragesPage));
                           }
                           if (textSpoken.ToLower().Contains("special"))
                           {
                               RootFrame.Navigate(typeof (MainPage), "SpecialOffers");
                           }
                           break;
                   }
               }
           }
           Window.Current.Activate();
       }

Each possible voice command defined in VCD must be handled for the results showed to the user don´t be weird.

 

Using Cortana

Before we talk with Cortana, we need to run the Menu App in the device, because we need to install the VCD. After it, we can start Cortana


And the click in “see more”, for see what we can say


 

Each app will show some examples to help users using Cortana. Clicking the Menu App it will show the samples defined In the VCD file:


 

Playing with Cortana, we will see the following:

Saying “Menu I am hungry”




 

And then


Saying “Menu I want to drink”

 



 


Saying “Menu Show offers”



 


Code

See the code for this sample in

Step 9: How to integrate Cortana with Menu App

 

See also