public Models.Comment ShowComment(int id) { try { var result = new Models.Comment(); IContent doc = ApplicationContext.Services.ContentService.GetById(id); if (doc != null) { doc.SetValue("showComment", true); ApplicationContext.Services.ContentService.SaveAndPublishWithStatus(doc); if (doc.Ancestors().Any(x => x.ContentType.Alias == "CommentItem")) { foreach (IContent child in doc.Ancestors().Where(x => x.ContentType.Alias == "CommentItem")) { child.SetValue("showComment", true); child.SetValue("isSpam", false); ApplicationContext.Services.ContentService.SaveAndPublishWithStatus(child); } } result.Id = doc.Id; result.Name = doc.GetValue <string>("name"); result.Email = doc.GetValue <string>("email"); result.Content = doc.GetValue <string>("message"); result.IsAdmin = doc.GetValue <bool>("isBackOffice"); result.IsShow = doc.GetValue <bool>("showComment"); result.IsSpam = doc.GetValue <bool>("isSpam"); result.CreateDate = doc.CreateDate; } else { result.Name = "~notfound~"; } return(result); } catch (Exception e) { return(null); } }
private void AddOrUpdateLecture(IEnumerable <IContent> content, Func <IContent, bool> isActive) { IContent lectureContent = content.FirstOrDefault(x => x.ContentType.Alias == nameof(DocumentTypes.Lecture)); IContent moduleContent = content.FirstOrDefault(x => x.ContentType.Alias == nameof(DocumentTypes.Module)); if (lectureContent != null && lectureContent.HasIdentity) { ILecturesService lecturesService = DependencyResolver.Current.GetService(typeof(ILecturesService)) as ILecturesService; if (lecturesService == null) { throw new InvalidOperationException("LecturesService failed to instantiate"); } Lecture lecture = lecturesService.GetLectureByExternalId(lectureContent.Id); if (lecture == null) { lecture = new Lecture { ExternalId = lectureContent.Id, Title = lectureContent.Name }; } IContent courseParentNode = lectureContent.Ancestors().FirstOrDefault(x => x.ContentType.Alias == nameof(DocumentTypes.Course)); if (courseParentNode?.ContentType.Alias == nameof(DocumentTypes.Course)) { string courseId = (string)courseParentNode.Properties[(nameof(DocumentTypes.Course.CourseId))].Value; if (string.IsNullOrWhiteSpace(courseId)) { throw new ArgumentException($"Course with Id: {courseParentNode.Id} doesn't have a CourseId field present"); } lecture.CourseId = int.Parse(courseId); } lecture.IsActive = isActive(lectureContent); lecturesService.AddOrUpdate(lecture); } else if (moduleContent != null) { ILecturesService lecturesService = DependencyResolver.Current.GetService(typeof(ILecturesService)) as ILecturesService; if (lecturesService == null) { throw new InvalidOperationException("LecturesService failed to instantiate"); } bool isModuleActive = isActive(moduleContent); foreach (IContent lect in moduleContent.Descendants().Where(x => x.ContentType.Alias == nameof(DocumentTypes.Lecture))) { Lecture lecture = lecturesService.GetLectureByExternalId(lect.Id); lecture.IsActive = isModuleActive && isActive(lect); lecturesService.AddOrUpdate(lecture); } } }
public static IEnumerable <string> GetDomains(this IContent content) { var domainList = new List <string>(); var domains = Domain.GetDomainsById(content.Ancestors().Where(x => x.Level == 2).FirstOrDefault().Id); foreach (var domain in domains) { domainList.Add(domain.Name); } return(domainList); }
private void createDocumentTranslation(IContent content) { var contentService = ApplicationContext.Current.Services.ContentService; var relationService = ApplicationContext.Current.Services.RelationService; var parentItems = content.Ancestors(); var directParent = parentItems.LastOrDefault(); var translations = relationService.GetByParent(directParent, "translation"); if (translations.Count() > 0) { foreach (var translation in translations) { var copy = contentService.Copy(content, translation.ChildId, false); relationService.Relate(content, copy, "translation"); } } return; }
/// <summary> /// Gathers the information from each node to add to the Examine index. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event arguments containing information about the nodes to be gathered.</param> /// <param name="helper">The <see cref="UmbracoHelper"/> to help gather node data.</param> /// <param name="contentHelper">The <see cref="ContentHelper"/> to help gather stong typed data.</param> /// <param name="applicationContext"> /// The Umbraco <see cref="ApplicationContext"/> for the current application. /// </param> // ReSharper disable once UnusedParameter.Local private void GatheringNodeData(object sender, IndexingNodeDataEventArgs e, UmbracoHelper helper, ContentHelper contentHelper, ApplicationContext applicationContext) { IPublishedContent content = null; switch (e.IndexType) { case IndexTypes.Content: content = helper.TypedContent(e.NodeId); break; case IndexTypes.Media: content = helper.TypedMedia(e.NodeId); break; } if (content != null) { // Convert the property and use reflection to grab the output property value adding it to the merged property // collection for each configured language. Type doctype = contentHelper.GetRegisteredType(content.DocumentTypeAlias); if (doctype != null) { // Check to see if the type is searchable. If not, we want to break out. // If the interface is not implemented then we add that to the index since it is not explicitly ommited. if (typeof(ISearchable).IsAssignableFrom(doctype)) { // TODO: Ask Shannon about this. // Depending on timing using IPublishedContent and searching the parent can fail. // This sucks obviously since the ContentService is slow. IContent c = applicationContext.Services.ContentService.GetById(e.NodeId); if (c.Published && c.HasProperty(ZoombracoConstants.Content.ExcludeFromSearchResults) && c.GetValue <bool>(ZoombracoConstants.Content.ExcludeFromSearchResults)) { return; } if (c.Ancestors().Any(i => i.Published && i.HasProperty(ZoombracoConstants.Content.ExcludeFromSearchResults) && i.GetValue <bool>(ZoombracoConstants.Content.ExcludeFromSearchResults))) { return; } } // TODO: How much does calling this service cost? ILanguage[] languages = applicationContext.Services.LocalizationService.GetAllLanguages().ToArray(); StringBuilder categoryStringBuilder = new StringBuilder(); StringBuilder[] mergedDataStringBuilders = new StringBuilder[languages.Length]; for (int i = 0; i < mergedDataStringBuilders.Length; i++) { mergedDataStringBuilders[i] = new StringBuilder(); } // We cache the properties for to improve performance. PropertyInfo[] properties; PropertyCache.TryGetValue(doctype, out properties); if (properties == null) { properties = doctype.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(x => x.CanWrite && x.GetSetMethod() != null) .ToArray(); PropertyCache.TryAdd(doctype, properties); } // Loop through each peoperty and check if we should add it to the fields foreach (PropertyInfo property in properties) { UmbracoSearchMergedFieldAttribute attr = property.GetCustomAttribute <UmbracoSearchMergedFieldAttribute>(); if (attr == null) { continue; } // Get the correct identifier for the property. string key = !string.IsNullOrWhiteSpace(attr.ExamineKey) ? attr.ExamineKey : property.Name; // Look for any custom search resolvers to convert the information to a useful search result. ZoombracoSearchResolverAttribute[] resolverAttributes = property.GetCustomAttributes <ZoombracoSearchResolverAttribute>().ToArray(); foreach (KeyValuePair <string, string> field in e.Fields) { if (!key.InvariantEquals(field.Key)) { continue; } // Combine property values for each language. for (int i = 0; i < languages.Length; i++) { if (resolverAttributes.Any()) { // Resolve each value and append to the language stringbuilder. foreach (ZoombracoSearchResolverAttribute attribute in resolverAttributes) { string value = attribute.ResolveValue(content, property, field.Key, field.Value, languages[i].CultureInfo); if (!string.IsNullOrWhiteSpace(value)) { mergedDataStringBuilders[i].AppendFormat(" {0} ", helper.StripHtml(value, null)); } } } else { if (!string.IsNullOrWhiteSpace(field.Value)) { mergedDataStringBuilders[i].AppendFormat("{0} ", helper.StripHtml(field.Value, null)); } } } // Jump out early break; } } // Combine categories. UmbracoSearchCategoryAttribute categoryAttribute = doctype.GetCustomAttribute <UmbracoSearchCategoryAttribute>(); if (categoryAttribute != null) { if (categoryAttribute.Categories.Any()) { foreach (string category in categoryAttribute.Categories) { categoryStringBuilder.AppendFormat("{0} ", category); } } } // Now add the site, categories, and merged data. e.Fields.Add(ZoombracoConstants.Search.SiteField, e.Fields["path"].Replace(",", " ")); e.Fields[ZoombracoConstants.Search.CategoryField] = categoryStringBuilder.ToString().Trim(); for (int i = 0; i < languages.Length; i++) { e.Fields[string.Format(ZoombracoConstants.Search.MergedDataFieldTemplate, languages[i].CultureInfo.Name)] = mergedDataStringBuilders[i].ToString().Trim(); } } } }
/// <summary> /// Maps the generic tab with custom properties for content /// </summary> /// <param name="content"></param> /// <param name="display"></param> /// <param name="dataTypeService"></param> /// <param name="localizedText"></param> /// <param name="contentTypeService"></param> private static void AfterMap(IContent content, ContentItemDisplay display, IDataTypeService dataTypeService, ILocalizedTextService localizedText, IContentTypeService contentTypeService) { //map the IsChildOfListView (this is actually if it is a descendant of a list view!) //TODO: Fix this shorthand .Ancestors() lookup, at least have an overload to use the current if (content.HasIdentity) { var ancesctorListView = content.Ancestors().FirstOrDefault(x => x.ContentType.IsContainer); display.IsChildOfListView = ancesctorListView != null; } else { //it's new so it doesn't have a path, so we need to look this up by it's parent + ancestors var parent = content.Parent(); if (parent == null) { display.IsChildOfListView = false; } else if (parent.ContentType.IsContainer) { display.IsChildOfListView = true; } else { var ancesctorListView = parent.Ancestors().FirstOrDefault(x => x.ContentType.IsContainer); display.IsChildOfListView = ancesctorListView != null; } } //map the tree node url if (HttpContext.Current != null) { var urlHelper = new UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData())); var url = urlHelper.GetUmbracoApiService <ContentTreeController>(controller => controller.GetTreeNode(display.Id.ToString(), null)); display.TreeNodeUrl = url; } //fill in the template config to be passed to the template drop down. var templateItemConfig = new Dictionary <string, string> { { "", "Choose..." } }; foreach (var t in content.ContentType.AllowedTemplates .Where(t => t.Alias.IsNullOrWhiteSpace() == false && t.Name.IsNullOrWhiteSpace() == false)) { templateItemConfig.Add(t.Alias, t.Name); } if (content.ContentType.IsContainer) { TabsAndPropertiesResolver.AddListView(display, "content", dataTypeService); } var properties = new List <ContentPropertyDisplay> { new ContentPropertyDisplay { Alias = string.Format("{0}releasedate", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = localizedText.Localize("content/releaseDate"), Value = display.ReleaseDate.HasValue ? display.ReleaseDate.Value.ToIsoString() : null, View = "datepicker" //TODO: Hard coding this because the templatepicker doesn't necessarily need to be a resolvable (real) property editor }, new ContentPropertyDisplay { Alias = string.Format("{0}expiredate", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = localizedText.Localize("content/unpublishDate"), Value = display.ExpireDate.HasValue ? display.ExpireDate.Value.ToIsoString() : null, View = "datepicker" //TODO: Hard coding this because the templatepicker doesn't necessarily need to be a resolvable (real) property editor }, new ContentPropertyDisplay { Alias = string.Format("{0}template", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = "Template", //TODO: localize this? Value = display.TemplateAlias, View = "dropdown", //TODO: Hard coding until we make a real dropdown property editor to lookup Config = new Dictionary <string, object> { { "items", templateItemConfig } } }, new ContentPropertyDisplay { Alias = string.Format("{0}urls", Constants.PropertyEditors.InternalGenericPropertiesPrefix), Label = localizedText.Localize("content/urls"), Value = string.Join(",", display.Urls), View = "urllist" //TODO: Hard coding this because the templatepicker doesn't necessarily need to be a resolvable (real) property editor } }; TabsAndPropertiesResolver.MapGenericProperties(content, display, properties.ToArray(), genericProperties => { //TODO: This would be much nicer with the IUmbracoContextAccessor so we don't use singletons //If this is a web request and there's a user signed in and the // user has access to the settings section, we will if (HttpContext.Current != null && UmbracoContext.Current != null && UmbracoContext.Current.Security.CurrentUser != null && UmbracoContext.Current.Security.CurrentUser.AllowedSections.Any(x => x.Equals(Constants.Applications.Settings))) { var currentDocumentType = contentTypeService.GetContentType(display.ContentTypeAlias); var currentDocumentTypeName = currentDocumentType == null ? string.Empty : currentDocumentType.Name; var currentDocumentTypeId = currentDocumentType == null ? string.Empty : currentDocumentType.Id.ToString(CultureInfo.InvariantCulture); //TODO: Hard coding this is not good var docTypeLink = string.Format("#/settings/framed/settings%252FeditNodeTypeNew.aspx%253Fid%253D{0}", currentDocumentTypeId); //Replace the doc type property var docTypeProp = genericProperties.First(x => x.Alias == string.Format("{0}doctype", Constants.PropertyEditors.InternalGenericPropertiesPrefix)); docTypeProp.Value = new List <object> { new { linkText = currentDocumentTypeName, url = docTypeLink, target = "_self", icon = "icon-item-arrangement" } }; //TODO: Hard coding this because the templatepicker doesn't necessarily need to be a resolvable (real) property editor docTypeProp.View = "urllist"; } }); }