using System;
using System.ComponentModel;
using System.Web;
using System.Web.Security;
using System.Xml.Linq;
using System.Xml.XPath;
using Umbraco.Core;
using Umbraco.Core.Dictionary;
using Umbraco.Core.Dynamics;
using Umbraco.Core.Models;
using Umbraco.Core.Security;
using Umbraco.Core.Services;
using Umbraco.Core.Xml;
using Umbraco.Web.Routing;
using Umbraco.Web.Security;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using Umbraco.Core.Cache;
namespace Umbraco.Web
{
///
/// A helper class that provides many useful methods and functionality for using Umbraco in templates
///
public class UmbracoHelper : IUmbracoComponentRenderer
{
private readonly UmbracoContext _umbracoContext;
private readonly IPublishedContent _currentPage;
private readonly ITypedPublishedContentQuery _typedQuery;
private readonly IDynamicPublishedContentQuery _dynamicQuery;
private readonly HtmlStringUtilities _stringUtilities = new HtmlStringUtilities();
private IUmbracoComponentRenderer _componentRenderer;
private PublishedContentQuery _query;
private MembershipHelper _membershipHelper;
private TagQuery _tag;
private IDataTypeService _dataTypeService;
private IEntityService _entityService;
private UrlProvider _urlProvider;
private ICultureDictionary _cultureDictionary;
///
/// Lazy instantiates the tag context
///
public TagQuery TagQuery
{
//TODO: Unfortunately we cannot change this return value to be ITagQuery
// since it's a breaking change, need to fix it for v8
// http://issues.umbraco.org/issue/U4-6899
get
{
return _tag ??
(_tag = new TagQuery(UmbracoContext.Application.Services.TagService,
_typedQuery ?? ContentQuery));
}
}
///
/// Lazy instantiates the query context if not specified in the constructor
///
public PublishedContentQuery ContentQuery
{
get
{
//If the content query doesn't exist it will either be created with the ITypedPublishedContentQuery, IDynamicPublishedContentQuery
// used to construct this instance or with the content caches of the UmbracoContext
return _query ??
(_query = _typedQuery != null
? new PublishedContentQuery(_typedQuery, _dynamicQuery)
: new PublishedContentQuery(UmbracoContext.ContentCache, UmbracoContext.MediaCache));
}
}
///
/// Helper method to ensure an umbraco context is set when it is needed
///
public UmbracoContext UmbracoContext
{
get
{
if (_umbracoContext == null)
{
throw new NullReferenceException("No " + typeof(UmbracoContext) + " reference has been set for this " + typeof(UmbracoHelper) + " instance");
}
return _umbracoContext;
}
}
///
/// Lazy instantiates the membership helper if not specified in the constructor
///
public MembershipHelper MembershipHelper
{
get { return _membershipHelper ?? (_membershipHelper = new MembershipHelper(UmbracoContext)); }
}
///
/// Lazy instantiates the UrlProvider if not specified in the constructor
///
public UrlProvider UrlProvider
{
get { return _urlProvider ?? (_urlProvider = UmbracoContext.UrlProvider); }
}
///
/// Lazy instantiates the IDataTypeService if not specified in the constructor
///
public IDataTypeService DataTypeService
{
get { return _dataTypeService ?? (_dataTypeService = UmbracoContext.Application.Services.DataTypeService); }
}
///
/// Lazy instantiates the IEntityService
///
private IEntityService EntityService
{
get { return _entityService ?? (_entityService = UmbracoContext.Application.Services.EntityService); }
}
///
/// Lazy instantiates the IUmbracoComponentRenderer if not specified in the constructor
///
public IUmbracoComponentRenderer UmbracoComponentRenderer
{
get { return _componentRenderer ?? (_componentRenderer = new UmbracoComponentRenderer(UmbracoContext)); }
}
#region Constructors
///
/// Empty constructor to create an umbraco helper for access to methods that don't have dependencies
///
public UmbracoHelper()
{
}
///
/// Constructor accepting all dependencies
///
///
///
///
///
///
///
///
///
///
///
///
/// This constructor can be used to create a testable UmbracoHelper
///
public UmbracoHelper(UmbracoContext umbracoContext, IPublishedContent content,
ITypedPublishedContentQuery typedQuery,
IDynamicPublishedContentQuery dynamicQuery,
ITagQuery tagQuery,
IDataTypeService dataTypeService,
UrlProvider urlProvider,
ICultureDictionary cultureDictionary,
IUmbracoComponentRenderer componentRenderer,
MembershipHelper membershipHelper)
{
if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
if (content == null) throw new ArgumentNullException("content");
if (typedQuery == null) throw new ArgumentNullException("typedQuery");
if (dynamicQuery == null) throw new ArgumentNullException("dynamicQuery");
if (tagQuery == null) throw new ArgumentNullException("tagQuery");
if (dataTypeService == null) throw new ArgumentNullException("dataTypeService");
if (urlProvider == null) throw new ArgumentNullException("urlProvider");
if (cultureDictionary == null) throw new ArgumentNullException("cultureDictionary");
if (componentRenderer == null) throw new ArgumentNullException("componentRenderer");
if (membershipHelper == null) throw new ArgumentNullException("membershipHelper");
_umbracoContext = umbracoContext;
_tag = new TagQuery(tagQuery);
_dataTypeService = dataTypeService;
_urlProvider = urlProvider;
_cultureDictionary = cultureDictionary;
_componentRenderer = componentRenderer;
_membershipHelper = membershipHelper;
_currentPage = content;
_typedQuery = typedQuery;
_dynamicQuery = dynamicQuery;
}
[Obsolete("Use the constructor specifying all dependencies")]
[EditorBrowsable(EditorBrowsableState.Never)]
public UmbracoHelper(UmbracoContext umbracoContext, IPublishedContent content, PublishedContentQuery query)
: this(umbracoContext)
{
if (content == null) throw new ArgumentNullException("content");
if (query == null) throw new ArgumentNullException("query");
_currentPage = content;
_query = query;
}
///
/// Custom constructor setting the current page to the parameter passed in
///
///
///
public UmbracoHelper(UmbracoContext umbracoContext, IPublishedContent content)
: this(umbracoContext)
{
if (content == null) throw new ArgumentNullException("content");
_currentPage = content;
}
///
/// Standard constructor setting the current page to the page that has been routed to
///
///
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;
}
}
[Obsolete("Use the constructor specifying all dependencies")]
[EditorBrowsable(EditorBrowsableState.Never)]
public UmbracoHelper(UmbracoContext umbracoContext, PublishedContentQuery query)
: this(umbracoContext)
{
if (query == null) throw new ArgumentNullException("query");
_query = query;
}
#endregion
///
/// Returns the current IPublishedContent item assigned to the UmbracoHelper
///
///
/// 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
///
/// Thrown if the UmbracoHelper is constructed with an UmbracoContext and it is not a front-end request
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;
}
}
///
/// Renders the template for the specified pageId and an optional altTemplateId
///
///
/// If not specified, will use the template assigned to the node
///
public IHtmlString RenderTemplate(int pageId, int? altTemplateId = null)
{
return UmbracoComponentRenderer.RenderTemplate(pageId, altTemplateId);
}
#region RenderMacro
///
/// Renders the macro with the specified alias.
///
/// The alias.
///
public IHtmlString RenderMacro(string alias)
{
return UmbracoComponentRenderer.RenderMacro(alias, new { });
}
///
/// Renders the macro with the specified alias, passing in the specified parameters.
///
/// The alias.
/// The parameters.
///
public IHtmlString RenderMacro(string alias, object parameters)
{
return UmbracoComponentRenderer.RenderMacro(alias, parameters.ToDictionary());
}
///
/// Renders the macro with the specified alias, passing in the specified parameters.
///
/// The alias.
/// The parameters.
///
public IHtmlString RenderMacro(string alias, IDictionary parameters)
{
return UmbracoComponentRenderer.RenderMacro(alias, parameters);
}
#endregion
#region Field
///
/// Renders an field to the template
///
///
///
///
///
///
///
///
///
///
///
///
///
///
////
///
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 = "")
{
return UmbracoComponentRenderer.Field(AssignedContentItem, fieldAlias, altFieldAlias,
altText, insertBefore, insertAfter, recursive, convertLineBreaks, removeParagraphTags,
casing, encoding, formatAsDate, formatAsDateWithTime, formatAsDateWithTimeSeparator);
}
///
/// Renders an field to the template
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
////
///
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 = "")
{
return UmbracoComponentRenderer.Field(currentPage, fieldAlias, altFieldAlias,
altText, insertBefore, insertAfter, recursive, convertLineBreaks, removeParagraphTags,
casing, encoding, formatAsDate, formatAsDateWithTime, formatAsDateWithTimeSeparator);
}
#endregion
#region Dictionary
///
/// Returns the dictionary value for the key specified
///
///
///
public string GetDictionaryValue(string key)
{
return CultureDictionary[key];
}
///
/// Returns the dictionary value for the key specified, and if empty returns the specified default fall back value
///
/// key of dictionary item
/// fall back text if dictionary item is empty - Name altText to match Umbraco.Field
///
public string GetDictionaryValue(string key, string altText)
{
var dictionaryValue = GetDictionaryValue(key);
if (String.IsNullOrWhiteSpace(dictionaryValue))
{
dictionaryValue = altText;
}
return dictionaryValue;
}
///
/// Returns the ICultureDictionary for access to dictionary items
///
public ICultureDictionary CultureDictionary
{
get
{
if (_cultureDictionary == null)
{
var factory = CultureDictionaryFactoryResolver.Current.Factory;
_cultureDictionary = factory.CreateDictionary();
}
return _cultureDictionary;
}
}
#endregion
#region Membership
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use the IsProtected method that only specifies path")]
public bool IsProtected(int documentId, string path)
{
return IsProtected(path.EnsureEndsWith("," + documentId));
}
///
/// Check if a document object is protected by the "Protect Pages" functionality in umbraco
///
/// The full path of the document object to check
/// True if the document object is protected
public bool IsProtected(string path)
{
return MembershipHelper.IsProtected(path);
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use the MemberHasAccess method that only specifies path")]
public bool MemberHasAccess(int nodeId, string path)
{
return MemberHasAccess(path.EnsureEndsWith("," + nodeId));
}
///
/// Check if the current user has access to a document
///
/// The full path of the document object to check
/// True if the current user has access or if the current document isn't protected
public bool MemberHasAccess(string path)
{
return MembershipHelper.MemberHasAccess(path);
}
///
/// Whether or not the current member is logged in (based on the membership provider)
///
/// True is the current user is logged in
public bool MemberIsLoggedOn()
{
return MembershipHelper.IsLoggedIn();
}
#endregion
#region NiceUrls
///
/// 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)
///
/// Identifier for the node that should be returned
/// String with a friendly url from a node
public string NiceUrl(int nodeId)
{
return Url(nodeId);
}
///
/// Gets the url of a content identified by its identifier.
///
/// The content identifier.
/// The url for the content.
public string Url(int contentId)
{
return UrlProvider.GetUrl(contentId);
}
///
/// Gets the url of a content identified by its identifier, in a specified mode.
///
/// The content identifier.
/// The mode.
/// The url for the content.
public string Url(int contentId, UrlProviderMode mode)
{
return UrlProvider.GetUrl(contentId, mode);
}
///
/// This method will always add the domain to the path if the hostnames are set up correctly.
///
/// Identifier for the node that should be returned
/// String with a friendly url with full domain from a node
public string NiceUrlWithDomain(int nodeId)
{
return UrlAbsolute(nodeId);
}
///
/// Gets the absolute url of a content identified by its identifier.
///
/// The content identifier.
/// The absolute url for the content.
public string UrlAbsolute(int contentId)
{
return UrlProvider.GetUrl(contentId, true);
}
#endregion
#region Members
public IPublishedContent TypedMember(Udi id)
{
var guidUdi = id as GuidUdi;
if (guidUdi == null) return null;
return TypedMember(guidUdi.Guid);
}
public IPublishedContent TypedMember(Guid id)
{
return MembershipHelper.GetByProviderKey(id);
}
public IPublishedContent TypedMember(object id)
{
var asInt = id.TryConvertTo();
return asInt ? MembershipHelper.GetById(asInt.Result) : MembershipHelper.GetByProviderKey(id);
}
public IPublishedContent TypedMember(int id)
{
return MembershipHelper.GetById(id);
}
public IPublishedContent TypedMember(string id)
{
var asInt = id.TryConvertTo();
return asInt ? MembershipHelper.GetById(asInt.Result) : MembershipHelper.GetByProviderKey(id);
}
public dynamic Member(object id)
{
var asInt = id.TryConvertTo();
return asInt
? MembershipHelper.GetById(asInt.Result).AsDynamic()
: MembershipHelper.GetByProviderKey(id).AsDynamic();
}
public dynamic Member(int id)
{
return MembershipHelper.GetById(id).AsDynamic();
}
public dynamic Member(string id)
{
var asInt = id.TryConvertTo();
return asInt
? MembershipHelper.GetById(asInt.Result).AsDynamic()
: MembershipHelper.GetByProviderKey(id).AsDynamic();
}
#endregion
#region Content
///
/// Gets a content item from the cache.
///
/// The unique identifier, or the key, of the content item.
/// The content, or null of the content item is not in the cache.
public IPublishedContent TypedContent(object id)
{
return TypedContentForObject(id);
}
private IPublishedContent TypedContentForObject(object id)
{
int intId;
if (ConvertIdObjectToInt(id, out intId))
return ContentQuery.TypedContent(intId);
Guid guidId;
if (ConvertIdObjectToGuid(id, out guidId))
return ContentQuery.TypedContent(guidId);
Udi udiId;
if (ConvertIdObjectToUdi(id, out udiId))
return ContentQuery.TypedContent(udiId);
return null;
}
///
/// Gets a content item from the cache.
///
/// The unique identifier of the content item.
/// The content, or null of the content item is not in the cache.
public IPublishedContent TypedContent(int id)
{
return ContentQuery.TypedContent(id);
}
///
/// Gets a content item from the cache.
///
/// The key of the content item.
/// The content, or null of the content item is not in the cache.
public IPublishedContent TypedContent(Guid id)
{
return ContentQuery.TypedContent(id);
}
///
/// Gets a content item from the cache
///
///
///
public IPublishedContent TypedContent(Udi id)
{
return ContentQuery.TypedContent(id);
}
///
/// Gets a content item from the cache.
///
/// The unique identifier, or the key, of the content item.
/// The content, or null of the content item is not in the cache.
public IPublishedContent TypedContent(string id)
{
return TypedContentForObject(id);
}
public IPublishedContent TypedContentSingleAtXPath(string xpath, params XPathVariable[] vars)
{
return ContentQuery.TypedContentSingleAtXPath(xpath, vars);
}
///
/// Gets content items from the cache.
///
/// The unique identifiers, or the keys, of the content items.
/// The content items that were found in the cache.
/// Does not support mixing identifiers and keys.
public IEnumerable TypedContent(params object[] ids)
{
return TypedContentForObjects(ids);
}
private IEnumerable TypedContentForObjects(IEnumerable ids)
{
var idsA = ids.ToArray();
IEnumerable intIds;
if (ConvertIdsObjectToInts(idsA, out intIds))
return ContentQuery.TypedContent(intIds);
IEnumerable guidIds;
if (ConvertIdsObjectToGuids(idsA, out guidIds))
return ContentQuery.TypedContent(guidIds);
return Enumerable.Empty();
}
///
/// Gets content items from the cache.
///
/// The unique identifiers of the content items.
/// The content items that were found in the cache.
public IEnumerable TypedContent(params int[] ids)
{
return ContentQuery.TypedContent(ids);
}
///
/// Gets content items from the cache.
///
/// The keys of the content items.
/// The content items that were found in the cache.
public IEnumerable TypedContent(params Guid[] ids)
{
return ContentQuery.TypedContent(ids);
}
///
/// Gets content items from the cache.
///
/// The unique identifiers, or the keys, of the content items.
/// The content items that were found in the cache.
/// Does not support mixing identifiers and keys.
public IEnumerable TypedContent(params string[] ids)
{
return TypedContentForObjects(ids);
}
///
/// Gets the contents corresponding to the identifiers.
///
/// The content identifiers.
/// The existing contents corresponding to the identifiers.
/// If an identifier does not match an existing content, it will be missing in the returned value.
public IEnumerable TypedContent(IEnumerable ids)
{
return TypedContentForObjects(ids);
}
///
/// Gets the contents corresponding to the identifiers.
///
/// The content identifiers.
/// The existing contents corresponding to the identifiers.
/// If an identifier does not match an existing content, it will be missing in the returned value.
public IEnumerable TypedContent(IEnumerable ids)
{
return TypedContentForObjects(ids);
}
///
/// Gets the contents corresponding to the identifiers.
///
/// The content identifiers.
/// The existing contents corresponding to the identifiers.
/// If an identifier does not match an existing content, it will be missing in the returned value.
public IEnumerable TypedContent(IEnumerable ids)
{
return ContentQuery.TypedContent(ids);
}
public IEnumerable TypedContentAtXPath(string xpath, params XPathVariable[] vars)
{
return ContentQuery.TypedContentAtXPath(xpath, vars);
}
public IEnumerable TypedContentAtXPath(XPathExpression xpath, params XPathVariable[] vars)
{
return ContentQuery.TypedContentAtXPath(xpath, vars);
}
public IEnumerable TypedContentAtRoot()
{
return ContentQuery.TypedContentAtRoot();
}
///
/// Gets a content item from the cache.
///
/// The unique identifier, or the key, of the content item.
/// The content, or DynamicNull of the content item is not in the cache.
public dynamic Content(object id)
{
return ContentForObject(id);
}
private dynamic ContentForObject(object id)
{
int intId;
if (ConvertIdObjectToInt(id, out intId))
return ContentQuery.Content(intId);
Guid guidId;
if (ConvertIdObjectToGuid(id, out guidId))
return ContentQuery.Content(guidId);
return DynamicNull.Null;
}
///
/// Gets a content item from the cache.
///
/// The unique identifier of the content item.
/// The content, or DynamicNull of the content item is not in the cache.
public dynamic Content(int id)
{
return ContentQuery.Content(id);
}
///
/// Gets a content item from the cache.
///
/// The unique identifier, or the key, of the content item.
/// The content, or DynamicNull of the content item is not in the cache.
public dynamic Content(string id)
{
return ContentForObject(id);
}
public dynamic ContentSingleAtXPath(string xpath, params XPathVariable[] vars)
{
return ContentQuery.ContentSingleAtXPath(xpath, vars);
}
public dynamic ContentSingleAtXPath(XPathExpression xpath, params XPathVariable[] vars)
{
return ContentQuery.ContentSingleAtXPath(xpath, vars);
}
///
/// Gets content items from the cache.
///
/// The unique identifiers, or the keys, of the content items.
/// The content items that were found in the cache.
/// Does not support mixing identifiers and keys.
public dynamic Content(params object[] ids)
{
return ContentForObjects(ids);
}
private dynamic ContentForObjects(IEnumerable ids)
{
var idsA = ids.ToArray();
IEnumerable intIds;
if (ConvertIdsObjectToInts(idsA, out intIds))
return ContentQuery.Content(intIds);
IEnumerable guidIds;
if (ConvertIdsObjectToGuids(idsA, out guidIds))
return ContentQuery.Content(guidIds);
return Enumerable.Empty();
}
///
/// Gets content items from the cache.
///
/// The unique identifiers of the content items.
/// The content items that were found in the cache.
public dynamic Content(params int[] ids)
{
return ContentQuery.Content(ids);
}
///
/// Gets content items from the cache.
///
/// The unique identifiers, or the keys, of the content items.
/// The content items that were found in the cache.
/// Does not support mixing identifiers and keys.
public dynamic Content(params string[] ids)
{
return ContentForObjects(ids);
}
///
/// Gets content items from the cache.
///
/// The unique identifiers, or the keys, of the content items.
/// The content items that were found in the cache.
/// Does not support mixing identifiers and keys.
public dynamic Content(IEnumerable ids)
{
return ContentForObjects(ids);
}
///
/// Gets content items from the cache.
///
/// The unique identifiers of the content items.
/// The content items that were found in the cache.
public dynamic Content(IEnumerable ids)
{
return ContentQuery.Content(ids);
}
///
/// Gets content items from the cache.
///
/// The unique identifiers, or the keys, of the content items.
/// The content items that were found in the cache.
/// Does not support mixing identifiers and keys.
public dynamic Content(IEnumerable ids)
{
return ContentForObjects(ids);
}
public dynamic ContentAtXPath(string xpath, params XPathVariable[] vars)
{
return ContentQuery.ContentAtXPath(xpath, vars);
}
public dynamic ContentAtXPath(XPathExpression xpath, params XPathVariable[] vars)
{
return ContentQuery.ContentAtXPath(xpath, vars);
}
public dynamic ContentAtRoot()
{
return ContentQuery.ContentAtRoot();
}
private static bool ConvertIdObjectToInt(object id, out int intId)
{
var s = id as string;
if (s != null)
{
return int.TryParse(s, out intId);
}
if (id is int)
{
intId = (int) id;
return true;
}
intId = default(int);
return false;
}
private static bool ConvertIdObjectToGuid(object id, out Guid guidId)
{
var s = id as string;
if (s != null)
{
return Guid.TryParse(s, out guidId);
}
if (id is Guid)
{
guidId = (Guid) id;
return true;
}
guidId = default(Guid);
return false;
}
private static bool ConvertIdObjectToUdi(object id, out Udi guidId)
{
var s = id as string;
if (s != null)
{
return Udi.TryParse(s, out guidId);
}
if (id is Udi)
{
guidId = (Udi)id;
return true;
}
guidId = null;
return false;
}
private static bool ConvertIdsObjectToInts(IEnumerable ids, out IEnumerable intIds)
{
var list = new List();
intIds = null;
foreach (var id in ids)
{
int intId;
if (ConvertIdObjectToInt(id, out intId))
list.Add(intId);
else
return false; // if one of them is not an int, fail
}
intIds = list;
return true;
}
private static bool ConvertIdsObjectToGuids(IEnumerable ids, out IEnumerable guidIds)
{
var list = new List();
guidIds = null;
foreach (var id in ids)
{
Guid guidId;
if (ConvertIdObjectToGuid(id, out guidId))
list.Add(guidId);
else
return false; // if one of them is not a guid, fail
}
guidIds = list;
return true;
}
#endregion
#region Media
public IPublishedContent TypedMedia(Udi id)
{
var guidUdi = id as GuidUdi;
if (guidUdi == null) return null;
return TypedMedia(guidUdi.Guid);
}
public IPublishedContent TypedMedia(Guid id)
{
//TODO: This is horrible but until the media cache properly supports GUIDs we have no choice here and
// currently there won't be any way to add this method correctly to `ITypedPublishedContentQuery` without breaking an interface and adding GUID support for media
var entityService = UmbracoContext.Application.Services.EntityService;
var mediaAttempt = entityService.GetIdForKey(id, UmbracoObjectTypes.Media);
return mediaAttempt.Success ? ContentQuery.TypedMedia(mediaAttempt.Result) : null;
}
///
/// Overloaded method accepting an 'object' type
///
///
///
///
/// 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.
///
public IPublishedContent TypedMedia(object id)
{
return TypedMediaForObject(id);
}
private IPublishedContent TypedMediaForObject(object id)
{
int intId;
if (ConvertIdObjectToInt(id, out intId))
return ContentQuery.TypedMedia(intId);
Guid guidId;
if (ConvertIdObjectToGuid(id, out guidId))
return TypedMedia(guidId);
Udi udiId;
if (ConvertIdObjectToUdi(id, out udiId))
return TypedMedia(udiId);
return null;
}
public IPublishedContent TypedMedia(int id)
{
return ContentQuery.TypedMedia(id);
}
public IPublishedContent TypedMedia(string id)
{
int intId;
return ConvertIdObjectToInt(id, out intId) ? ContentQuery.TypedMedia(intId) : null;
}
///
/// Gets the medias corresponding to the identifiers.
///
/// The media identifiers.
/// The existing medias corresponding to the identifiers.
/// If an identifier does not match an existing media, it will be missing in the returned value.
public IEnumerable TypedMedia(params object[] ids)
{
return TypedMediaForObjects(ids);
}
private IEnumerable TypedMediaForObjects(IEnumerable ids)
{
var idsA = ids.ToArray();
IEnumerable intIds;
if (ConvertIdsObjectToInts(idsA, out intIds))
return ContentQuery.TypedMedia(intIds);
//IEnumerable guidIds;
//if (ConvertIdsObjectToGuids(idsA, out guidIds))
// return ContentQuery.TypedMedia(guidIds);
return Enumerable.Empty();
}
///
/// Gets the medias corresponding to the identifiers.
///
/// The media identifiers.
/// The existing medias corresponding to the identifiers.
/// If an identifier does not match an existing media, it will be missing in the returned value.
public IEnumerable TypedMedia(params int[] ids)
{
return ContentQuery.TypedMedia(ids);
}
///
/// Gets the medias corresponding to the identifiers.
///
/// The media identifiers.
/// The existing medias corresponding to the identifiers.
/// If an identifier does not match an existing media, it will be missing in the returned value.
public IEnumerable TypedMedia(params string[] ids)
{
return TypedMediaForObjects(ids);
}
///
/// Gets the medias corresponding to the identifiers.
///
/// The media identifiers.
/// The existing medias corresponding to the identifiers.
/// If an identifier does not match an existing media, it will be missing in the returned value.
public IEnumerable TypedMedia(IEnumerable ids)
{
return TypedMediaForObjects(ids);
}
///
/// Gets the medias corresponding to the identifiers.
///
/// The media identifiers.
/// The existing medias corresponding to the identifiers.
/// If an identifier does not match an existing media, it will be missing in the returned value.
public IEnumerable TypedMedia(IEnumerable ids)
{
return ContentQuery.TypedMedia(ids);
}
///
/// Gets the medias corresponding to the identifiers.
///
/// The media identifiers.
/// The existing medias corresponding to the identifiers.
/// If an identifier does not match an existing media, it will be missing in the returned value.
public IEnumerable TypedMedia(IEnumerable ids)
{
return TypedMediaForObjects(ids);
}
public IEnumerable TypedMediaAtRoot()
{
return ContentQuery.TypedMediaAtRoot();
}
public dynamic Media(object id)
{
int intId;
return ConvertIdObjectToInt(id, out intId) ? ContentQuery.Media(intId) : DynamicNull.Null;
}
public dynamic Media(int id)
{
return ContentQuery.Media(id);
}
public dynamic Media(string id)
{
int intId;
return ConvertIdObjectToInt(id, out intId) ? ContentQuery.Media(intId) : DynamicNull.Null;
}
///
/// Gets the medias corresponding to the identifiers.
///
/// The media identifiers.
/// The existing medias corresponding to the identifiers.
/// If an identifier does not match an existing media, it will be missing in the returned value.
public dynamic Media(params object[] ids)
{
return MediaForObjects(ids);
}
private dynamic MediaForObjects(IEnumerable ids)
{
var idsA = ids.ToArray();
IEnumerable intIds;
if (ConvertIdsObjectToInts(idsA, out intIds))
return ContentQuery.Media(intIds);
//IEnumerable guidIds;
//if (ConvertIdsObjectToGuids(idsA, out guidIds))
// return ContentQuery.Media(guidIds);
return Enumerable.Empty();
}
///
/// Gets the medias corresponding to the identifiers.
///
/// The media identifiers.
/// The existing medias corresponding to the identifiers.
/// If an identifier does not match an existing media, it will be missing in the returned value.
public dynamic Media(params int[] ids)
{
return ContentQuery.Media(ids);
}
///
/// Gets the medias corresponding to the identifiers.
///
/// The media identifiers.
/// The existing medias corresponding to the identifiers.
/// If an identifier does not match an existing media, it will be missing in the returned value.
public dynamic Media(params string[] ids)
{
return MediaForObjects(ids);
}
///
/// Gets the medias corresponding to the identifiers.
///
/// The media identifiers.
/// The existing medias corresponding to the identifiers.
/// If an identifier does not match an existing media, it will be missing in the returned value.
public dynamic Media(IEnumerable ids)
{
return MediaForObjects(ids);
}
///
/// Gets the medias corresponding to the identifiers.
///
/// The media identifiers.
/// The existing medias corresponding to the identifiers.
/// If an identifier does not match an existing media, it will be missing in the returned value.
public dynamic Media(IEnumerable ids)
{
return ContentQuery.Media(ids);
}
///
/// Gets the medias corresponding to the identifiers.
///
/// The media identifiers.
/// The existing medias corresponding to the identifiers.
/// If an identifier does not match an existing media, it will be missing in the returned value.
public dynamic Media(IEnumerable ids)
{
return MediaForObjects(ids);
}
public dynamic MediaAtRoot()
{
return ContentQuery.MediaAtRoot();
}
#endregion
#region Search
///
/// Searches content
///
///
///
///
///
public dynamic Search(string term, bool useWildCards = true, string searchProvider = null)
{
return ContentQuery.Search(term, useWildCards, searchProvider);
}
///
/// Searhes content
///
///
///
///
public dynamic Search(Examine.SearchCriteria.ISearchCriteria criteria, Examine.Providers.BaseSearchProvider searchProvider = null)
{
return ContentQuery.Search(criteria, searchProvider);
}
///
/// Searches content
///
///
///
///
///
public IEnumerable TypedSearch(string term, bool useWildCards = true, string searchProvider = null)
{
return ContentQuery.TypedSearch(term, useWildCards, searchProvider);
}
///
/// Searhes content
///
///
///
///
public IEnumerable TypedSearch(Examine.SearchCriteria.ISearchCriteria criteria, Examine.Providers.BaseSearchProvider searchProvider = null)
{
return ContentQuery.TypedSearch(criteria, searchProvider);
}
#endregion
#region Xml
public dynamic ToDynamicXml(string xml)
{
if (string.IsNullOrWhiteSpace(xml)) return null;
var xElement = XElement.Parse(xml);
return new DynamicXml(xElement);
}
public dynamic ToDynamicXml(XElement xElement)
{
return new DynamicXml(xElement);
}
public dynamic ToDynamicXml(XPathNodeIterator xpni)
{
return new DynamicXml(xpni);
}
#endregion
#region Strings
///
/// Replaces text line breaks with html line breaks
///
/// The text.
/// The text with text line breaks replaced with html linebreaks ( )
public string ReplaceLineBreaksForHtml(string text)
{
return _stringUtilities.ReplaceLineBreaksForHtml(text);
}
///
/// Returns an MD5 hash of the string specified
///
/// The text to create a hash from
/// Md5 hash of the string
[Obsolete("Please use the CreateHash method instead. This may be removed in future versions")]
[EditorBrowsable(EditorBrowsableState.Never)]
public string CreateMd5Hash(string text)
{
return text.ToMd5();
}
///
/// Generates a hash based on the text string passed in. This method will detect the
/// security requirements (is FIPS enabled) and return an appropriate hash.
///
/// The text to create a hash from
/// Hash of the text string
public string CreateHash(string text)
{
return text.GenerateHash();
}
///
/// Strips all html tags from a given string, all contents of the tags will remain.
///
public HtmlString StripHtml(IHtmlString html, params string[] tags)
{
return StripHtml(html.ToHtmlString(), tags);
}
///
/// Strips all html tags from a given string, all contents of the tags will remain.
///
public HtmlString StripHtml(DynamicNull html, params string[] tags)
{
return new HtmlString(string.Empty);
}
///
/// Strips all html tags from a given string, all contents of the tags will remain.
///
public HtmlString StripHtml(string html, params string[] tags)
{
return _stringUtilities.StripHtmlTags(html, tags);
}
///
/// Will take the first non-null value in the collection and return the value of it.
///
public string Coalesce(params object[] args)
{
return _stringUtilities.Coalesce(args);
}
///
/// Will take the first non-null value in the collection and return the value of it.
///
public string Concatenate(params object[] args)
{
return _stringUtilities.Concatenate(args);
}
///
/// Joins any number of int/string/objects into one string and seperates them with the string seperator parameter.
///
public string Join(string seperator, params object[] args)
{
return _stringUtilities.Join(seperator, args);
}
///
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
///
public IHtmlString Truncate(IHtmlString html, int length)
{
return Truncate(html.ToHtmlString(), length, true, false);
}
///
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
///
public IHtmlString Truncate(IHtmlString html, int length, bool addElipsis)
{
return Truncate(html.ToHtmlString(), length, addElipsis, false);
}
///
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
///
public IHtmlString Truncate(IHtmlString html, int length, bool addElipsis, bool treatTagsAsContent)
{
return Truncate(html.ToHtmlString(), length, addElipsis, treatTagsAsContent);
}
///
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
///
public IHtmlString Truncate(DynamicNull html, int length)
{
return new HtmlString(string.Empty);
}
///
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
///
public IHtmlString Truncate(DynamicNull html, int length, bool addElipsis)
{
return new HtmlString(string.Empty);
}
///
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
///
public IHtmlString Truncate(DynamicNull html, int length, bool addElipsis, bool treatTagsAsContent)
{
return new HtmlString(string.Empty);
}
///
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
///
public IHtmlString Truncate(string html, int length)
{
return Truncate(html, length, true, false);
}
///
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
///
public IHtmlString Truncate(string html, int length, bool addElipsis)
{
return Truncate(html, length, addElipsis, false);
}
///
/// Truncates a string to a given length, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
///
public IHtmlString Truncate(string html, int length, bool addElipsis, bool treatTagsAsContent)
{
return _stringUtilities.Truncate(html, length, addElipsis, treatTagsAsContent);
}
#region Truncate by Words
///
/// Truncates a string to a given amount of words, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
///
public IHtmlString TruncateByWords(string html, int words)
{
int length = _stringUtilities.WordsToLength(html, words);
return Truncate(html, length, true, false);
}
///
/// Truncates a string to a given amount of words, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
///
public IHtmlString TruncateByWords(string html, int words, bool addElipsis)
{
int length = _stringUtilities.WordsToLength(html, words);
return Truncate(html, length, addElipsis, false);
}
///
/// Truncates a string to a given amount of words, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
///
public IHtmlString TruncateByWords(IHtmlString html, int words)
{
int length = _stringUtilities.WordsToLength(html.ToHtmlString(), words);
return Truncate(html, length, true, false);
}
///
/// Truncates a string to a given amount of words, can add a elipsis at the end (...). Method checks for open html tags, and makes sure to close them
///
public IHtmlString TruncateByWords(IHtmlString html, int words, bool addElipsis)
{
int length = _stringUtilities.WordsToLength(html.ToHtmlString(), words);
return Truncate(html, length, addElipsis, false);
}
#endregion
#endregion
#region If
///
/// If the test is true, the string valueIfTrue will be returned, otherwise the valueIfFalse will be returned.
///
public HtmlString If(bool test, string valueIfTrue, string valueIfFalse)
{
return test ? new HtmlString(valueIfTrue) : new HtmlString(valueIfFalse);
}
///
/// If the test is true, the string valueIfTrue will be returned, otherwise the valueIfFalse will be returned.
///
public HtmlString If(bool test, string valueIfTrue)
{
return test ? new HtmlString(valueIfTrue) : new HtmlString(string.Empty);
}
#endregion
#region Prevalues
///
/// Gets a specific PreValue by its Id
///
/// Id of the PreValue to retrieve the value from
/// PreValue as a string
public string GetPreValueAsString(int id)
{
return DataTypeService.GetPreValueAsString(id);
}
#endregion
#region canvasdesigner
[Obsolete("Use EnableCanvasDesigner on the HtmlHelper extensions instead")]
public IHtmlString EnableCanvasDesigner()
{
return EnableCanvasDesigner(string.Empty, string.Empty);
}
[Obsolete("Use EnableCanvasDesigner on the HtmlHelper extensions instead")]
public IHtmlString EnableCanvasDesigner(string canvasdesignerConfigPath)
{
return EnableCanvasDesigner(canvasdesignerConfigPath, string.Empty);
}
[Obsolete("Use EnableCanvasDesigner on the HtmlHelper extensions instead")]
public IHtmlString EnableCanvasDesigner(string canvasdesignerConfigPath, string canvasdesignerPalettesPath)
{
var html = CreateHtmlHelper("");
var urlHelper = new UrlHelper(UmbracoContext.HttpContext.Request.RequestContext);
return html.EnableCanvasDesigner(urlHelper, UmbracoContext, canvasdesignerConfigPath, canvasdesignerPalettesPath);
}
[Obsolete("This shouldn't need to be used but because the obsolete extension methods above don't have access to the current HtmlHelper, we need to create a fake one, unfortunately however this will not pertain the current views viewdata, tempdata or model state so should not be used")]
private HtmlHelper CreateHtmlHelper(object model)
{
var cc = new ControllerContext
{
RequestContext = UmbracoContext.HttpContext.Request.RequestContext
};
var viewContext = new ViewContext(cc, new FakeView(), new ViewDataDictionary(model), new TempDataDictionary(), new StringWriter());
var htmlHelper = new HtmlHelper(viewContext, new ViewPage());
return htmlHelper;
}
[Obsolete("This shouldn't need to be used but because the obsolete extension methods above don't have access to the current HtmlHelper, we need to create a fake one, unfortunately however this will not pertain the current views viewdata, tempdata or model state so should not be used")]
private class FakeView : IView
{
public void Render(ViewContext viewContext, TextWriter writer)
{
}
}
#endregion
///
/// This is used in methods like BeginUmbracoForm and SurfaceAction to generate an encrypted string which gets submitted in a request for which
/// Umbraco can decrypt during the routing process in order to delegate the request to a specific MVC Controller.
///
///
///
///
///
///
internal static string CreateEncryptedRouteString(string controllerName, string controllerAction, string area, object additionalRouteVals = null)
{
Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName");
Mandate.ParameterNotNullOrEmpty(controllerAction, "controllerAction");
Mandate.ParameterNotNull(area, "area");
//need to create a params string as Base64 to put into our hidden field to use during the routes
var surfaceRouteParams = string.Format("c={0}&a={1}&ar={2}",
HttpUtility.UrlEncode(controllerName),
HttpUtility.UrlEncode(controllerAction),
area);
//checking if the additional route values is already a dictionary and convert to querystring
string additionalRouteValsAsQuery;
if (additionalRouteVals != null)
{
var additionalRouteValsAsDictionary = additionalRouteVals as Dictionary;
if (additionalRouteValsAsDictionary != null)
additionalRouteValsAsQuery = additionalRouteValsAsDictionary.ToQueryString();
else
additionalRouteValsAsQuery = additionalRouteVals.ToDictionary().ToQueryString();
}
else
additionalRouteValsAsQuery = null;
if (additionalRouteValsAsQuery.IsNullOrWhiteSpace() == false)
surfaceRouteParams += "&" + additionalRouteValsAsQuery;
return surfaceRouteParams.EncryptWithMachineKey();
}
public int GetIdForUdi(Udi udi)
{
var udiToIdAttempt = EntityService.GetIdForUdi(udi);
return udiToIdAttempt.Success ? udiToIdAttempt.Result : -1;
}
}
}