public static HtmlString Edit <TBase, TProp>(this SitecoreHelper sitecoreHelper, TBase itemBase, Expression <Func <TBase, TProp> > property, object parameters = null) where TBase : ItemBase { var type = typeof(TBase); var member = property.Body as MemberExpression; if (member == null) { return(null); } var propInfo = member.Member as PropertyInfo; if (propInfo == null) { var func = property.Compile(); return(new HtmlString(func(itemBase).ToString())); } if (type != propInfo.ReflectedType && !type.IsSubclassOf(propInfo.ReflectedType)) { throw new ArgumentException( $"Expression '{property}' refers to a property that is not from type {type.FullName}."); } return(sitecoreHelper.Field(propInfo.Name, itemBase.Item, parameters)); }
public static HtmlString RenderEmmetAbbreviation(this SitecoreHelper helper, string abbreviation) { Assert.ArgumentNotNull(helper, nameof(helper)); Assert.ArgumentNotNullOrEmpty(abbreviation, nameof(abbreviation)); abbreviation = RemoveIgnoredCharacters(abbreviation); var result = Emmet.Expand(abbreviation, textFormatter, escapeText: false); return(new HtmlString(result)); HtmlTag textFormatter(HtmlTag tag) { tag = ApplyFieldSyntax(helper, tag); tag = ApplyTranslationSyntax(tag); tag = ApplyLinkSyntax(tag); tag = ApplyDynamicPlaceholderSyntax(helper, tag); tag = ApplyStaticPlaceholderSyntax(helper, tag); tag.Text = tag.Text .Replace("\\[", "[").Replace("\\]", "]") .Replace("\\(", "(").Replace("\\)", ")") .Replace("\\\\", "\\"); return(tag); } }
public virtual void Initialize(Sitecore.Mvc.Presentation.Rendering rendering) { var current = Sitecore.Mvc.Common.ContextService.Get().GetCurrent <ViewContext>(); _htmlHelper = new HtmlHelper(current, new Sitecore.Mvc.Presentation.ViewDataContainer(current.ViewData)); SitecoreMainHelper = Sitecore.Mvc.HtmlHelperExtensions.Sitecore(_htmlHelper); }
public static HtmlString Field(this SitecoreHelper helper, ID fieldID, Item item, object parameters) { Assert.ArgumentNotNullOrEmpty(fieldID, nameof(fieldID)); Assert.IsNotNull(item, nameof(item)); Assert.IsNotNull(parameters, nameof(parameters)); return(helper.Field(fieldID.ToString(), item, parameters)); }
protected override void RenderContent(PrintContext printContext, XElement output) { if (ScriptHelper.ExecuteScriptReference(printContext, this.RenderingItem, this.GetDataItem(printContext), output)) { return; } bool flag = !SitecoreHelper.HasScriptItemAssigned(this.RenderingItem) && !SitecoreHelper.HasMergeItemAssigned(this.RenderingItem); if (flag && string.IsNullOrEmpty(this.ContentFieldName)) { Item obj = this.RenderingItem.Children.FirstOrDefault <Item>((Func <Item, bool>)(c => c.TemplateName.Equals("p_text", StringComparison.InvariantCultureIgnoreCase))); if (obj != null && obj.Fields[printContext.Settings.StaticTextFieldName] != null) { this.DataSource = obj.ID.ToString(); this.ContentFieldName = printContext.Settings.StaticTextFieldName; this.RenderDeep = false; } } Item dataItem = this.GetDataItem(printContext); XElement xelement = RenderItemHelper.CreateXElement("TextFrame", this.RenderingItem, printContext.Settings.IsClient, dataItem); this.SetAttributes(xelement); IEnumerable <XElement> xelements = (IEnumerable <XElement>)null; if (flag) { xelements = this.GetContent(printContext, xelement); } output.Add((object)xelement); xelement.Add((object)xelements); this.RenderChildren(printContext, xelement); }
public static string GetLinkFieldUrl(this SitecoreHelper sitecoreHelper, Item item, string fieldName) { if (item == null) { throw new ArgumentNullException(nameof(item)); } if (string.IsNullOrEmpty(fieldName)) { throw new ArgumentNullException(nameof(fieldName)); } var fieldalue = item[fieldName]; if (ID.IsID(item[fieldName])) { var linkItem = item.Database.GetItem(ID.Parse(fieldalue)); return(linkItem != null?Sitecore.Links.LinkManager.GetItemUrl(linkItem) : string.Empty); } var field = item.Fields[fieldName]; if (field == null || !(FieldTypeManager.GetField(field) is LinkField)) { return(string.Empty); } else { LinkField linkField = (LinkField)field; switch (linkField.LinkType.ToLower()) { case "internal": // Use LinkMananger for internal links, if link is not empty return(linkField.TargetItem != null?Sitecore.Links.LinkManager.GetItemUrl(linkField.TargetItem) : string.Empty); case "media": // Use MediaManager for media links, if link is not empty return(linkField.TargetItem != null?Sitecore.Resources.Media.MediaManager.GetMediaUrl(linkField.TargetItem) : string.Empty); case "external": // Just return external links return(linkField.Url); case "anchor": // Prefix anchor link with # if link if not empty return(!string.IsNullOrEmpty(linkField.Anchor) ? "#" + linkField.Anchor : string.Empty); case "mailto": // Just return mailto link return(linkField.Url); case "javascript": // Just return javascript return(linkField.Url); default: // Just please the compiler, this // condition will never be met return(linkField.Url); } } }
public static HtmlString DynamicPlaceholder(this SitecoreHelper helper, string placeholderName, bool useStaticPlaceholderNames = false) { if (useStaticPlaceholderNames) { return(helper.Placeholder(placeholderName)); } return(DynamicPlaceholderExtension.DynamicPlaceholder(helper, placeholderName)); }
public static HtmlString DynamicPlaceholder(this SitecoreHelper helper, string placeholderName, ID placeholderSuffix) { Assert.ArgumentNotNull(placeholderName, nameof(placeholderName)); helper.CurrentRendering.Parameters[GetUniqueIdKeyWithinRendering.RenderingParameterKey] = placeholderSuffix.ToString(); return(helper.DynamicPlaceholder(new DynamicPlaceholderDefinition(placeholderName))); }
public static HtmlString Field(this SitecoreHelper htmlHelper, string fieldName, Item item, object parameters, bool shouldWrap) { string format = shouldWrap ? "<p>{0}{1}</p>" : "{0}{1}"; var value = String.Format(format, htmlHelper.BeginField(fieldName, item, parameters), htmlHelper.EndField()); return(new HtmlString(value)); }
public static HtmlString FormattedDateTimeField(this SitecoreHelper sitecoreHelper, Item item, string fieldName, string format) { if (Sitecore.Context.PageMode.IsExperienceEditor) { return(sitecoreHelper.Field(fieldName, item)); } return(new HtmlString(DateTimeField(sitecoreHelper, item, fieldName).ToString(format))); }
public static string JsonEncode(this SitecoreHelper helper, object obj) { var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; return(JsonConvert.SerializeObject(obj, Formatting.None, settings)); }
public static Item GetLinkedItem(this SitecoreHelper sitecoreHelper, Item item, string fieldName) { ID id; if (ID.TryParse(item[fieldName], out id)) { return(item.Database.GetItem(id)); } return(null); }
public static HtmlString DictionaryField(this SitecoreHelper helper, string relativePath, string defaultValue = "") { var item = DictionaryPhraseRepository.Current.GetItem(relativePath, defaultValue); if (item == null) { return(new HtmlString(defaultValue)); } return(helper.Field(Templates.DictionaryEntry.Fields.Phrase, item)); }
public void AnalyticsVisitorIdentification_ShoudReturnEmptyString_TrackingIsFalse() { var htmlHelper = new HtmlHelper(new ViewContext(), new ViewPage()); var sitecoreHelper = new SitecoreHelper(htmlHelper); var result = sitecoreHelper.AnalyticsVisitorIdentification(); result.ToString().Should().Be(string.Empty); }
public static IHtmlString Localize( this SitecoreHelper sitecoreHelper, string key, string defaultValue = null, bool editable = false, string language = null, bool autoCreate = true) { return(new HtmlString(LocalizationFactory.LocalizationService.Localize(key, defaultValue, editable, language, autoCreate))); }
public static HtmlString ImageField(this SitecoreHelper helper, ID fieldID, Item item, int mh = 0, int mw = 0, string cssClass = null, bool disableWebEditing = false) { return(helper.Field(fieldID.ToString(), item, new { mh, mw, DisableWebEdit = disableWebEditing, @class = cssClass ?? string.Empty })); }
public static HtmlString ImageField(this SitecoreHelper helper, string fieldName, Item item, int mh = 0, int mw = 0, string cssClass = null, bool disableWebEditing = false) { return(helper.Field(fieldName, item, new { mh, mw, DisableWebEdit = disableWebEditing, @class = cssClass ?? "" })); }
public static HtmlString AdvancedImageField(this SitecoreHelper helper, string fieldName, Item item, int width = 0, int height = 0, string alt = null, string cssClass = null, bool disableWebEditing = false) { /* * Example usage in view @Html.Sitecore().AdvancedImageField("Cropped", Model.Item, 100, 400) * * */ if (item == null) { return(new HtmlString("No datasource set")); } ImageField imageField = new ImageField(item.Fields[fieldName]); if (String.IsNullOrEmpty(imageField.Value)) { return(new HtmlString(String.Empty)); } XmlDocument xml = new XmlDocument(); xml.LoadXml(imageField.Value); if (xml.DocumentElement == null) { return(new HtmlString("No cropping image parameters found.")); } string cropx = xml.DocumentElement.HasAttribute("cropx") ? xml.DocumentElement.GetAttribute("cropx") : string.Empty; string cropy = xml.DocumentElement.HasAttribute("cropy") ? xml.DocumentElement.GetAttribute("cropy") : string.Empty; string focusx = xml.DocumentElement.HasAttribute("focusx") ? xml.DocumentElement.GetAttribute("focusx") : string.Empty; string focusy = xml.DocumentElement.HasAttribute("focusy") ? xml.DocumentElement.GetAttribute("focusy") : string.Empty; float.TryParse(cropx, out float cx); float.TryParse(cropy, out float cy); float.TryParse(focusx, out float fx); float.TryParse(focusy, out float fy); string imageSrc = MediaManager.GetMediaUrl(imageField.MediaItem); string src = $"{imageSrc}?cx={cx}&cy={cy}&cw={width}&ch={height}"; string hash = HashingUtils.GetAssetUrlHash(src); TagBuilder builder = new TagBuilder("img"); builder.Attributes.Add("src", $"{src}&hash={hash}"); builder.Attributes.Add("alt", !String.IsNullOrEmpty(imageField.Alt) ? imageField.Alt : alt); if (!string.IsNullOrEmpty(cssClass)) { builder.AddCssClass(cssClass); } return(MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal))); }
protected virtual IEnumerable <XElement> GetContent(PrintContext printContext, XElement textFrameNode) { XAttribute xattribute = textFrameNode.Attribute((XName)"ParagraphStyle"); string str = xattribute == null || string.IsNullOrEmpty(xattribute.Value) ? "NormalParagraphStyle" : xattribute.Value; if (!string.IsNullOrEmpty(this.InDesignContent)) { return(this.FormatText(str, this.InDesignContent)); } if (string.IsNullOrEmpty(this.ContentFieldName)) { return((IEnumerable <XElement>)null); } try { Item dataItem = this.GetDataItem(printContext); if (dataItem != null) { Field field = dataItem.Fields[this.ContentFieldName]; if (field == null) { return((IEnumerable <XElement>)null); } switch (field.Type) { case "Rich Text": ParseContext context = new ParseContext(printContext.Database, printContext.Settings) { DefaultParagraphStyle = str, ParseDefinitions = RichTextParser.GetParseDefinitionCollection(this.RenderingItem) }; string htmlWithItemId = $"<!--{dataItem.ID.Guid.ToString("B")}-->" + field.Value; string xml = RichTextParser.ConvertToXml(htmlWithItemId, context, printContext.Language); XElement element = new XElement((XName)"temp"); element.AddFragment(xml); return(element.Elements()); case "Single-Line Text": str = fieldStyles.ContainsKey(ContentFieldName) ? fieldStyles[ContentFieldName] : str; string singleLineContent = SitecoreHelper.FetchFieldValue(dataItem, field.Name, printContext.Database, str); return(this.FormatText(str, singleLineContent)); default: string content = SitecoreHelper.FetchFieldValue(dataItem, field.Name, printContext.Database, str); return(this.FormatText(str, content)); } } } catch (Exception ex) { Logger.Error("Rendering TextFrame: " + (object)this.RenderingItem.ID, ex); } return((IEnumerable <XElement>)null); }
public static HtmlString RenderDate(this SitecoreHelper sitecoreHelper, ID fieldId, Item item, string format = "D", bool disableWebEdit = false, bool setCulture = true, SafeDictionary <string> parameters = null) { return(RenderDate( sitecoreHelper, fieldId.ToString(), item, format, disableWebEdit, setCulture, parameters)); }
public static string CurrentLanguageCode(this SitecoreHelper helper) { var lang = RenderingContext.CurrentOrNull?.Rendering?.Item?.Language ?? Context.Language; if (lang != null) { return(lang.CultureInfo.TwoLetterISOLanguageName); } return("en"); }
public static Item[] GetLinkedItems(this SitecoreHelper sitecoreHelper, Item item, string fieldName) { var field = item.Fields[fieldName]; if (field == null) { return(null); } var multilistField = new MultilistField(field); return(multilistField.GetItems()); }
// GET: Sitemap public override ActionResult Index() { Item homePage = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.RootPath + Sitecore.Context.Site.StartItem); var sitemap = SitecoreHelper.GetItem <MenuItem>(homePage.ID.ToGuid()); SitemapViewModel model = new SitemapViewModel() { SitemapNodes = sitemap }; return(View("~/Views/Pages/Sitemap.cshtml", model)); }
public static string MediaUrl(this SitecoreHelper sitecoreHelper, ID fieldId, Item item, MediaUrlBuilderOptions options) { ImageField imageField = item?.Fields[fieldId]; if (imageField == null || imageField.MediaItem == null) { return(string.Empty); } var url = options != null?MediaManager.GetMediaUrl(imageField.MediaItem, options) : MediaManager.GetMediaUrl(imageField.MediaItem); return(HashingUtils.ProtectAssetUrl(url)); }
public void AnalyticsVisitorIdentification_ShoudReturnDebuggingMessage_WhenProfilingIsTrue() { var htmlHelper = new HtmlHelper(new ViewContext(), new ViewPage()); var sitecoreHelper = new SitecoreHelper(htmlHelper); var expectedResult = "<!-- Visitor identification is disabled because debugging is active. -->"; Context.Site = new FakeSiteContext("fake"); Profiler.StartSession(); Context.Diagnostics.Profiling = true; var result = sitecoreHelper.AnalyticsVisitorIdentification(); result.ToString().Should().Be(expectedResult); }
public static Item[] GetBreadcrumbItems(this SitecoreHelper sitecoreHelper) { var ancestorsAndSelf = sitecoreHelper.CurrentItem.Axes.GetAncestors(); for (var i = 0; i < ancestorsAndSelf.Length; i++) { if (HomePageTemplateIds.Any(ancestorsAndSelf[i].IsDerived)) { return(ancestorsAndSelf.Skip(i).ToArray()); } } return(new Item[] { }); }
private static HtmlTag ApplyStaticPlaceholderSyntax(SitecoreHelper helper, HtmlTag tag) { var match = StaticPlaceholderRegex.Match(tag.Text); if (match.Success) { var placeholderKey = match.Groups["placeholderKey"].Value; var placeholder = helper.Placeholder(placeholderKey).ToString(); tag.Text = StaticPlaceholderRegex.Replace(tag.Text, placeholder); } return(tag); }
//public override ActionResult Index() //{ // ViewBag.Module = "Cito.default.SimpleComponent";//Would it be useful to transfer this information to the rendering? // var item = RenderingContext.Current.Rendering.Item; // var helper = RenderingContext.Current.PageContext.HtmlHelper; // var scHelper = new SitecoreHelper(helper); // JObject o = new JObject(new JProperty("text", "Hello from the SimpleComponentController"), new JProperty("title", "This is from the server")); // return PartialView("Index", o); // //return PartialView("Index", this.GetModel()); //} public ActionResult React() { ViewBag.Module = "Cito.default.SimpleComponent";//Would it be useful to transfer this information to the rendering? var item = RenderingContext.Current.Rendering.Item; var helper = RenderingContext.Current.PageContext.HtmlHelper; var scHelper = new SitecoreHelper(helper); JObject o = new JObject(new JProperty("text", "ReactResult: Hello from the SimpleComponentController"), new JProperty("title", "This is from the server")); return(PartialView(o)); //return PartialView("Index", this.GetModel()); }
public static HtmlString RenderField(this SitecoreHelper sitecoreHelper, string fieldNameOrId, Item item, bool disableWebEdit = false, SafeDictionary <string> parameters = null) { if (parameters == null) { parameters = new SafeDictionary <string>(); } return(sitecoreHelper.Field(fieldNameOrId, new { DisableWebEdit = disableWebEdit, Parameters = parameters })); }
public static MvcHtmlString RenderingToken(this SitecoreHelper helper) { if (helper.CurrentRendering == null) { return(null); } var tagBuilder = new TagBuilder("input"); tagBuilder.Attributes["type"] = "hidden"; tagBuilder.Attributes["name"] = Constants.Uid; tagBuilder.Attributes["value"] = helper.CurrentRendering.UniqueId.ToString(); return(new MvcHtmlString(tagBuilder.ToString(TagRenderMode.SelfClosing))); }
public virtual void Initialize(Sitecore.Mvc.Presentation.Rendering rendering) { var current = Sitecore.Mvc.Common.ContextService.Get().GetCurrent<ViewContext>(); _htmlHelper = new HtmlHelper(current, new Sitecore.Mvc.Presentation.ViewDataContainer(current.ViewData)); SitecoreMainHelper = Sitecore.Mvc.HtmlHelperExtensions.Sitecore(_htmlHelper); }