Skip to content

Instantly share code, notes, and snippets.

@sitefinitysteve
Last active June 10, 2020 01:45
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sitefinitysteve/4333272 to your computer and use it in GitHub Desktop.
Save sitefinitysteve/4333272 to your computer and use it in GitHub Desktop.
SitefinitySteve Extension Collection, included in the RandomSiteControls
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Telerik.Sitefinity
{
public static class CollectionExtensions
{
/// <summary>
/// Shuffle the Enumerable around in a random order
/// ** Sitefinitysteve.com Extension, from StackOverflow **
/// </summary>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
T[] elements = source.ToArray();
for (int i = elements.Length - 1; i >= 0; i--)
{
int swapIndex = rng.Next(i + 1);
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
}
}
}
}
using System;
using System.Linq;
namespace System
{
public static class DateTimeExtensionMethods
{
public static string ToTimeSpanString(this DateTime date){
var ts = new TimeSpan(DateTime.UtcNow.Ticks - date.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
if (delta < 60)
{
return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
}
if (delta < 120)
{
return "a minute ago";
}
if (delta < 2700) // 45 * 60
{
return ts.Minutes + " minutes ago";
}
if (delta < 5400) // 90 * 60
{
return "an hour ago";
}
if (delta < 86400) // 24 * 60 * 60
{
return ts.Hours + " hours ago";
}
if (delta < 172800) // 48 * 60 * 60
{
return "yesterday";
}
if (delta < 2592000) // 30 * 24 * 60 * 60
{
return ts.Days + " days ago";
}
if (delta < 31104000) // 12 * 30 * 24 * 60 * 60
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "one month ago" : months + " months ago";
}
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Telerik.Sitefinity.DynamicModules;
using Telerik.Sitefinity.DynamicModules.Model;
using Telerik.Sitefinity.Libraries.Model;
using Telerik.Sitefinity.Model.ContentLinks;
using Telerik.Sitefinity.Model;
using Telerik.Sitefinity.Taxonomies.Model;
using Telerik.OpenAccess;
using Telerik.Sitefinity.Taxonomies;
using Telerik.Sitefinity.Utilities.TypeConverters;
namespace Telerik.Sitefinity
{
public static class DynamicContentExtensions
{
/// <summary>
/// Get a single image from a content link
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <returns>Telerik.Sitefinity.Libraries.Model.Image object</returns>
public static Image GetImage(this DynamicContent item, string fieldName){
var contentLinks = (ContentLink[])item.GetValue(fieldName);
ContentLink imageContentLink = contentLinks.FirstOrDefault();
return (imageContentLink == null) ? null : imageContentLink.ChildItemId.GetImage();
}
/// <summary>
/// Gets the images from a content link array
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <returns>IQueryable Telerik.Sitefinity.Libraries.Model.Image</returns>
public static IQueryable<Image> GetImages(this DynamicContent item, string fieldName)
{
var contentLinks = (ContentLink[])item.GetValue(fieldName);
var images = from i in contentLinks
select i.ChildItemId.GetImage();
return images.AsQueryable();
}
/// <summary>
/// Get a single document from a content link
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <returns>Telerik.Sitefinity.Libraries.Model.Image object</returns>
public static Document GetDocument(this DynamicContent item, string fieldName){
var contentLinks = (ContentLink[])item.GetValue(fieldName);
ContentLink docContentLink = contentLinks.FirstOrDefault();
return (docContentLink == null) ? null : docContentLink.ChildItemId.GetDocument();
}
/// <summary>
/// Gets the documents from a content link array
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <returns>IQueryable Telerik.Sitefinity.Libraries.Model.Image</returns>
public static IQueryable<Document> GetDocuments(this DynamicContent item, string fieldName)
{
var contentLinks = (ContentLink[])item.GetValue(fieldName);
var docs = from i in contentLinks
select i.ChildItemId.GetDocument();
return docs.AsQueryable();
}
/// <summary>
/// Get the Live Visible items
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <returns>IQueryable<DynamicContent></returns>
public static IQueryable<DynamicContent> Live(this IQueryable<DynamicContent> items){
return items.Where(x => x.Status == GenericContent.Model.ContentLifecycleStatus.Live && x.Visible == true);
}
/// <summary>
/// Get the Master Visible items
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <returns>IQueryable<DynamicContent></returns>
public static IQueryable<DynamicContent> Master(this IQueryable<DynamicContent> items)
{
return items.Where(x => x.Status == GenericContent.Model.ContentLifecycleStatus.Master);
}
/// <summary>
/// Get the Temp Visible items
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <returns>IQueryable<DynamicContent></returns>
public static IQueryable<DynamicContent> Temp(this IQueryable<DynamicContent> items)
{
return items.Where(x => x.Status == GenericContent.Model.ContentLifecycleStatus.Temp);
}
/// <summary>
/// Generic Taxon control, use GetCategories or GetTags for the defaults
/// </summary>
/// <returns>IQueryable<HierarchicalTaxon></returns>
public static List<HierarchicalTaxon> GetHierarchicalTaxons(this DynamicContent item, string fieldName, string taxonomyName)
{
var categories = item.GetValue<TrackedList<Guid>>(fieldName);
TaxonomyManager manager = TaxonomyManager.GetManager();
var taxonomyParent = manager.GetTaxonomies<HierarchicalTaxonomy>().SingleOrDefault(x => x.Name == taxonomyName);
var taxons = taxonomyParent.Taxa.Where(x => categories.Contains(x.Id)).Select(x => (HierarchicalTaxon)x);
return taxons.ToList();
}
/// <summary>
/// Generic Taxon control, use GetCategories or GetTags for the defaults
/// </summary>
/// <returns>IQueryable<HierarchicalTaxon></returns>
public static List<Taxon> GetFlatTaxons(this DynamicContent item, string fieldName)
{
var categories = item.GetValue<TrackedList<Guid>>(fieldName);
TaxonomyManager manager = TaxonomyManager.GetManager();
var taxonomyParent = manager.GetTaxonomies<Taxonomy>().FirstOrDefault(x => x.Name == fieldName);
var taxons = taxonomyParent.Taxa.Where(x => categories.Contains(x.Id)).Select(x => x);
return taxons.ToList();
}
/// <summary>
/// Get the linked Categories
/// </summary>
/// <returns>IQueryable<HierarchicalTaxon></returns>
public static List<HierarchicalTaxon> GetCategories(this DynamicContent item)
{
var categories = item.GetValue<TrackedList<Guid>>("Category");
TaxonomyManager manager = TaxonomyManager.GetManager();
var taxonomyParent = manager.GetTaxonomy<HierarchicalTaxonomy>(TaxonomyManager.CategoriesTaxonomyId);
var taxons = taxonomyParent.Taxa.Where(x => categories.Contains(x.Id)).Select(x => (HierarchicalTaxon)x);
return taxons.ToList();
}
/// <summary>
/// Get the linked Tags
/// </summary>
/// <returns>IQueryable<HierarchicalTaxon></returns>
public static List<Taxon> GetTags(this DynamicContent item)
{
var tags = item.GetValue<TrackedList<Guid>>("Tags");
TaxonomyManager manager = TaxonomyManager.GetManager();
var taxonomyParent = manager.GetTaxonomy<Taxonomy>(TaxonomyManager.TagsTaxonomyId);
var taxons = taxonomyParent.Taxa.Where(x => tags.Contains(x.Id)).ToList();
return taxons;
}
/// <summary>
/// Returns the linked DynamicContent objects
/// ** Sitefinitysteve.com Extension **
/// </summary>
public static IQueryable<DynamicContent> GetRelatedContentItems(this DynamicContent dataItem, string fieldName, string type)
{
var contentLinks = dataItem.GetValue<Guid[]>(fieldName);
var items = contentLinks.GetDynamicContentItems(type);
return items;
}
/// <summary>
/// Returns the linked DynamicContent object
/// ** Sitefinitysteve.com Extension **
/// </summary>
public static DynamicContent GetRelatedContentItem(this DynamicContent dataItem, string fieldName, string type)
{
var contentLink = dataItem.GetValue<Guid>(fieldName);
return contentLink.GetDynamicContent(type);
}
/// <summary>
/// Returns the Child Items of the current DataItem
/// ** Sitefinitysteve.com Extension **
/// </summary>
public static IQueryable<DynamicContent> GetChildren(this DynamicContent dataItem, Type type = null)
{
var manager = DynamicModuleManager.GetManager();
return manager.GetChildItems(dataItem, type);
}
/// <summary>
/// Returns the Child Items of the current DataItems Parent
/// ** Sitefinitysteve.com Extension **
/// </summary>
public static IQueryable<DynamicContent> GetChildrenFromParent(this DynamicContent dataItem, Type type = null)
{
var manager = DynamicModuleManager.GetManager();
return manager.GetChildItems(dataItem.SystemParentItem, type);
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using Telerik.Sitefinity.Data.Metadata;
using Telerik.Sitefinity.Taxonomies;
using Telerik.Sitefinity.Taxonomies.Model;
using Telerik.Sitefinity.DynamicModules.Model;
using Telerik.Sitefinity.Data;
namespace Telerik.Sitefinity.Model
{
public static class GeneralExtensions
{
/// <summary>
/// Gets an objects associated manager
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <returns>An instance of the manager of an object</returns>
public static IManager GetContentManager(this object item){
return ManagerBase.GetMappedManager(item.GetType());
}
/// <summary>
/// Validates a DynamicContent item has a field defined, thx Stacey Schlenker for the update\testing
/// </summary>
/// <param name="dataItem"></param>
/// <param name="field"></param>
/// <returns></returns>
public static bool HasValue(this DynamicContent dataItem, string field){
return App.WorkWith().DynamicData().Type(dataItem.GetType()).Get().Fields.Any(f => f.FieldName == field);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Telerik.Sitefinity.DynamicModules;
using Telerik.Sitefinity.DynamicModules.Model;
using Telerik.Sitefinity.Libraries.Model;
using Telerik.Sitefinity.Modules.Libraries;
using Telerik.Sitefinity.Modules.Pages;
using Telerik.Sitefinity.Pages.Model;
using Telerik.Sitefinity.Utilities.TypeConverters;
namespace Telerik.Sitefinity
{
public static class GuidExtensions
{
/// <summary>
/// Returns an Image object from a Guid
/// ** Sitefinitysteve.com Extension **
/// </summary>
public static Image GetImage(this Guid imageId)
{
LibrariesManager manager = LibrariesManager.GetManager();
return (imageId != Guid.Empty) ? manager.GetImage(imageId) : null;
}
/// <summary>
/// Returns an Document object from a Guid
/// ** Sitefinitysteve.com Extension **
/// </summary>
public static Document GetDocument(this Guid documentId)
{
LibrariesManager manager = LibrariesManager.GetManager();
return (documentId != Guid.Empty) ? manager.GetDocument(documentId) : null;
}
/// <summary>
/// Returns an Album object from a Guid
/// ** Sitefinitysteve.com Extension **
/// </summary>
public static Album GetAlbum(this Guid albumID)
{
LibrariesManager manager = LibrariesManager.GetManager();
return (albumID != Guid.Empty) ? manager.GetAlbum(albumID) : null;
}
/// <summary>
/// Returns a PageNode object from a Guid
/// ** Sitefinitysteve.com Extension **
/// </summary>
public static PageNode GetPage(this Guid pageId)
{
PageManager manager = PageManager.GetManager();
return (pageId != Guid.Empty) ? manager.GetPageNode(pageId) : null;
}
/// <summary>
/// Returns a PageNode object from a Guid
/// ** Sitefinitysteve.com Extension **
/// </summary>
public static PageData GetPageData(this Guid pageId)
{
PageManager manager = PageManager.GetManager();
return (pageId != Guid.Empty) ? manager.GetPageData(pageId) : null;
}
/// <summary>
/// Converts the Guid[] type to the DynamicContent objects
/// ** Sitefinitysteve.com Extension **
/// </summary>
public static IQueryable<DynamicContent> GetDynamicContentItems(this Guid[] contentLinks, string type)
{
DynamicModuleManager manager = DynamicModuleManager.GetManager();
var contentType = TypeResolutionService.ResolveType(type);
var items = manager.GetDataItems(contentType).Where(x => contentLinks.Contains(x.Id));
return items;
}
/// <summary>
/// Converts the Guid[] type to the DynamicContent objects
/// ** Sitefinitysteve.com Extension **
/// </summary>
public static DynamicContent GetDynamicContent(this Guid contentLink, string type)
{
DynamicModuleManager manager = DynamicModuleManager.GetManager();
var contentType = TypeResolutionService.ResolveType(type);
var item = manager.GetDataItem(contentType, contentLink);
return item;
}
public enum FilterOperatorEnum
{
AND,
OR
}
/// <summary>
/// Turns a guid array into a dynamic filter expression that openaccess can use
/// </summary>
public static string GenerateFilterExpression(this Guid[] elements, string fieldname, FilterOperatorEnum decision, bool wrapInBraces = true)
{
string filter = String.Empty;
foreach (var c in elements)
{
filter += "{0}.Contains(\"{{{1}}}\") {2} ".Arrange(fieldname, c, decision.ToString());
}
if (String.IsNullOrEmpty(filter))
return filter;
else
{
//Strip the end operator
filter = filter.Substring(0, filter.Length - (decision.ToString().Length + 2));
return (wrapInBraces) ? " (" + filter + ") " : filter;
}
}
#region OBSOLETE
/// <summary>
/// Converts the Guid[] type to the DynamicContent objects
/// ** Sitefinitysteve.com Extension **
/// </summary>
[Obsolete("Use GetDynamicContentItems", true)]
public static IQueryable<DynamicContent> GetContentLinks(this Guid[] contentLinks, string type)
{
return null;
}
/// <summary>
/// Converts the Guid[] type to the DynamicContent objects
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// [Obsolete("Use GetDynamicContent", true)]
public static DynamicContent GetContentLink(this Guid contentLink, string type)
{
return null;
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Telerik.Sitefinity.Taxonomies;
using Telerik.Sitefinity.Taxonomies.Model;
using Telerik.Sitefinity.DynamicModules.Model;
namespace Telerik.Sitefinity.Taxonomies.Model
{
public static class HierarchicalTaxonExtensions
{
public enum HierarchicalTaxonCompareType
{
Equals,
StartsWith,
EndsWith,
Contains
}
/// <summary>
/// Gets the Root of a HierarchicalTaxon
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <param name="currentTaxon">This Taxon</param>
/// <returns>Root Taxon</returns>
public static HierarchicalTaxon GetRootTaxon(this HierarchicalTaxon currentTaxon)
{
if (currentTaxon.Parent != null)
{
var parent = currentTaxon.Parent;
while (parent.HasParent())
{
parent = parent.Parent;
}
return parent;
}
else
return currentTaxon;
}
/// <summary>
/// Gets a list of the parent Taxon items
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <param name="currentTaxon">Current Taxon</param>
/// <returns>List of HierarchicalTaxons linked to this item. 0 index is the closest parent.</returns>
public static List<HierarchicalTaxon> GetParentTaxa(this HierarchicalTaxon currentTaxon)
{
List<HierarchicalTaxon> taxa = new List<HierarchicalTaxon>();
if (currentTaxon.Parent != null)
{
var parent = currentTaxon.Parent;
taxa.Add(parent);
while (parent.HasParent())
{
parent = parent.Parent;
taxa.Add(parent);
}
}
return taxa;
}
/// <summary>
/// Searches from Parent to parent to match the taxon name you need, returns the first match
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <param name="currentTaxon">Current Node</param>
/// <param name="textToFind">Text to locate</param>
/// <param name="type">Compare type</param>
/// <param name="isCaseSensitive">Case Sensitive check, doesn't apply to Contains</param>
/// <returns>Null if nothing found</returns>
public static HierarchicalTaxon GetFirstParentTaxon(this HierarchicalTaxon currentTaxon, string textToFind, HierarchicalTaxonCompareType type, bool isCaseSensitive)
{
bool found = false;
HierarchicalTaxon foundTaxon = null;
var compareType = (isCaseSensitive) ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
//Check this one, TODO: consolidate this and the one below
if (type == HierarchicalTaxonCompareType.StartsWith)
{
found = currentTaxon.Title.StartsWith(textToFind, compareType);
}
else if (type == HierarchicalTaxonCompareType.EndsWith)
{
found = currentTaxon.Title.EndsWith(textToFind, compareType);
}
else if (type == HierarchicalTaxonCompareType.Equals)
{
found = currentTaxon.Title.Equals(textToFind, compareType);
}
else if (type == HierarchicalTaxonCompareType.Contains)
{
found = currentTaxon.Title.Contains(textToFind);
}
if (found)
return currentTaxon;
if (currentTaxon.Parent != null)
{
while (currentTaxon != null)
{
switch (type)
{
case HierarchicalTaxonCompareType.StartsWith:
found = currentTaxon.Title.StartsWith(textToFind, compareType);
break;
case HierarchicalTaxonCompareType.EndsWith:
found = currentTaxon.Title.EndsWith(textToFind, compareType);
break;
case HierarchicalTaxonCompareType.Contains:
found = currentTaxon.Title.Contains(textToFind);
break;
case HierarchicalTaxonCompareType.Equals:
found = currentTaxon.Title.Equals(textToFind, compareType);
break;
}
if (found)
{
foundTaxon = currentTaxon;
break;
}
else
{
currentTaxon = currentTaxon.Parent;
}
}
}
return foundTaxon;
}
/// <summary>
/// Flattens out a taxon tree to a list
/// ** Sitefinitysteve.com Extension **
/// </summary>
public static IEnumerable<HierarchicalTaxon> FlattenHierarchy(this HierarchicalTaxon parent)
{
if (parent != null)
{
foreach (HierarchicalTaxon control in parent.Subtaxa)
{
yield return control;
foreach (HierarchicalTaxon descendant in control.FlattenHierarchy())
{
yield return descendant;
}
}
}
}
/// <summary>
/// Lets us know if a Hierarchical taxon object has a parent object
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <param name="currentTaxon"></param>
/// <returns></returns>
private static bool HasParent(this HierarchicalTaxon currentTaxon)
{
return (currentTaxon.Parent == null) ? false : true;
}
/// <summary>
/// Flattens out the taxons to a delimited string
/// ** Sitefinitysteve.com Extension **
/// </summary>
public static string FlattenToString(this IEnumerable<HierarchicalTaxon> items, char seperator = ',', bool appendSpace = true)
{
string result = String.Empty;
foreach (HierarchicalTaxon t in items)
{
result += String.Format("{0}{1}{2}", t.Title, seperator, (appendSpace) ? " " : "");
}
return result.Trim().TrimEnd(seperator);
}
/// <summary>
/// Flattens out the taxons to a delimited string
/// ** Sitefinitysteve.com Extension **
/// </summary>
public static string FlattenToString(this IEnumerable<HierarchicalTaxon> items, string seperator = "->", bool reverse = false)
{
if (!reverse)
{
return String.Join(seperator, items.Select(x => x.Title.Value).ToArray());
}
else
{
return String.Join(seperator, items.Reverse().Select(x => x.Title.Value).ToArray());
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Telerik.Sitefinity
{
public class MarkupExtensions
{
/// <summary>
/// Renders the "invisible class if the string item is empty, so clearly
/// you need to have .invisible{display:none;} in your css
/// </summary>
public static string HideIfEmpty(this object text, bool renderSpaceBeforeClass = false)
{
if (String.IsNullOrEmpty(text.ToString()))
return (renderSpaceBeforeClass) ? " invisible" : "invisible";
else
return "";
}
/// <summary>
/// Checks to see if there is content, returns true or false, useful for Visible
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static bool HasContent(this object text)
{
if (String.IsNullOrEmpty(text.ToString()))
return false;
else
return true;
}
/// <summary>
/// Renders passed text if item is NOT empty
/// </summary>
public static string IfContentExists(this object text, object textToRender, object elseRender = null)
{
if (!String.IsNullOrEmpty(text.ToString()))
{
return textToRender.ToString();
}
else
{
return (elseRender == null) ? "" : elseRender.ToString();
}
}
/// <summary>
/// Renders passed text if TRUE
/// </summary>
public static string IsTrue(this bool value, string textToRender, string elseRender = "")
{
if (value)
{
return textToRender;
}
else
{
return elseRender;
}
}
/// <summary>
/// Renders passed text if FALSE
/// </summary>
public static string IsFalse(this bool value, string textToRender, string elseRender = "")
{
if (value)
{
return textToRender;
}
else
{
return elseRender;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telerik.Sitefinity.DynamicModules;
using Telerik.Sitefinity.DynamicModules.Model;
using Telerik.Sitefinity.Security;
using Telerik.Sitefinity.Security.Claims;
using Telerik.Sitefinity.Utilities.TypeConverters;
using Telerik.Sitefinity;
using Telerik.Sitefinity.Model;
using System.Text.RegularExpressions;
namespace Telerik.Sitefinity
{
/// <summary>
/// Thanks Stephen Pittman https://plus.google.com/+StephenPittmanAus/posts
/// </summary>
public class PublishingExtensions
{
/// <summary>
/// Saves a dynamic content item without all the workflow bloat
/// *** SITEFINITY STEVE EXTENSION, NOT OFFICIAL TELERIK ***
/// </summary>
/// <param name="type">Telerik.Sitefinity.DynamicTypes.Model.YOURTYPE</param>
/// <param name="fields">BackingFields</param>
/// <param name="publishItem">Should we publish it?</param>
/// <param name="identifyingFieldName">What makes this type unique, usually Title</param>
/// <param name="requireUniqueIdentifyingField">Does it have a unique field?</param>
/// <param name="createUniqueUrl"></param>
/// <param name="ownerId"></param>
/// <param name="suppressSecurity"></param>
/// <param name="publishOn">Publish on this date</param>
/// <returns></returns>
public static DynamicContent JustFingSaveIt(string type, Dictionary<string, object> fields, bool publishItem = false, string identifyingFieldName = "Title", bool requireUniqueIdentifyingField = true, bool createUniqueUrl = false, Guid ownerId = new Guid(), bool suppressSecurity = true, DateTime? publishOn = null)
{
//Create blank item
var dynMgr = DynamicModuleManager.GetManager(DynamicModuleManager.GetDefaultProviderName());
if (!type.StartsWith("Telerik.Sitefinity.DynamicTypes.Model.")){
type = "Telerik.Sitefinity.DynamicTypes.Model.{0}".Arrange(type);
}
var itemType = TypeResolutionService.ResolveType(type);
var item = dynMgr.CreateDataItem(itemType);
//Set field data
foreach (var field in fields)
{
item.SetValue(field.Key, field.Value);
}
//Title doesn't have to be unique
var identifyingField = fields[identifyingFieldName].ToString();
if (requireUniqueIdentifyingField && dynMgr.GetDataItems(itemType).Any(o => o.GetValue<string>(identifyingFieldName).ToLower() == identifyingField.ToLower()))
{
throw new ArgumentException(string.Format("Identifying field value is not unique: '{0}', value: '{1}'", identifyingFieldName, identifyingField));
}
//URL must be unique
var url = Regex.Replace(identifyingField.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");
var itemExists = dynMgr.GetDataItems(itemType).Any(o => o.UrlName == url);
if (itemExists && !createUniqueUrl)
{
throw new ArgumentException(string.Format("URL is not unique based on identifying field: '{0}', value: '{1}'", identifyingFieldName, identifyingField));
}
if (itemExists && createUniqueUrl)
{
//Create unique URL means append "-1" or "-2" etc... until unique
var modifier = 1;
while (dynMgr.GetDataItems(itemType).Any(o => o.UrlName == string.Format("{0}-{1}", url, modifier)))
{
modifier++;
}
url = string.Format("{0}-{1}", url, modifier);
}
item.UrlName = url;
//Owner - if no ID provided, use logged on user
if (ownerId == Guid.Empty)
{
var currentUser = ClaimsManager.GetCurrentUserId();
item.Owner = currentUser == null ? Guid.Empty : currentUser;
}
else
{
item.Owner = ownerId;
}
//Save the master item
if (publishOn == null) {
item.PublicationDate = DateTime.Now;
}
item.SetWorkflowStatus(dynMgr.Provider.ApplicationName, "Draft");
if (suppressSecurity) {
dynMgr.Provider.SuppressSecurityChecks = true;
}
dynMgr.SaveChanges();
if (suppressSecurity) {
dynMgr.Provider.SuppressSecurityChecks = false;
}
if (publishItem)
{
//We can now call the following to publish the item
if (publishOn == null)
{
var publishedItem = dynMgr.Lifecycle.Publish(item);
}
else
{
var publishedItem = dynMgr.Lifecycle.PublishWithSpecificDate(item, publishOn.Value);
}
//You need to set appropriate workflow status
item.SetWorkflowStatus(dynMgr.Provider.ApplicationName, "Published");
//You need to call SaveChanges() in order for the items to be actually persisted to data store
if (suppressSecurity) {
dynMgr.Provider.SuppressSecurityChecks = true;
}
dynMgr.SaveChanges();
if (suppressSecurity) {
dynMgr.Provider.SuppressSecurityChecks = false;
}
}
return item;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Telerik.Sitefinity
{
public static class StringExtensions
{
public static string Capitalize(this string s)
{
// Check for empty string.
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
// Return char and concat substring.
return char.ToUpper(s[0]) + s.Substring(1);
}
public static bool ContainsAny(this string str, params string[] values)
{
if (!string.IsNullOrEmpty(str) || values.Length > 0)
{
foreach (string value in values)
{
if (str.ToLower().Contains(value.ToLower()))
return true;
}
}
return false;
}
public static bool ContainsAll(this string value, params string[] values)
{
foreach (string one in values)
{
if (!value.ToLower().Contains(one.ToLower()))
{
return false;
}
}
return true;
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using Telerik.Sitefinity.Taxonomies;
using Telerik.Sitefinity.Taxonomies.Model;
using Telerik.Sitefinity.DynamicModules.Model;
namespace Telerik.Sitefinity.Taxonomies.Model
{
public static class TaxonExtensions
{
/// <summary>
/// Gets a taxon attribute value
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <typeparam name="T">Type of the data</typeparam>
/// <param name="currentTaxon">This taxon</param>
/// <param name="key">Dictionary key the data is stored as</param>
/// <param name="isJson">If the data is a complex object stored as JSON make this true to return the deserialized object</param>
/// <param name="defaultValue">If the item doesn't exist, it will initalize to this</param>
/// <param name="createIfDoesntExist">If the item isnt in the attribute collection, create it</param>
/// <returns></returns>
public static T GetValue<T>(this Taxon currentTaxon, string key, bool createIfDoesntExist = false, bool isJson = false)
{
bool keyExists = currentTaxon.Attributes.ContainsKey(key);
if (!keyExists)
{
if (createIfDoesntExist)
{
var value = (default(T) == null) ? "null" : default(T).ToString();
currentTaxon.Attributes.Add(key, value);
}
}
else{
if (isJson)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(currentTaxon.Attributes[key]);
}
else
{
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(currentTaxon.Attributes[key]);
}
}
return default(T);
}
/// <summary>
/// Saves an attribute to a taxon. Do not forget to call SaveChanges on your TaxonomyManager.
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <param name="currentTaxon">This taxon</param>
/// <param name="key">Dictionary Key to store the value as</param>
/// <param name="value">Data to store</param>
/// <param name="asJSON">If it's a complex object, convert to JSON</param>
public static void SetValue(this Taxon currentTaxon, string key, object value, bool isJson = false)
{
string data = (isJson) ? Newtonsoft.Json.JsonConvert.SerializeObject(value) : value.ToString();
if (data.Length >= 255)
throw new ArgumentOutOfRangeException("Data length exceeded, Max 255");
if (!currentTaxon.Attributes.ContainsKey(key))
{
currentTaxon.Attributes.Add(key, data);
}else{
currentTaxon.Attributes[key] = data;
}
}
/// <summary>
/// To Impliment Later
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool IsSimpleType(
this Type type)
{
return
type.IsValueType ||
type.IsPrimitive ||
new Type[] {
typeof(String),
typeof(Decimal),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(TimeSpan),
typeof(Guid)
}.Contains(type) ||
Convert.GetTypeCode(type) != TypeCode.Object;
}
/// <summary>
/// Checks for a key
/// ** Sitefinitysteve.com Extension **
/// </summary>
/// <param name="currentTaxon">This taxon</param>
/// <param name="key">Key to find</param>
/// <returns></returns>
public static bool HasAttribute(this Taxon currentTaxon, string key){
return currentTaxon.Attributes.ContainsKey(key);
}
}
}
using System;
using System.Linq;
using Telerik.Sitefinity.Libraries.Model;
using Telerik.Sitefinity.Modules.UserProfiles;
using Telerik.Sitefinity.Security.Model;
namespace Telerik.Sitefinity.Security
{
public static class UserExtensionMethods
{
public static string DefaultAvatar = "/SFRes/images/Telerik.Sitefinity.Resources/Images.DefaultPhoto.png";
public static string GetAvatar(this User user, string defaultImageUrl = ""){
Image image;
UserProfilesHelper.GetAvatarImageUrl(user.Id, out image);
if (image != null)
{
return image.Url;
}
else
{
return (String.IsNullOrEmpty(defaultImageUrl)) ? DefaultAvatar : defaultImageUrl;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment