using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Xml;
using System.Xml.XPath;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.media;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.propertytype;
using umbraco.cms.businesslogic.relation;
using umbraco.cms.businesslogic.web;
using umbraco.cms.helpers;
using umbraco.presentation.cache;
using umbraco.scripting;
using umbraco.DataLayer;
using System.Web.Security;
using umbraco.cms.businesslogic.language;
using umbraco.IO;
using umbraco.presentation;
using System.Collections;
using System.Collections.Generic;
namespace umbraco
{
///
/// Function library for umbraco. Includes various helper-methods and methods to
/// save and load data from umbraco.
///
/// Especially usefull in XSLT where any of these methods can be accesed using the umbraco.library name-space. Example:
/// <xsl:value-of select="umbraco.library:NiceUrl(@id)"/>
///
public class library
{
#region Declarations
///
/// Used by umbraco's publishing enginge, to determine if publishing is currently active
///
public static bool IsPublishing = false;
///
/// Used by umbraco's publishing enginge, to how many nodes is publish in the current publishing cycle
///
public static int NodesPublished = 0;
///
/// Used by umbraco's publishing enginge, to determine the start time of the current publishing cycle.
///
public static DateTime PublishStart;
private page _page;
#endregion
#region Properties
protected static ISqlHelper SqlHelper
{
get { return umbraco.BusinessLogic.Application.SqlHelper; }
}
#endregion
#region Constructors
///
/// Empty constructor
///
public library()
{
}
public library(int id)
{
_page = new page(((System.Xml.IHasXmlNode)GetXmlNodeById(id.ToString()).Current).GetNode());
}
///
/// Initializes a new instance of the class.
///
/// The page.
public library(page page)
{
_page = page;
}
#endregion
#region Python Helper functions
///
/// Executes the given python script and returns the standardoutput.
/// The Globals known from python macros are not accessible in this context.
/// Neither macro or page nor the globals known from python macros are
/// accessible in this context. Only stuff we initialized in site.py
/// can be used.
///
/// The filename of the python script including the extension .py
/// Returns the StandardOutput
public static string PythonExecuteFile(string file)
{
try
{
string path = IOHelper.MapPath(SystemDirectories.Python + "/" + file);
object res = python.executeFile(path);
return res.ToString();
}
catch (Exception e)
{
return e.Message;
}
}
///
/// Executes the given python expression and returns the standardoutput.
/// The Globals known from python macros are not accessible in this context.
/// Neighter macro or page nor the globals known from python macros are
/// accessible in this context. Only stuff we initialized in site.py
/// can be used.
///
/// Python expression to execute
/// Returns the StandardOutput
public static string PythonExecute(string expression)
{
try
{
object res = python.execute(expression);
return res.ToString();
}
catch (Exception e)
{
return e.Message;
}
}
#endregion
#region Publish Helper Methods
// Esben Carlsen: Commented out, not referenced anywhere
/////
///// Updates nodes and eventually subnodes, making the latest version the one to be published.
///// Should always be used with library.rePublishNodes(), to ensure that the xml source is
///// updated
/////
///// Publish childnodes as well
/////
//public static void PublishDocument(Guid nodeID, bool publishChildren, User u)
//{
// Document d = new Document(nodeID, true);
// d.Publish(u);
// NodesPublished++;
// if(publishChildren)
// foreach(Document dc in d.Children)
// {
// PublishDocument(dc.UniqueId, true, u);
// }
//}
///
/// Unpublish a node, by removing it from the runtime xml index. Note, prior to this the Document should be
/// marked unpublished by setting the publish property on the document object to false
///
/// The Id of the Document to be unpublished
public static void UnPublishSingleNode(int DocumentId)
{
//PPH Added dispatcher support
if (UmbracoSettings.UseDistributedCalls)
dispatcher.Remove(
new Guid("27ab3022-3dfa-47b6-9119-5945bc88fd66"),
DocumentId);
else
content.Instance.ClearDocumentCache(DocumentId);
}
///
/// Publishes a Document by adding it to the runtime xml index. Note, prior to this the Document should be
/// marked published by calling Publish(User u) on the document object.
///
/// The Id of the Document to be published
public static void UpdateDocumentCache(int DocumentId)
{
if (UmbracoSettings.UseDistributedCalls)
dispatcher.Refresh(
new Guid("27ab3022-3dfa-47b6-9119-5945bc88fd66"),
DocumentId);
else
content.Instance.UpdateDocumentCache(DocumentId);
}
///
/// Publishes the single node, this method is obsolete
///
/// The document id.
[Obsolete("Please use: umbraco.library.UpdateDocumentCache")]
public static void PublishSingleNode(int DocumentId)
{
UpdateDocumentCache(DocumentId);
}
///
/// Refreshes the xml cache for all nodes
///
public static void RefreshContent()
{
if (UmbracoSettings.UseDistributedCalls)
{
dispatcher.RefreshAll(new Guid("27ab3022-3dfa-47b6-9119-5945bc88fd66"));
}
else
{
content.Instance.RefreshContentFromDatabaseAsync();
}
}
///
/// Re-publishes all nodes under a given node
///
/// The ID of the node and childnodes that should be republished
[Obsolete("Please use: umbraco.library.RefreshContent")]
public static string RePublishNodes(int nodeID)
{
//PPH - added dispatcher support to this call..
if (UmbracoSettings.UseDistributedCalls)
dispatcher.RefreshAll(new Guid("27ab3022-3dfa-47b6-9119-5945bc88fd66"));
else
{
content.Instance.RefreshContentFromDatabaseAsync();
}
return string.Empty;
}
///
/// Re-publishes all nodes under a given node
///
/// The ID of the node and childnodes that should be republished
[Obsolete("Please use: umbraco.library.RefreshContent")]
public static void RePublishNodesDotNet(int nodeID)
{
content.Instance.RefreshContentFromDatabaseAsync();
}
//private static Hashtable parents = new Hashtable();
//private static Hashtable nodes = new Hashtable();
//private static int nodeRepublishCounter = 0;
//public static void RePublishNodesDotNet(int nodeID)
//{
// RePublishNodesDotNet(nodeID, true);
//}
// Esben Carlsen: Commented out, is not referenced anywhere
//public static void _RePublishNodesDotNet(int nodeID, bool SaveToDisk)
//{
// content.isInitializing = true;
// content.Instance.XmlContent = null;
// BusinessLogic.Log.Add(BusinessLogic.LogTypes.Debug, BusinessLogic.User.GetUser(0), -1, "Republishing starting");
// cms.businesslogic.cache.Cache.ClearAllCache();
// XmlDocument xmlDoc = new XmlDocument();
// // Create id -1 attribute
// xmlDoc.LoadXml("");
// XmlNode n = xmlDoc.DocumentElement;
// buildNodes(ref xmlDoc, ref n, -1);
// content.Instance.XmlContent.Load(n.OuterXml);
// // reload xml
// n = null;
// xmlDoc = null;
// if (SaveToDisk)
// content.SaveCacheToDisk(false);
// // Reload content
// requestHandler.ClearProcessedRequests();
// content.clearContentCache();
// BusinessLogic.Log.Add(BusinessLogic.LogTypes.Debug, BusinessLogic.User.GetUser(0), -1, "Republishing done");
// content.isInitializing = false;
//}
// private static void buildNodes(ref XmlDocument Xd, ref XmlNode CurrentElement, int ParentId)
// {
// string sql =
// @"select umbracoNode.id, umbracoNode.sortOrder, cmsContentXml.xml from umbracoNode
// inner join cmsContentXml on cmsContentXml.nodeId = umbracoNode.id and umbracoNode.nodeObjectType = 'C66BA18E-EAF3-4CFF-8A22-41B16D66A972'
// and umbracoNode.parentId = @parentId
// order by umbracoNode.sortOrder";
// IRecordsReader dr =
// SqlHelper.ExecuteReader(sql, SqlHelper.CreateParameter("@parentId", ParentId));
// while(dr.Read())
// {
// int currentId = int.Parse(dr["id"].ToString());
// XmlNode n = xmlHelper.ImportXmlNodeFromText(dr["xml"].ToString(), ref Xd);
// CurrentElement.AppendChild(n);
// buildNodes(ref Xd, ref n, currentId);
// }
// dr.Close();
// }
///
/// Refreshes the runtime xml index.
/// Note: This *doesn't* mark any non-published document objects as published
///
/// Always use -1
/// Not used
[Obsolete("Please use: content.Instance.RefreshContentFromDatabaseAsync")]
public static void RePublishNodesDotNet(int nodeID, bool SaveToDisk)
{
content.Instance.RefreshContentFromDatabaseAsync();
}
#endregion
#region Xslt Helper functions
///
/// Add a session variable to the current user
///
/// The Key of the variable
/// The Value
public static void setSession(string key, string value)
{
if (HttpContext.Current.Session != null)
HttpContext.Current.Session[key] = value;
}
///
/// Add a cookie variable to the current user
///
/// The Key of the variable
/// The Value of the variable
public static void setCookie(string key, string value)
{
StateHelper.SetCookieValue(key, value);
}
///
/// 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 static string NiceUrl(int nodeID)
{
try
{
int startNode = 1;
if (GlobalSettings.HideTopLevelNodeFromPath)
startNode = 2;
return niceUrlDo(nodeID, startNode);
}
catch
{
return "#";
}
}
///
/// This method will always add the root node to the path. You should always use NiceUrl, as that is the
/// only one who checks for toplevel node settings in the web.config
///
/// Identifier for the node that should be returned
/// String with a friendly url from a node
public static string NiceUrlFullPath(int nodeID)
{
return niceUrlDo(nodeID, 1);
}
public static string ResolveVirtualPath(string path)
{
return IOHelper.ResolveUrl(path);
}
private static string niceUrlDo(int nodeID, int startNodeDepth)
{
bool directoryUrls = GlobalSettings.UseDirectoryUrls;
string baseUrl = SystemDirectories.Root; // SystemDirectories.Umbraco;
//baseUrl = baseUrl.Substring(0, baseUrl.LastIndexOf("/"));
bool atDomain = false;
string currentDomain = HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToLower();
if (UmbracoSettings.UseDomainPrefixes && Domain.Exists(currentDomain))
atDomain = true;
// Find path from nodeID
String tempUrl = "";
XmlElement node = UmbracoContext.Current.GetXml().GetElementById(nodeID.ToString());
String[] splitpath = null;
if (node != null)
{
try
{
splitpath =
node.Attributes.GetNamedItem("path").Value.ToString().
Split(",".ToCharArray());
int startNode = startNodeDepth;
// check root nodes for domains
if (UmbracoSettings.UseDomainPrefixes && startNode > 1)
{
if (node.ParentNode.Name.ToLower() == "node")
{
Domain[] domains =
Domain.GetDomainsById(int.Parse(node.ParentNode.Attributes.GetNamedItem("id").Value));
if (
domains.Length > 0)
{
tempUrl =
getUrlByDomain(int.Parse(node.ParentNode.Attributes.GetNamedItem("id").Value), "",
atDomain, currentDomain, true);
}
// test for domains on root nodes, then make the url domain only
}
else if (Domain.GetDomainsById(nodeID).Length > 0)
{
tempUrl = getUrlByDomain(nodeID, "",
false, currentDomain, false);
return tempUrl;
}
}
if (splitpath.Length > startNode)
{
for (int i = startNode; i < splitpath.Length; i++)
{
tempUrl = getUrlByDomain(int.Parse(splitpath[i]), tempUrl, atDomain, currentDomain, false);
}
}
else
{
// check the root node for language
tempUrl += getUrlByDomain(nodeID, "", atDomain, currentDomain, false);
}
}
catch (Exception e)
{
HttpContext.Current.Trace.Warn("library.NiceUrl",
string.Format("Error generating nice url for id '{0}'", nodeID), e);
tempUrl = "/" + nodeID;
}
tempUrl = appendUrlExtension(baseUrl, directoryUrls, tempUrl);
}
else
HttpContext.Current.Trace.Warn("niceurl", string.Format("No node found at '{0}'", nodeID));
return tempUrl;
}
private static string appendUrlExtension(string baseUrl, bool directoryUrls, string tempUrl)
{
if (!directoryUrls)
// append .aspx extension if the url includes other than just the domain name
if (tempUrl.ToString() != "" &&
(!tempUrl.StartsWith("http://") || tempUrl.Replace("http://", "").IndexOf("/") > -1))
tempUrl = baseUrl + tempUrl + ".aspx";
return tempUrl;
}
private static string getUrlByDomain(int DocumentId, string tempUrl, bool atDomain, string currentDomain,
bool emptyOnSameDomain)
{
Domain[] domains = Domain.GetDomainsById(DocumentId);
if (!UmbracoSettings.UseDomainPrefixes || domains.Length == 0)
tempUrl += "/" +
url.FormatUrl(
UmbracoContext.Current.GetXml().GetElementById(DocumentId.ToString()).Attributes.GetNamedItem
("urlName").Value);
else
{
// check if one of the domains are the same as the current one
if (atDomain)
{
bool inDomainRange = false;
foreach (Domain d in domains)
if (d.Name.ToLower() == currentDomain)
{
inDomainRange = true;
break;
}
if (inDomainRange)
{
if (emptyOnSameDomain)
return tempUrl;
else
tempUrl = "/" +
url.FormatUrl(
UmbracoContext.Current.GetXml().GetElementById(DocumentId.ToString()).Attributes.
GetNamedItem("urlName").Value);
}
else
tempUrl = "http://" + domains[0].Name;
}
else
tempUrl = "http://" + domains[0].Name;
}
return tempUrl;
}
///
/// Returns a string with the data from the given element of a node. Both elements (data-fields)
/// and properties can be used - ie:
/// getItem(1, nodeName) will return a string with the name of the node with id=1 even though
/// nodeName is a property and not an element (data-field).
///
/// Identifier for the node that should be returned
/// The element that should be returned
/// Returns a string with the data from the given element of a node
public static string GetItem(int nodeID, String alias)
{
XmlDocument umbracoXML = UmbracoContext.Current.GetXml();
if (umbracoXML.GetElementById(nodeID.ToString()) != null)
if (
",id,version,parentID,level,writerID,editDataType,template,sortOrder,createDate,updateDate,nodeName,writerName,path,"
.
IndexOf("," + alias + ",") > -1)
return umbracoXML.GetElementById(nodeID.ToString()).Attributes.GetNamedItem(alias).Value;
else if (
umbracoXML.GetElementById(nodeID.ToString()).SelectSingleNode("./data [@alias='" + alias + "']") !=
null)
return
umbracoXML.GetElementById(nodeID.ToString()).SelectSingleNode("./data [@alias = '" + alias +
"']").ChildNodes[0].
Value; //.Value + "*";
else
return string.Empty;
else
return string.Empty;
}
///
/// Checks with the Assigned domains settings and retuns an array the the Domains matching the node
///
/// Identifier for the node that should be returned
/// A Domain array with all the Domains that matches the nodeId
public static Domain[] GetCurrentDomains(int NodeId)
{
string[] pathIds = GetItem(NodeId, "path").Split(',');
for (int i = pathIds.Length - 1; i > 0; i--)
{
Domain[] retVal = Domain.GetDomainsById(int.Parse(pathIds[i]));
if (retVal.Length > 0)
{
return retVal;
}
}
return null;
}
///
/// Returns a string with the data from the given element of the current node. Both elements (data-fields)
/// and properties can be used - ie:
/// getItem(nodeName) will return a string with the name of the current node/page even though
/// nodeName is a property and not an element (data-field).
///
///
///
public static string GetItem(String alias)
{
try
{
int currentID = int.Parse(HttpContext.Current.Items["pageID"].ToString());
return GetItem(currentID, alias);
}
catch (Exception ItemException)
{
HttpContext.Current.Trace.Warn("library.GetItem", "Error reading '" + alias + "'", ItemException);
return string.Empty;
}
}
///
/// Returns that name of a generic property
///
/// The Alias of the content type (ie. Document Type, Member Type or Media Type)
/// The Alias of the Generic property (ie. bodyText or umbracoNaviHide)
/// A string with the name. If nothing matches the alias, an empty string is returned
public static string GetPropertyTypeName(string ContentTypeAlias, string PropertyTypeAlias)
{
try
{
umbraco.cms.businesslogic.ContentType ct = umbraco.cms.businesslogic.ContentType.GetByAlias(ContentTypeAlias);
PropertyType pt = ct.getPropertyType(PropertyTypeAlias);
return pt.Name;
}
catch
{
return string.Empty;
}
}
///
/// Returns the Member Name from an umbraco member object
///
/// The identifier of the Member
/// The Member name matching the MemberId, an empty string is member isn't found
public static string GetMemberName(int MemberId)
{
if (MemberId != 0)
{
try
{
Member m = new Member(MemberId);
return m.Text;
}
catch
{
return string.Empty;
}
}
else
return string.Empty;
}
///
/// Get a media object as an xml object
///
/// The identifier of the media object to be returned
/// If true, children of the media object is returned
/// An umbraco xml node of the media (same format as a document node)
public static XPathNodeIterator GetMedia(int MediaId, bool Deep)
{
try
{
Media m = new Media(MediaId);
if (m.nodeObjectType == Media._objectType)
{
XmlDocument mXml = new XmlDocument();
mXml.LoadXml(m.ToXml(mXml, Deep).OuterXml);
XPathNavigator xp = mXml.CreateNavigator();
return xp.Select("/node");
}
}
catch
{
}
XmlDocument xd = new XmlDocument();
xd.LoadXml(string.Format("No media is maching '{0}'", MediaId));
return xd.CreateNavigator().Select("/");
}
///
/// Get a member as an xml object
///
/// The identifier of the member object to be returned
/// An umbraco xml node of the member (same format as a document node), but with two additional attributes on the "node" element:
/// "email" and "loginName".
///
public static XPathNodeIterator GetMember(int MemberId)
{
try
{
Member m = new Member(MemberId);
XmlDocument mXml = new XmlDocument();
mXml.LoadXml(m.ToXml(mXml, false).OuterXml);
XPathNavigator xp = mXml.CreateNavigator();
return xp.Select("/node");
}
catch
{
}
XmlDocument xd = new XmlDocument();
xd.LoadXml(string.Format("No member is maching '{0}'", MemberId));
return xd.CreateNavigator().Select("/");
}
///
/// Get the current member as an xml node
///
/// Look in documentation for umbraco.library.GetMember(MemberId) for more information
public static XPathNodeIterator GetCurrentMember()
{
Member m = Member.GetCurrentMember();
if (m != null)
{
XmlDocument mXml = new XmlDocument();
mXml.LoadXml(m.ToXml(mXml, false).OuterXml);
XPathNavigator xp = mXml.CreateNavigator();
return xp.Select("/node");
}
XmlDocument xd = new XmlDocument();
xd.LoadXml(
"No current member exists (best practice is to validate with 'isloggedon()' prior to this call)");
return xd.CreateNavigator().Select("/");
}
///
/// Whether or not the current user is logged in (as a member)
///
/// True is the current user is logged in
public static bool IsLoggedOn()
{
/*
MembershipUser u = Membership.GetUser();
return u != null;
*/
return Member.IsLoggedOn();
}
public static XPathNodeIterator AllowedGroups(int documentId, string path)
{
XmlDocument xd = new XmlDocument();
xd.LoadXml("");
foreach (string role in Access.GetAccessingMembershipRoles(documentId, path))
xd.DocumentElement.AppendChild(xmlHelper.addTextNode(xd, "role", role));
return xd.CreateNavigator().Select(".");
}
///
/// Check if a document object is protected by the "Protect Pages" functionality in umbraco
///
/// The identifier of the document object to check
/// The full path of the document object to check
/// True if the document object is protected
public static bool IsProtected(int DocumentId, string Path)
{
return Access.IsProtected(DocumentId, Path);
}
///
/// Check if the current user has access to a document
///
/// The identifier of the document object to check
/// 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 static bool HasAccess(int NodeId, string Path)
{
if (IsProtected(NodeId, Path))
{
if (Member.IsLoggedOn())
return Access.HasAccess(NodeId, Path, Membership.GetUser());
else
return false;
}
else
return true;
}
///
/// Encrypts the string using md5
///
/// The text.
/// Md5 encrupted string
public static string md5(string text)
{
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(text);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
return s.ToString();
}
///
/// Compare two dates
///
/// The first date to compare
/// The second date to compare
/// True if the first date is greater than the second date
public static bool DateGreaterThan(string firstDate, string secondDate)
{
if (DateTime.Parse(firstDate) > DateTime.Parse(secondDate))
return true;
else
return false;
}
///
/// Compare two dates
///
/// The first date to compare
/// The second date to compare
/// True if the first date is greater than or equal the second date
public static bool DateGreaterThanOrEqual(string firstDate, string secondDate)
{
if (DateTime.Parse(firstDate) >= DateTime.Parse(secondDate))
return true;
else
return false;
}
///
/// Check if a date is greater than today
///
/// The date to check
/// True if the date is greater that today (ie. at least the day of tomorrow)
public static bool DateGreaterThanToday(string firstDate)
{
DateTime first = DateTime.Parse(firstDate);
first = new DateTime(first.Year, first.Month, first.Day);
DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
TimeSpan TS = new TimeSpan(first.Ticks - today.Ticks);
if (TS.Days > 0)
return true;
else
return false;
}
///
/// Check if a date is greater than or equal today
///
/// The date to check
/// True if the date is greater that or equal today (ie. at least today or the day of tomorrow)
public static bool DateGreaterThanOrEqualToday(string firstDate)
{
DateTime first = DateTime.Parse(firstDate);
first = new DateTime(first.Year, first.Month, first.Day);
DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
TimeSpan TS = new TimeSpan(first.Ticks - today.Ticks);
if (TS.Days >= 0)
return true;
else
return false;
}
///
/// Get the current date
///
/// Current date i xml format (ToString("s"))
public static string CurrentDate()
{
return DateTime.Now.ToString("s");
}
///
/// Add a value to a date
///
/// The Date to user
/// The type to add: "y": year, "m": month, "d": day, "h": hour, "min": minutes, "s": seconds
/// An integer value to add
/// A date in xml format (ToString("s"))
public static string DateAdd(string Date, string AddType, int add)
{
return DateAddWithDateTimeObject(DateTime.Parse(Date), AddType, add);
}
///
/// Get the day of week from a date matching the current culture settings
///
/// The date to use
/// A string with the DayOfWeek matching the current contexts culture settings
public static string GetWeekDay(string Date)
{
return DateTime.Parse(Date).ToString("dddd");
}
///
/// Add a value to a date. Similar to the other overload, but uses a datetime object instead of a string
///
/// The Date to user
/// The type to add: "y": year, "m": month, "d": day, "h": hour, "min": minutes, "s": seconds
/// An integer value to add
/// A date in xml format (ToString("s"))
public static string DateAddWithDateTimeObject(DateTime Date, string AddType, int add)
{
switch (AddType.ToLower())
{
case "y":
Date = Date.AddYears(add);
break;
case "m":
Date = Date.AddMonths(add);
break;
case "d":
Date = Date.AddDays(add);
break;
case "h":
Date = Date.AddHours(add);
break;
case "min":
Date = Date.AddMinutes(add);
break;
case "s":
Date = Date.AddSeconds(add);
break;
}
return Date.ToString("s");
}
///
/// Return the difference between 2 dates, in either minutes, seconds or years.
///
/// The first date.
/// The second date.
/// format to return, can only be: s,m or y: s = seconds, m = minutes, y = years.
/// A timespan as a integer
public static int DateDiff(string firstDate, string secondDate, string diffType)
{
TimeSpan TS = DateTime.Parse(firstDate).Subtract(DateTime.Parse(secondDate));
switch (diffType.ToLower())
{
case "m":
return Convert.ToInt32(TS.TotalMinutes);
case "s":
return Convert.ToInt32(TS.TotalSeconds);
case "y":
return Convert.ToInt32(TS.TotalDays / 365);
}
// return default
return 0;
}
///
/// Formats a string to the specified formate.
///
/// The date.
/// The format, compatible with regular .net date formats
/// A date in the new format as a string
public static string FormatDateTime(string Date, string Format)
{
DateTime result;
if (DateTime.TryParse(Date, out result))
return result.ToString(Format);
return string.Empty;
}
///
/// Converts a string to Long Date and returns it as a string
///
/// The date.
/// if set to true the date will include time.
/// The splitter between date and time.
/// A Long Date as a string.
public static string LongDate(string Date, bool WithTime, string TimeSplitter)
{
DateTime result;
if (DateTime.TryParse(Date, out result))
{
if (WithTime)
return result.ToLongDateString() + TimeSplitter + result.ToLongTimeString();
return result.ToLongDateString();
}
return string.Empty;
}
///
/// Checks whether the Culture with the specified name exixts in the standard .net cultureInfo.
///
/// Name of the culture.
///
public static bool CultureExists(string cultureName)
{
CultureInfo[] ci = CultureInfo.GetCultures(CultureTypes.AllCultures);
CultureInfo c = Array.Find(ci, delegate(CultureInfo culture) { return culture.Name == cultureName; });
return c != null;
}
///
/// Converts a string to datetime in the longdate with day name format.
///
/// The date.
/// String between day name and date
/// if set to true the datetiem will include time.
/// String between date and time.
/// Culture name.
/// A datetime in the longdate formate with day name, as a string
public static string LongDateWithDayName(string Date, string DaySplitter, bool WithTime, string TimeSplitter,
string GlobalAlias)
{
if (!CultureExists(GlobalAlias))
return string.Empty;
DateTime result;
CultureInfo.GetCultureInfo(GlobalAlias);
DateTimeFormatInfo dtInfo = CultureInfo.GetCultureInfo(GlobalAlias).DateTimeFormat;
if (DateTime.TryParse(Date, dtInfo, DateTimeStyles.None, out result))
{
if (WithTime)
return
result.ToString(dtInfo.LongDatePattern) + TimeSplitter + result.ToString(dtInfo.LongTimePattern);
return result.ToString(dtInfo.LongDatePattern);
}
return string.Empty;
}
///
/// Converts a string to a Long Date and returns it as a string
///
/// The date.
/// A Long Date as a string.
public static string LongDate(string Date)
{
DateTime result;
if (DateTime.TryParse(Date, out result))
return result.ToLongDateString();
return string.Empty;
}
///
/// Converts a string to a Short Date and returns it as a string
///
/// The date.
/// A Short Date as a string.
public static string ShortDate(string Date)
{
DateTime result;
if (DateTime.TryParse(Date, out result))
return result.ToShortDateString();
return string.Empty;
}
///
/// Converts a string to a Short Date, with a specific culture, and returns it as a string
///
/// The date.
/// Culture name
/// A short date with a specific culture, as a string
public static string ShortDateWithGlobal(string Date, string GlobalAlias)
{
if (!CultureExists(GlobalAlias))
return string.Empty;
DateTime result;
if (DateTime.TryParse(Date, out result))
{
DateTimeFormatInfo dtInfo = CultureInfo.GetCultureInfo(GlobalAlias).DateTimeFormat;
return result.ToString(dtInfo.ShortDatePattern);
}
return string.Empty;
}
///
/// Converts a string to a Short Date with time, with a specific culture, and returns it as a string
///
/// The date.
/// Culture name
/// A short date withi time, with a specific culture, as a string
public static string ShortDateWithTimeAndGlobal(string Date, string GlobalAlias)
{
if (!CultureExists(GlobalAlias))
return string.Empty;
DateTime result;
if (DateTime.TryParse(Date, out result))
{
DateTimeFormatInfo dtInfo = CultureInfo.GetCultureInfo(GlobalAlias).DateTimeFormat;
return result.ToString(dtInfo.ShortDatePattern) + " " +
result.ToString(dtInfo.ShortTimePattern);
}
return string.Empty;
}
///
/// Converts a datetime string to the ShortTime format.
///
/// The date.
///
public static string ShortTime(string Date)
{
DateTime result;
if (DateTime.TryParse(Date, out result))
return result.ToShortTimeString();
return string.Empty;
}
///
/// Converts a datetime string to the ShortDate format.
///
/// The date.
/// if set to true the date will include time.
/// String dividing date and time
///
public static string ShortDate(string Date, bool WithTime, string TimeSplitter)
{
DateTime result;
if (DateTime.TryParse(Date, out result))
{
if (WithTime)
return result.ToShortDateString() + TimeSplitter + result.ToLongTimeString();
return result.ToShortDateString();
}
return string.Empty;
}
///
/// Replaces text line breaks with html line breaks
///
/// The text.
/// The text with text line breaks replaced with html linebreaks ( )
public static string ReplaceLineBreaks(string text)
{
if (bool.Parse(GlobalSettings.EditXhtmlMode))
return text.Replace("\n", " \n");
else
return text.Replace("\n", " \n");
}
///
/// Renders the content of a macro. Uses the normal template umbraco macro markup as input.
/// This only works properly with xslt macros.
/// Python and .ascx based macros will not render properly, as viewstate is not included.
///
/// The macro markup to be rendered.
/// The page id.
/// The rendered macro as a string
public static string RenderMacroContent(string Text, int PageId)
{
try
{
page p = new page(((IHasXmlNode)GetXmlNodeById(PageId.ToString()).Current).GetNode());
template t = new template(p.Template);
Control c = t.parseStringBuilder(new StringBuilder(Text), p);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
c.RenderControl(hw);
return sw.ToString();
}
catch (Exception ee)
{
return string.Format("", ee);
}
}
///
/// Renders a template.
///
/// The page id.
/// The template id.
/// The rendered template as a string
public static string RenderTemplate(int PageId, int TemplateId)
{
try
{
if (UmbracoSettings.UseAspNetMasterPages)
{
System.Collections.Generic.Dictionary