Home » Data » Get a Handle on UrlHandle

Get a Handle on UrlHandle

Sitecore Technology MVP 2016
Sitecore MVP 2015
Sitecore MVP 2014

Enter your email address to follow this blog and receive notifications of new posts by email.

Tweets

Over the past year or so, I’ve been having random blobs of information bubbling up into my consciousness and grabbing my attention — please don’t worry, these are pretty geeky things, mostly things I’ve encountered within Sitecore.Kernel.dll using .NET Reflector, or things I’ve discussed with other Sitecore developers. These random tidbits usually commandeer my attention during mundane events — examples include vegging out in front of TV, taking a shower, or during my long walks. I don’t mind when this happens since it has the benefit of keeping my mind engaged in something interesting, and perhaps constructive.

The UrlHandle class — a utility class found within the Sitecore.Web namespace in Sitecore.Kernel.dll — is probably the one thing that grabs my attention the most. This class usurps my attention at least once a day — more often multiple times a day — and does so usually in the context of a question that I will ask you at the end of this post. There is no doubt in my mind you’ll have a good answer to my question.

I remember hearing about the UrlHandle class for the first time at Dreamcore 2010 North America during a talk given by Lars Fløe Nielsen. Nielsen, co-founder and Senior VP of Technical Marketing at Sitecore, sold me on using this class around its core function of transferring a huge set of query string data between two pages without being confined to browser imposed limits.

The UrlHandle class is used within the content editor. An example of its usage can be seen within code for the TreelistEx field. The TreelistEx field passes information to its dialog window via the UrlHandle class.

Below, I created two sublayouts for the purpose of showing you how the UrlHandle class works, and how you may use it in your own solutions.

Sublayout on the originating page:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UrlHandle Origin.ascx.cs" Inherits="Sitecore650rev120706.layouts.sublayouts.UrlHandle_Origin" %>

<h2>Querystring:</h2>
<asp:Literal ID="litQueryStringForGettingAHandle" runat="server" /><br /><br />
<asp:Button ID="btnGotoDestinationPage" OnClick="btnGotoDestinationPage_Click" Text="Goto Destination Page" runat="server" />
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Sitecore.Text;
using Sitecore.Web;

namespace Sitecore650rev120706.layouts.sublayouts
{
    public partial class UrlHandle_Origin : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetQueryStringLiteral();
            }
        }

        protected void btnGotoDestinationPage_Click(object sender, EventArgs e)
        {
            AddToUrlHandleAndRedirect();
        }

        private string GetBigQueryString()
        {
            const char startLetter = 'a';
            const string queryStringParamFormat = "{0}={1}";
            Random random = new Random();

            IList<string> stringBuffer = new List<string>();

            for (int i = 0; i < 26; i++)
            {
                int ascii = i + (int)startLetter;
                char letter = (char)ascii;
                string queryStringParam = string.Format(queryStringParamFormat, letter.ToString(), random.Next(1000000000));
                stringBuffer.Add(queryStringParam);
            }

            string queryString = string.Join("&", stringBuffer);
            return string.Concat("?", queryString);
        }

        private void SetQueryStringLiteral()
        {
            litQueryStringForGettingAHandle.Text = GetBigQueryString();
        }

        private void AddToUrlHandleAndRedirect()
        {
            UrlHandle urlHandle = new UrlHandle();
            urlHandle["My Big Query String"] = litQueryStringForGettingAHandle.Text;

            UrlString urlString = new UrlString("/urlhandle-destination.aspx");
            urlHandle.Add(urlString);

            Response.Redirect(urlString.ToString());
        }
    }
}

The originating page’s sublayout above generates a querystring using all letters in the English alphabet coupled with random integers. These are placed within an instance of the UrlHandle class, with a key of the destination page’s url via the UrlString class.

If you are unfamiliar with the UrlString class, Jimmi Lyhne Andersen wrote a good blog post on using the UrlString class. I recommend that you check it out.

Output of the originating page:

Sublayout on the destination page:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UrlHandle Destination.ascx.cs" Inherits="Sitecore650rev120706.layouts.sublayouts.UrlHandle_Destination" %>

<h2>Querystring in UrlHandle:</h2>
<asp:Literal ID="litQueryStringFromHandle" runat="server" />
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Sitecore.Web;

namespace Sitecore650rev120706.layouts.sublayouts
{
    public partial class UrlHandle_Destination : System.Web.UI.UserControl
    {
        private UrlHandle _UrlHandle;
        private UrlHandle UrlHandle
        {
            get
            {
                if (_UrlHandle == null)
                    _UrlHandle = UrlHandle.Get();

                return _UrlHandle;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            SetLiterals();
        }

        private void SetLiterals()
        {
            litQueryStringFromHandle.Text = UrlHandle["My Big Query String"];
        }
    }
}

In the code-behind of the destination page’s sublayout, we use the parameterless static Get() method on the UrlHandle class to get a UrlHandle instance associated with the current url, and it uses “hdl” as the default handle name. Please be aware that an exception will be thrown if a url passed to this method is not associated with a UrlHandle object — or the current url if we are using the parameterless method. The Get method has overloads for passing in different parameters — one being a UrlString instance, and another being the name of the handle key. You have the ability to override the default handle name of “hdl” if you desire.

The handle value itself is a ShortID as the following screenshot highlights. Basically, this ShortID conjoined with the url of the destination page serve a unique key into the UrlHandle object for retrieving saved information.

Output of the destination page:

Once you pull information out of the UrlHandle class, it is removed from the UrlHandle’s repository of saved information. There is a way to override this default behavior in the object’s Get method by passing a boolean parameter.

So, you may be asking yourself how this class works behind the scenes. Well, it’s quite simple, and even I was surprised to learn how it really worked once I took a peek:

I thought there was some kind of magic happening under the hood but had a reality check after seeing how it really work — this ultimately reminded me of the KISS principle.

Everyday, I ponder and vacillate on whether it would be a good idea to create another class similar to the UrlHandle that would persist across sessions. At this point, I am convinced there is no utility in building such a class. What would be your argument for or against building such a class?

Advertisements

Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: