/// <summary> /// Ensure that sub-editor values are translated through their FromEditor methods /// </summary> /// <param name="editorValue"></param> /// <param name="currentValue"></param> /// <returns></returns> public override object FromEditor(ContentPropertyData editorValue, object currentValue) { if (editorValue.Value == null || string.IsNullOrWhiteSpace(editorValue.Value.ToString())) { return(null); } BlockEditorData blockEditorData; try { blockEditorData = _blockEditorValues.DeserializeAndClean(editorValue.Value); } catch (JsonSerializationException) { // if this occurs it means the data is invalid, shouldn't happen but has happened if we change the data format. return(string.Empty); } if (blockEditorData == null || blockEditorData.BlockValue.ContentData.Count == 0) { return(string.Empty); } foreach (var row in blockEditorData.BlockValue.ContentData) { foreach (var prop in row.PropertyValues) { // Fetch the property types prevalue var propConfiguration = _dataTypeService.GetDataType(prop.Value.PropertyType.DataTypeId).Configuration; // Lookup the property editor var propEditor = _propertyEditors[prop.Value.PropertyType.PropertyEditorAlias]; if (propEditor == null) { continue; } // Create a fake content property data object var contentPropData = new ContentPropertyData(prop.Value.Value, propConfiguration); // Get the property editor to do it's conversion var newValue = propEditor.GetValueEditor().FromEditor(contentPropData, prop.Value.Value); // update the raw value since this is what will get serialized out row.RawPropertyValues[prop.Key] = newValue; } } // return json return(JsonConvert.SerializeObject(blockEditorData.BlockValue)); }
public override void Extracting(Item item) { ContentPropertyData cpd = (ContentPropertyData)item; foreach (var cp in cpd.Data.Where(X => X.Value != null && localLinkDataTypes.Contains(X.DataTypeEditor.ToString().ToLower()))) { if (cp.Value != null && cp.Value.ToString().IndexOf("{locallink:", StringComparison.OrdinalIgnoreCase) >= 0) { Helpers.LocalLinkResolver res = new Helpers.LocalLinkResolver(); cp.Value = res.ReplaceLocalLinks(cp.Value.ToString(), false, item); } } }
/// <summary> /// When multiple values are selected a json array will be posted back so we need to format for storage in /// the database which is a comma separated string value /// </summary> /// <param name="editorValue"></param> /// <param name="currentValue"></param> /// <returns></returns> public override object FromEditor(ContentPropertyData editorValue, object currentValue) { var json = editorValue.Value as JArray; if (json == null) { return(null); } var values = json.Select(item => item.Value <string>()).ToArray(); return(JsonConvert.SerializeObject(values)); }
/// <summary> /// Constructor specifies the defaults and sets the ContentPropertyData being used to set the tag values which /// can be used to dynamically adjust the tags definition for this property. /// </summary> /// <param name="propertySaving"></param> /// <param name="tagsAttribute"></param> protected TagPropertyDefinition(ContentPropertyData propertySaving, SupportTagsAttribute tagsAttribute) { PropertySaving = propertySaving; TagsAttribute = tagsAttribute; Delimiter = tagsAttribute.Delimiter; ReplaceTags = tagsAttribute.ReplaceTags; TagGroup = tagsAttribute.TagGroup; var preValues = propertySaving.PreValues.PreValuesAsDictionary; StorageType = preValues.ContainsKey("storageType") && preValues["storageType"].Value == TagCacheStorageType.Json.ToString() ? TagCacheStorageType.Json : TagCacheStorageType.Csv; }
public override object FromEditor(ContentPropertyData editorValue, object currentValue) { string json = editorValue.Value?.ToString(); var modelValue = _deserializer.Deserialize(json); if (modelValue == null) { return(base.FromEditor(editorValue, currentValue)); } JArray fromEditor(ContentBlockModelValue block) { if (_utils.GetDataType(block.DefinitionId) is IDataType dataType && dataType.Editor?.GetValueEditor() is IDataValueEditor valueEditor) { var propertyData = new ContentPropertyData(block.Content.ToString(), dataType.Configuration); try { var ncJson = valueEditor.FromEditor(propertyData, null)?.ToString(); if (!string.IsNullOrWhiteSpace(ncJson)) { return(JArray.Parse(ncJson)); } } catch { return(block.Content); } } // Fallback: return the original value return(block.Content); } if (modelValue.Header != null) { modelValue.Header.Content = fromEditor(modelValue.Header); } if (modelValue.Blocks?.Any() == true) { foreach (var block in modelValue.Blocks) { block.Content = fromEditor(block); } } return(JsonConvert.SerializeObject(modelValue, Formatting.None)); }
public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue) { var value = editorValue?.Value?.ToString(); if (value == null || string.IsNullOrWhiteSpace(value)) { return(base.ConvertEditorToDb(editorValue, currentValue)); } var model = JsonConvert.DeserializeObject <PropertyListValue>(value); if (model == null || model.DataTypeGuid.Equals(Guid.Empty) || model.Values == null) { return(base.ConvertEditorToDb(editorValue, currentValue)); } var dataTypeService = ApplicationContext.Current.Services.DataTypeService; var dtd = dataTypeService.GetDataTypeDefinitionById(model.DataTypeGuid); if (dtd == null) { return(base.ConvertEditorToDb(editorValue, currentValue)); } var preValues = dataTypeService.GetPreValuesCollectionByDataTypeId(dtd.Id); if (preValues == null) { return(base.ConvertEditorToDb(editorValue, currentValue)); } var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias); if (propEditor == null) { return(base.ConvertEditorToDb(editorValue, currentValue)); } for (var i = 0; i < model.Values.Count; i++) { var obj = model.Values[i]; var propData = new ContentPropertyData(obj, preValues, new Dictionary <string, object>()); var newValue = propEditor.ValueEditor.ConvertEditorToDb(propData, obj); model.Values[i] = (newValue == null) ? null : JToken.FromObject(newValue); } return(JsonConvert.SerializeObject(model)); }
public override bool ShouldExecute(Item item, Core.Enums.ItemEvent itemEvent) { ContentPropertyData cpd = (ContentPropertyData)item; foreach (var data in cpd.Data) { if (data.Value != null && mediaPickerDataTypes.ContainsValue(data.DataTypeEditor.ToString().ToLower())) { return(true); } } return(false); }
protected object ConvertEditorToDb_Fake(string propEditorAlias, object value) { // Lookup the property editor var fakePropEditor = PropertyEditorResolver.Current.GetByAlias(propEditorAlias); // Create a fake content property data object (note, we don't have a prevalue, so passing in null) var fakeContentPropData = new ContentPropertyData(value, null, new Dictionary <string, object>()); // Get the property editor to do it's conversion var fakeNewValue = fakePropEditor.ValueEditor.ConvertEditorToDb(fakeContentPropData, value); // Store the value back return(fakeNewValue == null ? null : fakeNewValue.ToString()); }
public override bool ShouldExecute(Item item, Core.Enums.ItemEvent itemEvent) { ContentPropertyData cpd = (ContentPropertyData)item; foreach (var cp in cpd.Data.Where(X => X.Value != null && localLinkDataTypes.Contains(X.DataTypeEditor.ToString().ToLower()))) { if (cp.Value != null && cp.Value.ToString().IndexOf("{locallink:", StringComparison.OrdinalIgnoreCase) >= 0) { return(true); } } return(false); }
public override bool ShouldExecute(Item item, Core.Enums.ItemEvent itemEvent) { ContentPropertyData cpd = (ContentPropertyData)item; foreach (var data in cpd.Data) { if (keyValuePrevalueEditors.ContainsValue(data.PreValueEditor.ToString().ToLower())) { return(true); } } return(false); }
protected object ConvertEditorToDb_DocType(string docTypeAlias, object value) { var contentType = ApplicationContext.Current.Services.ContentTypeService.GetContentType(docTypeAlias); // Loop through doc type properties var propValues = ((JObject)value); var propValueKeys = propValues.Properties().Select(x => x.Name).ToArray(); if (contentType != null && contentType.PropertyTypes != null) { foreach (var propKey in propValueKeys) { // Fetch the current property type var propType = contentType.PropertyTypes.FirstOrDefault(x => x.Alias.InvariantEquals(propKey)); if (propType == null) { if (propKey != "name") { // Property missing so just remove the value propValues[propKey] = null; } } else { // Fetch the property types prevalue var propPreValues = ApplicationContext.Current.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] == null ? null : propValues[propKey].ToString(), 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(propValues); }
public override void Packaging(Item item) { try { ContentPropertyData cpd = (ContentPropertyData)item; foreach (var cp in cpd.Data) { if (cp.Value != null && uploadDataTypes.Values.Contains(cp.DataTypeEditor.ToString())) { string file = cp.Value.ToString(); string dir = IO.DirectoryPart(file); if (!string.IsNullOrEmpty(file)) { if (IO.FileExists(file)) { var fi = new FileInfo(Umbraco.Courier.Core.Context.Current.MapPath(file)); string ext = fi.Extension.ToLower().Trim('.'); //add file as a resource item.Resources.Add(file); if (umbraco.UmbracoSettings.ImageFileTypes.ToLower().Contains(ext)) { string name = fi.Name.Substring(0, (fi.Name.LastIndexOf('.'))); foreach (VirtualFile img in HostingEnvironment.VirtualPathProvider.GetDirectory(dir).Files) { //it's not the same file, but has the same start, hence it's a thumbnail if (img.Name != fi.Name && img.Name.StartsWith(name)) { string relPath = dir + img.Name;; //add file as a resource item.Resources.Add(relPath); } } } } } } } } catch (Exception ex) { Logging._Debug(ex.ToString()); } }
public override object?FromEditor(ContentPropertyData editorValue, object?currentValue) { if (editorValue.Value is JArray dtos) { // Clean up redundant/default data foreach (var dto in dtos.Values <JObject>()) { MediaWithCropsDto.Prune(dto); } return(dtos.ToString(Formatting.None)); } return(base.FromEditor(editorValue, currentValue)); }
public override bool ShouldExecute(Item item, Core.Enums.ItemEvent itemEvent) { if (item.GetType() == typeof(ContentPropertyData)) { ContentPropertyData cpd = (ContentPropertyData)item; foreach (var cp in cpd.Data) { if (cp.Value != null && macroDataTypes.Contains(cp.DataTypeEditor.ToString().ToLower())) { return(true); } } } return(false); }
public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue) { if (editorValue.Value == null || string.IsNullOrEmpty(editorValue.Value.ToString())) { return(""); } var dataFormat = editorValue.PreValues.PreValuesAsDictionary["dataformat"].Value; // Grab the angular formatted value var adminModel = JsonConvert.DeserializeObject <UrlPickerState>(editorValue.Value.ToString()); // Serialized return string string serializedData = null; switch (dataFormat.ToLower()) { case "xml": serializedData = new XElement("url-picker", new XAttribute("mode", adminModel.Mode), new XElement("new-window", adminModel.NewWindow), new XElement("node-id", adminModel.NodeId), new XElement("url", adminModel.Url), new XElement("link-title", adminModel.Title) ).ToString(); break; case "csv": // Making sure to escape commas: serializedData = adminModel.Mode + "," + adminModel.NewWindow + "," + adminModel.NodeId + "," + adminModel.Url.Replace(",", "-") + "," + adminModel.Title.Replace(",", "-"); break; case "json": serializedData = JsonConvert.SerializeObject(adminModel); break; default: throw new NotImplementedException(); } return(serializedData); }
/// <summary> /// When multiple values are selected a json array will be posted back so we need to format for storage in /// the database which is a comma separated string value /// </summary> /// <param name="editorValue"></param> /// <param name="currentValue"></param> /// <returns></returns> public override object?FromEditor(ContentPropertyData editorValue, object?currentValue) { if (editorValue.Value is not JArray json || json.HasValues == false) { return(null); } var values = json.Select(item => item.Value <string>()).ToArray(); if (values.Length == 0) { return(null); } return(JsonConvert.SerializeObject(values, Formatting.None)); }
public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue) { var value = editorValue?.Value?.ToString(); if (value == null || string.IsNullOrWhiteSpace(value)) { return(base.ConvertEditorToDb(editorValue, currentValue)); } var model = JsonConvert.DeserializeObject <TupleValueItems>(value); if (model == null || model.Count == 0) { return(base.ConvertEditorToDb(editorValue, currentValue)); } var dataTypeService = ApplicationContext.Current.Services.DataTypeService; for (var i = 0; i < model.Count; i++) { var obj = model[i]; var dtd = dataTypeService.GetDataTypeDefinitionById(obj.DataTypeGuid); // TODO: Caching? [LK:2018-06-25] if (dtd == null) { continue; } var preValues = dataTypeService.GetPreValuesCollectionByDataTypeId(dtd.Id); // TODO: Caching? [LK:2018-06-25] if (preValues == null) { continue; } var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias); if (propEditor == null) { continue; } var propData = new ContentPropertyData(obj.Value, preValues, new Dictionary <string, object>()); model[i].Value = propEditor.ValueEditor.ConvertEditorToDb(propData, obj.Value); } return(JsonConvert.SerializeObject(model)); }
/// <summary> /// A method to deserialize the string value that has been saved in the content editor /// to an object to be stored in the database. /// </summary> /// <param name="editorValue"></param> /// <param name="currentValue"> /// The current value that has been persisted to the database for this editor. This value may be useful for /// how the value then get's deserialized again to be re-persisted. In most cases it will probably not be used. /// </param> /// <param name="languageId"></param> /// <param name="segment"></param> /// <returns></returns> /// <remarks> /// By default this will attempt to automatically convert the string value to the value type supplied by ValueType. /// /// If overridden then the object returned must match the type supplied in the ValueType, otherwise persisting the /// value to the DB will fail when it tries to validate the value type. /// </remarks> public virtual object FromEditor(ContentPropertyData editorValue, object currentValue) { //if it's json but it's empty json, then return null if (ValueType.InvariantEquals(ValueTypes.Json) && editorValue.Value != null && editorValue.Value.ToString().DetectIsEmptyJson()) { return(null); } var result = TryConvertValueToCrlType(editorValue.Value); if (result.Success == false) { StaticApplicationLogging.Logger.LogWarning("The value {EditorValue} cannot be converted to the type {StorageTypeValue}", editorValue.Value, ValueTypes.ToStorageType(ValueType)); return(null); } return(result.Result); }
/// <summary> /// A method to deserialize the string value that has been saved in the content editor /// to an object to be stored in the database. /// </summary> /// <param name="editorValue"></param> /// <param name="currentValue"> /// The current value that has been persisted to the database for this editor. This value may be usesful for /// how the value then get's deserialized again to be re-persisted. In most cases it will probably not be used. /// </param> /// <returns></returns> /// <remarks> /// By default this will attempt to automatically convert the string value to the value type supplied by ValueType. /// /// If overridden then the object returned must match the type supplied in the ValueType, otherwise persisting the /// value to the DB will fail when it tries to validate the value type. /// </remarks> public virtual object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue) { //if it's json but it's empty json, then return null if (ValueType.InvariantEquals(PropertyEditorValueTypes.Json) && editorValue.Value != null && editorValue.Value.ToString().DetectIsEmptyJson()) { return(null); } var result = TryConvertValueToCrlType(editorValue.Value); if (result.Success == false) { LogHelper.Warn <PropertyValueEditor>("The value " + editorValue.Value + " cannot be converted to the type " + GetDatabaseType()); return(null); } return(result.Result); }
public override void Extracting(Item item) { ContentPropertyData cpd = (ContentPropertyData)item; foreach (var cp in cpd.Data) { if (cp.Value != null && RelatedLinksGuid.Contains(cp.DataTypeEditor)) { string xml = cp.Value.ToString(); try { XmlDocument xd = new XmlDocument(); xd.LoadXml(xml); bool changed = false; foreach (XmlNode node in xd.SelectNodes("//link [@type ='internal' or @type = 'media']")) { XmlAttribute link = node.Attributes["link"]; if (link != null && !string.IsNullOrEmpty(link.Value)) { Guid guid; if (Guid.TryParse(link.Value, out guid)) { int nodeID = PersistenceManager.Default.GetNodeId(guid); if (nodeID > 0) { link.Value = nodeID.ToString(); changed = true; } } } } if (changed) { cp.Value = xd.OuterXml; } } catch (Exception ex) { RevisionLog.Instance.Error(item, this, RevisionLog.ItemDataResolvers, ex.ToString()); } } } }
/// <summary> /// Maps the dto property values to the persisted model /// </summary> /// <typeparam name="TPersisted"></typeparam> /// <param name="contentItem"></param> protected virtual void MapPropertyValues <TPersisted>(ContentBaseItemSave <TPersisted> contentItem) where TPersisted : IContentBase { //Map the property values foreach (var p in contentItem.ContentDto.Properties) { //get the dbo property var dboProperty = contentItem.PersistedContent.Properties[p.Alias]; //create the property data to send to the property editor var d = new Dictionary <string, object>(); //add the files if any var files = contentItem.UploadedFiles.Where(x => x.PropertyAlias == p.Alias).ToArray(); if (files.Length > 0) { d.Add("files", files); } var data = new ContentPropertyData(p.Value, p.PreValues, d); //get the deserialized value from the property editor if (p.PropertyEditor == null) { LogHelper.Warn <ContentController>("No property editor found for property " + p.Alias); } else { var valueEditor = p.PropertyEditor.ValueEditor; //don't persist any bound value if the editor is readonly if (valueEditor.IsReadOnly == false) { var propVal = p.PropertyEditor.ValueEditor.ConvertEditorToDb(data, dboProperty.Value); var supportTagsAttribute = TagExtractor.GetAttribute(p.PropertyEditor); if (supportTagsAttribute != null) { TagExtractor.SetPropertyTags(dboProperty, data, propVal, supportTagsAttribute); } else { dboProperty.Value = propVal; } } } } }
/// <summary> /// Format the data for persistence /// This to ensure if a RTE is used in a Grid cell/control that we parse it for tmp stored images /// to persist to the media library when we go to persist this to the DB /// </summary> /// <param name="editorValue"></param> /// <param name="currentValue"></param> /// <returns></returns> public override object?FromEditor(ContentPropertyData editorValue, object?currentValue) { if (editorValue.Value == null) { return(null); } // editorValue.Value is a JSON string of the grid var rawJson = editorValue.Value.ToString(); if (rawJson.IsNullOrWhiteSpace()) { return(null); } var config = editorValue.DataTypeConfiguration as GridConfiguration; GuidUdi?mediaParent = config?.MediaParentId; Guid mediaParentId = mediaParent?.Guid ?? Guid.Empty; GridValue?grid = DeserializeGridValue(rawJson !, out var rtes, out _, out _); var userId = _backOfficeSecurityAccessor?.BackOfficeSecurity?.CurrentUser?.Id ?? Constants.Security.SuperUserId; if (rtes is null) { return(JsonConvert.SerializeObject(grid, Formatting.None)); } // Process the rte values foreach (GridValue.GridControl rte in rtes) { // Parse the HTML var html = rte.Value?.ToString(); if (html is not null) { var parseAndSavedTempImages = _pastedImages.FindAndPersistPastedTempImages(html, mediaParentId, userId, _imageUrlGenerator); var editorValueWithMediaUrlsRemoved = _imageSourceParser.RemoveImageSources(parseAndSavedTempImages); rte.Value = editorValueWithMediaUrlsRemoved; } } // Convert back to raw JSON for persisting return(JsonConvert.SerializeObject(grid, Formatting.None)); }
public override void Extracting(Item item) { ContentPropertyData cpd = (ContentPropertyData)item; foreach (var cp in cpd.Data) { if (cp.Value != null && contentPickerDataTypes.Values.Contains(cp.DataTypeEditor.ToString().ToLower())) { if (Core.Helpers.Dependencies.IsNodeGuidList(cp.Value.ToString())) { //a content picker either stores IDs as a single int or comma seperated string[] vals = cp.Value.ToString().Split(','); string newVals = string.Empty; bool changed = false; foreach (string val in vals) { if (!string.IsNullOrEmpty(val)) { Guid docGUID; if (Guid.TryParse(val, out docGUID)) { int nodeId = PersistenceManager.Default.GetNodeId(docGUID, NodeObjectTypes.Document); if (nodeId != 0) { newVals += nodeId.ToString() + ","; changed = true; } } else { newVals += val.Trim() + ','; } } } //replace the GUIDs with int IDs, everything is now back to normal... if (changed) { cp.Value = newVals.Trim(','); } } } } }
public override void Extracting(Item item) { ContentPropertyData cpd = (ContentPropertyData)item; foreach (var cp in cpd.Data) { if (keyValuePrevalueEditors.Values.Contains(cp.PreValueEditor.ToLower()) && cp.Value != null) { //nonConvert indicator string value = cp.Value.ToString(); bool nonConvert = value.StartsWith("¤"); value = value.TrimStart('¤'); string[] vals = value.Split(','); string newVals = string.Empty; ItemIdentifier itemid = new ItemIdentifier(cp.DataType.ToString(), ProviderIDCollection.dataTypeItemProviderGuid); if (nonConvert) { cp.Value = value.Trim(','); } else { DataType dt = PersistenceManager.Default.RetrieveItem <DataType>(itemid); if (dt != null) { foreach (string s in vals) { var val = dt.Prevalues.Where(x => x.Value == s).FirstOrDefault(); if (val != null) { newVals += val.Id.ToString() + ","; } } cp.Value = newVals.Trim(','); } } } } }
public override bool ShouldExecute(Item item, Core.Enums.ItemEvent itemEvent) { ContentPropertyData cpd = (ContentPropertyData)item; foreach (var cp in cpd.Data.Where(x => macroDataTypes.Contains(x.DataTypeEditor.ToString(), StringComparer.OrdinalIgnoreCase))) { if ( cp.Value != null && (cp.Value.ToString().IndexOf("umbraco:macro", StringComparison.OrdinalIgnoreCase) > 0 || cp.Value.ToString().IndexOf("UMBRACO_MACRO", StringComparison.OrdinalIgnoreCase) > 0) ) { return(true); } } return(false); }
/// <inheritdoc /> public override object?FromEditor(ContentPropertyData editorValue, object?currentValue) { var value = editorValue.Value?.ToString(); if (string.IsNullOrEmpty(value)) { return(null); } if (editorValue.Value is JArray json) { return(json.HasValues ? json.Select(x => x.Value <string>()) : null); } if (string.IsNullOrWhiteSpace(value) == false) { return(value.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries)); } return(null); }
public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue) { // Convert / validate value if (editorValue.Value == null || string.IsNullOrWhiteSpace(editorValue.Value.ToString())) { return(null); } var value = JsonConvert.DeserializeObject <JToken>(editorValue.Value.ToString()); if (value == null || (value is JArray && ((JArray)value).Count == 0)) { return(null); } // Process value ConvertEditorToDbRecursive(value, editorValue, currentValue); // Return value return(JsonConvert.SerializeObject(value)); }
public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue) { if (editorValue.Value == null || editorValue.Value.ToString().IsNullOrWhiteSpace()) { return(string.Empty); } try { var value = JsonConvert.DeserializeObject <VortoValue>(editorValue.Value.ToString()); if (value.Values != null) { var dtd = VortoHelper.GetTargetDataTypeDefinition(value.DtdGuid); if (dtd != null) { var preValues = ApplicationContext.Current.Services.DataTypeService.GetPreValuesCollectionByDataTypeId(dtd.Id); var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias); var keys = value.Values.Keys.ToArray(); foreach (var key in keys) { var propData = new ContentPropertyData(value.Values[key], preValues, new Dictionary <string, object>()); var newValue = propEditor.ValueEditor.ConvertEditorToDb(propData, value.Values[key]); value.Values[key] = (newValue == null) ? null : JToken.FromObject(newValue); } } else { LogHelper.Error <VortoPropertyValueEditor>($"Unabled to locate target DTD for source DTD ${value.DtdGuid}", null); } } return(JsonConvert.SerializeObject(value)); } catch (Exception ex) { LogHelper.Error <VortoPropertyValueEditor>("Error converting DB value to Editor", ex); } return(base.ConvertEditorToDb(editorValue, currentValue)); }
public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue) { // Convert / validate value if (editorValue.Value == null) { return(string.Empty); } var dbValue = editorValue.Value.ToString(); if (string.IsNullOrWhiteSpace(dbValue)) { return(string.Empty); } var value = JsonConvert.DeserializeObject <JObject>(dbValue); if (value == null) { return(string.Empty); } // Process inner content value var markers = value.GetValue("markers") as JArray; if (markers != null) { foreach (var marker in markers) { var content = value.GetValue("content") as JObject; if (content != null) { ConvertInnerContentEditorToDb(markers, ApplicationContext.Current.Services.DataTypeService); } } } // Return value return(JsonConvert.SerializeObject(value)); }
private string ProcessFile(ContentPropertyData editorValue, ContentItemFile file, string currentPath, Guid cuid, Guid puid) { // process the file // no file, invalid file, reject change if (UploadFileTypeValidator.ValidateFileExtension(file.FileName) == false) { return(null); } // get the filepath // in case we are using the old path scheme, try to re-use numbers (bah...) var filepath = _mediaFileSystem.GetMediaPath(file.FileName, currentPath, cuid, puid); // fs-relative path using (var filestream = File.OpenRead(file.TempFilePath)) { _mediaFileSystem.AddFile(filepath, filestream, true); // must overwrite! var ext = _mediaFileSystem.GetExtension(filepath); if (_mediaFileSystem.IsImageFile(ext) && ext != ".svg") { var preValues = editorValue.PreValues.FormatAsDictionary(); var sizes = preValues.Any() ? preValues.First().Value.Value : string.Empty; try { using (var image = Image.FromStream(filestream)) _mediaFileSystem.GenerateThumbnails(image, filepath, sizes); } catch (ArgumentException ex) { // send any argument errors caused by the thumbnail generation to the log instead of failing miserably LogHelper.WarnWithException <ImageCropperPropertyValueEditor>("Could not extract image thumbnails.", ex); } } // all related properties (auto-fill) are managed by ImageCropperPropertyEditor // when the content is saved (through event handlers) } return(filepath); }
/// <summary> /// Replaces the property data Ids. /// </summary> /// <param name="item">The item.</param> /// <param name="propertyData">The property data.</param> /// <param name="direction">The direction.</param> private void ReplacePropertyDataIds(Item item, ContentProperty propertyData, Direction direction) { if (propertyData != null && propertyData.Value != null) { var dataType = ExecutionContext.DatabasePersistence.RetrieveItem<DataType>(new ItemIdentifier(propertyData.DataType.ToString(), ItemProviderIds.dataTypeItemProviderGuid)); //Fetch the Prevalues for the current Property's DataType (if its an 'Archetype config') var prevalue = dataType.Prevalues.FirstOrDefault(x => x.Alias.ToLowerInvariant().Equals("archetypeconfig")); var archetypePreValue = prevalue == null ? null : JsonConvert.DeserializeObject<ArchetypePreValue>(prevalue.Value, ArchetypeHelper.Instance.JsonSerializerSettings); RetrieveAdditionalProperties(ref archetypePreValue); //Deserialize the value of the current Property to an ArchetypeModel and set additional properties before converting values var sourceJson = propertyData.Value.ToString(); var archetype = JsonConvert.DeserializeObject<ArchetypeModel>(sourceJson, ArchetypeHelper.Instance.JsonSerializerSettings); RetrieveAdditionalProperties(ref archetype, archetypePreValue); if (archetype != null) { // get the `PropertyItemProvider` from the collection. var propertyItemProvider = ItemProviderCollection.Instance.GetProvider(ItemProviderIds.propertyDataItemProviderGuid, ExecutionContext); foreach (var property in archetype.Fieldsets.SelectMany(x => x.Properties)) { if (property == null || string.IsNullOrWhiteSpace(property.PropertyEditorAlias)) continue; // create a 'fake' item for Courier to process var fakeItem = new ContentPropertyData { ItemId = item.ItemId, Name = string.Format("{0} [{1}: Nested {2} ({3})]", new[] { item.Name, EditorAlias, property.PropertyEditorAlias, property.Alias }), Data = new List<ContentProperty> { new ContentProperty { Alias = property.Alias, DataType = ExecutionContext.DatabasePersistence.GetUniqueId(property.DataTypeId, UmbracoNodeObjectTypeIds.DataType), PropertyEditorAlias = property.PropertyEditorAlias, Value = property.Value } } }; if (direction == Direction.Packaging) { try { // run the 'fake' item through Courier's data resolvers ResolutionManager.Instance.PackagingItem(fakeItem, propertyItemProvider); } catch (Exception ex) { CourierLogHelper.Error<ArchetypeDataResolver>(string.Concat("Error packaging data value: ", fakeItem.Name), ex); } // pass up the dependencies and resources item.Dependencies.AddRange(fakeItem.Dependencies); item.Resources.AddRange(fakeItem.Resources); } else if (direction == Direction.Extracting) { try { // run the 'fake' item through Courier's data resolvers ResolutionManager.Instance.ExtractingItem(fakeItem, propertyItemProvider); } catch (Exception ex) { CourierLogHelper.Error<ArchetypeDataResolver>(string.Concat("Error extracting data value: ", fakeItem.Name), ex); } } if (fakeItem.Data != null && fakeItem.Data.Any()) { var firstDataType = fakeItem.Data.FirstOrDefault(); if (firstDataType != null) { // set the resolved property data value property.Value = firstDataType.Value; // (if packaging) add a dependency for the property's data-type if (direction == Direction.Packaging) item.Dependencies.Add(firstDataType.DataType.ToString(), ItemProviderIds.dataTypeItemProviderGuid); } } } // serialize the Archetype back to a string propertyData.Value = archetype.SerializeForPersistence(); } } }
private void ReplacePropertyDataIds(Item item, ContentProperty propertyData, Direction direction) { if (propertyData != null && propertyData.Value != null) { // just look at the amount of dancing around we have to do in order to fake a `PublishedPropertyType`?! var dataTypeId = PersistenceManager.Default.GetNodeId(propertyData.DataType, NodeObjectTypes.DataType); var fakePropertyType = this.CreateDummyPropertyType(dataTypeId, this.EditorAlias); var converter = new ArchetypeValueConverter(); var archetype = (ArchetypeModel)converter.ConvertDataToSource(fakePropertyType, propertyData.Value, false); if (archetype != null) { // create a 'fake' provider, as ultimately only the 'Packaging' enum will be referenced. var fakeItemProvider = new PropertyItemProvider(); foreach (var property in archetype.Fieldsets.SelectMany(x => x.Properties)) { if (property == null || string.IsNullOrWhiteSpace(property.PropertyEditorAlias)) continue; // create a 'fake' item for Courier to process var fakeItem = new ContentPropertyData() { ItemId = item.ItemId, Name = string.Format("{0} [{1}: Nested {2} ({3})]", new[] { item.Name, this.EditorAlias, property.PropertyEditorAlias, property.Alias }), Data = new List<ContentProperty> { new ContentProperty { Alias = property.Alias, DataType = PersistenceManager.Default.GetUniqueId(property.DataTypeId, NodeObjectTypes.DataType), PropertyEditorAlias = property.PropertyEditorAlias, Value = property.Value } } }; if (direction == Direction.Packaging) { try { // run the 'fake' item through Courier's data resolvers ResolutionManager.Instance.PackagingItem(fakeItem, fakeItemProvider); } catch (Exception ex) { LogHelper.Error<ArchetypeDataResolver>(string.Concat("Error packaging data value: ", fakeItem.Name), ex); } // pass up the dependencies and resources item.Dependencies.AddRange(fakeItem.Dependencies); item.Resources.AddRange(fakeItem.Resources); } else if (direction == Direction.Extracting) { try { // run the 'fake' item through Courier's data resolvers ResolutionManager.Instance.ExtractingItem(fakeItem, fakeItemProvider); } catch (Exception ex) { LogHelper.Error<ArchetypeDataResolver>(string.Concat("Error extracting data value: ", fakeItem.Name), ex); } } if (fakeItem.Data != null && fakeItem.Data.Any()) { var firstDataType = fakeItem.Data.FirstOrDefault(); if (firstDataType != null) { // set the resolved property data value property.Value = firstDataType.Value; // (if packaging) add a dependency for the property's data-type if (direction == Direction.Packaging) item.Dependencies.Add(firstDataType.DataType.ToString(), ProviderIDCollection.dataTypeItemProviderGuid); } } } if (item.Name.Contains(string.Concat(this.EditorAlias, ": Nested"))) { // if the Archetype is nested, then we only want to return the object itself - not a serialized string propertyData.Value = archetype; } else { // if the Archetype is the root/container, then we can serialize it to a string propertyData.Value = archetype.SerializeForPersistence(); } } } }
private void ProcessProperty(Item item, ContentProperty propertyData, Direction direction) { var propertyItemProvider = ItemProviderCollection.Instance.GetProvider(ItemProviderIds.propertyDataItemProviderGuid, ExecutionContext); if (direction == Direction.Packaging) item.Dependencies.Add(propertyData.DataType.ToString(), ItemProviderIds.dataTypeItemProviderGuid); var array = JsonConvert.DeserializeObject<JArray>(propertyData.Value.ToString()); foreach (var ncObj in array) { var doctypeAlias = ncObj["ncContentTypeAlias"].ToString(); var doctype = ExecutionContext.DatabasePersistence.RetrieveItem<DocumentType>(new ItemIdentifier(doctypeAlias, ItemProviderIds.documentTypeItemProviderGuid)); if (doctype == null) continue; foreach (var propertyType in doctype.Properties) { object o; if ((o = ncObj[propertyType.Alias]) != null) { //make fake item var value = o.ToString(); var datatype = ExecutionContext.DatabasePersistence.RetrieveItem<DataType>( new ItemIdentifier(propertyType.DataTypeDefinitionId.ToString(), ItemProviderIds.dataTypeItemProviderGuid)); var fakeItem = new ContentPropertyData { ItemId = item.ItemId, Name = string.Format("{0} [{1}: Nested {2} ({3})]", item.Name, EditorAlias, datatype.PropertyEditorAlias, propertyType.Alias), Data = new List<ContentProperty> { new ContentProperty { Alias = propertyType.Alias, DataType = datatype.UniqueID, PropertyEditorAlias = datatype.PropertyEditorAlias, Value = value } } }; if (direction == Direction.Packaging) { try { // run the 'fake' item through Courier's data resolvers ResolutionManager.Instance.PackagingItem(fakeItem, propertyItemProvider); } catch (Exception ex) { CourierLogHelper.Error<NestedContentDataResolverProvider>( string.Concat("Error packaging data value: ", fakeItem.Name), ex); } } else if (direction == Direction.Extracting) { try { // run the 'fake' item through Courier's data resolvers ResolutionManager.Instance.ExtractingItem(fakeItem, propertyItemProvider); } catch (Exception ex) { CourierLogHelper.Error<NestedContentDataResolverProvider>( string.Concat("Error extracting data value: ", fakeItem.Name), ex); } } // pass up the dependencies and resources item.Dependencies.AddRange(fakeItem.Dependencies); item.Resources.AddRange(fakeItem.Resources); if (fakeItem.Data != null && fakeItem.Data.Any()) { var firstDataType = fakeItem.Data.FirstOrDefault(); if (firstDataType != null) { // set the resolved property data value string serializedValue = firstDataType.Value as string ?? JsonConvert.SerializeObject(firstDataType.Value); ncObj[propertyType.Alias] = new JValue(serializedValue); // (if packaging) add a dependency for the property's data-type if (direction == Direction.Packaging) item.Dependencies.Add(firstDataType.DataType.ToString(), ItemProviderIds.dataTypeItemProviderGuid); } } } } } propertyData.Value = JsonConvert.SerializeObject(array); }
private object ResolvePropertyItemData( Item item, ItemProvider itemProvider, object value, string propertyEditorAlias, string propertyTypeAlias, Guid dataTypeGuid, Direction direction = Direction.Packaging) { // create a 'fake' item for Courier to process var fakeItem = new ContentPropertyData { ItemId = item.ItemId, Name = string.Format("{0} [{1}: {2} ({3})]", item.Name, EditorAlias, propertyEditorAlias, propertyTypeAlias), Data = new List<ContentProperty> { new ContentProperty { Alias = propertyTypeAlias, DataType = dataTypeGuid, PropertyEditorAlias = propertyEditorAlias, Value = value } } }; if (direction == Direction.Packaging) { try { // run the 'fake' item through Courier's data resolvers ResolutionManager.Instance.PackagingItem(fakeItem, itemProvider); } catch (Exception ex) { CourierLogHelper.Error<MortarDataResolver>(string.Concat("Error packaging data value: ", fakeItem.Name), ex); } // pass up the dependencies if (fakeItem.Dependencies != null && fakeItem.Dependencies.Count > 0) item.Dependencies.AddRange(fakeItem.Dependencies); // pass up the resources if (fakeItem.Resources != null && fakeItem.Resources.Count > 0) item.Resources.AddRange(fakeItem.Resources); } else if (direction == Direction.Extracting) { try { // run the 'fake' item through Courier's data resolvers ResolutionManager.Instance.ExtractingItem(fakeItem, itemProvider); item.Status = ItemStatus.NeedPostProcessing; item.PostProcess = true; } catch (Exception ex) { CourierLogHelper.Error<MortarDataResolver>(string.Concat("Error extracting data value: ", fakeItem.Name), ex); } } // return the resolved data from the 'fake' item if (fakeItem.Data != null && fakeItem.Data.Any()) return fakeItem.Data.FirstOrDefault().Value; return value; }
private void ProcessCell(Item item, ContentProperty propertyData, dynamic cell, Direction direction) { string docTypeId = cell?.value?.docType?.ToString(); string cellValue = cell?.value?.value?.ToString(); if (cellValue == null || docTypeId == null) return; var data = JsonConvert.DeserializeObject(cellValue); if (!(data is JObject)) return; var propValues = ((JObject)data).ToObject<Dictionary<string, object>>(); var docType = ExecutionContext.DatabasePersistence.RetrieveItem<DocumentType>( new ItemIdentifier(docTypeId, ItemProviderIds.documentTypeItemProviderGuid)); if (direction == Direction.Packaging) { item.Dependencies.Add(docTypeId, ItemProviderIds.documentTypeItemProviderGuid); //package doctype from guid to alias cell.value.docType = new JValue(docType.Alias); } else if (direction == Direction.Extracting) { //extract doctype from alias to guid cell.value.docType = new JValue(docType.UniqueId.ToString()); } var propertyItemProvider = ItemProviderCollection.Instance.GetProvider(ItemProviderIds.propertyDataItemProviderGuid, ExecutionContext); foreach (var prop in docType.Properties) { object value; if (!propValues.TryGetValue(prop.Alias, out value)) continue; var datatype = ExecutionContext.DatabasePersistence.RetrieveItem<DataType>( new ItemIdentifier( prop.DataTypeDefinitionId.ToString(), ItemProviderIds.dataTypeItemProviderGuid)); var fakeItem = new ContentPropertyData { ItemId = item.ItemId, Name = string.Format("{0} [{1}: Nested {2} ({3})]", item.Name, EditorAlias, datatype.PropertyEditorAlias, prop.Alias), Data = new List<ContentProperty> { new ContentProperty { Alias = prop.Alias, DataType = datatype.UniqueID, PropertyEditorAlias = datatype.PropertyEditorAlias, Value = value.ToString() } } }; if (direction == Direction.Packaging) { try { // run the 'fake' item through Courier's data resolvers ResolutionManager.Instance.PackagingItem(fakeItem, propertyItemProvider); } catch (Exception ex) { CourierLogHelper.Error<NestedContentDataResolverProvider>( string.Concat("Error packaging data value: ", fakeItem.Name), ex); } } else if (direction == Direction.Extracting) { try { // run the 'fake' item through Courier's data resolvers ResolutionManager.Instance.ExtractingItem(fakeItem, propertyItemProvider); } catch (Exception ex) { CourierLogHelper.Error<NestedContentDataResolverProvider>( string.Concat("Error extracting data value: ", fakeItem.Name), ex); } } // pass up the dependencies and resources item.Dependencies.AddRange(fakeItem.Dependencies); item.Resources.AddRange(fakeItem.Resources); if (fakeItem.Data != null && fakeItem.Data.Any()) { var firstDataType = fakeItem.Data.FirstOrDefault(); if (firstDataType != null) { // set the resolved property data value string serializedValue = firstDataType.Value as string ?? JsonConvert.SerializeObject(firstDataType.Value); object jsonValue; try { jsonValue = JsonConvert.DeserializeObject(serializedValue); } catch { jsonValue = serializedValue; } propValues[prop.Alias] = jsonValue; // (if packaging) add a dependency for the property's data-type if (direction == Direction.Packaging) item.Dependencies.Add(firstDataType.DataType.ToString(), ItemProviderIds.dataTypeItemProviderGuid); } } } var serialized = JsonConvert.SerializeObject(propValues); cell.value.value = JsonConvert.DeserializeObject(serialized); }
private void ReplacePropertyDataIds(Item item, ContentProperty propertyData, Direction direction) { if (propertyData != null && propertyData.Value != null) { var dataTypeId = ExecutionContext.DatabasePersistence.GetNodeId(propertyData.DataType, NodeObjectTypes.DataType); var fakePropertyType = this.CreateDummyPropertyType(dataTypeId, this.EditorAlias); var converter = new ArchetypeValueConverter(); var archetype = (ArchetypeModel)converter.ConvertDataToSource(fakePropertyType, propertyData.Value, false); if (archetype != null) { // get the `PropertyItemProvider` from the collection. var propertyItemProvider = ItemProviderCollection.Instance.GetProvider(ProviderIDCollection.propertyDataItemProviderGuid, this.ExecutionContext); foreach (var property in archetype.Fieldsets.SelectMany(x => x.Properties)) { if (property == null || string.IsNullOrWhiteSpace(property.PropertyEditorAlias)) continue; // create a 'fake' item for Courier to process var fakeItem = new ContentPropertyData() { ItemId = item.ItemId, Name = string.Format("{0} [{1}: Nested {2} ({3})]", new[] { item.Name, this.EditorAlias, property.PropertyEditorAlias, property.Alias }), Data = new List<ContentProperty> { new ContentProperty { Alias = property.Alias, DataType = ExecutionContext.DatabasePersistence.GetUniqueId(property.DataTypeId, NodeObjectTypes.DataType), PropertyEditorAlias = property.PropertyEditorAlias, Value = property.Value } } }; if (direction == Direction.Packaging) { try { // run the 'fake' item through Courier's data resolvers ResolutionManager.Instance.PackagingItem(fakeItem, propertyItemProvider); } catch (Exception ex) { LogHelper.Error<ArchetypeDataResolver>(string.Concat("Error packaging data value: ", fakeItem.Name), ex); } // pass up the dependencies and resources item.Dependencies.AddRange(fakeItem.Dependencies); item.Resources.AddRange(fakeItem.Resources); } else if (direction == Direction.Extracting) { try { // run the 'fake' item through Courier's data resolvers ResolutionManager.Instance.ExtractingItem(fakeItem, propertyItemProvider); } catch (Exception ex) { LogHelper.Error<ArchetypeDataResolver>(string.Concat("Error extracting data value: ", fakeItem.Name), ex); } } if (fakeItem.Data != null && fakeItem.Data.Any()) { var firstDataType = fakeItem.Data.FirstOrDefault(); if (firstDataType != null) { // set the resolved property data value property.Value = firstDataType.Value; // (if packaging) add a dependency for the property's data-type if (direction == Direction.Packaging) item.Dependencies.Add(firstDataType.DataType.ToString(), ProviderIDCollection.dataTypeItemProviderGuid); } } } // serialize the Archetype back to a string propertyData.Value = archetype.SerializeForPersistence(); } } }