Exemplo n.º 1
0
        public void Can_Get_Recursive_Permissions_When_Node_Has_No_Permissions()
        {
            Scaffold.ContentType(_contentTypeService);
            IContentType contentType = _contentTypeService.GetContentType("textpage");

            IContent root  = Scaffold.Node(_contentService);
            IContent child = Scaffold.Node(_contentService, root.Id);

            List <UserGroupPermissionsPoco> permissions = _configService.GetRecursivePermissionsForNode(root.ToPublishedContent());

            Assert.Null(permissions);

            permissions = _configService.GetRecursivePermissionsForNode(child.ToPublishedContent());
            Assert.Null(permissions);

            // add a permission so something is returned...
            var poco = new UserGroupPermissionsPoco
            {
                ContentTypeId = contentType.Id,
                GroupId       = 3,
                Permission    = 0
            };

            _configService.UpdateContentTypeConfig(new Dictionary <int, List <UserGroupPermissionsPoco> >
            {
                { 0, new List <UserGroupPermissionsPoco> {
                      poco
                  } }
            });

            permissions = _configService.GetRecursivePermissionsForNode(child.ToPublishedContent());
            Assert.NotNull(permissions);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Imports and saves package xml as <see cref="IContentType"/>
        /// </summary>
        /// <param name="element">Xml to import</param>
        /// <param name="importStructure">Boolean indicating whether or not to import the </param>
        /// <param name="userId">Optional id of the User performing the operation. Default is zero (admin).</param>
        /// <returns>An enumrable list of generated ContentTypes</returns>
        public IEnumerable <IContentType> ImportContentTypes(XElement element, bool importStructure, int userId = 0)
        {
            var name = element.Name.LocalName;

            if (name.Equals("DocumentTypes") == false && name.Equals("DocumentType") == false)
            {
                throw new ArgumentException("The passed in XElement is not valid! It does not contain a root element called 'DocumentTypes' for multiple imports or 'DocumentType' for a single import.");
            }

            _importedContentTypes = new Dictionary <string, IContentType>();
            var documentTypes = name.Equals("DocumentTypes")
                                    ? (from doc in element.Elements("DocumentType") select doc).ToList()
                                    : new List <XElement> {
                element
            };

            //NOTE it might be an idea to sort the doctype XElements based on dependencies
            //before creating the doc types - should also allow for a better structure/inheritance support.
            foreach (var documentType in documentTypes)
            {
                var alias = documentType.Element("Info").Element("Alias").Value;
                if (_importedContentTypes.ContainsKey(alias) == false)
                {
                    var contentType = _contentTypeService.GetContentType(alias);
                    _importedContentTypes.Add(alias, contentType == null
                                                         ? CreateContentTypeFromXml(documentType)
                                                         : UpdateContentTypeFromXml(documentType, contentType));
                }
            }

            var list = _importedContentTypes.Select(x => x.Value).ToList();

            _contentTypeService.Save(list, userId);

            if (importStructure)
            {
                var updatedContentTypes = new List <IContentType>();
                //Update the structure here - we can't do it untill all DocTypes have been created
                foreach (var documentType in documentTypes)
                {
                    var alias            = documentType.Element("Info").Element("Alias").Value;
                    var structureElement = documentType.Element("Structure");
                    //Ensure that we only update ContentTypes which has actual structure-elements
                    if (structureElement == null || structureElement.Elements("DocumentType").Any() == false)
                    {
                        continue;
                    }

                    var updated = UpdateContentTypesStructure(_importedContentTypes[alias], structureElement);
                    updatedContentTypes.Add(updated);
                }
                //Update ContentTypes with a newly added structure/list of allowed children
                if (updatedContentTypes.Any())
                {
                    _contentTypeService.Save(updatedContentTypes, userId);
                }
            }

            return(list);
        }
        public override void Down()
        {
            var doctype = _contentTypeService.GetContentType("NewTextPage");

            //
            // i wouldn't do this - because you will loose any content that might
            // be using this doctype.
            //
            if (doctype != null)
            {
                _contentTypeService.Delete(doctype);
            }
        }
        internal void UpdateContentType(string contentTypeAlias, string propertyAlias)
        {
            IContentType contentType  = _contentTypeService.GetContentType(contentTypeAlias);
            PropertyType propertyType = contentType.PropertyTypes.FirstOrDefault(o => o.Alias.Equals(propertyAlias));

            this.UpdateContentType(contentType, propertyType);
        }
Exemplo n.º 5
0
        ExecutionResult IMigrationStep.Execute()
        {
            var dataFolderContentType = _contentTypeService.GetContentType(CoreInstallationConstants.DocumentTypeAliases.DataFolder);
            var dataFolderPage        = _contentService.GetContentOfContentType(dataFolderContentType.Id).First();

            UpdateOldName(dataFolderPage, CoreInstallationConstants.ContentDefaultName.DataFolder, DataFolderName);

            var children = dataFolderPage.Children().ToList();

            UpdateOldName(
                children,
                PanelsInstallationConstants.DocumentTypeAliases.GlobalPanelFolder,
                PanelsInstallationConstants.ContentDefaultName.GlobalPanelFolder,
                GlobalPanelsName);
            UpdateOldName(
                children,
                MailInstallationConstants.DocumentTypeAliases.MailTemplatesFolder,
                MailInstallationConstants.ContentDefaultName.MailTemplatesFolder,
                MailTemplatesName);
            UpdateOldName(
                children,
                NavigationInstallationConstants.DocumentTypeAliases.SystemLinkFolder,
                NavigationInstallationConstants.ContentDefaultName.SystemLinkFolder,
                SystemLinksName);
            UpdateOldName(
                children,
                TaggingInstallationConstants.DocumentTypeAliases.UserTagFolder,
                TaggingInstallationConstants.ContentDefaultName.UserTagFolder,
                UserTagsName);

            return(ExecutionResult.Success);
        }
Exemplo n.º 6
0
        public static bool ContentTypeChanged(XElement node)
        {
            string filehash = XmlDoc.GetPreCalculatedHash(node);

            if (string.IsNullOrEmpty(filehash))
            {
                return(true);
            }

            XElement aliasElement = node.Element("Info").Element("Alias");

            if (aliasElement == null)
            {
                return(true);
            }

            //var _contentService = ApplicationContext.Current.Services.ContentTypeService;
            var item = _contentService.GetContentType(aliasElement.Value);

            if (item == null) // import because it's new.
            {
                return(true);
            }

            XElement export = item.ExportToXml();
            string   dbMD5  = XmlDoc.CalculateMD5Hash(export);

            // XmlDoc.SaveElement("doctmp", item.Alias, export);

            return(!filehash.Equals(dbMD5));
        }
Exemplo n.º 7
0
        public override async Task <DeliverableResponse> Run(string command, string[] args)
        {
            if (args.Length != 3)
            {
                await Out.WriteLineAsync("Invalid arguments, expected format of `change-alias <what> <old> <new>`");

                return(DeliverableResponse.Continue);
            }

            var what = args[0].ToLower();

            var old  = args[1];
            var @new = args[2];

            switch (what)
            {
            case "document-type":
            case "doc-type":
            case "dt":
                var ct = contentTypeService.GetContentType(old);
                ct.Alias = @new;
                contentTypeService.Save(ct);
                break;

            default:
                await Out.WriteLineFormattedAsync("Presently we cannot change the alias of `{0}`. Run `help ca` to see what can be changed", what);

                break;
            }

            return(DeliverableResponse.Continue);
        }
        public ProductAttributeDisplay PutProductAttributeDetachedContent(
            [ModelBinder(typeof(ProductAttributeContentSaveBinder))]
            ProductAttributeContentSave attributeContentItem)
        {
            var contentTypeAlias = attributeContentItem.DetachedContentType.UmbContentType.Alias;
            var contentType      = _contentTypeService.GetContentType(contentTypeAlias);

            if (contentType == null)
            {
                var nullRef = new NullReferenceException("Could not find ContentType with alias: " + contentTypeAlias);
                MultiLogHelper.Error <ProductOptionApiController>("Failed to find content type", nullRef);
                throw nullRef;
            }

            var attribute = attributeContentItem.Display;

            attribute.DetachedDataValues = DetachedContentHelper.GetUpdatedValues <ProductAttributeContentSave, ProductAttributeDisplay>(contentType, attributeContentItem);
            var destination = _productOptionService.GetProductAttributeByKey(attribute.Key);

            destination = attribute.ToProductAttribute(destination);

            ((ProductOptionService)_productOptionService).Save(destination);

            return(destination.ToProductAttributeDisplay(contentType, DetachedValuesConversionType.Editor));
        }
Exemplo n.º 9
0
        private List <NodeTreeModel> recursiveTrees(IEnumerable <IPublishedContent> nodes)
        {
            List <NodeTreeModel> nodeList = new List <NodeTreeModel>();

            foreach (IPublishedContent child in nodes)
            {
                var           documentType = contentTypeService.GetContentType(child.DocumentTypeId);
                NodeTreeModel nodeModel    = new NodeTreeModel(child.Id, child.GetKey(), child.Name, child.Url, documentType.Icon, true);
                nodeList.Add(nodeModel);
                if (child.Children.Count() > 0)
                {
                    nodeModel.childs = recursiveTrees(child.Children);
                }
            }
            return(nodeList);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Update the existing content Type based on the data in the attributes
        /// </summary>
        /// <param name="contentTypeService"></param>
        /// <param name="fileService"></param>
        /// <param name="attribute"></param>
        /// <param name="contentType"></param>
        /// <param name="type"></param>
        /// <param name="dataTypeService"></param>
        private static void UpdateContentType(IContentTypeService contentTypeService, IFileService fileService, UmbracoContentTypeAttribute attribute, IContentType contentType, Type type, IDataTypeService dataTypeService)
        {
            contentType.Name                = attribute.ContentTypeName;
            contentType.Alias               = attribute.ContentTypeAlias;
            contentType.Icon                = attribute.Icon;
            contentType.IsContainer         = attribute.EnableListView;
            contentType.AllowedContentTypes = FetchAllowedContentTypes(attribute.AllowedChildren, contentTypeService);
            contentType.AllowedAsRoot       = attribute.AllowedAtRoot;

            Type parentType = type.BaseType;

            if (parentType != null && parentType != typeof(UmbracoGeneratedBase) && parentType.GetBaseTypes(false).Any(x => x == typeof(UmbracoGeneratedBase)))
            {
                UmbracoContentTypeAttribute parentAttribute = parentType.GetCustomAttribute <UmbracoContentTypeAttribute>();
                if (parentAttribute != null)
                {
                    string       parentAlias       = parentAttribute.ContentTypeAlias;
                    IContentType parentContentType = contentTypeService.GetContentType(parentAlias);
                    contentType.ParentId = parentContentType.Id;
                }
                else
                {
                    throw new Exception("The given base class has no UmbracoContentTypeAttribute");
                }
            }

            if (attribute.CreateMatchingView)
            {
                CreateMatchingView(fileService, attribute, type, contentType);

                //Template currentTemplate = fileService.GetTemplate(attribute.ContentTypeAlias) as Template;
                //if (currentTemplate == null)
                //{
                //    //there should be a template but there isn't so we create one
                //    currentTemplate = new Template("~/Views/" + attribute.ContentTypeAlias + ".cshtml", attribute.ContentTypeName, attribute.ContentTypeAlias);
                //    CreateViewFile(attribute.ContentTypeAlias, attribute.MasterTemplate, currentTemplate, type, fileService);
                //    fileService.SaveTemplate(currentTemplate, 0);
                //}
                //contentType.AllowedTemplates = new ITemplate[] { currentTemplate };
                //contentType.SetDefaultTemplate(currentTemplate);
            }

            VerifyProperties(contentType, type, dataTypeService);

            //verify if a tab has no properties, if so remove
            var propertyGroups = contentType.PropertyGroups.ToArray();
            int length         = propertyGroups.Length;

            for (int i = 0; i < length; i++)
            {
                if (propertyGroups[i].PropertyTypes.Count == 0)
                {
                    //remove
                    contentType.RemovePropertyGroup(propertyGroups[i].Name);
                }
            }

            //persist
            contentTypeService.Save(contentType, 0);
        }
Exemplo n.º 11
0
        public ICollection <string> GetContentTypes(ICmsContent node)
        {
            IContent      nativeNodeObject = node.NativeNodeObject as IContent;
            List <string> stringList       = new List <string>();

            if (((IUmbracoEntity)nativeNodeObject.ContentType).Path.Length == 2)
            {
                stringList.Add(((IContentTypeBase)nativeNodeObject.ContentType).Alias);
            }
            else
            {
                IContentTypeService contentTypeService = ApplicationContext.Current.Services.ContentTypeService;
                string path    = ((IUmbracoEntity)nativeNodeObject.ContentType).Path;
                char[] chArray = new char[1] {
                    ','
                };
                foreach (string str in path.Split(chArray))
                {
                    if (!(str == "-1"))
                    {
                        IContentType contentType = contentTypeService.GetContentType(Convert.ToInt32(str));
                        stringList.Add(((IContentTypeBase)contentType).Alias);
                    }
                }
            }
            return((ICollection <string>)stringList);
        }
Exemplo n.º 12
0
        public DocumentTypeState Delete()
        {
            var result = new DocumentTypeState();

            var homeNavigationComposition = _contentTypeService.GetContentType(Alias);

            if (homeNavigationComposition == null)
            {
                result.IsExists = false;
                return(result);
            }

            _contentTypeService.Delete(homeNavigationComposition);

            result.IsExists = false;
            return(result);
        }
        public void Convert(string name)
        {
            var archetypeDataType = _dataTypeService.GetDataTypeDefinitionByName(name);

            var nestedContentDataType = CreateNestedContentDataType(archetypeDataType);
            var archetypeContentTypes = ArchetypeContentTypes(archetypeDataType);

            foreach (var archetypeContentType in archetypeContentTypes)
            {
                ConvertInsideNestedContents(archetypeContentType.Alias, Alias(archetypeDataType.Name + "nc"));
                ConvertArchetypeValuesToNestedContent(archetypeContentType.Id, archetypeDataType.Id, Alias(archetypeDataType.Name + "nc"));
            }

            foreach (var archetypeContentType in archetypeContentTypes)
            {
                foreach (var composition in archetypeContentType.ContentTypeComposition)
                {
                    if (Archetypes(composition.PropertyTypes, archetypeDataType).Any())
                    {
                        var compositionContentType = _contentTypeService.GetContentType(composition.Id);

                        var propertyTypes = Archetypes(compositionContentType.PropertyTypes, archetypeDataType).ToArray();
                        foreach (var propType in propertyTypes)
                        {
                            propType.DataTypeDefinitionId = nestedContentDataType.Id;
                            propType.PropertyEditorAlias  = NestedContentAlias;
                        }
                        _contentTypeService.Save(compositionContentType);
                    }
                }
                if (Archetypes(archetypeContentType.PropertyTypes, archetypeDataType).Any())
                {
                    var propertyTypes = Archetypes(archetypeContentType.PropertyTypes, archetypeDataType).ToArray();

                    foreach (var propType in propertyTypes)
                    {
                        propType.DataTypeDefinitionId = nestedContentDataType.Id;
                        propType.PropertyEditorAlias  = NestedContentAlias;
                    }
                    _contentTypeService.Save(archetypeContentType);
                }
            }

            _dataTypeService.Delete(archetypeDataType);
        }
        private void DeleteContentTypeIfExists()
        {
            var myGroupsContentType = _contentTypeService.GetContentType(GroupsInstallationConstants.DocumentTypeAliases.GroupsMyGroupsOverviewPage);

            if (myGroupsContentType != null)
            {
                _contentTypeService.Delete(myGroupsContentType);
            }
        }
Exemplo n.º 15
0
        public void Can_Get_Recursive_Permissions_For_Node()
        {
            Scaffold.Config();
            Scaffold.ContentType(_contentTypeService);
            var type = _contentTypeService.GetContentType("textpage");

            var mock = new MockRepository(MockBehavior.Default);
            Mock <IPublishedContent> content = mock.Create <IPublishedContent>();

            content.Setup(x => x.Id).Returns(1089);

            List <UserGroupPermissionsPoco> permissions = _configService.GetRecursivePermissionsForNode(content.Object);

            // node has permissions, returns without recursion
            Assert.NotNull(permissions);

            // todo - to recurse, we need a contenttype
        }
Exemplo n.º 16
0
        public static Func <IEnumerable <IContent> > MyGetIContentsByTypeFromService(ContentTypeKey key, IContentService service, IContentTypeService typeService)
        {
            var type = typeService.GetContentType(key.ToString());

            return(() =>
            {
                return service.GetContentOfContentType(type.Id);
            });
        }
Exemplo n.º 17
0
        /// <summary>
        /// Convert the Archetype data types to their Nested Content equivalent
        /// </summary>
        /// <param name="archetypeContentTypes"></param>
        /// <param name="archetypeDataType"></param>
        /// <param name="nestedContentDataType"></param>
        private void ConvertDataType(IEnumerable <IContentType> archetypeContentTypes, IDataTypeDefinition archetypeDataType,
                                     IDataTypeDefinition nestedContentDataType)
        {
            foreach (var archetypeContentType in archetypeContentTypes)
            {
                foreach (var composition in archetypeContentType.ContentTypeComposition)
                {
                    if (composition.PropertyTypes.Any(IsArchetypeWithId(archetypeDataType.Id)))
                    {
                        var compositionContentType = _contentTypeService.GetContentType(composition.Id);

                        var propertyTypes = compositionContentType.PropertyTypes.Where(IsArchetypeWithId(archetypeDataType.Id))
                                            .ToArray();
                        foreach (var propType in propertyTypes)
                        {
                            propType.DataTypeDefinitionId = nestedContentDataType.Id;
                            propType.PropertyEditorAlias  = NestedContentAlias;
                        }

                        _contentTypeService.Save(compositionContentType);
                    }
                }

                if (archetypeContentType.PropertyTypes.Any(IsArchetypeWithId(archetypeDataType.Id)))
                {
                    var propertyTypes = archetypeContentType.PropertyTypes.Where(IsArchetypeWithId(archetypeDataType.Id)).ToArray();

                    foreach (var propType in propertyTypes)
                    {
                        propType.DataTypeDefinitionId = nestedContentDataType.Id;
                        propType.PropertyEditorAlias  = NestedContentAlias;
                    }

                    _contentTypeService.Save(archetypeContentType);
                }
            }

            _dataTypeService.Delete(archetypeDataType);

            Func <PropertyType, bool> IsArchetypeWithId(int id)
            {
                return(type => type.DataTypeDefinitionId == id && type.PropertyEditorAlias == ArchetypeAlias);
            }
        }
Exemplo n.º 18
0
        public IEnumerable <ILinkedEntity> GetLinkedEntities(object propertyValue)
        {
            if (propertyValue == null)
            {
                return(Enumerable.Empty <ILinkedEntity>());
            }

            var entities     = new List <ILinkedEntity>();
            var contentTypes = new Dictionary <string, IContentType>();
            var dataTypes    = new Dictionary <int, IDataTypeDefinition>();

            try
            {
                var items = JsonConvert.DeserializeObject <EmbeddedContentItem[]>(propertyValue.ToString());

                foreach (EmbeddedContentItem item in items)
                {
                    if (false == contentTypes.TryGetValue(item.ContentTypeAlias, out IContentType contentType))
                    {
                        contentTypes[item.ContentTypeAlias] = contentType = _contentTypeService.GetContentType(item.ContentTypeAlias);
                    }
                    if (contentType == null)
                    {
                        continue;
                    }
                    foreach (PropertyType propertyType in contentType.PropertyTypes)
                    {
                        if (false == item.Properties.TryGetValue(propertyType.Alias, out object value))
                        {
                            continue;
                        }

                        if (false == dataTypes.TryGetValue(propertyType.DataTypeDefinitionId, out IDataTypeDefinition dataTypeDefinition))
                        {
                            dataTypes[propertyType.DataTypeDefinitionId] = dataTypeDefinition = _dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId);
                        }
                        if (dataTypeDefinition == null)
                        {
                            continue;
                        }
                        IPropertyParser parser = PropertyParserResolver.Current.Parsers.FirstOrDefault(x => x.IsParserFor(dataTypeDefinition));

                        if (parser != null)
                        {
                            entities.AddRange(parser.GetLinkedEntities(value));
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                _logger.Error <EmbeddedContentParser>("Error parsing embedded content", exception);
            }
            return(entities);
        }
Exemplo n.º 19
0
 public static Func <string, Func <IEnumerable <IContent> > > MyGetIContentsByTypeFromService(IContentService service, IContentTypeService typeService)
 {
     return((typeName) =>
     {
         var type = typeService.GetContentType(typeName);
         return () =>
         {
             return service.GetContentOfContentType(type.Id);
         };
     });
 }
        /// <summary>
        /// Resolves <see cref="UmbContentTypeDisplay"/> for <see cref="IDetachedContentType"/> mappings.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <returns>
        /// The <see cref="UmbContentTypeDisplay"/>.
        /// </returns>
        protected override UmbContentTypeDisplay ResolveCore(IDetachedContentType source)
        {
            var contentType = source.ContentTypeKey != null?
                              _contentTypeService.GetContentType(source.ContentTypeKey.Value) :
                                  null;

            return(contentType != null?contentType.ToUmbContentTypeDisplay() : new UmbContentTypeDisplay()
            {
                AllowedTemplates = Enumerable.Empty <UmbTemplateDisplay>()
            });
        }
Exemplo n.º 21
0
        /// <summary>
        ///  these shoud be doable with the entity service, but for now, we
        ///  are grouping these making it eaiser should we add another
        /// contentTypeBased type to it.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private IContentTypeBase LookupByKey(Guid key)
        {
            IContentTypeBase item = default(IContentTypeBase);

            switch (_itemType)
            {
            case Constants.Packaging.DocumentTypeNodeName:
                item = _contentTypeService.GetContentType(key);
                break;

            case "MediaType":
                item = _contentTypeService.GetMediaType(key);
                break;

            case "MemberType":
                item = _memberTypeService.Get(key);
                break;
            }

            return(item);
        }
Exemplo n.º 22
0
        public ExecutionResult Execute()
        {
            var groupMembersContentType = _contentTypeService.GetContentType(DocumentTypeAliasConstants.GroupsMembersPage);
            var groupMembersPage        = _contentService.GetContentOfContentType(groupMembersContentType.Id).First();

            var gridContent = EmbeddedResourcesUtils.ReadResourceContent($"{Assembly.GetExecutingAssembly().GetName().Name}.Core.Updater.Migrations._1._2.PreValues.groupsMembersPageGrid.json");

            groupMembersPage.SetValue(UmbracoContentMigrationConstants.Grid.GridPropName, gridContent);

            _contentService.SaveAndPublishWithStatus(groupMembersPage);
            return(ExecutionResult.Success);
        }
Exemplo n.º 23
0
        /// <summary>
        /// This method is called when the Content Type declared in the attribute hasn't been found in Umbraco
        /// </summary>
        /// <param name="contentTypeService"></param>
        /// <param name="fileService"></param>
        /// <param name="attribute"></param>
        /// <param name="type"></param>
        /// <param name="dataTypeService"></param>
        private static void CreateContentType(IContentTypeService contentTypeService, IFileService fileService,
                                              UmbracoContentTypeAttribute attribute, Type type, IDataTypeService dataTypeService)
        {
            IContentType newContentType;
            Type         parentType = type.BaseType;

            if (parentType != null && parentType != typeof(UmbracoGeneratedBase) && parentType.GetBaseTypes(false).Any(x => x == typeof(UmbracoGeneratedBase)))
            {
                UmbracoContentTypeAttribute parentAttribute = parentType.GetCustomAttribute <UmbracoContentTypeAttribute>();
                if (parentAttribute != null)
                {
                    string       parentAlias       = parentAttribute.ContentTypeAlias;
                    IContentType parentContentType = contentTypeService.GetContentType(parentAlias);
                    newContentType = new ContentType(parentContentType);
                }
                else
                {
                    throw new Exception("The given base class has no UmbracoContentTypeAttribute");
                }
            }
            else
            {
                newContentType = new ContentType(-1);
            }

            newContentType.Name  = attribute.ContentTypeName;
            newContentType.Alias = attribute.ContentTypeAlias;
            newContentType.Icon  = attribute.Icon;

            if (attribute.CreateMatchingView)
            {
                CreateMatchingView(fileService, attribute, type, newContentType);
            }

            newContentType.AllowedAsRoot       = attribute.AllowedAtRoot;
            newContentType.IsContainer         = attribute.EnableListView;
            newContentType.AllowedContentTypes = FetchAllowedContentTypes(attribute.AllowedChildren, contentTypeService);

            //create tabs
            CreateTabs(newContentType, type, dataTypeService);

            //create properties on the generic tab
            var propertiesOfRoot = type.GetProperties().Where(x => x.GetCustomAttribute <UmbracoPropertyAttribute>() != null);

            foreach (var item in propertiesOfRoot)
            {
                CreateProperty(newContentType, null, dataTypeService, true, item);
            }

            //Save and persist the content Type
            contentTypeService.Save(newContentType, 0);
        }
Exemplo n.º 24
0
        internal void ExportToFile(string absoluteFilePath, string nodeType, int id)
        {
            XElement xml = null;

            if (nodeType.Equals("content", StringComparison.InvariantCultureIgnoreCase))
            {
                var content = _contentService.GetById(id);
                xml = Export(content);
            }

            if (nodeType.Equals("media", StringComparison.InvariantCultureIgnoreCase))
            {
                var media = _mediaService.GetById(id);
                xml = Export(media);
            }

            if (nodeType.Equals("contenttype", StringComparison.InvariantCultureIgnoreCase))
            {
                var contentType = _contentTypeService.GetContentType(id);
                xml = Export(contentType);
            }

            if (nodeType.Equals("mediatype", StringComparison.InvariantCultureIgnoreCase))
            {
                var mediaType = _contentTypeService.GetMediaType(id);
                xml = Export(mediaType);
            }

            if (nodeType.Equals("datatype", StringComparison.InvariantCultureIgnoreCase))
            {
                var dataType = _dataTypeService.GetDataTypeDefinitionById(id);
                xml = Export(dataType);
            }

            if (xml != null)
            {
                xml.Save(absoluteFilePath);
            }
        }
        /// <summary>
        /// This method is called when the Content Type declared in the attribute hasn't been found in Umbraco
        /// </summary>
        /// <param name="contentTypeService"></param>
        /// <param name="fileService"></param>
        /// <param name="attribute"></param>
        /// <param name="type"></param>
        /// <param name="dataTypeService"></param>
        private static void CreateContentType(IContentTypeService contentTypeService, IFileService fileService,
            UmbracoContentTypeAttribute attribute, Type type, IDataTypeService dataTypeService)
        {
            IContentType newContentType;
            Type parentType = type.BaseType;
            if (parentType != null && parentType != typeof(UmbracoGeneratedBase) && parentType.GetBaseTypes(false).Any(x => x == typeof(UmbracoGeneratedBase)))
            {
                UmbracoContentTypeAttribute parentAttribute = parentType.GetCustomAttribute<UmbracoContentTypeAttribute>();
                if (parentAttribute != null)
                {
                    string parentAlias = parentAttribute.ContentTypeAlias;
                    IContentType parentContentType = contentTypeService.GetContentType(parentAlias);
                    newContentType = new ContentType(parentContentType);
                }
                else
                {
                    throw new Exception("The given base class has no UmbracoContentTypeAttribute");
                }
            }
            else
            {
                newContentType = new ContentType(-1);
            }

            newContentType.Name = attribute.ContentTypeName;
            newContentType.Alias = attribute.ContentTypeAlias;
            newContentType.Icon = attribute.Icon;

            if (attribute.CreateMatchingView)
            {
                CreateMatchingView(fileService, attribute, type, newContentType);
            }

            newContentType.AllowedAsRoot = attribute.AllowedAtRoot;
            newContentType.IsContainer = attribute.EnableListView;
            newContentType.AllowedContentTypes = FetchAllowedContentTypes(attribute.AllowedChildren, contentTypeService);

            //create tabs
            CreateTabs(newContentType, type, dataTypeService);

            //create properties on the generic tab
            var propertiesOfRoot = type.GetProperties().Where(x => x.GetCustomAttribute<UmbracoPropertyAttribute>() != null);
            foreach (var item in propertiesOfRoot)
            {
                CreateProperty(newContentType, null, dataTypeService, true, item);
            }

            //Save and persist the content Type
            contentTypeService.Save(newContentType, 0);
        }
Exemplo n.º 26
0
        private IEnumerable <string> CollectMissedContentTypes()
        {
            var types    = CollectDocTypesClasses().ToList();
            var docTypes = CollectDocTypeAliasses(types).ToList();

            foreach (var dt in docTypes)
            {
                var contentType = _contentTypeService.GetContentType(dt);
                if (contentType == null)
                {
                    yield return(dt);
                }
            }
        }
        private string GetValue(string value, bool exporting)
        {
            if (string.IsNullOrEmpty(value))
            {
                return(value);
            }

            var items = JsonConvert.DeserializeObject <EmbeddedContentItem[]>(value);

            foreach (EmbeddedContentItem item in items)
            {
                IContentType contentType = _contentTypeService.GetContentType(item.ContentTypeAlias);
                if (contentType == null)
                {
                    continue;
                }

                foreach (KeyValuePair <string, object> property in item.Properties.ToList())
                {
                    PropertyType propertyType = contentType.CompositionPropertyTypes.FirstOrDefault(_ => _.Alias == property.Key);
                    if (propertyType == null)
                    {
                        continue;
                    }
                    IDataTypeDefinition dataType = _dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId);

                    IContentMapper mapper = ContentMapperFactory.GetMapper(new uSyncContentMapping {
                        EditorAlias = dataType.PropertyEditorAlias
                    });
                    if (mapper != null)
                    {
                        string newValue;
                        if (exporting)
                        {
                            newValue = mapper.GetExportValue(dataType.Id, property.Value.ToString());
                        }
                        else
                        {
                            newValue = mapper.GetImportValue(dataType.Id, property.Value.ToString());
                        }
                        item.Properties[property.Key] = newValue;
                    }
                }
            }

            return(JsonConvert.SerializeObject(items, Formatting.Indented));
        }
Exemplo n.º 28
0
 public static GetAllContentByType GetAllContentTypeFunction(IContentTypeService typeService, IContentService service)
 {
     return((string typeAlais) =>
     {
         var type = typeService.GetContentType(typeAlais);
         if (type == null)
         {
             return null;
         }
         var contents = service.GetContentOfContentType(type.Id);
         if (contents == null)
         {
             return null;
         }
         return contents;
     });
 }
Exemplo n.º 29
0
        private IUmbracoEntity GetEntity(Guid childObjectType, int childId)
        {
            switch (UmbracoObjectTypesExtensions.GetUmbracoObjectType(childObjectType))
            {
            case UmbracoObjectTypes.Document:
                return(contentService.GetById(childId));

            case UmbracoObjectTypes.Media:
                return(mediaService.GetById(childId));

            case UmbracoObjectTypes.DocumentType:
                return(contentTypeService.GetContentType(childId));

            case UmbracoObjectTypes.MediaType:
                return(contentTypeService.GetMediaType(childId));
            }
            throw new Exception("Unknown child type");
        }
Exemplo n.º 30
0
        public DocTypeViewModel GetDocTypeInformation(int id)
        {
            var docTypeInfo = new DocTypeViewModel();
            var node        = ContentService.GetById(id);

            if (node != null)
            {
                var docType = ContentTypeService.GetContentType(node.ContentTypeId);
                if (docType != null)
                {
                    docTypeInfo.Description     = docType.Description;
                    docTypeInfo.AllowAtRoot     = docType.AllowedAsRoot;
                    docTypeInfo.DefaultTemplate = new Template();
                    if (docType.DefaultTemplate != null)
                    {
                        docTypeInfo.DefaultTemplate.Alias = docType.DefaultTemplate.Alias;
                        docTypeInfo.DefaultTemplate.Id    = docType.DefaultTemplate.Id;
                    }

                    var templates = new List <Template>();

                    foreach (var template in docType.AllowedTemplates)
                    {
                        templates.Add(new Template
                        {
                            Alias = template.Alias,
                            Id    = template.Id
                        });
                    }

                    docTypeInfo.Templates = templates;

                    docTypeInfo.CreatedOn    = node.CreateDate.ToString("g");
                    docTypeInfo.CreatedBy    = node.GetCreatorProfile(UserService).Name;
                    docTypeInfo.LastEditedOn = node.UpdateDate.ToString("g");
                    docTypeInfo.LastEditedBy = node.GetWriterProfile(UserService).Name;
                    docTypeInfo.Status       = ContentService.GetById(node.Id).Status;
                }
            }

            return(docTypeInfo);
        }
Exemplo n.º 31
0
        private IContentTypeBase GetParentType(IContentTypeBase type)
        {
            if (type.ParentId <= 0)
            {
                return(null);
            }

            if (type is IContentType)
            {
                return(ContentTypeService.GetContentType(type.ParentId));
            }
            else if (type is IMediaType)
            {
                return(ContentTypeService.GetMediaType(type.ParentId));
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
        /// <summary>
        /// Update the existing content Type based on the data in the attributes
        /// </summary>
        /// <param name="contentTypeService"></param>
        /// <param name="fileService"></param>
        /// <param name="attribute"></param>
        /// <param name="contentType"></param>
        /// <param name="type"></param>
        /// <param name="dataTypeService"></param>
        private static void UpdateContentType(IContentTypeService contentTypeService, IFileService fileService, UmbracoContentTypeAttribute attribute, IContentType contentType, Type type, IDataTypeService dataTypeService)
        {
            contentType.Name = attribute.ContentTypeName;
            contentType.Alias = attribute.ContentTypeAlias;
            contentType.Icon = attribute.Icon;
            contentType.IsContainer = attribute.EnableListView;
            contentType.AllowedContentTypes = FetchAllowedContentTypes(attribute.AllowedChildren, contentTypeService);
            contentType.AllowedAsRoot = attribute.AllowedAtRoot;

            Type parentType = type.BaseType;
            if (parentType != null && parentType != typeof(UmbracoGeneratedBase) && parentType.GetBaseTypes(false).Any(x => x == typeof(UmbracoGeneratedBase)))
            {
                UmbracoContentTypeAttribute parentAttribute = parentType.GetCustomAttribute<UmbracoContentTypeAttribute>();
                if (parentAttribute != null)
                {
                    string parentAlias = parentAttribute.ContentTypeAlias;
                    IContentType parentContentType = contentTypeService.GetContentType(parentAlias);
                    contentType.ParentId = parentContentType.Id;
                }
                else
                {
                    throw new Exception("The given base class has no UmbracoContentTypeAttribute");
                }
            }

            if (attribute.CreateMatchingView)
            {
                Template currentTemplate = fileService.GetTemplate(attribute.ContentTypeAlias) as Template;
                if (currentTemplate == null)
                {
                    //there should be a template but there isn't so we create one
                    currentTemplate = new Template("~/Views/" + attribute.ContentTypeAlias + ".cshtml", attribute.ContentTypeName, attribute.ContentTypeAlias);
                    CreateViewFile(attribute.ContentTypeAlias, attribute.MasterTemplate, currentTemplate, type, fileService);
                    fileService.SaveTemplate(currentTemplate, 0);
                }
                contentType.AllowedTemplates = new ITemplate[] { currentTemplate };
                contentType.SetDefaultTemplate(currentTemplate);
            }

            VerifyProperties(contentType, type, dataTypeService);

            //verify if a tab has no properties, if so remove
            var propertyGroups = contentType.PropertyGroups.ToArray();
            int length = propertyGroups.Length;
            for (int i = 0; i < length; i++)
            {
                if (propertyGroups[i].PropertyTypes.Count == 0)
                {
                    //remove
                    contentType.RemovePropertyGroup(propertyGroups[i].Name);
                }
            }

            //persist
            contentTypeService.Save(contentType, 0);
        }
Exemplo n.º 33
0
		internal static IContent GetOrCreateContent(string alias, string contentName, IContentTypeService contentTypeService, IContentService contentService, IContent parentContent, List<IContent> contentList)
		{
			var contentType = contentTypeService.GetContentType(alias);

			return GetOrCreateContent(contentType, contentName, contentTypeService, contentService, parentContent, contentList);
		}