コード例 #1
0
        /// <summary>
        /// Convert ContentPickerAlias data types with the given name
        ///
        /// Converts the content from ids to UDIs
        /// Swaps the data type alias itself over
        /// </summary>
        /// <param name="name"></param>
        public void Convert(string name)
        {
            var oldDataTypeDefinition = _dataTypeService.GetDataTypeDefinitionByName(name);

            oldDataTypeDefinition.Name = oldDataTypeDefinition.Name + " (Obsolete)";
            _dataTypeService.Save(oldDataTypeDefinition);

            var oldPreValues = _dataTypeService.GetPreValuesCollectionByDataTypeId(oldDataTypeDefinition.Id);

            var newDataTypeDefinition = new DataTypeDefinition(_newDataTypeAlias);

            newDataTypeDefinition.Name = name;
            _dataTypeService.SaveDataTypeAndPreValues(newDataTypeDefinition, _preValueConversion == null ? new Dictionary <string, PreValue>() : _preValueConversion(oldPreValues.PreValuesAsDictionary));

            var allContentTypes       = _contentTypeService.GetAllContentTypes();
            var contentTypesToConvert = allContentTypes
                                        .Where(c =>
                                               c.PropertyTypes.Any(a => a.DataTypeDefinitionId == oldDataTypeDefinition.Id) ||
                                               c.CompositionPropertyTypes.Any(a => a.DataTypeDefinitionId == oldDataTypeDefinition.Id))
                                        .ToArray();

            AddReplacementDataType(contentTypesToConvert, oldDataTypeDefinition, newDataTypeDefinition);
            ConvertContent(contentTypesToConvert, oldDataTypeDefinition);
            DeleteOldDataType(oldDataTypeDefinition);
        }
        private IContentType[] ArchetypeContentTypes(IDataTypeDefinition archetypeDataType)
        {
            var allContentTypes = _contentTypeService.GetAllContentTypes();

            return(allContentTypes
                   .Where(c => c.PropertyTypes.Any(a => a.DataTypeDefinitionId == archetypeDataType.Id) || c.CompositionPropertyTypes.Any(a => a.DataTypeDefinitionId == archetypeDataType.Id))
                   .ToArray());
        }
コード例 #3
0
        /// <summary>
        /// Returns a list of all DocumentType Aliases in the site
        /// </summary>
        /// <returns></returns>
        public static IEnumerable <string> GetAllContentTypesAliases()
        {
            List <string> docTypesList = new List <string>();

            foreach (var dt in umbContentTypeService.GetAllContentTypes())
            {
                docTypesList.Add(dt.Alias);
            }

            return(docTypesList);
        }
コード例 #4
0
        /// <summary>
        /// Convert archetype data types with the given name
        ///
        /// Creates new data types, including a content type to represent the Archetype
        /// Then converts the content from one json format to the other
        /// This searches inside other nested contents as well as just standard content
        /// Finally swaps the data type itself over
        /// </summary>
        /// <param name="name"></param>
        public void Convert(string name)
        {
            var archetypeDataType = _dataTypeService.GetDataTypeDefinitionByName(name);

            var nestedContentDataType = CreateNestedContentDataTypeBasedOnArchetype(archetypeDataType);

            var allContentTypes       = _contentTypeService.GetAllContentTypes();
            var archetypeContentTypes = allContentTypes
                                        .Where(c =>
                                               c.PropertyTypes.Any(a => a.DataTypeDefinitionId == archetypeDataType.Id) ||
                                               c.CompositionPropertyTypes.Any(a => a.DataTypeDefinitionId == archetypeDataType.Id));

            ConvertContent(archetypeContentTypes, archetypeDataType);
            ConvertDataType(archetypeContentTypes, archetypeDataType, nestedContentDataType);
        }
コード例 #5
0
        /// <summary>
        /// Gets the allowed children
        /// </summary>
        /// <param name="types"></param>
        /// <param name="contentTypeService"></param>
        /// <returns></returns>
        private static IEnumerable <ContentTypeSort> FetchAllowedContentTypes(Type[] types, IContentTypeService contentTypeService)
        {
            if (types == null)
            {
                return(new ContentTypeSort[0]);
            }

            List <ContentTypeSort> contentTypeSorts = new List <ContentTypeSort>();

            List <string> aliases = GetAliasesFromTypes(types);

            var contentTypes = contentTypeService.GetAllContentTypes().Where(x => aliases.Contains(x.Alias)).ToArray();

            int length = contentTypes.Length;

            for (int i = 0; i < length; i++)
            {
                ContentTypeSort sort = new ContentTypeSort();
                sort.Alias = contentTypes[i].Alias;
                int id = contentTypes[i].Id;
                sort.Id        = new Lazy <int>(() => { return(id); });
                sort.SortOrder = i;
                contentTypeSorts.Add(sort);
            }
            return(contentTypeSorts);
        }
コード例 #6
0
        /// <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 =
                _contentTypeService.GetAllContentTypes().FirstOrDefault(x => x.Key == source.ContentTypeKey);

            return(contentType != null?contentType.ToUmbContentTypeDisplay() : new UmbContentTypeDisplay()
            {
                AllowedTemplates = Enumerable.Empty <UmbTemplateDisplay>()
            });
        }
コード例 #7
0
ファイル: UtilityTests.cs プロジェクト: blevai13/Plumber
        public void Can_Get_Content_Type()
        {
            Scaffold.ContentType(_contentTypeService);
            IEnumerable <IContentType> contentTypes = _contentTypeService.GetAllContentTypes();
            IContentType textpage = contentTypes.First(x => x.Alias == "textpage");

            IContentType result = _utility.GetContentType(textpage.Id);

            Assert.Equal(textpage.Id, result.Id);
        }
コード例 #8
0
            public override IDictionary <string, object> ConvertDbToEditor(IDictionary <string, object> defaultPreVals, PreValueCollection persistedPreVals)
            {
                if (persistedPreVals.PreValuesAsDictionary.TryGetValue("embeddedContentConfig",
                                                                       out PreValue preValue) && false == string.IsNullOrEmpty(preValue.Value))
                {
                    List <IContentType>   contentTypes = _contentTypeService.GetAllContentTypes().ToList();
                    EmbeddedContentConfig config       = JsonConvert.DeserializeObject <EmbeddedContentConfig>(preValue.Value);
                    var configDisplay = new EmbeddedContentConfigDisplay
                    {
                        EnableCollapsing = config.EnableCollapsing,
                        EnableFiltering  = config.EnableFiltering,
                        DocumentTypes    = from item in config.DocumentTypes
                                           let contentType =
                            contentTypes.FirstOrDefault(x => x.Alias == item.DocumentTypeAlias)
                            where contentType != null
                            select new EmbeddedContentConfigDocumentTypeDisplay
                        {
                            AllowEditingName  = item.AllowEditingName,
                            Description       = UmbracoDictionaryTranslate(contentType.Description),
                            DocumentTypeAlias = item.DocumentTypeAlias,
                            Group             = item.Group,
                            Icon         = contentType.Icon,
                            MaxInstances = item.MaxInstances,
                            Name         = UmbracoDictionaryTranslate(contentType.Name),
                            NameTemplate = item.NameTemplate,
                            SettingsTab  =
                                item.SettingsTabKey.HasValue
                                                    ? contentType.CompositionPropertyGroups
                                .FirstOrDefault(x => x.Key == item.SettingsTabKey)?.Id
                                                    : null
                        },
                        Groups   = config.Groups,
                        MaxItems = config.MaxItems,
                        MinItems = config.MinItems
                    };

                    preValue.Value = JsonConvert.SerializeObject(configDisplay);
                }

                return(base.ConvertDbToEditor(defaultPreVals, persistedPreVals));
            }
コード例 #9
0
        private async Task GetAll()
        {
            var types = contentTypeService.GetAllContentTypes();

            if (!types.Any())
            {
                await Out.WriteLineAsync("No content types found.");

                return;
            }

            await Out.WriteTableAsync(types.Select(t => new { t.Id, t.Alias, t.Name }));
        }
コード例 #10
0
        public ICollection <DocumentTypeDTO> GetAllDocumentTypeAliases()
        {
            IContentTypeService contentTypeService = _ServiceContext.ContentTypeService;

            return(contentTypeService.GetAllContentTypes()
                   .Select(t => new DocumentTypeDTO
            {
                Id = t.Id,
                Name = t.Name,
                Alias = t.Alias
            })
                   .ToArray());
        }
コード例 #11
0
        private async System.Threading.Tasks.Task CreatePackage(StreamWriter deliveryFileStream, string name)
        {
            var contentTypes = GetEntityChanges(_contentTypeService.GetAllContentTypes(), EntityType.CONTENT_TYPE);
            var dataTypes    = GetEntityChanges(_dataTypeService.GetAllDataTypeDefinitions(), EntityType.DATA_TYPE);
            var templates    = GetFileChanges(_fileService.GetTemplates(), EntityType.TEMPLATE);
            var styleSheets  = GetFileChanges(_fileService.GetStylesheets(), EntityType.STYLESHEET);
            var macros       = GetChangedMacros();

            var packageXml = new XDocument();

            packageXml.Add(
                new XElement(
                    "umbPackage",
                    new XElement(
                        "DocumentTypes",
                        contentTypes.Select(ct => _packagingService.Export(ct, false))
                        ),
                    _packagingService.Export(dataTypes, false),
                    _packagingService.Export(templates, false),
                    _packagingService.Export(macros, false),
                    new XElement(
                        "Stylesheets",
                        styleSheets.Select(s =>
                                           new XElement(
                                               "Stylesheet",
                                               new XElement("Name", s.Alias),
                                               new XElement("FileName", s.Name),
                                               new XElement("Content", new XCData(s.Content)),
                                               new XElement(
                                                   "Properties",
                                                   s.Properties.Select(p =>
                                                                       new XElement(
                                                                           "Property",
                                                                           new XElement("Name", p.Name),
                                                                           new XElement("Alias", p.Alias),
                                                                           new XElement("Value", p.Value)
                                                                           )
                                                                       )
                                                   )
                                               )
                                           )
                        )
                    )
                );

            _settings.TryGetChauffeurDirectory(out string dir);
            _fileSystem.File.WriteAllText(_fileSystem.Path.Combine(dir, $"{name}.xml"), packageXml.ToString());
            await deliveryFileStream.WriteLineAsync($"package {name}");

            _database.TruncateTable("Chauffeur_Changes");
        }
コード例 #12
0
        private async Task CreatePackage(StreamWriter deliveryFileStream, string name)
        {
            var contentTypes = contentTypeService.GetAllContentTypes();
            var dataTypes    = dataTypeService.GetAllDataTypeDefinitions();
            var templates    = fileService.GetTemplates();
            var styleSheets  = fileService.GetStylesheets();
            var macros       = macroService.GetAll();

            var packageXml = new XDocument();

            packageXml.Add(
                new XElement(
                    "umbPackage",
                    new XElement(
                        "DocumentTypes",
                        contentTypes.Select(ct => packagingService.Export(ct, false))
                        ),
                    packagingService.Export(dataTypes, false),
                    packagingService.Export(templates, false),
                    packagingService.Export(macros, false),
                    new XElement(
                        "Stylesheets",
                        styleSheets.Select(s =>
                                           new XElement(
                                               "Stylesheet",
                                               new XElement("Name", s.Alias),
                                               new XElement("FileName", s.Name),
                                               new XElement("Content", new XCData(s.Content)),
                                               new XElement(
                                                   "Properties",
                                                   s.Properties.Select(p =>
                                                                       new XElement(
                                                                           "Property",
                                                                           new XElement("Name", p.Name),
                                                                           new XElement("Alias", p.Alias),
                                                                           new XElement("Value", p.Value)
                                                                           )
                                                                       )
                                                   )
                                               )
                                           )
                        )
                    )
                );

            settings.TryGetChauffeurDirectory(out string dir);
            fileSystem.File.WriteAllText(fileSystem.Path.Combine(dir, $"{name}.xml"), packageXml.ToString());
            await deliveryFileStream.WriteLineAsync($"package {name}");
        }
コード例 #13
0
        public List <DocumentType> GetDocumentTypes()
        {
            List <DocumentType> documentTypes = new List <DocumentType>();

            IEnumerable <IContentType> contentTypes = ct.GetAllContentTypes();

            foreach (IContentType contentType in contentTypes)
            {
                DocumentType documentType = new DocumentType();
                documentType.Name  = contentType.Name;
                documentType.Alias = contentType.Alias;
                documentTypes.Add(documentType);
            }

            return(documentTypes);
        }
コード例 #14
0
        public IEnumerable <uSyncAction> ExportAll(string folder)
        {
            LogHelper.Info <ContentTypeHandler>("Exporting all ContentTypes (DocTypes)");

            List <uSyncAction> actions = new List <uSyncAction>();

            foreach (var item in _contentTypeService.GetAllContentTypes())
            {
                if (item != null)
                {
                    actions.Add(ExportToDisk(item, folder));
                }
            }

            return(actions);
        }
コード例 #15
0
        /// <summary>
        /// Synchronizes this instance.
        /// </summary>
        public void Run()
        {
            var documentTypes = _contentTypeService.GetAllContentTypes().ToArray();

            foreach (var model in _typeResolver.DocumentTypes.Where(model => Attribute.IsDefined(model.ModelType, typeof(PreviewTemplateAttribute), false)))
            {
                var documentType = _documentTypeFinder.Find(model, documentTypes).SingleOrDefault();

                if (documentType == null)
                {
                    continue;
                }

                UpdateDocumentType(documentType);
            }
        }
コード例 #16
0
        /// <summary>
        /// Gets list of all DocTypes on site as IContentType models
        /// </summary>
        /// <returns></returns>
        public static IEnumerable <IContentType> GetAllDocTypes()
        {
            var list = new List <IContentType>();

            var doctypes = umbDocTypeService.GetAllContentTypes();

            foreach (var type in doctypes)
            {
                if (type != null)
                {
                    list.Add(type);
                }
            }

            return(list);
        }
コード例 #17
0
        public static void CleanUpDocumentTypes()
        {
            List <string> existingDocumentTypesAliases = new List <string>();
            List <Type>   existingDocumentTypes        = Util.GetAllSubTypes(typeof(DocumentTypeBase));

            foreach (var item in existingDocumentTypes)
            {
                existingDocumentTypesAliases.Add(GetDocumentTypeAlias(item));
            }

            // get all umbraco defined doc types that don't exist in the class definitions
            var docTypesToDelete = ContentTypeService.GetAllContentTypes().Where(contentType => existingDocumentTypesAliases.All(alias => alias != contentType.Alias));

            foreach (var docTypeToDelete in docTypesToDelete.OrderByDescending(dt => dt.Level))
            {
                DeleteDocumentType(docTypeToDelete.Alias);
            }
        }
コード例 #18
0
        private async Task GetAll()
        {
            var types = contentTypeService.GetAllContentTypes();

            if (!types.Any())
            {
                await Out.WriteLineAsync("No content types found.");

                return;
            }

            await Out.WriteLineAsync("\tId\tAlias\tName");

            foreach (var type in types)
            {
                await Out.WriteLineFormattedAsync("\t{0}\t{1}\t{2}", type.Id, type.Alias, type.Name);
            }
        }
コード例 #19
0
        /// <summary>
        /// Private method to create new content
        /// </summary>
        /// <param name="contentService"></param>
        /// <param name="contentTypeService"></param>
        private static void CreateNewContent(IContentService contentService, IContentTypeService contentTypeService)
        {
            //We find all ContentTypes so we can show a nice list of everything that is available
            var contentTypes       = contentTypeService.GetAllContentTypes();
            var contentTypeAliases = string.Join(", ", contentTypes.Select(x => x.Alias));

            Console.WriteLine("Please enter the Alias of the ContentType ({0}):", contentTypeAliases);
            var contentTypeAlias = Console.ReadLine();

            Console.WriteLine("Please enter the Id of the Parent:");
            var strParentId = Console.ReadLine();
            int parentId;

            if (int.TryParse(strParentId, out parentId) == false)
            {
                parentId = -1;//Default to -1 which is the root
            }
            Console.WriteLine("Please enter the name of the Content to create:");
            var name = Console.ReadLine();

            //Create the Content
            var content = contentService.CreateContent(name, parentId, contentTypeAlias);

            foreach (var property in content.Properties)
            {
                Console.WriteLine("Please enter the value for the Property with Alias '{0}':", property.Alias);
                var value   = Console.ReadLine();
                var isValid = property.IsValid(value);
                if (isValid)
                {
                    property.Value = value;
                }
                else
                {
                    Console.WriteLine("The entered value was not valid and thus not saved");
                }
            }

            //Save the Content
            contentService.Save(content);

            Console.WriteLine("Content was saved: " + content.HasIdentity);
        }
        public override IEnumerable <HealthCheckStatus> GetStatus()
        {
            var foundDataTypes = new List <int>();
            var contentTypes   = _contentTypeService.GetAllContentTypes();

            foreach (var contentType in contentTypes)
            {
                foundDataTypes.AddRange(contentType.PropertyTypes.Select(p => p.DataTypeDefinitionId));
                foundDataTypes.AddRange(contentType.NoGroupPropertyTypes.Select(p => p.DataTypeDefinitionId));
                foundDataTypes.AddRange(contentType.CompositionPropertyTypes.Select(p => p.DataTypeDefinitionId));
            }

            var mediaTypes = _contentTypeService.GetAllMediaTypes();

            foreach (var mediaType in mediaTypes)
            {
                foundDataTypes.AddRange(mediaType.PropertyTypes.Select(p => p.DataTypeDefinitionId));
                foundDataTypes.AddRange(mediaType.NoGroupPropertyTypes.Select(p => p.DataTypeDefinitionId));
                foundDataTypes.AddRange(mediaType.CompositionPropertyTypes.Select(p => p.DataTypeDefinitionId));
            }

            var unusedDataTypes = _dataTypeService.GetAllDataTypeDefinitions()
                                  .Where(d => !d.Name.StartsWith("List View -"))
                                  .Where(d => !foundDataTypes.Distinct().Contains(d.Id))
                                  .ToArray();

            if (!unusedDataTypes.Any())
            {
                yield return(new HealthCheckStatus("No unused data types found")
                {
                    ResultType = StatusResultType.Success
                });
            }

            foreach (var dataType in unusedDataTypes)
            {
                yield return(new HealthCheckStatus($"{dataType.Name} does not appear to be used")
                {
                    ResultType = StatusResultType.Warning
                });
            }
        }
コード例 #21
0
        /// <summary>
        /// Private method to create new content
        /// </summary>
        /// <param name="contentService"></param>
        /// <param name="contentTypeService"></param>
        private static void CreateNewContent(IContentService contentService, IContentTypeService contentTypeService)
        {
            //We find all ContentTypes so we can show a nice list of everything that is available
            var contentTypes = contentTypeService.GetAllContentTypes();
            var contentTypeAliases = string.Join(", ", contentTypes.Select(x => x.Alias));

            Console.WriteLine("Please enter the Alias of the ContentType ({0}):", contentTypeAliases);
            var contentTypeAlias = Console.ReadLine();

            Console.WriteLine("Please enter the Id of the Parent:");
            var strParentId = Console.ReadLine();
            int parentId;
            if (int.TryParse(strParentId, out parentId) == false)
                parentId = -1;//Default to -1 which is the root

            Console.WriteLine("Please enter the name of the Content to create:");
            var name = Console.ReadLine();

            //Create the Content
            var content = contentService.CreateContent(name, parentId, contentTypeAlias);
            foreach (var property in content.Properties)
            {
                Console.WriteLine("Please enter the value for the Property with Alias '{0}':", property.Alias);
                var value = Console.ReadLine();
                var isValid = property.IsValid(value);
                if (isValid)
                {
                    property.Value = value;
                }
                else
                {
                    Console.WriteLine("The entered value was not valid and thus not saved");
                }
            }

            //Save the Content
            contentService.Save(content);

            Console.WriteLine("Content was saved: " + content.HasIdentity);
        }
コード例 #22
0
        /// <summary>
        /// Checks if there were any changes in document types defined in Umbraco/uSiteBuilder/Both.
        /// Does not check relations between document types (allowed childs and allowable parents)
        /// </summary>
        /// <param name="hasDefaultValues"></param>
        /// <returns></returns>
        public static List <ContentComparison> PreviewDocumentTypeChanges(out bool hasDefaultValues)
        {
#if DEBUG
            Stopwatch timer = new Stopwatch();
            timer.Start();
#endif
            // compare the library based definitions to the Umbraco DB
            var definedDocTypes = PreviewDocTypes(typeof(DocumentTypeBase), "");

#if DEBUG
            timer.Stop();
            StopwatchLogger.AddToLog(string.Format("Total elapsed time for method 'DocumentTypeComparer.PreviewDocumentTypeChanges' - only PreviewDocTypes: {0}ms.", timer.ElapsedMilliseconds));
            timer.Restart();
#endif



#if DEBUG
            timer.Start();
#endif
            hasDefaultValues = _hasDefaultValues;
            // add any umbraco defined doc types that don't exist in the class definitions
            definedDocTypes.AddRange(ContentTypeService.GetAllContentTypes()
                                     .Where(doctype => definedDocTypes.All(dd => dd.Alias != doctype.Alias))
                                     .Select(docType => new ContentComparison {
                Alias = docType.Alias, DocumentTypeStatus = Status.Deleted, DocumentTypeId = docType.Id
            }));

#if DEBUG
            timer.Stop();
            StopwatchLogger.AddToLog(string.Format("Total elapsed time for method 'DocumentTypeComparer.PreviewDocumentTypeChanges' - add any umbraco defined doc types that don't exist in the class definitions: {0}ms.", timer.ElapsedMilliseconds));
            timer.Restart();
#endif

            return(definedDocTypes);
        }
コード例 #23
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);
            }
        }
コード例 #24
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);
            }
        }
コード例 #25
0
 protected override IEnumerable <IContentTypeBase> GetAllContentTypes()
 {
     return(_service.GetAllContentTypes());
 }
コード例 #26
0
                public IEnumerable <ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor)
                {
                    if (value == null)
                    {
                        yield break;
                    }

                    List <IContentType> contentTypes = _contentTypeService.GetAllContentTypes().ToList();
                    List <EmbeddedContentItemDisplay> itemsDisplay = JsonConvert.DeserializeObject <IEnumerable <EmbeddedContentItemDisplay> >(value.ToString()).ToList();

                    foreach (EmbeddedContentItemDisplay itemDisplay in itemsDisplay)
                    {
                        IContentType contentType = contentTypes.FirstOrDefault(x => x.Alias == itemDisplay.ContentTypeAlias);

                        if (contentType == null)
                        {
                            continue;
                        }

                        IEnumerable <EmbeddedContentPropertyDisplay> properties = itemDisplay.Tabs.SelectMany(x => x.Properties).ToList();

                        foreach (PropertyType propertyType in contentType.CompositionPropertyGroups.SelectMany(x => x.PropertyTypes))
                        {
                            EmbeddedContentPropertyDisplay property = properties.FirstOrDefault(x => x.Alias == propertyType.Alias);
                            if (property == null)
                            {
                                continue;
                            }

                            PropertyEditor propertyEditor = PropertyEditorResolver.Current.GetByAlias(propertyType.PropertyEditorAlias);
                            if (propertyEditor == null)
                            {
                                continue;
                            }

                            PreValueCollection propertyPreValues = _dataTypeService.GetPreValuesCollectionByDataTypeId(propertyType.DataTypeDefinitionId);
                            if (propertyType.Mandatory)
                            {
                                foreach (ValidationResult result in propertyEditor.ValueEditor.RequiredValidator.Validate(property.Value, "", propertyPreValues, editor))
                                {
                                    yield return(new ValidationResult(result.ErrorMessage, result.MemberNames.Select(x => $"item-{itemDisplay.Key}-{property.Alias}-{x}")));
                                }
                            }

                            if (false == propertyType.ValidationRegExp.IsNullOrWhiteSpace())
                            {
                                var str = property.Value as string;
                                if (property.Value != null && false == str.IsNullOrWhiteSpace() || propertyType.Mandatory)
                                {
                                    foreach (ValidationResult result in propertyEditor.ValueEditor.RegexValidator.Validate(property.Value, propertyType.ValidationRegExp, propertyPreValues, editor))
                                    {
                                        yield return(new ValidationResult(result.ErrorMessage, result.MemberNames.Select(x => $"item-{itemDisplay.Key}-{property.Alias}-{x}")));
                                    }
                                }
                            }

                            foreach (IPropertyValidator validator in propertyEditor.ValueEditor.Validators)
                            {
                                foreach (ValidationResult result in validator.Validate(property.Value, propertyPreValues, editor))
                                {
                                    yield return(new ValidationResult(result.ErrorMessage, result.MemberNames.Select(x => $"item-{itemDisplay.Key}-{property.Alias}-{x}")));
                                }
                            }
                        }
                    }
                }
コード例 #27
0
 /// <summary>
 /// Gets the content types.
 /// </summary>
 /// <returns>
 /// The content types.
 /// </returns>
 protected override IContentType[] GetContentTypes()
 {
     return(_contentTypeService.GetAllContentTypes().ToArray());
 }
コード例 #28
0
        protected override void PerformIndexAll(string type)
        {
            if (SupportedTypes.Contains(type) == false)
            {
                return;
            }

            var pageIndex = 0;

            DataService.LogService.AddInfoLog(-1, string.Format("PerformIndexAll - Start data queries - {0}", type));
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            try
            {
                switch (type)
                {
                case IndexTypes.Content:
                    var contentParentId = -1;
                    if (IndexerData.ParentNodeId.HasValue && IndexerData.ParentNodeId.Value > 0)
                    {
                        contentParentId = IndexerData.ParentNodeId.Value;
                    }

                    if (SupportUnpublishedContent == false && DisableXmlDocumentLookup == false)
                    {
                        //get all node Ids that have a published version - this is a fail safe check, in theory
                        // only document nodes that have a published version would exist in the cmsContentXml table
                        var allNodesWithPublishedVersions = ApplicationContext.Current.DatabaseContext.Database.Fetch <int>(
                            "select DISTINCT cmsDocument.nodeId from cmsDocument where cmsDocument.published = 1");

                        XElement last       = null;
                        var      trackedIds = new HashSet <string>();

                        ReindexWithXmlEntries(type, contentParentId,
                                              () => _contentTypeService.GetAllContentTypes().ToArray(),
                                              (path, pIndex, pSize) =>
                        {
                            long totalContent;

                            //sorted by: umbracoNode.level, umbracoNode.parentID, umbracoNode.sortOrder
                            var result = _contentService.GetPagedXmlEntries(path, pIndex, pSize, out totalContent).ToArray();
                            var more   = result.Length == pSize;

                            //then like we do in the ContentRepository.BuildXmlCache we need to track what Parents have been processed
                            // already so that we can then exclude implicitly unpublished content items
                            var filtered = new List <XElement>();

                            foreach (var xml in result)
                            {
                                var id = xml.AttributeValue <int>("id");

                                //don't include this if it doesn't have a published version
                                if (allNodesWithPublishedVersions.Contains(id) == false)
                                {
                                    continue;
                                }

                                var parentId = xml.AttributeValue <string>("parentID");

                                if (parentId == null)
                                {
                                    continue;                           //this shouldn't happen
                                }
                                //if the parentid is changing
                                if (last != null && last.AttributeValue <string>("parentID") != parentId)
                                {
                                    var found = trackedIds.Contains(parentId);
                                    if (found == false)
                                    {
                                        //Need to short circuit here, if the parent is not there it means that the parent is unpublished
                                        // and therefore the child is not published either so cannot be included in the xml cache
                                        continue;
                                    }
                                }

                                last = xml;
                                trackedIds.Add(xml.AttributeValue <string>("id"));

                                filtered.Add(xml);
                            }

                            return(Tuple.Create(filtered.ToArray(), more));
                        },
                                              i => _contentService.GetById(i));
                    }
                    else
                    {
                        //used to track non-published entities so we can determine what items are implicitly not published
                        //currently this is not in use apart form in tests
                        var notPublished = new HashSet <string>();

                        int currentPageSize;
                        do
                        {
                            long total;

                            IContent[] descendants;
                            if (SupportUnpublishedContent)
                            {
                                descendants = _contentService.GetPagedDescendants(contentParentId, pageIndex, PageSize, out total, "umbracoNode.id").ToArray();
                            }
                            else
                            {
                                //get all paged records but order by level ascending, we need to do this because we need to track which nodes are not published so that we can determine
                                // which descendent nodes are implicitly not published
                                descendants = _contentService.GetPagedDescendants(contentParentId, pageIndex, PageSize, out total, "level", Direction.Ascending, true, (string)null).ToArray();
                            }

                            // need to store decendants count before filtering, in order for loop to work correctly
                            currentPageSize = descendants.Length;

                            //if specific types are declared we need to post filter them
                            //TODO: Update the service layer to join the cmsContentType table so we can query by content type too
                            IEnumerable <IContent> content;
                            if (IndexerData.IncludeNodeTypes.Any())
                            {
                                content = descendants.Where(x => IndexerData.IncludeNodeTypes.Contains(x.ContentType.Alias));
                            }
                            else
                            {
                                content = descendants;
                            }

                            AddNodesToIndex(GetSerializedContent(
                                                SupportUnpublishedContent,
                                                c => _serializer.Serialize(_contentService, _dataTypeService, _userService, c),
                                                content, notPublished).WhereNotNull(), type);

                            pageIndex++;
                        } while (currentPageSize == PageSize);
                    }

                    break;

                case IndexTypes.Media:
                    var mediaParentId = -1;

                    if (IndexerData.ParentNodeId.HasValue && IndexerData.ParentNodeId.Value > 0)
                    {
                        mediaParentId = IndexerData.ParentNodeId.Value;
                    }

                    ReindexWithXmlEntries(type, mediaParentId,
                                          () => _contentTypeService.GetAllMediaTypes().ToArray(),
                                          (path, pIndex, pSize) =>
                    {
                        long totalMedia;
                        var result = _mediaService.GetPagedXmlEntries(path, pIndex, pSize, out totalMedia).ToArray();
                        var more   = result.Length == pSize;
                        return(Tuple.Create(result, more));
                    },
                                          i => _mediaService.GetById(i));

                    break;
                }
            }
            finally
            {
                stopwatch.Stop();
            }

            DataService.LogService.AddInfoLog(-1, string.Format("PerformIndexAll - End data queries - {0}, took {1}ms", type, stopwatch.ElapsedMilliseconds));
        }
        /// <summary>
        /// Gets the allowed children
        /// </summary>
        /// <param name="types"></param>
        /// <param name="contentTypeService"></param>
        /// <returns></returns>
        private static IEnumerable<ContentTypeSort> FetchAllowedContentTypes(Type[] types, IContentTypeService contentTypeService)
        {
            if (types == null) return new ContentTypeSort[0];

            List<ContentTypeSort> contentTypeSorts = new List<ContentTypeSort>();

            List<string> aliases = GetAliasesFromTypes(types);

            var contentTypes = contentTypeService.GetAllContentTypes().Where(x => aliases.Contains(x.Alias)).ToArray();

            int length = contentTypes.Length;
            for (int i = 0; i < length; i++)
            {
                ContentTypeSort sort = new ContentTypeSort();
                sort.Alias = contentTypes[i].Alias;
                int id = contentTypes[i].Id;
                sort.Id = new Lazy<int>(() => { return id; });
                sort.SortOrder = i;
                contentTypeSorts.Add(sort);
            }
            return contentTypeSorts;
        }
コード例 #30
0
        // TODO: Move registration to another place
        public UmbracoSchema(
            IContentTypeService contentTypeService,
            IMemberTypeService memberTypeService,
            GraphQLServerOptions options)
        {
            if (contentTypeService == null)
            {
                throw new ArgumentNullException(nameof(contentTypeService));
            }

            FieldNameConverter = new DefaultFieldNameConverter();

            var documentTypes = CreateGraphTypes(contentTypeService.GetAllContentTypes(), PublishedItemType.Content).ToList();
            var mediaTypes    = CreateGraphTypes(contentTypeService.GetAllMediaTypes(), PublishedItemType.Media).ToList();

            //foreach (var documentType in documentTypes.OfType<ComplexGraphType<IPublishedContent>>())
            //{
            //    var allowedChildren = documentType.GetMetadata<string[]>("allowedChildren");
            //    if (allowedChildren == null || allowedChildren.Length == 0) continue;

            //    var childTypes =
            //        documentTypes.FindAll(x =>
            //            allowedChildren.Contains(x.GetMetadata<string>("documentTypeAlias")));

            //    IGraphType childrenGraphType;
            //    if (childTypes.Count == 1)
            //    {
            //        childrenGraphType = childTypes[0];
            //    }
            //    else
            //    {
            //        var unionType = new UnionGraphType()
            //        {
            //            Name = $"{documentType.Name}Children",
            //        };

            //        foreach (var childType in childTypes.OfType<IObjectGraphType>())
            //        {
            //            unionType.AddPossibleType(childType);
            //        }

            //        childrenGraphType = unionType;

            //        RegisterTypes(unionType);
            //    }

            //    documentType.AddField(
            //        new FieldType
            //        {
            //            Name = "children",
            //            Description = "Children of the content.",
            //            Resolver = new FuncFieldResolver<IPublishedContent, object>(context => context.Source.Children),
            //            ResolvedType = new ListGraphType(childrenGraphType)
            //        }
            //    );
            //}

            RegisterTypes(documentTypes.ToArray());
            RegisterTypes(mediaTypes.ToArray());
            // RegisterTypes(memberTypeService.GetAll().CreateGraphTypes(PublishedItemType.Member, resolveName).ToArray());

            Query = new UmbracoQuery(documentTypes);
        }