views:

57

answers:

2

I have a site that leverages both Google Analytics and Google Maps. Both of these services have API keys that need to be managed in our site's code. For Google Analytics, we have two accounts, a live account and staging account to test tracking prior to lunch. For Google Maps we actually need a unique API key for every single host name. We have several staging domains and local hostnames so our maps code has quite a bit of toggling for API keys.

Right now I am managing my keys in a C# code-behind for the respective pages using a switch on the Request.Url.Host:

// for analytics in file1
switch (Request.Url.Host) {
  case "staging": ltlUACode.Text = "stageKey"; break;
  case "client.stage.com": ltlUACode.Text = "stageKey"; break;
  case "www.livesite.com": ltlUACode.Text = "liveKey"; break;
  case "livesite.com": ltlUACode.Text = "liveKey"; break;
}

// for maps in file2
switch(Request.Url.Host) {
  case "staging": GoogleMapsKey = "uniqueKey1"; break;
  case "client.stage.com": GoogleMapsKey = "uniqueKey2"; break;
  case "www.livesite.com": GoogleMapsKey = "uniqueKey3"; break;
  // etc
}

I'd like to know what would a better method be to keep track of all of these keys. I considered two possible things that could work:

  1. Using app settings in my web.config: one issue here though is that the maps keys change often based on the hostnames (i.e. the many variants for the maps key would be a nightmare to manage)
  2. Having a C# class to handle all of these keys based on the hostname: I could write a static class that has properties for the analytics key and the maps key and based on the Request.Url.Host I could set the properties to their appropriate values. This method is essentially my switch method wrapped up into a helper class.
A: 

Do Both:

Since they're not really code, store the Domain => ApiKey pairs in the web config. For large blocks of similar web.config settings, it's helpful to create custom sections and handlers. The bonus of the extra work here is that you can extend the functionality of the custom section handlers to return the correct values based on the environment, too.

Create one custom section type, then add one section (of that type) for each api key (maps, analytics, etc).

grossvogel
A: 

I usually split them up in to their own files and then deploy different config files based on their location.

web.config

   <appSettings configSource="Host1.config">
        </appSettings>

c#

System.Configuration.ConfigurationManager.AppSettings(fieldname)
Glennular
Part of the problem with this approach is that the same IIS website has multiple host bindings so the same code is rendering the same site on different URLs. That's exactly why I cannot do it that way...
Mark Ursino