im in ur web, enriching ur code

 
 

December 2007 Entries

ShortGuid - A shorter and url friendly GUID class in C#

I like Mads Kristensen, he's often coming up with useful code snippets which he shares with the community AND he heads up the BlogEngine.NET project. He's produced the GuidEncoder helper class, which takes a standard guid like this:

c9a646d3-9c61-4cb7-bfcd-ee2522c8f633

And shortens it to a smaller string like this:

00amyWGct0y_ze4lIsj2Mw

Which is a huge help if you happen to be using guids in your URL's. You can read his article, A shorter and URL friendly GUID, on his website.

I've gone one step further than Mads, and created a struct which encapsulates the GuidEncoder functionality. I've called mine the "ShortGuid", but you could equally call it a "Sguid" if you like how that sounds (and if you pronounce GUID like "squid" and not "goo-id"). Mads's code for en/decoding the guid is still in there as static methods, which you can see further down - I'm pretty sure it hasn't been changed.

I'll jump right into the usage, if you're interested in the code, jump to the bottom and download the source.

Using the ShortGuid

The ShortGuid is compatible with normal Guid's and other ShortGuid strings. Let's see an example:

Guid guid = Guid.NewGuid();

ShortGuid sguid1 = guid; // implicitly cast the guid as a shortguid

Console.WriteLine( sguid1 );

Console.WriteLine( sguid1.Guid );

This produces a new guid, uses that guid to create a ShortGuid, and displays the two equivalent values in the console. Results would be something along the lines of:

FEx1sZbSD0ugmgMAF_RGHw
b1754c14-d296-4b0f-a09a-030017f4461f

Or you can implicitly cast a string to a ShortGuid as well.

string code = "Xy0MVKupFES9NpmZ9TiHcw";

ShortGuid sguid2 = code; // implicitly cast the string as a shortguid

Console.WriteLine( sguid2 );

Console.WriteLine( sguid2.Guid );

Which produces the following:

Xy0MVKupFES9NpmZ9TiHcw
540c2d5f-a9ab-4414-bd36-9999f5388773

Flexible with your other data types

The ShortGuid is made to be easily used with the different types, so you can simplify your code. Take note of the following examples:

// for a new ShortGuid, just like Guid.NewGuid()

ShortGuid sguid = ShortGuid.NewGuid();

 

// to cast the string "myString" as a ShortGuid,

string myString = "Xy0MVKupFES9NpmZ9TiHcw";

 

// the following 3 lines are equivilent

ShortGuid sguid = new ShortGuid( myString ); // traditional

ShortGuid sguid = (ShortGuid)myString; // explicit cast

ShortGuid sguid = myString; // implicit cast

 

// Likewise, to cast the Guid "myGuid" as a ShortGuid

Guid myGuid = new Guid( "540c2d5f-a9ab-4414-bd36-9999f5388773" );

 

// the following 3 lines are equivilent

ShortGuid sguid = new ShortGuid( myGuid ); // traditional

ShortGuid sguid = (ShortGuid)myGuid; // explicit cast

ShortGuid sguid = myGuid; // implicit cast

After you've created your ShortGuid's the 3 members of most interest are the original Guid value, the new short string (the short encoded guid string), and the ToString() method, which also returns the short encoded guid string.

sguid.Guid; // gets the Guid part

sguid.Value; // gets the encoded Guid as a string

sguid.ToString(); // same as sguid.Value

Easy comparison with guid's and strings

You can also do equals comparison against the three types, Guid, string and ShortGuid like in the following example:

Guid myGuid = new Guid( "540c2d5f-a9ab-4414-bd36-9999f5388773" );

ShortGuid sguid = (ShortGuid)"Xy0MVKupFES9NpmZ9TiHcw";

 

if( sguid == myGuid )

  // logic if guid and sguid are equal

 

if( sguid == "Xy0MVKupFES9NpmZ9TiHcw" )

  // logic if string and sguid are equal

ShortGuid Source Code

Following is the full listing in C#, or you can download the source code for the ShortGuid struct.

using System;

 

namespace CSharpVitamins

{

  /// <summary>

  /// Represents a globally unique identifier (GUID) with a

  /// shorter string value. Sguid

  /// </summary>

  public struct ShortGuid

  {

    #region Static

 

    /// <summary>

    /// A read-only instance of the ShortGuid class whose value

    /// is guaranteed to be all zeroes.

    /// </summary>

    public static readonly ShortGuid Empty = new ShortGuid(Guid.Empty);

 

    #endregion

 

    #region Fields

 

    Guid _guid;

    string _value;

 

    #endregion

 

    #region Contructors

 

    /// <summary>

    /// Creates a ShortGuid from a base64 encoded string

    /// </summary>

    /// <param name="value">The encoded guid as a

    /// base64 string</param>

    public ShortGuid(string value)

    {

      _value = value;

      _guid = Decode(value);

    }

 

    /// <summary>

    /// Creates a ShortGuid from a Guid

    /// </summary>

    /// <param name="guid">The Guid to encode</param>

    public ShortGuid(Guid guid)

    {

      _value = Encode(guid);

      _guid = guid;

    }

 

    #endregion

 

    #region Properties

 

    /// <summary>

    /// Gets/sets the underlying Guid

    /// </summary>

    public Guid Guid

    {

      get { return _guid; }

      set

      {

        if (value != _guid)

        {

          _guid = value;

          _value = Encode(value);

        }

      }

    }

 

    /// <summary>

    /// Gets/sets the underlying base64 encoded string

    /// </summary>

    public string Value

    {

      get { return _value; }

      set

      {

        if (value != _value)

        {

          _value = value;

          _guid = Decode(value);

        }

      }

    }

 

    #endregion

 

    #region ToString

 

    /// <summary>

    /// Returns the base64 encoded guid as a string

    /// </summary>

    /// <returns></returns>

    public override string ToString()

    {

      return _value;

    }

 

    #endregion

 

    #region Equals

 

    /// <summary>

    /// Returns a value indicating whether this instance and a

    /// specified Object represent the same type and value.

    /// </summary>

    /// <param name="obj">The object to compare</param>

    /// <returns></returns>

    public override bool Equals(object obj)

    {

      if (obj is ShortGuid)

        return _guid.Equals(((ShortGuid)obj)._guid);

      if (obj is Guid)

        return _guid.Equals((Guid)obj);

      if (obj is string)

        return _guid.Equals(((ShortGuid)obj)._guid);

      return false;

    }

 

    #endregion

 

    #region GetHashCode

 

    /// <summary>

    /// Returns the HashCode for underlying Guid.

    /// </summary>

    /// <returns></returns>

    public override int GetHashCode()

    {

      return _guid.GetHashCode();

    }

 

    #endregion

 

    #region NewGuid

 

    /// <summary>

    /// Initialises a new instance of the ShortGuid class

    /// </summary>

    /// <returns></returns>

    public static ShortGuid NewGuid()

    {

      return new ShortGuid(Guid.NewGuid());

    }

 

    #endregion

 

    #region Encode

 

    /// <summary>

    /// Creates a new instance of a Guid using the string value,

    /// then returns the base64 encoded version of the Guid.

    /// </summary>

    /// <param name="value">An actual Guid string (i.e. not a ShortGuid)</param>

    /// <returns></returns>

    public static string Encode(string value)

    {

      Guid guid = new Guid(value);

      return Encode(guid);

    }

 

    /// <summary>

    /// Encodes the given Guid as a base64 string that is 22

    /// characters long.

    /// </summary>

    /// <param name="guid">The Guid to encode</param>

    /// <returns></returns>

    public static string Encode(Guid guid)

    {

      string encoded = Convert.ToBase64String(guid.ToByteArray());

      encoded = encoded

        .Replace("/", "_")

        .Replace("+", "-");

      return encoded.Substring(0, 22);

    }

 

    #endregion

 

    #region Decode

 

    /// <summary>

    /// Decodes the given base64 string

    /// </summary>

    /// <param name="value">The base64 encoded string of a Guid</param>

    /// <returns>A new Guid</returns>

    public static Guid Decode(string value)

    {

      value = value

        .Replace("_", "/")

        .Replace("-", "+");

      byte[] buffer = Convert.FromBase64String(value + "==");

      return new Guid(buffer);

    }

 

    #endregion

 

    #region Operators

 

    /// <summary>

    /// Determines if both ShortGuids have the same underlying

    /// Guid value.

    /// </summary>

    /// <param name="x"></param>

    /// <param name="y"></param>

    /// <returns></returns>

    public static bool operator ==(ShortGuid x, ShortGuid y)

    {

      if ((object)x == null) return (object)y == null;

      return x._guid == y._guid;

    }

 

    /// <summary>

    /// Determines if both ShortGuids do not have the

    /// same underlying Guid value.

    /// </summary>

    /// <param name="x"></param>

    /// <param name="y"></param>

    /// <returns></returns>

    public static bool operator !=(ShortGuid x, ShortGuid y)

    {

      return !(x == y);

    }

 

    /// <summary>

    /// Implicitly converts the ShortGuid to it's string equivilent

    /// </summary>

    /// <param name="shortGuid"></param>

    /// <returns></returns>

    public static implicit operator string(ShortGuid shortGuid)

    {

      return shortGuid._value;

    }

 

    /// <summary>

    /// Implicitly converts the ShortGuid to it's Guid equivilent

    /// </summary>

    /// <param name="shortGuid"></param>

    /// <returns></returns>

    public static implicit operator Guid(ShortGuid shortGuid)

    {

      return shortGuid._guid;

    }

 

    /// <summary>

    /// Implicitly converts the string to a ShortGuid

    /// </summary>

    /// <param name="shortGuid"></param>

    /// <returns></returns>

    public static implicit operator ShortGuid(string shortGuid)

    {

      return new ShortGuid(shortGuid);

    }

 

    /// <summary>

    /// Implicitly converts the Guid to a ShortGuid

    /// </summary>

    /// <param name="guid"></param>

    /// <returns></returns>

    public static implicit operator ShortGuid(Guid guid)

    {

      return new ShortGuid(guid);

    }

 

    #endregion

  }

}

 

kick it on DotNetKicks.com

posted @ Thursday, December 20, 2007 5:15 PM | Feedback (36)
Filed Under [ C#, Tips, .NET, Source Code ]

Programmatically setting the SmtpClient pickup directory location at runtime

In my last post on using an smtp pickup directory for ASP.NET development, I explained some of the reasons to use a pickup folder instead of an SMTP server during ASP.NET development. One of the caveats of that configuration is that you have to enter the full path of the folder you want to store the application's mail in. This is fine if you're working solo, or can agree on a common folder/path use amongst your colleagues but it reduces the instant portability of your application, since you'll have the full path of the folder set in the web.config.

You can always use the configSource property for your web.config/system.net configuration element, and specify the 'per machine details' in a separate file which isn't source controlled. Not a bad idea.

However, it still doesn't solve the 'portability' issue. ASP.NET 2.0 (Visual Studio 2005) introduced the new Web Project model, where you can simply open a folder from the file system as a website and start coding. You can copy or move the folder to another location, or another machine, and open the folder in VS2005, and once again you're away.

With that in mind, configuring the SpecifiedPickupDirectory PickupDirectoryLocation as an absolute path (which is required by the framework) isn't the best solution as it ties the mail drop folder to a fixed path and you'll have to reconfigure if you move your project.

Changing the mailSettings through the configuration model

It's not entirely straight forward to change the location of the pickup folder at runtime. Initially, I thought of using the frameworks built-in functionality to change the application's mailSettings. Which looks something like this: 

Configuration config = WebConfigurationManager.OpenWebConfiguration( "~/web.config" );

MailSettingsSectionGroup mail = (MailSettingsSectionGroup)config.GetSectionGroup( "system.net/mailSettings" );

if( mail.Smtp.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory )

{

  string path = Path.Combine( HttpRuntime.AppDomainAppPath, @"..\Mail" );

  mail.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation = path;

}

But on closer inspection of the SmtpClient class using Reflector, you'll find that the default smtp settings utilise a static instance of an internal class called MailSettingsSectionGroupInternal, and is initialised from the default web.config settings. So changes to the runtime configuration don't effect the actual values the SmtpClient uses. That pretty much means the settings can only be 'set' when the configuration is loaded.

The only way we can get our changes to be applied is to save the configuration (with a call to config.Save()), which means writing to the web.config file. This in turn triggers the application to reload the changes. It's not ideal, since the app will be restarted and it's bad because it updates the web.config file with the new absolute path to the pickup folder. It's pretty much back to square one.

Reflection to the rescue

In .NET, nothing is too far from our reach if you know how to go about it. To programmatically set the PickupDirectoryLocation at runtime, all we need to do is use reflection to navigate our way down a path of interal classes and properties, to the single private variable that needs to change, and then simply set it.

The hierarchy that we need to change looks like this: System.Net.Mail.SmtpClient.MailConfiguration.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation

Since we can access the public member SmtpClient, we'll start there and get the first internal (and static) property, MailConfiguration. This should be called or defined in the Application_Start method of your Global.asax.

First, let's define some variables for working with, as well as the path we want to use for our drop folder. In this instance, I've set the path to the folder above the current application root, in a folder called "Mail".

BindingFlags instanceFlags = BindingFlags.Instance | BindingFlags.NonPublic;

PropertyInfo prop;

object mailConfiguration, smtp, specifiedPickupDirectory;

string path = Path.Combine( HttpRuntime.AppDomainAppPath, @"..\Mail" );

Then get the first static property and object from the SmtpClient

// get static internal property: MailConfiguration

prop = typeof( SmtpClient ).GetProperty( "MailConfiguration", BindingFlags.Static | BindingFlags.NonPublic );

mailConfiguration = prop.GetValue( null, null );

Continue down the hierarchy from the object we just assigned to mailConfiguration, getting the properties, and then the value, for each instance.

// get internal property: Smtp

prop = mailConfiguration.GetType().GetProperty( "Smtp", instanceFlags );

smtp = prop.GetValue( mailConfiguration, null );

 

// get internal property: SpecifiedPickupDirectory

prop = smtp.GetType().GetProperty( "SpecifiedPickupDirectory", instanceFlags );

specifiedPickupDirectory = prop.GetValue( smtp, null );

Lastly, get the field we want to set, as the corresponding property doesn't provide a setter.

// get private field: pickupDirectoryLocation, then set it to the supplied path

FieldInfo field = specifiedPickupDirectory.GetType().GetField( "pickupDirectoryLocation", instanceFlags );

field.SetValue( specifiedPickupDirectory, path );

And now, whenever an instance of SmtpClient is created, it will be initialised with the new pickup folder path.

A C# helper class, for your convenience.

So now you know how to set the property, here is the full listing of the helper class I use to achieve it.

How to use the CSharpVitamins.MailHelper class.

void Application_Start(object sender, EventArgs e)

{

  // set drop folder for mail

  if( MailHelper.IsUsingPickupDirectory )

    MailHelper.SetRelativePickupDirectoryLocation( @"..\Mail" );

}

Source code for the CSharpVitamins.MailHelper class.

using System;

using System.Configuration;

using System.Web;

using System.IO;

using System.Reflection;

using System.Net.Mail;

using System.Net.Configuration;

 

namespace CSharpVitamins

{

  public static class MailHelper

  {

    static bool? _isUsingPickupDirectory;

 

    /// <summary>

    /// Gets a value to indicate if the default SMTP Delivery

    /// method is SpecifiedPickupDirectory

    /// </summary>

    public static bool IsUsingPickupDirectory

    {

      get

      {

        if( !_isUsingPickupDirectory.HasValue )

        {

          Configuration config = WebConfigurationManager.OpenWebConfiguration( "~/web.config" );

          MailSettingsSectionGroup mail = (MailSettingsSectionGroup)config.GetSectionGroup( "system.net/mailSettings" );

          _isUsingPickupDirectory = mail.Smtp.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory;

        }

        return _isUsingPickupDirectory.Value;

      }

    }

 

    /// <summary>

    /// Sets the default PickupDirectoryLocation for the SmtpClient.

    /// </summary>

    /// <remarks>

    /// This method should be called to set the PickupDirectoryLocation

    /// for the SmtpClient at runtime (Application_Start)

    ///

    /// Reflection is used to set the private variable located in the

    /// internal class for the SmtpClient's mail configuration:

    /// System.Net.Mail.SmtpClient.MailConfiguration.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation

    ///

    /// The folder must exist.

    /// </remarks>

    /// <param name="path"></param>

    public static void SetPickupDirectoryLocation( string path )

    {

      BindingFlags instanceFlags = BindingFlags.Instance | BindingFlags.NonPublic;

      PropertyInfo prop;

      object mailConfiguration, smtp, specifiedPickupDirectory;

 

      // get static internal property: MailConfiguration

      prop = typeof( SmtpClient ).GetProperty( "MailConfiguration", BindingFlags.Static | BindingFlags.NonPublic );

      mailConfiguration = prop.GetValue( null, null );

 

      // get internal property: Smtp

      prop = mailConfiguration.GetType().GetProperty( "Smtp", instanceFlags );

      smtp = prop.GetValue( mailConfiguration, null );

 

      // get internal property: SpecifiedPickupDirectory

      prop = smtp.GetType().GetProperty( "SpecifiedPickupDirectory", instanceFlags );

      specifiedPickupDirectory = prop.GetValue( smtp, null );

 

      // get private field: pickupDirectoryLocation, then set it to the supplied path

      FieldInfo field = specifiedPickupDirectory.GetType().GetField( "pickupDirectoryLocation", instanceFlags );

      field.SetValue( specifiedPickupDirectory, path );

    }

 

    /// <summary>

    /// Sets the default PickupDirectoryLocation for the SmtpClient

    /// to the relative path from the current web root.

    /// </summary>

    /// <param name="path">Relative path to the web root</param>

    public static void SetRelativePickupDirectoryLocation( string path )

    {

      SetPickupDirectoryLocation( HttpRuntime.AppDomainAppPath, path );

    }

 

    /// <summary>

    /// Sets the default PickupDirectoryLocation for the SmtpClient.

    /// </summary>

    /// <remarks>

    /// This is a shortcut for passing in two paths, which are then

    /// combined to set the pickup directory.

    /// </remarks>

    /// <param name="path1">Base path</param>

    /// <param name="path3">Relative path to be combined with </param>

    public static void SetPickupDirectoryLocation( string path1, string path3 )

    {

      SetPickupDirectoryLocation( Path.Combine( path1, path3 ) );

    }

  }

}

Click here to download the source code for the MailHelper class.

Conclusion

In summary, it appears that we need to jump through a few hoops to achieve something fairly small in nature. Although encapsulating our code into a helper class improves the process of applying our desired setting, I couldn't find anything more straight forward to accomplish the task.

kick it on DotNetKicks.com

posted @ Wednesday, December 19, 2007 6:23 PM | Feedback (11)
Filed Under [ C#, Utilities, Tips, .NET, ASP.NET, Source Code ]

Recently on C# Vitamins...

Powered By Subtext

 

About C# Vitamins

Dave has been working in the industry for around 14 years, and has a focus on Javascript, C#, ASP.NET and SQL Server web development; not to mention being a standards driven type of guy.

C# Vitamins is the result of his findings while working in the web industry and a desire to share with the community; and if it was traced back far enough, you might say it might not have existed if he hadn't taken such an interest in id Software's original Quake.

Related Links

Below is a list of related links of Dave's other sites.