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

Other Interesting Posts

 

Leave a Reply

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

*


6 + = 13

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>