Beispiel #1
0
        /// <summary>
        /// Constructor for creating a Content object
        /// </summary>
        /// <param name="name">Name of the content</param>
        /// <param name="parent">Parent <see cref="IContent"/> object</param>
        /// <param name="contentType">ContentType for the current Content object</param>
        /// <param name="properties">Collection of properties</param>
		public Content(string name, IContent parent, IContentType contentType, PropertyCollection properties)
			: base(name, parent, contentType, properties)
		{
			Mandate.ParameterNotNull(contentType, "contentType");

			_contentType = contentType;
		}
        private static string DiscPath(IContent content, IEnumerable<IContent> allContent)
        {
            var pathComponents = content.Path.Split(',').Select(int.Parse).ToList();

            var pathArray = new List<string>();

            foreach (var pathComponentId in pathComponents.Where(x => x > -1))
            {
                var pathComponentContent = allContent.FirstOrDefault(x => x.Id == pathComponentId);

                if (pathComponentContent != null)
                {
                    var name = pathComponentContent.Name;
                    string invalid = new string(Path.GetInvalidPathChars());

                    foreach (char c in invalid)
                        name = name.Replace(c.ToString(), "-");
                    
                    pathArray.Add(name);

                }
            }

            return "/" + string.Join("/", pathArray);
        }
        public void GetMenu(IContent menu, NavigationBuilder builder) {
            var menuParts = _contentManager
                .Query<MenuPart, MenuPartRecord>()
                .Where(x => x.MenuId == menu.Id)
                .WithQueryHints(new QueryHints().ExpandRecords<MenuItemPartRecord>())
                .List();

            foreach (var menuPart in menuParts) {
                if (menuPart != null) {
                    var part = menuPart;

                    string culture = null;
                    // fetch the culture of the content menu item, if any
                    var localized = part.As<ILocalizableAspect>();
                    if (localized != null) {
                        culture = localized.Culture;
                    }
                    else {
                        // fetch the culture of the content menu item, if any
                        var contentMenuItemPart = part.As<ContentMenuItemPart>();
                        if (contentMenuItemPart != null) {
                            localized = contentMenuItemPart.Content.As<ILocalizableAspect>();
                            if (localized != null) {
                                culture = localized.Culture;
                            }
                        }
                    }

                    if (part.Is<MenuItemPart>())
                        builder.Add(new LocalizedString(HttpUtility.HtmlEncode(part.MenuText)), part.MenuPosition, item => item.Url(part.As<MenuItemPart>().Url).Content(part).Culture(culture));
                    else
                        builder.Add(new LocalizedString(HttpUtility.HtmlEncode(part.MenuText)), part.MenuPosition, item => item.Action(_contentManager.GetItemMetadata(part.ContentItem).DisplayRouteValues).Content(part).Culture(culture));
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <b>PagesController</b> class.
 /// </summary>
 /// <param name="structureInfo">The structure info.</param>
 /// <param name="currentPage">The current page.</param>
 /// <param name="session">The session.</param>
 /// <param name="content">The content.</param>
 public PagesController(IStructureInfo structureInfo, IPageModel currentPage, IDocumentSession session, IContent content)
 {
     _structureInfo = structureInfo;
     _currentPage = currentPage;
     _session = session;
     _content = content;
 }
Beispiel #5
0
        public IEnumerable<IImpulse> ListImpulses(IContent content, string displayType, object data = null)
        {
            var impulses = new List<ImpulseDisplayContext>();
            foreach (var impulse in GetDescriptors().Values) {

                if (!CheckDescriptor(impulse, content, data)) {
                    continue;
                }
                int? versionId = null;
                if (content.ContentItem.VersionRecord != null) versionId = content.ContentItem.VersionRecord.Id;
                var display = new ImpulseDisplayContext(impulse) {
                    Content = content,
                    DisplayType = displayType,
                    Data = data,
                    HrefRoute = new RouteValueDictionary(new {
                        action = "Actuate",
                        controller = "Impulse",
                        area = "Downplay.Mechanics",
                        name = impulse.Name,
                        returnUrl = Services.WorkContext.HttpContext.Request.RawUrl,
                        contentId = content.Id,
                        contentVersionId = versionId
                    })
                };
                                
                foreach (var e in impulse.DisplayingHandlers) {
                    e(display);
                }
                impulses.Add(display);

            }
            return impulses;
        }
Beispiel #6
0
        public IIndexResponse Index(IContent content)
        {
            try {
                var response = Client.Index(content, x => x.
                    Index(IndexResolver.GetIndex()).
                    Id(content.ContentLink.ID)
                );
                var onIndexed = content as IOnIndexed;
                if(onIndexed != null) onIndexed.OnIndexed();

                if (response.IsValid == false) throw new IndexException {
                    ServerError = response.ServerError,
                    RequestInformation = response.RequestInformation
                };
                Logger.WriteToLog($"Indexed content: Name={content.Name} Id={content.ContentLink.ID} Type={content.GetOriginalType().Name}. Elasticsearch response: Created={response.Created} Version={response.Version} Id={response.Id} Type={response.Type}");
                return response;
            }
            catch (IndexException exception) {
                Logger.WriteToLog($"Indexing content failed: Name={content.Name} Id={content.ContentLink.ID} Type={content.GetOriginalType().Name} Exception details: Request={Encoding.UTF8.GetString(exception.RequestInformation.Request)} Response={Encoding.UTF8.GetString(exception.RequestInformation.ResponseRaw)}"  ,Level.Error,exception);
            }
            catch (Exception exception) {
                Logger.WriteToLog("Unknown exception occured during indexing of content", Level.Error, exception);
            }
            return null;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="UmbracoDataMappingContext"/> class.
 /// </summary>
 /// <param name="obj">The obj.</param>
 /// <param name="content">The content.</param>
 /// <param name="service">The service.</param>
 public UmbracoDataMappingContext(object obj, IContent content, IUmbracoService service, bool publishedOnly)
     : base(obj)
 {
     Content = content;
     Service = service;
     PublishedOnly = publishedOnly;
 }
        public Task Write(IContent content, Stream outputStream)
        {
            if (content.Model != null)
            {
                object output;

                var enumerable = content.Model as IEnumerable<object>;
                if (enumerable != null)
                {
                    output = ProcessList(enumerable.ToList());
                }
                else
                {
                    output = ProcessContent(content);
                }
                byte[] buffer;
                using (var writer = new StringWriter())
                {
                    var dataWriterSettings = new DataWriterSettings(new MonoCompatResolverStrategy(),
                                                                    new Iso8601DateFilter());

                    new JsonWriter(dataWriterSettings).Write(output, writer);
                    buffer = Encoding.Default.GetBytes(writer.ToString());
                }
                return outputStream.WriteAsync(buffer, 0, buffer.Length);
            }

            return TaskHelper.Completed();
        }
        public Task Write(IContent content, Stream outputStream)
        {
            if (content.Model != null)
            {
                var enumerable = content.Model as IEnumerable<object>;
                if (enumerable != null)
                {
                    WriteList(outputStream, enumerable);
                }
                else
                {
                    var links = content.Links.ToList();
                    if (links.Count == 0)
                    {
                        new DataContractSerializer(content.Model.GetType()).WriteObject(outputStream, content.Model);
                    }
                    else
                    {
                        WriteWithLinks(content, outputStream, links);
                    }
                }
            }

            return TaskHelper.Completed();
        }
        public ContentDocument(IDataTypeService service, IContent content)
            : this()
        {
            Id = content.Id;
            ContentTypeId = content.ContentTypeId;
            ContentType = content.ContentType.Name;
            Name = content.Name;
            ParentId = content.ParentId;
            Level = content.Level;
            Path = content.Path;

            foreach (var propInfo in content.PropertyTypes.OrderBy(n => n.SortOrder))
            {

                var p = new Property
                {
                    Name = propInfo.Name,
                    Alias = propInfo.Alias,
                    Description = propInfo.Description,
                    Required = propInfo.Mandatory,
                    Validation = propInfo.ValidationRegExp,
                    DataType = service.GetDataTypeDefinitionById(propInfo.DataTypeDefinitionId).Name,
                    Value = (content.Properties.SingleOrDefault(n => n.Alias == propInfo.Alias).Value ?? string.Empty).ToString()
                };
                Properties.Add(p);
            }
        }
        public RuntimeContentModel Serialise(IContent content)
        {
            var publishedContent = _umbracoHelper.TypedContent(content.Id);

            if (publishedContent == null)
                return null;     

            var runtimeContent = Mapper.Map<RuntimeContentModel>(publishedContent);

            runtimeContent.Url = RemovePortFromUrl(publishedContent.UrlWithDomain());
            runtimeContent.RelativeUrl = publishedContent.Url;
            runtimeContent.CacheTime = null;

            runtimeContent.Type = publishedContent.DocumentTypeAlias;

            runtimeContent.Template = publishedContent.GetTemplateAlias();

            runtimeContent.Content = new Dictionary<string, object>();

            foreach (var property in content.Properties)
            {
                if (!runtimeContent.Content.ContainsKey(property.Alias))
                    runtimeContent.Content.Add(property.Alias, property.Value);
            }

            foreach (var contentParser in _contentParsers)
            {
                runtimeContent = contentParser.ParseContent(runtimeContent);
            }
            
            RuntimeContext.Instance.ContentService.AddContent(runtimeContent);
            return runtimeContent;
        }
 protected virtual void SetupModel(FilterOptionFormModel model, string q, string sort, string facets, IContent content)
 {
     EnsurePage(model);
     EnsureQ(model, q);
     EnsureSort(model, sort);
     EnsureFacets(model, facets, content);
 }
 public string Slugify(IContent content)
 {
     var metadata = content.ContentItem.ContentManager.GetItemMetadata(content);
     if (metadata == null) return null;
     var title = metadata.DisplayText.Trim();
     return Slugify(new FillSlugContext(content,title));
 }
        public Task Write(IContent content, Stream outputStream)
        {
            if (content.Model != null)
            {
                object output;

                var enumerable = content.Model as IEnumerable<object>;
                if (enumerable != null)
                {
                    output = ProcessList(enumerable);
                }
                else
                {
                    output = ProcessContent(content);
                }
                byte[] buffer;
                using (var writer = new StringWriter())
                {
                    new JsonWriter().Write(output, writer);
                    buffer = Encoding.Default.GetBytes(writer.ToString());
                }
                return outputStream.WriteAsync(buffer, 0, buffer.Length);
            }

            return TaskHelper.Completed();
        }
Beispiel #15
0
 public ItemInspector(IContent item, ContentItemMetadata metadata) {
     _item = item;
     _metadata = metadata;
     _common = item.Get<ICommonAspect>();
     _routable = item.Get<RoutableAspect>();
     _body = item.Get<BodyAspect>();
 }
        public static int IndexContentPage(IContent content)
        {
            // Does this type have any CategoryAssignment properties?
            if (!HasCategoryAssignments(content))
            {
                return 0;
            }

            var baseType = content.GetType().BaseType;

            var contentRef = content.ContentLink.ToReferenceWithoutVersion();

            var categoryRepo = ServiceLocator.Current.GetInstance<ICategoryRepository>();
            categoryRepo.DeleteAssignmentsByContent(contentRef);

            var assignmentsAdded = 0;
            foreach (var propertyName in CategoryAssignmentProperties[baseType])
            {
                var propertyData = content.Property[propertyName].Value;
                if(propertyData == null)
                {
                    continue;
                }
                foreach (var value in (IEnumerable<ContentReference>)propertyData)
                {
                    assignmentsAdded++;
                    categoryRepo.AddAssignment(contentRef, value, propertyName);
                }
            }

            return assignmentsAdded;
        }
Beispiel #17
0
 protected override void ExecuteSync(IContent content, Index index, object parameter)
 {
     var value = content.Retrieve(index);
     var collectionDescriptor = (CollectionDescriptor)TypeDescriptorFactory.Default.Find(value.GetType());
     object itemToAdd = null;
     // TODO: Find a better solution for ContentSerializerAttribute that doesn't require to reference Core.Serialization (and unreference this assembly)
     if (collectionDescriptor.ElementType.IsAbstract || collectionDescriptor.ElementType.IsNullable() || collectionDescriptor.ElementType.GetCustomAttributes(typeof(ContentSerializerAttribute), true).Any())
     {
         // If the parameter is a type instead of an instance, try to construct an instance of this type
         var type = parameter as Type;
         if (type?.GetConstructor(Type.EmptyTypes) != null)
             itemToAdd = Activator.CreateInstance(type);
     }
     else if (collectionDescriptor.ElementType == typeof(string))
     {
         itemToAdd = parameter ?? "";
     }
     else
     {
         itemToAdd = parameter ?? ObjectFactory.NewInstance(collectionDescriptor.ElementType);
     }
     if (index.IsEmpty)
     {
         content.Add(itemToAdd);
     }
     else
     {
         // Handle collections in collections
         // TODO: this is not working on the observable node side
         var collectionNode = content.Reference.AsEnumerable[index].TargetNode;
         collectionNode.Content.Add(itemToAdd);
     }
 }
Beispiel #18
0
        public async Task<dynamic> BuildEditorAsync(IContent content, string groupId)
        {
            if (content == null || content.ContentItem == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(content.ContentItem.ContentType);

            JToken stereotype;
            if (!contentTypeDefinition.Settings.TryGetValue("Stereotype", out stereotype))
            {
                stereotype = "Content";
            }

            var actualShapeType = stereotype + "_Edit";

            dynamic itemShape = CreateContentShape(actualShapeType);
            itemShape.ContentItem = content.ContentItem;

            // adding an alternate for [Stereotype]_Edit__[ContentType] e.g. Content-Menu.Edit
            ((IShape)itemShape).Metadata.Alternates.Add(actualShapeType + "__" + content.ContentItem.ContentType);

            var context = new UpdateEditorContext(itemShape, content, groupId, _shapeFactory);
            await BindPlacementAsync(context, null, stereotype.Value<string>());

            await _handlers.InvokeAsync(handler => handler.BuildEditorAsync(context), Logger);


            return context.Shape;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ContentChangeEventArgs"/> class.
 /// </summary>
 /// <param name="content">The content that has changed.</param>
 /// <param name="index">The index where the change occurred, if applicable. <c>null</c> otherwise.</param>
 /// <param name="oldValue">The old value of the content.</param>
 /// <param name="newValue">The new value of the content.</param>
 public ContentChangeEventArgs(IContent content, object index, object oldValue, object newValue)
 {
     Content = content;
     Index = index;
     OldValue = oldValue;
     NewValue = newValue;
 }
        private SyndicationItem CreateSyndicationItem(IContent content)
        {
            var changeTrackable = content as IChangeTrackable;
            var changed = DateTime.Now;
            var changedby = string.Empty;

            if (changeTrackable != null)
            {
                changed = changeTrackable.Saved;
                changedby = changeTrackable.ChangedBy;
            }

            var item = new SyndicationItem
            {
                Title = new TextSyndicationContent(content.Name),
                Summary = new TextSyndicationContent(FeedDescriptionProvider.ItemDescripton(content)),
                PublishDate = changed,
            };

            foreach (var contentCategory in ContentCategoryLoader.GetContentCategories(content))
            {
                item.Categories.Add(new SyndicationCategory(contentCategory));
            }         

            var mimeType = GetMimeType(content);
            Uri url = GetItemUrl(content);

            item.Content = new UrlSyndicationContent(url, mimeType);
            item.AddPermalink(url);
            item.Authors.Add(new SyndicationPerson(string.Empty, changedby, string.Empty));

            return item;
        }
Beispiel #21
0
        public async Task<dynamic> BuildDisplayAsync(IContent content, string displayType, string groupId)
        {
            if(content == null || content.ContentItem == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(content.ContentItem.ContentType);

            JToken stereotype;
            if (!contentTypeDefinition.Settings.TryGetValue("Stereotype", out stereotype))
            {
                stereotype = "Content";
            }

            var actualShapeType = stereotype.Value<string>();
            var actualDisplayType = string.IsNullOrWhiteSpace(displayType) ? "Detail" : displayType;

            dynamic itemShape = CreateContentShape(actualShapeType);
            itemShape.ContentItem = content.ContentItem;
            itemShape.Metadata.DisplayType = actualDisplayType;

            var context = new BuildDisplayContext(itemShape, content, actualDisplayType, groupId, _shapeFactory);
            context.Layout = _layoutAccessor.GetLayout();

            await BindPlacementAsync(context, actualDisplayType, stereotype.Value<string>());

            await _handlers.InvokeAsync(handler => handler.BuildDisplayAsync(context), Logger);
            return context.Shape;
        }
 protected BuildShapeContext(IShape shape, IContent content, string groupId, IShapeFactory shapeFactory) {
     Shape = shape;
     ContentItem = content.ContentItem;
     New = shapeFactory;
     GroupId = groupId;
     FindPlacement = (partType, differentiator, defaultLocation) => new PlacementInfo {Location = defaultLocation, Source = String.Empty};
 }
Beispiel #23
0
        void ILocalizationService.SetContentCulture(IContent content, string culture) {
            var localized = content.As<LocalizationPart>();
            if (localized == null || localized.MasterContentItem == null)
                return;

            localized.Culture = _cultureManager.GetCultureByName(culture);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ContentValueChangedActionItem"/> class.
 /// </summary>
 /// <param name="name">The name of this action item.</param>
 /// <param name="content">The <see cref="IContent"/> instance that has changed.</param>
 /// <param name="index">The index of the change if the change occurred on an item of a collection. <c>null</c> otherwise.</param>
 /// <param name="previousValue">The previous value of the content (or the item if the change occurred on an item of a collection).</param>
 /// <param name="dirtiables">The dirtiable objects associated to this action item.</param>
 public ContentValueChangedActionItem(string name, IContent content, object index, object previousValue, IEnumerable<IDirtiable> dirtiables)
     : base(name, dirtiables)
 {
     this.Content = content;
     PreviousValue = previousValue;
     Index = index;
 }
        public void SetupViewModel(FrontendContext frontendContext, IContent node, NodeViewModel viewModel)
        {
            if (node.ContentItem.ContentType != "WikipediaPage") return;

            viewModel.name = node.As<ITitleAspect>().Title;
            viewModel.data["url"] = node.As<WikipediaPagePart>().Url;
        }
Beispiel #26
0
 public UpdateEditorContext(IShape model, IContent content, IUpdateModel updater, string groupInfoId, IShapeFactory shapeFactory, ShapeTable shapeTable, string path)
     : base(model, content, groupInfoId, shapeFactory) {
     
     ShapeTable = shapeTable;
     Updater = updater;
     Path = path;
 }
        /// <summary>
        /// Generate the json output for the page.
        /// </summary>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GenerateJson(IContent page)
        {
            string json;

            List<KeyValuePair<string, string>> propertyValues = page.GetPropertyValues();

            StringBuilder stringBuilder = new StringBuilder();

            using (StringWriter sw = new StringWriter(stringBuilder, CultureInfo.InvariantCulture))
            {
                JsonWriter jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented };

                jsonWriter.WriteStartObject();

                jsonWriter.WritePropertyName(page.Name);

                jsonWriter.WriteStartObject();

                foreach (KeyValuePair<string, string> content in propertyValues)
                {
                    jsonWriter.WritePropertyName(content.Key);
                    jsonWriter.WriteValue(TextIndexer.StripHtml(content.Value, content.Value.Length));
                }

                jsonWriter.WriteEndObject();

                jsonWriter.WriteEndObject();

                json = sw.ToString();
            }

            return json;
        }
        /// <summary>
        /// The generate xml.
        /// </summary>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GenerateXml(IContent page)
        {
            if (page == null)
            {
                return string.Empty;
            }

            XDocument xDocument = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new object[0]);

            XElement xElement = new XElement("content");
            xElement.SetAttributeValue("name", XmlConvert.EncodeName(page.Name));

            List<KeyValuePair<string, string>> propertyValues = page.GetPropertyValues();

            foreach (KeyValuePair<string, string> content in propertyValues)
            {
                XElement xElement3 = new XElement(XmlConvert.EncodeName(content.Key));
                xElement3.SetValue(TextIndexer.StripHtml(content.Value, content.Value.Length));
                xElement.Add(xElement3);
            }

            xDocument.Add(xElement);

            return xDocument.ToString();
        }
Beispiel #29
0
        /// <summary>
        /// Gets the markup for the tag based upon the passed in parameters.
        /// </summary>
        /// <param name="currentPage">The current page.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns></returns>
        public override string GetMarkup(IContent currentPage, IDictionary<string, string> parameters)
        {
            var email = parameters["email"];
            var text = email;

            if (parameters.ContainsKey("subject"))
                email += ((email.IndexOf("?", StringComparison.InvariantCulture) == -1) ? "?" : "&") + "subject=" + parameters["subject"];

            if (parameters.ContainsKey("body"))
                email += ((email.IndexOf("?", StringComparison.InvariantCulture) == -1) ? "?" : "&") + "body=" + parameters["body"];

            var sb = new StringBuilder();
            sb.AppendFormat("<a href=\"mailto:{0}\"", email); // TODO: HTML encode

            if (parameters.ContainsKey("title"))
                sb.AppendFormat(" title=\"{0}\"", parameters["title"]);

            if (parameters.ContainsKey("class"))
                sb.AppendFormat(" class=\"{0}\"", parameters["class"]);

            sb.Append(">");
            sb.Append(parameters.ContainsKey("text")
                ? parameters["text"]
                : text);

            sb.Append("</a>");

            return sb.ToString();
        }
        private static JObject ProcessContent(IContent content, JsonSerializer serializer)
        {
            var links = content.Links.ToList();

            JObject jo;

            var list = content.Model as IEnumerable;
            if (list != null)
            {
                jo = new JObject();
                var array = new JArray();
                jo["collection"] = array;
                foreach (var o in list)
                {
                    var jitem = JObject.FromObject(o, serializer);
                    jitem.Add("_links", CreateHalLinks(LinkHelper.GetLinksForModel(o), serializer));
                    array.Add(jitem);
                }
            }
            else
            {
                jo = JObject.FromObject(content.Model, serializer);
            }

            if (links.Count > 0)
            {
                jo["_links"] = CreateHalLinks(links, serializer);
            }
            return jo;
        }
Beispiel #31
0
        internal static List <FieldWithValue> GetAllFieldsForDisplay(FormModel model, IContent document)
        {
            var allFields = model.AllValueFields().ToList();

            // show logged IPs?
            if (ContentHelper.IpDisplayEnabled(document) && ContentHelper.IpLoggingEnabled(document))
            {
                // IPs are being logged, add a single line text field to retrieve IPs as a string
                allFields.Add(new TextBoxField {
                    Name = "IP", FormSafeName = "_ip"
                });
            }
            return(allFields);
        }
Beispiel #32
0
 public void Insert(int index, IContent item)
 {
     ValidateItemNotInUse(item as Content);
     this.ContentInsertBefore(item as Content, index);
 }
Beispiel #33
0
 public void Add(IContent item)
 {
     ValidateItemNotInUse(item as Content);
     this.ContentAppend(item as Content);
 }
Beispiel #34
0
 public void Set(int index, IContent item)
 {
     ValidateItemNotInUse(item as Content);
     this.ContentSet(item as Content, index);
 }
Beispiel #35
0
        public virtual List <ContentInspectorViewModel.ContentAreaItemViewModel> GetContentAreaItems(int level, List <ContentReference> parentIds, ContentType contentType, IContent content)
        {
            var contentAreaItemViewModels = new List <ContentInspectorViewModel.ContentAreaItemViewModel>();

            foreach (var prop in contentType.PropertyDefinitions.Where(x => x.Type.Name == "ContentArea"))
            {
                var nestedContentArea = content.Property[prop.Name] as PropertyContentArea;
                if (nestedContentArea?.Value is ContentArea && (nestedContentArea.Value as ContentArea).Items != null)
                {
                    var contentAreaViewModel = new ContentInspectorViewModel.ContentAreaItemViewModel
                    {
                        Name             = prop.Name,
                        ContentAreaItems = new List <ContentInspectorViewModel>()
                    };
                    var contentArea = (nestedContentArea.Value as ContentArea);
                    for (int i = 0; i < (nestedContentArea.Value as ContentArea).Count; i++)
                    {
                        var contentAreaItem      = contentArea.Items[i];
                        var internalFormat       = contentArea.Fragments[i].InternalFormat;
                        var visitorGroups        = GetVisitorGroupNames(internalFormat);
                        var contentAreaItemModel = CreateModel(contentAreaItem.ContentLink,
                                                               visitorGroups, contentAreaItem.ContentGroup, level, new List <ContentReference>(parentIds));
                        if (contentAreaItemModel != null)
                        {
                            contentAreaViewModel.ContentAreaItems.Add(contentAreaItemModel);
                        }
                    }
                    contentAreaItemViewModels.Add(contentAreaViewModel);
                }
            }
            return(contentAreaItemViewModels);
        }
Beispiel #36
0
        public virtual ContentInspectorViewModel.InspectorContentViewModel CreateInspectorContentViewModel(IContent content)
        {
            var versionAble = content as IVersionable;
            var currentItem = new ContentInspectorViewModel.InspectorContentViewModel()
            {
                Name                 = content.Name,
                IsDeleted            = content.IsDeleted,
                Id                   = content.ContentLink.ID.ToString(),
                Status               = versionAble?.Status ?? VersionStatus.Published,
                Type                 = content.GetOriginalType().Name,
                PreviewUrl           = content.PreviewUrl(_urlResolver, _templateResolver),
                AdditionalProperties = new Dictionary <string, object>(),
                PublishedDate        = versionAble?.StartPublish?.ToString("g",
                                                                           DateTimeFormatInfo.InvariantInfo)
            };

            return(currentItem);
        }
Beispiel #37
0
        private void GetContentReferenceProperty(int level, List <ContentReference> parentIds, IContent content, PropertyInfo propertyInfo,
                                                 ContentInspectorViewModel model)
        {
            var contentReferenceProperty = content.Property[propertyInfo.Name] as PropertyContentReference;
            var contentReferenceSubItem  = contentReferenceProperty?.Value as ContentReference;

            if (contentReferenceSubItem != null)
            {
                if (!model.Content.IsMaxLevel && !model.Content.HasDuplicateParent)
                {
                    var contentReferenceItem = CreateModel(contentReferenceSubItem, null, null, level,
                                                           new List <ContentReference>(parentIds));
                    var contentReferenceViewModel = new ContentInspectorViewModel.ContentReferenceViewModel()
                    {
                        Name = contentReferenceProperty.TranslateDisplayName() ?? propertyInfo.Name,
                        ContentReferenceItem = contentReferenceItem
                    };
                    model.ContentReferenceItems.Add(contentReferenceViewModel);
                }
            }
        }
Beispiel #38
0
 public bool CanApply(IContent content)
 {
     return(content.As <ProjectPart>() != null);
 }
Beispiel #39
0
 public PreviewModel(SitePageData currentPage, IContent previewContent)
     : base(currentPage)
 {
     PreviewContent = previewContent;
     Areas          = new List <PreviewArea>();
 }
Beispiel #40
0
        private string RenderWidget(IContent widget)
        {
            var widgetShape = _orchardServices.ContentManager.BuildDisplay(widget);

            return(_shapeDisplay.Display(widgetShape));
        }
 public DeferedReIndexForContent(IBackgroundTaskQueue backgroundTaskQueue, ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IContent content, bool isPublished)
 {
     _backgroundTaskQueue           = backgroundTaskQueue;
     _examineUmbracoIndexingHandler = examineUmbracoIndexingHandler;
     _content     = content;
     _isPublished = isPublished;
 }
Beispiel #42
0
        public override void Execute(IContent content, Index index, object parameter)
        {
            var item = content.Retrieve(index);

            content.Remove(item, index);
        }
Beispiel #43
0
        public virtual T Save <T>(T entity, string includes) where T : class, IContent
        {
            bool save       = false;
            var  entityType = entity.GetType();
            var  content    = entity as IContent;

            var      isNew         = content.EntityId == Guid.Empty || !this.DataSource.Query(entityType).Where("EntityId.Equals(@0)", content.EntityId).Any();
            var      currentUserId = StrixPlatform.User.Id;
            IContent theContent    = null;

            if (isNew)
            {
                var fixedUrl  = content.Entity.Url;
                var sortOrder = content.SortOrder;
                var newEntity = CreateEntity(entityType, currentUserId);
                theContent = this.CreateNewContent(entityType, content, newEntity, currentUserId);
                MapContent(entityType, content, theContent);

                if (sortOrder == 0)
                {
                    theContent.SortOrder = this.GetNextSortOrder(entityType);
                }

                theContent.Entity.Url = UrlHelpers.CreateUniqueUrl(this.DataSource.Query(entityType), !string.IsNullOrWhiteSpace(fixedUrl) ? fixedUrl : theContent.Name, theContent.EntityId, "Entity.Url", "EntityId");
                save = true;
            }
            else
            {
                if (includes == null || !includes.ToLower().Contains("entity"))
                {
                    if (string.IsNullOrWhiteSpace(includes))
                    {
                        includes = "Entity";
                    }
                    else
                    {
                        includes = includes + ", Entity";
                    }
                }

                // Check whether there is content for this culture already.
                theContent = this.Get(entityType, content.EntityId, content.Culture, 0, includes);

                // Check whether the current user is allowed to edit this item.
                CheckCanEditOrDelete(theContent);

                if (theContent == null)
                {
                    theContent = this.TranslateContent(entityType, content);
                    save       = true;
                }
                else
                {
                    var publishedDate = content.PublishedOn;

                    MapContent(entityType, content, theContent);

                    if (publishedDate.HasValue)
                    {
                        theContent.PublishedOn = publishedDate;
                    }

                    theContent.UpdatedByUserId = StrixPlatform.User.Id;
                    theContent.UpdatedOn       = DateTime.Now;

                    if (EntityHelper.IsServiceActive(entityType, EntityServiceActions.UpdatePaths))
                    {
                        theContent.Entity.Url = UrlHelpers.CreateUniqueUrl(this.DataSource.Query(entityType), theContent.Name, theContent.EntityId, "Entity.Url", "EntityId");
                    }

                    var modifiedProperties = this.DataSource.GetModifiedPropertyValues(theContent).Where(p => !PropertiesToIgnoreForVersioning.Contains(p.PropertyName)).ToArray();

                    if (!modifiedProperties.IsEmpty())
                    {
                        theContent = this.CreateNewVersion(entityType, theContent, modifiedProperties);
                        save       = true;
                    }
                    else
                    {
                        return(theContent as T);
                    }
                }
            }

            if (!theContent.IsValid)
            {
                throw new StrixValidationException();
            }

            // Todo: remove when implemented publishing.
            theContent.PublishedOn       = theContent.CreatedOn;
            theContent.PublishedByUserId = theContent.CreatedByUserId;

            if (save)
            {
                this.DataSource.Save(theContent);
            }

            return(theContent as T);
        }
 public static void Execute(IBackgroundTaskQueue backgroundTaskQueue, ExamineUmbracoIndexingHandler examineUmbracoIndexingHandler, IContent content, bool isPublished)
 => backgroundTaskQueue.QueueBackgroundWorkItem(cancellationToken =>
        /// <summary>
        /// Exports an <see cref="IContent"/> item to xml as an <see cref="XElement"/>
        /// </summary>
        /// <param name="contentService"></param>
        /// <param name="dataTypeService"></param>
        /// <param name="userService"></param>
        /// <param name="content">Content to export</param>
        /// <param name="deep">Optional parameter indicating whether to include descendents</param>
        /// <returns><see cref="XElement"/> containing the xml representation of the Content object</returns>
        public XElement Serialize(IContentService contentService, IDataTypeService dataTypeService, IUserService userService, IContent content, bool deep = false)
        {
            //nodeName should match Casing.SafeAliasWithForcingCheck(content.ContentType.Alias);
            var nodeName = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : content.ContentType.Alias.ToSafeAliasWithForcingCheck();

            var xml = Serialize(dataTypeService, content, nodeName);

            xml.Add(new XAttribute("nodeType", content.ContentType.Id));
            xml.Add(new XAttribute("creatorName", content.GetCreatorProfile(userService).Name));
            xml.Add(new XAttribute("writerName", content.GetWriterProfile(userService).Name));
            xml.Add(new XAttribute("writerID", content.WriterId));
            xml.Add(new XAttribute("template", content.Template == null ? "0" : content.Template.Id.ToString(CultureInfo.InvariantCulture)));
            xml.Add(new XAttribute("nodeTypeAlias", content.ContentType.Alias));

            if (deep)
            {
                var descendants     = contentService.GetDescendants(content).ToArray();
                var currentChildren = descendants.Where(x => x.ParentId == content.Id);
                AddChildXml(contentService, dataTypeService, userService, descendants, currentChildren, xml);
            }

            return(xml);
        }
Beispiel #46
0
        /// <summary>
        /// Maps one content to another, preserving all important properties that should not be overwritten.
        /// </summary>
        /// <param name="entityType">The type of the content to map</param>
        /// <param name="first">The source content</param>
        /// <param name="second">The target content</param>
        private static void MapContent(Type entityType, IContent first, IContent second)
        {
            Guid           id                           = second.Id;
            Guid           entityId                     = second.EntityId;
            PlatformEntity entity                       = second.Entity;
            string         culture                      = second.Culture;
            bool           isCurrent                    = second.IsCurrentVersion;
            int            versionNumber                = second.VersionNumber;
            Guid           createdByUserId              = second.CreatedByUserId;
            DateTime       createdOn                    = second.CreatedOn;
            Guid           updatedByUserId              = second.UpdatedByUserId;
            DateTime       updatedOn                    = second.UpdatedOn;
            Guid?          publishedByUserId            = second.PublishedByUserId;
            DateTime?      publishedOn                  = second.PublishedOn;
            int            numberOfComments             = second.NumberOfComments;
            DateTime?      lastCommentDate              = second.LastCommentDate;
            IDictionary <string, object> fileValues     = GetFileValues(entityType, first, second);
            IDictionary <string, object> relationValues = GetRelationValues(entityType, first, second);

            first.Map(entityType, second);

            second.Id                = id;
            second.EntityId          = entityId;
            second.Entity            = entity;
            second.Culture           = culture;
            second.IsCurrentVersion  = isCurrent;
            second.VersionNumber     = versionNumber;
            second.CreatedByUserId   = createdByUserId;
            second.CreatedOn         = createdOn;
            second.UpdatedByUserId   = updatedByUserId;
            second.UpdatedOn         = updatedOn;
            second.PublishedByUserId = publishedByUserId;
            second.PublishedOn       = publishedOn;
            second.NumberOfComments  = numberOfComments;
            second.LastCommentDate   = lastCommentDate;

            if (fileValues.Count > 0)
            {
                int index = 0;

                foreach (var prop in fileValues.Keys)
                {
                    if (fileValues[prop] != null)
                    {
                        second.SetPropertyValue(prop, fileValues[prop]);
                    }

                    index++;
                }
            }

            if (relationValues.Count > 0)
            {
                int index = 0;

                foreach (var prop in relationValues.Keys)
                {
                    if (relationValues[prop] != null)
                    {
                        var collection  = second.GetPropertyValue(prop);
                        var values      = relationValues[prop];
                        var clearMethod = collection.GetType().GetMethod("Clear");
                        var addMethod   = collection.GetType().GetMethod("Add");
                        clearMethod.Invoke(collection, null);

                        foreach (var item in (IEnumerable <ValidationBase>)values)
                        {
                            addMethod.Invoke(collection, new object[] { item });
                        }
                    }

                    index++;
                }
            }
        }
Beispiel #47
0
 /// <summary>
 /// Publishes a single piece of Content
 /// </summary>
 /// <param name="content"><see cref="IContent"/> to publish</param>
 /// <param name="userId">Id of the User issueing the publish operation</param>
 /// <returns>True if the publish operation was successfull and not cancelled, otherwise false</returns>
 public override bool Publish(IContent content, int userId)
 {
     return(PublishInternal(content, userId).Success);
 }
Beispiel #48
0
 private IContentQuery <CommonPart, CommonPartRecord> GetParentQuery(IContent parentPart, VersionOptions versionOptions)
 {
     return(_contentManager.Query <CommonPart, CommonPartRecord>(versionOptions)
            .Where(cpr => cpr.Container == parentPart.ContentItem.Record));
 }
 public IContentConverter Resolve(IContent content)
 {
     return(content is LatestNewsBlockType ? _modelMapper : null);
 }
Beispiel #50
0
 public void UpdateReplacementLanguage(IContent currentContent, string requestedLanguage)
 {
     _defaultUpdateCurrentLanguage.UpdateReplacementLanguage(currentContent, requestedLanguage);
 }
Beispiel #51
0
        /// <summary>
        /// Sets Featured Product property and Best Bet Product property to ProductViewModels.
        /// </summary>
        /// <param name="searchResult">The search result (product list).</param>
        /// <param name="currentContent">The product category.</param>
        /// <param name="searchQuery">The search query string to filter Best Bet result.</param>
        /// <param name="productViewModels">The ProductViewModels is added two properties: Featured Product and Best Bet.</param>
        private void ApplyBoostedProperties(ref List <ProductTileViewModel> productViewModels, IContentResult <EntryContentBase> searchResult, IContent currentContent, string searchQuery)
        {
            var node     = currentContent as GenericNode;
            var products = new List <EntryContentBase>();

            if (node != null)
            {
                UpdateListWithFeatured(ref productViewModels, node);
            }

            var bestBetList = _bestBetRepository.List().Where(i => i.PhraseCriterion.Phrase.CompareTo(searchQuery) == 0);
            //Filter for product best bet only.
            var productBestBet  = bestBetList.Where(i => i.BestBetSelector is CommerceBestBetSelector);
            var ownStyleBestBet = bestBetList.Where(i => i.BestBetSelector is CommerceBestBetSelector && i.HasOwnStyle);

            productViewModels.ToList()
            .ForEach(p =>
            {
                if (productBestBet.Any(i => ((CommerceBestBetSelector)i.BestBetSelector).ContentLink.ID == p.ProductId))
                {
                    p.IsBestBetProduct = true;
                }
                if (ownStyleBestBet.Any(i => ((CommerceBestBetSelector)i.BestBetSelector).ContentLink.ID == p.ProductId))
                {
                    p.HasBestBetStyle = true;
                }
            });
        }
Beispiel #52
0
 /// <summary>
 /// Call to fire event that updating the unpublished content has finalized.
 /// </summary>
 /// <param name="content"><see cref="IContent"/> thats being unpublished</param>
 public override void UnPublishingFinalized(IContent content)
 {
     UnPublished.RaiseEvent(new PublishEventArgs <IContent>(content, false, false), this);
 }
Beispiel #53
0
        private ProductSearchResults GetSearchResults(IContent currentContent,
                                                      FilterOptionViewModel filterOptions,
                                                      string selectedfacets,
                                                      IEnumerable <Filter> filters = null,
                                                      int catalogId = 0)
        {
            //If contact belong organization, only find product that belong the categories that has owner is this organization
            var contact        = PrincipalInfo.CurrentPrincipal.GetCustomerContact();
            var organizationId = contact?.ContactOrganization?.PrimaryKeyId ?? Guid.Empty;

            EPiServer.Commerce.Catalog.ContentTypes.CatalogContent catalogOrganization = null;
            if (organizationId != Guid.Empty)
            {
                //get category that has owner id = organizationId
                catalogOrganization = _contentRepository
                                      .GetChildren <EPiServer.Commerce.Catalog.ContentTypes.CatalogContent>(_referenceConverter.GetRootLink())
                                      .FirstOrDefault(x => !string.IsNullOrEmpty(x.Owner) && x.Owner.Equals(organizationId.ToString(), StringComparison.OrdinalIgnoreCase));
            }

            var pageSize = filterOptions.PageSize > 0 ? filterOptions.PageSize : DefaultPageSize;
            var market   = _currentMarket.GetCurrentMarket();

            var query = _findClient.Search <EntryContentBase>();

            query = ApplyTermFilter(query, filterOptions.Q, filterOptions.TrackData);
            query = query.Filter(x => x.Language.Name.Match(_languageResolver.GetPreferredCulture().Name));

            if (organizationId != Guid.Empty && catalogOrganization != null)
            {
                query = query.Filter(x => x.Outline().PrefixCaseInsensitive(catalogOrganization.Name));
            }

            var nodeContent = currentContent as NodeContent;

            if (nodeContent != null)
            {
                var outline = GetOutline(nodeContent.Code);
                query = query.FilterOutline(new[] { outline });
            }

            query = query.FilterMarket(market);
            var facetQuery = query;

            query = FilterSelected(query, filterOptions.FacetGroups);
            query = ApplyFilters(query, filters);
            query = OrderBy(query, filterOptions);
            //Exclude products from search
            //query = query.Filter(x => (x as ProductContent).ExcludeFromSearch.Match(false));

            if (catalogId != 0)
            {
                query = query.Filter(x => x.CatalogId.Match(catalogId));
            }

            query = query.ApplyBestBets()
                    .Skip((filterOptions.Page - 1) * pageSize)
                    .Take(pageSize)
                    .StaticallyCacheFor(TimeSpan.FromMinutes(1));

            var result = query.GetContentResult();

            return(new ProductSearchResults
            {
                ProductViewModels = CreateProductViewModels(result, currentContent, filterOptions.Q),
                FacetGroups = GetFacetResults(filterOptions.FacetGroups, facetQuery, selectedfacets),
                TotalCount = result.TotalMatching,
                DidYouMeans = string.IsNullOrEmpty(filterOptions.Q) ? null : result.TotalMatching != 0 ? null : _findClient.Statistics().GetDidYouMean(filterOptions.Q),
                Query = filterOptions.Q,
            });
        }
Beispiel #54
0
 public ActionResult Index(IContent currentContent)
 {
     return(View(currentContent));
 }
Beispiel #55
0
 public ProductSearchResults Search(IContent currentContent,
                                    FilterOptionViewModel filterOptions,
                                    string selectedFacets,
                                    int catalogId = 0) => filterOptions == null?CreateEmptyResult() : GetSearchResults(currentContent, filterOptions, selectedFacets, null, catalogId);
Beispiel #56
0
        public IEnumerable <ProductTileViewModel> CreateProductViewModels(IContentResult <EntryContentBase> searchResult, IContent content, string searchQuery)
        {
            List <ProductTileViewModel> productViewModels = null;
            var market   = _currentMarket.GetCurrentMarket();
            var currency = _currencyService.GetCurrentCurrency();

            if (searchResult == null)
            {
                throw new ArgumentNullException(nameof(searchResult));
            }

            productViewModels = searchResult.Select(document => document.GetProductTileViewModel(market, currency)).ToList();
            ApplyBoostedProperties(ref productViewModels, searchResult, content, searchQuery);
            return(productViewModels);
        }
        /// <summary>
        ///  these items do exist in the content serializer,
        ///  but they are here because we are not doing this
        ///  for our primary object type but for content.
        /// </summary>

        protected virtual string GetItemPath(IContent item)
        {
            var entity = entityService.Get(item.Id);

            return(GetItemPath(entity));
        }
Beispiel #58
0
 public ProductSearchResults SearchWithFilters(IContent currentContent,
                                               FilterOptionViewModel filterOptions,
                                               IEnumerable <Filter> filters,
                                               int catalogId = 0) => filterOptions == null?CreateEmptyResult() : GetSearchResults(currentContent, filterOptions, "", filters, catalogId);
        private void ProcessItemContent(string contentItemContent, ContentAreaItem contentAreaItem, IContent content, HtmlHelper htmlHelper, TextWriter originalWriter)
        {
            HtmlNode blockContentNode = null;

            var shouldStop = CallbackOnItemNode(contentItemContent, contentAreaItem, content, ref blockContentNode);

            if (shouldStop)
            {
                return;
            }

            shouldStop = RenderItemContainer(contentItemContent, htmlHelper, originalWriter, ref blockContentNode);
            if (shouldStop)
            {
                return;
            }

            shouldStop = ControlItemVisibility(contentItemContent, content, originalWriter, ref blockContentNode);
            if (shouldStop)
            {
                return;
            }

            // finally we just render whole body
            originalWriter.Write(contentItemContent);
        }
Beispiel #60
0
        protected virtual HeaderViewModel CreateViewModel(IContent currentContent, HomePage homePage, FoundationContact contact, bool isBookmarked)
        {
            var menuItems         = new List <MenuItemViewModel>();
            var homeLanguage      = homePage.Language.DisplayName;
            var layoutSettings    = _settingsService.GetSiteSettings <LayoutSettings>();
            var referenceSettings = _settingsService.GetSiteSettings <ReferencePageSettings>();
            var filter            = new FilterContentForVisitor();

            menuItems = layoutSettings?.MainMenu?.FilteredItems.Where(x =>
            {
                var _menuItem = _contentLoader.Get <IContent>(x.ContentLink);
                MenuItemBlock _menuItemBlock;
                if (_menuItem is MenuItemBlock)
                {
                    _menuItemBlock = _menuItem as MenuItemBlock;
                    if (_menuItemBlock.Link == null)
                    {
                        return(true);
                    }
                    var linkedItem = UrlResolver.Current.Route(new UrlBuilder(_menuItemBlock.Link));
                    if (linkedItem != null && filter.ShouldFilter(linkedItem))
                    {
                        return(false);
                    }
                    return(true);
                }
                return(true);
            }).Select(x =>
            {
                var itemCached = CacheManager.Get(x.ContentLink.ID + homeLanguage + ":" + Constant.CacheKeys.MenuItems) as MenuItemViewModel;
                if (itemCached != null && !PageEditing.PageIsInEditMode)
                {
                    return(itemCached);
                }
                else
                {
                    var content = _contentLoader.Get <IContent>(x.ContentLink);
                    MenuItemBlock _;
                    MenuItemViewModel menuItem;
                    if (content is MenuItemBlock)
                    {
                        _        = content as MenuItemBlock;
                        menuItem = new MenuItemViewModel
                        {
                            Name       = _.Name,
                            ButtonText = _.ButtonText,
                            TeaserText = _.TeaserText,
                            Uri        = _.Link == null ? string.Empty : _urlResolver.GetUrl(new UrlBuilder(_.Link.ToString()), new UrlResolverArguments()
                            {
                                ContextMode = ContextMode.Default
                            }),
                            ImageUrl   = !ContentReference.IsNullOrEmpty(_.MenuImage) ? _urlResolver.GetUrl(_.MenuImage) : "",
                            ButtonLink = _.ButtonLink?.Host + _.ButtonLink?.PathAndQuery,
                            ChildLinks = _.ChildItems?.ToList() ?? new List <GroupLinkCollection>()
                        };
                    }
                    else
                    {
                        menuItem = new MenuItemViewModel
                        {
                            Name       = content.Name,
                            Uri        = _urlResolver.GetUrl(content.ContentLink),
                            ChildLinks = new List <GroupLinkCollection>()
                        };
                    }

                    if (!PageEditing.PageIsInEditMode)
                    {
                        var keyDependency = new List <string>
                        {
                            _contentCacheKeyCreator.CreateCommonCacheKey(homePage.ContentLink), // If The HomePage updates menu (remove MenuItems)
                            _contentCacheKeyCreator.CreateCommonCacheKey(x.ContentLink)
                        };

                        var eviction = new CacheEvictionPolicy(TimeSpan.FromDays(1), CacheTimeoutType.Sliding, keyDependency);
                        CacheManager.Insert(x.ContentLink.ID + homeLanguage + ":" + Constant.CacheKeys.MenuItems, menuItem, eviction);
                    }

                    return(menuItem);
                }
            }).ToList();

            return(new HeaderViewModel
            {
                HomePage = homePage,
                CurrentContentLink = currentContent?.ContentLink,
                CurrentContentGuid = currentContent?.ContentGuid ?? Guid.Empty,
                UserLinks = new LinkItemCollection(),
                Name = contact?.FirstName ?? "",
                IsBookmarked = isBookmarked,
                IsReadonlyMode = _databaseMode.DatabaseMode == DatabaseMode.ReadOnly,
                MenuItems = menuItems ?? new List <MenuItemViewModel>(),
                LoginViewModel = new LoginViewModel
                {
                    ResetPasswordPage = referenceSettings?.ResetPasswordPage ?? ContentReference.StartPage
                },
                RegisterAccountViewModel = new RegisterAccountViewModel
                {
                    Address = new AddressModel()
                },
            });
        }