/// <summary>
        /// Adds a content type to the composition.
        /// </summary>
        /// <param name="contentType">The content type to add.</param>
        /// <returns>True if the content type was added, otherwise false.</returns>
        public bool AddContentType(IContentTypeComposition contentType)
        {
            if (contentType.ContentTypeComposition.Any(x => x.CompositionAliases().Any(ContentTypeCompositionExists)))
            {
                return(false);
            }

            if (string.IsNullOrEmpty(Alias) == false && Alias.Equals(contentType.Alias))
            {
                return(false);
            }

            if (ContentTypeCompositionExists(contentType.Alias) == false)
            {
                //Before we actually go ahead and add the ContentType as a Composition we ensure that we don't
                //end up with duplicate PropertyType aliases - in which case we throw an exception.
                var conflictingPropertyTypeAliases = CompositionPropertyTypes.SelectMany(
                    x => contentType.CompositionPropertyTypes
                    .Where(y => y.Alias.Equals(x.Alias, StringComparison.InvariantCultureIgnoreCase))
                    .Select(p => p.Alias)).ToList();

                if (conflictingPropertyTypeAliases.Any())
                {
                    throw new InvalidCompositionException(Alias, contentType.Alias, conflictingPropertyTypeAliases.ToArray());
                }

                _contentTypeComposition.Add(contentType);
                OnPropertyChanged(Ps.Value.ContentTypeCompositionSelector);
                return(true);
            }
            return(false);
        }
        /// <summary>
        /// Gets the entity identifier of the entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns>The entity identifier of the entity.</returns>
        public static GuidUdi GetUdi(this IContentTypeComposition entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            string type;

            if (entity is IContentType)
            {
                type = Constants.UdiEntityType.DocumentType;
            }
            else if (entity is IMediaType)
            {
                type = Constants.UdiEntityType.MediaType;
            }
            else if (entity is IMemberType)
            {
                type = Constants.UdiEntityType.MemberType;
            }
            else
            {
                throw new NotSupportedException(string.Format("Composition type {0} is not supported.", entity.GetType().FullName));
            }
            return(new GuidUdi(type, entity.Key).EnsureClosed());
        }
        public PublishedContentGraphType(IContentTypeComposition contentType, PublishedItemType itemType, IDictionary <string, IInterfaceGraphType> interfaceGraphTypes)
        {
            Name        = contentType.Alias.ToPascalCase();
            Description = contentType.Description;
            IsTypeOf    = content => ((IPublishedContent)content).ContentType.Alias == contentType.Alias;
            Metadata    = new Dictionary <string, object>
            {
                [Constants.Metadata.ContentTypeAlias] = contentType.Alias,
                [Constants.Metadata.AllowedAtRoot]    = contentType.AllowedAsRoot,
                [Constants.Metadata.AllowedChildren]  = contentType.AllowedContentTypes.Select(x => x.Alias).ToArray(),
            };

            Interface <PublishedContentInterfaceGraphType>();

            foreach (IContentTypeComposition composition in contentType.ContentTypeComposition)
            {
                if (interfaceGraphTypes.TryGetValue(composition.Alias, out IInterfaceGraphType interfaceType))
                {
                    AddResolvedInterface(interfaceType);
                }
            }

            this.AddUmbracoBuiltInProperties();
            this.AddUmbracoContentPropeties(contentType, itemType);
        }
        public PublishedContentGraphType(IContentTypeComposition contentType, PublishedItemType itemType, IDictionary <string, IInterfaceGraphType> interfaceGraphTypes)
        {
            Name        = contentType.Alias.ToPascalCase();
            Description = contentType.Description;
            IsTypeOf    = content => ((IPublishedContent)content).ContentType.Alias == contentType.Alias;
            Metadata    = new Dictionary <string, object>
            {
                [Constants.Metadata.ContentTypeAlias] = contentType.Alias,
                [Constants.Metadata.AllowedAtRoot]    = contentType.AllowedAsRoot,
                [Constants.Metadata.AllowedChildren]  = contentType.AllowedContentTypes.Select(x => x.Alias).ToArray(),
            };

            Interface <PublishedContentInterfaceGraphType>();

            foreach (IContentTypeComposition composition in contentType.ContentTypeComposition)
            {
                if (interfaceGraphTypes.TryGetValue(composition.Alias, out IInterfaceGraphType interfaceType))
                {
                    AddResolvedInterface(interfaceType);
                }
            }

            // TODO: set this field name as a reserved property alias
            Field <NonNullGraphType <PublishedContentDataGraphType> >()
            .Name("_contentData")
            .Description("Built in published content data.")
            .Resolve(context => context.Source)
            .SetDoctypeMetadata(GetMetadata <string>(Constants.Metadata.ContentTypeAlias));

            this.AddUmbracoContentPropeties(contentType, itemType);
        }
        private PropertyType MapPropertyType(IContentTypeComposition contentType, PropertyTypeCommonDto dto, IDictionary <string, PropertyType> builtinProperties)
        {
            var groupId = dto.PropertyTypeGroupId;

            var readonlyStorageType = builtinProperties.TryGetValue(dto.Alias, out var propertyType);
            var storageType         = readonlyStorageType ? propertyType.ValueStorageType : Enum <ValueStorageType> .Parse(dto.DataTypeDto.DbType);

            if (contentType is MemberType memberType)
            {
                var access = new MemberTypePropertyProfileAccess(dto.ViewOnProfile, dto.CanEdit, dto.IsSensitive);
                memberType.MemberTypePropertyTypes[dto.Alias] = access;
            }

            return(new PropertyType(dto.DataTypeDto.EditorAlias, storageType, readonlyStorageType, dto.Alias)
            {
                Description = dto.Description,
                DataTypeId = dto.DataTypeId,
                DataTypeKey = dto.DataTypeDto.NodeDto.UniqueId,
                Id = dto.Id,
                Key = dto.UniqueId,
                Mandatory = dto.Mandatory,
                Name = dto.Name,
                PropertyGroupId = groupId.HasValue ? new Lazy <int>(() => groupId.Value) : null,
                SortOrder = dto.SortOrder,
                ValidationRegExp = dto.ValidationRegExp,
                Variations = (ContentVariation)dto.Variations
            });
        }
        private TypeBuilder BuildType(ModuleBuilder module, IContentTypeComposition contentType)
        {
            var parent     = !contentType.IsElement ? typeof(PublishedContentModelMapper) : typeof(PublishedElementModelMapper);
            var interfaces = new[] { this.Type, typeof(IModelMapper) };

            return(module.DefineType("ModelsMapper_" + this.Type.FullName, TypeAttributes.Public, parent, interfaces));
        }
Example #7
0
        /// <summary>
        /// Loades PropertyTypes by Tab/PropertyGroup using the new API.
        /// </summary>
        /// <param name="contentType"></param>
        /// <param name="tabPage"></param>
        /// <param name="inTab"></param>
        /// <param name="tabId"></param>
        /// <param name="tabCaption"></param>
        private void LoadPropertyTypes(IContentTypeComposition contentType, TabPage tabPage, Hashtable inTab, int tabId, string tabCaption)
        {
            var propertyGroups      = contentType.CompositionPropertyGroups.Where(x => x.Id == tabId || x.ParentId == tabId);
            var propertyTypeAliases = propertyGroups.SelectMany(x => x.PropertyTypes.OrderBy(y => y.SortOrder).Select(y => new Tuple <int, string, int>(y.Id, y.Alias, y.SortOrder)));

            foreach (var items in propertyTypeAliases)
            {
                var property = _content.getProperty(items.Item2);
                if (property != null)
                {
                    AddControlNew(property, tabPage, tabCaption);

                    if (!inTab.ContainsKey(items.Item1.ToString(CultureInfo.InvariantCulture)))
                    {
                        inTab.Add(items.Item1.ToString(CultureInfo.InvariantCulture), true);
                    }
                }
                else
                {
                    throw new ArgumentNullException(
                              string.Format(
                                  "Property {0} ({1}) on Content Type {2} could not be retrieved for Document {3} on Tab Page {4}. To fix this problem, delete the property and recreate it.",
                                  items.Item2, items.Item1, _content.ContentType.Alias, _content.Id,
                                  tabCaption));
                }
            }
        }
Example #8
0
        // Umbraco.Code.MapAll -Blueprints -Errors -ListViewEditorName -Trashed
        private void MapTypeToDisplayBase(IContentTypeComposition source, ContentTypeCompositionDisplay target)
        {
            target.Alias        = source.Alias;
            target.AllowAsRoot  = source.AllowedAsRoot;
            target.CreateDate   = source.CreateDate;
            target.Description  = source.Description;
            target.Icon         = source.Icon;
            target.IconFilePath = target.IconIsClass
                ? string.Empty
                : $"{_globalSettings.GetBackOfficePath(_hostingEnvironment).EnsureEndsWith("/")}images/umbraco/{source.Icon}";
            target.Id                = source.Id;
            target.IsContainer       = source.IsContainer;
            target.IsElement         = source.IsElement;
            target.Key               = source.Key;
            target.Name              = source.Name;
            target.ParentId          = source.ParentId;
            target.Path              = source.Path;
            target.Thumbnail         = source.Thumbnail;
            target.ThumbnailFilePath = target.ThumbnailIsClass
                ? string.Empty
                : _hostingEnvironment.ToAbsolute("~/umbraco/images/thumbnails/" + source.Thumbnail);
            target.Udi        = MapContentTypeUdi(source);
            target.UpdateDate = source.UpdateDate;

            target.AllowedContentTypes         = source.AllowedContentTypes.OrderBy(c => c.SortOrder).Select(x => x.Id.Value);
            target.CompositeContentTypes       = source.ContentTypeComposition.Select(x => x.Alias);
            target.LockedCompositeContentTypes = MapLockedCompositions(source);
        }
Example #9
0
        public static Udi MapContentTypeUdi(IContentTypeComposition source)
        {
            if (source == null)
            {
                return(null);
            }

            string udiType;

            switch (source)
            {
            case IMemberType _:
                udiType = Constants.UdiEntityType.MemberType;
                break;

            case IMediaType _:
                udiType = Constants.UdiEntityType.MediaType;
                break;

            case IContentType _:
                udiType = Constants.UdiEntityType.DocumentType;
                break;

            default:
                throw new PanicException($"Source is of type {source.GetType()} which isn't supported here");
            }

            return(Udi.Create(udiType, source.Key));
        }
Example #10
0
        private IEnumerable <string> MapLockedCompositions(IContentTypeComposition source)
        {
            // get ancestor ids from path of parent if not root
            if (source.ParentId == Constants.System.Root)
            {
                return(Enumerable.Empty <string>());
            }

            IContentType parent = _contentTypeService.Get(source.ParentId);

            if (parent == null)
            {
                return(Enumerable.Empty <string>());
            }

            var aliases = new List <string>();
            IEnumerable <int> ancestorIds = parent.Path.Split(Constants.CharArrays.Comma)
                                            .Select(s => int.Parse(s, CultureInfo.InvariantCulture));

            // loop through all content types and return ordered aliases of ancestors
            IContentType[] allContentTypes = _contentTypeService.GetAll().ToArray();
            foreach (var ancestorId in ancestorIds)
            {
                IContentType ancestor = allContentTypes.FirstOrDefault(x => x.Id == ancestorId);
                if (ancestor != null)
                {
                    aliases.Add(ancestor.Alias);
                }
            }

            return(aliases.OrderBy(x => x));
        }
Example #11
0
        public object GetDataTypeByAlias(string contentType, string contentTypeAlias, string propertyAlias)
        {
            IContentTypeComposition ct = null;

            switch (contentType)
            {
            case "content":
                ct = Services.ContentTypeService.GetContentType(contentTypeAlias);
                break;

            case "media":
                ct = Services.ContentTypeService.GetMediaType(contentTypeAlias);
                break;
            }

            if (ct == null)
            {
                return(null);
            }

            var prop = ct.CompositionPropertyTypes.SingleOrDefault(x => x.Alias == propertyAlias);

            if (prop == null)
            {
                return(null);
            }

            var dtd = Services.DataTypeService.GetDataTypeDefinitionById(prop.DataTypeDefinitionId);

            return(FormatDataType(dtd));
        }
Example #12
0
        private static IGraphQLValueResolver GetValueResolver(IContentTypeComposition contentType, PublishedPropertyType propertyType)
        {
            var foundResolvers   = GraphQLValueResolversResolver.Current.Resolvers.Where(r => r.IsResolver(propertyType)).ToList();
            var defaultResolvers = GraphQLValueResolversResolver.Current.DefaultResolvers;

            if (foundResolvers.Count == 1)
            {
                return(foundResolvers[0]);
            }

            if (foundResolvers.Count > 0)
            {
                //more than one resolver was found
                //get the non-default and see if we have only one
                var nonDefault = foundResolvers.Except(defaultResolvers.Select(x => x.Item1)).ToList();
                if (nonDefault.Count == 1)
                {
                    //there's only 1 custom resolver registered, so use it
                    return(nonDefault[0]);
                }

                //this is not allowed, there cannot be more than 1 resolver
                throw new InvalidOperationException($"Type '{nonDefault[1].GetType().FullName}' cannot be an IGraphQLValueResolver" +
                                                    $" for property '{propertyType.PropertyTypeAlias}' of content type '{contentType.Alias}' because type '{nonDefault[0].GetType().FullName}' has already been detected as a resolver" +
                                                    $" for that property, and only one converter can exist for a resolver.");
            }

            //no resolvers registered so we use the fallback resolver
            return(GraphQLValueResolversResolver.Current.FallbackResolver);
        }
        private void FixMissingImplementations(IContentTypeComposition documentType)
        {
            if (!this.MissingImplementations.Any() || this.GeneratedType == null)
            {
                return;
            }

            var iPublishType      = documentType.IsElement ? typeof(IPublishedElement) : typeof(IPublishedContent);
            var umbracoProperties = documentType.CompositionPropertyTypes.ToDictionary(
                keySelector: p => p.Alias,
                elementSelector: p => p.Alias,
                comparer: StringComparer.OrdinalIgnoreCase);

            foreach (var property in this.MissingImplementations.ToList())
            {
                if (!umbracoProperties.TryGetValue(property.Name, out var alias))
                {
                    continue;
                }

                this.MissingImplementations.Remove(property);
                var name   = GetImplementationFieldName(property);
                var getter = new DynamicMethod(name, property.PropertyType, new[] { iPublishType }, this.GeneratedType);
                var il     = getter.GetILGenerator();
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldstr, alias);
                this.CallValueMethod(this.GeneratedType, il, property);
                il.Emit(OpCodes.Ret);
                this.GeneratedType.GetField(name, BindingFlags.Static | BindingFlags.NonPublic)
                ?.SetValue(null, getter.CreateDelegate(typeof(Func <,>).MakeGenericType(iPublishType, property.PropertyType)));
            }
        }
Example #14
0
        internal static Udi MapContentTypeUdi(IContentTypeComposition source)
        {
            if (source == null)
            {
                return(null);
            }

            string udiType;

            switch (source)
            {
            case IMemberType _:
                udiType = Constants.UdiEntityType.MemberType;
                break;

            case IMediaType _:
                udiType = Constants.UdiEntityType.MediaType;
                break;

            case IContentType _:
                udiType = Constants.UdiEntityType.DocumentType;
                break;

            default:
                throw new Exception("panic");
            }

            return(Udi.Create(udiType, source.Key));
        }
Example #15
0
        private static IContentTypeComposition[] GetAncestors(IContentTypeComposition ctype, IContentTypeComposition[] allContentTypes)
        {
            if (ctype == null)
            {
                return new IContentTypeComposition[] {}
            }
            ;
            var ancestors = new List <IContentTypeComposition>();
            var parentId  = ctype.ParentId;

            while (parentId > 0)
            {
                var parent = allContentTypes.FirstOrDefault(x => x.Id == parentId);

                if (parent != null)
                {
                    ancestors.Add(parent);
                    parentId = parent.ParentId;
                }
                else
                {
                    parentId = -1;
                }
            }
            return(ancestors.ToArray());
        }
Example #16
0
 public void Validate(IContentTypeComposition compo)
 {
     using (new WriteLock(Locker))
     {
         ValidateLocked(compo);
     }
 }
Example #17
0
 public MemberType(IShortStringHelper shortStringHelper, IContentTypeComposition parent)
     : this(
         shortStringHelper,
         parent,
         string.Empty)
 {
 }
Example #18
0
        private PropertyType MapPropertyType(IContentTypeComposition contentType, PropertyTypeCommonDto dto, IDictionary <string, PropertyType> builtinProperties)
        {
            var groupId = dto.PropertyTypeGroupId;

            var readonlyStorageType = builtinProperties.TryGetValue(dto.Alias, out var propertyType);
            var storageType         = readonlyStorageType ? propertyType.ValueStorageType : Enum <ValueStorageType> .Parse(dto.DataTypeDto.DbType);

            if (contentType is IMemberType memberType)
            {
                memberType.SetIsSensitiveProperty(dto.Alias, dto.IsSensitive);
                memberType.SetMemberCanEditProperty(dto.Alias, dto.CanEdit);
                memberType.SetMemberCanViewProperty(dto.Alias, dto.ViewOnProfile);
            }

            return(new PropertyType(_shortStringHelper, dto.DataTypeDto.EditorAlias, storageType, readonlyStorageType, dto.Alias)
            {
                Description = dto.Description,
                DataTypeId = dto.DataTypeId,
                DataTypeKey = dto.DataTypeDto.NodeDto.UniqueId,
                Id = dto.Id,
                Key = dto.UniqueId,
                Mandatory = dto.Mandatory,
                MandatoryMessage = dto.MandatoryMessage,
                Name = dto.Name,
                PropertyGroupId = groupId.HasValue ? new Lazy <int>(() => groupId.Value) : null,
                SortOrder = dto.SortOrder,
                ValidationRegExp = dto.ValidationRegExp,
                ValidationRegExpMessage = dto.ValidationRegExpMessage,
                Variations = (ContentVariation)dto.Variations,
                LabelOnTop = dto.LabelOnTop
            });
        }
Example #19
0
        /// <summary>
        /// Get those that we use directly
        /// </summary>
        /// <param name="ctype"></param>
        /// <returns></returns>
        private static IEnumerable <IContentTypeComposition> GetDirectOrIndirect(IContentTypeComposition ctype)
        {
            if (ctype == null)
            {
                return(Enumerable.Empty <IContentTypeComposition>());
            }

            // hashset guarantees uniqueness on Id
            var all = new HashSet <IContentTypeComposition>(new DelegateEqualityComparer <IContentTypeComposition>(
                                                                (x, y) => x.Id == y.Id,
                                                                x => x.Id));

            var stack = new Stack <IContentTypeComposition>();

            foreach (var x in ctype.ContentTypeComposition)
            {
                stack.Push(x);
            }

            while (stack.Count > 0)
            {
                var x = stack.Pop();
                all.Add(x);
                foreach (var y in x.ContentTypeComposition)
                {
                    stack.Push(y);
                }
            }

            return(all);
        }
        protected override IEnumerable <string> ResolveCore(IContentTypeComposition source)
        {
            var aliases = new List <string>();

            // get ancestor ids from path of parent if not root
            if (source.ParentId != Constants.System.Root)
            {
                var parent = _applicationContext.Services.ContentTypeService.GetContentType(source.ParentId);
                if (parent != null)
                {
                    var ancestorIds = parent.Path.Split(',').Select(int.Parse);
                    // loop through all content types and return ordered aliases of ancestors
                    var allContentTypes = _applicationContext.Services.ContentTypeService.GetAllContentTypes().ToArray();
                    foreach (var ancestorId in ancestorIds)
                    {
                        var ancestor = allContentTypes.FirstOrDefault(x => x.Id == ancestorId);
                        if (ancestor != null)
                        {
                            aliases.Add(ancestor.Alias);
                        }
                    }
                }
            }
            return(aliases.OrderBy(x => x));
        }
        private static void ProcessRelationship(IContentService contentService, IContent block, IContent content,
                                                IRelationType bentoBlocksRelationType, string blockDoctypeCompositionAlias)
        {
            //check that the control is a block i.e. it's composed of the block type composition doctype
            //IContent block = contentService.GetById(controlValueId);
            if (block == null)
            {
                return;
            }

            IContentTypeComposition contentTypeOf = ContentTypeService.GetContentTypeOf(block);

            if (contentTypeOf.ContentTypeComposition.FirstOrDefault(x => x.Alias == blockDoctypeCompositionAlias) == null)
            {
                return;
            }

            bool areRelated = RelationService.AreRelated(content, block, RelationTypes.BentoItemsAlias);

            if (areRelated)
            {
                return;
            }

            Relation relation = new Relation(content.Id, block.Id, bentoBlocksRelationType);

            //possibly record additional info on the comment field e.g. who created the relationship (so the editor of the parent)
            //var user = UserService.GetByUsername(HttpContext.Current.User.Identity.Name);
            //relation.Comment = user.Name;
            RelationService.Save(relation);
        }
Example #22
0
 public TempContent(int id, int versionId, int publishedVersionId, IContentTypeComposition contentType)
 {
     Id                 = id;
     VersionId          = versionId;
     PublishedVersionId = publishedVersionId;
     ContentType        = contentType;
 }
Example #23
0
 public PropertyFactory(IContentTypeComposition contentType, Guid version, int id, DateTime createDate, DateTime updateDate)
 {
     _contentType = contentType;
     _version     = version;
     _id          = id;
     _createDate  = createDate;
     _updateDate  = updateDate;
 }
Example #24
0
 private static List<IContentType> GetDependants(IContentTypeComposition umbracoContentType, IEnumerable<IContentType> allContentTypes)
 {
     var id = umbracoContentType.Id;
     var composedOfThis = allContentTypes
         .Where(ct => ct.CompositionIds().Contains(id) && ct.ParentId != id)
         .ToList();
     return composedOfThis;
 }
Example #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object"/> class.
 /// </summary>
 public DocumentDefinition(int id, Guid version, DateTime versionDate, DateTime createDate, IContentTypeComposition composition)
 {
     Id          = id;
     Version     = version;
     VersionDate = versionDate;
     CreateDate  = createDate;
     Composition = composition;
 }
        private static List <IContentType> GetDependants(IContentTypeComposition umbracoContentType, IEnumerable <IContentType> allContentTypes)
        {
            var id             = umbracoContentType.Id;
            var composedOfThis = allContentTypes
                                 .Where(ct => ct.CompositionIds().Contains(id) && ct.ParentId != id)
                                 .ToList();

            return(composedOfThis);
        }
Example #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ContentBase"/> class.
 /// </summary>
 protected ContentBase(string name, IContentBase parent, IContentTypeComposition contentType, PropertyCollection properties, string culture = null)
     : this(name, contentType, properties, culture)
 {
     if (parent == null)
     {
         throw new ArgumentNullException(nameof(parent));
     }
     SetParent(parent);
 }
 // internal so it can be used by PublishedNoCache which does _not_ want to cache anything and so will never
 // use the static cache getter PublishedContentType.GetPublishedContentType(alias) below - anything else
 // should use it.
 internal PublishedContentType(IContentTypeComposition contentType)
 {
     Id             = contentType.Id;
     Alias          = contentType.Alias;
     _propertyTypes = contentType.CompositionPropertyTypes
                      .Select(x => new PublishedPropertyType(this, x))
                      .ToArray();
     InitializeIndexes();
 }
 // internal so it can be used by PublishedNoCache which does _not_ want to cache anything and so will never
 // use the static cache getter PublishedContentType.GetPublishedContentType(alias) below - anything else
 // should use it.
 internal PublishedContentType(IContentTypeComposition contentType)
 {
     Id = contentType.Id;
     Alias = contentType.Alias;
     _propertyTypes = contentType.CompositionPropertyTypes
         .Select(x => new PublishedPropertyType(this, x))
         .ToArray();
     InitializeIndexes();
 }
Example #30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ContentBase"/> class.
 /// </summary>
 protected ContentBase(string name, int parentId, IContentTypeComposition contentType, PropertyCollection properties, string culture = null)
     : this(name, contentType, properties, culture)
 {
     if (parentId == 0)
     {
         throw new ArgumentOutOfRangeException(nameof(parentId));
     }
     ParentId = parentId;
 }
Example #31
0
        /// <summary>
        /// Sets parent ID for content type inheritance
        /// </summary>
        /// <param name="itemType"></param>
        /// <param name="ct"></param>
        protected void SetParent(IContentTypeComposition ct, Type itemType)
        {
            var parentAttr = itemType.BaseType.GetCustomAttributes().FirstOrDefault(x => x is BaseContentTypeAttribute) as BaseContentTypeAttribute;

            if (parentAttr != null)
            {
                ct.SetLazyParentId(new Lazy <int>(() => GetByAlias(itemType.BaseType.Name).Id));
                ct.AddContentType(GetByAlias(itemType.BaseType.Name));
            }
        }
Example #32
0
        // no MapAll - relies on the non-generic method
        private void MapTypeToDisplayBase <TTarget, TTargetPropertyType>(IContentTypeComposition source, TTarget target)
            where TTarget : ContentTypeCompositionDisplay <TTargetPropertyType>
            where TTargetPropertyType : PropertyTypeDisplay, new()
        {
            MapTypeToDisplayBase(source, target);

            var groupsMapper = new PropertyTypeGroupMapper <TTargetPropertyType>(_propertyEditors, _dataTypeService, _logger);

            target.Groups = groupsMapper.Map(source);
        }
        /// <summary>
        /// Adds a new ContentType to the list of composite ContentTypes
        /// </summary>
        /// <param name="contentType"><see cref="ContentType"/> to add</param>
        /// <returns>True if ContentType was added, otherwise returns False</returns>
        public bool AddContentType(IContentTypeComposition contentType)
        {
            if (contentType.ContentTypeComposition.Any(x => x.CompositionAliases().Any(ContentTypeCompositionExists)))
                return false;

            if (!ContentTypeCompositionExists(contentType.Alias))
            {
                _contentTypeComposition.Add(contentType);
                OnPropertyChanged(ContentTypeCompositionSelector);
                return true;
            }
            return false;
        }
Example #34
0
        private void GenerateDependencies(IContentTypeComposition umbracoContentType, IEnumerable<IContentType> allContentTypes)
        {
            var compositionIds = umbracoContentType.CompositionIds();
            var thisIsComposedOf = allContentTypes
                .Where(ct => compositionIds.Contains(ct.Id) && umbracoContentType.ParentId != ct.Id)
                .ToList();

            foreach (var composition in thisIsComposedOf)
            {
                var compositionType = ContentTypeMapping.Map(composition);
                compositionType.IsMixin = true;
                GenerateClass(compositionType);
                GenerateInterface(compositionType);
            }
        }
Example #35
0
        public void GenerateModelAndDependants(IContentTypeService service, IContentTypeComposition umbracoContentType)
        {
            var contentType = ContentTypeMapping.Map(umbracoContentType);
            var allContentTypes = service.GetAllContentTypes().ToList();

            GenerateDependencies(umbracoContentType, allContentTypes);

            var composedOfThis = GetDependants(umbracoContentType, allContentTypes);

            var isMixin = composedOfThis.Any();
            
            if (isMixin)
            {
                contentType.IsMixin = true;
            }

            GenerateClass(contentType);

            if (isMixin)
            {
                GenerateInterface(contentType);
                GenerateDependants(composedOfThis);
            }
        }
 private void AddTabs(string nspace, IContentTypeComposition node, ContentTypeDescription type)
 {
     type.Tabs = new List<TabDescription>();
     foreach (var group in node.PropertyGroups.Where(x => !type.IgnoredTabs.Any(y => y.Equals(x.Name, StringComparison.InvariantCultureIgnoreCase))))
     {
         var tab = BuildTabModel(nspace, group, type.IgnoredPropertyAliases, type.ClassName);
         type.Tabs.Add(tab);
     }
 }
 private IContentTypeComposition Reparent(ContentTypeRegistration registration, IContentTypeComposition contentType, IContentTypeBase newParent, IContentTypeBase oldParent)
 {
     //TODO sort out reparenting
     throw new CodeFirstException("Changing parent types of existing content types is not supported. Consider dropping & recreating your content type hierarchy or using compositions instead." + Environment.NewLine +
         "Affected type alias: " + registration.Alias + ", previous parent alias: " + (oldParent == null ? "[none]" : oldParent.Alias) + ", new parent alias: " + (newParent == null ? "[none]" : newParent.Alias));
 }
        private void UpdatePropertyTypes(IContentTypeComposition contentTypeItem)
        {
            //Loop through the _genericProperties ArrayList and update all existing PropertyTypes
            foreach (GenericPropertyWrapper gpw in _genericProperties)
            {
                if (gpw.PropertyType == null) continue;
                if (contentTypeItem.PropertyTypes == null || contentTypeItem.PropertyTypes.Any(x => x.Alias == gpw.PropertyType.Alias) == false) continue;
                var propertyType = contentTypeItem.PropertyTypes.First(x => x.Alias == gpw.PropertyType.Alias);
                if (propertyType == null) continue;
                var dataTypeDefinition = ApplicationContext.Current.Services.DataTypeService.GetDataTypeDefinitionById(gpw.GenricPropertyControl.Type);
                propertyType.Alias = gpw.GenricPropertyControl.Alias;
                propertyType.Name = gpw.GenricPropertyControl.Name;
                propertyType.Description = gpw.GenricPropertyControl.Description;
                propertyType.ValidationRegExp = gpw.GenricPropertyControl.Validation;
                propertyType.Mandatory = gpw.GenricPropertyControl.Mandatory;
                propertyType.DataTypeDatabaseType = dataTypeDefinition.DatabaseType;
                propertyType.DataTypeDefinitionId = dataTypeDefinition.Id;
                propertyType.DataTypeId = dataTypeDefinition.ControlId;
                if (propertyType.PropertyGroupId == null || propertyType.PropertyGroupId.Value != gpw.GenricPropertyControl.Tab)
                {
                    if (gpw.GenricPropertyControl.Tab == 0)
                    {
                        propertyType.PropertyGroupId = new Lazy<int>(() => 0);
                    }
                    else if (contentTypeItem.PropertyGroups.Any(x => x.Id == gpw.GenricPropertyControl.Tab))
                    {
                        propertyType.PropertyGroupId = new Lazy<int>(() => gpw.GenricPropertyControl.Tab);
                    }
                    else if (contentTypeItem.PropertyGroups.Any(x => x.ParentId == gpw.GenricPropertyControl.Tab))
                    {
                        var propertyGroup = contentTypeItem.PropertyGroups.First(x => x.ParentId == gpw.GenricPropertyControl.Tab);
                        propertyType.PropertyGroupId = new Lazy<int>(() => propertyGroup.Id);
                    }
                    else
                    {
                        var propertyGroup = contentTypeItem.CompositionPropertyGroups.First(x => x.Id == gpw.GenricPropertyControl.Tab);
                        contentTypeItem.AddPropertyGroup(propertyGroup.Name);
                        contentTypeItem.MovePropertyType(propertyType.Alias, propertyGroup.Name);
                    }
                }
            }

            //Update the SortOrder of the PropertyTypes
            foreach (HtmlInputHidden propSorter in _sortLists)
            {
                if (propSorter.Value.Trim() != "")
                {
                    string[] newSortOrders = propSorter.Value.Split("&".ToCharArray());
                    for (int i = 0; i < newSortOrders.Length; i++)
                    {
                        var propertyTypeId = int.Parse(newSortOrders[i].Split("=".ToCharArray())[1]);
                        if (contentTypeItem.PropertyTypes != null &&
                            contentTypeItem.PropertyTypes.Any(x => x.Id == propertyTypeId))
                        {
                            var propertyType = contentTypeItem.PropertyTypes.First(x => x.Id == propertyTypeId);
                            propertyType.SortOrder = i;
                        }
                    }
                }
            }
        }
        private void SavePropertyType(SaveClickEventArgs e, IContentTypeComposition contentTypeItem)
        {
            this.CreateChildControls();

            //The GenericPropertyWrapper control, which contains the details for the PropertyType being added
            GenericProperty gpData = gp.GenricPropertyControl;
            if (string.IsNullOrEmpty(gpData.Name.Trim()) == false && string.IsNullOrEmpty(gpData.Alias.Trim()) == false)
            {
                var propertyTypeAlias = Casing.SafeAliasWithForcingCheck(gpData.Alias.Trim());
                if (contentTypeItem.PropertyTypeExists(propertyTypeAlias) == false)
                {
                    //Find the DataTypeDefinition that the PropertyType should be based on
                    var dataTypeDefinition = ApplicationContext.Current.Services.DataTypeService.GetDataTypeDefinitionById(gpData.Type);
                    var propertyType = new PropertyType(dataTypeDefinition)
                                           {
                                               Alias = propertyTypeAlias,
                                               Name = gpData.Name.Trim(),
                                               Mandatory = gpData.Mandatory,
                                               ValidationRegExp = gpData.Validation,
                                               Description = gpData.Description
                                           };
                    //gpData.Tab == 0 Generic Properties / No Group
                    if (gpData.Tab == 0)
                    {
                        contentTypeItem.AddPropertyType(propertyType);
                    }
                    else
                    {
                        //Find the PropertyGroup by its Id and then set the PropertyType on that group
                        var exists = contentTypeItem.CompositionPropertyGroups.Any(x => x.Id == gpData.Tab);
                        if (exists)
                        {
                            var propertyGroup = contentTypeItem.CompositionPropertyGroups.First(x => x.Id == gpData.Tab);
                            contentTypeItem.AddPropertyType(propertyType, propertyGroup.Name);
                        }
                        else
                        {
                            var tab = gpData.Tabs.FirstOrDefault(x => x.Id == gpData.Tab);
                            if (tab != null)
                            {
                                var caption = tab.GetRawCaption();
                                contentTypeItem.AddPropertyType(propertyType, caption);
                            }
                        }
                    }
                    gpData.Clear();
                }
                else
                {
                    e.Message = ui.Text("contentTypeDublicatePropertyType");
                    e.IconType = BasePage.speechBubbleIcon.warning;
                }
            }
        }
        protected ContentTypeCompositionBase(IContentTypeComposition parent)
            : base(parent)
		{
		    AddContentType(parent);
		}
        private void UpdatePropertyTypes(IContentTypeComposition contentTypeItem)
        {
            //Loop through the _genericProperties ArrayList and update all existing PropertyTypes
            foreach (GenericPropertyWrapper gpw in _genericProperties)
            {
                if (gpw.PropertyType == null) continue;
                if (contentTypeItem.PropertyTypes == null || contentTypeItem.PropertyTypes.Any(x => x.Alias == gpw.PropertyType.Alias) == false) continue;
                var propertyType = contentTypeItem.PropertyTypes.First(x => x.Alias == gpw.PropertyType.Alias);
                if (propertyType == null) continue;
                var dataTypeDefinition = ApplicationContext.Current.Services.DataTypeService.GetDataTypeDefinitionById(gpw.GenricPropertyControl.Type);
                propertyType.Alias = gpw.GenricPropertyControl.Alias;
                propertyType.Name = gpw.GenricPropertyControl.Name;
                propertyType.Description = gpw.GenricPropertyControl.Description;
                propertyType.ValidationRegExp = gpw.GenricPropertyControl.Validation;
                propertyType.Mandatory = gpw.GenricPropertyControl.Mandatory;
                propertyType.DataTypeDatabaseType = dataTypeDefinition.DatabaseType;
                propertyType.DataTypeDefinitionId = dataTypeDefinition.Id;
                propertyType.DataTypeId = dataTypeDefinition.ControlId;
                if (propertyType.PropertyGroupId == null || propertyType.PropertyGroupId.Value != gpw.GenricPropertyControl.Tab)
                {
                    if (gpw.GenricPropertyControl.Tab == 0)
                    {
                        propertyType.PropertyGroupId = new Lazy<int>(() => 0);
                    }
                    else if (contentTypeItem.PropertyGroups.Any(x => x.Id == gpw.GenricPropertyControl.Tab))
                    {
                        propertyType.PropertyGroupId = new Lazy<int>(() => gpw.GenricPropertyControl.Tab);
                    }
                    else if (contentTypeItem.PropertyGroups.Any(x => x.ParentId == gpw.GenricPropertyControl.Tab))
                    {
                        var propertyGroup = contentTypeItem.PropertyGroups.First(x => x.ParentId == gpw.GenricPropertyControl.Tab);
                        propertyType.PropertyGroupId = new Lazy<int>(() => propertyGroup.Id);
                    }
                    else
                    {
                        var propertyGroup = contentTypeItem.CompositionPropertyGroups.First(x => x.Id == gpw.GenricPropertyControl.Tab);
                        contentTypeItem.AddPropertyGroup(propertyGroup.Name);
                        contentTypeItem.MovePropertyType(propertyType.Alias, propertyGroup.Name);
                    }
                }
                //Is only called to flush cache since gpw.PropertyType.Save() isn't called
                // clear local cache
                cms.businesslogic.cache.Cache.ClearCacheItem("UmbracoPropertyTypeCache" + gpw.PropertyType.Id);
                // clear cache in ContentType
                cms.businesslogic.cache.Cache.ClearCacheItem("ContentType_PropertyTypes_Content:" + contentTypeItem.Id);
                _contentType.ClearVirtualTabs();
            }
        
            //Update the SortOrder of the PropertyTypes
            foreach (HtmlInputHidden propSorter in _sortLists)
            {
                if (propSorter.Value.Trim() != "")
                {
                    string tabId = propSorter.ID;
                    // remove leading "propSort_" and trailing "_Content"
                    tabId = tabId.Substring(9, tabId.Length - 9 - 8);
                    // calc the position of the prop SO i.e. after "t_<tabId>Contents[]="
                    int propSOPosition = "t_".Length + tabId.Length + "Contents[]=".Length + 1;

                    string[] tempSO = propSorter.Value.Split("&".ToCharArray());
                    for (int i = 0; i < tempSO.Length; i++)
                    {
                        string propSO = tempSO[i].Substring(propSOPosition);
                        int propertyTypeId = int.Parse(propSO);
                        if (contentTypeItem.PropertyTypes != null &&
                            contentTypeItem.PropertyTypes.Any(x => x.Id == propertyTypeId))
                        {
                            var propertyType = contentTypeItem.PropertyTypes.First(x => x.Id == propertyTypeId);
                            propertyType.SortOrder = i;
                        }
                    }
                }
            }
        }
Example #42
0
        /// <summary>
        /// Loades PropertyTypes by Tab/PropertyGroup using the new API.
        /// </summary>
        /// <param name="contentType"></param>
        /// <param name="tabPage"></param>
        /// <param name="inTab"></param>
        /// <param name="tabId"></param>
        /// <param name="tabCaption"></param>
        private void LoadPropertyTypes(IContentTypeComposition contentType, TabPage tabPage, Hashtable inTab, int tabId, string tabCaption)
        {
            var propertyGroups = contentType.CompositionPropertyGroups.Where(x => x.Id == tabId || x.ParentId == tabId);
            var propertyTypeAliases = propertyGroups.SelectMany(x => x.PropertyTypes.OrderBy(y => y.SortOrder).Select(y => new Tuple<int, string, int>(y.Id, y.Alias, y.SortOrder)));
            foreach (var items in propertyTypeAliases)
            {
                var property = _content.getProperty(items.Item2);
                if (property != null)
                {
                    AddControlNew(property, tabPage, tabCaption);

                    if (!inTab.ContainsKey(items.Item1.ToString(CultureInfo.InvariantCulture)))
                        inTab.Add(items.Item1.ToString(CultureInfo.InvariantCulture), true);
                }
                else
                {
                    throw new ArgumentNullException(
                        string.Format(
                            "Property {0} ({1}) on Content Type {2} could not be retrieved for Document {3} on Tab Page {4}. To fix this problem, delete the property and recreate it.",
                            items.Item2, items.Item1, _content.ContentType.Alias, _content.Id,
                            tabCaption));
                }
            }
        }
Example #43
0
        internal protected void PopulateContentTypeFromContentTypeBase(IContentTypeComposition contentType)
        {
            _alias = contentType.Alias;
            _iconurl = contentType.Icon;
            _isContainerContentType = contentType.IsContainer;
            _allowAtRoot = contentType.AllowedAsRoot;
            _thumbnail = contentType.Thumbnail;
            _description = contentType.Description;

            if (ContentTypeItem == null)
                ContentTypeItem = contentType;
        }
Example #44
0
 internal ContentType(IContentTypeComposition contentType) : base(contentType)
 {
     ContentTypeItem = contentType;
 }
Example #45
0
 public MemberType(IContentTypeComposition parent) : base(parent)
 {
     _memberTypePropertyTypes = new Dictionary<string, Tuple<bool, bool, int>>();
 }
 private ContentTypeDescription CreateTypeDescription(IContentTypeComposition node, string attributeName)
 {
     var type = new ContentTypeDescription();
     type.AttributeName = attributeName;
     type.Alias = node.Alias;
     type.Name = node.Name;
     type.AllowAtRoot = node.AllowedAsRoot.ToString().ToLower();
     type.ClassName = TypeGeneratorUtils.GetFormattedMemberName(node.Alias);
     type.EnableListView = node.IsContainer.ToString().ToLower();
     type.Icon = node.Icon;
     type.Description = node.Description == null ? "null" : node.Description.Replace(@"""", @"\""");
     return type;
 }
 private void AddAllowedChildTypes(IContentTypeComposition node, ContentTypeDescription type)
 {
     if (node.AllowedContentTypes.Count() > 0)
     {
         var typeArray = "";
         foreach (var allowedType in node.AllowedContentTypes)
         {
             if (typeArray != "")
             {
                 typeArray += ", ";
             }
             typeArray += "typeof(" + TypeGeneratorUtils.GetFormattedMemberName(allowedType.Alias) + ")";
         }
         type.AllowedChildren = "new Type[] { " + typeArray + " }";
     }
     else
     {
         type.AllowedChildren = "null";
     }
 }
 private ContentTypeDescription BuildContentTypeModel(string nameSpace, IContentTypeComposition node, string attributeName, Action<IContentTypeComposition, ContentTypeDescription> customAction)
 {
     var type = CreateTypeDescription(node, attributeName);
     if (customAction != null)
     {
         customAction.Invoke(node, type);
     }
     AddAllowedChildTypes(node, type);
     AddTabs(nameSpace, node, type);
     type.Properties = new List<PropertyDescription>();
     type.Compositions = new List<CompositionDescription>();
     AddProperties(type.Properties, node.PropertyTypes.Except(node.PropertyGroups.SelectMany(x => x.PropertyTypes)).Where(x => !type.IgnoredPropertyAliases.Any(y => y.Equals(x.Alias, StringComparison.InvariantCultureIgnoreCase))), nameSpace, type.ClassName);
     AddCompositions(type.Compositions, node.ContentTypeComposition, type.ParentAlias);
     return type;
 }