Using AppSettings in AppHarbor to keep connection strings out of your git repository

When you generate a new entity framework project in C#, it generates an Application context object, which is very insistent on reading it’s connection from the connection strings settings of the web.config:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
  public ApplicationDbContext()
    : base("DefaultConnection", throwIfV1Schema: false)
  {
  }
 
  public static ApplicationDbContext Create()
  {
    return new ApplicationDbContext();
  }
}

Ideally you don’t want to check in the connection string. If you’re using AppHarbor, their UI helpfully lets you add AppSettings, but it takes some juggling to get these into the app context.

You still need to have a connection string, but you can leave it blank:

<connectionStrings>
  <add name="DefaultConnection" 
      connectionString="" 
      providerName="System.Data.SqlClient" />
</connectionStrings>

For testing purposes, you should also add your own AppSetting by adding this to the web.config:

<appSettings>
    <add 
      key="db_connection_string" 
      value="<my connection string>"/>
</appSettings>

Then, modify the Application_Start to read the appSetting and hack it into the connection string:

protected void Application_Start()
{
  var connections =
    ConfigurationManager.ConnectionStrings;
 
  ConnectionStringSettings 
    defaultConnection = null;
 
  foreach (ConnectionStringSettings c in connections) 
  {
    if ("DefaultConnection".Equals(c.Name))
    {
      defaultConnection = c;
    }
  }
 
  var fi = 
    typeof(ConfigurationElement)
      .GetField("_bReadOnly", 
          BindingFlags.Instance | 
          BindingFlags.NonPublic);
 
      fi.SetValue(defaultConnection, false);
 
  defaultConnection.ConnectionString = 
    ConfigurationManager.AppSettings["db_connection_string"];
}

Credit for this technique goes to David Gardiner (VB example available there too if you need it for some reason).

Want to learn something new? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *