Get to Know Your Sitecore Utilities – Part 2: WebUtil

In the new Spider-Man: Homecoming movie, Peter Parker received an awesome, high-tech suit. One of the cool features of this suit is the new 🕸 web utilities he now has at his disposal. Excited, Spider-Man didn’t hesitate and rushed into web development without understanding the basic functionality of these tools… naturally, hilarity ensued. 🕷

Tony Stark gave Spider-Man those new web utilities to make Peter’s job easier, just as Sitecore gave us web utilities to help make our jobs easier.


Sitecore.Web.WebUtil

WebUtil has a lot of useful utilities that provide us an opportunity to save time and money by reducing the amount of new code that is needed, whether it’s simple code like a null check or more complex code such as parsing query strings into a dictionary while performing all the necessary checks to prevent exceptions, etc.

Request.Querystring vs. WebUtil.GetQueryString

Request.Querystring
The old-fashioned C# method of getting a collection of HTTP query string variables.
Returns:  NameValueCollection
Potential Issue: If you forget to check for null, it will throw an exception and if the exception is unhandled, the page will explode with an error. That won’t please the client. Another issue exists and it’s explained below.

GetQueryString
I prefer this method as it gives you some protection from a few errors. It also allows you to specify a default value. A related method, WebUtil.GetSafeQueryString gives you the added protection by encoding the querystring value. That’s super important for obvious security reasons.
Parameters: string url
Returns: String or Empty String
Why Did Sitecore Include It: Per the comments in the code, “This method is a work-around to a bug in ASP.NET. Direct access to an empty QueryString collection will cause the RewritePath method in the HttpModule to fail after exactly 50 calls. This method avoids direct access to QueryString collection. If the parameter was not found, the default value is returned.”
How to Use:

ParseQueryString
Parses a query string into a SafeDictionary of key/value pairs. The parameter list must have the format: “key1=value1&key2=value2&…”.
Parameters:  string queryString, bool decodeParamValues
Returns: A dictionary containing the query string parameters.
Why Use It?: If you want a dictionary populated with the query string’s keys and values, this provides you with a safe method to get that dictionary. It’s safe because it prevents errors such as a “possible” duplicate key. It also adds it to the query string cache.
How to Use:

Other “Cool” Utilities 🤷‍♂️

  • RemoveAllScripts
    Removes the inline scripts. For example, when the Rich Text field is saved, in the saveUI pipeline, the processor “Sitecore.Pipelines.Save.Save” fires. If scripts are not permitted via the config setting “HtmlEditor.RemoveScripts”, it removes all the JavaScript from the HTML.
    Parameters: string content
    Returns: A string stripped of possible inline Javascript
  • SafeEncode
    Encodes user input so that it is safe to use as output. Use to prevent XSS attacks.
    Parameters: string value
    Returns: The safe encoded string.
  • RedirectToLoginPage
    Redirect the visitor to the login defined for the site in the Site Definition config.
    Parameters: HttpContext httpContext, List<string> queryParamsToRemove
  • RedirectToErrorPage
    Handles the logic to redirect to the error page that is defined in the config setting “ErrorPage”.
    Parameters: string text
    The string “text” is passed to the error page and displayed.
  • GetPlaceholders
    Gets all the placeholders on the current page.
    Parameters: Type placeholderType
    Returns: Hashlist<string, object>
  • AddQueryString
    Adds a parameter to an URL. The parameters are added in pairs: name and value. The value is URL encoded.
    Parameters: string url, bool xhtml, params string[] parameters
    Example:

The Basics are so Basic… And Boring!

The Web Utilities have been around for as long as I can remember and they have probably been blogged about hundreds of times. Over time the older posts fade away and they are forgotten by Google. It’s extremely important that posts covering the Sitecore basics are not lost to time. I hope by revisiting topics like these, I can keep them fresh in Google and the Sitecore Community.

Inexperienced Sitecore developers need a solid understanding of the basics of this platform, its concepts and its best practices, no matter how elementary they may seem. Neglecting the basics could jeopardize everything; the basics start to become complex tasks and complex tasks begin to become impossible.

Recently, I had a glimpse of a Sitecore implementation where the basic Sitecore concepts were neglected by the developers. Concepts such as using placeholders to add renderings to a page. In this implementation, the devs placed the renderings on the page in a way that must be seen to be believed.

They added fields to item templates that stored a controller and action name. They also added code to the views that loops through the current page’s children. They retrieve the controller and action name values from the fields and then search the renderings to find a match. If a match is found, the rendering is programmably added to the page and then the datasource is set to that child item.

The developers did not understand the basics and thus the client’s goal of personalization is not possible without a massive rewrite.


Learn More about the Web Utilities

I listed the utilities I tend to use often. There are a lot more useful utilities you should be aware of. Click here to peruse thru the nearly 3000 lines of code that make up the WebUtil class and see what looks useful to you.

If you decide to stick with plain old C#, that’s perfectly fine. Personally, I utilize Sitecore’s Utilities whenever possible. My thought is simple, I am a Sitecore Developer, developing with Sitecore, why not use as much of Sitecore’s API as I can? I am trusting they did their due diligence in testing their code, I should have no reason to worry… right?

If you’ve used Sitecore’s Utilities and have had a bad experience or if you have facts to why using Sitecore’s code is not a good idea, I would love to hear your story. Leave a comment below.

Thanks for reading!


Do you enjoy my oddly themed blogs and wish you had access to even more of me and my ideas? Good news, you’re in luck!

If 140 characters is your thing, follow me on Twitter.

If you hate reading and watching Sitecore videos entertains you, head over to my YouTube channel! Sometimes I entertain, sometime I provide useful Sitecore information and sometimes I can do both in the same video.

I can also be found hanging out on the Sitecore channels on Slack, I like it, although it occasionally triggers AOL chat room flashbacks from the olden days.

You can also find me adding content on LinkedIn and on Reddit.