Wednesday, November 30, 2005

Trying to re-start this once more

Okay,

So after many false starts, I am trying to get my techology blog rolling again. Please bear with me as a port over my existing blog entries. I hope to actually get some Relevant posts up here soon.

Wednesday, September 21, 2005

How to handle server-specific configuration settings in C#.Net

One of the biggest hassles I've ever had with deployment so far has been trying to ensure that I preserve the correct global variables for my application when I deploy my code from development to staging to production. The primary example being connection strings to the database.

In doing some research, I discovered that .Net allows you to create customized sections in your web.config, and then I came across this article on ToDotNet -http://todotnet.com/archive/2005/06/03/478.aspx.

The article explained how to create a custom XML handler and have it look at the URL to pick the correct connection strings.

Although it was written in VB.Net, it was very easy to port into C#, and I also added two small enhancements:

  • I added the ability to add a default section, just in case the server name doesn't match one of the other defined sections.
  • I also had it include the name of the selected configuration, so that you can export it for debugging purposes - i.e. in case you are not sure which configuration is selected.


Below is my C# code. If you want to implement the full solution, look at the above article:


using System;
using System.Web;
using System.Xml;
using System.Configuration;
using System.Collections;

namespace ujci_v3
{
///
/// Summary description for ConfigHandler.
///

public class ConfigHandler:Hashtable,IConfigurationSectionHandler
{
///
/// For now, an empty constructor
///

public ConfigHandler()
{

}
///
/// This implements the Create interface of IConfigurationSectionHandler,
/// needed to be able to retreive the config info
/// from web.config
///

///
///
///
///
public object Create(object parent,object configContext,XmlNode section)
{
try
{
//Get the host name
string server=HttpContext.Current.Request.Url.Host;
XmlNodeList NodeSettings;

//Find the configuration for this hostname
NodeSettings=section.SelectNodes("configuration[contains(@url,'"+server+"')]/add");

//If no config is found, use the default.
//Also, add the 'Config' key to tell us which configuration is being used.
if(NodeSettings.Count==0)
{
NodeSettings=section.SelectNodes("configuration[contains(@url,'default')]/add");
this.Add("Config","default");
}
else
{
this.Add("Config",server);
}
foreach(XmlNode n in NodeSettings)
{
this.Add(n.Attributes.GetNamedItem("key").Value,n.Attributes.GetNamedItem("value").Value);
}
}
catch(Exception ex)
{
//If any error ocurrs, add the error message as part of the config, to help us debug.
this.Add("Error",ex.Message);
}
return this;
}
}
}

Thursday, August 11, 2005

Views vs. Stored Procedures

Wow - I got to do these more often! I recently hired a new programmer, and we were having a discussion regarding the best way to handle complex queries involving lots of joins. Obviously, running one of those complex queries ad-hoc (even if it is somewhat optimized) will put a strain against your server. In certain situations, it definitely makes sense to use a 'pre-compiled' version of this query - but the question is, what kind?

You could create a stored proc that, when executed, returned the appropriate result set, or you could create a view that would allow you to query the joined tables as if they were actually one big happy table. While different schools of thought have evolved around this subject, I generally use the following rules of thumb to determine when it is appropriate to use either a Stored Proc or a View:

Use a stored proc if:

  • You need to obscure specific details of the query from the querier
  • You need to perform advanced logic or calculations against the data before returning it (beyond basic aggregation).
  • You will only be using the data in one or two specific places and will not need to further filter, sort, or modify it.




Use a view if:
  • You need the ability to further modify or manipulate the data - by specifying sorting or aggregates.
  • You will be using this in enough places that maintaining a stored proc will be cumbersome to customize and maintain for each place.
  • You want to select the specific output columns to be passed back to your application
  • You need to join the results of the data to another table or tables.

.Net Tip - Caching and Data Updates

Wow, it's been a while! I promise to update more frequently. To make up for not posting for a while here is a very useful caching tip that I use on my own sites.

We all have user controls that appear on every page (a perfect example of this - a header control or a navigation control). User controls can very easily be cached using the OutputCache directive:

<%@ OutputCache duration="3600"%>


By embedding the above tag into a user control, it will be cached for an hour. But what if the data it displays changes during the course of the hour? How do I ensure that the data will be updated in a timely manner? The simple solution is in the VaryByCustom attribute of the tag.

VaryByCustom calls a special function called GetVaryByCustomString and passes it the value you specify for the VaryByCustom attribute in the OutputCache tag. Essentially you write the code to determine what value gets returned. With each subsequent request for the cached object, the ASP.Net engine first checks the result GetVaryByCustomString function. If the result has changed - regardless of the duration on the Cache, the system will bypass the cache and execute the code in the control.

Therefore, it is very easy to set up, say, an application variable that gets changed only when the data gets changed, then use the GetVaryByCustomString function to check for updates.

So your OutputCache line will now look like this:


<%@ OutputCache duration="3600" VaryByCustom="updateCheck"%>


Then make the following changes to your Global.asax:
  1. Add the following line to your Application_Start method:

    Application["lastUpate"]=DateTime.Now.ToString();

  2. Add the following code as the function GetVaryByCustomString:

    public override string GetVaryByCustomString(HttpContext context,string arg)
    {
    if(arg=="serial")
    {
    return Application["serial"].ToString();
    }
    //We need to return an empty string so that this compiles
    return "";
    }


Now you are almost done. All you still need to do to ensure that your cached pages are updated when data changes is to make the following call:

Application["lastUpate"]=DateTime.Now.ToString();


This will update the application variable, and change the result of the GetVaryByCustomString function, which will force the Cache to update.

Wednesday, May 25, 2005

My server has a usb port on the front, should I be worried?

Recently at work we got a handful of new servers. In addition to all of the standard bells and whistles, and expected improvements in processing power, capacity and speed, these servers also had another new feature on their front panel - a USB port.

The intent of course is so that those Sys admins who carry around configuration files and other utils on usb keychain drives will be able to easily plug those drives in to update these servers.

Convenient as it might be, it really scares the crap out of me. Think for a minute about the following scenarios:

1. Someone plugs in a bootable usb drive and then hard-cycles the machine and manages to put a virus, spyware or other malware on the machine.

2. Someone plugs in a USB wireless adapter, and then has an accomplice connect to the server via wi-fi to steal information or put trojans on the machine

3. Someone walks in, plugs their digital music player into the server, downloads oodles of sensitive data, and then walks out, completely unsuspected.

While these might sound a bit far-fetched, but in reality why couldn't a saavy janitor pull something like this off?