Skip to content

Instantly share code, notes, and snippets.

@5up3rman
Last active November 11, 2023 15:06
Show Gist options
  • Save 5up3rman/997f2308a17d09eeaf0d3cd242800fea to your computer and use it in GitHub Desktop.
Save 5up3rman/997f2308a17d09eeaf0d3cd242800fea to your computer and use it in GitHub Desktop.
Web Utility
using HtmlAgilityPack;
using Sitecore.Caching;
using Sitecore.Collections;
using Sitecore.Configuration;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.IO;
using Sitecore.Layouts;
using Sitecore.Links;
using Sitecore.Reflection;
using Sitecore.Security;
using Sitecore.SecurityModel.Cryptography;
using Sitecore.Sites;
using Sitecore.Text;
using Sitecore.Web.UI.WebControls;
using Sitecore.Xml.Xsl;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;
namespace Sitecore.Web
{
/// <summary>
/// Implements a library of standard utility functions relating to Web operations.
/// </summary>
/// <remarks>
/// <seealso cref="T:Sitecore.DateUtil" />
/// <seealso cref="T:Sitecore.IO.FileUtil" />
/// <seealso cref="T:Sitecore.Web.HtmlUtil" />
/// <seealso cref="T:Sitecore.MainUtil" />
/// <seealso cref="T:Sitecore.StringUtil" />
/// </remarks>
public class WebUtil
{
/// <summary>The CSS expression pattern.</summary>
private static readonly Regex cssExpressionPattern = new Regex("<[a-zA-Z0-9]+[^>]*?style=['\"]?.*?(?<cssRule>[^;\"]+: expression(?<bracket>\\())", RegexOptions.Compiled);
/// <summary>The error marker.</summary>
private const string ErrorMarker = "?404;";
/// <summary>The original cookie value key.</summary>
private const string OriginalCookieValueKey = "WebUtil_OriginalCookieValue";
/// <summary>The query string cache.</summary>
private static ICache queryStringCache;
/// <summary>The session ID cookie name.</summary>
private static string sessionIdCookieName;
/// <summary>Gets the current page.</summary>
/// <value>The current page.</value>
public static Page CurrentPage
{
get
{
PageContext page = Context.Page;
if (page != null)
return page.Page;
return (Page) null;
}
}
/// <summary>Gets the query string cache.</summary>
/// <value>The query string cache.</value>
public static ICache QueryStringCache
{
get
{
if (WebUtil.queryStringCache == null)
WebUtil.queryStringCache = Sitecore.Caching.CacheManager.GetNamedInstance("WebUtil.QueryStringCache", 20000L, true);
return WebUtil.queryStringCache;
}
}
/// <summary>Gets the boundary.</summary>
/// <value>The boundary.</value>
protected static string Boundary
{
get
{
return "1227b9d441e84256966a3e60d59ec37d";
}
}
/// <summary>Add control to page.</summary>
/// <param name="page">The page to add control for.</param>
/// <param name="control">The control.</param>
/// <remarks>Control is appended to the main form control.</remarks>
public static void AddPageControl(Page page, Control control)
{
Assert.ArgumentNotNull((object) page, "page");
Assert.ArgumentNotNull((object) control, "control");
Control controlOfType = WebUtil.FindControlOfType((Control) page, typeof (HtmlForm));
if (controlOfType == null)
return;
controlOfType.Controls.Add(control);
}
/// <summary>Adds a parameter to an URL.</summary>
/// <param name="url">An URL path.</param>
/// <param name="parameters">An array of parameter pairs.</param>
/// <returns>An URL path with the new parameters added.</returns>
/// <remarks>
/// The parameters are added in pairs: name and value. The value is URL encoded.
/// </remarks>
/// <example>
/// <code>
/// string url0 = WebUtil.AddQueryString("http://www.mysite.net", "print", "1"); // "http://www.mysite.net?print=1"
/// string url1 = WebUtil.AddQueryString("http://www.mysite.net", "print", "1", "lg", "print"); // "http://www.mysite.net?print=1&amp;lg=print"
/// </code>
/// <seealso cref="M:System.Web.HttpUtility.UrlEncode(System.String)" />
/// </example>
public static string AddQueryString(string url, params string[] parameters)
{
Assert.ArgumentNotNull((object) url, "url");
Assert.ArgumentNotNull((object) parameters, "parameters");
return WebUtil.AddQueryString(url, false, parameters);
}
/// <summary>Adds a parameter to an URL.</summary>
/// <param name="url">An URL path.</param>
/// <param name="xhtml">If set to <c>true</c> '&amp;' will be encoded as '&amp;amp;'.</param>
/// <param name="parameters">An array of parameter pairs.</param>
/// <returns>An URL path with the new parameters added.</returns>
/// <remarks>
/// The parameters are added in pairs: name and value. The value is URL encoded.
/// </remarks>
/// <example>
/// <code>
/// string url0 = WebUtil.AddQueryString("http://www.mysite.net", "print", "1"); // "http://www.mysite.net?print=1"
/// string url1 = WebUtil.AddQueryString("http://www.mysite.net", "print", "1", "lg", "print"); // "http://www.mysite.net?print=1&amp;lg=print"
/// </code>
/// <seealso cref="M:System.Web.HttpUtility.UrlEncode(System.String)" />
/// </example>
public static string AddQueryString(string url, bool xhtml, params string[] parameters)
{
Assert.ArgumentNotNull((object) url, "url");
Assert.ArgumentNotNull((object) parameters, "parameters");
string str1 = xhtml ? "&amp;" : "&";
string str2 = url.IndexOf('?') >= 0 ? str1 : "?";
int index = 0;
while (index < parameters.Length - 1)
{
url += string.Format("{0}{1}={2}", (object) str2, (object) parameters[index], (object) HttpUtility.UrlEncode(parameters[index + 1]));
str2 = str1;
index += 2;
}
return url;
}
/// <summary>Builds the query string.</summary>
/// <param name="parameters">The parameters.</param>
/// <param name="xhtml">
/// If set to <c>true</c>, return an XHTML compliant query string.
/// </param>
/// <param name="encodeParamValues">
/// If set to <c>true</c>, applies UrlEncode to parameter values.
/// </param>
/// <returns>The build query string.</returns>
public static string BuildQueryString(SafeDictionary<string> parameters, bool xhtml, bool encodeParamValues)
{
Assert.ArgumentNotNull((object) parameters, "parameters");
string empty = string.Empty;
foreach (KeyValuePair<string, string> parameter in (SafeDictionary<string, string>) parameters)
{
if (empty.Length > 0)
empty += xhtml ? "&amp;" : "&";
string input = parameter.Value;
if (encodeParamValues)
input = WebUtil.UrlEncode(input);
empty += string.Format("{0}={1}", (object) parameter.Key, (object) input);
}
return empty;
}
/// <summary>Builds the query string.</summary>
/// <param name="parameters">The parameters.</param>
/// <param name="xhtml">
/// If set to <c>true</c>, return an XHTML compliant query string.
/// </param>
/// <returns>The build query string.</returns>
public static string BuildQueryString(SafeDictionary<string> parameters, bool xhtml)
{
return WebUtil.BuildQueryString(parameters, xhtml, false);
}
/// <summary>Escapes the JavaScript string.</summary>
/// <param name="text">The text.</param>
/// <returns>Escaped JavaScript string</returns>
public static string EscapeJavascriptString(string text)
{
if (text == null)
return string.Empty;
return new StringBuilder(text).Replace("\\", "\\\\").Replace("'", "\\'").Replace("\"", "\\\"").Replace("<", "\\<").Replace(">", "\\>").ToString();
}
/// <summary>Executes a web page.</summary>
/// <param name="url">An URL path.</param>
/// <returns>The content of the web page.</returns>
/// <remarks>
/// If <i>URL</i> does not contain a protocol ("<i>protocol</i>://",
/// e.g. "http://" or "https://"), the page is assumed to be local, and the
/// current server URL will be prepended.
/// </remarks>
/// <example>
/// <code>
/// string content = WebUtil.Execute("http://www.mysite.net");
/// </code>
/// <seealso cref="T:System.Net.WebClient" />
/// </example>
public static string ExecuteWebPage(string url)
{
Assert.ArgumentNotNull((object) url, "url");
return WebUtil.ExecuteWebPage(url, (NameValueCollection) null);
}
/// <summary>Executes a web page.</summary>
/// <param name="url">An URL path.</param>
/// <param name="headers">A collection of HTTP headers values.</param>
/// <returns>The content of the web page.</returns>
/// <remarks>
/// If <i>URL</i> does not contain a protocol ("<i>protocol</i>://",
/// e.g. "http://" or "https://"), the page is assumed to be local, and the
/// current server URL will be prepended.
/// </remarks>
/// <example>
/// <code>
/// string content = WebUtil.Execute("http://www.mysite.net");
/// </code>
/// <seealso cref="T:System.Net.WebClient" />
/// </example>
public static string ExecuteWebPage(string url, NameValueCollection headers)
{
Assert.ArgumentNotNull((object) url, "url");
if (url.IndexOf("://", StringComparison.InvariantCulture) < 0)
url = WebUtil.GetServerUrl() + url;
WebClient webClient = new WebClient();
if (headers != null)
webClient.Headers.Add(headers);
return Encoding.UTF8.GetString(webClient.DownloadData(url));
}
/// <summary>Extracts the file path from an URL.</summary>
/// <param name="url">The URL to extract path from.</param>
/// <returns>The url without server and query string</returns>
/// <example>
/// http://www.server.com/news.aspx?id=10 returns /news.aspx
/// </example>
public static string ExtractFilePath(string url)
{
Assert.ArgumentNotNull((object) url, "url");
string str = url;
int length = str.IndexOf('?');
if (length >= 0)
str = str.Substring(0, length);
int num1 = str.IndexOf("://", StringComparison.InvariantCulture);
if (num1 >= 0)
{
int num2 = str.IndexOf('/', num1 + 3);
str = num2 >= 0 ? str.Substring(num2 + 1) : string.Empty;
}
return str;
}
/// <summary>Extracts the name of the language.</summary>
/// <param name="localPath">The local path.</param>
/// <returns>The name of the language.</returns>
public static string ExtractLanguageName(string localPath)
{
Assert.ArgumentNotNull((object) localPath, "localPath");
if (string.IsNullOrEmpty(localPath) || !localPath.StartsWith("/", StringComparison.InvariantCulture))
return (string) null;
int num = localPath.IndexOfAny(new char[2]{ '/', '.' }, 1);
if (num < 0)
num = localPath.Length;
return localPath.Substring(1, num - 1);
}
/// <summary>Extracts a parameter from an URL.</summary>
/// <param name="name">Name of the parameter.</param>
/// <param name="url">An URL path.</param>
/// <returns>The value of the parameter.</returns>
/// <remarks>
/// If the parameter does not exist, blank is returned. The parameters are URL decoded.
/// </remarks>
/// <example>
/// <code>
/// string print = WebUtil.ExtractUrlParm("print", "http://www.mysite.net?print=1&amp;lg=print"); // "1"
/// </code>
/// <seealso cref="M:System.Web.HttpUtility.UrlDecode(System.String)" />
/// </example>
public static string ExtractUrlParm(string name, string url)
{
Assert.ArgumentNotNull((object) name, "name");
Assert.ArgumentNotNull((object) url, "url");
int num = url.IndexOf("?", StringComparison.InvariantCulture);
if (num >= 0)
{
string str1 = HttpUtility.UrlDecode(url.Substring(num + 1));
char[] chArray = new char[1]{ '&' };
foreach (string str2 in str1.Split(chArray))
{
if (str2.StartsWith(string.Format("{0}=", (object) name), StringComparison.OrdinalIgnoreCase) && str2.Length > name.Length + 1)
return str2.Substring(name.Length + 1);
}
}
return string.Empty;
}
/// <summary>Finds the ancestor of the specified type.</summary>
/// <param name="control">The control.</param>
/// <param name="type">The type to search.</param>
/// <param name="includeSelf">If set to <c>true</c> this instance is include self.</param>
/// <returns>The ancestor of the specified type.</returns>
public static Control FindAncestorOfType(Control control, Type type, bool includeSelf)
{
Assert.ArgumentNotNull((object) type, "type");
if (control == null)
return (Control) null;
if (includeSelf)
{
Type type1 = control.GetType();
if (type1 == type || type1.IsSubclassOf(type))
return control;
}
return WebUtil.FindAncestorOfType(control.Parent, type, true);
}
/// <summary>Finds the ancestor of the specified type.</summary>
/// <param name="control">The control.</param>
/// <param name="typeName">Name of the type.</param>
/// <param name="includeSelf">If set to <c>true</c> this instance is include self.</param>
/// <returns>The ancestor of the specified type.</returns>
public static Control FindAncestorOfType(Control control, string typeName, bool includeSelf)
{
Assert.ArgumentNotNull((object) typeName, "typeName");
if (control == null)
return (Control) null;
if (includeSelf && control.GetType().Name == typeName)
return control;
return WebUtil.FindAncestorOfType(control.Parent, typeName, true);
}
/// <summary>Finds the control of specific name.</summary>
/// <param name="parent">The parent.</param>
/// <param name="name">The name to search.</param>
/// <returns>The control.</returns>
public static Control FindControl(Control parent, string name)
{
Assert.ArgumentNotNull((object) parent, "parent");
Assert.ArgumentNotNull((object) name, "name");
return parent.FindControl(name) ?? WebUtil.FindSubControl(parent, name);
}
/// <summary>Finds the control of the specified type.</summary>
/// <param name="parentControl">The parent control.</param>
/// <param name="targetType">Type of the target.</param>
/// <returns>The control of the specified type.</returns>
public static Control FindControlOfType(Control parentControl, Type targetType)
{
Assert.ArgumentNotNull((object) parentControl, "parentControl");
Assert.ArgumentNotNull((object) targetType, "targetType");
return WebUtil.FindControlOfType(parentControl, targetType, (string) null);
}
/// <summary>Finds the control of the specified type.</summary>
/// <param name="parentControl">The parent control.</param>
/// <param name="targetType">Type of the target.</param>
/// <param name="targetId">The target ID.</param>
/// <returns>The control of the specified type.</returns>
public static Control FindControlOfType(Control parentControl, Type targetType, string targetId)
{
Assert.ArgumentNotNull((object) parentControl, "parentControl");
Assert.ArgumentNotNull((object) targetType, "targetType");
if (MainUtil.IsType((object) parentControl, targetType))
{
if (targetId != null)
{
if (!targetId.Equals(StringUtil.GetString(new string[1]{ parentControl.ID }), StringComparison.OrdinalIgnoreCase))
goto label_4;
}
return parentControl;
}
label_4:
foreach (Control control in parentControl.Controls)
{
Control controlOfType = WebUtil.FindControlOfType(control, targetType, targetId);
if (controlOfType != null)
return controlOfType;
}
return (Control) null;
}
/// <summary>Finds all controls of the specified type.</summary>
/// <param name="type">The type to search.</param>
/// <param name="parentControl">The parent control.</param>
/// <returns>All controls of the specified type.</returns>
public static Control[] FindControlsOfType(Type type, Control parentControl)
{
Assert.ArgumentNotNull((object) type, "type");
Assert.ArgumentNotNull((object) parentControl, "parentControl");
ArrayList list = new ArrayList();
WebUtil.FindControlsOfType(type, parentControl, list);
return list.ToArray(typeof (Control)) as Control[];
}
/// <summary>Finds a placeholder below a root control.</summary>
/// <param name="key">The placeholder key.</param>
/// <param name="root">The root control.</param>
/// <returns>The placeholder.</returns>
public static Placeholder FindPlaceholder(string key, Control root)
{
Assert.ArgumentNotNull((object) key, "key");
Assert.ArgumentNotNull((object) root, "root");
Placeholder placeholder1 = root as Placeholder;
if (placeholder1 != null && placeholder1.Key.Equals(key, StringComparison.OrdinalIgnoreCase))
return placeholder1;
foreach (Control control in root.Controls)
{
Placeholder placeholder2 = WebUtil.FindPlaceholder(key, control);
if (placeholder2 != null)
return placeholder2;
}
return (Placeholder) null;
}
/// <summary>Finds all controls of the specified type.</summary>
/// <typeparam name="T">Type parameter.</typeparam>
/// <param name="parentControl">The parent control.</param>
/// <returns>All controls of the specified type.</returns>
public static List<T> FindSubControls<T>(Control parentControl) where T : Control
{
Assert.ArgumentNotNull((object) parentControl, "parentControl");
List<T> result = new List<T>();
WebUtil.FindSubControls<T>(parentControl, result);
return result;
}
/// <summary>Creates an anchor control from a link field.</summary>
/// <param name="itm">An item with link field.</param>
/// <param name="linkField">Name of the link field in the item.</param>
/// <returns>The created HtmlAnchor control.</returns>
/// <remarks>The inner text of the anchor control is blank.</remarks>
/// <example>
/// <code>
/// IMasterItem item = MasterFactory.GetItem("/sitecore/content/Home");
/// HtmlAnchor anchor = WebUtil.GetAnchor(item, "Link");
/// </code>
/// <seealso cref="T:System.Web.UI.HtmlControls.HtmlAnchor" />
/// </example>
public static HtmlAnchor GetAnchor(Item itm, string linkField)
{
Assert.ArgumentNotNull((object) itm, "itm");
Assert.ArgumentNotNull((object) linkField, "linkField");
return WebUtil.GetAnchor(itm, linkField, string.Empty);
}
/// <summary>Creates an anchor control from a link field.</summary>
/// <param name="itm">An item with link field.</param>
/// <param name="linkFieldName">Name of the link field in the item.</param>
/// <param name="text">Inner text of the anchor control.</param>
/// <returns>The created HtmlAnchor control.</returns>
/// <example>
/// <code>
/// IMasterItem item = MasterFactory.GetItem("/sitecore/content/Home");
/// HtmlAnchor anchor = WebUtil.GetAnchor(item, "Link", "Click me");
/// </code>
/// <seealso cref="T:System.Web.UI.HtmlControls.HtmlAnchor" />
/// </example>
public static HtmlAnchor GetAnchor(Item itm, string linkFieldName, string text)
{
Assert.ArgumentNotNull((object) itm, "itm");
Assert.ArgumentNotNull((object) linkFieldName, "linkFieldName");
Assert.ArgumentNotNull((object) text, "text");
HtmlAnchor htmlAnchor = new HtmlAnchor();
string url = WebUtil.GetUrl(itm, linkFieldName);
LinkField field = (LinkField) itm.Fields[linkFieldName];
Assert.IsNotNull((object) field, "link field");
if (text.Length == 0)
text = StringUtil.GetString(new string[2]
{
field.Text,
itm.Name
});
htmlAnchor.Title = field.Title;
htmlAnchor.Attributes["class"] = field.Class;
switch (field.LinkType)
{
case "javascript":
htmlAnchor.HRef = "#";
htmlAnchor.Attributes["onclick"] = url;
break;
default:
htmlAnchor.HRef = url;
htmlAnchor.Target = field.Target;
break;
}
htmlAnchor.InnerText = text;
return htmlAnchor;
}
/// <summary>Gets the browser capabilities.</summary>
/// <returns>The browser capabilities.</returns>
public static HttpBrowserCapabilities GetBrowserCapabilities()
{
HttpContext current = HttpContext.Current;
if (current == null)
return (HttpBrowserCapabilities) null;
return current.Request.Browser;
}
/// <summary>Gets a boolean cookie value.</summary>
/// <param name="key">Cookie key.</param>
/// <param name="defaultValue">A default value.</param>
/// <returns>The value of the cookie as a boolean.</returns>
/// <remarks>
/// If the cookie was not found, the default value is returned.
/// </remarks>
/// <example>
/// <code>
/// bool val = WebUtil.GetCookieBool("mykey", true);
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.Cookies" />
/// </example>
public static bool GetCookieBool(string key, bool defaultValue)
{
Assert.ArgumentNotNull((object) key, "key");
string cookieValue = WebUtil.GetCookieValue(key);
if (cookieValue.Length <= 0)
return defaultValue;
return System.Convert.ToBoolean(cookieValue);
}
/// <summary>Gets a date/time cookie value.</summary>
/// <param name="key">Cookie key.</param>
/// <param name="defaultValue">A default value.</param>
/// <returns>The value of the cookie as a UTC date/time.</returns>
/// <remarks>
/// If the cookie was not found, the default value is returned.
/// </remarks>
/// <example>
/// <code>
/// DateTime val = WebUtil.GetCookieDateTime("mykey", DateTime.UtcNow);
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.Cookies" />
/// </example>
public static DateTime GetCookieDateTime(string key, DateTime defaultValue)
{
Assert.ArgumentNotNull((object) key, "key");
string cookieValue = WebUtil.GetCookieValue(key);
return DateUtil.ToUniversalTime(cookieValue.Length > 0 ? DateUtil.IsoDateToDateTime(cookieValue) : defaultValue);
}
/// <summary>Gets the cookie value.</summary>
/// <param name="key">The cookie key.</param>
/// <returns>The get cookie value.</returns>
public static string GetCookieValue(string key)
{
Assert.ArgumentNotNullOrEmpty(key, "key");
string cookieValue = WebUtil.GetCookieValue(key, string.Empty);
Assert.IsNotNull((object) cookieValue, "value");
return cookieValue;
}
/// <summary>Gets the cookie value.</summary>
/// <param name="siteName">Name of the site.</param>
/// <param name="key">The cookie key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The cookie value.</returns>
public static string GetCookieValue(string siteName, string key, string defaultValue)
{
Assert.IsNotNullOrEmpty(siteName, "siteName");
Assert.ArgumentNotNull((object) key, "key");
return WebUtil.GetCookieValue(SiteContext.GetCookieKey(siteName, key), defaultValue);
}
/// <summary>Gets a cookie value.</summary>
/// <param name="key">Cookie key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The value of the cookie.</returns>
/// <remarks>If the cookie was not found, null is returned.</remarks>
/// <example>
/// <code>
/// string val = WebUtil.GetCookieValue("mykey");
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.Cookies" />
/// </example>
public static string GetCookieValue(string key, string defaultValue)
{
Assert.ArgumentNotNullOrEmpty(key, "key");
HttpContext current = HttpContext.Current;
if (current == null)
return defaultValue;
HttpCookie cookie = current.Request.Cookies[key];
if (cookie != null && cookie.Value != null)
return cookie.Value;
return defaultValue;
}
/// <summary>Gets the control to display an error message.</summary>
/// <param name="error">The error.</param>
/// <param name="details">The details.</param>
/// <returns>The control.</returns>
public static Control GetErrorControl(string error, string details)
{
Assert.ArgumentNotNull((object) error, "error");
Assert.ArgumentNotNull((object) details, "details");
HtmlTable table = new HtmlTable() { Border = 0, CellPadding = 3 };
HtmlTableRow htmlTableRow = HtmlUtil.AddRow(table, string.Empty, error);
HtmlImage htmlImage = new HtmlImage();
htmlTableRow.Cells[0].Controls.Add((Control) htmlImage);
htmlImage.Src = string.Format("/sitecore/client/themes/{0}/warning.gif", (object) State.Theme);
htmlImage.Alt = details;
htmlImage.Attributes["onclick"] = "javascript:alert(this.alt);";
htmlTableRow.Cells[1].Style["color"] = "red";
return (Control) table;
}
/// <summary>Get the form control of a page.</summary>
/// <param name="page">The page to search for Form control.</param>
/// <returns>The control.</returns>
public static Control GetFormControl(Page page)
{
Assert.ArgumentNotNull((object) page, "page");
return WebUtil.FindControlOfType((Control) page, typeof (HtmlForm));
}
/// <summary>Gets a value posted with a form.</summary>
/// <param name="fieldName">Name of the field.</param>
/// <returns>The get form value.</returns>
public static string GetFormValue(string fieldName)
{
Assert.ArgumentNotNull((object) fieldName, "fieldName");
HttpContext current = HttpContext.Current;
if (current == null)
return string.Empty;
return StringUtil.GetString(new string[1]{ current.Request.Form[fieldName] });
}
/// <summary>
/// Gets a value posted with a form which is not validated by asp.net.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <returns>The get form value.</returns>
public static string GetUnvalidatedFormValue(string fieldName)
{
Assert.ArgumentNotNull((object) fieldName, "fieldName");
HttpContext current = HttpContext.Current;
if (current == null)
return string.Empty;
return StringUtil.GetString(new string[1]{ current.Request.Unvalidated.Form[fieldName] });
}
/// <summary>
/// Expands an URL path to include the protocol, host and port.
/// </summary>
/// <param name="url">An URL path.</param>
/// <returns>The URL with protocol, host and port.</returns>
/// <remarks>
/// The port part is omitted, if the port is 80 (the HTTP port).
/// </remarks>
/// <example>
/// <code>
/// string url = WebUtil.GetFullUrl("/home.aspx"); // "http//www.mysite.net/home.aspx"
/// </code>
/// </example>
public static string GetFullUrl(string url)
{
Assert.ArgumentNotNull((object) url, "url");
return WebUtil.GetFullUrl(url, WebUtil.GetServerUrl());
}
/// <summary>
/// Expands an URL path to include the protocol, host and port.
/// </summary>
/// <param name="url">An URL path.</param>
/// <param name="serverUrl">A server part consisting of protocol, host and port.</param>
/// <returns>The URL with protocol, host and port.</returns>
/// <remarks>
/// <para>
/// The <i>serverUrl</i> parameter is ignore, if the URL path contains a protocol part
/// identified by the string "://".
/// </para>
/// <para>
/// The port part is omitted, if the port is 80 (the HTTP port).
/// </para>
/// </remarks>
/// <example>
/// <code>
/// string url = WebUtil.GetFullUrl("/home.aspx", "http//www.mysite.net"); // "http//www.mysite.net/home.aspx"
/// </code>
/// </example>
public static string GetFullUrl(string url, string serverUrl)
{
Assert.ArgumentNotNull((object) url, "url");
Assert.ArgumentNotNull((object) serverUrl, "serverUrl");
if (url.IndexOf("://", StringComparison.InvariantCulture) < 0)
return FileUtil.MakePath(serverUrl, url, '/');
return url;
}
/// <summary>Gets the IP address of the server host.</summary>
/// <returns>The IP address of the host.</returns>
/// <remarks>
/// If the host address cannot be converted to an IP address, blank is returned.
/// </remarks>
/// <example>
/// <code>
/// string host = WebUtil.GetHostIPAddress(); // "127.0.0.1"
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.Url" />
/// </example>
public static string GetHostIPAddress()
{
HttpContext current = HttpContext.Current;
try
{
if (current != null)
{
if (current.Request != null)
{
Uri url = current.Request.Url;
if (url.HostNameType == UriHostNameType.Dns)
{
IPHostEntry hostEntry = Dns.GetHostEntry(url.Host);
if (hostEntry.AddressList.Length >= 0)
return hostEntry.AddressList[0].ToString();
}
}
}
}
catch (SocketException ex)
{
Log.SingleWarn(string.Format("Cannot resolve the IP address of the web server with the specified hostname: {0}.", (object) current.Request.Url.Host), (object) typeof (WebUtil));
}
return string.Empty;
}
/// <summary>Gets the DNS name of the server host.</summary>
/// <returns>The DNS name of the server host.</returns>
/// <remarks>If the host cannot be obtained, blank is returned.</remarks>
/// <example>
/// <code>
/// string host = WebUtil.GetHostName(); // "www.mysite.net"
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.Url" />
/// </example>
public static string GetHostName()
{
HttpContext current = HttpContext.Current;
if (current != null && current.Request != null)
return current.Request.Url.Host;
return string.Empty;
}
/// <summary>Gets the IIS name of the web site.</summary>
/// <returns>The path to the web site on the IIS server.</returns>
/// <remarks>
/// This method can be used to identify the web site on the IIS server.
/// </remarks>
/// <example>
/// <code>
/// string name = Webutil.GetIISName(); / "c:\inetpub\wwwroot\mysite"
/// </code>
/// </example>
public static string GetIISName()
{
HttpServerUtility server = WebUtil.GetServer();
if (server != null)
return SecurityUtil.ComputeHash(server.MapPath("/"));
return string.Empty;
}
/// <summary>Gets an boolean value from the Items collection.</summary>
/// <param name="key">Name of the value.</param>
/// <param name="defaultValue">A default value.</param>
/// <returns>The value of the item in the Items collection.</returns>
/// <remarks>If the key was not found, the default is returned.</remarks>
/// <example>
/// <code>
/// bool b = WebUtil.GetItemsBool("mykey", true);
/// </code>
/// <seealso cref="P:System.Web.HttpContext.Items" />
/// </example>
public static bool GetItemsBool(string key, bool defaultValue)
{
Assert.ArgumentNotNull((object) key, "key");
object obj = Context.Items[key];
if (!(obj is bool))
return defaultValue;
return System.Convert.ToBoolean(obj);
}
/// <summary>Gets an string value from the Items collection.</summary>
/// <param name="key">Name of the value.</param>
/// <returns>The value of the item in the Items collection.</returns>
/// <remarks>If the key was not found, the blank is returned.</remarks>
/// <example>
/// <code>
/// string s = WebUtil.GetItemsString("mykey");
/// </code>
/// <seealso cref="P:System.Web.HttpContext.Items" />
/// </example>
public static string GetItemsString(string key)
{
Assert.ArgumentNotNull((object) key, "key");
return Context.Items[key] as string ?? string.Empty;
}
/// <summary>Gets an object from the Items collection.</summary>
/// <param name="key">Name of the object.</param>
/// <returns>The named object in the Items collection.</returns>
/// <remarks>If the key was not found, the null is returned.</remarks>
/// <example>
/// <code>
/// object o = WebUtil.GetItemsValue("mykey");
/// </code>
/// <seealso cref="P:System.Web.HttpContext.Items" />
/// </example>
public static object GetItemsValue(string key)
{
Assert.ArgumentNotNull((object) key, "key");
HttpContext current = HttpContext.Current;
if (current == null)
return (object) null;
return current.Items[(object) key];
}
/// <summary>
/// Gets the local path of an URL (ie. no query string).
/// </summary>
/// <param name="rawUrl">The raw URL.</param>
/// <returns>The get local path.</returns>
public static string GetLocalPath(string rawUrl)
{
Assert.ArgumentNotNullOrEmpty(rawUrl, "rawUrl");
return StringUtil.Divide(rawUrl, '?', false)[0];
}
/// <summary>Gets the name of the login cookie.</summary>
/// <returns>The login cookie name.</returns>
public static string GetLoginCookieName()
{
HttpContext current = HttpContext.Current;
if (current != null && current.Request != null)
return string.Format("{0}_sitecore_username", (object) new HashEncryption(HashEncryption.EncryptionProvider.SHA256).Hash(current.Request.Url.Host + (object) current.Request.Url.Port));
return string.Empty;
}
/// <summary>Gets the original value of a cookie.</summary>
/// <param name="cookieName">Name of the cookie.</param>
/// <returns>The get original cookie value.</returns>
public static string GetOriginalCookieValue(string cookieName)
{
Assert.ArgumentNotNull((object) cookieName, "cookieName");
HttpContext current = HttpContext.Current;
if (current == null)
return (string) null;
string str = string.Format("{0}_{1}", (object) "WebUtil_OriginalCookieValue", (object) cookieName);
if (!current.Items.Contains((object) str))
return WebUtil.GetCookieValue(cookieName, (string) null);
return current.Items[(object) str] as string;
}
/// <summary>Gets the path and query of a URL.</summary>
/// <param name="url">The URL to get path and query from.</param>
/// <returns>The get path and query.</returns>
public static string GetPathAndQuery(string url)
{
Assert.ArgumentNotNullOrEmpty(url, "url");
return new Uri(url).PathAndQuery;
}
/// <summary>Gets the all placeholders on the current page.</summary>
/// <param name="placeholderType">Type of the placeholder.</param>
/// <returns>The all placeholders on the current page.</returns>
public static HashList<string, object> GetPlaceholders(Type placeholderType)
{
Assert.ArgumentNotNull((object) placeholderType, "placeholderType");
Page handler = HttpContext.Current.Handler as Page;
if (handler != null)
{
Control[] controlsOfType = WebUtil.FindControlsOfType(placeholderType, (Control) handler);
if (controlsOfType != null && controlsOfType.Length > 0)
{
HashList<string, object> hashList = new HashList<string, object>();
foreach (Control control in controlsOfType)
{
string index = string.Empty;
if (control.ID != null)
index = control.ID.ToLowerInvariant();
hashList[index] = (object) control;
}
return hashList;
}
}
return (HashList<string, object>) null;
}
/// <summary>Gets the port number of the server host.</summary>
/// <returns>The port number of the server host.</returns>
/// <remarks>If the host cannot be obtained, 80.</remarks>
public static int GetPort()
{
HttpContext current = HttpContext.Current;
if (current != null && current.Request != null)
return current.Request.Url.Port;
return 80;
}
/// <summary>
/// Gets the entire query string of the current HTTP request.
/// </summary>
/// <returns>The raw URL path.</returns>
/// <remarks>The parameters are URL decoded.</remarks>
/// <example>
/// <code>
/// string url = WebUtil.GetQueryString(); // "http://www.mysite.net/home.aspx?print=1"
/// </code>
/// <seealso cref="P:Sitecore.Context.RawUrl" />
/// <seealso cref="M:System.Web.HttpUtility.UrlDecode(System.String)" />
/// </example>
public static string GetQueryString()
{
HttpContext current = HttpContext.Current;
if (current == null)
return string.Empty;
string rawUrl = current.Request.RawUrl;
int num = rawUrl.IndexOf("?", StringComparison.InvariantCulture);
if (num < 0)
return string.Empty;
return WebUtil.NormalizeUrl(rawUrl).Substring(num + 1);
}
/// <summary>
/// Gets a safe query string value from the current HTTP request.
/// </summary>
/// <param name="key">Name of value to get.</param>
/// <returns>The value of the parameter.</returns>
/// <remarks>
/// <para>
/// This method is a work-around to a bug in ASP.NET.
/// </para>
/// <para>
/// Direct access to an empty QueryString collection will cause
/// the RewritePath method in the HttpModule to fail after exactly 50 calls.
/// </para>
/// <para>
/// This methods avoids direct access to QueryString collection.
/// </para>
/// <para>
/// If the parameter was not found, blank is returned.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// // query string = "/home.aspx?print=1"
/// string print = WebUtil.GetQueryString("print"); / "1"
/// string target = WebUtil.GetQueryString("target"); / ""
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.QueryString" />
/// <seealso cref="P:System.Web.HttpRequest.Url" />
/// </example>
public static string GetQueryString(string key)
{
Assert.ArgumentNotNull((object) key, "key");
return WebUtil.GetQueryString(key, string.Empty) ?? string.Empty;
}
/// <summary>
/// Gets a safe query string value from the current HTTP request.
/// </summary>
/// <param name="key">Name of value to get.</param>
/// <param name="defaultValue">A default value.</param>
/// <returns>The value of the parameter.</returns>
/// <remarks>
/// <para>
/// This method is a work-around to a bug in ASP.NET.
/// </para>
/// <para>
/// Direct access to an empty QueryString collection will cause
/// the RewritePath method in the HttpModule to fail after exactly 50 calls.
/// </para>
/// <para>
/// This methods avoids direct access to QueryString collection.
/// </para>
/// <para>
/// If the parameter was not found, the default value is returned.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// // query string = "/home.aspx?print=1"
/// string print = WebUtil.GetQueryString("print", "0"); // "1"
/// string target = WebUtil.GetQueryString("target", "0"); // "0"
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.QueryString" />
/// </example>
public static string GetQueryString(string key, string defaultValue)
{
Assert.ArgumentNotNull((object) key, "key");
HttpContext current = HttpContext.Current;
if (current == null)
return defaultValue;
try
{
return current.Request.QueryString[key] ?? defaultValue;
}
catch (HttpRequestValidationException ex)
{
return defaultValue;
}
}
/// <summary>Gets the query string or cookie.</summary>
/// <param name="key">The key to search.</param>
/// <returns>The get query string or cookie.</returns>
public static string GetQueryStringOrCookie(string key)
{
Assert.ArgumentNotNull((object) key, "key");
return WebUtil.GetQueryStringOrCookie(key, string.Empty);
}
/// <summary>Gets the query string or cookie.</summary>
/// <param name="key">The key to search.</param>
/// <param name="defaultValue">The default.</param>
/// <returns>The get query string or cookie.</returns>
public static string GetQueryStringOrCookie(string key, string defaultValue)
{
Assert.ArgumentNotNull((object) key, "key");
string str = WebUtil.GetQueryString(key);
if (str.Length == 0)
str = WebUtil.GetCookieValue(key);
if (str.Length < 0)
return defaultValue;
return str;
}
/// <summary>Gets the raw URL.</summary>
/// <returns>The get raw url.</returns>
public static string GetRawUrl()
{
return Context.RawUrl;
}
/// <summary>Gets the request extension.</summary>
/// <returns>The request extension.</returns>
public static string GetRequestExtension()
{
HttpContext current = HttpContext.Current;
if (current != null)
return FileUtil.GetExtension(current.Request.CurrentExecutionFilePath);
return string.Empty;
}
/// <summary>Gets the request extension.</summary>
/// <param name="catchArgumentException">
/// Determines whether method should return string.Empty if current request virtual
/// path contains illegal characters.
/// </param>
/// <returns>
/// The request extension.
/// If current request virtual path contains illegal characters and <c>catchArgumentException</c> equals <c>true</c>
/// returns string.Empty.
/// </returns>
/// <exception cref="T:System.ArgumentException">
/// throws if current request virtual path contains illegal characters and
/// <c>catchArgumentException</c> equals <c>false</c>
/// </exception>
public static string GetRequestExtension(bool catchArgumentException)
{
if (!catchArgumentException)
return WebUtil.GetRequestExtension();
try
{
return WebUtil.GetRequestExtension();
}
catch (ArgumentException ex)
{
return string.Empty;
}
}
/// <summary>
/// Gets a boolean flag from the current HTTP request query string.
/// </summary>
/// <param name="flagName">Name of the flag.</param>
/// <param name="defaultValue">A default value.</param>
/// <returns>True, if the parameter is "1", otherwise false.</returns>
/// <remarks>
/// <para>
/// The flag is true, if the query string value is "1".
/// </para>
/// <para>
/// If the name was not found in the query string, the default is returned.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// // query string = "/home.aspx?print=1"
/// bool b0 = WebUtil.GetRequestFlag("print", false); // true
/// bool b1 = WebUtil.GetRequestFlag("group", false); // false
/// bool b2 = WebUtil.GetRequestFlag("target", true); // true
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.QueryString" />
/// </example>
public static bool GetRequestFlag(string flagName, bool defaultValue)
{
Assert.ArgumentNotNull((object) flagName, "flagName");
HttpContext current = HttpContext.Current;
if (current == null || current.Request.QueryString[flagName] == null)
return defaultValue;
return StringUtil.GetString(new string[1]{ current.Request.QueryString[flagName] }) == "1";
}
/// <summary>Gets a header value from the current HTTP request.</summary>
/// <param name="name">Name of the header.</param>
/// <returns>The value of the header.</returns>
/// <remarks>
/// If the header value was not found, blank is returned.
/// </remarks>
/// <example>
/// <code>
/// string header = WebUtil.GetRequestHeader("myHeader");
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.Headers" />
/// </example>
public static string GetRequestHeader(string name)
{
Assert.ArgumentNotNull((object) name, "name");
HttpContext current = HttpContext.Current;
if (current == null)
return string.Empty;
return StringUtil.GetString(new string[1]{ current.Request.Headers[name] });
}
/// <summary>
/// Gets an integer value from the current HTTP request query string.
/// </summary>
/// <param name="parameterName">Name of parameter.</param>
/// <param name="defaultValue">A default value.</param>
/// <returns>The value of the parameter.</returns>
/// <example>
/// <code>
/// // query string = "/home.aspx?print=1"
/// int i0 = WebUtil.GetQueryString("print", 0); // 1
/// int i1 = WebUtil.GetQueryString("target", 0); // 0
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.QueryString" />
/// </example>
public static int GetRequestInt(string parameterName, int defaultValue)
{
Assert.ArgumentNotNull((object) parameterName, "parameterName");
HttpContext current = HttpContext.Current;
if (current == null || current.Request.QueryString[parameterName] == null)
return defaultValue;
return System.Convert.ToInt32(StringUtil.GetString(new string[2]{ current.Request.QueryString[parameterName], defaultValue.ToString() }));
}
/// <summary>
/// Gets the <see cref="T:System.Uri" /> the current HTTP request.
/// </summary>
/// <returns>The DNS name of the server host.</returns>
/// <remarks>If the host cannot be obtained, blank is returned.</remarks>
/// <example>
/// <code>
/// string host = WebUtil.GetHostName(); // "www.mysite.net"
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.Url" />
/// </example>
public static Uri GetRequestUri()
{
HttpContext current = HttpContext.Current;
if (current == null || current.Request == null)
return (Uri) null;
return current.Request.Url;
}
/// <summary>
/// Gets the request Uri. Can handle requests which performed without aspx extention.
/// </summary>
/// <param name="url">The url to get request.</param>
/// <returns>The request Uri.</returns>
public static string GetRequestUri404(string url)
{
Assert.ArgumentNotNull((object) url, "url");
string url1 = HttpUtility.UrlDecode(url);
if (WebUtil.Is404Request(url1))
url1 = url1.Substring(url1.IndexOf("?404;", StringComparison.InvariantCulture) + "?404;".Length);
return url1;
}
/// <summary>Gets the safe query string.</summary>
/// <param name="key">The quiery key.</param>
/// <returns>The safe query string.</returns>
public static string GetSafeQueryString(string key)
{
Assert.ArgumentNotNull((object) key, "key");
return HttpUtility.HtmlEncode(WebUtil.GetQueryString(key));
}
/// <summary>Gets the current scheme (ie. http or https).</summary>
/// <returns>The scheme of the current request url.</returns>
/// <example>
/// <code>
/// string scheme = WebUtil.GetScheme(); // "http"
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.Url" />
/// </example>
public static string GetScheme()
{
HttpContext current = HttpContext.Current;
if (current != null)
return current.Request.Url.Scheme;
return string.Empty;
}
/// <summary>Gets the server.</summary>
/// <returns>The server.</returns>
public static HttpServerUtility GetServer()
{
HttpContext current = HttpContext.Current;
if (current == null)
return Globals.Server;
return current.Server;
}
/// <summary>Gets the server.</summary>
/// <returns>The server.</returns>
public static HttpServerUtilityBase GetServer(HttpContextBase context)
{
if (context != null)
return context.Server;
return Globals.ServerBase;
}
/// <summary>Gets the current server URL.</summary>
/// <returns>The URL of the server.</returns>
/// <remarks>
/// The server URL contains the port, if the port is not "80" (the default HTTP port).
/// </remarks>
/// <example>
/// <code>
/// string server = WebUtil.GetServerURL(); // "http://www.mysite.net:81"
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.Url" />
/// </example>
public static string GetServerUrl()
{
return WebUtil.GetServerUrl(false);
}
/// <summary>Gets the current server URL.</summary>
/// <param name="forcePort">
/// A boolean flag indicating if the port must be present.
/// </param>
/// <returns>The URL of the server.</returns>
/// <remarks>
/// The server URL contains the port, if the port is not "80" (the default HTTP port).
/// </remarks>
/// <example>
/// <code>
/// string server = WebUtil.GetServerURL(true); // "http://www.mysite.net:80"
/// string server = WebUtil.GetServerURL(false); // "http://www.mysite.net"
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.Url" />
/// </example>
public static string GetServerUrl(bool forcePort)
{
HttpContext current = HttpContext.Current;
if (current != null)
return WebUtil.GetServerUrl(current.Request.Url, forcePort);
string serverUrl = Globals.ServerUrl;
if (string.IsNullOrEmpty(serverUrl))
return string.Empty;
if (!forcePort)
return serverUrl;
int num = serverUrl.LastIndexOf(':');
if (num >= 0 && num < serverUrl.Length - 1 && (int) serverUrl[num + 1] != 47)
return serverUrl;
return string.Format("{0}:80", (object) StringUtil.RemovePostfix(':', serverUrl));
}
/// <summary>Gets the current server URL.</summary>
/// <param name="url">The URL to get server from.</param>
/// <param name="forcePort">
/// if set to <c>true</c> this instance is force port.
/// </param>
/// <returns>The get server url.</returns>
public static string GetServerUrl(Uri url, bool forcePort)
{
if (url == (Uri) null)
return string.Empty;
string scheme = url.Scheme;
string host = url.Host;
string str1 = url.Port.ToString();
string str2 = string.Format("{0}://{1}", (object) scheme, (object) host);
if (forcePort || str1 != "80")
str2 += string.Format(":{0}", (object) str1);
return str2;
}
/// <summary>Gets a boolean value from the current session.</summary>
/// <param name="key">Name of the boolean value.</param>
/// <param name="defaultValue">A default value.</param>
/// <returns>The value of the named session variable.</returns>
/// <remarks>
/// If the session variable was not found, the default value is returned.
/// </remarks>
/// <example>
/// <code>
/// bool b = WebUtil.GetSessionBool("myBoolean", false);
/// </code>
/// <seealso cref="T:System.Web.SessionState.HttpSessionState" />
/// </example>
public static bool GetSessionBool(string key, bool defaultValue)
{
Assert.ArgumentNotNull((object) key, "key");
object sessionValue = WebUtil.GetSessionValue(key);
if (sessionValue is bool)
return System.Convert.ToBoolean(sessionValue);
return defaultValue;
}
/// <summary>Gets a date/time value from the current session.</summary>
/// <param name="key">Name of the date/time value.</param>
/// <param name="defaultValue">A default value.</param>
/// <returns>The value of the named session variable as a UTC date/time.</returns>
/// <remarks>
/// If the session variable was not found, the default value is returned.
/// </remarks>
/// <example>
/// <code>
/// DateTime dt = WebUtil.GetSessionDateTime("myBoolean", DateTime.UtcNow);
/// </code>
/// <seealso cref="T:System.Web.SessionState.HttpSessionState" />
/// </example>
public static DateTime GetSessionDateTime(string key, DateTime defaultValue)
{
Assert.ArgumentNotNull((object) key, "key");
object sessionValue = WebUtil.GetSessionValue(key);
if (sessionValue is DateTime)
return DateUtil.ToUniversalTime(System.Convert.ToDateTime(sessionValue));
return DateUtil.ToUniversalTime(defaultValue);
}
/// <summary>Gets the current session ID.</summary>
/// <returns>The current session ID.</returns>
/// <remarks>
/// If there is no current session, the value of the ASP.NET session ID cookie (default: asp.net_sessionid) is returned.
/// </remarks>
/// <example>
/// <code>
/// string sessionID = WebUtil.GetSessionID();
/// </code>
/// <seealso cref="P:System.Web.SessionState.HttpSessionState.SessionID" />
/// </example>
public static string GetSessionID()
{
HttpContext current = HttpContext.Current;
if (current != null && current.Session != null)
{
if (current.Session.IsNewSession && Settings.Performance.ForceASPSessionIDPersist)
current.Session["__forceSessionPersist"] = (object) "dummy";
return current.Session.SessionID;
}
string sessionIdCookieName = WebUtil.GetSessionIdCookieName();
Assert.IsNotNull((object) sessionIdCookieName, "key");
if (!Context.IsUnitTesting)
return WebUtil.GetCookieValue(sessionIdCookieName);
return WebUtil.GetCookieValue(sessionIdCookieName, "unittests.net_sessionid");
}
/// <summary>Gets a string value from the current session.</summary>
/// <param name="key">Name of value.</param>
/// <returns>The value of the named session variable.</returns>
/// <remarks>
/// If the session variable was not found, blank is returned.
/// </remarks>
/// <example>
/// <code>
/// string val = WebUtil.GetSessionString("myValue");
/// </code>
/// <seealso cref="T:System.Web.SessionState.HttpSessionState" />
/// </example>
public static string GetSessionString(string key)
{
Assert.ArgumentNotNull((object) key, "key");
return WebUtil.GetSessionString(key, string.Empty);
}
/// <summary>Gets a string value from the current session.</summary>
/// <param name="key">Name of value.</param>
/// <param name="defaultValue">A default value.</param>
/// <returns>The value of the named session variable.</returns>
/// <remarks>
/// If the session variable was not found, the default value is returned.
/// </remarks>
/// <example>
/// <code>
/// string val = WebUtil.GetSessionString("myValue", "1");
/// </code>
/// <seealso cref="T:System.Web.SessionState.HttpSessionState" />
/// </example>
public static string GetSessionString(string key, string defaultValue)
{
Assert.ArgumentNotNull((object) key, "key");
object sessionValue = WebUtil.GetSessionValue(key);
if (sessionValue is string)
return sessionValue as string;
return defaultValue;
}
/// <summary>Sets the session timeout.</summary>
/// <returns>The session timeout.</returns>
public static TimeSpan GetSessionTimeout()
{
HttpContext current = HttpContext.Current;
if (current != null && current.Session != null)
return TimeSpan.FromMinutes((double) current.Session.Timeout);
return ((SessionStateSection) WebConfigurationManager.GetSection("system.web/sessionState")).Timeout;
}
/// <summary>Gets an object from the current session.</summary>
/// <param name="key">Name of object.</param>
/// <returns>The object of the named session variable.</returns>
/// <remarks>
/// If the session variable was not found, null is returned.
/// </remarks>
/// <example>
/// <code>
/// object o = WebUtil.GetSessionValue("myObject");
/// </code>
/// <seealso cref="T:System.Web.SessionState.HttpSessionState" />
/// </example>
public static object GetSessionValue(string key)
{
Assert.ArgumentNotNull((object) key, "key");
HttpContext current = HttpContext.Current;
if (current != null && current.Session != null)
return current.Session[key];
return (object) null;
}
/// <summary>Gets an object from the current session.</summary>
/// <param name="key">Name of object.</param>
/// <param name="context">The context.</param>
/// <returns>The object of the named session variable.</returns>
/// <remarks>
/// If the session variable was not found, null is returned.
/// </remarks>
/// <example>
/// <code>
/// object o = WebUtil.GetSessionValue("myObject");
/// </code>
/// <seealso cref="T:System.Web.SessionState.HttpSessionState" />
/// </example>
public static object GetSessionValue(string key, HttpContext context)
{
Assert.ArgumentNotNull((object) key, "key");
if (context == null)
return (object) null;
HttpSessionState session = context.Session;
if (session != null)
return session[key];
return (object) null;
}
/// <summary>Generates an URL path from a link field.</summary>
/// <param name="item">An item with link field.</param>
/// <param name="linkFieldName">Name of a Link field in the item.</param>
/// <returns>An URL path.</returns>
/// <example>
/// <code>
/// IMasterItem item = MasterFactory.GetItem("/sitecore/content/Home");
/// string url = WebUtil.GetUrl(item, "Link"); // "/Home/Products.aspx"
/// </code>
/// </example>
public static string GetUrl(Item item, string linkFieldName)
{
Assert.ArgumentNotNull((object) item, "item");
Assert.ArgumentNotNullOrEmpty(linkFieldName, "linkFieldName");
return new LinkUrl().GetUrl(item, linkFieldName);
}
/// <summary>
/// Gets an item name as specified in the current URL path.
/// </summary>
/// <param name="index">
/// Index of the URL part. Counted from the right starting with zero.
/// </param>
/// <returns>
/// The specified part of the current URL path including the .aspx extension.
/// </returns>
/// <example>
/// <code>
/// string url = "http://localhost/home/news/test+winner.aspx";
/// string p0 = WebUtil.GetUrlName(0); // "test winner"
/// string p1 = WebUtil.GetUrlName(1); // "news"
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.QueryString" />
/// <seealso cref="M:System.Web.HttpUtility.UrlDecode(System.String)" />
/// </example>
public static string GetUrlName(int index)
{
string queryString = WebUtil.GetQueryString("path");
if (queryString.Length == 0)
queryString = StringUtil.Divide(StringUtil.Divide(Context.RawUrl, '?', false)[0], '.', true)[0];
if (index == 0)
{
int num = queryString.LastIndexOf('/');
if (num >= 0)
return MainUtil.DecodeName(HttpUtility.UrlDecode(queryString.Substring(num + 1)));
}
else
{
string[] strArray = queryString.Split('/');
if (strArray.Length > index)
return MainUtil.DecodeName(HttpUtility.UrlDecode(strArray[strArray.Length - 1 - index]));
}
return string.Empty;
}
/// <summary>
/// Gets the item source path of the current HTTP request.
/// </summary>
/// <returns>The path to the current item.</returns>
/// <remarks>
/// If there is no current item, the path to the default item is returned.
/// The default item is configured in the web.config setting "DefaultItem". If the
/// path is a GUID and the closing brace is missing, the brace is added.
/// <seealso cref="P:Sitecore.Configuration.Settings.DefaultItem" />
/// </remarks>
/// <example>
/// <code>
/// // query string: "http://www.mysite.net/?path=/home.aspx"
/// string source = WebUtil.GetWebItemSource(); // "/home.aspx"
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.QueryString" />
/// </example>
public static string GetWebItemSource()
{
HttpContext current = HttpContext.Current;
if (current == null)
return string.Empty;
string str = StringUtil.GetString(new string[2]{ current.Request.QueryString["path"], Settings.DefaultItem });
if (str.Length == 37 && str.StartsWith("{", StringComparison.InvariantCulture))
str += (string) (object) '}';
return str;
}
/// <summary>Try to handles the full name of the user.</summary>
/// <param name="userName">Name of the user.</param>
/// <returns>
/// If success return fullUserName (domain\name) else return userName without changes
/// </returns>
public static string HandleFullUserName(string userName)
{
Assert.ArgumentNotNull((object) userName, "userName");
if (Membership.GetUser(userName) != null)
return userName;
string fullName = Context.Domain.GetFullName(userName);
if (Membership.GetUser(fullName) != null)
return fullName;
return userName;
}
/// <summary>
/// Calls HttpUtility.HtmlEncode and then replaces single quotes with HTML entity "'"
/// </summary>
/// <param name="html">The HTML.</param>
/// <returns></returns>
[Obsolete("Use HttpUtility.HtmlEncode instead, since starting from .NET 4.0 it replaces single quotes with HTML entity &#39;")]
public static string HtmlEncode(string html)
{
return HttpUtility.HtmlEncode(html);
}
/// <summary>Insert control in a placeholder on the page</summary>
/// <param name="control">The control.</param>
/// <param name="placeholderID">The placeholder ID.</param>
/// <param name="placeholderType">Type of the placeholder.</param>
/// <param name="page">The page to insert control in.</param>
/// <returns>The insert control.</returns>
public static bool InsertControl(Control control, string placeholderID, Type placeholderType, Page page)
{
Control control1 = WebUtil.FindPlaceholder(placeholderID, placeholderType);
if (control1 == null && placeholderID.Length == 0)
control1 = WebUtil.GetFormControl(page) ?? (Control) page;
if (control1 == null)
return false;
control1.Controls.Add(control);
return true;
}
/// <summary>Is404s the request.</summary>
/// <param name="url">The url to check.</param>
/// <returns>
/// The true if request performed without aspx extention.
/// </returns>
public static bool Is404Request(string url)
{
Assert.ArgumentNotNull((object) url, "url");
return url.IndexOf("?404;", StringComparison.InvariantCulture) >= 0;
}
/// <summary>Determines if a path is an external URL path.</summary>
/// <param name="path">An URL path.</param>
/// <returns>True, if the path is external, otherwise false.</returns>
/// <remarks>
/// An URL path is external if it contains a protocol identified
/// by the string "://".
/// </remarks>
public static bool IsExternalUrl(string path)
{
Assert.ArgumentNotNull((object) path, "path");
Uri result;
if (Uri.TryCreate(WebUtil.RemoveQueryString(path), UriKind.Absolute, out result))
return true;
return path.IndexOf("://", StringComparison.InvariantCulture) >= 0;
}
/// <summary>
/// Determines whether specified URL is external to specified host.
/// </summary>
/// <param name="url">The URL to check.</param>
/// <param name="host">The host name.</param>
/// <returns>
/// <c>true</c> if specified URL is external to specified host; otherwise, <c>false</c>.
/// </returns>
public static bool IsExternalUrl(string url, string host)
{
Assert.ArgumentNotNullOrEmpty(url, "url");
Assert.ArgumentNotNullOrEmpty(host, "host");
if (!WebUtil.IsExternalUrl(url))
return false;
return !new Uri(WebUtil.RemoveQueryString(url)).Host.Equals(host, StringComparison.OrdinalIgnoreCase);
}
/// <summary>Determines if a path is an internal URL path.</summary>
/// <param name="path">An URL path.</param>
/// <returns>True, if the path is internal, otherwise false.</returns>
/// <remarks>
/// An URL path is internal if it does not contain a
/// protocol (identified by the string "://").
/// </remarks>
public static bool IsInternalUrl(string path)
{
Assert.ArgumentNotNull((object) path, "path");
return !WebUtil.IsExternalUrl(path);
}
/// <summary>Determines whether the specified request is local.</summary>
/// <param name="request">The request.</param>
/// <returns>
/// <c>true</c> if the specified request is local; otherwise, <c>false</c>.
/// </returns>
public static bool IsLocalRequest(HttpRequest request)
{
Assert.IsNotNull((object) request, "request");
return request.ServerVariables["REMOTE_ADDR"] == request.ServerVariables["LOCAL_ADDR"];
}
/// <summary>
/// Determines whether the current page is an aspx page.
/// </summary>
/// <returns>
/// <c>true</c> if it is an aspx page; otherwise, <c>false</c>.
/// </returns>
public static bool IsOnAspxPage()
{
string localPath = WebUtil.GetLocalPath(Context.RawUrl);
if (!localPath.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase))
return localPath == "/";
return true;
}
/// <summary>Checks if the current page matches a path.</summary>
/// <param name="path">The path to check.</param>
/// <returns>
/// <c>true</c> if [is on page] [the specified path]; otherwise, <c>false</c>.
/// </returns>
public static bool IsOnPage(string path)
{
Assert.ArgumentNotNull((object) path, "path");
HttpContext current = HttpContext.Current;
if (current != null)
return WebUtil.ExtractFilePath(path).ToLowerInvariant() == current.Request.CurrentExecutionFilePath.ToLowerInvariant();
return false;
}
/// <summary>
/// Determines whether the current request is a post back.
/// </summary>
/// <returns>
/// <c>true</c> if it is post back; otherwise, <c>false</c>.
/// </returns>
public static bool IsPostBack()
{
HttpContext current = HttpContext.Current;
if (current == null)
return false;
Page handler = current.Handler as Page;
if (handler != null)
return handler.IsPostBack;
return false;
}
/// <summary>Normalizes a URL.</summary>
/// <remarks>
/// <para>
/// Replaces &amp;amp; with &amp;.
/// </para>
/// <para>
/// Url decodes query string parameters (see <see cref="M:System.Web.HttpUtility.UrlDecode(System.String)" />).
/// </para>
/// <para>
/// Removes empty parameters.
/// </para>
/// </remarks>
/// <param name="url">The URL to normilize.</param>
/// <returns>The normalize url.</returns>
public static string NormalizeUrl(string url)
{
Assert.ArgumentNotNull((object) url, "url");
int num = url.IndexOf('?');
if (num < 0)
return url;
return url.Substring(0, num) + url.Substring(num).Replace("&amp;", "&");
}
/// <summary>
/// Parses a list of parameters into a Hashtable of key/value pairs.
/// </summary>
/// <param name="queryString">A complete query string.</param>
/// <param name="separator">The separator.</param>
/// <returns>A Hashtable containing the parameters.</returns>
/// <remarks>
/// The parameter list must have the format: "key1=value1&amp;key2=value2&amp;...".
/// </remarks>
/// <example>
/// <code>
/// Hashtable table = WebUtil.ParseParameters("print=1&amp;target=me&amp;group=first");
/// string s0 = table["print"]; // "1";
/// string s1 = table["target"]; // "me";
/// string s2 = table["group"]; // "first";
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.QueryString" />
/// </example>
public static NameValueCollection ParseParameters(string queryString, char separator)
{
Assert.ArgumentNotNull((object) queryString, "queryString");
NameValueCollection nameValueCollection = new NameValueCollection();
if (queryString.Length == 0)
return nameValueCollection;
int position = 0;
char[] stopCharacters = new char[2]{ '=', '&' };
char stopCharacter;
string token1;
while (TextParser.ReadToken(queryString, stopCharacters, ref position, out token1, out stopCharacter))
{
string token2 = string.Empty;
if ((int) stopCharacter == 61 && !TextParser.ReadToken(queryString, separator, ref position, out token2))
{
token2 = queryString.Substring(position);
position = queryString.Length;
}
nameValueCollection.Add(token1.Trim(), HttpUtility.UrlDecode(token2));
}
if (!string.IsNullOrEmpty(token1))
nameValueCollection.Add(token1, string.Empty);
return nameValueCollection;
}
/// <summary>
/// Parses a query string into a <see cref="T:Sitecore.Collections.SafeDictionary`1">dictionary</see> of key/value pairs.
/// </summary>
/// <param name="queryString">
/// \
/// The query string.
/// </param>
/// <param name="decodeParamValues">
/// If set to <c>true</c>, applies HttpUtility.UrlDecode to parameter values.
/// </param>
/// <returns>
/// A dictionary containing the query string parameters.
/// </returns>
/// <remarks>
/// The parameter list must have the format: "key1=value1&amp;key2=value2&amp;...".
/// </remarks>
/// <example>
/// <code>
/// SafeDictionary&lt;string&gt; values = WebUtil.ParseQueryString("print=1&amp;target=me&amp;group=first");
/// string s0 = values["print"]; // "1";
/// string s1 = values["target"]; // "me";
/// string s2 = values["group"]; // "first";
/// string s3 = values["non-existing"]; // null;
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.QueryString" />
/// </example>
public static SafeDictionary<string> ParseQueryString(string queryString, bool decodeParamValues)
{
SafeDictionary<string> safeDictionary1 = WebUtil.QueryStringCache[queryString] as SafeDictionary<string>;
if (safeDictionary1 != null)
return safeDictionary1.Clone();
SafeDictionary<string> safeDictionary2 = new SafeDictionary<string>((IEqualityComparer) StringComparer.OrdinalIgnoreCase);
if (string.IsNullOrEmpty(queryString))
return safeDictionary2;
int position = 0;
TextParser.MovePast(queryString, "?", ref position);
string token1;
while (TextParser.ReadToken(queryString, '=', ref position, out token1))
{
string token2;
bool flag = TextParser.ReadToken(queryString, '&', ref position, out token2);
if (!flag)
token2 = queryString.Substring(position);
if (decodeParamValues)
token2 = HttpUtility.UrlDecode(token2);
safeDictionary2[token1] = token2;
if (flag)
TextParser.MovePast(queryString, "amp;", ref position);
else
break;
}
WebUtil.QueryStringCache.Add(queryString, (object) safeDictionary2.Clone());
return safeDictionary2;
}
/// <summary>
/// Parses a query string into a <see cref="T:Sitecore.Collections.SafeDictionary`1">dictionary</see> of key/value pairs.
/// </summary>
/// <param name="queryString">
/// \
/// The query string.
/// </param>
/// <returns>
/// A dictionary containing the query string parameters.
/// </returns>
public static SafeDictionary<string> ParseQueryString(string queryString)
{
return WebUtil.ParseQueryString(queryString, false);
}
/// <summary>
/// Parses a list of URL parameters into a Hashtable of key/value pairs.
/// </summary>
/// <param name="url">An URL parameter list.</param>
/// <returns>A Hashtable containing the URL parameters.</returns>
/// <remarks>
/// The parameter list must have the format: "key1=value1&amp;key2=value2&amp;...".
/// </remarks>
/// <example>
/// <code>
/// Hashtable table = WebUtil.ParseUrlParameters("print=1&amp;target=me&amp;group=first");
/// string s0 = table["print"]; // "1";
/// string s1 = table["target"]; // "me";
/// string s2 = table["group"]; // "first";
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.QueryString" />
/// </example>
public static NameValueCollection ParseUrlParameters(string url)
{
Assert.ArgumentNotNull((object) url, "url");
return WebUtil.ParseUrlParameters(url, '&');
}
/// <summary>
/// Parses a list of URL parameters into a Hashtable of key/value pairs.
/// </summary>
/// <param name="urlOrQueryString">
/// A complete URL or a query string.
/// </param>
/// <param name="separator">The separator.</param>
/// <returns>A Hashtable containing the URL parameters.</returns>
/// <remarks>
/// The parameter list must have the format: "key1=value1,key2=value2,...".
/// </remarks>
/// <example>
/// <code>
/// Hashtable table = WebUtil.ParseUrlParameters("print=1&amp;target=me&amp;group=first");
/// string s0 = table["print"]; // "1";
/// string s1 = table["target"]; // "me";
/// string s2 = table["group"]; // "first";
/// </code>
/// <seealso cref="P:System.Web.HttpRequest.QueryString" />
/// </example>
public static NameValueCollection ParseUrlParameters(string urlOrQueryString, char separator)
{
Assert.ArgumentNotNull((object) urlOrQueryString, "urlOrQueryString");
int num = urlOrQueryString.IndexOf('?');
return WebUtil.ParseParameters(num >= 0 ? urlOrQueryString.Substring(num + 1) : urlOrQueryString, separator);
}
/// <summary>Posts a file to a web page.</summary>
/// <param name="url">An URL path to post to.</param>
/// <param name="name">
/// Form name of file data - same as the name
/// attribute on an HTML input element.
/// </param>
/// <param name="filePath">A path to a file.</param>
/// <param name="timeout">Timeout in seconds.</param>
/// <param name="values">
/// Field values to include in the form post.
/// Format is: name,value,name,value,...
/// </param>
/// <returns>The response from the web page posted to.</returns>
/// <remarks>
/// If an error occurs, the string "##Error:" and a
/// error message is returned.
/// </remarks>
/// <example>
/// Post a file to a web server:
/// <code>
/// string filename = FileUtil.MapPath("/data.txt");
/// string response = WebUtil.PostFile("http://myserver/process.aspx", "data", filename, 60, "date", "20031019", "author", "ku");
/// MainUtil.Out("Response: " + response);
/// </code>
/// Outputs: <c>OK</c>
/// </example>
public static string PostFile(string url, string name, string filePath, int timeout, params string[] values)
{
Assert.ArgumentNotNull((object) url, "url");
Assert.ArgumentNotNull((object) name, "name");
Assert.ArgumentNotNull((object) filePath, "filePath");
Assert.ArgumentNotNull((object) values, "values");
wwHttp wwHttp = new wwHttp() { PostMode = 2, Timeout = timeout };
wwHttp.AddPostFile(name, FileUtil.MapPath(filePath));
int index = 0;
while (index < values.Length - 1)
{
wwHttp.AddPostKey(values[index], values[index + 1]);
index += 2;
}
string url1 = wwHttp.GetUrl(url);
if (!wwHttp.Error)
return url1;
return string.Format("##Error: {0}", (object) wwHttp.ErrorMsg);
}
/// <summary>Posts data to a web page.</summary>
/// <param name="url">An URL path to post to.</param>
/// <param name="formData">List of alternating names and values.</param>
/// <returns>The content of the web page.</returns>
/// <remarks>
/// The values are URL encoded before posting. The parameters are sent as ASCII encoded.
/// <seealso cref="T:System.Net.WebRequest" />
/// </remarks>
public static string PostWebPage(string url, ArrayList formData)
{
Assert.ArgumentNotNull((object) url, "url");
Assert.ArgumentNotNull((object) formData, "formData");
HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create(url);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.UserAgent = HttpContext.Current.Request.Headers["User-Agent"];
string s = string.Empty;
int index = 0;
while (index < formData.Count - 1)
{
s += string.Format("{0}={1}{2}", formData[index], (object) HttpUtility.UrlEncode(formData[index + 1] as string), (object) '&');
index += 2;
}
if (s.Length > 0)
s = s.Substring(0, s.Length - 1);
byte[] bytes = Encoding.ASCII.GetBytes(s);
if (bytes.Length <= 0)
return string.Empty;
httpWebRequest.ContentLength = (long) bytes.Length;
Stream requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
WebResponse response = httpWebRequest.GetResponse();
Assert.IsNotNull((object) response, "response");
Stream responseStream = response.GetResponseStream();
Assert.IsNotNull((object) responseStream, "response stream");
return new StreamReader(responseStream).ReadToEnd().Trim();
}
/// <summary>Posts the web page to W3.ORG validation service.</summary>
/// <param name="webPage">The web page.</param>
/// <returns>The page with validation result.</returns>
public static string PostWebPageToW3ValidationService(string webPage)
{
Assert.ArgumentNotNull((object) webPage, "webPage");
string str = HttpContext.Current == null ? string.Empty : HttpContext.Current.Request.Headers["User-Agent"];
string[][] strArray1 = new string[1][]{ new string[2]{ "fragment", webPage } };
HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create(Settings.HtmlEditor.ValidatorServiceUrl);
httpWebRequest.ContentType = "multipart/form-data; boundary=" + WebUtil.Boundary;
httpWebRequest.Method = "POST";
httpWebRequest.UserAgent = str;
StringBuilder stringBuilder = new StringBuilder();
foreach (string[] strArray2 in strArray1)
{
stringBuilder.AppendLine("--" + WebUtil.Boundary);
stringBuilder.AppendLine("Content-Disposition: form-data; name=\"" + strArray2[0] + "\"");
stringBuilder.AppendLine(string.Empty);
stringBuilder.AppendLine(strArray2[1]);
}
stringBuilder.AppendLine("--" + WebUtil.Boundary + "--");
byte[] bytes = Encoding.UTF8.GetBytes(stringBuilder.ToString());
if (bytes.Length <= 0)
return string.Empty;
httpWebRequest.ContentLength = (long) bytes.Length;
Stream requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
WebResponse response = httpWebRequest.GetResponse();
Assert.IsNotNull((object) response, "response");
Stream responseStream = response.GetResponseStream();
Assert.IsNotNull((object) responseStream, "response stream");
string html = new StreamReader(responseStream).ReadToEnd().Trim();
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(html);
HtmlNode elementbyId = htmlDocument.GetElementbyId("results");
if (elementbyId != null)
return elementbyId.OuterHtml;
return html;
}
/// <summary>Redirects to another page.</summary>
/// <param name="path">The path to redirect.</param>
public static void Redirect(string path)
{
Assert.ArgumentNotNull((object) path, "path");
WebUtil.Redirect(path, true);
}
/// <summary>Redirects to another page.</summary>
/// <param name="path">The path to redirect.</param>
/// <param name="allowSame">if set to <c>true</c> this instance is allow same.</param>
public static void Redirect(string path, bool allowSame)
{
Assert.ArgumentNotNull((object) path, "path");
HttpContext current = HttpContext.Current;
if (current == null || !allowSame && WebUtil.IsOnPage(path))
return;
current.Response.Redirect(path, true);
}
/// <summary>Redirects to the error page.</summary>
/// <param name="text">The text to show on error page.</param>
public static void RedirectToErrorPage(string text)
{
Assert.ArgumentNotNull((object) text, "text");
WebUtil.RedirectToErrorPage(text, true);
}
/// <summary>Redirects to the error page.</summary>
/// <param name="text">The text to show on error page.</param>
/// <param name="allowSame">if set to <c>true</c> this instance is allow same.</param>
public static void RedirectToErrorPage(string text, bool allowSame)
{
Assert.ArgumentNotNull((object) text, "text");
HttpServerUtility server = WebUtil.GetServer();
if (server == null)
return;
WebUtil.Redirect(string.Format("{0}?error={1}", (object) Settings.ErrorPage, (object) server.UrlEncode(text)), allowSame);
}
/// <summary>Redirects to the login page for current context</summary>
public static void RedirectToLoginPage()
{
WebUtil.RedirectToLoginPage(HttpContext.Current);
}
/// <summary>Redirects to the login page.</summary>
/// <param name="httpContext">The HTTP context.</param>
public static void RedirectToLoginPage(HttpContext httpContext)
{
Assert.ArgumentNotNull((object) httpContext, "httpContext");
WebUtil.RedirectToLoginPage(httpContext, (List<string>) null);
}
/// <summary>Redirects to login page.</summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="queryParametersToRemove">The query parameters to remove.</param>
public static void RedirectToLoginPage(HttpContext httpContext, List<string> queryParametersToRemove)
{
Assert.ArgumentNotNull((object) httpContext, "httpContext");
UrlString url = new UrlString(WebUtil.GetQueryString());
WebUtil.RemoveQueryParameters(url, queryParametersToRemove);
SiteContext site = Context.Site;
if (site != null && site.LoginPage.Length > 0)
{
url.Path = site.LoginPage;
httpContext.Response.Redirect(url.ToString(), true);
}
Error.Raise("No login page specified for current site: " + (site != null ? site.Name : "(unknown)"));
}
/// <summary>Reloads the current page.</summary>
/// <remarks>
/// The page reloads by redirecting to the URL of the current Sitecore item.
/// The current Sitecore item is located in
/// <see cref="P:Sitecore.Context.Item">Context.Item</see>.
/// </remarks>
/// <example>
/// <code>
/// WebUtil.ReloadPage();
/// </code>
/// <seealso cref="M:System.Web.HttpResponse.Redirect(System.String)" />
/// <seealso cref="P:Sitecore.Context.Item" />
/// </example>
public static void ReloadPage()
{
HttpContext current = HttpContext.Current;
if (current == null)
return;
Assert.IsNotNull((object) Context.Item, "context item");
current.Response.Redirect(LinkManager.GetItemUrl(Context.Item), true);
}
/// <summary>Removes the inline scripts.</summary>
/// <param name="content">The content.</param>
/// <returns>The value without inline scripts.</returns>
public static string RemoveAllScripts(string content)
{
return WebUtil.RemoveScripts(content, true, true, true);
}
/// <summary>Removes the inline scripts.</summary>
/// <param name="content">The content.</param>
/// <returns>The value without inline scripts.</returns>
public static string RemoveInlineScripts(string content)
{
return WebUtil.RemoveScripts(content, false, true, true);
}
/// <summary>Removes an object from the current items.</summary>
/// <param name="key">The key to remove.</param>
public static void RemoveItemsValue(string key)
{
Assert.ArgumentNotNull((object) key, "key");
HttpContext current = HttpContext.Current;
if (current == null || current.Session == null)
return;
current.Items.Remove((object) key);
}
/// <summary>Removes the query string from a Url.</summary>
/// <param name="url">The URL to remove.</param>
/// <returns>The remove query string.</returns>
public static string RemoveQueryString(string url)
{
Assert.ArgumentNotNull((object) url, "url");
int length = url.IndexOf('?');
if (length <= 0)
return url;
return url.Substring(0, length);
}
/// <summary>Removes an object from the current session.</summary>
/// <param name="key">The key to remove.</param>
public static void RemoveSessionValue(string key)
{
Assert.ArgumentNotNull((object) key, "key");
HttpContext current = HttpContext.Current;
if (current == null || current.Session == null)
return;
current.Session.Remove(key);
}
/// <summary>Replaces the control.</summary>
/// <param name="oldControl">The old control.</param>
/// <param name="newControl">The new control.</param>
public static void ReplaceControl(Control oldControl, Control newControl)
{
Assert.ArgumentNotNull((object) oldControl, "oldControl");
Assert.ArgumentNotNull((object) newControl, "newControl");
Control parent = oldControl.Parent;
int index = parent.Controls.IndexOf(oldControl);
Error.Assert(index >= 0, "Could not find control to be replaced.");
parent.Controls.Remove(oldControl);
parent.Controls.AddAt(index, newControl);
}
/// <summary>Replaces the URL parameter.</summary>
/// <param name="url">The URL to replace.</param>
/// <param name="replace">The replace.</param>
/// <param name="withtext">The withtext.</param>
/// <param name="append">if set to <c>true</c> this instance is append.</param>
/// <returns>The replace url parameter.</returns>
public static string ReplaceUrlParameter(string url, string replace, string withtext, bool append)
{
Assert.ArgumentNotNull((object) url, "url");
Assert.ArgumentNotNull((object) replace, "replace");
Assert.ArgumentNotNull((object) withtext, "withtext");
int num1 = url.IndexOf(string.Format("&{0}=", (object) replace), StringComparison.InvariantCulture);
if (num1 < 0)
num1 = url.IndexOf(string.Format("?{0}=", (object) replace), StringComparison.InvariantCulture);
if (num1 >= 0)
{
int num2 = url.IndexOf("&", num1 + 1, StringComparison.InvariantCulture);
int startIndex = num2 < 0 ? url.Length : num2;
url = string.Format("{0}{1}={2}{3}", (object) url.Substring(0, num1 + 1), (object) replace, (object) withtext, (object) url.Substring(startIndex));
}
else if (append)
url += string.Format("{0}{1}={2}", url.IndexOf("?", StringComparison.InvariantCulture) >= 0 ? (object) "&" : (object) "?", (object) replace, (object) withtext);
return url;
}
/// <summary>Rewrites the current URL.</summary>
/// <param name="pathAndQuery">The path and query.</param>
public static void RewriteUrl(string pathAndQuery)
{
Assert.ArgumentNotNull((object) pathAndQuery, "pathAndQuery");
HttpContext current = HttpContext.Current;
if (current == null)
return;
Uri uri = new Uri(FileUtil.MakePath(WebUtil.GetServerUrl(), pathAndQuery, '/'));
current.RewritePath(WebUtil.GetPath(uri), WebUtil.GetPathInfo(uri), WebUtil.GetQueryString(uri));
}
/// <summary>
/// Encodes user input so that it is safe to use as output. Use to prevent XSS attacks.
/// </summary>
/// <param name="value">The value to encode.</param>
/// <returns>The safe encode.</returns>
public static string SafeEncode(string value)
{
Assert.ArgumentNotNull((object) value, "value");
if (value.IndexOfAny(new char[8]{ '<', '>', '(', ')', '#', '&', '"', '\'' }) < 0)
return value;
StringBuilder stringBuilder = new StringBuilder();
foreach (char ch in value)
{
switch (ch)
{
case '"':
stringBuilder.Append("&quot;");
break;
case '#':
stringBuilder.Append("&#35;");
break;
case '&':
stringBuilder.Append("&#38;");
break;
case '\'':
stringBuilder.Append("&#x27;");
break;
case '(':
stringBuilder.Append("&#40;");
break;
case ')':
stringBuilder.Append("&#41;");
break;
case '<':
stringBuilder.Append("&lt;");
break;
case '>':
stringBuilder.Append("&gt;");
break;
default:
stringBuilder.Append(ch);
break;
}
}
return stringBuilder.ToString();
}
/// <summary>Sets a boolean value in a cookie.</summary>
/// <param name="cookieName">Name of a cookie.</param>
/// <param name="cookieValue">A boolean value.</param>
/// <example>
/// <code>
/// WebUtil.SetCookieBool("myCookie", true);
/// </code>
/// <seealso cref="T:System.Web.HttpCookie" />
/// </example>
public static void SetCookieBool(string cookieName, bool cookieValue)
{
Assert.ArgumentNotNull((object) cookieName, "cookieName");
WebUtil.SetCookieValue(cookieName, cookieValue.ToString());
}
/// <summary>Sets a date/time value in a cookie.</summary>
/// <param name="cookieName">Name of a cookie.</param>
/// <param name="cookieValue">A date/time value.</param>
/// <remarks>
/// The date/time is converted to UTC and is saved in ISO format.
/// </remarks>
/// <example>
/// <code>
/// WebUtil.SetCookieDateTime("myCookie", DateTime.UtcNow);
/// </code>
/// <seealso cref="T:System.Web.HttpCookie" />
/// <seealso cref="M:Sitecore.DateUtil.ToIsoDate(System.DateTime)" />
/// </example>
public static void SetCookieDateTime(string cookieName, DateTime cookieValue)
{
Assert.ArgumentNotNull((object) cookieName, "cookieName");
WebUtil.SetCookieValue(cookieName, DateUtil.ToIsoDate(DateUtil.ToUniversalTime(cookieValue)));
}
/// <summary>Sets a string value in a cookie.</summary>
/// <param name="cookieName">Name of a cookie.</param>
/// <param name="cookieValue">A string value.</param>
/// <example>
/// <code>
/// WebUtil.SetCookieValue("myCookie", "myValue");
/// </code>
/// <seealso cref="T:System.Web.HttpCookie" />
/// </example>
public static void SetCookieValue(string cookieName, string cookieValue)
{
Assert.ArgumentNotNull((object) cookieName, "cookieName");
Assert.ArgumentNotNull((object) cookieValue, "cookieValue");
WebUtil.SetCookieValue(cookieName, cookieValue, DateTime.MinValue);
}
/// <summary>Sets a string value in a cookie.</summary>
/// <param name="cookieName">Name of a cookie.</param>
/// <param name="cookieValue">A string value.</param>
/// <param name="expiryDate">The expiry date for the cookie.</param>
/// <example>
/// <code>
/// WebUtil.SetCookieValue("myCookie", "myValue");
/// </code>
/// <seealso cref="T:System.Web.HttpCookie" />
/// </example>
public static void SetCookieValue(string cookieName, string cookieValue, DateTime expiryDate)
{
WebUtil.SetCookieValue(cookieName, cookieValue, expiryDate, false);
}
/// <summary>Sets the cookie value.</summary>
/// <param name="cookieName">Name of the cookie.</param>
/// <param name="cookieValue">The cookie value.</param>
/// <param name="expiryDate">The expiry date.</param>
/// <param name="httpOnly">if set to <c>true</c> [HTTP only].</param>
public static void SetCookieValue(string cookieName, string cookieValue, DateTime expiryDate, bool httpOnly)
{
Assert.ArgumentNotNull((object) cookieName, "cookieName");
expiryDate = DateUtil.ToUniversalTime(expiryDate);
HttpContext current = HttpContext.Current;
if (current == null)
return;
WebUtil.SaveOriginalCookieValue(cookieName, current);
HttpCookie cookie = new HttpCookie(cookieName, cookieValue);
cookie.HttpOnly = httpOnly;
if (expiryDate != DateTime.MinValue)
cookie.Expires = expiryDate;
if (current.Response.Cookies[cookieName] != null)
current.Response.Cookies.Remove(cookieName);
current.Response.Cookies.Add(cookie);
}
/// <summary>Sets an attribute value on an HTML control.</summary>
/// <param name="control">An HTML control.</param>
/// <param name="attribute">Name of an attribute.</param>
/// <param name="value">Value of the attribute.</param>
/// <remarks>
/// The attribute is not set, if the value is null or blank.
/// </remarks>
/// <example>
/// <code>
/// WebUtil.SetHtmlAttribute(control, "myAttribute", "myValue");
/// </code>
/// <seealso cref="T:System.Web.UI.HtmlControls.HtmlControl" />
/// </example>
public static void SetHtmlAttribute(HtmlControl control, string attribute, string value)
{
Assert.ArgumentNotNull((object) control, "control");
Assert.ArgumentNotNull((object) attribute, "attribute");
if (string.IsNullOrEmpty(value))
return;
control.Attributes[attribute] = value;
}
/// <summary>Sets an object in the Items collection.</summary>
/// <param name="key">Name of the value.</param>
/// <param name="value">An object.</param>
/// <example>
/// <code>
/// object myValue;
/// WebUtil.SetItemsValue("myKey", myValue);
/// </code>
/// <seealso cref="P:System.Web.HttpContext.Items" />
/// </example>
public static void SetItemsValue(string key, object value)
{
Assert.ArgumentNotNull((object) key, "key");
Context.Items[key] = value;
}
/// <summary>Sets the session timeout.</summary>
/// <param name="timeout">The timeout.</param>
public static void SetSessionTimeout(TimeSpan timeout)
{
HttpContext current = HttpContext.Current;
if (current == null || current.Session == null)
return;
current.Session.Timeout = (int) timeout.TotalMinutes;
}
/// <summary>Sets an object value in the current session.</summary>
/// <param name="key">Name of the object value.</param>
/// <param name="value">An object.</param>
/// <example>
/// <code>
/// object myValue;
/// WebUtil.SetSessionValue("myKey", myValue);
/// </code>
/// <seealso cref="T:System.Web.SessionState.HttpSessionState" />
/// </example>
public static void SetSessionValue(string key, object value)
{
Assert.ArgumentNotNull((object) key, "key");
HttpContext current = HttpContext.Current;
if (current == null || current.Session == null)
return;
current.Session[key] = value;
}
/// <summary>Checks wether url should be ingored.</summary>
/// <param name="url">The url.</param>
/// <returns>Value that indicates wether url should be ignore.</returns>
public static bool ShouldIgnoreUrl(string url)
{
Assert.ArgumentNotNull((object) url, "url");
return ((IEnumerable<string>) Settings.IgnoreUrlPrefixes).Any<string>((Func<string, bool>) (prefix => url.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)));
}
/// <summary>Show a control tree.</summary>
/// <param name="control">The control.</param>
/// <param name="indent">The indent.</param>
public static void ShowControlTree(Control control, int indent)
{
Assert.ArgumentNotNull((object) control, "control");
string str = string.Empty;
if (control.GetType().Name == "GenericControl")
str = string.Format("({0})", ReflectionUtil.GetProperty((object) control, "TagName"));
if (control is LiteralControl)
str = string.Format("({0})", (object) (control as LiteralControl).Text);
MainUtil.Out(string.Format("{0}{1} {2}", (object) StringUtil.Repeat("&nbsp;&nbsp;", indent), (object) control.GetType().FullName, (object) str));
foreach (Control control1 in control.Controls)
WebUtil.ShowControlTree(control1, indent + 2);
}
/// <summary>
/// Writes a stream to the output stream of the HTTP response object.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="response">The response object.</param>
/// <param name="blockSize">Size of individual blocks that will be transmitted.</param>
public static void TransmitStream(Stream stream, HttpResponse response, int blockSize)
{
Assert.ArgumentNotNull((object) stream, "stream");
Assert.ArgumentNotNull((object) response, "response");
if (stream.Length == 0L)
return;
if (stream is FileStream)
{
try
{
response.TransmitFile(((FileStream) stream).Name);
return;
}
catch (IOException ex)
{
}
}
if (stream.CanSeek)
stream.Seek(0L, SeekOrigin.Begin);
byte[] buffer = new byte[blockSize];
while (true)
{
int count = stream.Read(buffer, 0, blockSize);
if (count != 0)
{
response.OutputStream.Write(buffer, 0, count);
try
{
response.Flush();
}
catch
{
response.End();
}
}
else
break;
}
}
/// <summary>
/// Tries to get value of <code>If-Modified-Since</code> HTTP header.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="ifModifiedSince">The parsed value of <code>If-Modified-Since</code> HTTP header.</param>
/// <returns>
/// Boolean value indicating whether attempt to parse value of <code>If-Modified-Since</code> HTTP header was successful.
/// </returns>
public static bool TryGetValueOfIfModifiedSinceHeader(HttpRequest request, out DateTime ifModifiedSince)
{
Assert.ArgumentNotNull((object) request, "request");
return WebUtil.TryParseHttpDateTime(request.Headers["If-Modified-Since"] ?? string.Empty, out ifModifiedSince);
}
/// <summary>Tries to parse HTTP date/time.</summary>
/// <param name="dateTimeValue">The string representation of date/time.</param>
/// <param name="dateTime">The parsed HTTP date/time.</param>
/// <returns>
/// Boolean value indicating whether attempt to parse HTTP date/time was successful.
/// </returns>
public static bool TryParseHttpDateTime(string dateTimeValue, out DateTime dateTime)
{
Assert.ArgumentNotNull((object) dateTimeValue, "dateTimeValue");
dateTimeValue = dateTimeValue.Replace(" UTC", " GMT");
CultureInfo invariantCulture = CultureInfo.InvariantCulture;
bool flag = DateTime.TryParse(dateTimeValue, (IFormatProvider) invariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out dateTime) || DateTime.TryParseExact(dateTimeValue, "ddd MMM dd HH:mm:ss yyyy", (IFormatProvider) invariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out dateTime) || DateTime.TryParseExact(dateTimeValue, "ddd MMM d HH:mm:ss yyyy", (IFormatProvider) invariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out dateTime);
if (!flag)
dateTime = DateTimeOffset.MinValue.UtcDateTime;
return flag;
}
/// <summary>
/// Calls the Uri.EscapeDataString method and then replaces single quotes with "%27" entity.
/// </summary>
/// <param name="input">The input.</param>
/// <returns></returns>
public static string UriEscapeDataString(string input)
{
Assert.ArgumentNotNull((object) input, "input");
return Uri.EscapeDataString(input).Replace("'", "%27");
}
/// <summary>
/// Calls the HttpUtility.UrlEncode method and then replaces single quotes with "%27" entity.
/// </summary>
/// <param name="input">The input.</param>
/// <returns></returns>
public static string UrlEncode(string input)
{
Assert.ArgumentNotNull((object) input, "input");
return HttpUtility.UrlEncode(input).Replace("'", "%27");
}
/// <summary>Sanitizes CSS expression in input string.</summary>
/// <param name="input">The input.</param>
/// <returns>Processed input.</returns>
private static string SanitizeCssExpression(string input)
{
MatchCollection matchCollection = WebUtil.cssExpressionPattern.Matches(input);
for (int index = matchCollection.Count - 1; index >= 0; --index)
input = WebUtil.SanitizeExpression(input, matchCollection[index]);
return input;
}
/// <summary>Sanitizes the expression.</summary>
/// <param name="input">The input.</param>
/// <param name="m">The m.</param>
/// <returns></returns>
private static string SanitizeExpression(string input, Match m)
{
int index1 = m.Groups["cssRule"].Index;
int index2 = m.Groups["bracket"].Index;
input = WebUtil.StripMatchingBracketsWithContent(input, index2);
input = input.Remove(index1, index2 - index1);
if ((int) input[index1] == 59)
input = input.Remove(index1, 1);
return input;
}
/// <summary>Sanitizes in pair chars.</summary>
/// <param name="input">The input.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="currentChar">The current char.</param>
/// <returns></returns>
private static string SanitizeInPairChars(string input, int startIndex, char currentChar)
{
Regex regex = new Regex(((int) currentChar).ToString() + ".*?(?<!\\\\)" + (object) currentChar);
string input1 = input.Substring(startIndex);
input = input.Substring(0, startIndex) + regex.Replace(input1, string.Empty, 1);
return input;
}
/// <summary>Strips matching brackets with content.</summary>
/// <param name="input">The input.</param>
/// <param name="startIndex">The start index.</param>
/// <returns></returns>
private static string StripMatchingBracketsWithContent(string input, int startIndex)
{
int num = 0;
do
{
char currentChar = input[startIndex];
switch (currentChar)
{
case '"':
case '\'':
case '/':
input = WebUtil.SanitizeInPairChars(input, startIndex, currentChar);
currentChar = input[startIndex];
break;
}
input = input.Remove(startIndex, 1);
if ((int) currentChar == 40)
++num;
else if ((int) currentChar == 41)
--num;
}
while (num > 0 && input.Length > startIndex);
return input;
}
/// <summary>Removes the specified query parameters.</summary>
/// <param name="url">The URL to remove query parameters from.</param>
/// <param name="queryParametersToRemove">The query parameters to remove.</param>
internal static void RemoveQueryParameters(UrlString url, List<string> queryParametersToRemove)
{
Assert.ArgumentNotNull((object) url, "url");
if (queryParametersToRemove == null || queryParametersToRemove.Count <= 0)
return;
foreach (string name in queryParametersToRemove)
{
if (!string.IsNullOrEmpty(name))
url.Parameters.Remove(name);
}
}
/// <summary>Find all controls of specific type</summary>
/// <param name="type">The type to search for.</param>
/// <param name="parentControl">The parent control.</param>
/// <param name="list">The result list.</param>
private static void FindControlsOfType(Type type, Control parentControl, ArrayList list)
{
Assert.ArgumentNotNull((object) type, "type");
Assert.ArgumentNotNull((object) parentControl, "parentControl");
Assert.ArgumentNotNull((object) list, "list");
if (MainUtil.IsType((object) parentControl, type))
list.Add((object) parentControl);
foreach (Control control in parentControl.Controls)
WebUtil.FindControlsOfType(type, control, list);
}
/// <summary>Finds a placeholder.</summary>
/// <param name="id">The ID to search for.</param>
/// <param name="placeholderType">Type of the placeholder.</param>
/// <returns>The placeholder.</returns>
private static Control FindPlaceholder(string id, Type placeholderType)
{
Assert.ArgumentNotNull((object) id, "id");
Assert.ArgumentNotNull((object) placeholderType, "placeholderType");
Page handler = HttpContext.Current.Handler as Page;
if (handler != null)
{
Control controlOfType = WebUtil.FindControlOfType((Control) handler, placeholderType, id);
if (controlOfType != null)
return controlOfType;
if (id.Length == 0)
return WebUtil.FindControlOfType((Control) handler, placeholderType);
}
return (Control) null;
}
/// <summary>Finds the sub control.</summary>
/// <param name="parent">The parent.</param>
/// <param name="name">The control name to search for.</param>
/// <returns>The sub control.</returns>
private static Control FindSubControl(Control parent, string name)
{
Assert.ArgumentNotNull((object) parent, "parent");
Assert.ArgumentNotNull((object) name, "name");
foreach (Control control1 in parent.Controls)
{
Control control2 = control1 is UserControl ? WebUtil.FindControl(control1, name) : WebUtil.FindSubControl(control1, name);
if (control2 != null)
return control2;
}
return (Control) null;
}
/// <summary>Find all sub controls of specific type.</summary>
/// <typeparam name="T">Type parameter.</typeparam>
/// <param name="parentControl">The parent control.</param>
/// <param name="result">The result.</param>
private static void FindSubControls<T>(Control parentControl, List<T> result) where T : Control
{
Assert.ArgumentNotNull((object) parentControl, "parentControl");
Assert.ArgumentNotNull((object) result, "result");
foreach (T control in parentControl.Controls)
{
if (typeof (T).IsAssignableFrom(control.GetType()))
result.Add(control);
WebUtil.FindSubControls<T>((Control) control, result);
}
}
/// <summary>Gets the path.</summary>
/// <param name="uri">The URI to get path from.</param>
/// <returns>The get path.</returns>
private static string GetPath(Uri uri)
{
Assert.ArgumentNotNull((object) uri, "uri");
string path = HttpUtility.UrlDecode(uri.AbsolutePath);
if (string.IsNullOrEmpty(path))
return string.Empty;
if (WebUtil.HasExtension(path))
{
string pathInfo = WebUtil.GetPathInfo(uri);
if (pathInfo.Length > 0)
path = path.Substring(0, path.Length - pathInfo.Length);
}
return path;
}
/// <summary>Gets the path info.</summary>
/// <param name="uri">The URI to get path from.</param>
/// <returns>The get path info.</returns>
private static string GetPathInfo(Uri uri)
{
Assert.ArgumentNotNull((object) uri, "uri");
string absolutePath = uri.AbsolutePath;
int startIndex1 = absolutePath.LastIndexOf('.');
if (startIndex1 < 0)
return string.Empty;
int startIndex2 = absolutePath.IndexOf('/', startIndex1);
if (startIndex2 >= 0)
return absolutePath.Substring(startIndex2);
return string.Empty;
}
/// <summary>Gets the query string.</summary>
/// <param name="uri">The URI to get path from.</param>
/// <returns>The get query string.</returns>
private static string GetQueryString(Uri uri)
{
Assert.ArgumentNotNull((object) uri, "uri");
string query = uri.Query;
if (string.IsNullOrEmpty(query))
return string.Empty;
if ((int) query[0] != 63)
return query;
return query.Substring(1);
}
/// <summary>Gets the name of the session ID cookie.</summary>
/// <returns>The get session ID cookie name.</returns>
private static string GetSessionIdCookieName()
{
if (WebUtil.sessionIdCookieName != null)
return WebUtil.sessionIdCookieName;
WebUtil.sessionIdCookieName = WebUtil.GetSessionIdCookieNameFromConfig() ?? "ASP.NET_SessionId";
return WebUtil.sessionIdCookieName;
}
/// <summary>Gets the session ID cookie name from config.</summary>
/// <returns>The get session ID cookie name from config.</returns>
private static string GetSessionIdCookieNameFromConfig()
{
try
{
string applicationVirtualPath = HostingEnvironment.ApplicationVirtualPath;
if (string.IsNullOrEmpty(applicationVirtualPath))
return (string) null;
SessionStateSection section = WebConfigurationManager.OpenWebConfiguration(applicationVirtualPath).GetSection("system.web/sessionState") as SessionStateSection;
return section == null ? (string) null : section.CookieName;
}
catch
{
return (string) null;
}
}
/// <summary>
/// Determines whether the specified path has extension.
/// </summary>
/// <param name="path">The path to check extension for.</param>
/// <returns>
/// <c>true</c> if the specified path has extension; otherwise, <c>false</c>.
/// </returns>
private static bool HasExtension(string path)
{
Assert.ArgumentNotNull((object) path, "path");
return path.IndexOf('.') >= 0;
}
/// <summary>Removes the scripts.</summary>
/// <param name="content">The content.</param>
/// <param name="removeScriptTags">if set to <c>true</c> [remove script tags].</param>
/// <param name="removeInlineScripts">if set to <c>true</c> [remove inline scripts].</param>
/// <param name="removeCssExpressions">if set to <c>true</c> [remove CSS expressions].</param>
/// <returns></returns>
private static string RemoveScripts(string content, bool removeScriptTags, bool removeInlineScripts, bool removeCssExpressions)
{
string input = string.Empty;
if (string.IsNullOrWhiteSpace(content))
return input;
List<string> cdatas = new List<string>();
content = Regex.Replace(content, "<!\\[CDATA\\[.*?\\]\\]>", (MatchEvaluator) (match =>
{
cdatas.Add(match.Value);
return "<cdata_sc" + (object) cdatas.Count + "></cdata_sc" + (object) cdatas.Count + ">";
}));
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(content);
HtmlNodeCollection htmlNodeCollection = htmlDocument.DocumentNode.SelectNodes("//*");
if (htmlNodeCollection != null)
{
for (int index1 = 0; index1 < htmlNodeCollection.Count; ++index1)
{
HtmlNode htmlNode = htmlNodeCollection[index1];
if (htmlNode != null)
{
if (removeScriptTags && htmlNode.Name == "script")
htmlNode.Remove();
else if (removeInlineScripts)
{
if (htmlNode.Attributes["allowscriptaccess"] != null)
htmlNode.Attributes["allowscriptaccess"].Remove();
if (htmlNode.Attributes["srcdoc"] != null)
htmlNode.Attributes["srcdoc"].Remove();
for (int index2 = 0; index2 < htmlNode.Attributes.Count; ++index2)
{
HtmlAttribute attribute1 = htmlNode.Attributes[index2];
if (attribute1.Name.StartsWith("on") || attribute1.Value.Contains("javascript") || attribute1.Value.Contains("base64"))
{
HtmlAttribute attribute2 = htmlNode.Attributes[attribute1.Name];
if (attribute2 != null)
attribute2.Remove();
}
}
}
}
}
}
using (StringWriter stringWriter = new StringWriter())
{
htmlDocument.OptionWriteEmptyNodes = true;
htmlDocument.Save((TextWriter) stringWriter);
input = stringWriter.ToString();
}
for (int index = 0; index < cdatas.Count; ++index)
{
int i1 = index;
input = Regex.Replace(input, "<cdata_sc" + (object) (index + 1) + "></cdata_sc" + (object) (index + 1) + ">", (MatchEvaluator) (match => cdatas[i1]));
}
if (removeCssExpressions)
input = WebUtil.SanitizeCssExpression(input);
return input;
}
/// <summary>
/// Saves the original cookie value in the HttpContext.Items collection.
/// </summary>
/// <param name="cookieName">Name of the cookie.</param>
/// <param name="context">The context.</param>
private static void SaveOriginalCookieValue(string cookieName, HttpContext context)
{
Assert.ArgumentNotNull((object) cookieName, "cookieName");
Assert.ArgumentNotNull((object) context, "context");
string str = string.Format("{0}_{1}", (object) "WebUtil_OriginalCookieValue", (object) cookieName);
if (context.Items.Contains((object) str))
return;
HttpCookie cookie = context.Request.Cookies[cookieName];
context.Items[(object) str] = cookie != null ? (object) cookie.Value : new object();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment