Esempio n. 1
0
            public override IDictionary <string, object> ConvertDbToEditor(IDictionary <string, object> defaultPreVals, PreValueCollection persistedPreVals)
            {
                // re-format old style (v0.1.1) pre values if necessary
                NestedContentHelper.ConvertPreValueCollectionFromV011(persistedPreVals);

                return(base.ConvertDbToEditor(defaultPreVals, persistedPreVals));
            }
Esempio n. 2
0
        public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
        {
            if (string.IsNullOrEmpty(source?.ToString()))
            {
                return(null);
            }

            return(NestedContentHelper.ConvertFromNestedContent(JArray.Parse(source.ToString())));
        }
Esempio n. 3
0
            public override string ConvertDbToString(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
            {
                if (string.IsNullOrEmpty(property.Value?.ToString()))
                {
                    return(string.Empty);
                }
                using (_profilingLogger.DebugDuration <EmbeddedContentPropertyEditor>($"ConvertDbToString({property.Alias})"))
                {
                    List <IContentType> contentTypes = _contentTypeService.GetAllContentTypes().ToList();
                    var items = new List <EmbeddedContentItem>();

                    JArray source = NestedContentHelper.ConvertFromNestedContent(JArray.Parse(property.Value.ToString()));

                    foreach (EmbeddedContentItem item in source.ToObject <EmbeddedContentItem[]>())
                    {
                        if (!item.Published)
                        {
                            continue;
                        }

                        IContentType contentType = contentTypes.FirstOrDefault(x => x.Alias == item.ContentTypeAlias);
                        if (contentType == null)
                        {
                            continue;
                        }
                        foreach (PropertyType propType in contentType.CompositionPropertyGroups.SelectMany(_ => _.PropertyTypes))
                        {
                            item.Properties.TryGetValue(propType.Alias, out object value);
                            PropertyEditor propertyEditor = _propertyEditorResolver.GetByAlias(propType.PropertyEditorAlias);

                            if (propertyEditor == null)
                            {
                                continue;
                            }

                            item.Properties[propType.Alias] = propertyEditor.ValueEditor.ConvertDbToString(
                                new Property(propType, value),
                                propType,
                                dataTypeService
                                );
                        }

                        items.Add(item);
                    }

                    if (items.Count == 0)
                    {
                        return(string.Empty);
                    }

                    return(JsonConvert.SerializeObject(items));
                }
            }
Esempio n. 4
0
 private void DataTypeCacheRefresher_Updated(DataTypeCacheRefresher sender, CacheRefresherEventArgs e)
 {
     if (e.MessageType == MessageType.RefreshByJson)
     {
         var payload = JsonConvert.DeserializeObject <JsonPayload[]>((string)e.MessageObject);
         if (payload != null)
         {
             foreach (var item in payload)
             {
                 NestedContentHelper.ClearCache(item.Id);
             }
         }
     }
 }
        public static bool IsSingleNestedContentProperty(this PublishedPropertyType publishedProperty)
        {
            if (!publishedProperty.IsNestedContentProperty())
            {
                return(false);
            }

            var preValueCollection = NestedContentHelper.GetPreValuesCollectionByDataTypeId(publishedProperty.DataTypeId);
            var preValueDictionary = preValueCollection.PreValuesAsDictionary.ToDictionary(x => x.Key, x => x.Value.Value);

            int minItems, maxItems;

            return(preValueDictionary.ContainsKey("minItems") &&
                   int.TryParse(preValueDictionary["minItems"], out minItems) && minItems == 1 &&
                   preValueDictionary.ContainsKey("maxItems") &&
                   int.TryParse(preValueDictionary["maxItems"], out maxItems) && maxItems == 1);
        }
Esempio n. 6
0
        public override void Refresh(string jsonPayload)
        {
            var payloads = DeserializeFromJsonPayload(jsonPayload);

            //we need to clear the ContentType runtime cache since that is what caches the
            // db data type to store the value against and anytime a datatype changes, this also might change
            // we basically need to clear all sorts of runtime caches here because so many things depend upon a data type

            ClearAllIsolatedCacheByEntityType <IContent>();
            ClearAllIsolatedCacheByEntityType <IContentType>();
            ClearAllIsolatedCacheByEntityType <IMedia>();
            ClearAllIsolatedCacheByEntityType <IMediaType>();
            ClearAllIsolatedCacheByEntityType <IMember>();
            ClearAllIsolatedCacheByEntityType <IMemberType>();

            var dataTypeCache = ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.GetCache <IDataTypeDefinition>();

            foreach (var payload in payloads)
            {
                //clears the prevalue cache
                if (dataTypeCache)
                {
                    dataTypeCache.Result.ClearCacheByKeySearch(string.Format("{0}_{1}", CacheKeys.DataTypePreValuesCacheKey, payload.Id));
                }

                ApplicationContext.Current.Services.IdkMap.ClearCache(payload.Id);
                PublishedContentType.ClearDataType(payload.Id);
                NestedContentHelper.ClearCache(payload.Id);
            }

            TagsValueConverter.ClearCaches();
            LegacyMediaPickerPropertyConverter.ClearCaches();
            SliderValueConverter.ClearCaches();
            MediaPickerPropertyConverter.ClearCaches();
            MultiUrlPickerPropertyConverter.ClearCaches();


            base.Refresh(jsonPayload);
        }
Esempio n. 7
0
            public IEnumerable <ValidationResult> Validate(object rawValue, PreValueCollection preValues, PropertyEditor editor)
            {
                var value = JsonConvert.DeserializeObject <List <object> >(rawValue.ToString());

                if (value == null)
                {
                    yield break;
                }

                IDataTypeService dataTypeService = ApplicationContext.Current.Services.DataTypeService;

                for (var i = 0; i < value.Count; i++)
                {
                    var o          = value[i];
                    var propValues = ((JObject)o);

                    var contentType = NestedContentHelper.GetContentTypeFromItem(propValues);
                    if (contentType == null)
                    {
                        continue;
                    }

                    var propValueKeys = propValues.Properties().Select(x => x.Name).ToArray();

                    foreach (var propKey in propValueKeys)
                    {
                        var propType = contentType.CompositionPropertyTypes.FirstOrDefault(x => x.Alias == propKey);
                        if (propType != null)
                        {
                            PreValueCollection propPrevalues  = dataTypeService.GetPreValuesCollectionByDataTypeId(propType.DataTypeDefinitionId);
                            PropertyEditor     propertyEditor = PropertyEditorResolver.Current.GetByAlias(propType.PropertyEditorAlias);

                            foreach (IPropertyValidator validator in propertyEditor.ValueEditor.Validators)
                            {
                                foreach (ValidationResult result in validator.Validate(propValues[propKey], propPrevalues, propertyEditor))
                                {
                                    result.ErrorMessage = "Item " + (i + 1) + " '" + propType.Name + "' " + result.ErrorMessage;
                                    yield return(result);
                                }
                            }

                            // Check mandatory
                            if (propType.Mandatory)
                            {
                                if (propValues[propKey] == null)
                                {
                                    yield return(new ValidationResult("Item " + (i + 1) + " '" + propType.Name + "' cannot be null", new[] { propKey }));
                                }
                                else if (propValues[propKey].ToString().IsNullOrWhiteSpace())
                                {
                                    yield return(new ValidationResult("Item " + (i + 1) + " '" + propType.Name + "' cannot be empty", new[] { propKey }));
                                }
                            }

                            // Check regex
                            if (!propType.ValidationRegExp.IsNullOrWhiteSpace() &&
                                propValues[propKey] != null && !propValues[propKey].ToString().IsNullOrWhiteSpace())
                            {
                                var regex = new Regex(propType.ValidationRegExp);
                                if (!regex.IsMatch(propValues[propKey].ToString()))
                                {
                                    yield return(new ValidationResult("Item " + (i + 1) + " '" + propType.Name + "' is invalid, it does not match the correct pattern", new[] { propKey }));
                                }
                            }
                        }
                    }
                }
            }
Esempio n. 8
0
            public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue)
            {
                if (editorValue.Value == null || string.IsNullOrWhiteSpace(editorValue.Value.ToString()))
                {
                    return(null);
                }

                var value = JsonConvert.DeserializeObject <List <object> >(editorValue.Value.ToString());

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

                // Issue #38 - Keep recursive property lookups working
                if (!value.Any())
                {
                    return(null);
                }

                // Process value
                for (var i = 0; i < value.Count; i++)
                {
                    var o          = value[i];
                    var propValues = ((JObject)o);

                    var contentType = NestedContentHelper.GetContentTypeFromItem(propValues);
                    if (contentType == null)
                    {
                        continue;
                    }

                    var propValueKeys = propValues.Properties().Select(x => x.Name).ToArray();

                    foreach (var propKey in propValueKeys)
                    {
                        var propType = contentType.CompositionPropertyTypes.FirstOrDefault(x => x.Alias == propKey);
                        if (propType == null)
                        {
                            if (IsSystemPropertyKey(propKey) == false)
                            {
                                // Property missing so just delete the value
                                propValues[propKey] = null;
                            }
                        }
                        else
                        {
                            // Fetch the property types prevalue
                            var propPreValues = Services.DataTypeService.GetPreValuesCollectionByDataTypeId(
                                propType.DataTypeDefinitionId);

                            // Lookup the property editor
                            var propEditor = PropertyEditorResolver.Current.GetByAlias(propType.PropertyEditorAlias);

                            // Create a fake content property data object
                            var contentPropData = new ContentPropertyData(
                                propValues[propKey], propPreValues,
                                new Dictionary <string, object>());

                            // Get the property editor to do it's conversion
                            var newValue = propEditor.ValueEditor.ConvertEditorToDb(contentPropData, propValues[propKey]);

                            // Store the value back
                            propValues[propKey] = (newValue == null) ? null : JToken.FromObject(newValue);
                        }
                    }
                }

                return(JsonConvert.SerializeObject(value));
            }
Esempio n. 9
0
            public override object ConvertDbToEditor(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
            {
                if (property.Value == null || string.IsNullOrWhiteSpace(property.Value.ToString()))
                {
                    return(string.Empty);
                }

                var value = JsonConvert.DeserializeObject <List <object> >(property.Value.ToString());

                if (value == null)
                {
                    return(string.Empty);
                }

                // Process value
                PreValueCollection preValues = null;

                for (var i = 0; i < value.Count; i++)
                {
                    var o          = value[i];
                    var propValues = ((JObject)o);

                    // convert from old style (v0.1.1) data format if necessary
                    NestedContentHelper.ConvertItemValueFromV011(propValues, propertyType.DataTypeDefinitionId, ref preValues);

                    var contentType = NestedContentHelper.GetContentTypeFromItem(propValues);
                    if (contentType == null)
                    {
                        continue;
                    }

                    var propValueKeys = propValues.Properties().Select(x => x.Name).ToArray();

                    foreach (var propKey in propValueKeys)
                    {
                        var propType = contentType.CompositionPropertyTypes.FirstOrDefault(x => x.Alias == propKey);
                        if (propType == null)
                        {
                            if (IsSystemPropertyKey(propKey) == false)
                            {
                                // Property missing so just delete the value
                                propValues[propKey] = null;
                            }
                        }
                        else
                        {
                            // Create a fake property using the property abd stored value
                            var prop = new Property(propType, propValues[propKey] == null ? null : propValues[propKey].ToString());

                            // Lookup the property editor
                            var propEditor = PropertyEditorResolver.Current.GetByAlias(propType.PropertyEditorAlias);

                            // Get the editor to do it's conversion
                            var newValue = propEditor.ValueEditor.ConvertDbToEditor(prop, propType,
                                                                                    ApplicationContext.Current.Services.DataTypeService);

                            // Store the value back
                            propValues[propKey] = (newValue == null) ? null : JToken.FromObject(newValue);
                        }
                    }
                }

                // Update the value on the property
                property.Value = JsonConvert.SerializeObject(value);

                // Pass the call down
                return(base.ConvertDbToEditor(property, propertyType, dataTypeService));
            }
        public static object ConvertPropertyToNestedContent(this PublishedPropertyType propertyType, object source, bool preview)
        {
            using (DisposableTimer.DebugDuration <PublishedPropertyType>(string.Format("ConvertPropertyToNestedContent ({0})", propertyType.DataTypeId)))
            {
                if (source != null && !source.ToString().IsNullOrWhiteSpace())
                {
                    var rawValue       = JsonConvert.DeserializeObject <List <object> >(source.ToString());
                    var processedValue = new List <IPublishedContent>();

                    var preValueCollection = NestedContentHelper.GetPreValuesCollectionByDataTypeId(propertyType.DataTypeId);
                    var preValueDictionary = preValueCollection.PreValuesAsDictionary.ToDictionary(x => x.Key, x => x.Value.Value);

                    for (var i = 0; i < rawValue.Count; i++)
                    {
                        var item = (JObject)rawValue[i];

                        // Convert from old style (v.0.1.1) data format if necessary
                        // - Please note: This call has virtually no impact on rendering performance for new style (>v0.1.1).
                        //                Even so, this should be removed eventually, when it's safe to assume that there is
                        //                no longer any need for conversion.
                        NestedContentHelper.ConvertItemValueFromV011(item, propertyType.DataTypeId, ref preValueCollection);

                        var contentTypeAlias = NestedContentHelper.GetContentTypeAliasFromItem(item);
                        if (string.IsNullOrEmpty(contentTypeAlias))
                        {
                            continue;
                        }

                        var publishedContentType = PublishedContentType.Get(PublishedItemType.Content, contentTypeAlias);
                        if (publishedContentType == null)
                        {
                            continue;
                        }

                        var propValues = item.ToObject <Dictionary <string, object> >();
                        var properties = new List <IPublishedProperty>();

                        foreach (var jProp in propValues)
                        {
                            var propType = publishedContentType.GetPropertyType(jProp.Key);
                            if (propType != null)
                            {
                                properties.Add(new DetachedPublishedProperty(propType, jProp.Value, preview));
                            }
                        }

                        // Parse out the name manually
                        object nameObj = null;
                        if (propValues.TryGetValue("name", out nameObj))
                        {
                            // Do nothing, we just want to parse out the name if we can
                        }

                        // Get the current request node we are embedded in
                        var pcr           = UmbracoContext.Current == null ? null : UmbracoContext.Current.PublishedContentRequest;
                        var containerNode = pcr != null && pcr.HasPublishedContent ? pcr.PublishedContent : null;

                        // Create the model based on our implementation of IPublishedContent
                        IPublishedContent content = new DetachedPublishedContent(
                            nameObj == null ? null : nameObj.ToString(),
                            publishedContentType,
                            properties.ToArray(),
                            containerNode,
                            i,
                            preview);

                        if (PublishedContentModelFactoryResolver.HasCurrent && PublishedContentModelFactoryResolver.Current.HasValue)
                        {
                            // Let the current model factory create a typed model to wrap our model
                            content = PublishedContentModelFactoryResolver.Current.Factory.CreateModel(content);
                        }

                        // Add the (typed) model as a result
                        processedValue.Add(content);
                    }

                    if (propertyType.IsSingleNestedContentProperty())
                    {
                        return(processedValue.FirstOrDefault());
                    }

                    return(processedValue);
                }
            }

            return(null);
        }
        public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
        {
            try
            {
                using (var timer = DisposableTimer.DebugDuration <NestedContentValueConverter>(string.Format("ConvertDataToSource ({0})", propertyType.DataTypeId)))
                {
                    if (source != null && !source.ToString().IsNullOrWhiteSpace())
                    {
                        var rawValue       = JsonConvert.DeserializeObject <List <object> >(source.ToString());
                        var processedValue = new List <IPublishedContent>();

                        var preValue    = NestedContentHelper.GetPreValuesDictionaryByDataTypeId(propertyType.DataTypeId);
                        var contentType = NestedContentHelper.GetContentTypeFromPreValue(propertyType.DataTypeId);
                        if (contentType == null)
                        {
                            return(null);
                        }

                        var publishedContentType = PublishedContentType.Get(PublishedItemType.Content, contentType.Alias);
                        if (publishedContentType == null)
                        {
                            return(null);
                        }

                        for (var i = 0; i < rawValue.Count; i++)
                        {
                            var o          = rawValue[i];
                            var propValues = ((JObject)o).ToObject <Dictionary <string, object> >();
                            var properties = new List <IPublishedProperty>();

                            foreach (var jProp in propValues)
                            {
                                var propType = publishedContentType.GetPropertyType(jProp.Key);
                                if (propType != null)
                                {
                                    properties.Add(new DetachedPublishedProperty(propType, jProp.Value));
                                }
                            }

                            // Parse out the name manually
                            object nameObj = null;
                            if (propValues.TryGetValue("name", out nameObj))
                            {
                                // Do nothing, we just want to parse out the name if we can
                            }

                            processedValue.Add(new DetachedPublishedContent(nameObj == null ? null : nameObj.ToString(), publishedContentType, properties.ToArray()));
                        }

                        // Detect min/max items == 1 and just return a single IPublishedContent
                        int minItems, maxItems;
                        if (preValue.ContainsKey("minItems") && int.TryParse(preValue["minItems"], out minItems) && minItems == 1 &&
                            preValue.ContainsKey("maxItems") && int.TryParse(preValue["maxItems"], out maxItems) && maxItems == 1)
                        {
                            return(processedValue.FirstOrDefault());
                        }

                        return(processedValue);
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.Error <NestedContentValueConverter>("Error converting value", e);
            }

            return(null);
        }
Esempio n. 12
0
            public override string ConvertDbToString(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
            {
                // Convert / validate value
                if (property.Value == null || string.IsNullOrWhiteSpace(property.Value.ToString()))
                {
                    return(string.Empty);
                }

                var value = JsonConvert.DeserializeObject <List <object> >(property.Value.ToString());

                if (value == null)
                {
                    return(string.Empty);
                }

                // Process value
                PreValueCollection preValues = null;

                for (var i = 0; i < value.Count; i++)
                {
                    var o          = value[i];
                    var propValues = ((JObject)o);

                    // convert from old style (v0.1.1) data format if necessary
                    NestedContentHelper.ConvertItemValueFromV011(propValues, propertyType.DataTypeDefinitionId, ref preValues);

                    var contentType = NestedContentHelper.GetContentTypeFromItem(propValues);
                    if (contentType == null)
                    {
                        continue;
                    }

                    var propValueKeys = propValues.Properties().Select(x => x.Name).ToArray();

                    foreach (var propKey in propValueKeys)
                    {
                        var propType = contentType.CompositionPropertyTypes.FirstOrDefault(x => x.Alias == propKey);
                        if (propType == null)
                        {
                            if (IsSystemPropertyKey(propKey) == false)
                            {
                                // Property missing so just delete the value
                                propValues[propKey] = null;
                            }
                        }
                        else
                        {
                            try
                            {
                                // Create a fake property using the property abd stored value
                                var prop = new Property(propType, propValues[propKey] == null ? null : propValues[propKey].ToString());

                                // Lookup the property editor
                                var propEditor = PropertyEditorResolver.Current.GetByAlias(propType.PropertyEditorAlias);

                                // Get the editor to do it's conversion, and store it back
                                propValues[propKey] = propEditor.ValueEditor.ConvertDbToString(prop, propType, dataTypeService);
                            }
                            catch (InvalidOperationException)
                            {
                                // https://github.com/umco/umbraco-nested-content/issues/111
                                // Catch any invalid cast operations as likely means courier failed due to missing
                                // or trashed item so couldn't convert a guid back to an int

                                propValues[propKey] = null;
                            }
                        }
                    }
                }

                // Update the value on the property
                property.Value = JsonConvert.SerializeObject(value);

                // Pass the call down
                return(base.ConvertDbToString(property, propertyType, dataTypeService));
            }
        public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
        {
            try
            {
                using (DisposableTimer.DebugDuration <NestedContentValueConverter>(string.Format("ConvertDataToSource ({0})", propertyType.DataTypeId)))
                {
                    if (source != null && !source.ToString().IsNullOrWhiteSpace())
                    {
                        var rawValue       = JsonConvert.DeserializeObject <List <object> >(source.ToString());
                        var processedValue = new List <IPublishedContent>();

                        var preValueCollection = NestedContentHelper.GetPreValuesCollectionByDataTypeId(propertyType.DataTypeId);
                        var preValueDictionary = preValueCollection.AsPreValueDictionary();

                        for (var i = 0; i < rawValue.Count; i++)
                        {
                            var item = (JObject)rawValue[i];

                            // Convert from old style (v.0.1.1) data format if necessary
                            // - Please note: This call has virtually no impact on rendering performance for new style (>v0.1.1).
                            //                Even so, this should be removed eventually, when it's safe to assume that there is
                            //                no longer any need for conversion.
                            NestedContentHelper.ConvertItemValueFromV011(item, propertyType.DataTypeId, ref preValueCollection);

                            var contentTypeAlias = NestedContentHelper.GetContentTypeAliasFromItem(item);
                            if (string.IsNullOrEmpty(contentTypeAlias))
                            {
                                continue;
                            }

                            var publishedContentType = PublishedContentType.Get(PublishedItemType.Content, contentTypeAlias);
                            if (publishedContentType == null)
                            {
                                continue;
                            }

                            var propValues = item.ToObject <Dictionary <string, object> >();
                            var properties = new List <IPublishedProperty>();

                            foreach (var jProp in propValues)
                            {
                                var propType = publishedContentType.GetPropertyType(jProp.Key);
                                if (propType != null)
                                {
                                    properties.Add(new DetachedPublishedProperty(propType, jProp.Value));
                                }
                            }

                            // Parse out the name manually
                            object nameObj = null;
                            if (propValues.TryGetValue("name", out nameObj))
                            {
                                // Do nothing, we just want to parse out the name if we can
                            }

                            processedValue.Add(new DetachedPublishedContent(
                                                   nameObj == null ? null : nameObj.ToString(),
                                                   publishedContentType,
                                                   properties.ToArray(),
                                                   i));
                        }

                        // Detect min/max items == 1 and just return a single IPublishedContent
                        int minItems, maxItems;
                        if (preValueDictionary.ContainsKey("minItems") && int.TryParse(preValueDictionary["minItems"], out minItems) && minItems == 1 &&
                            preValueDictionary.ContainsKey("maxItems") && int.TryParse(preValueDictionary["maxItems"], out maxItems) && maxItems == 1)
                        {
                            return(processedValue.FirstOrDefault());
                        }

                        return(processedValue);
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.Error <NestedContentValueConverter>("Error converting value", e);
            }

            return(null);
        }
            public IEnumerable <ValidationResult> Validate(object rawValue, PreValueCollection preValues, PropertyEditor editor)
            {
                var value = JsonConvert.DeserializeObject <List <object> >(rawValue.ToString());

                if (value == null)
                {
                    yield break;
                }

                var contentType = NestedContentHelper.GetContentTypeFromPreValue(preValues);

                if (contentType == null)
                {
                    yield break;
                }

                for (var i = 0; i < value.Count; i++)
                {
                    var o             = value[i];
                    var propValues    = ((JObject)o);
                    var propValueKeys = propValues.Properties().Select(x => x.Name).ToArray();

                    foreach (var propKey in propValueKeys)
                    {
                        var propType = contentType.PropertyTypes.FirstOrDefault(x => x.Alias == propKey);
                        if (propType != null)
                        {
                            // It would be better to pass this off to the individual property editors
                            // to validate themselves and pass the result down, however a lot of the
                            // validation checking code in core seems to be internal so for now we'll
                            // just replicate the mandatory / regex validation checks ourselves.
                            // This does of course mean we will miss any custom validators a property
                            // editor may have registered by itself, and it also means we can only
                            // validate to a single depth so having a complex property editor in a
                            // doc type could get passed validation if it can't be validated from it's
                            // stored value alone.

                            // Check mandatory
                            if (propType.Mandatory)
                            {
                                if (propValues[propKey] == null)
                                {
                                    yield return(new ValidationResult("Item " + (i + 1) + " '" + propType.Name + "' cannot be null", new[] { propKey }));
                                }
                                else if (propValues[propKey].ToString().IsNullOrWhiteSpace())
                                {
                                    yield return(new ValidationResult("Item " + (i + 1) + " '" + propType.Name + "' cannot be empty", new[] { propKey }));
                                }
                            }

                            // Check regex
                            if (!propType.ValidationRegExp.IsNullOrWhiteSpace() &&
                                propValues[propKey] != null && !propValues[propKey].ToString().IsNullOrWhiteSpace())
                            {
                                var regex = new Regex(propType.ValidationRegExp);
                                if (!regex.IsMatch(propValues[propKey].ToString()))
                                {
                                    yield return(new ValidationResult("Item " + (i + 1) + " '" + propType.Name + "' is invalid, it does not match the correct pattern", new[] { propKey }));
                                }
                            }
                        }
                    }
                }
            }
            public override string ConvertDbToString(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
            {
                // Convert / validate value
                if (property.Value == null || string.IsNullOrWhiteSpace(property.Value.ToString()))
                {
                    return(string.Empty);
                }

                var value = JsonConvert.DeserializeObject <List <object> >(property.Value.ToString());

                if (value == null)
                {
                    return(string.Empty);
                }

                var contentType = NestedContentHelper.GetContentTypeFromPreValue(propertyType.DataTypeDefinitionId);

                if (contentType == null)
                {
                    return(string.Empty);
                }

                // Process value
                for (var i = 0; i < value.Count; i++)
                {
                    var o             = value[i];
                    var propValues    = ((JObject)o);
                    var propValueKeys = propValues.Properties().Select(x => x.Name).ToArray();

                    foreach (var propKey in propValueKeys)
                    {
                        var propType = contentType.PropertyTypes.FirstOrDefault(x => x.Alias == propKey);
                        if (propType == null)
                        {
                            if (propKey != "name")
                            {
                                // Property missing so just delete the value
                                propValues[propKey] = null;
                            }
                        }
                        else
                        {
                            // Create a fake property using the property abd stored value
                            var prop = new Property(propType, propValues[propKey] == null ? null : propValues[propKey].ToString());

                            // Lookup the property editor
                            var propEditor = PropertyEditorResolver.Current.GetByAlias(propType.PropertyEditorAlias);

                            // Get the editor to do it's conversion, and store it back
                            propValues[propKey] = propEditor.ValueEditor.ConvertDbToString(prop, propType,
                                                                                           ApplicationContext.Current.Services.DataTypeService);
                        }
                    }
                }

                // Update the value on the property
                property.Value = JsonConvert.SerializeObject(value);

                // Pass the call down
                return(base.ConvertDbToString(property, propertyType, dataTypeService));
            }
Esempio n. 16
0
            public override object ConvertDbToEditor(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
            {
                if (string.IsNullOrEmpty(property.Value?.ToString()))
                {
                    return(new object[0]);
                }

                using (_profilingLogger.DebugDuration <EmbeddedContentPropertyEditor>($"ConvertDbToEditor({property.Alias})"))
                {
                    JArray source = NestedContentHelper.ConvertFromNestedContent(JArray.Parse(property.Value.ToString()));

                    List <IContentType> contentTypes = _contentTypeService.GetAllContentTypes().ToList();
                    PreValueCollection  preValues    = dataTypeService.GetPreValuesCollectionByDataTypeId(propertyType.DataTypeDefinitionId);

                    PreValue configPreValue = preValues.PreValuesAsDictionary["embeddedContentConfig"];
                    var      config         = JsonConvert.DeserializeObject <EmbeddedContentConfig>(configPreValue.Value);

                    var items = source.ToObject <EmbeddedContentItem[]>();

                    return((from indexedItem in items.Select((item, index) => new { item, index })
                            let item = indexedItem.item
                                       let index = indexedItem.index
                                                   let configDocType = config.DocumentTypes.FirstOrDefault(x => x.DocumentTypeAlias == item.ContentTypeAlias)
                                                                       where configDocType != null
                                                                       let contentType = contentTypes.FirstOrDefault(x => x.Alias == item.ContentTypeAlias)
                                                                                         let tabs = (from pg in contentType.CompositionPropertyGroups
                                                                                                     orderby pg.SortOrder
                                                                                                     group pg by pg.Name into groupedByTabName
                                                                                                     let firstTab = groupedByTabName.First()
                                                                                                                    let propertyTypes = groupedByTabName.SelectMany(x => x.PropertyTypes)
                                                                                                                                        select new TabWithKey <EmbeddedContentPropertyDisplay>()
                    {
                        Id = firstTab.Id,
                        Key = firstTab.Key,
                        Label = UmbracoDictionaryTranslate(firstTab.Name),
                        Alias = firstTab.Key.ToString(),
                        Properties = from pt in propertyTypes
                                     orderby pt.SortOrder
                                     let value = GetPropertyValue(item.Properties, pt.Alias)
                                                 let p = GetProperty(pt, value)
                                                         where p != null
                                                         select p
                    }).ToList()
                                                                                                    where contentType != null
                                                                                                    select new EmbeddedContentItemDisplay
                    {
                        Key = item.Key,
                        AllowEditingName = configDocType.AllowEditingName == "1",
                        ContentTypeAlias = item.ContentTypeAlias,
                        ContentTypeName = UmbracoDictionaryTranslate(contentType.Name),
                        Description = UmbracoDictionaryTranslate(contentType.Description),
                        CreateDate = item.CreateDate,
                        UpdateDate = item.UpdateDate,
                        CreatorId = item.CreatorId,
                        WriterId = item.WriterId,
                        Icon = contentType.Icon,
                        Name = item.Name,
                        Published = item.Published,
                        SettingsTab = configDocType.SettingsTabKey.HasValue ? tabs.FirstOrDefault(x => x.Key == configDocType.SettingsTabKey) : null,
                        Tabs = configDocType.SettingsTabKey.HasValue ? tabs.Where(x => x.Key != configDocType.SettingsTabKey) : tabs
                    }).ToList());
                }
            }