public void SetAllowedContentTypes(IContentType parentContentType, IContentType[] childContentTypes) { var allowedContentTypes = parentContentType.AllowedContentTypes.ToList(); var count = 0; foreach (var contentType in childContentTypes) { allowedContentTypes.Add(new ContentTypeSort(contentType.Id, count)); count++; } parentContentType.AllowedContentTypes = allowedContentTypes; _contentTypeService.Save(parentContentType); }
public ActionResult <DocumentTypeDisplay> PostSave(DocumentTypeSave contentTypeSave) { //Before we send this model into this saving/mapping pipeline, we need to do some cleanup on variations. //If the doc type does not allow content variations, we need to update all of it's property types to not allow this either //else we may end up with ysods. I'm unsure if the service level handles this but we'll make sure it is updated here if (!contentTypeSave.AllowCultureVariant) { foreach (var prop in contentTypeSave.Groups.SelectMany(x => x.Properties)) { prop.AllowCultureVariant = false; } } var savedCt = PerformPostSave <DocumentTypeDisplay, DocumentTypeSave, PropertyTypeBasic>( contentTypeSave: contentTypeSave, getContentType: i => _contentTypeService.Get(i), saveContentType: type => _contentTypeService.Save(type), beforeCreateNew: ctSave => { //create a default template if it doesn't exist -but only if default template is == to the content type if (ctSave.DefaultTemplate.IsNullOrWhiteSpace() == false && ctSave.DefaultTemplate == ctSave.Alias) { var template = CreateTemplateForContentType(ctSave.Alias, ctSave.Name); // If the alias has been manually updated before the first save, // make sure to also update the first allowed template, as the // name will come back as a SafeAlias of the document type name, // not as the actual document type alias. // For more info: http://issues.umbraco.org/issue/U4-11059 if (ctSave.DefaultTemplate != template.Alias) { var allowedTemplates = ctSave.AllowedTemplates.ToArray(); if (allowedTemplates.Any()) { allowedTemplates[0] = template.Alias; } ctSave.AllowedTemplates = allowedTemplates; } //make sure the template alias is set on the default and allowed template so we can map it back ctSave.DefaultTemplate = template.Alias; } }); if (!(savedCt.Result is null)) { return(savedCt.Result); } var display = _umbracoMapper.Map <DocumentTypeDisplay>(savedCt.Value); display.AddSuccessNotification( _localizedTextService.Localize("speechBubbles", "contentTypeSavedHeader"), string.Empty); return(display); }
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); }
public async Task PostSave_Validate_Existing_Content() { ILocalizationService localizationService = GetRequiredService <ILocalizationService>(); // Add another language localizationService.Save(new LanguageBuilder() .WithCultureInfo(DkIso) .WithIsDefault(false) .Build()); string url = PrepareApiControllerUrl <ContentController>(x => x.PostSave(null)); IContentService contentService = GetRequiredService <IContentService>(); IContentTypeService contentTypeService = GetRequiredService <IContentTypeService>(); IContentType contentType = new ContentTypeBuilder() .WithId(0) .AddPropertyType() .WithAlias("title") .WithValueStorageType(ValueStorageType.Integer) .WithPropertyEditorAlias(Constants.PropertyEditors.Aliases.TextBox) .WithName("Title") .Done() .WithContentVariation(ContentVariation.Nothing) .Build(); contentTypeService.Save(contentType); Content content = new ContentBuilder() .WithId(0) .WithName("Invariant") .WithContentType(contentType) .AddPropertyData() .WithKeyValue("title", "Cool invariant title") .Done() .Build(); contentService.SaveAndPublish(content); ContentItemSave model = new ContentItemSaveBuilder() .WithContent(content) .WithId(-1337) // HERE We overwrite the Id, so we don't expect to find it on the server .Build(); // Act HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent { { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" } }); // Assert Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); //// Assert.AreEqual(")]}',\n{\"Message\":\"content was not found\"}", response.Item1.Content.ReadAsStringAsync().Result); //// //// //var obj = JsonConvert.DeserializeObject<PagedResult<UserDisplay>>(response.Item2); //// //Assert.AreEqual(0, obj.TotalItems); }
public override ContentType Create(int parentId = -1) { foreach (var component in _components) { _contentTypeService.Save(component.Create(parentId)); } return(null); }
public static void AddAllowedDocumentType(IContentTypeService service, string parentAlias, string childAlias, int order = -1) { var parent = service.Get(parentAlias); var child = service.Get(childAlias); var allowed = parent.AllowedContentTypes.ToList(); allowed.Add(new Core.Models.ContentTypeSort(child.Id, order == -1 ? allowed.Count() : order)); parent.AllowedContentTypes = allowed; service.Save(parent); }
/// <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); } }
/// <summary> /// Updates the specified document type. /// </summary> /// <param name="documentType">The document type.</param> private void UpdateDocumentType(IContentType documentType) { var allowedTemplates = GetAllowedTemplates(documentType); var template = allowedTemplates.Single(t => t.Alias == PreviewTemplateAttribute.TemplateName.Alias()); documentType.AllowedTemplates = allowedTemplates; documentType.SetDefaultTemplate(template); _contentTypeService.Save(documentType); }
private void CreateConfirmEmailDocumentType() { try { var container = contentTypeService.GetContainers(CONTAINER, 1).FirstOrDefault(); var containerId = container.Id; var contentType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS); var parentDocType = contentTypeService.Get(PARENT_DOCUMENT_TYPE_ALIAS); if (contentType == null) { ContentType docType = (ContentType)contentType ?? new ContentType(containerId) { Name = DOCUMENT_TYPE_NAME, Alias = DOCUMENT_TYPE_ALIAS, AllowedAsRoot = false, Description = DOCUMENT_TYPE_DESCRIPTION, Icon = ICON, SortOrder = 0, Variations = ContentVariation.Culture, ParentId = parentDocType.Id }; // Create the Template if it doesn't exist if (fileService.GetTemplate(TEMPLATE_ALIAS) == null) { //then create the template Template newTemplate = new Template(TEMPLATE_NAME, TEMPLATE_ALIAS); fileService.SaveTemplate(newTemplate); } // Set templates for document type var template = fileService.GetTemplate(TEMPLATE_ALIAS); docType.AllowedTemplates = new List <ITemplate> { template }; docType.SetDefaultTemplate(template); contentTypeService.Save(docType); // set as allowed content type in home ContentHelper.AddAllowedDocumentType(contentTypeService, Phase2MergedHomeDocumentType.DOCUMENT_TYPE_ALIAS, DOCUMENT_TYPE_ALIAS); ConfigureMasterTemplate(); ConnectorContext.AuditService.Add(AuditType.New, -1, docType.Id, "Document Type", $"Document Type '{DOCUMENT_TYPE_NAME}' has been created"); ContentHelper.CopyPhysicalAssets(new Milestone7EmbeddedResources()); } } catch (System.Exception ex) { logger.Error(typeof(_07_ResetPasswordViaEmailDocumentType), ex.Message); logger.Error(typeof(_07_ResetPasswordViaEmailDocumentType), ex.StackTrace); } }
/// <summary> /// Add a simple content tree to the install /// </summary> public static void ContentType(IContentTypeService contentTypeService, string name = "Textpage") { var type = new ContentType(-1) { Alias = name.ToLower(), Name = name, AllowedAsRoot = true }; contentTypeService.Save(type); }
/// <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); }
private void CreateDocumentType() { try { // generic page var genericType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS); if (genericType != null) { var changed = false; try { if (genericType.PropertyTypeExists("playButtonText")) { genericType.RemovePropertyType("playButtonText"); changed = true; } if (genericType.PropertyTypeExists("demoButtonText")) { genericType.RemovePropertyType("demoButtonText"); changed = true; } if (genericType.PropertyTypeExists("demoPageImages")) { genericType.RemovePropertyType("demoPageImages"); changed = true; } if (genericType.PropertyGroups["Demo Mode"] != null) { genericType.PropertyGroups.Remove("Demo Mode"); changed = true; } if (changed) { contentTypeService.Save(genericType); } } catch { } ConnectorContext.AuditService.Add(AuditType.Save, -1, genericType.Id, "Document Type", $"Document Type '{DOCUMENT_TYPE_ALIAS}' has been updated"); } } catch (Exception ex) { logger.Error(typeof(_21_DemoModeReconfiguration), ex.Message); logger.Error(typeof(_21_DemoModeReconfiguration), ex.StackTrace); } }
public override SyncAttempt <IContentType> DeserializeSecondPass(IContentType item, XElement node, SerializerFlags flags) { DeserializeCompositions(item, node); DeserializeStructure(item, node); if (!flags.HasFlag(SerializerFlags.DoNotSave)) { contentTypeService.Save(item); } CleanFolder(item, node); return(SyncAttempt <IContentType> .Succeed(item.Name, item, ChangeType.Import)); }
private void CreateContentType(Models.SimpleContentType docType) { var contentType = GetContentType(docType); if (docType is ComposedContentType) { AddCompositions((ComposedContentType)docType, contentType); } AddTabs(docType, contentType); AddAllowedContentTypes(docType, contentType); AddTemplate(docType, contentType); _ContentTypeService.Save(contentType); }
private void CreateContentType() { var contentType = InstallationStepsHelper.GetBasePageWithGridBase(CoreInstallationConstants.DocumentTypeAliases.BasePage); contentType.Name = GroupsInstallationConstants.DocumentTypeNames.GroupsMyGroupsOverviewPage; contentType.Alias = GroupsInstallationConstants.DocumentTypeAliases.GroupsMyGroupsOverviewPage; contentType.Icon = GroupsInstallationConstants.DocumentTypeIcons.GroupsMyGroupsOverviewPage; contentType.AddPropertyGroup(CoreInstallationConstants.DataTypePropertyGroupNames.Content); contentType.AddPropertyType(InstallationStepsHelper.GetGridPropertyType(GroupsInstallationConstants.DataTypeNames.GroupGrid), CoreInstallationConstants.DataTypePropertyGroupNames.Content); _contentTypeService.Save(contentType); InstallationStepsHelper.InheritCompositionForPage(contentType.Alias, NavigationInstallationConstants.DocumentTypeAliases.NavigationComposition); InstallationStepsHelper.AddAllowedChildNode(GroupsInstallationConstants.DocumentTypeAliases.GroupsOverviewPage, contentType.Alias); }
public async Task PostSave_Validates_Domains_Exist() { ILocalizationService localizationService = GetRequiredService <ILocalizationService>(); localizationService.Save(new LanguageBuilder() .WithCultureInfo(DkIso) .WithIsDefault(false) .Build()); IContentTypeService contentTypeService = GetRequiredService <IContentTypeService>(); IContentType contentType = new ContentTypeBuilder().WithContentVariation(ContentVariation.Culture).Build(); contentTypeService.Save(contentType); Content content = new ContentBuilder() .WithId(1) .WithContentType(contentType) .WithCultureName(UsIso, "Root") .WithCultureName(DkIso, "Rod") .Build(); ContentItemSave model = new ContentItemSaveBuilder() .WithContent(content) .WithAction(ContentSaveAction.PublishNew) .Build(); var url = PrepareApiControllerUrl <ContentController>(x => x.PostSave(null)); HttpResponseMessage response = await Client.PostAsync(url, new MultipartFormDataContent { { new StringContent(JsonConvert.SerializeObject(model)), "contentItem" } }); var body = await response.Content.ReadAsStringAsync(); body = body.TrimStart(AngularJsonMediaTypeFormatter.XsrfPrefix); ContentItemDisplay display = JsonConvert.DeserializeObject <ContentItemDisplay>(body); ILocalizedTextService localizedTextService = GetRequiredService <ILocalizedTextService>(); var expectedMessage = localizedTextService.Localize("speechBubbles", "publishWithNoDomains"); Assert.Multiple(() => { Assert.IsNotNull(display); Assert.AreEqual(1, display.Notifications.Count(x => x.NotificationType == NotificationStyle.Warning)); Assert.AreEqual(expectedMessage, display.Notifications.FirstOrDefault(x => x.NotificationType == NotificationStyle.Warning)?.Message); }); }
private int?CreateDocumentType(Item item, int parentId, int userId = 0) { ContentType contentType = new ContentType(parentId); contentType.Name = item.Name; contentType.Alias = item.Alias; contentType.Icon = "icon-message"; var textstringDef = new DataTypeDefinition(-1, "Umbraco.Textbox"); var richtextEditorDef = new DataTypeDefinition(-1, "Umbraco.TinyMCEv3"); var textboxMultipleDef = new DataTypeDefinition(-1, "Umbraco.TextboxMultiple"); if (item.Tabs != null && item.Tabs.Any()) { foreach (var tab in item.Tabs) { if (!string.IsNullOrEmpty(tab.Name)) { contentType.AddPropertyGroup(tab.Name); foreach (var property in tab.Properties) { contentType.AddPropertyType( new PropertyType(textstringDef) { Alias = property.Alias, Name = property.Name, Description = "", Mandatory = property.Mandatory, SortOrder = 1 }, tab.Name); } } } } _contentTypeService.Save(contentType); if (contentType != null) { return(contentType.Id); } else { return(parentId); } }
public override ContentType Create(int parentId = -1) { var parentContainer = _contentTypeService.CreateContainer(parentId, _name); if (parentContainer.Success) { var parentNode = _contentTypeService.GetContainers(_name, 1).FirstOrDefault(); foreach (var component in _components) { _contentTypeService.Save(component.Create(parentNode.Id)); } } return(null); }
private void UpdateHomeDocumentType() { try { var contentType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS); var changed = false; if (contentType != null) { #region Telegram and WhatsApp if (!contentType.PropertyTypeExists("telegramUsername")) { PropertyType tenantTelegramPropType = new PropertyType(dataTypeService.GetDataType(-88), "telegramUsername") { Name = "Telegram Username", Description = "The Telegram Username", Variations = ContentVariation.Culture }; contentType.AddPropertyType(tenantTelegramPropType, TAB); changed = true; } if (!contentType.PropertyTypeExists("whatsAppNumber")) { PropertyType tenantWhatsAppPropType = new PropertyType(dataTypeService.GetDataType(-88), "whatsAppNumber") { Name = "WhatsApp Number", Description = "The Full Phone number including country code (+ NOT NECESSARY)", Variations = ContentVariation.Culture }; contentType.AddPropertyType(tenantWhatsAppPropType, TAB); changed = true; } if (changed) { contentTypeService.Save(contentType); } #endregion } } catch (System.Exception ex) { logger.Error(typeof(_27_HomeDocTypeTelegramWhatsApp), ex.Message); logger.Error(typeof(_27_HomeDocTypeTelegramWhatsApp), ex.StackTrace); } }
internal void UpdateContentType(IContentType contentType, PropertyType propertyType) { if (propertyType != null) { IDataTypeDefinition dataTypeDefinition = _dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId); PropertyGroup propertyGroup = contentType.PropertyGroups.FirstOrDefault(o => o.PropertyTypes.Contains(propertyType.Alias)); var allFollowingPropertyTypes = propertyGroup.PropertyTypes.Where(o => o != propertyType && o.SortOrder >= propertyType.SortOrder).OrderBy(o => o.SortOrder).ToList(); var sortOrderIndex = propertyType.SortOrder + 1; if (PropertyHelper.IsLocalizedProperty(propertyType.Alias) == false) { propertyType.Alias = PropertyHelper.GetAlias(propertyType.Alias, LocalizationContext.DefaultCulture.TwoLetterISOLanguageName); } foreach (ILanguage language in LocalizationContext.Languages) { string localizedAlias = PropertyHelper.GetAlias(PropertyHelper.GetNotLocalizedAlias(propertyType.Alias), language.CultureInfo.TwoLetterISOLanguageName); if ((contentType.PropertyTypeExists(localizedAlias) == false || propertyType.Alias.Equals(localizedAlias) == false) && propertyType.PropertyEditorAlias.Equals("OPTEN.UrlAlias", StringComparison.OrdinalIgnoreCase) == false) { PropertyType newPropertyType = new PropertyType(dataTypeDefinition) { Alias = localizedAlias, Name = propertyType.Name, Description = propertyType.Description, SortOrder = sortOrderIndex }; contentType.AddPropertyType(newPropertyType, propertyGroup.Name); newPropertyType.SortOrder = sortOrderIndex; // Somehow umbraco sets a sort order on adding... but not always?!? sortOrderIndex++; } } foreach (var followingPropertyType in allFollowingPropertyTypes) { propertyGroup.PropertyTypes.Single(o => followingPropertyType == o).SortOrder = sortOrderIndex; sortOrderIndex++; } } _contentTypeService.Save(contentType); }
public override SyncAttempt <IContentType> DeserializeSecondPass(IContentType item, XElement node, SyncSerializerOptions options) { logger.Debug <ContentTypeSerializer>("Deserialize Second Pass {0}", item.Alias); var details = new List <uSyncChange>(); details.AddRange(DeserializeCompositions(item, node)); details.AddRange(DeserializeStructure(item, node)); if (!options.Flags.HasFlag(SerializerFlags.DoNotSave) && item.IsDirty()) { contentTypeService.Save(item); } CleanFolder(item, node); return(SyncAttempt <IContentType> .Succeed(item.Name, item, ChangeType.Import, details)); }
private void Reconfigure() { try { var genericDocType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS); // Create the Template if it doesn't exist if (fileService.GetTemplate(TEMPLATE_ALIAS) == null) { //then create the template Template newTemplate = new Template(TEMPLATE_NAME, TEMPLATE_ALIAS); ITemplate masterTemplate = fileService.GetTemplate(PARENT_TEMPLATE_ALIAS); newTemplate.SetMasterTemplate(masterTemplate); fileService.SaveTemplate(newTemplate); // Set template for document type genericDocType.AddTemplate(contentTypeService, newTemplate); ContentHelper.CopyPhysicalAssets(new GamesPagesEmbeddedResources()); ConnectorContext.AuditService.Add(AuditType.Save, -1, newTemplate.Id, "Template", $"Teplate '{TEMPLATE_NAME}' has been created and assigned"); } if (!genericDocType.PropertyTypeExists("gameType")) { PropertyType propType = new PropertyType(dataTypeService.GetDataType(-92), "gameType") { Name = "Game Type", Description = "The game this page will display", Variations = ContentVariation.Nothing }; genericDocType.AddPropertyType(propType, TAB_NAME); contentTypeService.Save(genericDocType); ConnectorContext.AuditService.Add(AuditType.Save, -1, genericDocType.Id, "DocumentType", $"Document Type '{DOCUMENT_TYPE_ALIAS}' has been updated"); } } catch (Exception ex) { logger.Error(typeof(_19_GamePages), ex.Message); logger.Error(typeof(_19_GamePages), ex.StackTrace); } }
private ContentType CreateVariantContentType(IEnumerable <IDataTypeDefinition> allDataTypeDefinitions, IContentTypeService contentTypeService) { ContentType contentType = new ContentType(-1); contentType.Alias = "variant"; contentType.Name = "Variant"; contentType.Icon = "icon-folder"; PropertyGroup contentPropertyGroup = new PropertyGroup(new PropertyTypeCollection(new List <PropertyType> { new PropertyType(allDataTypeDefinitions.FirstOrDefault(d => d.PropertyEditorAlias == "TeaCommerce.StockManagement")) { Alias = "stock", Name = "Stock", Description = "Remember to add a sku for the product. Without a sku the variant cannot have it's own stock.", }, new PropertyType(allDataTypeDefinitions.FirstOrDefault(d => d.PropertyEditorAlias == "Umbraco.Textbox")) { Alias = "productName", Name = "Name", }, new PropertyType(allDataTypeDefinitions.FirstOrDefault(d => d.PropertyEditorAlias == "Umbraco.Textbox")) { Alias = "sku", Name = "Sku", }, new PropertyType(allDataTypeDefinitions.FirstOrDefault(d => d.PropertyEditorAlias == "Umbraco.Textbox")) { Alias = "priceJMD", Name = "Price", ValidationRegExp = @"^(\s*|\d+(?:[,|\.]\d+)?)$", }, })) { Name = "Content" }; contentType.PropertyGroups.Add(contentPropertyGroup); contentTypeService.Save(contentType); return(contentType); }
public override SyncAttempt <IContentType> DeserializeSecondPass(IContentType item, XElement node, SyncSerializerOptions options) { logger.LogDebug("Deserialize Second Pass {0}", item.Alias); var details = new List <uSyncChange>(); SetSafeAliasValue(item, node, false); details.AddRange(DeserializeCompositions(item, node)); details.AddRange(DeserializeStructure(item, node)); // When doing this reflectiony - it doesn't set is dirty. var historyChanges = DeserializeCleanupHistory(item, node); var historyUpdated = historyChanges.Any(x => x.Change > ChangeDetailType.NoChange); details.AddRange(historyChanges); CleanTabAliases(item); // clean tabs details.AddRange(CleanTabs(item, node, options)); bool saveInSerializer = !options.Flags.HasFlag(SerializerFlags.DoNotSave); if (saveInSerializer && (item.IsDirty() || historyUpdated)) { var dirty = string.Join(", ", item.GetDirtyProperties()); dirty += string.Join(", ", item.PropertyGroups.Where(x => x.IsDirty()).Select(x => $"Group:{x.Name}")); dirty += string.Join(", ", item.PropertyTypes.Where(x => x.IsDirty()).Select(x => $"Property:{x.Name}")); dirty += historyUpdated ? " CleanupHistory" : ""; logger.LogDebug("Saving in Serializer because item is dirty [{properties}]", dirty); contentTypeService.Save(item); } CleanFolder(item, node); return(SyncAttempt <IContentType> .Succeed(item.Name, item, ChangeType.Import, "", saveInSerializer, details)); }
private static void SecondPassFitAndFix() { foreach (KeyValuePair <string, XElement> update in updated) { XElement node = update.Value; LogHelper.Debug <uSync>("Second pass {0}", () => update.Value); if (node != null) { // load the doctype IContentType docType = ApplicationContext.Current.Services.ContentTypeService.GetContentType(update.Key); if (docType != null) { LogHelper.Debug <uSync>("Container Type", () => update.Value); // is it a container (in v6 api but only really a v7 thing) docType.ImportContainerType(node); LogHelper.Debug <uSync>("Structure", () => update.Value); // import structure docType.ImportStructure(node); LogHelper.Debug <uSync>("Missing Property Removal", () => update.Value); // delete things that are not in our source xml? docType.ImportRemoveMissingProps(node); LogHelper.Debug <uSync>("Sort order", () => update.Value); // fix tab order docType.ImportTabSortOrder(node); LogHelper.Debug <uSync>("Save", () => update.Value); _contentTypeService.Save(docType); } } } }
private void CreateExampleBlockElementType(string contentTypeAlias) { if (_contentTypeService.Get(contentTypeAlias) != null) { // Already created return; } IContentType contentType = new ContentType(-1) { Alias = contentTypeAlias, IsElement = true, Name = "Example Block", PropertyGroups = new PropertyGroupCollection(new[] { new PropertyGroup(new PropertyTypeCollection(true, new[] { new PropertyType(PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { PropertyEditorAlias = PropertyEditors.Aliases.TextBox, Name = "Title", Alias = "title", }, new PropertyType(PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { PropertyEditorAlias = PropertyEditors.Aliases.TinyMce, Name = "Text", Alias = "text", }, })) { Name = "Content", } }) }; _contentTypeService.Save(contentType); }
/// <summary> /// Registers the specified templates for the given doctype. Creates a basic default cshtml file if none exists at the specified path. /// </summary> public void RegisterTemplates(Type docType) { if (CodeFirstManager.Current.Features.InitialisationMode == InitialisationMode.Passive) { return; } DocumentTypeRegistration reg; if (_documentTypeModule.TryGetDocumentType(docType, out reg)) { var attributes = docType.GetCodeFirstAttributes <TemplateAttribute>(); var type = _contentTypeService.GetContentType(reg.Alias); List <ITemplate> templateList = new List <ITemplate>(); ITemplate defaultTemplate = null; foreach (var attribute in attributes) { if (templateList.Any(x => x.Alias == attribute.TemplateAlias)) { throw new CodeFirstException("Duplicate template aliases specified on " + docType.FullName); } var template = ConfigureTemplate(docType, ref defaultTemplate, attribute); templateList.Add(template); } if (defaultTemplate != null) { type.SetDefaultTemplate(defaultTemplate); } type.AllowedTemplates = templateList; _contentTypeService.Save(type); } else { throw new CodeFirstException(docType.Name + " is not a registered document type. [Template] can only be applied to document types."); } }
private void Reconfigure() { try { var genericDocType = contentTypeService.Get(DOCUMENT_TYPE_ALIAS); var template = (Template)fileService.GetTemplate(TEMPLATE_ALIAS); var alreadyAdded = genericDocType.AllowedTemplates.SingleOrDefault(x => x.Alias == TEMPLATE_ALIAS) != null; if (!alreadyAdded) { genericDocType.AddTemplate(contentTypeService, template); genericDocType.SetDefaultTemplate(template); contentTypeService.Save(genericDocType); } ConnectorContext.AuditService.Add(AuditType.Save, -1, genericDocType.Id, "Document Type", $"Document Type '{DOCUMENT_TYPE_ALIAS}' has been updated"); } catch (Exception ex) { logger.Error(typeof(_26_InPlayGamePageReconfiguration), ex.Message); logger.Error(typeof(_26_InPlayGamePageReconfiguration), ex.StackTrace); } }
public void CreateTestData() { IFileService fileService = GetRequiredService <IFileService>(); Template template = TemplateBuilder.CreateTextPageTemplate(); fileService.SaveTemplate(template); // else, FK violation on contentType! IContentService contentService = GetRequiredService <IContentService>(); IContentTypeService contentTypeService = GetRequiredService <IContentTypeService>(); // Create and Save ContentType "umbTextpage" -> (NodeDto.NodeIdSeed) ContentType contentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); contentType.Key = Guid.NewGuid(); contentTypeService.Save(contentType); // Create and Save Content "Homepage" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 1) _textpage = ContentBuilder.CreateSimpleContent(contentType); _textpage.Key = Guid.NewGuid(); contentService.Save(_textpage); // Create and Save Content "Text Page 1" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 2) _subpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 1", _textpage.Id); _subpage.Key = Guid.NewGuid(); contentService.Save(_subpage); // Create and Save Content "Text Page 1" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 3) _otherpage = ContentBuilder.CreateSimpleContent(contentType, "Text Page 2", _textpage.Id); _otherpage.Key = Guid.NewGuid(); contentService.Save(_otherpage); // Create and Save Content "Text Page Deleted" based on "umbTextpage" -> (NodeDto.NodeIdSeed + 4) _trashed = ContentBuilder.CreateSimpleContent(contentType, "Text Page Deleted", -20); _trashed.Key = Guid.NewGuid(); ((Content)_trashed).Trashed = true; contentService.Save(_trashed); }
public virtual void CreateTestData() { // NOTE Maybe not the best way to create/save test data as we are using the services, which are being tested. Template template = TemplateBuilder.CreateTextPageTemplate(); FileService.SaveTemplate(template); // Create and Save ContentType "umbTextpage" -> 1051 (template), 1052 (content type) ContentType = ContentTypeBuilder.CreateSimpleContentType("umbTextpage", "Textpage", defaultTemplateId: template.Id); ContentType.Key = new Guid("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522"); ContentTypeService.Save(ContentType); // Create and Save Content "Homepage" based on "umbTextpage" -> 1053 Textpage = ContentBuilder.CreateSimpleContent(ContentType); Textpage.Key = new Guid("B58B3AD4-62C2-4E27-B1BE-837BD7C533E0"); ContentService.Save(Textpage, 0); // Create and Save Content "Text Page 1" based on "umbTextpage" -> 1054 Subpage = ContentBuilder.CreateSimpleContent(ContentType, "Text Page 1", Textpage.Id); var contentSchedule = ContentScheduleCollection.CreateWithEntry(DateTime.Now.AddMinutes(-5), null); ContentService.Save(Subpage, 0, contentSchedule); // Create and Save Content "Text Page 1" based on "umbTextpage" -> 1055 Subpage2 = ContentBuilder.CreateSimpleContent(ContentType, "Text Page 2", Textpage.Id); ContentService.Save(Subpage2, 0); Subpage3 = ContentBuilder.CreateSimpleContent(ContentType, "Text Page 3", Textpage.Id); ContentService.Save(Subpage3, 0); // Create and Save Content "Text Page Deleted" based on "umbTextpage" -> 1056 Trashed = ContentBuilder.CreateSimpleContent(ContentType, "Text Page Deleted", -20); Trashed.Trashed = true; ContentService.Save(Trashed, 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); }
/// <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); }
/// <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="mediaType"></param> /// <param name="type"></param> /// <param name="dataTypeService"></param> private static void UpdateMediaType(IContentTypeService contentTypeService, IFileService fileService, UmbracoMediaTypeAttribute attribute, IMediaType mediaType, Type type, IDataTypeService dataTypeService) { mediaType.Name = attribute.MediaTypeName; mediaType.Alias = attribute.MediaTypeAlias; mediaType.Icon = attribute.Icon; mediaType.Description = attribute.Description; mediaType.IsContainer = attribute.EnableListView; mediaType.AllowedContentTypes = FetchAllowedContentTypes(attribute.AllowedChildren, contentTypeService); mediaType.AllowedAsRoot = attribute.AllowedAtRoot; Type parentType = type.BaseType; if (parentType != null && parentType != typeof(UmbracoGeneratedBase) && parentType.GetBaseTypes(false).Any(x => x == typeof(UmbracoGeneratedBase))) { UmbracoMediaTypeAttribute parentAttribute = parentType.GetCustomAttribute<UmbracoMediaTypeAttribute>(); if (parentAttribute != null) { string parentAlias = parentAttribute.MediaTypeAlias; IMediaType parentContentType = contentTypeService.GetMediaType(parentAlias); mediaType.ParentId = parentContentType.Id; } else { throw new Exception("The given base class has no UmbracoMediaTypeAttribute"); } } VerifyProperties(mediaType, type, dataTypeService); //verify if a tab has no properties, if so remove var propertyGroups = mediaType.PropertyGroups.ToArray(); int length = propertyGroups.Length; for (int i = 0; i < length; i++) { if (propertyGroups[i].PropertyTypes.Count == 0) { //remove mediaType.RemovePropertyGroup(propertyGroups[i].Name); } } //persist contentTypeService.Save(mediaType, 0); }