Mobile Services .NET Backend adding extra connection strings

17/05/2014

In my first two posts about the Mobile Services .NET backend, I didn’t talk about the publishing process to Microsoft Azure, because I thought there was nothing to talk about.

It turns out that I missed a very important thing, which is how to add new connection strings to your project. You might need an extra connection string, other than the default SQL connection string that the template project comes with, if you want to use Azure Table Storage instead of SQL. If you are testing it locally it’s easy to add the connection string, as you can just modify the web.config, but this modification is not published to Azure. In Azure you typically for a Azure Website which Mobile Services is just a special case of have to define the connection string in the portal. You do this on the configuration tab, but for some reason the Mobile Service team decided to remove the option from this page to configure you connection strings and instead add a database settings that only supports a SQL database connection string.
mobileservice_configuration

If you want, then you can check the exact connection string from the Kudu interface by browsing to your site on https://.scm.azure-mobile.net you can also see all environment variables for your site here, but you can’t change anything.

The solution I found to add an additional connection string was to add it in code, and read the value from an app setting because those you can add as many as you want of in the portal.
Here is how my WebApiConfig.cs looks after adding an extra connection string called “AzureTable” and reading the value for it from an app setting also called “AzureTable”.
[csharp]
using System.Configuration;
using System.Web.Http;
using Microsoft.WindowsAzure.Mobile.Service;

namespace MobileService1
{
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;
var constring = ConfigurationManager.AppSettings["AzureTable"];

new ApiServices(config).Settings.Connections.Add("AzureTable", new ConnectionSettings("AzureTable", constring));
}
}
}
[/csharp]

With this change in place, my solution from the first two post now also work when hosted in Azure. You can use the help pages when hosted in Azure as you did locally by using one of your access keys as password (username should be empty) when prompted for login.