Sunday, April 26, 2009

URL Builder Functions

I am working on an internal web application that does some state management through the query string. That being the case, I have to add, remove and change paramters in the query string. Here are the functions that I use to edit the URL to change these varables

// Takes a URL with parameters and replaces the current value of a given parameter 
// with the new value provided
public static string replaceParameterInUrl(string theUrl, string param, string newValue)
{
    StringBuilder sb = new StringBuilder();
    string[] parts = theUrl.Split(new char[] { '?', '&' });
    sb.Append(parts[0]).Append("?");
    for (int i = 1; i < parts.Length; ++i)
    {
         string thisParam = parts[i];
         string[] paramParts = thisParam.Split(new char[] { '=' });
         if (paramParts[0] != param)
             sb.Append(thisParam).Append("&");
    }
    sb.Append(param).Append("=").Append(newValue);
    return sb.ToString();
}
/// Takes a URL with parameters and replaces the current value of a given parameter 
/// with the new value provided
public static string removeParameterFromUrl(string theUrl, string param)
{
    StringBuilder sb = new StringBuilder();
    bool isFirstItem = true;
    string[] parts = theUrl.Split(new char[] { '?', '&' });
    sb.Append(parts[0]).Append("?");
    for (int i = 1; i < parts.Length; ++i)
    {
        string thisParam = parts[i];
        string[] paramParts = thisParam.Split(new char[] { '=' });
        if (paramParts[0] != param)
        {
            if (!isFirstItem)
                sb.Append("&");
            sb.Append(thisParam);
            isFirstItem = false;
        }
   }
   return sb.ToString();
}

If I was going to use these functions in a public facing site,I'd probably sort the parameters alphabetically, so there would be less flux in the URLs that Google would see

No comments: