/// <summary>
        /// Extension used to convert an IPublishedContent back to a Typed model instance.
        /// Your model does need to inherit from UmbracoGeneratedBase and contain the correct attributes
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content"></param>
        /// <returns></returns>
        public static T ConvertToModel <T>(this IPublishedContent content)
        {
            T   instance = Activator.CreateInstance <T>();
            var propertiesWithTabsAttribute = typeof(T).GetProperties().Where(x => x.GetCustomAttribute <UmbracoTabAttribute>() != null);

            foreach (var property in propertiesWithTabsAttribute)
            {
                //tab instance
                UmbracoTabAttribute tabAttribute = property.GetCustomAttribute <UmbracoTabAttribute>();
                var propertyTabInstance          = Activator.CreateInstance(property.PropertyType);
                var propertiesOnTab = property.PropertyType.GetProperties();

                foreach (var propertyOnTab in propertiesOnTab.Where(x => x.GetCustomAttribute <UmbracoPropertyAttribute>() != null))
                {
                    UmbracoPropertyAttribute propertyAttribute = propertyOnTab.GetCustomAttribute <UmbracoPropertyAttribute>();
                    string alias = HyphenToUnderscore(ParseUrl(propertyAttribute.Alias + "_" + tabAttribute.Name, false));
                    GetPropertyValueOnInstance(content, propertyTabInstance, propertyOnTab, propertyAttribute, alias);
                }

                property.SetValue(instance, propertyTabInstance);
            }

            //properties on Generic Tab
            var propertiesOnGenericTab = typeof(T).GetProperties().Where(x => x.GetCustomAttribute <UmbracoPropertyAttribute>() != null);

            foreach (var item in propertiesOnGenericTab)
            {
                UmbracoPropertyAttribute umbracoPropertyAttribute = item.GetCustomAttribute <UmbracoPropertyAttribute>();
                GetPropertyValueOnInstance(content, instance, item, umbracoPropertyAttribute);
            }

            (instance as UmbracoGeneratedBase).UmbracoId = content.Id;
            return(instance);
        }
Exemple #2
0
        /// <summary>
        /// Creates a new property on the ContentType under the correct tab
        /// </summary>
        /// <param name="newContentType"></param>
        /// <param name="tabName"></param>
        /// <param name="dataTypeService"></param>
        /// <param name="atTabGeneric"></param>
        /// <param name="item"></param>
        private static void CreateProperty(IContentType newContentType, string tabName, IDataTypeService dataTypeService, bool atTabGeneric, PropertyInfo item)
        {
            UmbracoPropertyAttribute attribute = item.GetCustomAttribute <UmbracoPropertyAttribute>();

            IDataTypeDefinition dataTypeDef;

            if (string.IsNullOrEmpty(attribute.DataTypeInstanceName))
            {
                dataTypeDef = dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(attribute.DataType).FirstOrDefault();
            }
            else
            {
                dataTypeDef = dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(attribute.DataType).FirstOrDefault(x => x.Name == attribute.DataTypeInstanceName);
            }

            if (dataTypeDef != null)
            {
                PropertyType propertyType = new PropertyType(dataTypeDef);
                propertyType.Name        = attribute.Name;
                propertyType.Alias       = (atTabGeneric ? attribute.Alias : UmbracoCodeFirstExtensions.HyphenToUnderscore(UmbracoCodeFirstExtensions.ParseUrl(attribute.Alias + "_" + tabName, false)));
                propertyType.Description = attribute.Description;
                propertyType.Mandatory   = attribute.Mandatory;

                if (atTabGeneric)
                {
                    newContentType.AddPropertyType(propertyType);
                }
                else
                {
                    newContentType.AddPropertyType(propertyType, tabName);
                }
            }
        }
        private static bool GetPropertyRecursion(UmbracoPropertyAttribute umbracoPropertyBinding)
        {
            if (umbracoPropertyBinding != null)
            {
                return(umbracoPropertyBinding.Recursive);
            }

            return(false);
        }
        private static string GetPropertyAlias(UmbracoPropertyAttribute umbracoPropertyBinding, PropertyInfo propertyInfo)
        {
            if (!string.IsNullOrWhiteSpace(umbracoPropertyBinding?.Alias))
            {
                return(umbracoPropertyBinding.Alias);
            }

            return($"{propertyInfo.Name[0].ToString(CultureInfo.InvariantCulture).ToLower()}{propertyInfo.Name.Substring(1)}");
        }
        public void Default_Constructor_Set_Setting_To_Default()
        {
            //Assign
            var testUmbracoPropertyAttribute = new UmbracoPropertyAttribute();

            //Act

            //Assert
            testUmbracoPropertyAttribute.Setting.ShouldBeEquivalentTo(UmbracoPropertySettings.Default);
        }
        public void Constructor_Sets_PropertyAlias()
        {
            //Assign
            var testPropertyAlias = "testPropertyAlias";

            //Act
            var testUmbracoPropertyAttribute = new UmbracoPropertyAttribute(testPropertyAlias);

            //Assert
            testUmbracoPropertyAttribute.PropertyAlias.ShouldBeEquivalentTo(testPropertyAlias);
        }
Exemple #7
0
        public static ITypeHandler GetTypeHander(this UmbracoPropertyAttribute attribute, Type propertyType)
        {
            var typeHandler = attribute.TypeHandler ?? TypeHandlerFactory.Instance.GetHandlerForType(propertyType);

            if (typeHandler == null)
            {
                throw new NotSupportedException($"The property type {propertyType} is not supported by Umbraco.Vault.");
            }

            return(typeHandler);
        }
        private ITypeHandler GetTypeHandler(Type propertyType, UmbracoPropertyAttribute propertyMetaData)
        {
            // TODO: this can be cleaned up... perhaps a total rethink of the architecture

            //Get the attribute's property name value
            var classMetaData = propertyType.GetCustomAttributes(typeof(UmbracoEntityAttribute), true).FirstOrDefault() as
                                UmbracoEntityAttribute;

            if (classMetaData?.TypeHandlerOverride != null)
            {
                // Check for type-level override
                return(classMetaData.TypeHandlerOverride.CreateWithNoParams <ITypeHandler>());
            }

            if (propertyMetaData?.TypeHandler != null)
            {
                // Check for property-level override
                return(propertyMetaData.TypeHandler);
            }

            // Attempt to find default handler

            // If it's generic, get the underlying type and return it as a nullable with a value, otherwise null.
            if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                var innerType        = Nullable.GetUnderlyingType(propertyType);
                var innerTypeHandler = _typeHandlerFactory.GetHandlerForType(innerType);
                if (innerTypeHandler != null)
                {
                    var nullableTypeHandlerType = typeof(NullableTypeHandler <>);
                    // ReSharper disable once PossibleNullReferenceException - Shouldn't happen (KMS 31 MAR 2016)
                    return((ITypeHandler)nullableTypeHandlerType.MakeGenericType(innerType).GetConstructor(new[] { typeof(ITypeHandler) }).Invoke(new object[] { innerTypeHandler }));
                }
            }

            // Check for a default handler for this type.
            var factoryHandler = _typeHandlerFactory.GetHandlerForType(propertyType);

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

            if (classMetaData?.GetType() == typeof(UmbracoEntityAttribute))
            {
                // Finally, if no other handler has been found yet, AND the target type is an Entity
                // then let's attempt to recursively get the content
                return(new UmbracoEntityTypeHandler());
            }

            // Otherwise, we got nothing
            return(null);
        }
        public void Configure_SettingNotSet_SettingsReturnAsDefault()
        {
            //Assign
            var attr         = new UmbracoPropertyAttribute(string.Empty);
            var propertyInfo = typeof(StubClass).GetProperty("DummyProperty");

            //Act
            var result = attr.Configure(propertyInfo) as UmbracoPropertyConfiguration;

            //Assert
            result.Should().NotBeNull();
            result.Setting.ShouldBeEquivalentTo(UmbracoPropertySettings.Default);
        }
Exemple #10
0
        public static string GetUmbracoPropertyName(this PropertyInfo propertyInfo, UmbracoPropertyAttribute attribute = null)
        {
            if (attribute == null)
            {
                attribute = propertyInfo.GetUmbracoPropertyAttribute();
            }

            string propertyName = string.IsNullOrWhiteSpace(attribute.Alias)
                                          ? $"{propertyInfo.Name[0].ToString().ToLower()}{propertyInfo.Name.Substring(1)}" //camel case the property name
                                          : attribute.Alias;

            return(propertyName);
        }
        protected object TransformParsedValue(PropertyInfo propertyInfo, UmbracoPropertyAttribute propertyMetaData, object parsedValue)
        {
            object value = parsedValue;

            var propertyType = propertyInfo.PropertyType;

            /*
             * var transformations = _transformations.Where(x => x.TypeSupported == propertyType);
             * var transformedValue = transformations.Aggregate(value,
             *  (current, transform) => transform.Transform(current));
             */

            var typeHandler = GetTypeHandler(propertyType, propertyMetaData);

            //unsupported if the value is not target type and there is no handler
            if (value.GetType() != propertyType && typeHandler == null)
            {
                throw new NotSupportedException($"The property type {propertyType} is not supported by Umbraco Vault.");
            }

            //if there is no handler, but value is already the target type, return value
            if (typeHandler == null)
            {
                return(value);
            }

            //apply handler
            if (typeHandler is EnumTypeHandler)
            {
                // Unfortunately, the EnumTypeHandler currently requires special attention because the GetAsType has a "where T : class" constraint.
                // TODO: refactor this architecture so this workaround isn't necessary
                var method  = typeHandler.GetType().GetMethod("GetAsEnum");
                var generic = method.MakeGenericMethod(propertyInfo.PropertyType);

                value = generic.Invoke(typeHandler, new[] { value });
                return(value);
            }

            if (propertyInfo.PropertyType.IsGenericType)
            {
                var method  = typeHandler.GetType().GetMethod("GetAsType");
                var generic = method.MakeGenericMethod(propertyInfo.PropertyType.GetGenericArguments()[0]);
                return(generic.Invoke(typeHandler, new[] { value }));
            }
            else
            {
                var method  = typeHandler.GetType().GetMethod("GetAsType");
                var generic = method.MakeGenericMethod(propertyInfo.PropertyType);
                return(generic.Invoke(typeHandler, new[] { value }));
            }
        }
Exemple #12
0
        private static string VerifyExistingProperty(IContentType contentType, string tabName, IDataTypeService dataTypeService, PropertyInfo item, bool atGenericTab = false)
        {
            UmbracoPropertyAttribute attribute = item.GetCustomAttribute <UmbracoPropertyAttribute>();
            IDataTypeDefinition      dataTypeDef;

            if (string.IsNullOrEmpty(attribute.DataTypeInstanceName))
            {
                dataTypeDef = dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(attribute.DataType).FirstOrDefault();
            }
            else
            {
                dataTypeDef = dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(attribute.DataType).FirstOrDefault(x => x.Name == attribute.DataTypeInstanceName);
            }

            if (dataTypeDef != null)
            {
                PropertyType property;
                bool         alreadyExisted = contentType.PropertyTypeExists(attribute.Alias);
                // TODO: Added attribute.Tab != null after Generic Properties add, is this bulletproof?
                if (alreadyExisted && attribute.Tab != null)
                {
                    property = contentType.PropertyTypes.FirstOrDefault(x => x.Alias == attribute.Alias);
                }
                else
                {
                    property = new PropertyType(dataTypeDef);
                }

                property.Name = attribute.Name;
                //TODO: correct name?
                property.Alias       = (atGenericTab ? attribute.Alias : UmbracoCodeFirstExtensions.HyphenToUnderscore(UmbracoCodeFirstExtensions.ParseUrl(attribute.Alias + "_" + tabName, false)));
                property.Description = attribute.Description;
                property.Mandatory   = attribute.Mandatory;

                if (!alreadyExisted)
                {
                    if (atGenericTab)
                    {
                        contentType.AddPropertyType(property);
                    }
                    else
                    {
                        contentType.AddPropertyType(property, tabName);
                    }
                }

                return(property.Alias);
            }
            return(null);
        }
        public void Constructor_Sets_PropertyIdAndPropertyType()
        {
            //Assign
            var testPropertyId = "test";
            var testContentTab = "General Properties";
            var testCodeFirst  = true;

            //Act
            var testUmbracoPropertyAttribute = new UmbracoPropertyAttribute("test", UmbracoPropertyType.NotSet);

            //Assert
            testUmbracoPropertyAttribute.CodeFirst.ShouldBeEquivalentTo(testCodeFirst);
            testUmbracoPropertyAttribute.ContentTab.ShouldBeEquivalentTo(testContentTab);
            testUmbracoPropertyAttribute.PropertyAlias.ShouldBeEquivalentTo(testPropertyId);
            testUmbracoPropertyAttribute.PropertyType.ShouldBeEquivalentTo(UmbracoPropertyType.NotSet);
        }
        public void Configure_SettingPropertyMandatory_PropertyMandatoryIsSetOnConfiguration(
            [Values(true)] bool value,
            [Values(true)] bool expected)
        {
            //Assign
            var attr         = new UmbracoPropertyAttribute(string.Empty);
            var propertyInfo = typeof(StubClass).GetProperty("DummyProperty");

            attr.PropertyIsMandatory = value;

            //Act
            var result = attr.Configure(propertyInfo) as UmbracoPropertyConfiguration;

            //Assert
            result.Should().NotBeNull();
            result.PropertyIsMandatory.ShouldBeEquivalentTo(expected);
        }
        public void Configure_SettingDataType_DataTypeIsSetOnConfiguration(
            [Values(UmbracoPropertyType.TextString)] UmbracoPropertyType value,
            [Values(UmbracoPropertyType.TextString)] UmbracoPropertyType expected)
        {
            //Assign
            var attr         = new UmbracoPropertyAttribute(string.Empty);
            var propertyInfo = typeof(StubClass).GetProperty("DummyProperty");

            attr.PropertyType = value;

            //Act
            var result = attr.Configure(propertyInfo) as UmbracoPropertyConfiguration;

            //Assert
            result.Should().NotBeNull();
            result.PropertyType.ShouldBeEquivalentTo(expected);
        }
        public void Configure_SettingPropertyDescription_PropertyDescriptionIsSetOnConfiguration(
            [Values("property description")] string value,
            [Values("property description")] string expected)
        {
            //Assign
            var attr         = new UmbracoPropertyAttribute(string.Empty);
            var propertyInfo = typeof(StubClass).GetProperty("DummyProperty");

            attr.PropertyDescription = value;

            //Act
            var result = attr.Configure(propertyInfo) as UmbracoPropertyConfiguration;

            //Assert
            result.Should().NotBeNull();
            result.PropertyDescription.ShouldBeEquivalentTo(expected);
        }
Exemple #17
0
        /// <summary>
        /// Abstract base class for any entity you want to be generated
        /// The persist method makes sure that you can save all the changes to you entity back into the database
        /// </summary>
        /// <param name="contentId">Id of the Umbraco Document</param>
        /// <param name="userId"></param>
        /// <param name="raiseEvents"></param>
        public virtual void Persist(int contentId, int userId = 0, bool raiseEvents = false)
        {
            IContentService contentSerivce = ApplicationContext.Current.Services.ContentService;
            IContent        content        = contentSerivce.GetById(contentId);

            //search for propertys with the UmbracoTab on
            Type currentType = this.GetType();
            var  propertiesWithTabAttribute = currentType.GetProperties().Where(x => x.GetCustomAttributes <UmbracoTabAttribute>() != null).ToArray();
            int  length = propertiesWithTabAttribute.Count();

            for (int i = 0; i < length; i++)
            {
                PropertyInfo        tabProperty   = propertiesWithTabAttribute[i];
                Type                tabType       = tabProperty.PropertyType;
                object              instanceOfTab = tabProperty.GetValue(this);
                UmbracoTabAttribute tabAttribute  = tabProperty.GetCustomAttribute <UmbracoTabAttribute>();

                //persist the fields foreach tab
                var propertiesInsideTab = tabType.GetProperties().Where(x => x.GetCustomAttribute <UmbracoPropertyAttribute>() != null).ToArray();
                int propertyLength      = propertiesInsideTab.Length;
                for (int j = 0; j < propertyLength; j++)
                {
                    PropertyInfo             property = propertiesInsideTab[j];
                    UmbracoPropertyAttribute umbracoPropertyAttribute = property.GetCustomAttribute <UmbracoPropertyAttribute>();
                    object propertyValue = property.GetValue(instanceOfTab);
                    string alias         = UmbracoCodeFirstExtensions.HyphenToUnderscore(UmbracoCodeFirstExtensions.ParseUrl(umbracoPropertyAttribute.Alias + "_" + tabAttribute.Name, false));
                    SetPropertyOnIContent(content, umbracoPropertyAttribute, propertyValue, alias);
                }
            }

            //properties on generic tab
            var propertiesOnGenericTab = currentType.GetProperties().Where(x => x.GetCustomAttribute <UmbracoPropertyAttribute>() != null);

            foreach (var item in propertiesOnGenericTab)
            {
                UmbracoPropertyAttribute umbracoPropertyAttribute = item.GetCustomAttribute <UmbracoPropertyAttribute>();
                object propertyValue = item.GetValue(this);
                SetPropertyOnIContent(content, umbracoPropertyAttribute, propertyValue);
            }

            //persist object into umbraco database
            contentSerivce.SaveAndPublishWithStatus(content, userId, raiseEvents);
        }
Exemple #18
0
        private void SetPropertyOnIContent(IContent content, UmbracoPropertyAttribute umbracoPropertyAttribute, object propertyValue, string alias = null)
        {
            object convertedValue;

            if (umbracoPropertyAttribute.ConverterType != null)
            {
                TypeConverter converter = (TypeConverter)Activator.CreateInstance(umbracoPropertyAttribute.ConverterType);
                convertedValue = converter.ConvertTo(null, CultureInfo.InvariantCulture, propertyValue, typeof(string));
            }
            else
            {
                //No converter is given so basically we push the string back into umbraco
                convertedValue = (propertyValue != null ? propertyValue.ToString() : string.Empty);
            }

            if (alias == null)
            {
                alias = umbracoPropertyAttribute.Alias;
            }

            content.SetValue(alias, convertedValue);
        }
        private static void GetPropertyValueOnInstance(IPublishedContent content, object objectInstance, PropertyInfo propertyOnTab, UmbracoPropertyAttribute propertyAttribute, string alias = null)
        {
            if (alias == null)
            {
                alias = propertyAttribute.Alias;
            }
            string umbracoStoredValue = content.GetPropertyValue <string>(alias);

            if (propertyAttribute.ConverterType != null)
            {
                TypeConverter converter = (TypeConverter)Activator.CreateInstance(propertyAttribute.ConverterType);
                propertyOnTab.SetValue(objectInstance, converter.ConvertFrom(null, CultureInfo.InvariantCulture, umbracoStoredValue));
            }
            else
            {
                propertyOnTab.SetValue(objectInstance, umbracoStoredValue);
            }
        }