<commit_before>﻿using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Xml.Linq;
using System.Xml.XPath;
using HtmlAgilityPack;
using Umbraco.Core;
using Umbraco.Core.Dictionary;
using Umbraco.Core.Dynamics;
using Umbraco.Core.Models;
using Umbraco.Web.Models;
using Umbraco.Web.PublishedCache;
using Umbraco.Web.Templates;
using umbraco;
using System.Collections.Generic;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.web;
using umbraco.presentation.templateControls;

namespace Umbraco.Web
{

	/// <summary>
	/// A helper class that provides many useful methods and functionality for using Umbraco in templates
	/// </summary>
	public class UmbracoHelper
	{
		private readonly UmbracoContext _umbracoContext;
		private readonly IPublishedContent _currentPage;

		/// <summary>
		/// Custom constructor setting the current page to the parameter passed in
		/// </summary>
		/// <param name="umbracoContext"></param>
		/// <param name="content"></param>
		public UmbracoHelper(UmbracoContext umbracoContext, IPublishedContent content)
			: this(umbracoContext)
		{			
			if (content == null) throw new ArgumentNullException("content");
			_currentPage = content;
		}

		/// <summary>
		/// Standard constructor setting the current page to the page that has been routed to
		/// </summary>
		/// <param name="umbracoContext"></param>
		public UmbracoHelper(UmbracoContext umbracoContext)
		{
			if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
			if (umbracoContext.RoutingContext == null) throw new NullReferenceException("The RoutingContext on the UmbracoContext cannot be null");
			_umbracoContext = umbracoContext;
			if (_umbracoContext.IsFrontEndUmbracoRequest)
			{
				_currentPage = _umbracoContext.PublishedContentRequest.PublishedContent;
			}
		}

        /// <summary>
        /// Returns the current IPublishedContent item assigned to the UmbracoHelper
        /// </summary>
        /// <remarks>
        /// Note that this is the assigned IPublishedContent item to the UmbracoHelper, this is not necessarily the Current IPublishedContent item
        /// being rendered. This IPublishedContent object is contextual to the current UmbracoHelper instance.
        /// 
        /// In some cases accessing this property will throw an exception if there is not IPublishedContent assigned to the Helper
        /// this will only ever happen if the Helper is constructed with an UmbracoContext and it is not a front-end request
        /// </remarks>
        /// <exception cref="InvalidOperationException">Thrown if the UmbracoHelper is constructed with an UmbracoContext and it is not a front-end request</exception>
	    public IPublishedContent AssignedContentItem
	    {
	        get
	        {
	            if (_currentPage == null)
                    throw new InvalidOperationException("Cannot return the " + typeof(IPublishedContent).Name + " because the " + typeof(UmbracoHelper).Name + " was constructed with an " + typeof(UmbracoContext).Name + " and the current request is not a front-end request.");
                
                return _currentPage;
	        }
	    }

	    /// <summary>
		/// Renders the template for the specified pageId and an optional altTemplateId
		/// </summary>
		/// <param name="pageId"></param>
		/// <param name="altTemplateId">If not specified, will use the template assigned to the node</param>
		/// <returns></returns>
		public IHtmlString RenderTemplate(int pageId, int? altTemplateId = null)
		{
			var templateRenderer = new TemplateRenderer(_umbracoContext, pageId, altTemplateId);
			using (var sw = new StringWriter())
			{
				try
				{
					templateRenderer.Render(sw);					
				}
				catch(Exception ex)
				{
					sw.Write("<!-- Error rendering template with id {0}: '{1}' -->", pageId, ex);
				}
				return new HtmlString(sw.ToString());	
			}			
		}

		#region RenderMacro

		/// <summary>
		/// Renders the macro with the specified alias.
		/// </summary>
		/// <param name="alias">The alias.</param>
		/// <returns></returns>
		public IHtmlString RenderMacro(string alias)
		{
			return RenderMacro(alias, new { });
		}

		/// <summary>
		/// Renders the macro with the specified alias, passing in the specified parameters.
		/// </summary>
		/// <param name="alias">The alias.</param>
		/// <param name="parameters">The parameters.</param>
		/// <returns></returns>
		public IHtmlString RenderMacro(string alias, object parameters)
		{
			return RenderMacro(alias, parameters.ToDictionary<object>());
		}

		/// <summary>
		/// Renders the macro with the specified alias, passing in the specified parameters.
		/// </summary>
		/// <param name="alias">The alias.</param>
		/// <param name="parameters">The parameters.</param>
		/// <returns></returns>
		public IHtmlString RenderMacro(string alias, IDictionary<string, object> parameters)
		{
			if (alias == null) throw new ArgumentNullException("alias");

			var m = macro.GetMacro(alias);
			if (_umbracoContext.PageId == null)
			{
				throw new InvalidOperationException("Cannot render a macro when UmbracoContext.PageId is null.");
			}
			if (_umbracoContext.PublishedContentRequest == null)
			{
				throw new InvalidOperationException("Cannot render a macro when there is no current PublishedContentRequest.");
			}
			var macroProps = new Hashtable();
			foreach (var i in parameters)
			{
				//TODO: We are doing at ToLower here because for some insane reason the UpdateMacroModel method of macro.cs 
				// looks for a lower case match. WTF. the whole macro concept needs to be rewritten.
				macroProps.Add(i.Key.ToLower(), i.Value);
			}
			var macroControl = m.renderMacro(macroProps,
				UmbracoContext.Current.PublishedContentRequest.UmbracoPage.Elements,
				_umbracoContext.PageId.Value);

			string html;
			if (macroControl is LiteralControl)
			{
				// no need to execute, we already have text
				html = (macroControl as LiteralControl).Text;
			}
			else
			{
				var containerPage = new FormlessPage();
				containerPage.Controls.Add(macroControl);

				using (var output = new StringWriter())
				{
					// .Execute() does a PushTraceContext/PopTraceContext and writes trace output straight into 'output'
					// and I do not see how we could wire the trace context to the current context... so it creates dirty
					// trace output right in the middle of the page.
					//
					// The only thing we can do is fully disable trace output while .Execute() runs and restore afterwards
					// which means trace output is lost if the macro is a control (.ascx or user control) that is invoked
					// from within Razor -- which makes sense anyway because the control can _not_ run correctly from
					// within Razor since it will never be inserted into the page pipeline (which may even not exist at all
					// if we're running MVC).
					//
					var traceIsEnabled = containerPage.Trace.IsEnabled;
					containerPage.Trace.IsEnabled = false;
					_umbracoContext.HttpContext.Server.Execute(containerPage, output, false);
					containerPage.Trace.IsEnabled = traceIsEnabled;

					//Now, we need to ensure that local links are parsed
					html = TemplateUtilities.ParseInternalLinks(output.ToString());
				}
			}

			return new HtmlString(html);
		}

		#endregion

		#region Field

		/// <summary>
		/// Renders an field to the template
		/// </summary>
		/// <param name="fieldAlias"></param>
		/// <param name="altFieldAlias"></param>
		/// <param name="altText"></param>
		/// <param name="insertBefore"></param>
		/// <param name="insertAfter"></param>
		/// <param name="recursive"></param>
		/// <param name="convertLineBreaks"></param>
		/// <param name="removeParagraphTags"></param>
		/// <param name="casing"></param>
		/// <param name="encoding"></param>
        /// <param name="formatAsDate"></param>
        /// <param name="formatAsDateWithTime"></param>
        /// <param name="formatAsDateWithTimeSeparator"></param>
        //// <param name="formatString"></param>
		/// <returns></returns>
		public IHtmlString Field(string fieldAlias, 
			string altFieldAlias = "", string altText = "", string insertBefore = "", string insertAfter = "",
			bool recursive = false, bool convertLineBreaks = false, bool removeParagraphTags = false,
			RenderFieldCaseType casing = RenderFieldCaseType.Unchanged,
            RenderFieldEncodingType encoding = RenderFieldEncodingType.Unchanged, 
            bool formatAsDate = false, 
            bool formatAsDateWithTime = false,
            string formatAsDateWithTimeSeparator = "")

            //TODO: commented out until as it is not implemented by umbraco:item yet
            //,string formatString = "")
		{			
            return Field(AssignedContentItem, fieldAlias, altFieldAlias,
                altText, insertBefore, insertAfter, recursive, convertLineBreaks, removeParagraphTags,
                casing, encoding, formatAsDate, formatAsDateWithTime, formatAsDateWithTimeSeparator); // formatString);
		}

		/// <summary>
		/// Renders an field to the template
		/// </summary>
		/// <param name="currentPage"></param>
		/// <param name="fieldAlias"></param>
		/// <param name="altFieldAlias"></param>
		/// <param name="altText"></param>
		/// <param name="insertBefore"></param>
		/// <param name="insertAfter"></param>
		/// <param name="recursive"></param>
		/// <param name="convertLineBreaks"></param>
		/// <param name="removeParagraphTags"></param>
		/// <param name="casing"></param>
        /// <param name="encoding"></param>
        /// <param name="formatAsDate"></param>
        /// <param name="formatAsDateWithTime"></param>
        /// <param name="formatAsDateWithTimeSeparator"></param>
		//// <param name="formatString"></param>
		/// <returns></returns>
		public IHtmlString Field(IPublishedContent currentPage, string fieldAlias, 
			string altFieldAlias = "", string altText = "", string insertBefore = "", string insertAfter = "",
			bool recursive = false, bool convertLineBreaks = false, bool removeParagraphTags = false,
			RenderFieldCaseType casing = RenderFieldCaseType.Unchanged,
			RenderFieldEncodingType encoding = RenderFieldEncodingType.Unchanged, 
            bool formatAsDate =  false,
            bool formatAsDateWithTime = false,
            string formatAsDateWithTimeSeparator = "")
            
            //TODO: commented out until as it is not implemented by umbraco:item yet
            //,string formatString = "")
		{
			Mandate.ParameterNotNull(currentPage, "currentPage");
			Mandate.ParameterNotNullOrEmpty(fieldAlias, "fieldAlias");

			//TODO: This is real nasty and we should re-write the 'item' and 'ItemRenderer' class but si fine for now

			var attributes = new Dictionary<string, string>
				{
					{"field", fieldAlias},
					{"recursive", recursive.ToString().ToLowerInvariant()},
					{"useifempty", altFieldAlias},
					{"textifempty", altText},
					{"stripparagraph", removeParagraphTags.ToString().ToLowerInvariant()},
					{
						"case", casing == RenderFieldCaseType.Lower ? "lower"
						        	: casing == RenderFieldCaseType.Upper ? "upper"
						        	  	: casing == RenderFieldCaseType.Title ? "title"
						        	  	  	: string.Empty
						},
					{"inserttextbefore", insertBefore},
					{"inserttextafter", insertAfter},
					{"convertlinebreaks", convertLineBreaks.ToString().ToLowerInvariant()},
                    {"formatasdate", formatAsDate.ToString().ToLowerInvariant()},
                    {"formatasdatewithtime", formatAsDateWithTime.ToString().ToLowerInvariant()},
                    {"formatasdatewithtimeseparator", formatAsDateWithTimeSeparator}
				};
			switch (encoding)
			{
				case RenderFieldEncodingType.Url:
					attributes.Add("urlencode", "true");
					break;
				case RenderFieldEncodingType.Html:
					attributes.Add("htmlencode", "true");
					break;
				case RenderFieldEncodingType.Unchanged:
				default:
					break;
			}

			//need to convert our dictionary over to this weird dictionary type
			var attributesForItem = new AttributeCollectionAdapter(
				new AttributeCollection(
					new StateBag()));
			foreach (var i in attributes)
			{
				attributesForItem.Add(i.Key, i.Value);
			}



		    var item = new Item()
		                   {		        
		                       Field = fieldAlias,
		                       TextIfEmpty = altText,
		                       LegacyAttributes = attributesForItem
		                   };

            //this is here to figure out if this request is in the context of a partial
            if (_umbracoContext.PublishedContentRequest.PublishedContent.Id != currentPage.Id)
                item.NodeId = currentPage.Id.ToString();
            
		
			var containerPage = new FormlessPage();
			containerPage.Controls.Add(item);

			using (var output = new StringWriter())
			using (var htmlWriter = new HtmlTextWriter(output))
			{
				ItemRenderer.Instance.Init(item);
				ItemRenderer.Instance.Load(item);
				ItemRenderer.Instance.Render(item, htmlWriter);
				
				//because we are rendering the output through the legacy Item (webforms) stuff, the {localLinks} will already be replaced.
				return new HtmlString(output.ToString());
			}
		}

		#endregion

		#region Dictionary

		private ICultureDictionary _cultureDictionary;

		/// <summary>
		/// Returns the dictionary value for the key specified
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public string GetDictionaryValue(string key)
		{
			if (_cultureDictionary == null)
			{
				var factory = CultureDictionaryFactoryResolver.Current.Factory;
				_cultureDictionary = factory.CreateDictionary();
			}
			return _cultureDictionary[key];
		}

		#endregion

		#region Membership

		/// <summary>
		/// Check if a document object is protected by the "Protect Pages" functionality in umbraco
		/// </summary>
		/// <param name="documentId">The identifier of the document object to check</param>
		/// <param name="path">The full path of the document object to check</param>
		/// <returns>True if the document object is protected</returns>
		public bool IsProtected(int documentId, string path)
		{
			return Access.IsProtected(documentId, path);
		}

		/// <summary>
		/// Check if the current user has access to a document
		/// </summary>
		/// <param name="nodeId">The identifier of the document object to check</param>
		/// <param name="path">The full path of the document object to check</param>
		/// <returns>True if the current user has access or if the current document isn't protected</returns>
		public bool MemberHasAccess(int nodeId, string path)
		{
			if (IsProtected(nodeId, path))
			{
				return Member.IsLoggedOn() && Access.HasAccess(nodeId, path, Membership.GetUser());
			}
			return true;
		}

		/// <summary>
		/// Whether or not the current member is logged in (based on the membership provider)
		/// </summary>
		/// <returns>True is the current user is logged in</returns>
		public bool MemberIsLoggedOn()
		{
			/*
			   MembershipUser u = Membership.GetUser();
			   return u != null;           
			*/
			return Member.IsLoggedOn();
		} 

		#endregion

		#region NiceUrls

		/// <summary>
		/// Returns a string with a friendly url from a node.
		/// IE.: Instead of having /482 (id) as an url, you can have
		/// /screenshots/developer/macros (spoken url)
		/// </summary>
		/// <param name="nodeId">Identifier for the node that should be returned</param>
		/// <returns>String with a friendly url from a node</returns>
		public string NiceUrl(int nodeId)
		{
			var urlProvider = UmbracoContext.Current.UrlProvider;
			return urlProvider.GetUrl(nodeId);
		}

		/// <summary>
		/// This method will always add the domain to the path if the hostnames are set up correctly. 
		/// </summary>
		/// <param name="nodeId">Identifier for the node that should be returned</param>
		/// <returns>String with a friendly url with full domain from a node</returns>
		public string NiceUrlWithDomain(int nodeId)
		{
			var urlProvider = UmbracoContext.Current.UrlProvider;
			return urlProvider.GetUrl(nodeId, true);
		}

		#endregion

		#region Content

		public IPublishedContent TypedContent(object id)
		{
            return TypedDocumentById(id, _umbracoContext.ContentCache);
		}

		public IPublishedContent TypedContent(int id)
		{
            return TypedDocumentById(id, _umbracoContext.ContentCache);
		}

		public IPublishedContent TypedContent(string id)
		{
            return TypedDocumentById(id, _umbracoContext.ContentCache);
		}

		public IEnumerable<IPublishedContent> TypedContent(params object[] ids)
		{
            return TypedDocumentsbyIds(_umbracoContext.ContentCache, ids);
		}

		public IEnumerable<IPublishedContent> TypedContent(params int[] ids)
		{
            return TypedDocumentsbyIds(_umbracoContext.ContentCache, ids);
		}

		public IEnumerable<IPublishedContent> TypedContent(params string[] ids)
		{
            return TypedDocumentsbyIds(_umbracoContext.ContentCache, ids);
		}

		public IEnumerable<IPublishedContent> TypedContent(IEnumerable<object> ids)
		{
			return TypedContent(ids.ToArray());
		}

		public IEnumerable<IPublishedContent> TypedContent(IEnumerable<string> ids)
		{
			return TypedContent(ids.ToArray());
		}

		public IEnumerable<IPublishedContent> TypedContent(IEnumerable<int> ids)
		{
			return TypedContent(ids.ToArray());
		}

        public IEnumerable<IPublishedContent> TypedContentAtRoot()
        {
            return TypedDocumentsAtRoot(_umbracoContext.ContentCache);
        }

		public dynamic Content(object id)
		{
            return DocumentById(id, _umbracoContext.ContentCache, new DynamicNull());
		}

		public dynamic Content(int id)
		{
            return DocumentById(id, _umbracoContext.ContentCache, new DynamicNull());
		}

		public dynamic Content(string id)
		{
            return DocumentById(id, _umbracoContext.ContentCache, new DynamicNull());
		}

		public dynamic Content(params object[] ids)
		{
            return DocumentByIds(_umbracoContext.ContentCache, ids);
		}

		public dynamic Content(params int[] ids)
		{
            return DocumentByIds(_umbracoContext.ContentCache, ids);
		}

		public dynamic Content(params string[] ids)
		{
            return DocumentByIds(_umbracoContext.ContentCache, ids);
		}

		public dynamic Content(IEnumerable<object> ids)
		{
			return Content(ids.ToArray());
		}

		public dynamic Content(IEnumerable<int> ids)
		{
			return Content(ids.ToArray());
		}

		public dynamic Content(IEnumerable<string> ids)
		{
			return Content(ids.ToArray());
		}

        public dynamic ContentAtRoot()
        {
            return DocumentsAtRoot(_umbracoContext.ContentCache);
        }

		#endregion

		#region Media

		/// <summary>
		/// Overloaded method accepting an 'object' type
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		/// <remarks>
		/// We accept an object type because GetPropertyValue now returns an 'object', we still want to allow people to pass 
		/// this result in to this method.
		/// This method will throw an exception if the value is not of type int or string.
		/// </remarks>
		public IPublishedContent TypedMedia(object id)
		{
			return TypedDocumentById(id, _umbracoContext.MediaCache);
		}

		public IPublishedContent TypedMedia(int id)
		{
            return TypedDocumentById(id, _umbracoContext.MediaCache);
		}

		public IPublishedContent TypedMedia(string id)
		{
            return TypedDocumentById(id, _umbracoContext.MediaCache);
		}

		public IEnumerable<IPublishedContent> TypedMedia(params object[] ids)
		{
            return TypedDocumentsbyIds(_umbracoContext.MediaCache, ids);
		}

		public IEnumerable<IPublishedContent> TypedMedia(params int[] ids)
		{
            return TypedDocumentsbyIds(_umbracoContext.MediaCache, ids);
		}

		public IEnumerable<IPublishedContent> TypedMedia(params string[] ids)
		{
            return TypedDocumentsbyIds(_umbracoContext.MediaCache, ids);
		}

		public IEnumerable<IPublishedContent> TypedMedia(IEnumerable<object> ids)
		{
			return TypedMedia(ids.ToArray());
		}

		public IEnumerable<IPublishedContent> TypedMedia(IEnumerable<int> ids)
		{
			return TypedMedia(ids.ToArray());
		}

		public IEnumerable<IPublishedContent> TypedMedia(IEnumerable<string> ids)
		{
			return TypedMedia(ids.ToArray());
		}

        public IEnumerable<IPublishedContent> TypedMediaAtRoot()
        {
            return TypedDocumentsAtRoot(_umbracoContext.MediaCache);
        }

		public dynamic Media(object id)
		{
            return DocumentById(id, _umbracoContext.MediaCache, new DynamicNull());
		}

		public dynamic Media(int id)
		{
            return DocumentById(id, _umbracoContext.MediaCache, new DynamicNull());
		}

		public dynamic Media(string id)
		{
            return DocumentById(id, _umbracoContext.MediaCache, new DynamicNull());
		}

		public dynamic Media(params object[] ids)
		{
            return DocumentByIds(_umbracoContext.MediaCache, ids);
		}

		public dynamic Media(params int[] ids)
		{
            return DocumentByIds(_umbracoContext.MediaCache, ids);
		}

		public dynamic Media(params string[] ids)
		{
            return DocumentByIds(_umbracoContext.MediaCache, ids);
		}

		public dynamic Media(IEnumerable<object> ids)
		{
			return Media(ids.ToArray());
		}

		public dynamic Media(IEnumerable<int> ids)
		{
			return Media(ids.ToArray());
		}

		public dynamic Media(IEnumerable<string> ids)
		{
			return Media(ids.ToArray());
		}

        public dynamic MediaAtRoot()
        {
            return DocumentsAtRoot(_umbracoContext.MediaCache);
        }

		#endregion

		#region Used by Content/Media

		/// <summary>
		/// Overloaded method accepting an 'object' type
		/// </summary>
		/// <param name="id"></param>
		/// <param name="cache"> </param>
		/// <returns></returns>
		/// <remarks>
		/// We accept an object type because GetPropertyValue now returns an 'object', we still want to allow people to pass 
		/// this result in to this method.
		/// This method will throw an exception if the value is not of type int or string.
		/// </remarks>
        private IPublishedContent TypedDocumentById(object id, ContextualPublishedCache cache)
		{
			if (id is string)
				return TypedDocumentById((string)id, cache);
			if (id is int)
				return TypedDocumentById((int)id, cache);
			throw new InvalidOperationException("The value of parameter 'id' must be either a string or an integer");
		}

		private IPublishedContent TypedDocumentById(int id, ContextualPublishedCache cache)
		{
            var doc = cache.GetById(id);
			return doc;
		}

        private IPublishedContent TypedDocumentById(string id, ContextualPublishedCache cache)
		{
			int docId;
			return int.TryParse(id, out docId)
				       ? DocumentById(docId, cache, null)
				       : null;
		}

		/// <summary>
		/// Overloaded method accepting an 'object' type
		/// </summary>
		/// <param name="ids"></param>
		/// <param name="cache"> </param>
		/// <returns></returns>
		/// <remarks>
		/// We accept an object type because GetPropertyValue now returns an 'object', we still want to allow people to pass 
		/// this result in to this method.
		/// This method will throw an exception if the value is not of type int or string.
		/// </remarks>
        private IEnumerable<IPublishedContent> TypedDocumentsbyIds(ContextualPublishedCache cache, params object[] ids)
		{
			return ids.Select(eachId => TypedDocumentById(eachId, cache));
		}

        private IEnumerable<IPublishedContent> TypedDocumentsbyIds(ContextualPublishedCache cache, params int[] ids)
		{
			return ids.Select(eachId => TypedDocumentById(eachId, cache));
		}

        private IEnumerable<IPublishedContent> TypedDocumentsbyIds(ContextualPublishedCache cache, params string[] ids)
		{
			return ids.Select(eachId => TypedDocumentById(eachId, cache));
		}

        private IEnumerable<IPublishedContent> TypedDocumentsAtRoot(ContextualPublishedCache cache)
        {
            return cache.GetAtRoot();
        }

		/// <summary>
		/// Overloaded method accepting an 'object' type
		/// </summary>
		/// <param name="id"></param>
		/// <param name="cache"> </param>
		/// <param name="ifNotFound"> </param>
		/// <returns></returns>
		/// <remarks>
		/// We accept an object type because GetPropertyValue now returns an 'object', we still want to allow people to pass 
		/// this result in to this method.
		/// This method will throw an exception if the value is not of type int or string.
		/// </remarks>
        private dynamic DocumentById(object id, ContextualPublishedCache cache, object ifNotFound)
		{
			if (id is string)
				return DocumentById((string)id, cache, ifNotFound);
			if (id is int)
				return DocumentById((int)id, cache, ifNotFound);
			throw new InvalidOperationException("The value of parameter 'id' must be either a string or an integer");
		}

        private dynamic DocumentById(int id, ContextualPublishedCache cache, object ifNotFound)
		{
            var doc = cache.GetById(id);
			return doc == null
					? ifNotFound
					: new DynamicPublishedContent(doc).AsDynamic();
		}

        private dynamic DocumentById(string id, ContextualPublishedCache cache, object ifNotFound)
		{
			int docId;
			return int.TryParse(id, out docId)
				? DocumentById(docId, cache, ifNotFound)
				: ifNotFound;
		}

        private dynamic DocumentsAtRoot(ContextualPublishedCache cache)
        {
            return new DynamicPublishedContentList(
                cache.GetAtRoot()
                    .Select(publishedContent => new DynamicPublishedContent(publishedContent))
            );
        }

		/// <summary>
		/// Overloaded method accepting an 'object' type
		/// </summary>
		/// <param name="ids"></param>
		/// <param name="cache"> </param>
		/// <returns></returns>
		/// <remarks>
		/// We accept an object type because GetPropertyValue now returns an 'object', we still want to allow people to pass 
		/// this result in to this method.
		/// This method will throw an exception if the value is not of type int or string.
		/// </remarks>
        private dynamic DocumentByIds(ContextualPublishedCache cache, params object[] ids)
		{
			var dNull = new DynamicNull();
			var nodes = ids.Select(eachId => DocumentById(eachId, cache, dNull))
				.Where(x => !TypeHelper.IsTypeAssignableFrom<DynamicNull>(x))
				.Cast<DynamicPublishedContent>();
			return new DynamicPublishedContentList(nodes);
		}

        private dynamic DocumentByIds(ContextualPublishedCache cache, params int[] ids)
		{
			var dNull = new DynamicNull();
			var nodes = ids.Select(eachId => DocumentById(eachId, cache, dNull))
				.Where(x => !TypeHelper.IsTypeAssignableFrom<DynamicNull>(x))
				.Cast<DynamicPublishedContent>();
			return new DynamicPublishedContentList(nodes);
		}

        private dynamic DocumentByIds(ContextualPublishedCache cache, params string[] ids)
		{
			var dNull = new DynamicNull();
			var nodes = ids.Select(eachId => DocumentById(eachId, cache, dNull))
				.Where(x => !TypeHelper.IsTypeAssignableFrom<DynamicNull>(x))
				.Cast<DynamicPublishedContent>();
			return new DynamicPublishedContentList(nodes);
		}

		#endregion

		#region Search

		/// <summary>
		/// Searches content
		/// </summary>
		/// <param name="term"></param>
		/// <param name="useWildCards"></param><commit_msg>Web - cleanup UmbracoHelper XPath methods<commit_after>﻿using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Xml.Linq;
using System.Xml.XPath;
using HtmlAgilityPack;
using Umbraco.Core;
using Umbraco.Core.Dictionary;
using Umbraco.Core.Dynamics;
using Umbraco.Core.Models;
using Umbraco.Core.Xml;
using Umbraco.Web.Models;
using Umbraco.Web.PublishedCache;
using Umbraco.Web.Templates;
using umbraco;
using System.Collections.Generic;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.web;
using umbraco.presentation.templateControls;

namespace Umbraco.Web
{

	/// <summary>
	/// A helper class that provides many useful methods and functionality for using Umbraco in templates
	/// </summary>
	public class UmbracoHelper
	{
		private readonly UmbracoContext _umbracoContext;
		private readonly IPublishedContent _currentPage;

		/// <summary>
		/// Custom constructor setting the current page to the parameter passed in
		/// </summary>
		/// <param name="umbracoContext"></param>
		/// <param name="content"></param>
		public UmbracoHelper(UmbracoContext umbracoContext, IPublishedContent content)
			: this(umbracoContext)
		{			
			if (content == null) throw new ArgumentNullException("content");
			_currentPage = content;
		}

		/// <summary>
		/// Standard constructor setting the current page to the page that has been routed to
		/// </summary>
		/// <param name="umbracoContext"></param>
		public UmbracoHelper(UmbracoContext umbracoContext)
		{
			if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
			if (umbracoContext.RoutingContext == null) throw new NullReferenceException("The RoutingContext on the UmbracoContext cannot be null");
			_umbracoContext = umbracoContext;
			if (_umbracoContext.IsFrontEndUmbracoRequest)
			{
				_currentPage = _umbracoContext.PublishedContentRequest.PublishedContent;
			}
		}

        /// <summary>
        /// Returns the current IPublishedContent item assigned to the UmbracoHelper
        /// </summary>
        /// <remarks>
        /// Note that this is the assigned IPublishedContent item to the UmbracoHelper, this is not necessarily the Current IPublishedContent item
        /// being rendered. This IPublishedContent object is contextual to the current UmbracoHelper instance.
        /// 
        /// In some cases accessing this property will throw an exception if there is not IPublishedContent assigned to the Helper
        /// this will only ever happen if the Helper is constructed with an UmbracoContext and it is not a front-end request
        /// </remarks>
        /// <exception cref="InvalidOperationException">Thrown if the UmbracoHelper is constructed with an UmbracoContext and it is not a front-end request</exception>
	    public IPublishedContent AssignedContentItem
	    {
	        get
	        {
	            if (_currentPage == null)
                    throw new InvalidOperationException("Cannot return the " + typeof(IPublishedContent).Name + " because the " + typeof(UmbracoHelper).Name + " was constructed with an " + typeof(UmbracoContext).Name + " and the current request is not a front-end request.");
                
                return _currentPage;
	        }
	    }

	    /// <summary>
		/// Renders the template for the specified pageId and an optional altTemplateId
		/// </summary>
		/// <param name="pageId"></param>
		/// <param name="altTemplateId">If not specified, will use the template assigned to the node</param>
		/// <returns></returns>
		public IHtmlString RenderTemplate(int pageId, int? altTemplateId = null)
		{
			var templateRenderer = new TemplateRenderer(_umbracoContext, pageId, altTemplateId);
			using (var sw = new StringWriter())
			{
				try
				{
					templateRenderer.Render(sw);					
				}
				catch(Exception ex)
				{
					sw.Write("<!-- Error rendering template with id {0}: '{1}' -->", pageId, ex);
				}
				return new HtmlString(sw.ToString());	
			}			
		}

		#region RenderMacro

		/// <summary>
		/// Renders the macro with the specified alias.
		/// </summary>
		/// <param name="alias">The alias.</param>
		/// <returns></returns>
		public IHtmlString RenderMacro(string alias)
		{
			return RenderMacro(alias, new { });
		}

		/// <summary>
		/// Renders the macro with the specified alias, passing in the specified parameters.
		/// </summary>
		/// <param name="alias">The alias.</param>
		/// <param name="parameters">The parameters.</param>
		/// <returns></returns>
		public IHtmlString RenderMacro(string alias, object parameters)
		{
			return RenderMacro(alias, parameters.ToDictionary<object>());
		}

		/// <summary>
		/// Renders the macro with the specified alias, passing in the specified parameters.
		/// </summary>
		/// <param name="alias">The alias.</param>
		/// <param name="parameters">The parameters.</param>
		/// <returns></returns>
		public IHtmlString RenderMacro(string alias, IDictionary<string, object> parameters)
		{
			if (alias == null) throw new ArgumentNullException("alias");

			var m = macro.GetMacro(alias);
			if (_umbracoContext.PageId == null)
			{
				throw new InvalidOperationException("Cannot render a macro when UmbracoContext.PageId is null.");
			}
			if (_umbracoContext.PublishedContentRequest == null)
			{
				throw new InvalidOperationException("Cannot render a macro when there is no current PublishedContentRequest.");
			}
			var macroProps = new Hashtable();
			foreach (var i in parameters)
			{
				//TODO: We are doing at ToLower here because for some insane reason the UpdateMacroModel method of macro.cs 
				// looks for a lower case match. WTF. the whole macro concept needs to be rewritten.
				macroProps.Add(i.Key.ToLower(), i.Value);
			}
			var macroControl = m.renderMacro(macroProps,
				UmbracoContext.Current.PublishedContentRequest.UmbracoPage.Elements,
				_umbracoContext.PageId.Value);

			string html;
			if (macroControl is LiteralControl)
			{
				// no need to execute, we already have text
				html = (macroControl as LiteralControl).Text;
			}
			else
			{
				var containerPage = new FormlessPage();
				containerPage.Controls.Add(macroControl);

				using (var output = new StringWriter())
				{
					// .Execute() does a PushTraceContext/PopTraceContext and writes trace output straight into 'output'
					// and I do not see how we could wire the trace context to the current context... so it creates dirty
					// trace output right in the middle of the page.
					//
					// The only thing we can do is fully disable trace output while .Execute() runs and restore afterwards
					// which means trace output is lost if the macro is a control (.ascx or user control) that is invoked
					// from within Razor -- which makes sense anyway because the control can _not_ run correctly from
					// within Razor since it will never be inserted into the page pipeline (which may even not exist at all
					// if we're running MVC).
					//
					var traceIsEnabled = containerPage.Trace.IsEnabled;
					containerPage.Trace.IsEnabled = false;
					_umbracoContext.HttpContext.Server.Execute(containerPage, output, false);
					containerPage.Trace.IsEnabled = traceIsEnabled;

					//Now, we need to ensure that local links are parsed
					html = TemplateUtilities.ParseInternalLinks(output.ToString());
				}
			}

			return new HtmlString(html);
		}

		#endregion

		#region Field

		/// <summary>
		/// Renders an field to the template
		/// </summary>
		/// <param name="fieldAlias"></param>
		/// <param name="altFieldAlias"></param>
		/// <param name="altText"></param>
		/// <param name="insertBefore"></param>
		/// <param name="insertAfter"></param>
		/// <param name="recursive"></param>
		/// <param name="convertLineBreaks"></param>
		/// <param name="removeParagraphTags"></param>
		/// <param name="casing"></param>
		/// <param name="encoding"></param>
        /// <param name="formatAsDate"></param>
        /// <param name="formatAsDateWithTime"></param>
        /// <param name="formatAsDateWithTimeSeparator"></param>
        //// <param name="formatString"></param>
		/// <returns></returns>
		public IHtmlString Field(string fieldAlias, 
			string altFieldAlias = "", string altText = "", string insertBefore = "", string insertAfter = "",
			bool recursive = false, bool convertLineBreaks = false, bool removeParagraphTags = false,
			RenderFieldCaseType casing = RenderFieldCaseType.Unchanged,
            RenderFieldEncodingType encoding = RenderFieldEncodingType.Unchanged, 
            bool formatAsDate = false, 
            bool formatAsDateWithTime = false,
            string formatAsDateWithTimeSeparator = "")

            //TODO: commented out until as it is not implemented by umbraco:item yet
            //,string formatString = "")
		{			
            return Field(AssignedContentItem, fieldAlias, altFieldAlias,
                altText, insertBefore, insertAfter, recursive, convertLineBreaks, removeParagraphTags,
                casing, encoding, formatAsDate, formatAsDateWithTime, formatAsDateWithTimeSeparator); // formatString);
		}

		/// <summary>
		/// Renders an field to the template
		/// </summary>
		/// <param name="currentPage"></param>
		/// <param name="fieldAlias"></param>
		/// <param name="altFieldAlias"></param>
		/// <param name="altText"></param>
		/// <param name="insertBefore"></param>
		/// <param name="insertAfter"></param>
		/// <param name="recursive"></param>
		/// <param name="convertLineBreaks"></param>
		/// <param name="removeParagraphTags"></param>
		/// <param name="casing"></param>
        /// <param name="encoding"></param>
        /// <param name="formatAsDate"></param>
        /// <param name="formatAsDateWithTime"></param>
        /// <param name="formatAsDateWithTimeSeparator"></param>
		//// <param name="formatString"></param>
		/// <returns></returns>
		public IHtmlString Field(IPublishedContent currentPage, string fieldAlias, 
			string altFieldAlias = "", string altText = "", string insertBefore = "", string insertAfter = "",
			bool recursive = false, bool convertLineBreaks = false, bool removeParagraphTags = false,
			RenderFieldCaseType casing = RenderFieldCaseType.Unchanged,
			RenderFieldEncodingType encoding = RenderFieldEncodingType.Unchanged, 
            bool formatAsDate =  false,
            bool formatAsDateWithTime = false,
            string formatAsDateWithTimeSeparator = "")
            
            //TODO: commented out until as it is not implemented by umbraco:item yet
            //,string formatString = "")
		{
			Mandate.ParameterNotNull(currentPage, "currentPage");
			Mandate.ParameterNotNullOrEmpty(fieldAlias, "fieldAlias");

			//TODO: This is real nasty and we should re-write the 'item' and 'ItemRenderer' class but si fine for now

			var attributes = new Dictionary<string, string>
				{
					{"field", fieldAlias},
					{"recursive", recursive.ToString().ToLowerInvariant()},
					{"useifempty", altFieldAlias},
					{"textifempty", altText},
					{"stripparagraph", removeParagraphTags.ToString().ToLowerInvariant()},
					{
						"case", casing == RenderFieldCaseType.Lower ? "lower"
						        	: casing == RenderFieldCaseType.Upper ? "upper"
						        	  	: casing == RenderFieldCaseType.Title ? "title"
						        	  	  	: string.Empty
						},
					{"inserttextbefore", insertBefore},
					{"inserttextafter", insertAfter},
					{"convertlinebreaks", convertLineBreaks.ToString().ToLowerInvariant()},
                    {"formatasdate", formatAsDate.ToString().ToLowerInvariant()},
                    {"formatasdatewithtime", formatAsDateWithTime.ToString().ToLowerInvariant()},
                    {"formatasdatewithtimeseparator", formatAsDateWithTimeSeparator}
				};
			switch (encoding)
			{
				case RenderFieldEncodingType.Url:
					attributes.Add("urlencode", "true");
					break;
				case RenderFieldEncodingType.Html:
					attributes.Add("htmlencode", "true");
					break;
				case RenderFieldEncodingType.Unchanged:
				default:
					break;
			}

			//need to convert our dictionary over to this weird dictionary type
			var attributesForItem = new AttributeCollectionAdapter(
				new AttributeCollection(
					new StateBag()));
			foreach (var i in attributes)
			{
				attributesForItem.Add(i.Key, i.Value);
			}



		    var item = new Item()
		                   {		        
		                       Field = fieldAlias,
		                       TextIfEmpty = altText,
		                       LegacyAttributes = attributesForItem
		                   };

            //this is here to figure out if this request is in the context of a partial
            if (_umbracoContext.PublishedContentRequest.PublishedContent.Id != currentPage.Id)
                item.NodeId = currentPage.Id.ToString();
            
		
			var containerPage = new FormlessPage();
			containerPage.Controls.Add(item);

			using (var output = new StringWriter())
			using (var htmlWriter = new HtmlTextWriter(output))
			{
				ItemRenderer.Instance.Init(item);
				ItemRenderer.Instance.Load(item);
				ItemRenderer.Instance.Render(item, htmlWriter);
				
				//because we are rendering the output through the legacy Item (webforms) stuff, the {localLinks} will already be replaced.
				return new HtmlString(output.ToString());
			}
		}

		#endregion

		#region Dictionary

		private ICultureDictionary _cultureDictionary;

		/// <summary>
		/// Returns the dictionary value for the key specified
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public string GetDictionaryValue(string key)
		{
			if (_cultureDictionary == null)
			{
				var factory = CultureDictionaryFactoryResolver.Current.Factory;
				_cultureDictionary = factory.CreateDictionary();
			}
			return _cultureDictionary[key];
		}

		#endregion

		#region Membership

		/// <summary>
		/// Check if a document object is protected by the "Protect Pages" functionality in umbraco
		/// </summary>
		/// <param name="documentId">The identifier of the document object to check</param>
		/// <param name="path">The full path of the document object to check</param>
		/// <returns>True if the document object is protected</returns>
		public bool IsProtected(int documentId, string path)
		{
			return Access.IsProtected(documentId, path);
		}

		/// <summary>
		/// Check if the current user has access to a document
		/// </summary>
		/// <param name="nodeId">The identifier of the document object to check</param>
		/// <param name="path">The full path of the document object to check</param>
		/// <returns>True if the current user has access or if the current document isn't protected</returns>
		public bool MemberHasAccess(int nodeId, string path)
		{
			if (IsProtected(nodeId, path))
			{
				return Member.IsLoggedOn() && Access.HasAccess(nodeId, path, Membership.GetUser());
			}
			return true;
		}

		/// <summary>
		/// Whether or not the current member is logged in (based on the membership provider)
		/// </summary>
		/// <returns>True is the current user is logged in</returns>
		public bool MemberIsLoggedOn()
		{
			/*
			   MembershipUser u = Membership.GetUser();
			   return u != null;           
			*/
			return Member.IsLoggedOn();
		} 

		#endregion

		#region NiceUrls

		/// <summary>
		/// Returns a string with a friendly url from a node.
		/// IE.: Instead of having /482 (id) as an url, you can have
		/// /screenshots/developer/macros (spoken url)
		/// </summary>
		/// <param name="nodeId">Identifier for the node that should be returned</param>
		/// <returns>String with a friendly url from a node</returns>
		public string NiceUrl(int nodeId)
		{
			var urlProvider = UmbracoContext.Current.UrlProvider;
			return urlProvider.GetUrl(nodeId);
		}

		/// <summary>
		/// This method will always add the domain to the path if the hostnames are set up correctly. 
		/// </summary>
		/// <param name="nodeId">Identifier for the node that should be returned</param>
		/// <returns>String with a friendly url with full domain from a node</returns>
		public string NiceUrlWithDomain(int nodeId)
		{
			var urlProvider = UmbracoContext.Current.UrlProvider;
			return urlProvider.GetUrl(nodeId, true);
		}

		#endregion

		#region Content

		public IPublishedContent TypedContent(object id)
		{
            return TypedDocumentById(id, _umbracoContext.ContentCache);
		}

		public IPublishedContent TypedContent(int id)
		{
            return TypedDocumentById(id, _umbracoContext.ContentCache);
		}

		public IPublishedContent TypedContent(string id)
		{
            return TypedDocumentById(id, _umbracoContext.ContentCache);
		}

        public IPublishedContent TypedContentSingleAtXPath(string xpath, params XPathVariable[] vars)
        {
            return TypedDocumentByXPath(xpath, vars, _umbracoContext.ContentCache);
        }

		public IEnumerable<IPublishedContent> TypedContent(params object[] ids)
		{
            return TypedDocumentsbyIds(_umbracoContext.ContentCache, ids);
		}

		public IEnumerable<IPublishedContent> TypedContent(params int[] ids)
		{
            return TypedDocumentsbyIds(_umbracoContext.ContentCache, ids);
		}

		public IEnumerable<IPublishedContent> TypedContent(params string[] ids)
		{
            return TypedDocumentsbyIds(_umbracoContext.ContentCache, ids);
		}

		public IEnumerable<IPublishedContent> TypedContent(IEnumerable<object> ids)
		{
			return TypedContent(ids.ToArray());
		}

		public IEnumerable<IPublishedContent> TypedContent(IEnumerable<string> ids)
		{
			return TypedContent(ids.ToArray());
		}

		public IEnumerable<IPublishedContent> TypedContent(IEnumerable<int> ids)
		{
			return TypedContent(ids.ToArray());
		}

        public IEnumerable<IPublishedContent> TypedContentAtXPath(string xpath, params XPathVariable[] vars)
        {
            return TypedDocumentsByXPath(xpath, vars, _umbracoContext.ContentCache);
        }

        public IEnumerable<IPublishedContent> TypedContentAtRoot()
        {
            return TypedDocumentsAtRoot(_umbracoContext.ContentCache);
        }

		public dynamic Content(object id)
		{
            return DocumentById(id, _umbracoContext.ContentCache, new DynamicNull());
		}

		public dynamic Content(int id)
		{
            return DocumentById(id, _umbracoContext.ContentCache, new DynamicNull());
		}

		public dynamic Content(string id)
		{
            return DocumentById(id, _umbracoContext.ContentCache, new DynamicNull());
		}

        public dynamic ContentSingleAtXPath(string xpath, params XPathVariable[] vars)
        {
            return DocumentByXPath(xpath, vars, _umbracoContext.ContentCache, new DynamicNull());
        }

		public dynamic Content(params object[] ids)
		{
            return DocumentByIds(_umbracoContext.ContentCache, ids);
		}

		public dynamic Content(params int[] ids)
		{
            return DocumentByIds(_umbracoContext.ContentCache, ids);
		}

		public dynamic Content(params string[] ids)
		{
            return DocumentByIds(_umbracoContext.ContentCache, ids);
		}

		public dynamic Content(IEnumerable<object> ids)
		{
			return Content(ids.ToArray());
		}

		public dynamic Content(IEnumerable<int> ids)
		{
			return Content(ids.ToArray());
		}

		public dynamic Content(IEnumerable<string> ids)
		{
			return Content(ids.ToArray());
		}

        public dynamic ContentAtXPath(string xpath, params XPathVariable[] vars)
        {
            return DocumentsByXPath(xpath, vars, _umbracoContext.ContentCache);
        }

        public dynamic ContentAtRoot()
        {
            return DocumentsAtRoot(_umbracoContext.ContentCache);
        }

		#endregion

		#region Media

		/// <summary>
		/// Overloaded method accepting an 'object' type
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		/// <remarks>
		/// We accept an object type because GetPropertyValue now returns an 'object', we still want to allow people to pass 
		/// this result in to this method.
		/// This method will throw an exception if the value is not of type int or string.
		/// </remarks>
		public IPublishedContent TypedMedia(object id)
		{
			return TypedDocumentById(id, _umbracoContext.MediaCache);
		}

		public IPublishedContent TypedMedia(int id)
		{
            return TypedDocumentById(id, _umbracoContext.MediaCache);
		}

		public IPublishedContent TypedMedia(string id)
		{
            return TypedDocumentById(id, _umbracoContext.MediaCache);
		}

		public IEnumerable<IPublishedContent> TypedMedia(params object[] ids)
		{
            return TypedDocumentsbyIds(_umbracoContext.MediaCache, ids);
		}

		public IEnumerable<IPublishedContent> TypedMedia(params int[] ids)
		{
            return TypedDocumentsbyIds(_umbracoContext.MediaCache, ids);
		}

		public IEnumerable<IPublishedContent> TypedMedia(params string[] ids)
		{
            return TypedDocumentsbyIds(_umbracoContext.MediaCache, ids);
		}

		public IEnumerable<IPublishedContent> TypedMedia(IEnumerable<object> ids)
		{
			return TypedMedia(ids.ToArray());
		}

		public IEnumerable<IPublishedContent> TypedMedia(IEnumerable<int> ids)
		{
			return TypedMedia(ids.ToArray());
		}

		public IEnumerable<IPublishedContent> TypedMedia(IEnumerable<string> ids)
		{
			return TypedMedia(ids.ToArray());
		}

        public IEnumerable<IPublishedContent> TypedMediaAtRoot()
        {
            return TypedDocumentsAtRoot(_umbracoContext.MediaCache);
        }

		public dynamic Media(object id)
		{
            return DocumentById(id, _umbracoContext.MediaCache, new DynamicNull());
		}

		public dynamic Media(int id)
		{
            return DocumentById(id, _umbracoContext.MediaCache, new DynamicNull());
		}

		public dynamic Media(string id)
		{
            return DocumentById(id, _umbracoContext.MediaCache, new DynamicNull());
		}

		public dynamic Media(params object[] ids)
		{
            return DocumentByIds(_umbracoContext.MediaCache, ids);
		}

		public dynamic Media(params int[] ids)
		{
            return DocumentByIds(_umbracoContext.MediaCache, ids);
		}

		public dynamic Media(params string[] ids)
		{
            return DocumentByIds(_umbracoContext.MediaCache, ids);
		}

		public dynamic Media(IEnumerable<object> ids)
		{
			return Media(ids.ToArray());
		}

		public dynamic Media(IEnumerable<int> ids)
		{
			return Media(ids.ToArray());
		}

		public dynamic Media(IEnumerable<string> ids)
		{
			return Media(ids.ToArray());
		}

        public dynamic MediaAtRoot()
        {
            return DocumentsAtRoot(_umbracoContext.MediaCache);
        }

		#endregion

		#region Used by Content/Media

		/// <summary>
		/// Overloaded method accepting an 'object' type
		/// </summary>
		/// <param name="id"></param>
		/// <param name="cache"> </param>
		/// <returns></returns>
		/// <remarks>
		/// We accept an object type because GetPropertyValue now returns an 'object', we still want to allow people to pass 
		/// this result in to this method.
		/// This method will throw an exception if the value is not of type int or string.
		/// </remarks>
        private IPublishedContent TypedDocumentById(object id, ContextualPublishedCache cache)
		{
			if (id is string)
				return TypedDocumentById((string)id, cache);
			if (id is int)
				return TypedDocumentById((int)id, cache);
			throw new InvalidOperationException("The value of parameter 'id' must be either a string or an integer");
		}

		private IPublishedContent TypedDocumentById(int id, ContextualPublishedCache cache)
		{
            var doc = cache.GetById(id);
			return doc;
		}

        private IPublishedContent TypedDocumentById(string id, ContextualPublishedCache cache)
		{
			int docId;
			return int.TryParse(id, out docId)
				       ? DocumentById(docId, cache, null)
				       : null;
		}

        private IPublishedContent TypedDocumentByXPath(string xpath, XPathVariable[] vars, ContextualPublishedContentCache cache)
        {
            var doc = cache.GetSingleByXPath(xpath, vars);
            return doc;
        }

		/// <summary>
		/// Overloaded method accepting an 'object' type
		/// </summary>
		/// <param name="ids"></param>
		/// <param name="cache"> </param>
		/// <returns></returns>
		/// <remarks>
		/// We accept an object type because GetPropertyValue now returns an 'object', we still want to allow people to pass 
		/// this result in to this method.
		/// This method will throw an exception if the value is not of type int or string.
		/// </remarks>
        private IEnumerable<IPublishedContent> TypedDocumentsbyIds(ContextualPublishedCache cache, params object[] ids)
		{
			return ids.Select(eachId => TypedDocumentById(eachId, cache));
		}

        private IEnumerable<IPublishedContent> TypedDocumentsbyIds(ContextualPublishedCache cache, params int[] ids)
		{
			return ids.Select(eachId => TypedDocumentById(eachId, cache));
		}

        private IEnumerable<IPublishedContent> TypedDocumentsbyIds(ContextualPublishedCache cache, params string[] ids)
		{
			return ids.Select(eachId => TypedDocumentById(eachId, cache));
		}

        private IEnumerable<IPublishedContent> TypedDocumentsByXPath(string xpath, XPathVariable[] vars, ContextualPublishedContentCache cache)
        {
            var doc = cache.GetByXPath(xpath, vars);
            return doc;
        }

        private IEnumerable<IPublishedContent> TypedDocumentsAtRoot(ContextualPublishedCache cache)
        {
            return cache.GetAtRoot();
        }

		/// <summary>
		/// Overloaded method accepting an 'object' type
		/// </summary>
		/// <param name="id"></param>
		/// <param name="cache"> </param>
		/// <param name="ifNotFound"> </param>
		/// <returns></returns>
		/// <remarks>
		/// We accept an object type because GetPropertyValue now returns an 'object', we still want to allow people to pass 
		/// this result in to this method.
		/// This method will throw an exception if the value is not of type int or string.
		/// </remarks>
        private dynamic DocumentById(object id, ContextualPublishedCache cache, object ifNotFound)
		{
			if (id is string)
				return DocumentById((string)id, cache, ifNotFound);
			if (id is int)
				return DocumentById((int)id, cache, ifNotFound);
			throw new InvalidOperationException("The value of parameter 'id' must be either a string or an integer");
		}

        private dynamic DocumentById(int id, ContextualPublishedCache cache, object ifNotFound)
		{
            var doc = cache.GetById(id);
			return doc == null
					? ifNotFound
					: new DynamicPublishedContent(doc).AsDynamic();
		}

        private dynamic DocumentById(string id, ContextualPublishedCache cache, object ifNotFound)
		{
			int docId;
			return int.TryParse(id, out docId)
				? DocumentById(docId, cache, ifNotFound)
				: ifNotFound;
		}

        private dynamic DocumentByXPath(string xpath, XPathVariable[] vars, ContextualPublishedCache cache, object ifNotFound)
        {
            var doc = cache.GetSingleByXPath(xpath, vars);
            return doc == null
                ? ifNotFound
                : new DynamicPublishedContent(doc).AsDynamic();
        }
        
		/// <summary>
		/// Overloaded method accepting an 'object' type
		/// </summary>
		/// <param name="ids"></param>
		/// <param name="cache"> </param>
		/// <returns></returns>
		/// <remarks>
		/// We accept an object type because GetPropertyValue now returns an 'object', we still want to allow people to pass 
		/// this result in to this method.
		/// This method will throw an exception if the value is not of type int or string.
		/// </remarks>
        private dynamic DocumentByIds(ContextualPublishedCache cache, params object[] ids)
		{
			var dNull = new DynamicNull();
			var nodes = ids.Select(eachId => DocumentById(eachId, cache, dNull))
				.Where(x => !TypeHelper.IsTypeAssignableFrom<DynamicNull>(x))
				.Cast<DynamicPublishedContent>();
			return new DynamicPublishedContentList(nodes);
		}

        private dynamic DocumentByIds(ContextualPublishedCache cache, params int[] ids)
		{
			var dNull = new DynamicNull();
			var nodes = ids.Select(eachId => DocumentById(eachId, cache, dNull))
				.Where(x => !TypeHelper.IsTypeAssignableFrom<DynamicNull>(x))
				.Cast<DynamicPublishedContent>();
			return new DynamicPublishedContentList(nodes);
		}

        private dynamic DocumentByIds(ContextualPublishedCache cache, params string[] ids)
		{
			var dNull = new DynamicNull();
			var nodes = ids.Select(eachId => DocumentById(eachId, cache, dNull))
				.Where(x => !TypeHelper.IsTypeAssignableFrom<DynamicNull>(x))
				.Cast<DynamicPublishedContent>();
			return new DynamicPublishedContentList(nodes);
		}

        private dynamic DocumentsByXPath(string xpath, XPathVariable[] vars, ContextualPublishedCache cache)
        {
            return new DynamicPublishedContentList(
                cache.GetByXPath(xpath, vars)
                    .Select(publishedContent => new DynamicPublishedContent(publishedContent))
            );
        }

        private dynamic DocumentsAtRoot(ContextualPublishedCache cache)
        {
            return new DynamicPublishedContentList(
                cache.GetAtRoot()
                    .Select(publishedContent => new DynamicPublishedContent(publishedContent))
            );
        }

        #endregion

		#region Search

		/// <summary>
		/// Searches content
		/// </summary>
		/// <param name="term"></param>
		/// <param name="useWildCards"></param>
{'fraction_non_alphanumeric': 0.10979317131460102, 'fraction_numerical': 0.00017572530620134605, 'mean_word_length': 3.1038436576043846, 'pattern_counts': {'":': 0, '<': 501, '<?xml version=': 0, '>': 522, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4989756', 'n_tokens_mistral': 17917, 'n_tokens_neox': 15543, 'n_words': 4485}