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
{
  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:


  

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


    

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).

Leave a Reply

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