/// <summary> /// Tries to get the URL for the MediaItem referenced in the given image field on the given item. /// </summary> /// <param name="fieldName">The name of the field that references the MediaItem. Note, this field name must reference an ImageField.</param> /// <param name="item">The item that contains the given field.</param> /// <param name="url">The URL for the MediaItem.</param> /// <returns>True if a URL could be returned for the MediaItem; otherwise, false.</returns> public static Boolean GetMediaImageFriendlyURL(string fieldName, Item item, out String url) { url = ""; if (string.IsNullOrEmpty(fieldName) || item == null) { return(false); } var rawField = item.Fields[fieldName]; var fieldIsValidAndHasContent = rawField != null && !string.IsNullOrEmpty(rawField.Value) && FieldTypeManager.GetField(rawField) is Sitecore.Data.Fields.ImageField; if (!fieldIsValidAndHasContent) { return(false); } Sitecore.Data.Fields.ImageField imageField = rawField; if (imageField.MediaItem == null) { return(false); } return(GetMediaURL(imageField.MediaItem, out url)); }
//public HtmlString DialBoxBGImage //{ // get // { // return new HtmlString(FieldRenderer.Render(InnerItem, "DialBoxBGImage")); // } //} //public string DialBoxRedirect //{ // get // { // Item linkItem = Sitecore.Context.Database.GetItem(InnerItem["CarouselLinkItem"]); // if (linkItem != null) // return LinkManager.GetItemUrl(linkItem); // return ""; // } //} private string GetImageUrl() { var currentItem = Sitecore.Context.Item; var imageUrl = string.Empty; Sitecore.Data.Fields.ImageField imageField = InnerItem.Fields["DialBoxBGImage"]; if (imageField?.MediaItem != null) { var image = new MediaItem(imageField.MediaItem); imageUrl = StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(image)); } return(imageUrl); }
public static string GetImageFieldUrl(Item currentItem, string imageFieldId) { var imageUrl = string.Empty; Sitecore.Data.Fields.ImageField imageField = currentItem.Fields[imageFieldId]; if (imageField?.MediaItem != null) { var image = new MediaItem(imageField.MediaItem); imageUrl = StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(image)); } return(imageUrl); }
private void updateImageField(string itemPath, string fieldname, Sitecore.Data.Fields.ImageField image) { var item = _db.GetItem(itemPath); using (new SecurityDisabler()) { Sitecore.Data.Fields.ImageField imageField = item.Fields[fieldname]; item.Editing.BeginEdit(); imageField.MediaID = image.MediaID; item.Editing.EndEdit(); } }
/// <summary> /// Takes in a fieldname and an item and checks the Size field, returning the value as a megabyte value /// </summary> /// <param name="fieldName">name of the field of the media item</param> /// <param name="item">the item that contains the field</param> /// <returns>returns the size value as a string in megabytes/gigabytes/kilobytes/bytes, appended with 'mb/gb/kb/b'</returns> public static string GetMediaSize(string fieldName, Item item) { if (item == null || string.IsNullOrEmpty(fieldName)) { return(string.Empty); } Sitecore.Data.Fields.ImageField image = item.Fields[fieldName]; if (image == null || image.MediaItem == null) { return(string.Empty); } return(GetMediaSize(image.MediaItem)); }
/// <summary> /// Retrieves the user friendly URL from a field on a specific item that contains a media item /// </summary> /// <param name="helper"></param> /// <param name="fieldName"></param> /// <param name="item"></param> /// <returns></returns> public static string SitecoreMediaUrl(this HtmlHelper helper, string fieldName, Item item) { if (item != null) { ImageField imgField = item.Fields[fieldName]; if (imgField != null) { MediaItem mediaItem = imgField.MediaItem; if (mediaItem != null) { return(Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem)); } } } return(string.Empty); }
/// <summary> /// Previous Years Snapshot Section /// </summary> /// <returns></returns> public ActionResult RenderPastYearSnapshotSection() { var currentItem = RenderingContext.Current.Rendering.Item; var dataSourceId = RenderingContext.CurrentOrNull.Rendering.DataSource; var dataSource = Sitecore.Context.Database.GetItem(dataSourceId); if (dataSource != null) { var previousyearinformation = dataSource.Fields["PreviousYearSnapshotTitle"]?.Value; Sitecore.Data.Fields.MultilistField multiselectField = dataSource.Fields["PreviousYearSnapshotList"]; Sitecore.Data.Items.Item[] items = multiselectField.GetItems(); if (items != null && items.Length > 0) { var listofsnapshot = new List <PreviousYearSnapshotDetails>(); for (int i = 0; i < items.Length; i++) { Sitecore.Data.Items.Item snapshotItem = items[i]; Sitecore.Data.Fields.ImageField field = items[i].Fields["PreviousYearImage"]; var snapshotdetail = new PreviousYearSnapshotDetails() { PreviousYearTitle = FieldRenderer.Render(snapshotItem, "PreviousYearTitle"), PreviousYear = FieldRenderer.Render(snapshotItem, "PreviousYear"), PreviousYearDescription = FieldRenderer.Render(snapshotItem, "PreviousYearDescription"), PreviousYearImage = MediaManager.GetMediaUrl(field.MediaItem) }; listofsnapshot.Add(snapshotdetail); } var returnviewmodel = new PastYearSnapshotViewModel() { PreviousYearSnapshotTitle = previousyearinformation, PreviousYearSnapshotList = listofsnapshot }; return(View("~/Views/PreviousYear/PreviousYear.cshtml", returnviewmodel)); } ; } return(View("~/Views/PreviousYear/PreviousYear.cshtml", null)); }
/// <summary> /// Judges Information Section /// </summary> /// <returns></returns> public ActionResult RenderJudgesInfoSection() { var currentItem = RenderingContext.Current.Rendering.Item; var dataSourceId = RenderingContext.CurrentOrNull.Rendering.DataSource; var dataSource = Sitecore.Context.Database.GetItem(dataSourceId); if (dataSource != null) { var judgeinformation = dataSource.Fields["JudgesInformation"]?.Value; Sitecore.Data.Fields.MultilistField multiselectField = dataSource.Fields["JudgesList"]; Sitecore.Data.Items.Item[] items = multiselectField.GetItems(); if (items != null && items.Length > 0) { var listofjudges = new List <JudgesDetails>(); for (int i = 0; i < items.Length; i++) { Sitecore.Data.Items.Item judgeItem = items[i]; Sitecore.Data.Fields.ImageField field = items[i].Fields["JudgesPic"]; var judgedetail = new JudgesDetails() { JudgesInfo = FieldRenderer.Render(judgeItem, "JudgesInfo"), JudgeName = FieldRenderer.Render(judgeItem, "JudgeName"), JudgesProfession = FieldRenderer.Render(judgeItem, "JudgesProfession"), JudgesPic = MediaManager.GetMediaUrl(field.MediaItem) }; listofjudges.Add(judgedetail); } var returnviewmodel = new JudgesViewModel() { JudgesList = listofjudges, JudgesInformation = judgeinformation }; return(View("~/Views/JudgesInformation/JudgesInformation.cshtml", returnviewmodel)); } ; } return(View("~/Views/JudgesInformation/JudgesInformation.cshtml", null)); }
private void Page_Load(object sender, EventArgs e) { try { Item currentItem = Sitecore.Context.Item; IEnumerable <Item> meetingItems = Sitecore.Context.Item.Axes.SelectItems("/sitecore/content/CJCC//*[@@templatename='Meeting']").Where(x => DateUtil.ParseDateTime(x["Meeting Date"], DateTime.MaxValue) <= DateTime.UtcNow.Date).OrderByDescending(x => x["Meeting Date"]); if (meetingItems != null && meetingItems.Any()) { rptMeetingDocuments.DataSource = meetingItems; rptMeetingDocuments.DataBind(); } Sitecore.Data.Fields.ImageField imgField = ((Sitecore.Data.Fields.ImageField)currentItem.Fields["Hero Image"]); if (imgField != null && imgField.MediaItem != null) { string heroBG = Sitecore.Resources.Media.MediaManager.GetMediaUrl(imgField.MediaItem); litHeroBG.Text = String.Format("<section class=\"purple overlay\" style=\"background-image: url('{0}')\">", heroBG); litHeroBGClose.Text = "</section>"; } else { litHeroBG.Text = "<section>"; litHeroBGClose.Text = "</section>"; } Item[] richTextItems = currentItem.Axes.SelectItems("descendant::*[@@templatename='Title with Rich Text']"); if (richTextItems != null && richTextItems.Length > 0) { rptRichText.DataSource = richTextItems; rptRichText.DataBind(); } fldPageTitle.Item = currentItem; } catch (Exception ex) { } }
private void Page_Load(object sender, EventArgs e) { Item currentItem = Sitecore.Context.Item; Item[] strategyItems = currentItem.Axes.SelectItems("descendant::*[@@templatename='Strategy with Icon']"); if (strategyItems != null && strategyItems.Length > 0) { rptStrategy.DataSource = strategyItems; rptStrategy.DataBind(); } Item[] richTextItems = currentItem.Axes.SelectItems("descendant::*[@@templatename='Title with Rich Text']"); if (richTextItems != null && richTextItems.Length > 0) { rptRichText.DataSource = richTextItems; rptRichText.DataBind(); } Sitecore.Data.Fields.ImageField imgField = ((Sitecore.Data.Fields.ImageField)currentItem.Fields["Hero Image"]); if (imgField != null && imgField.MediaItem != null) { string heroBG = Sitecore.Resources.Media.MediaManager.GetMediaUrl(imgField.MediaItem); litHeroBG.Text = String.Format("<section class=\"purple overlay\" style=\"background-image: url('{0}')\">", heroBG); litHeroBGClose.Text = "</section>"; } else { litHeroBG.Text = "<section>"; litHeroBGClose.Text = "</section>"; } fldPageTitle.Item = currentItem; }
public List <Item> indexSitecoreContent() { // ID blogTemplateId = new Sitecore.Data.ID("{48587868-4A19-48BB-8FC9-F1DD31CB6C8E}"); //var index = Sitecore.ContentSearch.ContentSearchManager.GetIndex("sitecore_master_index"); //List<Item> results = new List<Item>(); //using (Sitecore.ContentSearch.IProviderSearchContext context = index.CreateSearchContext()) //{ // //var searchResults = context.GetQueryable<SearchResultItem>().Where(x => x.Content.Contains("Sitecore")); // var searchResults = context.GetQueryable<SearchResultItem>().Take(10); // results = (List<Item>)searchResults; //} #region Indexing // Get the indexes files from the "lucene_Index" folder string[] filePaths = System.IO.Directory.GetFiles(_luceneDir); // Delete all the indexes from "lucene_Index" folder foreach (string filePath in filePaths) { File.Delete(filePath); } //Create Directory for Indexes //There are 2 options, FS or RAM //Step 1: Declare Index Store //Now we need Analyzer //An Analyzer builds TokenStreams, which analyze text. It thus represents a policy for extracting index terms from text. //In general, any analyzer in Lucene is tokenizer + stemmer + stop-words filter. //Tokenizer splits your text into chunks-For example, for phrase "I am very happy" it will produce list ["i", "am", "very", "happy"] // stemmer:-piece of code responsible for “normalizing” words to their common form (horses => horse, indexing => index, etc) //Stop words are the most frequent and almost useless words Analyzer analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30); //Need an Index Writer to write the output of Analysis to Index IndexWriter writer = new IndexWriter(_directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED); // Get the data to index for search Item ExternalLinksFolder = Sitecore.Context.Database.GetItem("{6BD289C4-A964-4915-A769-A79C897D1746}"); string htmlContent = string.Empty; // string[] ExternalLinksHtmlContent = new string[ExternalLinksFolder.Children.Count]; // string ExternalPageHtmlContent; int count = 0; Sitecore.Data.Fields.ImageField imageField = null; SitecoreFields.LinkField linkfield = null; string externalurl; // web page declaring var htmlWeb = new HtmlWeb(); HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument(); string webPageTitle; string webPageContent; // end declaring foreach (Item externalLinkItem in ExternalLinksFolder.Children) { Document doc = new Document(); linkfield = externalLinkItem.Fields["ExternalURL"]; externalurl = linkfield.Url; imageField = externalLinkItem.Fields["Image"]; // webpage Title field LargestImage largestImage = new LargestImage(); HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument(); htmlDocument = htmlWeb.Load(externalurl); webPageTitle = GetWebPageTitle(htmlDocument); webPageContent = GetPageContent(htmlDocument); largestImage = GetLargestWebPageSec(htmlDocument, externalurl); // image field if (largestImage.imgSrc == "") // populate image attributes from sitecore image field if there is no image found on the external web page { largestImage.imgSrc = Sitecore.Resources.Media.MediaManager.GetMediaUrl(imageField.MediaItem); largestImage.imgAlt = imageField.Alt; } if (webPageTitle == "") // populate title from sitecore if webpage has no title or h1 tags { webPageTitle = externalLinkItem.Fields["Title"].Value; } if (webPageContent == "") { webPageContent = externalLinkItem.Fields["PageContent"].Value; } // end image field doc.Add(new Field("External_WebPage_Content", webPageContent, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("External_WebPage_Title", webPageTitle, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("External_WebPage_Url", externalurl, Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field("External_WebPage_ImageSrc", largestImage.imgSrc, Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field("External_WebPage_ImageAlt", largestImage.imgAlt, Field.Store.YES, Field.Index.NOT_ANALYZED)); writer.AddDocument(doc); count++; } writer.Optimize(); writer.Commit(); writer.Dispose(); #endregion return(results); }
protected void rptDownloads_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.IsItem()) { Item dataItem = e.Item.DataItem as Item; FieldRenderer frTitle = e.FindControlAs <FieldRenderer>("frTitle"); HtmlGenericControl iconType = e.FindControlAs <HtmlGenericControl>("iconType"); HtmlGenericControl fileSize = e.FindControlAs <HtmlGenericControl>("fileSize"); Literal litFileSize = e.FindControlAs <Literal>("litFileSize"); HyperLink hypActionLink = e.FindControlAs <HyperLink>("hypActionLink"); HyperLink hypTitle = e.FindControlAs <HyperLink>("hypTitle"); LinkField lf = dataItem.Fields["Link"]; if (frTitle != null) { frTitle.Item = dataItem; } if (hypActionLink != null) { hypActionLink.Text = dataItem.Fields["Action Text"].ToString(); } string itemLink = string.Empty; if (dataItem.IsOfType(PDFToolkitResourceItem.TemplateId)) { iconType.Attributes.Add("class", "pdf"); itemLink = ResolveMediaURL(dataItem); hypActionLink.Attributes.Add("download", "download"); } else if (dataItem.IsOfType(VideoToolkitResourceItem.TemplateId)) { iconType.Attributes.Add("class", "video"); if (lf.TargetItem != null) { itemLink = LinkManager.GetItemUrl(lf.TargetItem); } } else if (dataItem.IsOfType(AudioToolkitResourceItem.TemplateId)) { iconType.Attributes.Add("class", "audio"); if (lf.TargetItem != null) { itemLink = LinkManager.GetItemUrl(lf.TargetItem); } } else if (dataItem.IsOfType(WordToolkitResourceItem.TemplateId)) { iconType.Attributes.Add("class", "word"); Sitecore.Data.Fields.ImageField field = dataItem.Fields["link"]; if (field != null) { MediaItem wordDoc = new MediaItem(field.MediaItem); itemLink = Sitecore.Resources.Media.MediaManager.GetMediaUrl(wordDoc); hypActionLink.Attributes.Add("download", "download"); litFileSize.Text = Math.Round((wordDoc.Size / 1000.0), 0).ToString() + "k"; } //itemLink = ResolveMediaURL(dataItem); } else if (dataItem.IsOfType(ArticleToolkitResourceItem.TemplateId)) { iconType.Attributes.Add("class", "article"); fileSize.Visible = false; //LinkField lf = dataItem.Fields["Link"]; itemLink = ResolveMediaURL(dataItem); } if (!dataItem.IsOfType(WordToolkitResourceItem.TemplateId)) { string fileSizeText = GetFileSize(dataItem); if (fileSizeText != "") { litFileSize.Text = fileSizeText; } } hypActionLink.NavigateUrl = hypTitle.NavigateUrl = itemLink; } }
private void Page_Load(object sender, EventArgs e) { // Put user code to initialize the page here try { Item currentItem = Sitecore.Context.Item; string strSchemaDescription = string.Empty; string strDescription = string.Empty; string strSchemaTitle = string.Empty; string strTitle = string.Empty; string strKeywords = string.Empty; string strSchemaImage = string.Empty; string strImage = string.Empty; string strSchemaURL = string.Empty; string strURL = string.Empty; string strSummary = string.Empty; string strType = string.Empty; string strSiteName = string.Empty; //Set default Titles and Images for fallbacks strTitle = string.Format("<meta property=\"og:title\" content=\"{0}\" />", "Healthy You, Healthy Hennepin"); strSchemaTitle = string.Format("<meta itemprop=\"name\" content=\"{0}\" />", "Healthy You, Healthy Hennepin"); strImage = string.Format("<meta property=\"og:image\" content=\"{0}\" />", "/hyhh-assets/images/hyhh-logo.png"); strSchemaImage = string.Format("<meta itemprop=\"image\" content=\"{0}\" />", "/hyhh-assets/images/hyhh-logo.png"); if (currentItem.Fields["Description"].Value != "") { string result = Regex.Replace(currentItem.Fields["Description"].Value, @"<(.|\n)*?>", string.Empty); strDescription = string.Format("<meta name=\"description\" content=\"{0}\" />", result); strSchemaDescription = string.Format("<meta itemprop=\"description\" content=\"{0}\" />", result); } if (currentItem.Fields["Keywords"].Value != "") { strKeywords = string.Format("<meta name=\"keywords\" content=\"{0}\" />", currentItem.Fields["Keywords"].Value); } if (currentItem.Fields["Rollup Image"].Value != "") { Sitecore.Data.Fields.ImageField imgField = ((Sitecore.Data.Fields.ImageField)currentItem.Fields["Rollup Image"]); string imgURL = Sitecore.Resources.Media.MediaManager.GetMediaUrl(imgField.MediaItem); strImage = string.Format("<meta property=\"og:image\" content=\"{0}\" />", imgURL); strSchemaImage = string.Format("<meta itemprop=\"image\" content=\"{0}\" />", imgURL); } if (currentItem.Fields["Title"].Value != "") { string result = Regex.Replace(currentItem.Fields["Title"].Value, @"<(.|\n)*?>", string.Empty); strTitle = string.Format("<meta property=\"og:title\" content=\"{0}\" />", result); strSchemaTitle = string.Format("<meta itemprop=\"name\" content=\"{0}\" />", result); } if (currentItem.Fields["Title"].Value != "") { strURL = string.Format("<meta property=\"og:url\" content=\"{0}\" />", Sitecore.Links.LinkManager.GetItemUrl(currentItem)); strSchemaURL = string.Format("<meta itemprop=\"url\" content=\"{0}\" />", Sitecore.Links.LinkManager.GetItemUrl(currentItem)); strType = string.Format("<meta property=\"og:type\" content=\"website\" />"); strSiteName = string.Format("<meta property=\"og:site_name\" content=\"Healthy You Healthy Hennepin\" />"); } if (currentItem.Fields["Rollup Summary"].Value != "") { string result = Regex.Replace(currentItem.Fields["Rollup Summary"].Value, @"<(.|\n)*?>", string.Empty); strSummary = string.Format("<meta property=\"og:description\" content=\"{0}\" />", result); } //set descriptions litDescription.Text = strDescription; litSchemaDescription.Text = strSchemaDescription; litOGDescription.Text = strSummary; //set URLs litSchemaURL.Text = strSchemaURL; //litOGURL.Text = strURL; //set Keywords litKeywords.Text = strKeywords; //set Titles litSchemaName.Text = strSchemaTitle; litOGTitle.Text = strTitle; //set Type litOGType.Text = strType; //set site name litOGSiteName.Text = strSiteName; //set images litOGImage.Text = strImage; litSchemaImage.Text = strSchemaImage; } catch (Exception ex) { Sitecore.Diagnostics.Log.Error("error metadata hyhhMetadata", ex, this); } }
private XmlDocument BuildSitemapItem(XmlDocument doc, Item item, Site site) { string text = HtmlEncode(this.GetItemUrl(item, false, site)); string str2 = HtmlEncode(item.Statistics.Updated.ToString("yyyy-MM-ddTHH:mm:sszzz")); XmlNode lastChild = doc.LastChild; XmlNode newChild = doc.CreateElement("url"); lastChild.AppendChild(newChild); //location XmlNode loc = doc.CreateElement("loc"); newChild.AppendChild(loc); loc.AppendChild(doc.CreateTextNode(text)); //last modified XmlNode modified = doc.CreateElement("lastmod"); newChild.AppendChild(modified); modified.AppendChild(doc.CreateTextNode(str2)); //change frequency XmlNode freq = doc.CreateElement("changefreq"); newChild.AppendChild(freq); freq.AppendChild(doc.CreateTextNode("monthly")); //priority XmlNode priority = doc.CreateElement("priority"); newChild.AppendChild(priority); if (item.ID.Equals(BusinessLogic.Helper.Constants.Home)) { priority.AppendChild(doc.CreateTextNode("1.0")); } else { priority.AppendChild(doc.CreateTextNode("0.5")); } //try to find any images List <String> images = new List <String>(); Sitecore.Data.Fields.TextField pagebody = item.Fields["pagebody"]; Sitecore.Data.Fields.ImageField personimage = item.Fields["picture"]; Sitecore.Data.Fields.ImageField campusimage = item.Fields["campusPhoto"]; if (pagebody != null) { HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument(); html.LoadHtml(pagebody.Value); //get images var links = html.DocumentNode.SelectNodes("//img"); if (links != null) { foreach (var link in links) { string imgUrl = link.Attributes["src"].Value; if (!string.IsNullOrEmpty(imgUrl)) { if (!images.Contains(imgUrl)) { images.Add(imgUrl); } } } } } if (personimage != null && personimage.MediaItem != null) { images.Add(Sitecore.Resources.Media.MediaManager.GetMediaUrl(personimage.MediaItem)); } if (campusimage != null && campusimage.MediaItem != null) { images.Add(Sitecore.Resources.Media.MediaManager.GetMediaUrl(campusimage.MediaItem)); } //add images to xml foreach (String image in images) { string src = HtmlEncode(GetUrl(image, site)); XmlNode img = doc.CreateNode(XmlNodeType.Element, "image", "image", nsImage); newChild.AppendChild(img); XmlNode imgSrc = doc.CreateNode(XmlNodeType.Element, "image", "loc", nsImage); img.AppendChild(imgSrc); imgSrc.AppendChild(doc.CreateTextNode(src)); } return(doc); }