Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the application ConnectionString in the Service Configuration instead of web.config in Azure

I have an application currently in Azure and whenever we push it into the Staging segment, we cannot truly test since the connection string is pointing to the prod database.

Someone mentioned to me that you should be able to set the connection string in the ServiceConfiguration.cscfg file instead (or with) the web.config file. That way you can change the connection string in the Azure portal instead of republishing a who app.

Does anyone know how to do this?

like image 347
Andy Avatar asked May 12 '11 14:05

Andy


1 Answers

In your ServiceConfiguration.cscfg file add:

<ServiceConfiguration ... />
  <Role ... />
    <ConfigurationSettings>
      <Setting name="DatabaseConnectionString" value="put your connection string here" />
    </ConfigurationSettings>
  </Role>
</ServiceConfiguration>

Now you have a connection string you can change by editing the configuration inside the azure portal.

Then anytime you need to retrieve the connection string you can do it using:

using Microsoft.WindowsAzure.ServiceRuntime;

...

String connString = RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString")

You may need to add Microsoft.WindowsAzure.ServiceRuntime.dll to your references.

RoleEnviroment.IsAvailable can be used to test if your are running in Azure, and if not to fall back to your web.config settings.

using System.Configuration;
using Microsoft.WindowsAzure.ServiceRuntime;

...

if (RoleEnvironment.IsAvailable)
{
    return RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString");
}
else
{
    return ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString; 
}

This article has a more verbose explanation of the above.

like image 55
David Steele Avatar answered Oct 12 '22 10:10

David Steele