public override string ConvertDbToString(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
			{
				if (property.Value == null || property.Value.ToString() == "")
					return string.Empty;

                //LogHelper.Info<ArchetypeHelper>(property.Value.ToString());

				var archetype = ArchetypeHelper.Instance.DeserializeJsonToArchetype(property.Value.ToString(), propertyType.DataTypeDefinitionId);

				foreach (var fieldset in archetype.Fieldsets)
				{
					foreach (var propDef in fieldset.Properties)
					{
                        try
                        {
						    var dtd = dataTypeService.GetDataTypeDefinitionById(Guid.Parse(propDef.DataTypeGuid));
						    var propType = new PropertyType(dtd) { Alias = propDef.Alias };
						    var prop = new Property(propType, propDef.Value);
						    var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias);
						    propDef.Value = propEditor.ValueEditor.ConvertDbToString(prop, propType, dataTypeService);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error<ArchetypePropertyValueEditor>(ex.Message, ex);
                        }
					}
				}

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

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

                var p = new Property
                {
                    Name = propInfo.Name,
                    Alias = propInfo.Alias,
                    Description = propInfo.Description,
                    Required = propInfo.Mandatory,
                    Validation = propInfo.ValidationRegExp,
                    DataType = service.GetDataTypeDefinitionById(propInfo.DataTypeDefinitionId).Name,
                    Value = (content.Properties.SingleOrDefault(n => n.Alias == propInfo.Alias).Value ?? string.Empty).ToString()
                };
                Properties.Add(p);
            }
        }
Exemple #3
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);
            }
        }
Exemple #4
0
        private IDataTypeDefinition GetDataTypeDefinition(XElement property)
        {
            var dataTypeDefinitionId = new Guid(property.Element("Definition").Value);
            var dataTypeDefinition   = dataTypeService.GetDataTypeDefinitionById(dataTypeDefinitionId);

            var legacyPropertyEditorId = Guid.Empty;

            Guid.TryParse(property.Element("Type").Value, out legacyPropertyEditorId);
            var propertyEditorAlias = property.Element("Type").Value.Trim();

            if (dataTypeDefinition == null)
            {
                var dataTypeDefinitions = dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(propertyEditorAlias);
                if (dataTypeDefinitions != null && dataTypeDefinitions.Any())
                {
                    dataTypeDefinition = dataTypeDefinitions.FirstOrDefault();
                }
            }
            else
            {
#pragma warning disable CS0618 // Type or member is obsolete
                if (legacyPropertyEditorId != Guid.Empty && dataTypeDefinition.ControlId != legacyPropertyEditorId)
#pragma warning restore CS0618 // Type or member is obsolete
                {
#pragma warning disable CS0618 // Type or member is obsolete
                    var dataTypeDefinitions2 = dataTypeService.GetDataTypeDefinitionByControlId(legacyPropertyEditorId);
#pragma warning restore CS0618 // Type or member is obsolete
                    if (dataTypeDefinitions2 != null && dataTypeDefinitions2.Any())
                    {
                        dataTypeDefinition = dataTypeDefinitions2.FirstOrDefault();
                    }
                }
                else
                {
                    if (dataTypeDefinition.PropertyEditorAlias != propertyEditorAlias)
                    {
                        var dataTypeDefinitions3 = dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(propertyEditorAlias);
                        if (dataTypeDefinitions3 != null && dataTypeDefinitions3.Any())
                        {
                            dataTypeDefinition = dataTypeDefinitions3.FirstOrDefault();
                        }
                    }
                }
            }

            if (dataTypeDefinition == null)
            {
                dataTypeDefinition = dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias("Umbraco.NoEdit").FirstOrDefault();
            }
            return(dataTypeDefinition);
        }
Exemple #5
0
        public string GetExportValue(int dataTypeDefinitionId, string value)
        {
            // We need to retrieve the datatype associated with the property so that we can parse the fieldset
            // then we will go through each item in the fieldset and if there is a mapper associated with that item's datatype
            // we should map the property value

            string archetypeConfig = _dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDefinitionId).PreValuesAsDictionary["archetypeConfig"].Value;

            var config = JsonConvert.DeserializeObject <ArchetypePreValue>(archetypeConfig);

            var typedContent = JsonConvert.DeserializeObject <ArchetypeModel>(value);

            foreach (ArchetypePreValueFieldset fieldSet in config.Fieldsets)
            {
                foreach (ArchetypePreValueProperty property in fieldSet.Properties)
                {
                    IDataTypeDefinition dataType = _dataTypeService.GetDataTypeDefinitionById(property.DataTypeGuid);

                    uSyncContentMapping mapping =
                        uSyncCoreContext.Instance.Configuration.Settings.ContentMappings.SingleOrDefault(x => x.EditorAlias == dataType.PropertyEditorAlias);

                    if (mapping != null)
                    {
                        IContentMapper mapper = ContentMapperFactory.GetMapper(mapping);

                        if (mapper != null)
                        {
                            typedContent.Fieldsets.AsQueryable()
                            .SelectMany(fs => fs.Properties)
                            .Where(p => p.Alias == property.Alias)
                            .ForEach(pm => pm.Value = mapper.GetExportValue(dataType.Id, pm.Value.ToString()));
                        }
                    }
                }
            }

            return(typedContent.SerializeForPersistence());
        }
Exemple #6
0
            public override string ConvertDbToString(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
            {
                if (property.Value == null || property.Value.ToString().IsNullOrWhiteSpace())
                {
                    return(string.Empty);
                }

                // Something weird is happening in core whereby ConvertDbToString is getting
                // called loads of times on publish, forcing the property value to get converted
                // again, which in tern screws up the values. To get round it, we create a
                // dummy property copying the original properties value, this way not overwriting
                // the original property value allowing it to be re-converted again later
                var prop2 = new Property(propertyType, property.Value);

                try
                {
                    var value = JsonConvert.DeserializeObject <VortoValue>(property.Value.ToString());
                    if (value.Values != null)
                    {
                        // If the DTD Guid isn't set (probably because someone has made the value manually)
                        // then do a lookup and store it
                        if (value.DtdGuid == Guid.Empty)
                        {
                            var vortoDtd = dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId);
                            value.DtdGuid = vortoDtd.Key;
                        }

                        var dtd        = VortoHelper.GetTargetDataTypeDefinition(value.DtdGuid);
                        var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias);
                        var propType   = new PropertyType(dtd);

                        var keys = value.Values.Keys.ToArray();
                        foreach (var key in keys)
                        {
                            var prop     = new Property(propType, value.Values[key] == null ? null : value.Values[key].ToString());
                            var newValue = propEditor.ValueEditor.ConvertDbToString(prop, propType, dataTypeService);
                            value.Values[key] = newValue;
                        }

                        prop2.Value = JsonConvert.SerializeObject(value);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error <VortoPropertyValueEditor>("Error converting DB value to String", ex);
                }

                return(base.ConvertDbToString(prop2, propertyType, dataTypeService));
            }
Exemple #7
0
        public override SyncAttempt <IDataTypeDefinition> Import(string filePath, bool force = false)
        {
            IDataTypeDefinition item = null;

            var node = XElement.Load(filePath);

            var key = node.Attribute("Key").ValueOrDefault(Guid.Empty);

            if (key != Guid.Empty)
            {
                item = _dataTypeService.GetDataTypeDefinitionById(key);
            }

            return(SyncAttempt <IDataTypeDefinition> .Succeed(Path.GetFileName(filePath), item, ChangeType.Update));
        }
Exemple #8
0
        public static PropertyType CloneUsing(this PropertyType property, IDataTypeService dataTypeService)
        {
            var dataType = dataTypeService.GetDataTypeDefinitionById(property.DataTypeDefinitionId);

            return(new PropertyType(dataType)
            {
                Alias = property.Alias,
                CreateDate = property.CreateDate,
                Description = property.Description,
                Mandatory = property.Mandatory,
                Name = property.Name,
                PropertyEditorAlias = property.PropertyEditorAlias,
                SortOrder = property.SortOrder,
                ValidationRegExp = property.ValidationRegExp
            });
        }
        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));
        }
        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 static int?GetPrevalueIdForIContent(IContent ic, string propertyAlias, string propertyValue)
        {
            //find the property on the content node by its alias
            Property prop = ic.Properties.FirstOrDefault(a => a.Alias == propertyAlias);

            if (prop != null)
            {
                //get data type from the property
                IDataTypeService    dtService    = ApplicationContext.Current.Services.DataTypeService;
                IDataTypeDefinition dtDefinition = dtService.GetDataTypeDefinitionById(prop.PropertyType.DataTypeDefinitionId);

                //Return property value Id
                return(dtService.GetPreValuesCollectionByDataTypeId(dtDefinition.Id).PreValuesAsDictionary.Where(d => d.Value.Value == propertyValue).Select(f => f.Value.Id).First());
            }

            //Return nothing
            return(null);
        }
Exemple #12
0
        /// <summary>
        /// Fix for incompatible Umbraco versions
        /// </summary>
        /// <param name="contentType">Type of the content.</param>
        /// <param name="dt">The dt.</param>
        /// <param name="alias">The alias.</param>
        /// <param name="name">The name.</param>
        /// <param name="tabName">Name of the tab.</param>
        public static void AddPropertyType(IContentTypeBase contentType, DataTypeDefinition dt, string alias, string name, string tabName)
        {
            IDataTypeDefinition idt = DataTypeService.GetDataTypeDefinitionById(dt.Id);

            Umbraco.Core.Models.PropertyType pt = new Umbraco.Core.Models.PropertyType(idt)
            {
                Alias = alias,
                Name  = name
            };

            if (String.IsNullOrEmpty(tabName))
            {
                contentType.AddPropertyType(pt);
            }
            else
            {
                contentType.AddPropertyType(pt, tabName);
            }
        }
Exemple #13
0
        public override XNode ConvertDbToXml(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
        {
            var propertyValue = property?.Value?.ToString();

            if (propertyValue == null || string.IsNullOrWhiteSpace(propertyValue))
            {
                return(base.ConvertDbToXml(property, propertyType, dataTypeService));
            }

            var model = JsonConvert.DeserializeObject <PropertyListValue>(propertyValue);

            if (model == null || model.DataTypeGuid.Equals(Guid.Empty) || model.Values == null)
            {
                return(base.ConvertDbToXml(property, propertyType, dataTypeService));
            }

            var dtd = dataTypeService.GetDataTypeDefinitionById(model.DataTypeGuid);

            if (dtd == null)
            {
                return(base.ConvertDbToXml(property, propertyType, dataTypeService));
            }

            var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias);

            if (propEditor == null)
            {
                return(base.ConvertDbToXml(property, propertyType, dataTypeService));
            }

            var propType = new PropertyType(dtd, propertyType.Alias);

            for (var i = 0; i < model.Values.Count; i++)
            {
                var prop     = new Property(propType, model.Values[i]);
                var newValue = propEditor.ValueEditor.ConvertDbToXml(prop, propType, dataTypeService);
                model.Values[i] = newValue;
            }

            return(new XElement("values",
                                new XAttribute("dtd", model.DataTypeGuid),
                                model.Values.Select(x => new XElement("value", x))));
        }
        /// <summary>
        /// Gets the definition.
        /// </summary>
        /// <param name="dataTypeDefinition">The data type definition.</param>
        /// <returns>The definition.</returns>
        private IDataTypeDefinition GetDefinition(DataTypeDefinition dataTypeDefinition)
        {
            IDataTypeDefinition v;

            if (_mappedDefinitions.TryGetValue(dataTypeDefinition, out v))
            {
                return(v);
            }

            v = _dataTypeService.GetDataTypeDefinitionById((int)dataTypeDefinition);

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

            _mappedDefinitions.Add(dataTypeDefinition, v);

            return(v);
        }
Exemple #15
0
        public static bool IsDataTypeIgnoringUserStartNodes(this IDataTypeService dataTypeService, Guid key)
        {
            if (DataTypeExtensions.IsBuildInDataType(key))
            {
                return(false);                                           //built in ones can never be ignoring start nodes
            }
            var dataType = dataTypeService.GetDataTypeDefinitionById(key);

            if (dataType != null)
            {
                var preValues = dataTypeService.GetPreValuesCollectionByDataTypeId(dataType.Id);
                if (preValues.FormatAsDictionary().TryGetValue(
                        Constants.DataTypes.ReservedPreValueKeys.IgnoreUserStartNodes, out var preValue))
                {
                    return(preValue.Value.InvariantEquals("1"));
                }
            }

            return(false);
        }
Exemple #16
0
        public override object ConvertDbToEditor(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
        {
            var propertyValue = property?.Value?.ToString();

            if (propertyValue == null || string.IsNullOrWhiteSpace(propertyValue))
            {
                return(base.ConvertDbToEditor(property, propertyType, dataTypeService));
            }

            var items = JsonConvert.DeserializeObject <TupleValueItems>(propertyValue);

            if (items == null || items.Count == 0)
            {
                return(base.ConvertDbToEditor(property, propertyType, dataTypeService));
            }

            foreach (var item in items)
            {
                // Get the associated datatype definition
                var dtd = dataTypeService.GetDataTypeDefinitionById(item.DataTypeGuid); // TODO: Caching? [LK:2018-06-25]
                if (dtd == null)
                {
                    continue;
                }

                // Lookup the property editor and convert the db to editor value
                var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias); // TODO: Caching? [LK:2018-06-25]
                if (propEditor == null)
                {
                    continue;
                }

                var propType = new PropertyType(dtd, propertyType.Alias);
                var prop     = new Property(propType, item.Value);

                item.Value = propEditor.ValueEditor.ConvertDbToEditor(prop, propType, dataTypeService);
            }

            // Return the strongly-typed object, Umbraco will handle the JSON serializing/parsing, then Angular can handle it directly
            return(items);
        }
Exemple #17
0
        public override XNode ConvertDbToXml(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
        {
            var propertyValue = property?.Value?.ToString();

            if (propertyValue == null || string.IsNullOrWhiteSpace(propertyValue))
            {
                return(base.ConvertDbToXml(property, propertyType, dataTypeService));
            }

            var items = JsonConvert.DeserializeObject <TupleValueItems>(propertyValue);

            if (items == null || items.Count == 0)
            {
                return(base.ConvertDbToXml(property, propertyType, dataTypeService));
            }

            foreach (var item in items)
            {
                var dtd = dataTypeService.GetDataTypeDefinitionById(item.DataTypeGuid); // TODO: Caching? [LK:2018-06-25]
                if (dtd == null)
                {
                    continue;
                }

                var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias); // TODO: Caching? [LK:2018-06-25]
                if (propEditor == null)
                {
                    continue;
                }

                var propType = new PropertyType(dtd, propertyType.Alias);
                var prop     = new Property(propType, item.Value);

                item.DataTypeUdi = dtd.GetUdi();
                item.Value       = propEditor.ValueEditor.ConvertDbToXml(prop, propType, dataTypeService);
            }

            return(new XElement("values", items.Select(x => new XElement("value", new XAttribute("udi", x.DataTypeUdi), x.Value))));
        }
Exemple #18
0
        public override uSyncAction DeleteItem(Guid key, string keyString)
        {
            IDataTypeDefinition item = null;

            if (key != Guid.Empty)
            {
                item = _dataTypeService.GetDataTypeDefinitionById(key);
            }

            /* delete only by key
             * if (item == null && !string.IsNullOrEmpty(keyString))
             *  item = _dataTypeService.GetDataTypeDefinitionByName(keyString);
             */

            if (item != null)
            {
                LogHelper.Info <DataTypeHandler>("Deleting datatype: {0}", () => item.Name);
                _dataTypeService.Delete(item);
                return(uSyncAction.SetAction(true, keyString, typeof(IDataTypeDefinition), ChangeType.Delete, "Removed"));
            }

            return(uSyncAction.Fail(keyString, typeof(IDataTypeDefinition), ChangeType.Delete, "Not found"));
        }
        /// <summary>
        /// Exports an <see cref="IContentType"/> item to xml as an <see cref="XElement"/>
        /// </summary>
        /// <param name="dataTypeService"></param>
        /// <param name="contentTypeService"></param>
        /// <param name="contentType">Content type to export</param>
        /// <returns><see cref="XElement"/> containing the xml representation of the IContentType object</returns>
        public XElement Serialize(IDataTypeService dataTypeService, IContentTypeService contentTypeService, IContentType contentType)
        {
            var info = new XElement("Info",
                                    new XElement("Name", contentType.Name),
                                    new XElement("Alias", contentType.Alias),
                                    new XElement("Icon", contentType.Icon),
                                    new XElement("Thumbnail", contentType.Thumbnail),
                                    new XElement("Description", contentType.Description),
                                    new XElement("AllowAtRoot", contentType.AllowedAsRoot.ToString()),
                                    new XElement("IsListView", contentType.IsContainer.ToString()));

            var masterContentType = contentType.ContentTypeComposition.FirstOrDefault(x => x.Id == contentType.ParentId);

            if (masterContentType != null)
            {
                info.Add(new XElement("Master", masterContentType.Alias));
            }

            var compositionsElement = new XElement("Compositions");
            var compositions        = contentType.ContentTypeComposition;

            foreach (var composition in compositions)
            {
                compositionsElement.Add(new XElement("Composition", composition.Alias));
            }
            info.Add(compositionsElement);

            var allowedTemplates = new XElement("AllowedTemplates");

            foreach (var template in contentType.AllowedTemplates)
            {
                allowedTemplates.Add(new XElement("Template", template.Alias));
            }
            info.Add(allowedTemplates);

            if (contentType.DefaultTemplate != null && contentType.DefaultTemplate.Id != 0)
            {
                info.Add(new XElement("DefaultTemplate", contentType.DefaultTemplate.Alias));
            }
            else
            {
                info.Add(new XElement("DefaultTemplate", ""));
            }

            var structure = new XElement("Structure");

            foreach (var allowedType in contentType.AllowedContentTypes)
            {
                structure.Add(new XElement("DocumentType", allowedType.Alias));
            }

            var genericProperties = new XElement("GenericProperties"); // actually, all of them

            foreach (var propertyType in contentType.PropertyTypes)
            {
                var definition = dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId);

                var propertyGroup = propertyType.PropertyGroupId == null // true generic property
                    ? null
                    : contentType.PropertyGroups.FirstOrDefault(x => x.Id == propertyType.PropertyGroupId.Value);

                var genericProperty = new XElement("GenericProperty",
                                                   new XElement("Name", propertyType.Name),
                                                   new XElement("Alias", propertyType.Alias),
                                                   new XElement("Type", propertyType.PropertyEditorAlias),
                                                   new XElement("Definition", definition.Key),
                                                   new XElement("Tab", propertyGroup == null ? "" : propertyGroup.Name),
                                                   new XElement("SortOrder", propertyType.SortOrder),
                                                   new XElement("Mandatory", propertyType.Mandatory.ToString()),
                                                   propertyType.ValidationRegExp != null ? new XElement("Validation", propertyType.ValidationRegExp) : null,
                                                   propertyType.Description != null ? new XElement("Description", new XCData(propertyType.Description)) : null);

                genericProperties.Add(genericProperty);
            }

            var tabs = new XElement("Tabs");

            foreach (var propertyGroup in contentType.PropertyGroups)
            {
                var tab = new XElement("Tab",
                                       new XElement("Id", propertyGroup.Id.ToString(CultureInfo.InvariantCulture)),
                                       new XElement("Caption", propertyGroup.Name),
                                       new XElement("SortOrder", propertyGroup.SortOrder));
                tabs.Add(tab);
            }

            var xml = new XElement("DocumentType",
                                   info,
                                   structure,
                                   genericProperties,
                                   tabs);

            var folderNames = string.Empty;

            //don't add folders if this is a child doc type
            if (contentType.Level != 1 && masterContentType == null)
            {
                //get url encoded folder names
                var folders = contentTypeService.GetContentTypeContainers(contentType)
                              .OrderBy(x => x.Level)
                              .Select(x => HttpUtility.UrlEncode(x.Name));

                folderNames = string.Join("/", folders.ToArray());
            }

            if (string.IsNullOrWhiteSpace(folderNames) == false)
            {
                xml.Add(new XAttribute("Folders", folderNames));
            }

            return(xml);
        }
        public XElement Serialize(IDataTypeService dataTypeService, IMediaType mediaType)
        {
            var info = new XElement("Info",
                                    new XElement("Name", mediaType.Name),
                                    new XElement("Alias", mediaType.Alias),
                                    new XElement("Icon", mediaType.Icon),
                                    new XElement("Thumbnail", mediaType.Thumbnail),
                                    new XElement("Description", mediaType.Description),
                                    new XElement("AllowAtRoot", mediaType.AllowedAsRoot.ToString()));

            var masterContentType = mediaType.CompositionAliases().FirstOrDefault();

            if (masterContentType != null)
            {
                info.Add(new XElement("Master", masterContentType));
            }

            var structure = new XElement("Structure");

            foreach (var allowedType in mediaType.AllowedContentTypes)
            {
                structure.Add(new XElement("MediaType", allowedType.Alias));
            }

            var genericProperties = new XElement("GenericProperties"); // actually, all of them

            foreach (var propertyType in mediaType.PropertyTypes)
            {
                var definition = dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId);

                var propertyGroup = propertyType.PropertyGroupId == null // true generic property
                    ? null
                    : mediaType.PropertyGroups.FirstOrDefault(x => x.Id == propertyType.PropertyGroupId.Value);

                var genericProperty = new XElement("GenericProperty",
                                                   new XElement("Name", propertyType.Name),
                                                   new XElement("Alias", propertyType.Alias),
                                                   new XElement("Type", propertyType.PropertyEditorAlias),
                                                   new XElement("Definition", definition.Key),
                                                   new XElement("Tab", propertyGroup == null ? "" : propertyGroup.Name),
                                                   new XElement("Mandatory", propertyType.Mandatory.ToString()),
                                                   new XElement("Validation", propertyType.ValidationRegExp),
                                                   new XElement("Description", new XCData(propertyType.Description)));
                genericProperties.Add(genericProperty);
            }

            var tabs = new XElement("Tabs");

            foreach (var propertyGroup in mediaType.PropertyGroups)
            {
                var tab = new XElement("Tab",
                                       new XElement("Id", propertyGroup.Id.ToString(CultureInfo.InvariantCulture)),
                                       new XElement("Caption", propertyGroup.Name),
                                       new XElement("SortOrder", propertyGroup.SortOrder));

                tabs.Add(tab);
            }

            var xml = new XElement("MediaType",
                                   info,
                                   structure,
                                   genericProperties,
                                   tabs);

            return(xml);
        }
Exemple #21
0
        private IDataTypeDefinition GetDataTypeDefinitionByEnum(UmbracoPropertyTypeEnum propertyTypeEnum)
        {
            var result = _dataTypeService.GetDataTypeDefinitionById((int)propertyTypeEnum);

            return(result);
        }
        /// <summary>
        /// Adds the container (listview) tab to the document
        /// </summary>
        /// <typeparam name="TPersisted"></typeparam>
        /// <param name="display"></param>
        /// <param name="entityType">This must be either 'content' or 'media'</param>
        /// <param name="dataTypeService"></param>
        /// <param name="localizedTextService"></param>
        internal static void AddListView <TPersisted>(TabbedContentItem <ContentPropertyDisplay, TPersisted> display, string entityType, IDataTypeService dataTypeService, ILocalizedTextService localizedTextService)
            where TPersisted : IContentBase
        {
            int dtdId;
            var customDtdName = Constants.Conventions.DataTypes.ListViewPrefix + display.ContentTypeAlias;

            switch (entityType)
            {
            case "content":
                dtdId = Constants.System.DefaultContentListViewDataTypeId;

                break;

            case "media":
                dtdId = Constants.System.DefaultMediaListViewDataTypeId;
                break;

            case "member":
                dtdId = Constants.System.DefaultMembersListViewDataTypeId;
                break;

            default:
                throw new ArgumentOutOfRangeException("entityType does not match a required value");
            }

            //first try to get the custom one if there is one
            var dt = dataTypeService.GetDataTypeDefinitionByName(customDtdName)
                     ?? dataTypeService.GetDataTypeDefinitionById(dtdId);

            if (dt == null)
            {
                throw new InvalidOperationException("No list view data type was found for this document type, ensure that the default list view data types exists and/or that your custom list view data type exists");
            }

            var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dt.Id);

            var editor = PropertyEditorResolver.Current.GetByAlias(dt.PropertyEditorAlias);

            if (editor == null)
            {
                throw new NullReferenceException("The property editor with alias " + dt.PropertyEditorAlias + " does not exist");
            }

            var listViewTab = new Tab <ContentPropertyDisplay>();

            listViewTab.Alias    = Constants.Conventions.PropertyGroups.ListViewGroupName;
            listViewTab.Label    = localizedTextService.Localize("content/childItems");
            listViewTab.Id       = display.Tabs.Count() + 1;
            listViewTab.IsActive = true;

            var listViewConfig = editor.PreValueEditor.ConvertDbToEditor(editor.DefaultPreValues, preVals);

            //add the entity type to the config
            listViewConfig["entityType"] = entityType;

            //Override Tab Label if tabName is provided
            if (listViewConfig.ContainsKey("tabName"))
            {
                var configTabName = listViewConfig["tabName"];
                if (configTabName != null && string.IsNullOrWhiteSpace(configTabName.ToString()) == false)
                {
                    listViewTab.Label = configTabName.ToString();
                }
            }

            var listViewProperties = new List <ContentPropertyDisplay>();

            listViewProperties.Add(new ContentPropertyDisplay
            {
                Alias     = string.Format("{0}containerView", Constants.PropertyEditors.InternalGenericPropertiesPrefix),
                Label     = "",
                Value     = null,
                View      = editor.ValueEditor.View,
                HideLabel = true,
                Config    = listViewConfig
            });
            listViewTab.Properties = listViewProperties;

            SetChildItemsTabPosition(display, listViewConfig, listViewTab);
        }
        public bool Execute(string packageName, XmlNode xmlData)
        {
            IMediaService       mediaService       = ApplicationContext.Current.Services.MediaService;
            IContentService     contentService     = UmbracoContext.Current.Application.Services.ContentService;
            IContentTypeService contentTypeService = ApplicationContext.Current.Services.ContentTypeService;
            IFileService        fileService        = ApplicationContext.Current.Services.FileService;
            //ApplicationContext.Current.Services.DataTypeService.
            IDataTypeService dataTypeService = UmbracoContext.Current.Application.Services.DataTypeService;

            #region Create media
            List <int>    productImageIds = new List <int>();
            List <IMedia> productImages   = new List <IMedia>();
            try {
                //Create image files
                const string productImagesFolderName = "Product images";
                string[]     mediaInstallImages      = Directory.GetFiles(HostingEnvironment.MapPath("~/Assets/InstallMedia"));
                IMedia       productImagesFolder     = mediaService.GetByLevel(1).FirstOrDefault(m => m.Name == productImagesFolderName);
                if (productImagesFolder == null)
                {
                    productImagesFolder = mediaService.CreateMedia(productImagesFolderName, -1, "Folder");
                    mediaService.Save(productImagesFolder);
                }

                if (!productImagesFolder.Children().Any())
                {
                    foreach (string mediaInstallImage in mediaInstallImages)
                    {
                        string fileName     = Path.GetFileName(mediaInstallImage);
                        IMedia productImage = mediaService.CreateMedia(fileName, productImagesFolder.Id, "Image");
                        byte[] buffer       = File.ReadAllBytes(Path.GetFullPath(mediaInstallImage));
                        using (MemoryStream strm = new MemoryStream(buffer)) {
                            productImage.SetValue("umbracoFile", fileName, strm);
                            mediaService.Save(productImage);
                            productImages.Add(productImage);
                            productImageIds.Add(productImage.Id);
                        }
                    }
                }
                else
                {
                    productImageIds = productImagesFolder.Children().Select(c => c.Id).ToList();
                }

                Directory.Delete(HostingEnvironment.MapPath("~/Assets/InstallMedia"), true);
            } catch (Exception ex) {
                LogHelper.Error <TeaCommerceStarterKitInstall>("Create media failed", ex);
            }
            #endregion

            #region Set up Tea Commerce
            Store store = null;
            try {
                //Get store or create it
                IReadOnlyList <Store> stores = StoreService.Instance.GetAll().ToList();
                store = stores.FirstOrDefault();
                if (store == null)
                {
                    store = new Store("Starter Kit Store");
                }

                store.ProductSettings.ProductVariantPropertyAlias = "variants";
                store.Save();

                foreach (PaymentMethod paymentMethod in PaymentMethodService.Instance.GetAll(store.Id).Where(p => p.Alias == "invoicing"))
                {
                    PaymentMethodSetting setting = paymentMethod.Settings.FirstOrDefault(s => s.Key == "acceptUrl");
                    if (setting != null)
                    {
                        setting.Value = "/cart-content/confirmation/";
                    }
                    paymentMethod.Save();
                }
            } catch (Exception ex) {
                LogHelper.Error <TeaCommerceStarterKitInstall>("Setting up Tea Commerce failed", ex);
            }
            #endregion

            #region Create Templates
            List <ITemplate> templates = new List <ITemplate>();
            try {
                string[] templateFiles = Directory.GetFiles(HostingEnvironment.MapPath("~/views"));
                foreach (string templateFile in templateFiles)
                {
                    string fileName    = Path.GetFileNameWithoutExtension(templateFile);
                    string fileContent = File.ReadAllText(templateFile);
                    templates.Add(fileService.CreateTemplateWithIdentity(fileName, fileContent));
                }
            } catch (Exception ex) {
                LogHelper.Error <TeaCommerceStarterKitInstall>("Create templates failed", ex);
            }
            #endregion

            #region Set up content types

            IEnumerable <IDataTypeDefinition> allDataTypeDefinitions = dataTypeService.GetAllDataTypeDefinitions();
            try {
                IDataTypeDefinition variantEditorDataTypeDefinition = allDataTypeDefinitions.FirstOrDefault(d => d.Name.ToLowerInvariant().Contains("variant editor"));
                variantEditorDataTypeDefinition.DatabaseType = DataTypeDatabaseType.Ntext;

                var preValDictionary = new Dictionary <string, object> {
                    { "xpathOrNode", "{\"showXPath\": true,\"query\": \"$current/ancestor-or-self::frontpage/attributes\"}" },
                    { "variantDocumentType", "variant" },
                    { "extraListInformation", "sku,priceJMD" },
                    { "hideLabel", "1" },
                };
                var currVal = dataTypeService.GetPreValuesCollectionByDataTypeId(variantEditorDataTypeDefinition.Id);

                //we need to allow for the property editor to deserialize the prevalues
                PropertyEditor pe           = PropertyEditorResolver.Current.PropertyEditors.SingleOrDefault(x => x.Alias == "TeaCommerce.VariantEditor");
                var            formattedVal = pe.PreValueEditor.ConvertEditorToDb(preValDictionary, currVal);
                dataTypeService.SaveDataTypeAndPreValues(variantEditorDataTypeDefinition, formattedVal);
                //dataTypeService.Save( variantEditorDataTypeDefinition );
                variantEditorDataTypeDefinition = dataTypeService.GetDataTypeDefinitionById(variantEditorDataTypeDefinition.Id);
            } catch (Exception ex) {
                LogHelper.Error <TeaCommerceStarterKitInstall>("Set up content types failed", ex);
            }
            #endregion

            #region Create Document types
            ContentType attributeContentType      = null,
                        attributeGroupContentType = null,
                        attributesContentType     = null,
                        cartStepContentType       = null,
                        cartContentType           = null,
                        variantContentType        = null,
                        productContentType        = null,
                        productListContentType    = null,
                        frontpageContentType      = null;
            try {
                attributeContentType       = new ContentType(-1);
                attributeContentType.Alias = "attribute";
                attributeContentType.Name  = "Attribute";
                attributeContentType.Icon  = "icon-t-shirt";
                contentTypeService.Save(attributeContentType);

                attributeGroupContentType       = new ContentType(-1);
                attributeGroupContentType.Alias = "attributeGroup";
                attributeGroupContentType.Name  = "Attribute group";
                attributeGroupContentType.Icon  = "icon-t-shirt color-orange";
                attributeGroupContentType.AllowedContentTypes = new List <ContentTypeSort>()
                {
                    new ContentTypeSort(attributeContentType.Id, 0)
                };
                contentTypeService.Save(attributeGroupContentType);

                attributesContentType       = new ContentType(-1);
                attributesContentType.Alias = "attributes";
                attributesContentType.Name  = "Attributes";
                attributesContentType.Icon  = "icon-t-shirt";
                attributesContentType.AllowedContentTypes = new List <ContentTypeSort>()
                {
                    new ContentTypeSort(attributeGroupContentType.Id, 0)
                };
                contentTypeService.Save(attributesContentType);

                cartStepContentType                  = new ContentType(-1);
                cartStepContentType.Alias            = "cartStep";
                cartStepContentType.Name             = "Cart step";
                cartStepContentType.Icon             = "icon-shopping-basket-alt-2 color-orange";
                cartStepContentType.AllowedTemplates = templates.Where(t => t.Alias.ToLowerInvariant().Contains("cartstep") && !t.Alias.ToLowerInvariant().Contains("master"));
                contentTypeService.Save(cartStepContentType);

                cartContentType       = new ContentType(-1);
                cartContentType.Alias = "cart";
                cartContentType.Name  = "Cart";
                cartContentType.Icon  = "icon-shopping-basket-alt-2";
                cartContentType.AllowedContentTypes = new List <ContentTypeSort>()
                {
                    new ContentTypeSort(cartStepContentType.Id, 0)
                };
                cartContentType.AllowedTemplates = templates.Where(t => t.Alias.ToLowerInvariant().Contains("cartstep1"));
                contentTypeService.Save(cartContentType);

                variantContentType = CreateVariantContentType(allDataTypeDefinitions, contentTypeService);
                productContentType = CreateProductContentType(allDataTypeDefinitions, contentTypeService, templates);

                productListContentType       = new ContentType(-1);
                productListContentType.Alias = "productList";
                productListContentType.Name  = "Product list";
                productListContentType.Icon  = "icon-tags";
                productListContentType.AllowedContentTypes = new List <ContentTypeSort>()
                {
                    new ContentTypeSort(productContentType.Id, 0)
                };
                productListContentType.AllowedTemplates = templates.Where(t => t.Alias.ToLowerInvariant().Contains("productlist"));
                contentTypeService.Save(productListContentType);

                frontpageContentType = CreateFrontpageContentType(allDataTypeDefinitions, contentTypeService, templates);
            } catch (Exception ex) {
                LogHelper.Error <TeaCommerceStarterKitInstall>("Create templates failed", ex);
            }
            #endregion

            #region Create content
            try {
                Content frontPageContent = new Content("Home", -1, frontpageContentType);
                frontPageContent.Template = frontpageContentType.AllowedTemplates.First();
                frontPageContent.SetValue("slider", string.Join(",", productImages.Select(p => "umb://media/" + p.Key.ToString().Replace("-", ""))));
                frontPageContent.SetValue("store", store.Id);
                contentService.SaveAndPublishWithStatus(frontPageContent, raiseEvents: false);

                #region Create Cart
                Content cartContent = new Content("Cart content", frontPageContent.Id, cartContentType);
                cartContent.Template = cartContentType.AllowedTemplates.First();
                contentService.SaveAndPublishWithStatus(cartContent, raiseEvents: false);
                Content informationContent = new Content("Information", cartContent.Id, cartStepContentType);
                informationContent.Template = templates.First(t => t.Alias.ToLowerInvariant() == "cartstep2");
                contentService.SaveAndPublishWithStatus(informationContent, raiseEvents: false);
                Content shippingPaymentContent = new Content("Shipping/Payment", cartContent.Id, cartStepContentType);
                shippingPaymentContent.Template = templates.First(t => t.Alias.ToLowerInvariant() == "cartstep3");
                contentService.SaveAndPublishWithStatus(shippingPaymentContent, raiseEvents: false);
                Content acceptContent = new Content("Accept", cartContent.Id, cartStepContentType);
                acceptContent.Template = templates.First(t => t.Alias.ToLowerInvariant() == "cartstep4");
                contentService.SaveAndPublishWithStatus(acceptContent, raiseEvents: false);
                Content paymentContent = new Content("Payment", cartContent.Id, cartStepContentType);
                contentService.SaveAndPublishWithStatus(paymentContent);
                Content confirmationContent = new Content("Confirmation", cartContent.Id, cartStepContentType);
                confirmationContent.Template = templates.First(t => t.Alias.ToLowerInvariant() == "cartstep6");
                contentService.SaveAndPublishWithStatus(confirmationContent, raiseEvents: false);
                #endregion

                #region Create Attributes
                Content variantAttributesContent = new Content("Variant attributes", frontPageContent.Id, attributesContentType);
                contentService.SaveAndPublishWithStatus(variantAttributesContent, raiseEvents: false);
                Content colorContent = new Content("Color", variantAttributesContent.Id, attributeGroupContentType);
                contentService.SaveAndPublishWithStatus(colorContent, raiseEvents: false);
                Content sizeContent = new Content("Size", variantAttributesContent.Id, attributeGroupContentType);
                contentService.SaveAndPublishWithStatus(sizeContent, raiseEvents: false);
                Content blackContent = new Content("Black", colorContent.Id, attributeContentType);
                contentService.SaveAndPublishWithStatus(blackContent, raiseEvents: false);
                Content whiteContent = new Content("White", colorContent.Id, attributeContentType);
                contentService.SaveAndPublishWithStatus(whiteContent, raiseEvents: false);
                Content blueContent = new Content("Blue", colorContent.Id, attributeContentType);
                contentService.SaveAndPublishWithStatus(blueContent, raiseEvents: false);
                Content largeContent = new Content("Large", sizeContent.Id, attributeContentType);
                contentService.SaveAndPublishWithStatus(largeContent, raiseEvents: false);
                Content mediumContent = new Content("Medium", sizeContent.Id, attributeContentType);
                contentService.SaveAndPublishWithStatus(mediumContent, raiseEvents: false);
                Content smallContent = new Content("Small", sizeContent.Id, attributeContentType);
                contentService.SaveAndPublishWithStatus(smallContent, raiseEvents: false);
                #endregion

                #region Create Products
                Content expensiveYachtsContent = new Content("Expensive Yachts", frontPageContent.Id, productListContentType);
                expensiveYachtsContent.Template = productListContentType.AllowedTemplates.First();
                contentService.SaveAndPublishWithStatus(expensiveYachtsContent, raiseEvents: false);
                Content veryAxpensiveYachtsContent = new Content("Very expensive Yachts", frontPageContent.Id, productListContentType);
                veryAxpensiveYachtsContent.Template = productListContentType.AllowedTemplates.First();
                contentService.SaveAndPublishWithStatus(veryAxpensiveYachtsContent, raiseEvents: false);
                Content summerYachtContent = new Content("Summer Yacht", expensiveYachtsContent, productContentType);
                summerYachtContent.Template = productContentType.AllowedTemplates.First();
                summerYachtContent.SetValue("image", "umb://media/" + productImages[0].Key.ToString().Replace("-", ""));
                summerYachtContent.SetValue("productName", "Summer Yacht");
                summerYachtContent.SetValue("sku", "p0001");
                summerYachtContent.SetValue("priceJMD", "500");
                summerYachtContent.SetValue("description", "<p>This is the product description.</p>");
                summerYachtContent.SetValue("variants", "{\"variants\": [],\"variantGroupsOpen\":{}}");
                contentService.SaveAndPublishWithStatus(summerYachtContent, raiseEvents: false);
                Content yachtWithSailsContent = new Content("Yacht with sails", expensiveYachtsContent, productContentType);
                yachtWithSailsContent.Template = productContentType.AllowedTemplates.First();
                yachtWithSailsContent.SetValue("image", "umb://media/" + productImages[1].Key.ToString().Replace("-", ""));
                yachtWithSailsContent.SetValue("productName", "Yacht with sails");
                yachtWithSailsContent.SetValue("sku", "p0002");
                yachtWithSailsContent.SetValue("priceJMD", "1000");
                yachtWithSailsContent.SetValue("description", "<p>This is the product description.</p>");
                yachtWithSailsContent.SetValue("variants", "{\"variants\": [],\"variantGroupsOpen\":{}}");
                contentService.SaveAndPublishWithStatus(yachtWithSailsContent, raiseEvents: false);
                Content motorDrivenYachtContent = new Content("Motor driven Yacht", veryAxpensiveYachtsContent, productContentType);
                motorDrivenYachtContent.Template = productContentType.AllowedTemplates.First();
                motorDrivenYachtContent.SetValue("image", "umb://media/" + productImages[2].Key.ToString().Replace("-", ""));
                motorDrivenYachtContent.SetValue("productName", "Motor driven Yacht");
                motorDrivenYachtContent.SetValue("sku", "p0003");
                motorDrivenYachtContent.SetValue("priceJMD", "1500");
                motorDrivenYachtContent.SetValue("description", "<p>This is the product description.</p>");
                motorDrivenYachtContent.SetValue("variants", "{\"variants\": [],\"variantGroupsOpen\":{}}");
                contentService.SaveAndPublishWithStatus(motorDrivenYachtContent, raiseEvents: false);
                Content oneMastedYachtContent = new Content("One masted yacht", veryAxpensiveYachtsContent, productContentType);
                oneMastedYachtContent.Template = productContentType.AllowedTemplates.First();
                oneMastedYachtContent.SetValue("image", "umb://media/" + productImages[3].Key.ToString().Replace("-", ""));
                oneMastedYachtContent.SetValue("productName", "One masted yacht");
                oneMastedYachtContent.SetValue("sku", "p0004");
                oneMastedYachtContent.SetValue("priceJMD", "2000");
                oneMastedYachtContent.SetValue("description", "<p>This is the product description.</p>");
                oneMastedYachtContent.SetValue("variants", "{\"variants\": [],\"variantGroupsOpen\":{}}");


                contentService.SaveAndPublishWithStatus(oneMastedYachtContent, raiseEvents: false);


                #endregion
                frontPageContent.SetValue("featuredProducts", string.Join(",", new List <string> {
                    "umb://document/" + summerYachtContent.Key.ToString().Replace("-", ""),
                    "umb://document/" + yachtWithSailsContent.Key.ToString().Replace("-", ""),
                    "umb://document/" + motorDrivenYachtContent.Key.ToString().Replace("-", ""),
                    "umb://document/" + oneMastedYachtContent.Key.ToString().Replace("-", ""),
                }));
                contentService.SaveAndPublishWithStatus(frontPageContent, raiseEvents: false);
            } catch (Exception ex) {
                LogHelper.Error <TeaCommerceStarterKitInstall>("Create content failed", ex);
            }

            #endregion


            return(true);
        }
            public override object ConvertDbToEditor(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
            {
                var propertyValue = property?.Value?.ToString();

                if (propertyValue.IsNullOrWhiteSpace())
                {
                    return(string.Empty);
                }

                // Something weird is happening in core whereby ConvertDbToEditor is getting
                // called loads of times on publish, forcing the property value to get converted
                // again, which in tern screws up the values. To get round it, we create a
                // dummy property copying the original properties value, this way not overwriting
                // the original property value allowing it to be re-converted again later
                var prop2 = new Property(propertyType, property.Value);

                try
                {
                    VortoValue value = null;

                    // Does the value look like JSON and does it look like a vorto value?
                    if (propertyValue.DetectIsJson() && propertyValue.IndexOf("dtdGuid") != -1)
                    {
                        value = JsonConvert.DeserializeObject <VortoValue>(propertyValue);
                    }
                    else
                    {
                        // Doesn't look like a vorto value so we are going to assume it got converted
                        // from a normal prop editor to a vorto editor, so lets construct a VortoValue
                        var dataTypeDef = dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId);

                        string primaryLanguage = null;

                        // Look for primary language in prevalues
                        var preValues = dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDef.Id)?.PreValuesAsDictionary;
                        if (preValues != null)
                        {
                            // We need to store the current value inder a language key so try and find the best key to store it under
                            primaryLanguage = preValues.ContainsKey("primaryLanguage") && !preValues["primaryLanguage"].Value.IsNullOrWhiteSpace()
                                                                ? preValues["primaryLanguage"].Value
                                                                : null;
                        }

                        // No explicit primary language set, so try and work out the best match
                        if (primaryLanguage.IsNullOrWhiteSpace())
                        {
                            var currentCulture = Thread.CurrentThread.CurrentUICulture.Name;
                            var languages      = umbraco.cms.businesslogic.language.Language.GetAllAsList()
                                                 .Select(x => x.CultureAlias)
                                                 .ToList();

                            // Check for an exact culture match
                            primaryLanguage = languages.FirstOrDefault(x => x == currentCulture);

                            // Check for a close match
                            if (primaryLanguage.IsNullOrWhiteSpace())
                            {
                                primaryLanguage = languages.FirstOrDefault(x => x.Contains(currentCulture));
                            }

                            // Check for a close match
                            if (primaryLanguage.IsNullOrWhiteSpace())
                            {
                                primaryLanguage = languages.FirstOrDefault(x => currentCulture.Contains(x));
                            }

                            // Couldn't find a good enough match, just select the first language
                            if (primaryLanguage.IsNullOrWhiteSpace())
                            {
                                primaryLanguage = languages.FirstOrDefault();
                            }
                        }

                        if (!primaryLanguage.IsNullOrWhiteSpace())
                        {
                            value = new VortoValue
                            {
                                DtdGuid = dataTypeDef.Key,
                                Values  = new Dictionary <string, object>
                                {
                                    { primaryLanguage, property.Value }
                                }
                            };
                        }
                    }

                    if (value?.Values != null)
                    {
                        var dtd = VortoHelper.GetTargetDataTypeDefinition(value.DtdGuid);
                        if (dtd != null)
                        {
                            var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias);
                            var propType   = new PropertyType(dtd);

                            var keys = value.Values.Keys.ToArray();
                            foreach (var key in keys)
                            {
                                var prop     = new Property(propType, value.Values[key] == null ? null : value.Values[key].ToString());
                                var newValue = propEditor.ValueEditor.ConvertDbToEditor(prop, propType, dataTypeService);
                                value.Values[key] = (newValue == null) ? null : JToken.FromObject(newValue);
                            }

                            prop2.Value = JsonConvert.SerializeObject(value);
                        }
                        else
                        {
                            LogHelper.Error <VortoPropertyValueEditor>($"Unabled to locate target DTD for source DTD ${value.DtdGuid}", null);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error <VortoPropertyValueEditor>("Error converting DB value to Editor", ex);
                }

                return(base.ConvertDbToEditor(prop2, propertyType, dataTypeService));
            }
Exemple #25
0
        internal void DeserializeProperties(IContentTypeBase item, XElement node)
        {
            List <string> propertiesToRemove = new List <string>();
            Dictionary <string, string>        propertiesToMove = new Dictionary <string, string>();
            Dictionary <PropertyGroup, string> tabsToBlank      = new Dictionary <PropertyGroup, string>();

            var genericPropertyNode = node.Element("GenericProperties");

            if (genericPropertyNode != null)
            {
                // add or update properties
                foreach (var propertyNode in genericPropertyNode.Elements("GenericProperty"))
                {
                    bool newProperty = false;

                    var property = default(PropertyType);
                    var propKey  = propertyNode.Element("Key").ValueOrDefault(Guid.Empty);
                    if (propKey != Guid.Empty)
                    {
                        property = item.PropertyTypes.SingleOrDefault(x => x.Key == propKey);
                    }

                    var alias = propertyNode.Element("Alias").ValueOrDefault(string.Empty);

                    if (property == null)
                    {
                        // look up via alias?
                        property = item.PropertyTypes.SingleOrDefault(x => x.Alias == alias);
                    }

                    // we need to get element stuff now before we can create or update

                    var defGuid            = propertyNode.Element("Definition").ValueOrDefault(Guid.Empty);
                    var dataTypeDefinition = _dataTypeService.GetDataTypeDefinitionById(defGuid);

                    if (dataTypeDefinition == null)
                    {
                        var propEditorAlias = propertyNode.Element("Type").ValueOrDefault(string.Empty);
                        if (!string.IsNullOrEmpty(propEditorAlias))
                        {
                            dataTypeDefinition = _dataTypeService
                                                 .GetDataTypeDefinitionByPropertyEditorAlias(propEditorAlias)
                                                 .FirstOrDefault();
                        }
                    }

                    if (dataTypeDefinition == null)
                    {
                        LogHelper.Warn <Events>("Failed to get Definition for property type");
                        continue;
                    }

                    if (property == null)
                    {
                        // create the property
                        LogHelper.Debug <Events>("Creating new Property: {0} {1}", () => item.Alias, () => alias);
                        property    = new PropertyType(dataTypeDefinition, alias);
                        newProperty = true;
                    }

                    if (property != null)
                    {
                        LogHelper.Debug <Events>("Updating Property :{0} {1}", () => item.Alias, () => alias);

                        var key = propertyNode.Element("Key").ValueOrDefault(Guid.Empty);
                        if (key != Guid.Empty)
                        {
                            LogHelper.Debug <Events>("Setting Key :{0}", () => key);
                            property.Key = key;
                        }

                        LogHelper.Debug <Events>("Item Key    :{0}", () => property.Key);

                        // update settings.
                        property.Name = propertyNode.Element("Name").ValueOrDefault("unnamed" + DateTime.Now.ToString("yyyyMMdd_HHmmss"));

                        if (property.Alias != alias)
                        {
                            property.Alias = alias;
                        }

                        if (propertyNode.Element("Description") != null)
                        {
                            property.Description = propertyNode.Element("Description").Value;
                        }

                        if (propertyNode.Element("Mandatory") != null)
                        {
                            property.Mandatory = propertyNode.Element("Mandatory").Value.ToLowerInvariant().Equals("true");
                        }

                        if (propertyNode.Element("Validation") != null)
                        {
                            property.ValidationRegExp = propertyNode.Element("Validation").Value;
                        }

                        if (propertyNode.Element("SortOrder") != null)
                        {
                            property.SortOrder = int.Parse(propertyNode.Element("SortOrder").Value);
                        }

                        if (propertyNode.Element("Type") != null)
                        {
                            LogHelper.Debug <Events>("Setting Property Type : {0}", () => propertyNode.Element("Type").Value);
                            property.PropertyEditorAlias = propertyNode.Element("Type").Value;
                        }

                        if (property.DataTypeDefinitionId != dataTypeDefinition.Id)
                        {
                            property.DataTypeDefinitionId = dataTypeDefinition.Id;
                        }

                        var tabName = propertyNode.Element("Tab").ValueOrDefault(string.Empty);

                        if (_itemType == "MemberType")
                        {
                            ((IMemberType)item).SetMemberCanEditProperty(alias,
                                                                         propertyNode.Element("CanEdit").ValueOrDefault(false));

                            ((IMemberType)item).SetMemberCanViewProperty(alias,
                                                                         propertyNode.Element("CanView").ValueOrDefault(false));
                        }

                        if (!newProperty)
                        {
                            if (!string.IsNullOrEmpty(tabName))
                            {
                                var propGroup = item.PropertyGroups.FirstOrDefault(x => x.Name == tabName);
                                if (propGroup != null)
                                {
                                    if (!propGroup.PropertyTypes.Any(x => x.Alias == property.Alias))
                                    {
                                        // this tab currently doesn't contain this property, to we have to
                                        // move it (later)
                                        propertiesToMove.Add(property.Alias, tabName);
                                    }
                                }
                            }
                            else
                            {
                                // this property isn't in a tab (now!)
                                if (!newProperty)
                                {
                                    var existingTab = item.PropertyGroups.FirstOrDefault(x => x.PropertyTypes.Contains(property));
                                    if (existingTab != null)
                                    {
                                        // this item is now not in a tab (when it was)
                                        // so we have to remove it from tabs (later)
                                        tabsToBlank.Add(existingTab, property.Alias);
                                    }
                                }
                            }
                        }
                        else
                        {
                            // new propert needs to be added to content type..
                            if (string.IsNullOrEmpty(tabName))
                            {
                                item.AddPropertyType(property);
                            }
                            else
                            {
                                item.AddPropertyType(property, tabName);
                            }

                            // setting the key before here doesn't seem to work for new types.
                            if (key != Guid.Empty)
                            {
                                property.Key = key;
                            }
                        }
                    }
                } // end foreach property
            }     // end generic properties


            // look at what properties we need to remove.
            var propertyNodes = node.Elements("GenericProperties").Elements("GenericProperty");

            foreach (var property in item.PropertyTypes)
            {
                XElement propertyNode = propertyNodes
                                        .FirstOrDefault(x => x.Element("key") != null && x.Element("Key").Value == property.Key.ToString());

                if (propertyNode == null)
                {
                    LogHelper.Debug <uSync.Core.Events>("Looking up property type by alias {0}", () => property.Alias);
                    propertyNode = propertyNodes
                                   .SingleOrDefault(x => x.Element("Alias").Value == property.Alias);
                }

                if (propertyNode == null)
                {
                    propertiesToRemove.Add(property.Alias);
                }
            }


            // now we have gone through all the properties, we can do the moves and removes from the groups
            if (propertiesToMove.Any())
            {
                foreach (var move in propertiesToMove)
                {
                    LogHelper.Debug <Events>("Moving Property: {0} {1}", () => move.Key, () => move.Value);
                    item.MovePropertyType(move.Key, move.Value);
                }
            }

            if (propertiesToRemove.Any())
            {
                // removing properties can cause timeouts on installs with lots of content...
                foreach (var delete in propertiesToRemove)
                {
                    LogHelper.Debug <Events>("Removing Property: {0}", () => delete);
                    item.RemovePropertyType(delete);
                }
            }

            if (tabsToBlank.Any())
            {
                foreach (var blank in tabsToBlank)
                {
                    // there might be a bug here, we need to do some cheking of if this is
                    // possible with the public api

                    // blank.Key.PropertyTypes.Remove(blank.Value);
                }
            }
        }
 /// <summary>
 /// Get a DataTypeDefinition for a Datatype by its DataTypeDefinitionId
 /// </summary>
 /// <param name="DtDefinitionId"></param>
 /// <returns></returns>
 public static DataTypeDefinition GetDataTypeDefinition(int DtDefinitionId)
 {
     return((DataTypeDefinition)umbDataTypeService.GetDataTypeDefinitionById(DtDefinitionId));
 }
Exemple #27
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);
        }
        private IDataTypeDefinition CreateNestedContentDataType(IDataTypeDefinition archetypeDataType)
        {
            var name             = archetypeDataType.Name + " (NC)";
            var alias            = Alias(archetypeDataType.Name + "nc");  // TODO Umbraco method of creating aliases
            var existingDataType = _dataTypeService.GetDataTypeDefinitionByName(name);

            if (existingDataType != null)
            {
                return(existingDataType);
            }

            var preValue          = _dataTypeService.GetPreValuesByDataTypeId(archetypeDataType.Id).FirstOrDefault();
            var archetypePreValue = JsonConvert.DeserializeObject <ArchetypePreValue>(preValue);

            var contentType = new ContentType(-1);

            contentType.Name  = name;
            contentType.Alias = alias;

            foreach (var fieldset in archetypePreValue.Fieldsets)
            {
                var propertyGroup = new PropertyGroup();
                propertyGroup.Name = "Content";

                foreach (var prop in fieldset.Properties)
                {
                    var definition = _dataTypeService.GetDataTypeDefinitionById(prop.DataTypeGuid);
                    propertyGroup.PropertyTypes.Add(new PropertyType(definition)
                    {
                        Name = prop.Label, Alias = prop.Alias, Mandatory = prop.Required, Description = prop.HelpText
                    });
                }
                contentType.PropertyGroups.Add(propertyGroup);
            }
            _contentTypeService.Save(contentType);

            var dataType = new DataTypeDefinition(NestedContentAlias);

            dataType.Name = contentType.Name;

            var preValues = new Dictionary <string, PreValue>();

            preValues.Add("contentTypes", new PreValue(JsonConvert.SerializeObject(
                                                           new NestedContentPreValue[]
            {
                new NestedContentPreValue
                {
                    NcAlias      = contentType.Alias,
                    NcTabAlias   = "Content",
                    NameTemplate = archetypePreValue.Fieldsets.First().LabelTemplate
                }
            },
                                                           new JsonSerializerSettings {
                ContractResolver = _contractResolver
            })
                                                       ));
            preValues.Add("minItems", new PreValue("0"));
            preValues.Add("maxItems", new PreValue("0"));
            preValues.Add("confirmDeletes", new PreValue("0"));
            preValues.Add("showIcons", new PreValue("0"));
            preValues.Add("hideLabel", new PreValue(archetypePreValue.HidePropertyLabel ? "1" : "0"));

            _dataTypeService.SaveDataTypeAndPreValues(dataType, preValues);
            return(dataType);
        }
Exemple #29
0
        public static void ImportRemoveMissingProps(this IContentType item, XElement node)
        {
            // don't do this if the setting is set to false
            if (!uSyncSettings.docTypeSettings.DeletePropertyValues)
            {
                return;
            }

            List <string> propertiesToRemove             = new List <string>();
            Dictionary <string, string> propertiesToMove = new Dictionary <string, string>();

            // go through the properties in the item
            foreach (var property in item.PropertyTypes)
            {
                // is this property in the xml ?
                XElement propertyNode = node.Element("GenericProperties")
                                        .Elements("GenericProperty")
                                        .Where(x => x.Element("Alias").Value == property.Alias)
                                        .SingleOrDefault();

                if (propertyNode == null)
                {
                    LogHelper.Info <uSync>("Removing {0} from {1}", () => property.Alias, () => item.Name);
                    propertiesToRemove.Add(property.Alias);
                }
                else
                {
                    // at this point we write our properties over those
                    // in the db - because the import doesn't do this
                    // for existing items.
                    LogHelper.Debug <uSync>("Updating prop {0} for {1}", () => property.Alias, () => item.Alias);



                    var legacyEditorId = Guid.Empty;
                    var editorAlias    = string.Empty;
                    Guid.TryParse(propertyNode.Element("Type").Value, out legacyEditorId);
                    if (legacyEditorId == Guid.Empty)
                    {
                        // new style id...?
                    }

                    var dataTypeDefinitionId          = new Guid(propertyNode.Element("Definition").Value);
                    IDataTypeService _dataTypeService = ApplicationContext.Current.Services.DataTypeService;

                    IDataTypeDefinition dataTypeDefinition = null;
                    try
                    {
                        dataTypeDefinition = _dataTypeService.GetDataTypeDefinitionById(dataTypeDefinitionId);
                        if (dataTypeDefinition == null)
                        {
                            editorAlias = propertyNode.Element("Type").Value;
                            // try to match on guid as alias is not unique
                            dataTypeDefinition =
                                _dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(editorAlias).Any(x => x.Key == dataTypeDefinitionId)
                                    ? _dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(editorAlias).First(x => x.Key == dataTypeDefinitionId)
                                    : _dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(editorAlias).FirstOrDefault();
                        }

                        if (dataTypeDefinition != null &&
                            dataTypeDefinition.Key == dataTypeDefinitionId)
                        {
                            // all good, we are here..
                        }
                        else
                        {
                            // we need to do even more looking...
                            var dataTypeDefinitions = _dataTypeService.GetDataTypeDefinitionByControlId(legacyEditorId);

                            if (dataTypeDefinition != null && dataTypeDefinitions.Any())
                            {
                                dataTypeDefinition = dataTypeDefinitions.First();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // getDataTypeDefinition can throw exceptions - when you have issues with legacy ids'
                        // so we capture them, so we can carry on.
                        LogHelper.Info <SyncDocType>("Error looking for the datatype {0}, you might be missing a package?", () => dataTypeDefinitionId);
                    }

                    if (dataTypeDefinition != null)
                    {
                        // now we set it in the DB
                        // property.DataTypeDefinitionId = dataTypeDefinition.Id;
                        // we can set both the id and alias, but we can't directly change the
                        // underling database type, not sure if you can to be honest.
                        if (property.DataTypeDefinitionId != dataTypeDefinition.Id)
                        {
                            LogHelper.Info <SyncDocType>("Updating the datatype Definition");
                            property.DataTypeDefinitionId = dataTypeDefinition.Id;
                            property.PropertyEditorAlias  = dataTypeDefinition.PropertyEditorAlias;
                        }


                        // TODO: make changes to the datatype import/export properly.
                    }

                    property.Name             = propertyNode.Element("Name").Value;
                    property.Description      = propertyNode.Element("Description").Value;
                    property.Mandatory        = propertyNode.Element("Mandatory").Value.ToLowerInvariant().Equals("true");
                    property.ValidationRegExp = propertyNode.Element("Validation").Value;

                    XElement sortOrder = propertyNode.Element("SortOrder");
                    if (sortOrder != null)
                    {
                        property.SortOrder = int.Parse(sortOrder.Value);
                    }

                    var tab = propertyNode.Element("Tab").Value;
                    if (!string.IsNullOrEmpty(tab))
                    {
                        var propGroup = item.PropertyGroups.First(x => x.Name == tab);

                        if (!propGroup.PropertyTypes.Any(x => x.Alias == property.Alias))
                        {
                            // if it's not in this prop group - we can move it it into it
                            LogHelper.Info <uSync>("Moving {0} in {1} to {2}",
                                                   () => property.Alias, () => item.Name, () => tab);
                            propertiesToMove.Add(property.Alias, tab);
                        }
                    }
                }
            }

            foreach (string alias in propertiesToRemove)
            {
                LogHelper.Debug <uSync>("Removing {0}", () => alias);
                item.RemovePropertyType(alias);

                // if slow - save after every remove
                // on big sites, this increases the chances of your SQL server completing the operation in time...
                //

                /*
                 * if (uSyncSettings.SlowUpdate)
                 * {
                 *  LogHelper.Debug<uSync>("SlowMode: saving now {0}", () => item.Name);
                 *  _contentTypeService.Save(item);
                 * }
                 */
            }

            foreach (KeyValuePair <string, string> movePair in propertiesToMove)
            {
                item.MovePropertyType(movePair.Key, movePair.Value);
            }

            if (propertiesToRemove.Count > 0 || propertiesToMove.Count > 0)
            {
                LogHelper.Debug <uSync>("Saving {0}", () => item.Name);
                _contentTypeService.Save(item);
            }
        }
        /// <summary>
        /// Exports an <see cref="IContentType"/> item to xml as an <see cref="XElement"/>
        /// </summary>
        /// <param name="dataTypeService"></param>
        /// <param name="contentType">Content type to export</param>
        /// <returns><see cref="XElement"/> containing the xml representation of the IContentType object</returns>
        public XElement Serialize(IDataTypeService dataTypeService, IContentType contentType)
        {
            var info = new XElement("Info",
                                    new XElement("Name", contentType.Name),
                                    new XElement("Alias", contentType.Alias),
                                    new XElement("Icon", contentType.Icon),
                                    new XElement("Thumbnail", contentType.Thumbnail),
                                    new XElement("Description", contentType.Description),
                                    new XElement("AllowAtRoot", contentType.AllowedAsRoot.ToString()),
                                    new XElement("IsListView", contentType.IsContainer.ToString()));

            var masterContentType = contentType.ContentTypeComposition.FirstOrDefault(x => x.Id == contentType.ParentId);

            if (masterContentType != null)
            {
                info.Add(new XElement("Master", masterContentType.Alias));
            }

            var compositionsElement = new XElement("Compositions");
            var compositions        = contentType.ContentTypeComposition;

            foreach (var composition in compositions)
            {
                compositionsElement.Add(new XElement("Composition", composition.Alias));
            }
            info.Add(compositionsElement);

            var allowedTemplates = new XElement("AllowedTemplates");

            foreach (var template in contentType.AllowedTemplates)
            {
                allowedTemplates.Add(new XElement("Template", template.Alias));
            }
            info.Add(allowedTemplates);

            if (contentType.DefaultTemplate != null && contentType.DefaultTemplate.Id != 0)
            {
                info.Add(new XElement("DefaultTemplate", contentType.DefaultTemplate.Alias));
            }
            else
            {
                info.Add(new XElement("DefaultTemplate", ""));
            }

            var structure = new XElement("Structure");

            foreach (var allowedType in contentType.AllowedContentTypes)
            {
                structure.Add(new XElement("DocumentType", allowedType.Alias));
            }

            var genericProperties = new XElement("GenericProperties");

            foreach (var propertyType in contentType.PropertyTypes)
            {
                var definition = dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId);

                var propertyGroup = propertyType.PropertyGroupId == null
                                                ? null
                                                : contentType.PropertyGroups.FirstOrDefault(x => x.Id == propertyType.PropertyGroupId.Value);

                var genericProperty = new XElement("GenericProperty",
                                                   new XElement("Name", propertyType.Name),
                                                   new XElement("Alias", propertyType.Alias),
                                                   new XElement("Type", propertyType.PropertyEditorAlias),
                                                   new XElement("Definition", definition.Key),
                                                   new XElement("Tab", propertyGroup == null ? "" : propertyGroup.Name),
                                                   new XElement("Mandatory", propertyType.Mandatory.ToString()),
                                                   new XElement("Validation", propertyType.ValidationRegExp),
                                                   new XElement("Description", new XCData(propertyType.Description)));
                genericProperties.Add(genericProperty);
            }

            var tabs = new XElement("Tabs");

            foreach (var propertyGroup in contentType.PropertyGroups)
            {
                var tab = new XElement("Tab",
                                       new XElement("Id", propertyGroup.Id.ToString(CultureInfo.InvariantCulture)),
                                       new XElement("Caption", propertyGroup.Name),
                                       new XElement("SortOrder", propertyGroup.SortOrder));
                tabs.Add(tab);
            }

            return(new XElement("DocumentType",
                                info,
                                structure,
                                genericProperties,
                                tabs));
        }
Exemple #31
0
        public IMemberType AddDialogueMemberType()
        {
            #region DataType Ids
            //-49	    Umbraco.TrueFalse
            //-51	    Umbraco.Integer
            //-87	    Umbraco.TinyMCEv3
            //-88	    Umbraco.Textbox
            //-89	    Umbraco.TextboxMultiple
            //-90	    Umbraco.UploadField
            //-92	    Umbraco.NoEdit
            //-36	    Umbraco.DateTime
            //-37	    Umbraco.ColorPickerAlias
            //-38	    Umbraco.FolderBrowser
            //-39	    Umbraco.DropDownMultiple
            //-40	    Umbraco.RadioButtonList
            //-41	    Umbraco.Date
            //-42	    Umbraco.DropDown
            //-43	    Umbraco.CheckBoxList
            //1034	    Umbraco.ContentPickerAlias
            //1035	    Umbraco.MediaPicker
            //1036	    Umbraco.MemberPicker
            //1040	    Umbraco.RelatedLinks
            //1041	    Umbraco.Tags
            //1045	    Umbraco.MultipleMediaPicker
            //1077	    Apt.PartialPicker
            //1089	    Umbraco.ImageCropper
            //1092	    Umbraco.TinyMCEv3
            //1103	    Our.Umbraco.FilePicker
            //1104	    Umbraco.MemberGroupPicker
            //1105	    Apt.CssPicker
            //1128	    Dialogue.ThemePicker
            //1132	    Dialogue.Permissions
            //1147	    Umbraco.MultipleTextstring
            #endregion

            var label           = _dataTypeService.GetDataTypeDefinitionById(-92);
            var upload          = _dataTypeService.GetDataTypeDefinitionById(-90);
            var textstring      = _dataTypeService.GetDataTypeDefinitionById(-88);
            var textboxMultiple = _dataTypeService.GetDataTypeDefinitionById(-89);
            var truefalse       = _dataTypeService.GetDataTypeDefinitionById(-49);
            var numeric         = _dataTypeService.GetDataTypeDefinitionById(-51);
            var datetime        = _dataTypeService.GetDataTypeDefinitionById(-36);

            // Profile, Settings, Social Tokens

            // Create the member Type
            var memType = new MemberType(-1)
            {
                Alias = AppConstants.MemberTypeAlias,
                Name  = "Dialogue Member"
            };

            // Create the Profile group/tab
            var profileGroup = new PropertyGroup
            {
                Name = "Profile",
            };
            profileGroup.PropertyTypes.Add(new PropertyType(label)
            {
                Alias       = "email",
                Name        = "Email",
                SortOrder   = 0,
                Description = "This is a bit rubbish, but it's the only way to get the email from the new member service at the current time"
            });
            profileGroup.PropertyTypes.Add(new PropertyType(upload)
            {
                Alias       = "avatar",
                Name        = "Avatar",
                SortOrder   = 0,
                Description = ""
            });
            profileGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Alias       = "website",
                Name        = "Website",
                SortOrder   = 0,
                Description = ""
            });
            profileGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Alias       = "twitter",
                Name        = "Twitter",
                SortOrder   = 0,
                Description = ""
            });
            profileGroup.PropertyTypes.Add(new PropertyType(textboxMultiple)
            {
                Alias       = "signature",
                Name        = "Signature",
                SortOrder   = 0,
                Description = ""
            });
            profileGroup.PropertyTypes.Add(new PropertyType(datetime)
            {
                Alias       = "lastActiveDate",
                Name        = "Last Active Date",
                SortOrder   = 0,
                Description = ""
            });
            memType.PropertyGroups.Add(profileGroup);

            // Create the Settings group/tab
            var settingsGroup = new PropertyGroup
            {
                Name = "Settings",
            };
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias       = "canEditOtherMembers",
                Name        = "Can Edit Other Members",
                SortOrder   = 0,
                Description = "Enable this and the user can edit other members posts, their profiles and ban members (Usually use in conjunction with moderate permissions)."
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias       = "disableEmailNotifications",
                Name        = "Disable Email Notifications",
                SortOrder   = 0,
                Description = ""
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias       = "disablePosting",
                Name        = "Disable Posting",
                SortOrder   = 0,
                Description = ""
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias       = "disablePrivateMessages",
                Name        = "Disable Private Messages",
                SortOrder   = 0,
                Description = ""
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias       = "disableFileUploads",
                Name        = "Disable File Uploads",
                SortOrder   = 0,
                Description = ""
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(numeric)
            {
                Alias       = "postCount",
                Name        = "Post Count",
                SortOrder   = 0,
                Description = "The users post count. This is kept like this to help reduce SQL queries and improve performance of the forum"
            });
            memType.PropertyGroups.Add(settingsGroup);

            // Create the Settings group/tab
            var socialGroup = new PropertyGroup
            {
                Name = "Social Tokens",
            };
            socialGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Name        = "Facebook Access Token",
                Alias       = "facebookAccessToken",
                SortOrder   = 0,
                Description = ""
            });
            socialGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Name        = "Facebook Id",
                Alias       = "facebookId",
                SortOrder   = 0,
                Description = ""
            });
            socialGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Name        = "Google Access Token",
                Alias       = "googleAccessToken",
                SortOrder   = 0,
                Description = ""
            });
            socialGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Name        = "Google Id",
                Alias       = "googleId",
                SortOrder   = 0,
                Description = ""
            });
            memType.PropertyGroups.Add(socialGroup);

            // Add Slug
            memType.AddPropertyType(new PropertyType(textstring)
            {
                Name        = "Slug",
                Alias       = "slug",
                SortOrder   = 0,
                Description = "This is what we use to look up the member in the front end"
            });

            _memberTypeService.Save(memType);

            return(memType);
        }