How To Isolate Code To Run only on Certain Servers
Occasionally with websites, the need arises to have a block of code that executes only on a particular set of servers–whether local development servers, or client servers, or production servers. In particular, you may find this useful if you have code you want to run only on development servers. How, then, can you accomplish this?
One simple yet elegant solution is to make a class which provides the information you need. Observe the following class:
public sealed class HostSafety
{
private static string[] safeHosts = {
"192.168.0.1",
"192.168.0.2",
"localhost"
// etc.
};
}
Notice HostSafety is sealed–everything in it is static, so there’s no overhead in terms of extra data stored, and you don’t need to create instances to use it.
Then, simply add a function to check if the current host is safe:
public static bool IsCurrentHostSafe()
{
string userHost = HttpContext.Current.Request.Url.Host;
foreach (string curHost in HostSafety.safeHosts)
{
if (curHost == userHost)
{
return true;
}
}
return false;
}
That’s it! All you need to do is wrap your safe-host code in an if(…) function call!
public void someMethod() {
// Do some stuff ...
// Do more stuff ...
// ...
// Read from a developer-only file
if (HostSafety.IsCurrentHostSafe()) {
StreamReader debugFileReader = ...
// etc.
}
}
…and voila, you have your host-safe code!
By Ashiq Alibhai
Related Reading:
Other Interesting Posts
-
Articles
- January 2011
- April 2010
- March 2010
- February 2010
- January 2010
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- February 2009
- December 2008
- November 2008
- October 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
-
Meta







