public static string GetGeneralLinkUrl(this LinkField linkField) { string url = string.Empty; if (linkField == null) { return(string.Empty); } switch (linkField.LinkType) { case "internal": url = linkField.TargetItem != null?GetItemUrl(linkField.TargetItem) : String.Empty; return(url); case "external": case "mailto": case "anchor": case "javascript": url = linkField.Url; return(url); case "media": url = linkField.TargetItem != null ? MediaManager.GetMediaUrl((Item) new MediaItem(linkField.TargetItem)) : String.Empty; return(url); default: return(String.Empty); } }
public virtual void RemoveLink(LinkField link) { if (Links.Contains(link)) { Links.Remove(link); } }
/// <summary> /// /// </summary> /// <param name="item"></param> /// <param name="fieldName"></param> /// <returns></returns> public static string GetUrl(Item item, string fieldName, UrlOptions urlOptions, MediaUrlOptions mediaUrlOptions) { string url = String.Empty; LinkField linkField = item.Fields[fieldName]; if (linkField != null) { if (linkField.IsMediaLink) { MediaItem media = new MediaItem(linkField.TargetItem); url = Sitecore.StringUtil.EnsurePrefix('/', null != mediaUrlOptions ? MediaManager.GetMediaUrl(media, mediaUrlOptions) : MediaManager.GetMediaUrl(media)); } else if (linkField.IsInternal) { Item targetItem = linkField.TargetItem; if (targetItem != null) { url = null != urlOptions?Sitecore.Links.LinkManager.GetItemUrl(linkField.TargetItem, urlOptions) : Sitecore.Links.LinkManager.GetItemUrl(linkField.TargetItem); } else { url = linkField.Url; } } } return(url); }
private bool IsExternalLink(Item item, ID fieldId) { var field = item.Fields[fieldId]; LinkField linkField = (LinkField)field; return("external".Equals(linkField.LinkType, System.StringComparison.OrdinalIgnoreCase)); }
public static string GetUrlFromLinkField(LinkField lf) { switch (lf.LinkType.ToLower()) { case "internal": // Use LinkMananger for internal links, if link is not empty return(lf.TargetItem != null?Sitecore.Links.LinkManager.GetItemUrl(lf.TargetItem) : string.Empty); case "media": // Use MediaManager for media links, if link is not empty return(lf.TargetItem != null?Sitecore.Resources.Media.MediaManager.GetMediaUrl(lf.TargetItem) : string.Empty); case "external": // Just return external links return(lf.Url); case "anchor": // Prefix anchor link with # if link if not empty return(!string.IsNullOrEmpty(lf.Anchor) ? "#" + lf.Anchor : string.Empty); case "mailto": // Just return mailto link return(lf.Url); case "javascript": // Just return javascript return(lf.Url); default: // Just please the compiler, this // condition will never be met return(lf.Url); } }
public static string LinkFieldUrl(this Item item, ID fieldId) { if (item == null) { throw new ArgumentNullException(nameof(item)); } if (ID.IsNullOrEmpty(fieldId)) { throw new ArgumentNullException(nameof(fieldId)); } var field = item.Fields[fieldId]; if (field == null || !(FieldTypeManager.GetField(field) is LinkField)) { return(string.Empty); } LinkField linkField = field; switch (linkField.LinkType.ToLower()) { case "internal": // Use LinkMananger for internal links, if link is not empty return(linkField.TargetItem != null?LinkManager.GetItemUrl(linkField.TargetItem) : string.Empty); case "media": // Use MediaManager for media links, if link is not empty return(linkField.TargetItem != null?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 override void FillField(BaseDataMap map, object importRow, ref Item newItem, string importValue, out bool updatedField, ref LevelLogger logger) { var fillFieldLogger = logger.CreateLevelLogger(); updatedField = false; if (IsRequired) { if (String.IsNullOrEmpty(importValue)) { fillFieldLogger.AddError(CategoryConstants.ImportedValueToFieldWasEmpty, String.Format("The Item '{0}' of template type: '{1}' has a field '{2}', but the imported value '{3}' was empty. This field must be provided when the field is required. The field was not updated.", map.GetItemDebugInfo(newItem), newItem.TemplateName, NewItemField, importValue)); return; } } //get the field as a link field and store the url LinkField lf = newItem.Fields[NewItemField]; if (lf != null) { if (lf.Url != importValue) { lf.Url = importValue; updatedField = true; } } if (IsRequired && lf == null) { fillFieldLogger.AddError(CategoryConstants.RequiredFieldNotFoundOnItem, String.Format("The Item '{0}' of template type: '{1}' didn't contain a field with name '{2}'. This field must be present because the 'Is Required Field' is checked.", newItem.ID.ToString(), newItem.TemplateName, NewItemField)); return; } }
/// <summary> /// Updates an Article item. /// </summary> private static void UpdateArticleItem(Item articleItem, BlogFeedItem feedItem) { // Set the item fields articleItem.Editing.BeginEdit(); try { articleItem["Title"] = feedItem.Title; articleItem["Description"] = feedItem.Description; articleItem["Article Type"] = Constants.ArticleType_BlogPost; // Display Date DateField displayDate = articleItem.Fields["Display Date"]; displayDate.Value = DateUtil.ToIsoDate(feedItem.Updated.Date); // Link LinkField link = articleItem.Fields["Link"]; link.Url = feedItem.Link; link.Target = "_blank"; link.LinkType = "external"; } finally { articleItem.Editing.EndEdit(); } }
/// <summary> /// Sets the field. /// </summary> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <exception cref="Glass.Mapper.MapperException"> /// No item with ID {0}. Can not update Link linkField.Formatted(newId) /// or /// No item with ID {0}. Can not update Link linkField.Formatted(newId) /// </exception> public override void SetField(Field field, object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { Link link = value as Link; if (field == null) { return; } Guid fieldGuid = field.ID.Guid; // shortest route - we know whether or not its rich text var isInternalLink = _isInternalLinkFieldDictionary.GetOrAdd(fieldGuid, (id) => field.TypeKey == InternalLinkKey); if (isInternalLink) { InternalLinkField internalLinkField = new Sitecore.Data.Fields.InternalLinkField(field); MapToLinkField(link, internalLinkField, config); } else { LinkField linkField = new LinkField(field); if (link == null || link.Type == LinkType.NotSet) { linkField.Clear(); return; } MapToLinkField(link, linkField, config); } }
/// <summary> /// Gets the field. /// </summary> /// <param name="field">The field.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <returns>System.Object.</returns> public override object GetField(Sitecore.Data.Fields.Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { if (field == null || field.Value.Trim().IsNullOrEmpty()) { return(null); } Guid fieldGuid = field.ID.Guid; // shortest route - we know whether or not its rich text var isInternalLink = _isInternalLinkFieldDictionary.GetOrAdd(fieldGuid, (id) => field.TypeKey == InternalLinkKey); Link link = new Link(); if (isInternalLink) { InternalLinkField internalLinkField = new Sitecore.Data.Fields.InternalLinkField(field); MapToLinkModel(link, internalLinkField, config); } else { LinkField linkField = new LinkField(field); MapToLinkModel(link, linkField, config); } return(link); }
protected void MapToLinkModel(Link link, LinkField linkField, SitecoreFieldConfiguration config) { link.Anchor = linkField.Anchor; link.Class = linkField.Class; link.Style = linkField.GetAttribute("style"); link.Text = linkField.Text; link.Title = linkField.Title; link.Target = linkField.Target; link.Query = HttpUtility.UrlDecode(linkField.QueryString); switch (linkField.LinkType) { case "anchor": link.Url = linkField.Anchor; link.Type = LinkType.Anchor; break; case "external": link.Url = linkField.Url; link.Type = LinkType.External; break; case "mailto": link.Url = linkField.Url; link.Type = LinkType.MailTo; break; case "javascript": link.Url = linkField.Url; link.Type = LinkType.JavaScript; break; case "media": if (linkField.TargetItem == null) { link.Url = string.Empty; } else { global::Sitecore.Data.Items.MediaItem media = new global::Sitecore.Data.Items.MediaItem(linkField.TargetItem); link.Url = global::Sitecore.Resources.Media.MediaManager.GetMediaUrl(media); } link.Type = LinkType.Media; link.TargetId = linkField.TargetID.Guid; break; case "internal": var urlOptions = _urlOptionsResolver.CreateUrlOptions(config.UrlOptions); link.Url = linkField.TargetItem == null ? string.Empty : LinkManager.GetItemUrl(linkField.TargetItem, urlOptions); link.Type = LinkType.Internal; link.TargetId = linkField.TargetID.Guid; link.Text = linkField.Text.IsNullOrEmpty() ? (linkField.TargetItem == null ? string.Empty : linkField.TargetItem.DisplayName) : linkField.Text; break; default: link = null; break; } }
/// <summary> /// Set URL for General Link field with default link type set as external /// </summary> /// <param name="field">Sitecore Field</param> /// <param name="value">URL, Item Path, or Item ID</param> /// <param name="linkType">Type of link as string</param> public static void SetLinkValue(Field field, object value, string linkType = "external") { LinkField thisField = (LinkField)field; if (linkType == "media" || linkType == "internal") { Item item = field.Database.GetItemFromValue(value); if (item != null) { if (linkType == "media") { thisField.Url = item.Paths.MediaPath; } else { thisField.Url = SC.Links.LinkManager.GetItemUrl(item, SC.Links.LinkManager.GetDefaultUrlOptions()); } thisField.TargetID = item.ID; } else { thisField.Url = value.ToString(); } } else { thisField.Url = value.ToString(); } thisField.LinkType = linkType; }
public override object GetValue(global::Sitecore.Data.Items.Item item, ISitecoreService service) { var itemField = base.GetField(item); if (itemField == null || itemField.Value.Trim().IsNullOrEmpty()) return null; Link link = new Link(); LinkField field = new LinkField(itemField); switch (field.LinkType) { case "anchor": link.Url = field.Anchor; link.Type = LinkType.Anchor; break; case "external": link.Url = field.Url; link.Type = LinkType.External; break; case "mailto": link.Url = field.Url; link.Type = LinkType.MailTo; break; case "javascript": link.Url = field.Url; link.Type = LinkType.JavaScript; break; case "media": global::Sitecore.Data.Items.MediaItem media = new global::Sitecore.Data.Items.MediaItem(field.TargetItem); link.Url = global::Sitecore.Resources.Media.MediaManager.GetMediaUrl(media); link.Type = LinkType.Media; link.TargetId = field.TargetID.Guid; break; case "internal": if (field.TargetItem == null) link.Url = string.Empty; else link.Url = LinkManager.GetItemUrl(field.TargetItem); link.Type = LinkType.Internal; link.TargetId = field.TargetID.Guid; break; default: return null; break; } link.Anchor = field.Anchor; link.Class = field.Class; link.Text = field.Text; link.Title = field.Title; link.Target = field.Target; link.Query = field.QueryString; return link; }
public MailMessage GetForgotPasswordMailTemplate() { var settingsItem = GetAccountsSettingsItem(); LinkField link = settingsItem.Fields[Templates.AccountsSettings.Fields.ForgotPasswordMailTemplate]; var mailTemplateItem = link.TargetItem; if (mailTemplateItem == null) { throw new ItemNotFoundException($"Could not find mail template item with {link.TargetID} ID"); } var fromMail = mailTemplateItem.Fields[Templates.MailTemplate.Fields.From]; if (string.IsNullOrEmpty(fromMail.Value)) { throw new InvalidValueException("'From' field in mail template should be set"); } var body = mailTemplateItem.Fields[Templates.MailTemplate.Fields.Body]; var subject = mailTemplateItem.Fields[Templates.MailTemplate.Fields.Subject]; return(new MailMessage { From = new MailAddress(fromMail.Value), Body = body.Value, Subject = subject.Value }); }
//Записывает в текущую ячейку значение свойства выделенного параметра, field - имя поля //Транзакция создается из одной ячейки и добавляется в Transactions public void WriteValue(LinkField field, Transaction tlist) { try { if (!GeneralRep.CheckOneSheet(true)) { return; } var v = CurParam.GetField(field); var shape = _book.ActiveShape(); if (shape == null) { Range cell = GeneralRep.Application.ActiveCell; var t = new TransactionCell(cell) { NewValue = v, Value = v }; tlist.AddCell(t); } else if (shape.Type == MsoShapeType.msoTextBox) { var t = new TransactionShape(shape) { NewValue = v, Value = v }; tlist.AddShape(t); } } catch {} }
private NavigationItemModel GetNavLink(Item navItem) { var model = new NavigationItemModel { Title = navItem["Navigation Item Title"], Url = "#", Children = new NavigationItemModel[0], }; if (!navItem.HasChildren) { LinkField lf = navItem.Fields["Navigation Item Link"]; if (!string.IsNullOrEmpty(lf?.GetFriendlyUrl())) { model.Url = lf.GetFriendlyUrl(); } } else { // The model supports endless recursion. The front end view, however, does not. var childNavItems = new List <NavigationItemModel>(); foreach (Item childNavItem in navItem.GetChildren()) { childNavItems.Add(GetNavLink(childNavItem)); } model.Children = childNavItems.ToArray(); } return(model); }
public NewsPromoSectionViewModel GetNewsPromos() { var contextItem = RenderingContext.Current.Rendering.Item; var vm = new NewsPromoSectionViewModel(); vm.Title = contextItem[Templates.ExpertAdviceGroup.Fields.Title]; LinkField lnk = contextItem.Fields[Templates.ExpertAdviceGroup.Fields.ListPage]; vm.DetailsPage.Text = lnk.Text; vm.DetailsPage.Url = lnk.GetFriendlyUrl(); var articleIds = contextItem[Templates.ExpertAdviceGroup.Fields.Articles]?.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (var articleId in articleIds) { try { var article = context.Database.GetItem(articleId); if (article != null) { var model = new NewsListModel(article); vm.Articles.Add(model); } } catch (Exception) { // TODO: Log error } } return(vm); }
public override object GetField(Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { var sitecoreGalleryField = new LinkField(field); var advancedGallery = new AdvancedImageGalleryField(); var stringValue = sitecoreGalleryField.Value.IsNullOrEmpty() ? "<gallery />" : sitecoreGalleryField.Value; var xml = new XmlDocument(); xml.LoadXml(stringValue); var gallery = xml.DocumentElement; var galleryImages = new List <AdvancedImageField>(); if (gallery != null && gallery.HasChildNodes) { foreach (XmlElement galleryChildNode in gallery.ChildNodes) { var img = AdvancedImageHelper.ConvertMediaItemToField(galleryChildNode, field.Database); if (img == null) { continue; } galleryImages.Add(img); } } advancedGallery.GalleryItems = galleryImages; return(advancedGallery); }
protected void btnSubmit_OnClick(object sender, EventArgs e) { Database masterDatabase = Sitecore.Configuration.Factory.GetDatabase("master"); Item contextItem = masterDatabase.GetItem(Sitecore.Context.Item.ID); using (new SecurityDisabler()) { Item newComment = contextItem.Add(DateUtil.IsoNow, new TemplateID(new ID("{21B7E48C-3DFF-48A7-B48A-2BE90C9FAB06}"))); try { newComment.Editing.BeginEdit(); newComment.Fields["Comment Author"].Value = txtAuthor.Text; newComment.Fields["Comment Text"].Value = txtContent.Text; LinkField link = newComment.Fields["Comment Author Website"]; link.Url = txtLink.Text; link.Text = txtLink.Text; link.Target = "_blank"; link.LinkType = "external"; newComment.Editing.EndEdit(); } catch { newComment.Editing.CancelEdit(); } } Sitecore.Web.WebUtil.ReloadPage(); }
private string GetValue(Field field) { switch (field.Type.ToLowerInvariant()) { case "checkbox": return(field.Value == "1" ? "true" : "false"); case "image": if (field.Value == "<media />" || field.Value == "<media/>") { return(string.Empty); } var imageField = new ImageField(field); var imageItem = imageField.MediaItem; return(imageItem != null ? imageItem.Paths.Path : field.Value); case "link": if (field.Value == "<link />" || field.Value == "<link/>") { return(string.Empty); } var linkField = new LinkField(field); var linkItem = linkField.TargetItem; return(linkItem != null ? linkItem.Paths.Path : field.Value); default: return(field.Value); } }
public static string GetLinkFieldUrl(LinkField field) { if (field == null) return string.Empty; //If it is an internal link return the URL to the item if (field.IsInternal) { Item targetItem = Sitecore.Context.Database.GetItem(field.TargetID); if(targetItem == null) return string.Empty; if (targetItem.Paths.IsMediaItem) { return Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(targetItem)); } return LinkManager.GetItemUrl(targetItem); } //If it is a media link, return the media path if (field.IsMediaLink) { if (field.TargetItem == null) return string.Empty; return Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(field.TargetItem)); } //Return the url if it is not a if (field.Url == null) return string.Empty; return field.Url; }
/// <summary> /// Tries to get the URL for the link field on the item. /// </summary> /// <param name="item">The item containing the link field.</param> /// <param name="fieldName">The name of the link field on the item.</param> /// <param name="url">The URL contained in the link field.</param> /// <returns>True if able to return a URL; otherwise, false.</returns> public static bool GetGeneralLinkURL(Item item, string fieldName, out string url) { url = string.Empty; try { if (item == null || string.IsNullOrEmpty(fieldName)) { return(false); } var rawLinkField = item.Fields[fieldName]; var linkFieldIsValidAndHasContent = rawLinkField != null && !string.IsNullOrEmpty(rawLinkField.Value) && FieldTypeManager.GetField(rawLinkField) is LinkField; if (!linkFieldIsValidAndHasContent) { return(false); } LinkField linkField = rawLinkField; return(GetGeneralLinkURL(linkField, out url)); } catch { return(false); } }
//TODO - share this with RedirectItemResolver protected virtual string GetRedirectUrl(Item redirectItem) { LinkField redirectLinkField = redirectItem.Fields[Templates.AdvancedRedirect.Fields.Target]; string redirectUrl = null; if (redirectLinkField != null) { if (!redirectLinkField.IsInternal || redirectLinkField.TargetItem == null) { redirectUrl = (!redirectLinkField.IsMediaLink || redirectLinkField.TargetItem == null ? redirectLinkField.Url : ((MediaItem)redirectLinkField.TargetItem).GetMediaUrl(null)); } else { //TODO - get site of taret item, not context, to support cross site resolving SiteInfo siteInfo = Context.Site.SiteInfo; //get the base options from the link provider ItemUrlBuilderOptions defaultOptions = new DefaultItemUrlBuilderOptions(); defaultOptions.Site = SiteContextFactory.GetSiteContext(siteInfo.Name); defaultOptions.AlwaysIncludeServerUrl = true; defaultOptions.SiteResolving = true; //inject option for languageembedding defaultOptions.LanguageEmbedding = LanguageEmbedding.Never; redirectUrl = LinkManager.GetItemUrl(redirectLinkField.TargetItem, defaultOptions); } } return(redirectUrl); }
public static string SafeLinkFieldFriendlyUrl(this Item item, ID fieldId) { var toReturn = string.Empty; if (item != null && !fieldId.IsNull) { LinkField linkField = item.Fields[fieldId]; if (linkField != null) { toReturn = linkField.GetFriendlyUrl(); } } else { if (item == null) { GatedContentLogger.Error("item is null", new object()); } if (fieldId.IsNull) { GatedContentLogger.Error("fieldId is null", new object()); } } return(toReturn); }
public override string Value(TokenDataCollection extraData) { LinkField f = TokenKeeper.CurrentKeeper.GetDatabase().GetItem(BackingId).Fields["Link"]; return(string.Format("<a href='{0}' target='{1}' class='{2}' title='{3}'>{4}</a>", f.GetFriendlyUrl(), f.Target, f.Class, f.Title, extraData["Link Text"])); }
private UrlString GetRedirectUrl(Uri returnUrl) { // NOTE [ILs] Don't redirect to absolute uris for redirectUrl after login, this may be a nefarious attempt to steal user information string result = returnUrl != null && returnUrl.IsAbsoluteUri ? string.Empty : returnUrl?.OriginalString; if (string.IsNullOrWhiteSpace(result)) { SearchResultItem searchResult; using (IProviderSearchContext searchContext = _searchIndex.CreateSearchContext()) { searchResult = searchContext.GetQueryable <SearchResultItem>() .FirstOrDefault( i => i.Paths.Contains(_siteRoot) && i.TemplateId == Templates.LoginSettings.Id); } Item loginSettingsItem = searchResult?.GetItem(); if (loginSettingsItem != null) { LinkField linkField = loginSettingsItem.Fields[Templates.LoginSettings.Fields.PostLoginRedirect]; Item targetItem = linkField.TargetID != (ID)null && linkField.TargetID != ID.Null ? _db.GetItem(linkField.TargetID) : null; result = targetItem != null?LinkManager.GetItemUrl(targetItem) : null; } } return(new UrlString(result ?? "/")); }
public virtual TopNavigationModel GetModel(Item actionItem) { var model = new TopNavigationModel { BrandLinkText = actionItem["Brand Link Text"], BrandLinkUrl = "/", }; LinkField lf = actionItem.Fields["Brand Link"]; if (!string.IsNullOrEmpty(lf?.GetFriendlyUrl())) { model.BrandLinkUrl = lf.GetFriendlyUrl(); } var navLinks = new List <NavigationItemModel>(); foreach (Item navLinkItem in actionItem.GetChildren()) { navLinks.Add(GetNavLink(navLinkItem)); } model.TopNavigationLinks = navLinks.ToArray(); return(model); }
static public IGeneralLink GetGeneralLinkFieldValue(this Item item, ID fieldId) { LinkField f = ((LinkField)GetField(item, fieldId)); if (f != null && f.IsInternal && f.TargetItem != null) { return(new GeneralLink() { Url = f.TargetItem.GetLink(), Text = f.Text, CssClass = f.Class, Target = f.Target }); } else if (f != null) { return(new GeneralLink() { Url = f.Url, Text = f.Text, CssClass = f.Class, Target = f.Target }); } else { return(null); } }
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); } } }
private void TextField_KeyDown(object sender, KeyRoutedEventArgs e) { if (e.Key == Windows.System.VirtualKey.Enter) { LinkField.Focus(FocusState.Keyboard); e.Handled = true; } }
public bool FiletrItem(Item currentitem) { LinkField link = currentitem.Fields["Destination"]; var item = Sitecore.Context.Database.GetItem(link.TargetID); CheckboxField field = (CheckboxField)item.Fields["Include In Navigation"]; return(field.Checked); }
public void WithModifiesLink(LinkField field, Page newLinkedPage) { // Act var modified = field.With(f => f.PageLink == new LazyLink <Page>(newLinkedPage)); // Assert Assert.That(modified.PageLink.Link, Is.EqualTo(newLinkedPage)); }
public string GetMediaLinkFieldAbsoluteUrl(LinkField field) { if (field.TargetItem == null) { return null; } return Sitecore.Resources.Media.MediaManager.GetMediaUrl(field.TargetItem, BuildAbsoluteUrlMediaUrlOptions()); }
protected static string getFriendlyFieldValue(string name, Item itemElement, int iMaxLength) { Field field = itemElement.Fields[name]; if (field != null) { switch (field.TypeKey) { case "date": case "datetime": return formatDateField(itemElement, field.ID); case "droplink": case "droptree": case "reference": case "grouped droplink": LookupField lookupFld = (LookupField)field; if (lookupFld != null && lookupFld.TargetItem != null) { return lookupFld.TargetItem.Name; } break; case "checklist": case "multilist": case "treelist": case "treelistex": MultilistField multilistField = (MultilistField)field; if (multilistField != null) { StringBuilder strBuilder = new StringBuilder(); foreach (Item item in multilistField.GetItems()) { strBuilder.AppendFormat("{0}, ", item.Name); } return StringUtil.Clip(strBuilder.ToString().TrimEnd(',', ' '), iMaxLength, true); } break; case "link": case "general link": LinkField lf = new LinkField(field); switch (lf.LinkType) { case "media": case "internal": return lf.TargetItem.Paths.ContentPath; case "anchor": case "mailto": case "external": return lf.Url; default: return lf.Text; } default: return StringUtil.Clip(field.Value, iMaxLength, true); } } return String.Empty; }
/// <summary> /// Gets the correct URL for a general link field according to SDN as of SC 6.4 /// </summary> public static string GetGeneralLinkHref(LinkField field) { Assert.ArgumentNotNull(field, "field"); // so Sitecore, why isn't this encapsulated into the LinkField class again? string url; switch (field.LinkType) { case "internal": // catch internal links with external HTTP URLs if (Regex.IsMatch(field.Url, "^https?://")) return field.Url; if (field.TargetItem == null) return string.Empty; url = LinkManager.GetItemUrl(field.TargetItem); break; case "external": case "mailto": case "anchor": case "javascript": url = field.Url; break; case "media": Item target = field.TargetItem; if (target == null) return string.Empty; url = GetMediaUrl(target); break; case "": return string.Empty; default: string message = String.Format("Unknown link type {0} in {1}", field.LinkType, field.InnerField.Item.Paths.FullPath); Log.Warn(message, typeof(FieldUtility)); return string.Empty; } if (!string.IsNullOrEmpty(field.QueryString)) { url += "?" + field.QueryString.TrimStart('?'); } return url; }
/// <summary> /// Gets the item URL. /// </summary> /// <param name="field">The field.</param> /// <returns> /// The item URL. /// </returns> protected string GetItemUrl(Data.Fields.Field field) { LinkField lf = new LinkField(field); Item item = null; if (lf.IsInternal) { item = Sitecore.Context.Database.GetItem(lf.TargetID); } if (item != null) { return LinkManager.GetItemUrl(item) + (!string.IsNullOrEmpty(lf.QueryString) ? "?" + lf.QueryString : string.Empty); } return string.Empty; }
public string GetLinkFieldAbsoluteUrl(LinkField field) { if (field == null) { return null; } switch (field.LinkType.ToLower()) { case "internal": return GetItemAbsoluteUrl(field.TargetItem); case "media": return mediaManagerHelper.GetMediaLinkFieldAbsoluteUrl(field); case "anchor": // Prefix anchor link with # if link if not empty return !string.IsNullOrEmpty(field.Anchor) ? "#" + field.Anchor : string.Empty; default: // all others fallback return field.Url; } }
public override string Import(Field field, Item item, ILanguage language, string value) { var linkField = new LinkField(field); return linkField.TargetItem?.Paths.Path ?? value; }
public void SetValue_Internal() { //Assign Item item = _db.GetItem(new ID(_itemId)); string expected = "<link text=\"TestDesc\" linktype=\"internal\" url=\"/Home.aspx\" anchor=\"TestAnch\" querystring=\"TestQuery\" title=\"TestAlt\" class=\"TestClass\" target=\"_blank\" id=\"{98F907F7-CD1A-4C88-AF11-8F38A21A7FE1}\" />"; SitecoreProperty property = new SitecoreProperty() { Attribute = new SitecoreFieldAttribute(), Property = new FakePropertyInfo(typeof(Link), "GeneralLink") }; _handler.ConfigureDataHandler(property); Link link = new Link(); link.Text = "TestDesc"; link.Type = LinkType.Internal; link.Anchor = "TestAnch"; link.Query = "TestQuery"; link.Title = "TestAlt"; link.Target = "_blank"; link.Class = "TestClass"; link.TargetId = new Guid("{98F907F7-CD1A-4C88-AF11-8F38A21A7FE1}"); string result = string.Empty; using (new SecurityDisabler()) { item.Editing.BeginEdit(); //Act _handler.SetValue(item, link, null); LinkField field = new LinkField(item.Fields["GeneralLink"]); Assert.AreEqual( "TestAnch", field.Anchor); Assert.AreEqual( "TestClass", field.Class); Assert.AreEqual("internal", field.LinkType); Assert.AreEqual("TestQuery", field.QueryString); Assert.AreEqual(new Guid("{98F907F7-CD1A-4C88-AF11-8F38A21A7FE1}"), field.TargetID.Guid); Assert.AreEqual("TestDesc", field.Text); Assert.AreEqual("TestAlt", field.Title); item.Editing.CancelEdit(); } }
public void SetValue_Media() { //Assign Item item = _db.GetItem(new ID(_itemId)); string expected = "<link text=\"TestDesc\" linktype=\"media\" url=\"/Files/Kitten1\" title=\"TestText\" class=\"TestClass\" target=\"_blank\" id=\"{223EEAE5-DF4C-4E30-95AC-17BE2F00E2CD}\" />"; SitecoreProperty property = new SitecoreProperty() { Attribute = new SitecoreFieldAttribute(), Property = new FakePropertyInfo(typeof(Link), "GeneralLink") }; _handler.ConfigureDataHandler(property); Link link = new Link(); link.Text = "TestDesc"; link.Type = LinkType.Media; link.Anchor = "TestAnch"; link.Query = "TestQuery"; link.Title = "TestAlt"; link.Target = "_blank"; link.Class = "TestClass"; link.TargetId = new Guid("{223EEAE5-DF4C-4E30-95AC-17BE2F00E2CD}"); string result = string.Empty; using (new SecurityDisabler()) { item.Editing.BeginEdit(); //Act _handler.SetValue(item, link, null); LinkField field = new LinkField(item.Fields["GeneralLink"]); //Assert Assert.AreEqual("TestAnch", field.Anchor); Assert.AreEqual("TestClass", field.Class); Assert.AreEqual("media", field.LinkType); Assert.AreEqual("TestQuery", field.QueryString); Assert.AreEqual(new Guid("{223EEAE5-DF4C-4E30-95AC-17BE2F00E2CD}"), field.TargetID.Guid); Assert.AreEqual("TestDesc", field.Text); Assert.AreEqual("TestAlt", field.Title); item.Editing.CancelEdit(); } }
public void SetValue_JavaScript() { //Assign Item item = _db.GetItem(new ID(_itemId)); string expected = "<link text=\"Test\" linktype=\"javascript\" url=\"javascript:JavaScript\" anchor=\"\" title=\"text\" class=\"class\" />"; SitecoreProperty property = new SitecoreProperty() { Attribute = new SitecoreFieldAttribute(), Property = new FakePropertyInfo(typeof(Link), "GeneralLink") }; _handler.ConfigureDataHandler(property); Link link = new Link(); link.Text = "TestDesc"; link.Type = LinkType.JavaScript; link.Anchor = "TestAnch"; link.Query = "TestQuery"; link.Title = "TestAlt"; link.Target = "_blank"; link.Class = "TestClass"; link.Url = "javascript:JavaScript"; string result = string.Empty; using (new SecurityDisabler()) { item.Editing.BeginEdit(); //Act _handler.SetValue(item, link, null); LinkField field = new LinkField(item.Fields["GeneralLink"]); //Assert Assert.AreEqual("TestAnch", field.Anchor); Assert.AreEqual("TestClass", field.Class); Assert.AreEqual("javascript", field.LinkType); Assert.AreEqual("TestQuery", field.QueryString); Assert.AreEqual("TestDesc", field.Text); Assert.AreEqual("TestAlt", field.Title); Assert.AreEqual("javascript:JavaScript", field.Url); item.Editing.CancelEdit(); } }
protected virtual void AddLinkField(Document document, LinkField field, FieldConfiguration fieldConfiguration) { if (field == null || fieldConfiguration == null) { return; } string fieldName = SitecoreQueryBuilderExtensions.GetEncodedFieldName(field.InnerField.Name); if (fieldConfiguration.Analyze) { document.AddAnalysedField(fieldName, field.TargetID.ToLuceneId(), fieldConfiguration.Store); return; } document.AddNonAnalysedField(fieldName, field.TargetID.ToLuceneId(), fieldConfiguration.Store); }
public override void Initialize(Rendering rendering) { base.Initialize(rendering); Link = rendering.Item.Fields["Link"]; }
public string GetUrlFromLinkField(LinkField linkField) { using (new SecurityDisabler()) { return linkField == null ? string.Empty : FieldUtility.GetGeneralLinkHref(linkField); } }
/// <summary> /// Converts the field. /// </summary> /// <param name="field">The field.</param> /// <param name="writer">The writer.</param> private static void ConvertField(Field field, XmlTextWriter writer) { switch (field.Type.ToLower()) { case "lookup": LookupField lookupField = new LookupField(field); if (lookupField.TargetItem != null) { string language = lookupField.TargetItem["Regional Iso Code"]; if (string.IsNullOrEmpty(language) || !UseRegionalIsoCodeForEnglish) { language = lookupField.TargetItem["Iso"]; } if (!string.IsNullOrEmpty(language)) { writer.WriteStartAttribute(field.Name, string.Empty); writer.WriteString(language); writer.WriteEndAttribute(); } } break; case "link": LinkField link = new LinkField(field); if (link.InternalPath != string.Empty) { writer.WriteStartAttribute(field.Name, string.Empty); writer.WriteString(link.InternalPath); writer.WriteEndAttribute(); } break; case "checkbox": CheckboxField checkbox = new CheckboxField(field); if (field.Name == "mode") { if (!checkbox.Checked) { writer.WriteStartAttribute(field.Name, string.Empty); writer.WriteString("off"); writer.WriteEndAttribute(); } } else { if (checkbox.Checked) { writer.WriteStartAttribute(field.Name, string.Empty); writer.WriteString("true"); writer.WriteEndAttribute(); } } break; default: if (field.Value != string.Empty) { writer.WriteStartAttribute(field.Name, string.Empty); writer.WriteString(field.Value); writer.WriteEndAttribute(); } break; } }
/// <summary> /// Gets the field. /// </summary> /// <param name="field">The field.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <returns>System.Object.</returns> public override object GetField(Sitecore.Data.Fields.Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { if (field == null || field.Value.Trim().IsNullOrEmpty()) return null; Link link = new Link(); LinkField linkField = new LinkField(field); link.Anchor = linkField.Anchor; link.Class = linkField.Class; link.Text = linkField.Text; link.Title = linkField.Title; link.Target = linkField.Target; link.Query = linkField.QueryString; switch (linkField.LinkType) { case "anchor": link.Url = linkField.Anchor; link.Type = LinkType.Anchor; break; case "external": link.Url = linkField.Url; link.Type = LinkType.External; break; case "mailto": link.Url = linkField.Url; link.Type = LinkType.MailTo; break; case "javascript": link.Url = linkField.Url; link.Type = LinkType.JavaScript; break; case "media": if (linkField.TargetItem == null) link.Url = string.Empty; else { global::Sitecore.Data.Items.MediaItem media = new global::Sitecore.Data.Items.MediaItem(linkField.TargetItem); link.Url = global::Sitecore.Resources.Media.MediaManager.GetMediaUrl(media); } link.Type = LinkType.Media; link.TargetId = linkField.TargetID.Guid; break; case "internal": var urlOptions = Utilities.CreateUrlOptions(config.UrlOptions); if (linkField.TargetItem == null) link.Url = string.Empty; else link.Url = LinkManager.GetItemUrl(linkField.TargetItem, urlOptions); link.Type = LinkType.Internal; link.TargetId = linkField.TargetID.Guid; link.Text = linkField.Text.IsNullOrEmpty() ? (linkField.TargetItem == null ? string.Empty : linkField.TargetItem.DisplayName) : linkField.Text; break; default: return null; } return link; }
public virtual void RemoveLink(LinkField link) { if (Links.Contains(link)) Links.Remove(link); }
internal static void GetRedirectUrlOrItemId(LinkField redirectTo, out string actionRewriteUrl, out Guid? redirectItemId, out string redirectItemAnchor) { actionRewriteUrl = null; redirectItemId = null; redirectItemAnchor = null; if (redirectTo.TargetItem != null) { redirectItemId = redirectTo.TargetItem.ID.Guid; redirectItemAnchor = redirectTo.Anchor; } else { actionRewriteUrl = redirectTo.Url; } }
public void SetItem_Test2() { //Assign //clear all fields var clearItem = _db.GetItem("/sitecore/content/Configuration/Fluent/GeneralFluent/SetItemTest2"); using (new SecurityDisabler()) { clearItem.BeginEdit(); foreach (Field field in clearItem.Fields) { field.Value = ""; } clearItem["GroupedDropList"] = "Test2"; clearItem["DropList"] = "Test2"; clearItem.EndEdit(); } GeneralFluentFixtureNS.BasicTemplate test; using (new SecurityDisabler()) { test = _sitecore.GetItem<GeneralFluentFixtureNS.BasicTemplate>("/sitecore/content/Configuration/Fluent/GeneralFluent/SetItemTest2"); } //Simple Types test.Checkbox = true; test.Date = new DateTime(2011, 02, 28); test.DateTime = new DateTime(2011, 03, 04, 15, 23, 12); test.File = new File() { Id = new Guid("{B89EA3C6-C947-44AF-9AEF-7EF89CEB0A4B}") }; test.Image = new Image() { Alt="Test Alt", Border = "Test Border", Class="Test Class", Height=487, HSpace=52, MediaId = new Guid("{0CF0A6D0-8A2B-479B-AD8F-14938135174A}"), VSpace= 32, Width = 26 }; test.Integer = 659; test.Float = 458.7f; test.Double = 789.5d; test.Decimal = 986.4m; test.MultiLineText = "Test MultiLineText"; test.Number = 986; test.Password = "******"; test.RichText = "test Rich Text"; test.SingleLineText = "test single line text"; //List Types test.CheckList = new GeneralFluentFixtureNS.SubClass[]{ new GeneralFluentFixtureNS.SubClass(){Id = _check1.ID.Guid}, new GeneralFluentFixtureNS.SubClass(){Id = _check2.ID.Guid}, }; test.DropList = GeneralFluentFixtureNS.TestEnum.Test3; test.GroupedDropLink = new GeneralFluentFixtureNS.SubClass() { Id = _test3.ID.Guid }; test.GroupedDropList = GeneralFluentFixtureNS.TestEnum.Test3; test.MultiList = new GeneralFluentFixtureNS.SubClass[]{ new GeneralFluentFixtureNS.SubClass(){Id = _multiList1.ID.Guid}, new GeneralFluentFixtureNS.SubClass(){Id = _multiList2.ID.Guid}, }; test.Treelist = new GeneralFluentFixtureNS.SubClass[]{ new GeneralFluentFixtureNS.SubClass(){Id = _treeList1.ID.Guid}, new GeneralFluentFixtureNS.SubClass(){Id = _treeList2.ID.Guid}, }; test.TreeListEx = new GeneralFluentFixtureNS.SubClass[]{ new GeneralFluentFixtureNS.SubClass(){Id = _treeList1.ID.Guid}, }; //Link Types test.DropLink = new GeneralFluentFixtureNS.SubClass() { Id = _test3.ID.Guid }; test.DropTree = new GeneralFluentFixtureNS.SubClass() { Id = _test3.ID.Guid }; test.GeneralLink = new Link(){ Type = LinkType.External, Anchor="test anchor", Class="test class", Target="test target", Text="test text", Title="test title", Url="test url" }; //Developer Types test.Icon = "test icon"; test.TriState = TriState.Yes; //Act using (new SecurityDisabler()) { _sitecore.Save<GeneralFluentFixtureNS.BasicTemplate>(test); } //Assert //Simple Types Item result = _db.GetItem(clearItem.ID); Assert.AreEqual("1", result["Checkbox"]); Assert.AreEqual("20110228T000000", result["Date"]); Assert.AreEqual("20110304T152312", result["DateTime"]); var file = new FileField(result.Fields["File"]); Assert.AreEqual(new Guid("{B89EA3C6-C947-44AF-9AEF-7EF89CEB0A4B}"), file.MediaID.Guid); Assert.AreEqual("/~/media/Files/SimpleTextFile2.ashx", file.Src); var image = new ImageField(result.Fields["Image"]); Assert.AreEqual("Test Alt", image.Alt); Assert.AreEqual("Test Border", image.Border); Assert.AreEqual("Test Class", image.Class); Assert.AreEqual("487", image.Height); Assert.AreEqual("52", image.HSpace); Assert.AreEqual(new Guid("{0CF0A6D0-8A2B-479B-AD8F-14938135174A}"), image.MediaID.Guid); Assert.AreEqual("/~/media/Files/Kitten2.ashx", image.Src); Assert.AreEqual("32", image.VSpace); Assert.AreEqual("26", image.Width); Assert.AreEqual("659", result["Integer"]); Assert.AreEqual("458.7", result["Float"]); Assert.AreEqual("789.5", result["Double"]); Assert.AreEqual("986.4", result["Decimal"]); Assert.AreEqual("Test MultiLineText", result["MultiLineText"]); Assert.AreEqual("986", result["Number"]); Assert.AreEqual("test password", result["Password"]); Assert.AreEqual("test Rich Text", result["RichText"]); Assert.AreEqual("test single line text", result["SingleLineText"]); //List Types Assert.AreEqual("{68B87391-CFF7-4FF2-848E-90C8FD8336A2}|{154CABCB-9B04-449A-9F6F-8FD2AD0783D9}", result["CheckList"].ToUpper()); Assert.AreEqual("Test3", result["DropList"]); Assert.AreEqual(_test3.ID.Guid.ToString("B").ToUpper(), result["GroupedDropLink"].ToUpper()); Assert.AreEqual("Test3", result["GroupedDropList"]); Assert.AreEqual("{1BE4FAC5-90C2-4A5E-952C-071ECD7DA957}|{6127B3E3-B2EB-4B96-AE6D-51DF0212C0EA}", result["MultiList"].ToUpper()); Assert.AreEqual("{35E0CE21-2651-46CD-B87D-0B34216D3137}|{F52A1B3B-356E-45A4-B06C-DFAE28B6D78A}", result["Treelist"].ToUpper()); Assert.AreEqual("{35E0CE21-2651-46CD-B87D-0B34216D3137}", result["TreeListEx"].ToUpper()); //Linked Types Assert.AreEqual(_test3.ID.Guid.ToString("B").ToUpper(), result["DropLink"].ToUpper()); Assert.AreEqual(_test3.ID.Guid.ToString("B").ToUpper(), result["DropTree"].ToUpper()); LinkField link = new LinkField(result.Fields["GeneralLink"]); Assert.AreEqual("test class", link.Class); Assert.AreEqual("test target", link.Target); Assert.AreEqual("test text", link.Text); Assert.AreEqual("test title", link.Title); Assert.AreEqual("test url", link.Url); //Developer Type Assert.AreEqual("test icon", result["Icon"]); Assert.AreEqual("1", result["TriState"]); }
public override void SetValue(global::Sitecore.Data.Items.Item item, object value, ISitecoreService service) { Link link = value as Link; var itemField = base.GetField(item); if (itemField == null) return; LinkField field = new LinkField(itemField); if (link == null || link.Type == LinkType.NotSet) { field.Clear(); return; } switch (link.Type) { case LinkType.Internal: field.LinkType = "internal"; if (field.TargetID.Guid != link.TargetId) { if (link.TargetId == Guid.Empty) { ItemLink iLink = new ItemLink(item.Database.Name, item.ID, field.InnerField.ID, field.TargetItem.Database.Name, field.TargetID, field.TargetItem.Paths.FullPath); field.RemoveLink(iLink); } else { ID newId = new ID(link.TargetId); Item target = item.Database.GetItem(newId); if (target != null) { field.TargetID = newId; ItemLink nLink = new ItemLink(item.Database.Name, item.ID, field.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath); field.UpdateLink(nLink); field.Url = LinkManager.GetItemUrl(target); } else throw new MapperException("No item with ID {0}. Can not update Link field".Formatted(newId)); } } break; case LinkType.Media: field.LinkType = "media"; if (field.TargetID.Guid != link.TargetId) { if (link.TargetId == Guid.Empty) { ItemLink iLink = new ItemLink(item.Database.Name, item.ID, field.InnerField.ID, field.TargetItem.Database.Name, field.TargetID, field.TargetItem.Paths.FullPath); field.RemoveLink(iLink); } else { ID newId = new ID(link.TargetId); Item target = item.Database.GetItem(newId); global::Sitecore.Data.Items.MediaItem media = new global::Sitecore.Data.Items.MediaItem(target); if (target != null) { field.TargetID = newId; ItemLink nLink = new ItemLink(item.Database.Name, item.ID, field.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath); field.UpdateLink(nLink); field.Url = global::Sitecore.Resources.Media.MediaManager.GetMediaUrl(media); } else throw new MapperException("No item with ID {0}. Can not update Link field".Formatted(newId)); } } break; case LinkType.External: field.LinkType = "external"; field.Url = link.Url; break; case LinkType.Anchor: field.LinkType = "anchor"; field.Url = link.Anchor; break; case LinkType.MailTo: field.LinkType = "mailto"; field.Url = link.Url; break; case LinkType.JavaScript: field.LinkType = "javascript"; field.Url = link.Url; break; } if (!link.Anchor.IsNullOrEmpty()) field.Anchor = link.Anchor; if (!link.Class.IsNullOrEmpty()) field.Class = link.Class; if (!link.Text.IsNullOrEmpty()) field.Text = link.Text; if (!link.Title.IsNullOrEmpty()) field.Title = link.Title; if (!link.Query.IsNullOrEmpty()) field.QueryString = link.Query; if (!link.Target.IsNullOrEmpty()) field.Target = link.Target; }
public void SetItem_Test2() { //Assign //clear all fields using (new SecurityDisabler()) { _test2.BeginEdit(); foreach (Field field in _test2.Fields) { field.Value = ""; } _test2["GroupedDropList"] = "Test2"; _test2["DropList"] = "Test2"; _test2.EndEdit(); } MiscFixtureNS.BasicTemplate test = _sitecore.GetItem<MiscFixtureNS.BasicTemplate>("/sitecore/content/Glass/Test2"); //Simple Types test.Checkbox = true; test.Date = new DateTime(2011, 02, 28); test.DateTime = new DateTime(2011, 03, 04, 15, 23, 12); test.File = new File() { Id = new Guid("{B89EA3C6-C947-44AF-9AEF-7EF89CEB0A4B}") }; test.Image = new Image() { Alt="Test Alt", Border = "Test Border", Class="Test Class", Height=487, HSpace=52, MediaId = new Guid("{0CF0A6D0-8A2B-479B-AD8F-14938135174A}"), VSpace= 32, Width = 26 }; test.Integer = 659; test.Float = 458.7f; test.Double = 789.5d; test.Decimal = 986.4m; test.MultiLineText = "Test MultiLineText"; test.Number = 986; test.Password = "******"; test.RichText = "test Rich Text"; test.SingleLineText = "test single line text"; //List Types test.CheckList = new MiscFixtureNS.SubClass[]{ new MiscFixtureNS.SubClass(){Id = _test1.ID.Guid}, new MiscFixtureNS.SubClass(){Id = _test2.ID.Guid}, }; test.DropList = MiscFixtureNS.TestEnum.Test3; test.GroupedDropLink = new MiscFixtureNS.SubClass() { Id = _test3.ID.Guid }; test.GroupedDropList = MiscFixtureNS.TestEnum.Test3; test.MultiList = new MiscFixtureNS.SubClass[]{ new MiscFixtureNS.SubClass(){Id = _test1.ID.Guid}, new MiscFixtureNS.SubClass(){Id = _test2.ID.Guid}, }; test.Treelist = new MiscFixtureNS.SubClass[]{ new MiscFixtureNS.SubClass(){Id = _test1.ID.Guid}, new MiscFixtureNS.SubClass(){Id = _test2.ID.Guid}, }; test.TreeListEx = new MiscFixtureNS.SubClass[]{ new MiscFixtureNS.SubClass(){Id = _test1.ID.Guid}, new MiscFixtureNS.SubClass(){Id = _test2.ID.Guid}, }; //Link Types test.DropLink = new MiscFixtureNS.SubClass() { Id = _test3.ID.Guid }; test.DropTree = new MiscFixtureNS.SubClass() { Id = _test3.ID.Guid }; test.GeneralLink = new Link(){ Type = LinkType.External, Anchor="test anchor", Class="test class", Target="test target", Text="test text", Title="test title", Url="test url" }; //Developer Types test.Icon = "test icon"; test.TriState = TriState.Yes; //Act using (new SecurityDisabler()) { _sitecore.Save<MiscFixtureNS.BasicTemplate>(test); } //Assert //Simple Types Item result = _db.GetItem(_test2.ID); Assert.AreEqual("1", result["Checkbox"]); Assert.AreEqual("20110228T000000", result["Date"]); Assert.AreEqual("20110304T152312", result["DateTime"]); var file = new FileField(result.Fields["File"]); Assert.AreEqual(new Guid("{B89EA3C6-C947-44AF-9AEF-7EF89CEB0A4B}"), file.MediaID.Guid); Assert.AreEqual("/~/media/Files/SimpleTextFile2.ashx", file.Src); var image = new ImageField(result.Fields["Image"]); Assert.AreEqual("Test Alt", image.Alt); Assert.AreEqual("Test Border", image.Border); Assert.AreEqual("Test Class", image.Class); Assert.AreEqual("487", image.Height); Assert.AreEqual("52", image.HSpace); Assert.AreEqual(new Guid("{0CF0A6D0-8A2B-479B-AD8F-14938135174A}"), image.MediaID.Guid); Assert.AreEqual("/~/media/Files/Kitten2.ashx", image.Src); Assert.AreEqual("32", image.VSpace); Assert.AreEqual("26", image.Width); Assert.AreEqual("659", result["Integer"]); Assert.AreEqual("458.7", result["Float"]); Assert.AreEqual("789.5", result["Double"]); Assert.AreEqual("986.4", result["Decimal"]); Assert.AreEqual("Test MultiLineText", result["MultiLineText"]); Assert.AreEqual("986", result["Number"]); Assert.AreEqual("test password", result["Password"]); Assert.AreEqual("test Rich Text", result["RichText"]); Assert.AreEqual("test single line text", result["SingleLineText"]); //List Types Assert.AreEqual("{BD193B3A-D3CA-49B4-BF7A-2A61ED77F19D}|{8A317CBA-81D4-4F9E-9953-64C4084AECCA}", result["CheckList"].ToUpper()); Assert.AreEqual("Test3", result["DropList"]); Assert.AreEqual(_test3.ID.Guid.ToString("B").ToUpper(), result["GroupedDropLink"].ToUpper()); Assert.AreEqual("Test3", result["GroupedDropList"]); Assert.AreEqual("{BD193B3A-D3CA-49B4-BF7A-2A61ED77F19D}|{8A317CBA-81D4-4F9E-9953-64C4084AECCA}", result["MultiList"].ToUpper()); Assert.AreEqual("{BD193B3A-D3CA-49B4-BF7A-2A61ED77F19D}|{8A317CBA-81D4-4F9E-9953-64C4084AECCA}", result["Treelist"].ToUpper()); Assert.AreEqual("{BD193B3A-D3CA-49B4-BF7A-2A61ED77F19D}|{8A317CBA-81D4-4F9E-9953-64C4084AECCA}", result["TreeListEx"].ToUpper()); //Linked Types Assert.AreEqual(_test3.ID.Guid.ToString("B").ToUpper(), result["DropLink"].ToUpper()); Assert.AreEqual(_test3.ID.Guid.ToString("B").ToUpper(), result["DropTree"].ToUpper()); LinkField link = new LinkField(result.Fields["GeneralLink"]); Assert.AreEqual("test class", link.Class); Assert.AreEqual("test target", link.Target); Assert.AreEqual("test text", link.Text); Assert.AreEqual("test title", link.Title); Assert.AreEqual("test url", link.Url); //Developer Type Assert.AreEqual("test icon", result["Icon"]); Assert.AreEqual("1", result["TriState"]); }
/// <summary> /// Sets the field. /// </summary> /// <param name="field">The field.</param> /// <param name="value">The value.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <exception cref="Glass.Mapper.MapperException"> /// No item with ID {0}. Can not update Link linkField.Formatted(newId) /// or /// No item with ID {0}. Can not update Link linkField.Formatted(newId) /// </exception> public override void SetField(Field field, object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { Link link = value as Link; if (field == null) return; var item = field.Item; LinkField linkField = new LinkField(field); if (link == null || link.Type == LinkType.NotSet) { linkField.Clear(); return; } switch (link.Type) { case LinkType.Internal: linkField.LinkType = "internal"; if (linkField.TargetID.Guid != link.TargetId) { if (link.TargetId == Guid.Empty) { ItemLink iLink = new ItemLink(item.Database.Name, item.ID, linkField.InnerField.ID, linkField.TargetItem.Database.Name, linkField.TargetID, linkField.TargetItem.Paths.FullPath); linkField.RemoveLink(iLink); } else { ID newId = new ID(link.TargetId); Item target = item.Database.GetItem(newId); if (target != null) { linkField.TargetID = newId; ItemLink nLink = new ItemLink(item.Database.Name, item.ID, linkField.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath); linkField.UpdateLink(nLink); linkField.Url = LinkManager.GetItemUrl(target); } else throw new MapperException("No item with ID {0}. Can not update Link linkField".Formatted(newId)); } } break; case LinkType.Media: linkField.LinkType = "media"; if (linkField.TargetID.Guid != link.TargetId) { if (link.TargetId == Guid.Empty) { ItemLink iLink = new ItemLink(item.Database.Name, item.ID, linkField.InnerField.ID, linkField.TargetItem.Database.Name, linkField.TargetID, linkField.TargetItem.Paths.FullPath); linkField.RemoveLink(iLink); } else { ID newId = new ID(link.TargetId); Item target = item.Database.GetItem(newId); if (target != null) { global::Sitecore.Data.Items.MediaItem media = new global::Sitecore.Data.Items.MediaItem(target); linkField.TargetID = newId; ItemLink nLink = new ItemLink(item.Database.Name, item.ID, linkField.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath); linkField.UpdateLink(nLink); var mediaUrl = global::Sitecore.Resources.Media.MediaManager.GetMediaUrl(media); linkField.Url = mediaUrl; } else throw new MapperException("No item with ID {0}. Can not update Link linkField".Formatted(newId)); } } break; case LinkType.External: linkField.LinkType = "external"; linkField.Url = link.Url; break; case LinkType.Anchor: linkField.LinkType = "anchor"; linkField.Url = link.Anchor; break; case LinkType.MailTo: linkField.LinkType = "mailto"; linkField.Url = link.Url; break; case LinkType.JavaScript: linkField.LinkType = "javascript"; linkField.Url = link.Url; break; } if (!link.Anchor.IsNullOrEmpty()) linkField.Anchor = link.Anchor; if (!link.Class.IsNullOrEmpty()) linkField.Class = link.Class; if (!link.Text.IsNullOrEmpty()) linkField.Text = link.Text; if (!link.Title.IsNullOrEmpty()) linkField.Title = link.Title; if (!link.Query.IsNullOrEmpty()) linkField.QueryString = HttpUtility.UrlEncode(link.Query); if (!link.Target.IsNullOrEmpty()) linkField.Target = link.Target; }
protected virtual string GetFriendlyFieldValue(string name, Item itemElement) { // to allow forcing fields rather than properties, allow prepending the name with # name = name.TrimStart('@'); var field = itemElement.Fields[name]; if (field != null) { switch (field.TypeKey) { case "date": case "datetime": return formatDateField(itemElement, field.ID); case "droplink": case "droptree": case "reference": case "grouped droplink": var lookupFld = (LookupField)field; if (lookupFld.TargetItem != null) { return lookupFld.TargetItem.Name; } break; case "checklist": case "multilist": case "treelist": case "treelistex": var multilistField = (MultilistField)field; var strBuilder = new StringBuilder(); foreach (var item in multilistField.GetItems()) { strBuilder.AppendFormat("{0}, ", item.Name); } return StringUtil.Clip(strBuilder.ToString().TrimEnd(',', ' '), this.MaxLength, true); break; case "link": case "general link": var lf = new LinkField(field); switch (lf.LinkType) { case "media": case "internal": if (lf.TargetItem != null) { return lf.TargetItem.Paths.ContentPath; } return lf.Value == string.Empty ? "[undefined]" : "[broken link] " + lf.Value; case "anchor": case "mailto": case "external": return lf.Url; default: return lf.Text; } default: return StringUtil.Clip(StringUtil.RemoveTags(field.Value), MaxLength, true); } } return String.Empty; }
/// <summary> /// Initializes a new instance of the <see cref="LinkProperty"/> class. /// </summary> /// <param name="field">The field to wrap.</param> public LinkProperty(Field field) : base(field) { this.linkField = field; }