private static bool VerifyDefinition(IDataTypeDefinition def) { Assert.That(def, Has .Property("Name").EqualTo("A datatype").And .Property("PropertyEditorAlias").EqualTo("nice.editor")); return(true); }
/// <summary> /// Exports an <see cref="IDataTypeDefinition"/> item to xml as an <see cref="XElement"/> /// </summary> /// <param name="dataTypeService"></param> /// <param name="dataTypeDefinition">IDataTypeDefinition type to export</param> /// <returns><see cref="XElement"/> containing the xml representation of the IDataTypeDefinition object</returns> public XElement Serialize(IDataTypeService dataTypeService, IDataTypeDefinition dataTypeDefinition) { var prevalues = new XElement("PreValues"); var prevalueList = dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDefinition.Id) .FormatAsDictionary(); var sort = 0; foreach (var pv in prevalueList) { var prevalue = new XElement("PreValue"); prevalue.Add(new XAttribute("Id", pv.Value.Id)); prevalue.Add(new XAttribute("Value", pv.Value.Value ?? "")); prevalue.Add(new XAttribute("Alias", pv.Key)); prevalue.Add(new XAttribute("SortOrder", sort)); prevalues.Add(prevalue); sort++; } var xml = new XElement("DataType", prevalues); xml.Add(new XAttribute("Name", dataTypeDefinition.Name)); //The 'ID' when exporting is actually the property editor alias (in pre v7 it was the IDataType GUID id) xml.Add(new XAttribute("Id", dataTypeDefinition.PropertyEditorAlias)); xml.Add(new XAttribute("Definition", dataTypeDefinition.Key)); xml.Add(new XAttribute("DatabaseType", dataTypeDefinition.DatabaseType.ToString())); return(xml); }
/// <summary> /// Saves an <see cref="IDataTypeDefinition"/> /// </summary> /// <param name="dataTypeDefinition"><see cref="IDataTypeDefinition"/> to save</param> /// <param name="userId">Id of the user issueing the save</param> public void Save(IDataTypeDefinition dataTypeDefinition, int userId = 0) { using (var uow = UowProvider.GetUnitOfWork()) { var saveEventArgs = new SaveEventArgs <IDataTypeDefinition>(dataTypeDefinition); if (uow.Events.DispatchCancelable(Saving, this, saveEventArgs)) { uow.Commit(); return; } if (string.IsNullOrWhiteSpace(dataTypeDefinition.Name)) { throw new ArgumentException("Cannot save datatype with empty name."); } var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow); dataTypeDefinition.CreatorId = userId; repository.AddOrUpdate(dataTypeDefinition); saveEventArgs.CanCancel = false; uow.Events.Dispatch(Saved, this, saveEventArgs); Audit(uow, AuditType.Save, "Save DataTypeDefinition performed by user", userId, dataTypeDefinition.Id); uow.Commit(); } }
public static int?GetPrevalueIdForIMember(IMember im, string propertyAlias, string propertyValue) { if (propertyValue == "") { //Return nothing return(null); } else { //find the property on the content node by its alias Property prop = im.Properties.FirstOrDefault(a => a.Alias == propertyAlias); if (prop != null) { //get data type from the property IDataTypeService dtService = ApplicationContext.Current.Services.DataTypeService; IDataTypeDefinition dtDefinition = dtService.GetDataTypeDefinitionById(prop.PropertyType.DataTypeDefinitionId); //Return property value Id return(dtService.GetPreValuesCollectionByDataTypeId(dtDefinition.Id).PreValuesAsDictionary.Where(d => d.Value.Value == propertyValue).Select(f => f.Value.Id).First()); } //Return nothing return(null); } }
private void CreateMissingValidationDisplayTypeProperty(string documentTypeAlias, string propertyName, string propertyAlias) { if (IsInDebugMode()) { var tabName = "Form labels"; var service = ApplicationContext.Current.Services.ContentTypeService; var docType = service.GetContentType(documentTypeAlias); if (docType.PropertyGroups.All(a => a.Name != tabName)) { docType.AddPropertyGroup(tabName); service.Save(docType); } if (docType.PropertyTypes.All(a => a.Alias != propertyAlias)) { var dataTypeService = ApplicationContext.Current.Services.DataTypeService; IDataTypeDefinition textBox = dataTypeService.GetAllDataTypeDefinitions(-88).First(); docType.AddPropertyType(new PropertyType(textBox) { Alias = propertyAlias, Name = propertyName }, tabName); service.Save(docType); } } }
/// <summary> /// Check if it's a parser for a data type definition /// </summary> /// <param name="dataTypeDefinition"> /// The data type definition. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool IsParserFor(IDataTypeDefinition dataTypeDefinition) { if ( !dataTypeDefinition.PropertyEditorAlias.Equals("Umbraco.MultiNodeTreePicker2")) { return(false); } var prevalues = this.dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDefinition.Id).FormatAsDictionary(); if (!prevalues.ContainsKey("startNode")) { return(false); } var startNodeType = JsonConvert.DeserializeObject <JObject>(prevalues["startNode"].Value).Value <string>("type"); if (startNodeType == null || startNodeType != "content") { return(false); } return(true); }
internal void UpdateContentType(IContentType contentType, PropertyType propertyType) { if (propertyType != null) { IDataTypeDefinition dataTypeDefinition = _dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId); PropertyGroup propertyGroup = contentType.PropertyGroups.FirstOrDefault(o => o.PropertyTypes.Contains(propertyType.Alias)); if (PropertyHelper.IsLocalizedProperty(propertyType.Alias) == false) { propertyType.Alias = PropertyHelper.GetAlias(propertyType.Alias, LocalizationContext.DefaultCulture.TwoLetterISOLanguageName); } foreach (ILanguage language in LocalizationContext.Languages) { string localizedAlias = PropertyHelper.GetAlias(PropertyHelper.GetNotLocalizedAlias(propertyType.Alias), language.CultureInfo.TwoLetterISOLanguageName); if (contentType.PropertyTypeExists(localizedAlias) == false || propertyType.Alias.Equals(localizedAlias) == false || propertyType.PropertyEditorAlias.Equals("OPTEN.UrlAlias", StringComparison.OrdinalIgnoreCase) == false) { PropertyType newPropertyType = new PropertyType(dataTypeDefinition) { Alias = localizedAlias, Name = propertyType.Name, Description = propertyType.Description, SortOrder = propertyType.SortOrder }; contentType.AddPropertyType(newPropertyType, propertyGroup.Name); } } } _contentTypeService.Save(contentType); }
internal DataTypeInfo ResolveDataType(FluidityEditorFieldConfig fieldConfig) { var dtdKey = !fieldConfig.DataTypeName.IsNullOrWhiteSpace() ? fieldConfig.DataTypeName : fieldConfig.GetOrCalculateDefinititionId().ToString(); return(_cacheProvider.GetCacheItem <DataTypeInfo>($"fluidity_datatypeinfo_{dtdKey}", () => { IDataTypeDefinition dataTypeDefinition = null; if (!fieldConfig.DataTypeName.IsNullOrWhiteSpace()) { dataTypeDefinition = _dataTypeService.GetDataTypeDefinitionByName(fieldConfig.DataTypeName); } if (dataTypeDefinition == null) { var dataTypeId = fieldConfig.GetOrCalculateDefinititionId(); dataTypeDefinition = _dataTypeService.GetDataTypeDefinitionById(dataTypeId); } var preValues = _dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDefinition.Id); var propEditor = _propertyEditorResolver.GetByAlias(dataTypeDefinition.PropertyEditorAlias); return new DataTypeInfo(dataTypeDefinition, propEditor, preValues); })); }
internal IEnumerable <PreValueFieldDisplay> Convert(IDataTypeDefinition source) { PropertyEditor propEd = null; if (source.PropertyEditorAlias.IsNullOrWhiteSpace() == false) { propEd = PropertyEditorResolver.Current.GetByAlias(source.PropertyEditorAlias); if (propEd == null) { throw new InvalidOperationException("Could not find property editor with alias " + source.PropertyEditorAlias); } } //set up the defaults var dataTypeService = _dataTypeService.Value; var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(source.Id); IDictionary <string, object> dictionaryVals = preVals.FormatAsDictionary().ToDictionary(x => x.Key, x => (object)x.Value); var result = Enumerable.Empty <PreValueFieldDisplay>().ToArray(); //if we have a prop editor, then format the pre-values based on it and create it's fields. if (propEd != null) { result = propEd.PreValueEditor.Fields.Select(Mapper.Map <PreValueFieldDisplay>).ToArray(); dictionaryVals = propEd.PreValueEditor.ConvertDbToEditor(propEd.DefaultPreValues, preVals); } MapPreValueValuesToPreValueFields(result, dictionaryVals); return(result); }
private List <string> GetFolderContainerPath(IDataTypeDefinition DataType) { var folders = new List <string>(); var ids = DataType.Path.Split(','); try { //The final one is the DataType, so exclude it foreach (var sId in ids.Take(ids.Length - 1)) { if (sId != "-1") { var container = _services.DataTypeService.GetContainer(Convert.ToInt32(sId)); folders.Add(container.Name); } } } catch (Exception e) { folders.Add("~ERROR~"); var msg = $"Error in 'GetFolderContainerPath()' for DataType {DataType.Id} - '{DataType.Name}'"; LogHelper.Error(typeof(SiteAuditorService), msg, e); } return(folders); }
private AuditableDataType ConvertIDataTypeDefinitionToAuditableDataType(IDataTypeDefinition DataType) { var properties = PropsWithDocTypes(); var adt = new AuditableDataType(); adt.Name = DataType.Name; adt.EditorAlias = DataType.PropertyEditorAlias; adt.Guid = DataType.Key; adt.Id = DataType.Id; adt.FolderPath = GetFolderContainerPath(DataType); var matchingProps = properties.Where(p => p.Key.DataTypeDefinitionId == DataType.Id); adt.UsedOnProperties = matchingProps; var preValues = _services.DataTypeService.GetPreValuesCollectionByDataTypeId(DataType.Id).PreValuesAsDictionary; adt.ConfigurationDictionary = preValues; adt.ConfigurationJson = JsonConvert.SerializeObject(preValues); adt.UsesDocTypes = new List <string>(); if (DataType.PropertyEditorAlias == "Umbraco.NestedContent") { adt.UsesDocTypes = PropertyEditorNestedContentInfo.GetRelatedDocumentTypes(preValues); } return(adt); }
//public object GetByKey(string key) //{ //} /// <summary> /// The format data type. /// </summary> /// <param name="dtd"> /// The dtd. /// </param> /// <returns> /// The <see cref="object"/>. /// </returns> /// <exception cref="HttpResponseException"> /// </exception> protected object FormatDataType(IDataTypeDefinition dtd) { if (dtd == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } var dataTypeDisplay = Mapper.Map <IDataTypeDefinition, DataTypeDisplay>(dtd); var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias); var configDictionairy = new Dictionary <string, object>(); foreach (var pv in dataTypeDisplay.PreValues) { configDictionairy.Add(pv.Key, pv.Value); } return(new { guid = dtd.Key, propertyEditorAlias = dtd.PropertyEditorAlias, config = configDictionairy, view = propEditor.ValueEditor.View }); }
/// <summary> /// This will save a data type and it's pre-values in one transaction /// </summary> /// <param name="dataTypeDefinition"></param> /// <param name="values"></param> /// <param name="userId"></param> public void SaveDataTypeAndPreValues(IDataTypeDefinition dataTypeDefinition, IDictionary <string, PreValue> values, int userId = 0) { using (var uow = UowProvider.GetUnitOfWork()) { var saveEventArgs = new SaveEventArgs <IDataTypeDefinition>(dataTypeDefinition); if (uow.Events.DispatchCancelable(Saving, this, saveEventArgs)) { uow.Commit(); return; } // if preValues contain the data type, override the data type definition accordingly if (values != null && values.ContainsKey(Constants.PropertyEditors.PreValueKeys.DataValueType)) { dataTypeDefinition.DatabaseType = PropertyValueEditor.GetDatabaseType(values[Constants.PropertyEditors.PreValueKeys.DataValueType].Value); } var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow); dataTypeDefinition.CreatorId = userId; //add/update the dtd repository.AddOrUpdate(dataTypeDefinition); //add/update the prevalues repository.AddOrUpdatePreValues(dataTypeDefinition, values); Audit(uow, AuditType.Save, string.Format("Save DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id); uow.Commit(); saveEventArgs.CanCancel = false; uow.Events.Dispatch(Saved, this, saveEventArgs); } }
/// <inheritdoc /> public bool IsParserFor(IDataTypeDefinition dataTypeDefinition) { var isArchetype = dataTypeDefinition.PropertyEditorAlias.Equals("Imulus.Archetype"); if (isArchetype && !this._processedDataTypeIds.Contains(dataTypeDefinition.Id)) { var preValues = this._dataTypeService.GetPreValuesByDataTypeId(dataTypeDefinition.Id).FirstOrDefault(); if (preValues != null) { var data = JsonConvert.DeserializeObject <JObject>(preValues); foreach (var fieldset in data["fieldsets"]) { var fieldsetAlias = fieldset["alias"].ToString(); if (!this._aliasToIdMappings.ContainsKey(fieldsetAlias)) { this._aliasToIdMappings.Add(fieldsetAlias, new List <KeyValuePair <string, Guid> >()); } foreach (var property in fieldset["properties"]) { this._aliasToIdMappings[fieldsetAlias].Add(new KeyValuePair <string, Guid>(property["alias"].ToString(), new Guid(property["dataTypeGuid"].ToString()))); } } } this._processedDataTypeIds.Add(dataTypeDefinition.Id); } return(isArchetype); }
/// <summary> /// This will save a data type and it's pre-values in one transaction /// </summary> /// <param name="dataTypeDefinition"></param> /// <param name="values"></param> /// <param name="userId"></param> public void SaveDataTypeAndPreValues(IDataTypeDefinition dataTypeDefinition, IDictionary <string, PreValue> values, int userId = 0) { if (Saving.IsRaisedEventCancelled(new SaveEventArgs <IDataTypeDefinition>(dataTypeDefinition), this)) { return; } var uow = UowProvider.GetUnitOfWork(); using (var repository = RepositoryFactory.CreateDataTypeDefinitionRepository(uow)) { dataTypeDefinition.CreatorId = userId; //add/update the dtd repository.AddOrUpdate(dataTypeDefinition); //add/update the prevalues repository.AddOrUpdatePreValues(dataTypeDefinition, values); uow.Commit(); Saved.RaiseEvent(new SaveEventArgs <IDataTypeDefinition>(dataTypeDefinition, false), this); } Audit(AuditType.Save, string.Format("Save DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id); }
internal XElement Export(IDataTypeDefinition dataTypeDefinition) { var prevalues = new XElement("PreValues"); var prevalueList = ((DataTypeService)_dataTypeService).GetDetailedPreValuesByDataTypeId(dataTypeDefinition.Id); foreach (var tuple in prevalueList) { var prevalue = new XElement("PreValue"); prevalue.Add(new XAttribute("Id", tuple.Item1)); prevalue.Add(new XAttribute("Value", tuple.Item4)); prevalue.Add(new XAttribute("Alias", tuple.Item2)); prevalue.Add(new XAttribute("SortOrder", tuple.Item3)); prevalues.Add(prevalue); } var xml = new XElement("DataType", prevalues); xml.Add(new XAttribute("Name", dataTypeDefinition.Name)); xml.Add(new XAttribute("Id", dataTypeDefinition.Id)); xml.Add(new XAttribute("Definition", dataTypeDefinition.Key)); xml.Add(new XAttribute("DatabaseType", dataTypeDefinition.DatabaseType.ToString())); return(xml); }
internal DataTypeInfo ResolveDataType(FluidityEditorFieldConfig fieldConfig, bool isReadOnly = false) { var dtdKey = !fieldConfig.DataTypeName.IsNullOrWhiteSpace() ? fieldConfig.DataTypeName : fieldConfig.GetOrCalculateDefinititionId().ToString(); dtdKey += $"_{isReadOnly}"; return(_cacheProvider.GetCacheItem <DataTypeInfo>($"fluidity_datatypeinfo_{dtdKey}", () => { IDataTypeDefinition dataTypeDefinition = null; if (!fieldConfig.DataTypeName.IsNullOrWhiteSpace()) { dataTypeDefinition = _dataTypeService.GetDataTypeDefinitionByName(fieldConfig.DataTypeName); } if (dataTypeDefinition == null) { var dataTypeId = fieldConfig.DataTypeId == 0 && isReadOnly ? -92 // If readonly and no explicit datatype defined, default to label : fieldConfig.GetOrCalculateDefinititionId(); dataTypeDefinition = _dataTypeService.GetDataTypeDefinitionById(dataTypeId); } var preValues = _dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDefinition.Id); var propEditor = _propertyEditorResolver.GetByAlias(dataTypeDefinition.PropertyEditorAlias); return new DataTypeInfo(dataTypeDefinition, propEditor, preValues); })); }
private static void UpdatePreValues(IDataTypeDefinition dataType, XElement node) { LogHelper.Debug <SyncDataType>("Pre-Values"); var preValues = node.Element("PreValues"); var dataTypeSerivce = ApplicationContext.Current.Services.DataTypeService; var existingPreValues = dataTypeSerivce.GetPreValuesCollectionByDataTypeId(dataType.Id).FormatAsDictionary(); // .PreValuesAsDictionary; if (preValues != null) { List <string> toRemove = new List <string>(); // alter any values (add new ones) foreach (var preVal in existingPreValues) { var updateVal = preValues.Elements("PreValue").Where(x => ((string)x.Attribute("Alias").Value == preVal.Key)).FirstOrDefault(); if (updateVal != null) { preVal.Value.Value = updateVal.Attribute("Value").Value; } else { // this is a delete... LogHelper.Debug <SyncDataType>("Deleting prevalue {0}", () => preVal.Key); toRemove.Add(preVal.Key); } } // remove the ones we don't have anymore... foreach (var removeKey in toRemove) { existingPreValues.Remove(removeKey); } // add the new ones.. var valuesWithKeys = preValues.Elements("PreValue") .Where(x => ((string)x.Attribute("Alias")).IsNullOrWhiteSpace() == false) .ToDictionary(key => (string)key.Attribute("Alias"), val => (string)val.Attribute("Value")); foreach (var newVal in valuesWithKeys) { if (!existingPreValues.ContainsKey(newVal.Key)) { LogHelper.Debug <SyncDataType>("Adding prevalue {0}", () => newVal.Key); existingPreValues.Add(newVal.Key, new PreValue(newVal.Value)); } } var valuesWithoutKeys = preValues.Elements("PreValue") .Where(x => ((string)x.Attribute("Alias")).IsNullOrWhiteSpace()) .Select(x => x.Attribute("Value").Value); dataTypeSerivce.SavePreValues(dataType, existingPreValues); dataTypeSerivce.SavePreValues(dataType.Id, valuesWithoutKeys); } }
/// <summary> /// Updates the specified data type. /// </summary> /// <param name="dataType">The data type to update.</param> /// <param name="model">The model to use when updating the data type.</param> /// <returns>The updated data type.</returns> internal virtual IDataTypeDefinition UpdateDataTypeDefinition(IDataTypeDefinition dataType, DataType model) { dataType.Name = model.Name; dataType.PropertyEditorAlias = model.Editor; dataType.DatabaseType = GetDatabaseType(model.Type); return(dataType); }
private static PropertyType GetIsDeletedPropertyType(IDataTypeDefinition dataType) { return(new PropertyType(dataType) { Name = "Is deleted", Alias = UmbracoAliases.Media.IsDeletedPropertyTypeAlias }); }
public static void SaveToDisk(IDataTypeDefinition item) { if (item != null) { XElement node = _engine.DataType.Export((DataTypeDefinition)item); uSyncIO.SaveXmlToDisk(node, "DataTypeDefinition", item.Name); } }
/// <summary> /// Removes the cache amongst servers for a data type /// </summary> /// <param name="dc"></param> /// <param name="dataType"></param> public static void RemoveDataTypeCache(this DistributedCache dc, IDataTypeDefinition dataType) { if (dataType != null) { dc.RefreshByJson(new Guid(DistributedCache.DataTypeCacheRefresherId), DataTypeCacheRefresher.SerializeToJsonPayload(dataType)); } }
/// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IDataTypeDefinition entity) { if (entity == null) { throw new ArgumentNullException("entity"); } return(new GuidUdi(Constants.UdiEntityType.DataType, entity.Key).EnsureClosed()); }
public static void RemoveDataTypeCache(this DistributedCache dc, IDataTypeDefinition dataType) { if (dataType == null) { return; } dc.RefreshByJson(DistributedCache.DataTypeCacheRefresherGuid, DataTypeCacheRefresher.SerializeToJsonPayload(dataType)); }
internal DataType(IDataTypeDefinition dataTypeDefinition, IUmbracoDatabaseAdaptor umbracoDatabase, IDataTypeService dataTypeService) { DataTypeDefinition = dataTypeDefinition; UmbracoDatabase = umbracoDatabase; DataTypeService = dataTypeService; }
private IContentType[] ArchetypeContentTypes(IDataTypeDefinition archetypeDataType) { var allContentTypes = _contentTypeService.GetAllContentTypes(); return(allContentTypes .Where(c => c.PropertyTypes.Any(a => a.DataTypeDefinitionId == archetypeDataType.Id) || c.CompositionPropertyTypes.Any(a => a.DataTypeDefinitionId == archetypeDataType.Id)) .ToArray()); }
/// <summary> /// Represents the information needed to map an Umbraco data type to a .NET property type /// </summary> /// <param name="dataTypeInstanceName">The data type instance name</param> /// <param name="propertyEditorAlias">The property editor alias</param> /// <param name="converterType">The type converter to use to transform the Umbraco value into its .NET counterpart</param> public DataTypeRegistration(string dataTypeInstanceName, string propertyEditorAlias, Type converterType, DatabaseType dbType, IDataTypeDefinition definition, bool codeFirstControlled) { DataTypeInstanceName = dataTypeInstanceName; PropertyEditorAlias = propertyEditorAlias; ConverterType = converterType; DbType = dbType; Definition = definition; CodeFirstControlled = codeFirstControlled; }
/// <summary> /// Updates the prevalues for the property editor /// </summary> /// <param name="prevalue">The new value</param> /// <param name="alias">The prevalue to update</param> public void UpdatePrevalueForEditor(string prevalue, string alias) { IDataTypeDefinition datatype = _dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(Alias).First(); IDictionary <string, PreValue> prevalues = _dataTypeService.GetPreValuesCollectionByDataTypeId(datatype.Id).PreValuesAsDictionary; prevalues[alias] = new PreValue(prevalue); _dataTypeService.SaveDataTypeAndPreValues(datatype, prevalues); }
public void MapFile(CmsItem item, CmsField cmsField) { IContent createdItem = ContextService.ContentService.GetById(Convert.ToInt32(item.Id)); if (createdItem == null) { return; } var field = createdItem.PropertyTypes.SingleOrDefault(type => type.Id == Convert.ToInt32(cmsField.TemplateField.FieldId)); if (field != null) { string imageIds = string.Empty; IDataTypeDefinition dataType = ContextService.DataTypeService.GetDataTypeDefinitionById(field.DataTypeDefinitionId); if (cmsField.TemplateField != null) { foreach (var file in cmsField.Files) { var fileName = file.FileName; var ext = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower(); cmsField.TemplateField.FieldName = createdItem.PropertyTypes.Single(type => type.Id == Convert.ToInt32(cmsField.TemplateField.FieldId)).Name; var path = _mediaRepository.ResolveMediaPath(item, createdItem, cmsField); if (!UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles.Contains(ext)) { switch (dataType.PropertyEditorAlias) { case "Umbraco.MediaPicker": imageIds = _mediaRepository.UploadFile(path, file).ToString(); break; case "Umbraco.MultipleMediaPicker": imageIds += (imageIds.Length > 0 ? "," : "") + _mediaRepository.UploadFile(path, file); break; default: imageIds = _mediaRepository.UploadFile(path, file).ToString(); break; } } } createdItem.SetValue(field.Alias, imageIds); ContextService.ContentService.Save(createdItem); } } else { throw new KeyNotFoundException(String.Format("Some fields has been deleted from Document Type {0}", createdItem.ContentType.Name)); } }
/// <summary> /// Converts a macro to a jsonPayload object /// </summary> /// <param name="dataType"></param> /// <returns></returns> private static JsonPayload FromDataTypeDefinition(IDataTypeDefinition dataType) { var payload = new JsonPayload { UniqueId = dataType.Key, Id = dataType.Id }; return(payload); }
internal virtual PropertyEditor GetPropertyEditor(IDataTypeDefinition dtd) { if (dtd.Id != 0) { return PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias); } return dtd.PropertyEditorAlias.Equals(Core.Constants.SECURE_STRING_PROPERTY_EDITOR_ALIAS) ? new SecureStringPropertyEditor() : (PropertyEditor)new TextboxPropertyEditor(); }
private SyncAttempt<IDataTypeDefinition> DeserializeItem(XElement node, IDataTypeDefinition item) { // pre import var mappedNode = DeserializeGetMappedValues(node); Guid key = node.Attribute("Key").ValueOrDefault(Guid.Empty); var name = node.Attribute("Name").ValueOrDefault(string.Empty); var editorAlias = node.Attribute("Id").ValueOrDefault(string.Empty); var dbType = node.Attribute("DatabaseType").ValueOrDefault(string.Empty); var databaseType = !string.IsNullOrEmpty(dbType) ? dbType.EnumParse<DataTypeDatabaseType>(true) : DataTypeDatabaseType.Ntext; if (item == null && !string.IsNullOrEmpty(name)) { // lookup by alias. LogHelper.Debug<DataTypeSerializer>("Looking up datatype by name: {0}", () => name); item = _dataTypeService.GetDataTypeDefinitionByName(name); } if (item == null) { // create item = new DataTypeDefinition(editorAlias) { Key = key, Name = name, DatabaseType = databaseType }; } if (item.Name != name) { item.Name = name; } if (item.Key != key) { item.Key = key; } if (item.PropertyEditorAlias != editorAlias) { item.PropertyEditorAlias = editorAlias; } if (item.DatabaseType != databaseType) { item.DatabaseType = databaseType; } _dataTypeService.Save(item); DeserializeUpdatePreValues(item, mappedNode); _dataTypeService.Save(item); return SyncAttempt<IDataTypeDefinition>.Succeed(item.Name, item, ChangeType.Import); }
protected object FormatDataType(IDataTypeDefinition dtd) { if (dtd == null) throw new HttpResponseException(HttpStatusCode.NotFound); var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias); // Force converter before passing prevalues to view var preValues = Services.DataTypeService.GetPreValuesCollectionByDataTypeId(dtd.Id); var convertedPreValues = propEditor.PreValueEditor.ConvertDbToEditor(propEditor.DefaultPreValues, preValues); return new { guid = dtd.Key, propertyEditorAlias = dtd.PropertyEditorAlias, preValues = convertedPreValues, view = propEditor.ValueEditor.View }; }
public bool GetOrCreate(out IDataTypeDefinition dtd) { // Get a reference to the data type service IDataTypeService dts = ApplicationContext.Current.Services.DataTypeService; // Attempt to get the DTD dtd = dts.GetDataTypeDefinitionById(Guid); if (dtd != null) { return false; } // Or create a new one dtd = new DataTypeDefinition(EditorAlias) { Key = Guid, Name = Name }; if (PreValues == null) { dts.Save(dtd); } else { dts.SaveDataTypeAndPreValues(dtd, PreValues); } return true; }
//public object GetByKey(string key) //{ //} /// <summary> /// The format data type. /// </summary> /// <param name="dtd"> /// The dtd. /// </param> /// <returns> /// The <see cref="object"/>. /// </returns> /// <exception cref="HttpResponseException"> /// </exception> protected object FormatDataType(IDataTypeDefinition dtd) { if (dtd == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } var dataTypeDisplay = Mapper.Map<IDataTypeDefinition, DataTypeDisplay>(dtd); var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias); var configDictionairy = new Dictionary<string, object>(); foreach (var pv in dataTypeDisplay.PreValues) { configDictionairy.Add(pv.Key, pv.Value); } return new { guid = dtd.Key, propertyEditorAlias = dtd.PropertyEditorAlias, config = configDictionairy, view = propEditor.ValueEditor.View }; }
internal override SyncAttempt<IDataTypeDefinition> DesearlizeSecondPassCore(IDataTypeDefinition item, XElement node) { return DeserializeItem(node, item); }
protected object FormatDataType(IDataTypeDefinition dtd) { if (dtd == null) throw new HttpResponseException(HttpStatusCode.NotFound); var dataTypeDisplay = Mapper.Map<IDataTypeDefinition, DataTypeDisplay>(dtd); var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias); return new { guid = dtd.Key, propertyEditorAlias = dtd.PropertyEditorAlias, preValues = dataTypeDisplay.PreValues, view = propEditor.ValueEditor.View }; }
private Dictionary<string, PreValue> GetPreValues(IDataTypeDefinition dataType) { var preValuesCollection = ApplicationContext.Current.Services.DataTypeService.GetPreValuesCollectionByDataTypeId(dataType.Id); if (preValuesCollection.IsDictionaryBased) { return preValuesCollection .PreValuesAsDictionary .OrderBy(p => p.Value.SortOrder) .ThenBy(p => p.Value.Id) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); } else { // return an array, just make it a dictionary on the way out. return preValuesCollection .PreValuesAsArray .OrderBy(p => p.SortOrder) .ThenBy(p => p.Id) .ToDictionary(preValue => "zzzuSync" + preValue.Id.ToString(), preValue => preValue); } }
private void Init(ServiceContext services, int sourceDataTypeId, int targetDataTypeId, bool updatePropertyTypes, bool publish, bool isTest) { this.Services = services; this.SourceDataTypeDefinition = services.DataTypeService.GetAllDataTypeDefinitions(sourceDataTypeId).FirstOrDefault(); this.TargetDataTypeDefinition = services.DataTypeService.GetAllDataTypeDefinitions(targetDataTypeId).FirstOrDefault(); this.IsTest = isTest; this.ShouldPublish = publish; this.ShouldUpdatePropertyTypes = updatePropertyTypes; this.AffectedContent = new List<AffectedContent>(); this.AffectedDocTypes = new List<IContentType>(); var parentDocTypes = new List<IContentType>(); parentDocTypes.AddRange(services.ContentTypeService.GetAllContentTypes().Where(x => x.PropertyTypes.Where(y => y.DataTypeDefinitionId == sourceDataTypeId).Any())); //add their children foreach (var parentDocType in parentDocTypes) { this.AffectedDocTypes.AddRange(services.ContentTypeService.GetContentTypeChildren(parentDocType.Id)); } //add in parents this.AffectedDocTypes.AddRange(parentDocTypes); foreach (var docType in this.AffectedDocTypes) { foreach (var content in services.ContentService.GetContentOfContentType(docType.Id).Where(x => !x.Trashed)) { foreach (var propertyType in content.PropertyTypes.Where(x => x.DataTypeDefinitionId == sourceDataTypeId)) { this.AffectedContent.Add(new AffectedContent() { Content = content, PropertyType = propertyType }); } } } PropertyResults = new List<PropertyResult>(); }
internal override SyncAttempt<XElement> SerializeCore(IDataTypeDefinition item) { try { var node = new XElement(Constants.Packaging.DataTypeNodeName, new XAttribute("Name", item.Name), new XAttribute("Key", item.Key), new XAttribute("Id", item.PropertyEditorAlias), new XAttribute("DatabaseType", item.DatabaseType.ToString()) ); node.Add(SerializePreValues(item, node)); return SyncAttempt<XElement>.Succeed(item.Name, node, typeof(IDataTypeDefinition), ChangeType.Export); } catch (Exception ex) { LogHelper.Warn<DataTypeSerializer>("Error Serializing {0}", () => ex.ToString()); return SyncAttempt<XElement>.Fail(item.Name, typeof(IDataTypeDefinition), ChangeType.Export, "Failed to export", ex); } }
private XElement SerializePreValues(IDataTypeDefinition item, XElement node) { var mapper = LoadMapper(node, item.PropertyEditorAlias); var mapId = 1; // we clear them out, and write them ourselves. var nodePreValues = new XElement("PreValues"); var itemPreValues = GetPreValues(item); foreach (var itemPreValuePair in itemPreValues) { var preValue = itemPreValuePair.Value; var preValueValue = preValue.Value; XElement preValueNode = new XElement("PreValue", new XAttribute("Id", preValue.Id.ToString()), new XAttribute("Value", String.IsNullOrEmpty(preValueValue) ? "" : preValueValue)); if (!itemPreValuePair.Key.StartsWith("zzzuSync")) preValueNode.Add(new XAttribute("Alias", itemPreValuePair.Key)); if (mapper != null) { if (itemPreValuePair.Key.StartsWith("zzzuSync") || mapper.ValueAlias == itemPreValuePair.Key) { // Guid newGuid = Guid.NewGuid(); if (mapper.MapToGeneric(preValueValue, mapId)) { preValueNode.Add(new XAttribute("MapGuid", mapId)); mapId++; } } } nodePreValues.Add(preValueNode); } return nodePreValues; }
private void DeserializeUpdatePreValues(IDataTypeDefinition item, XElement node) { LogHelper.Debug<DataTypeSerializer>("Deserializing DataType PreValues: {0}", () => item.Name); var preValueRootNode = node.Element("PreValues"); if (preValueRootNode != null) { var itemPreValues = _dataTypeService.GetPreValuesCollectionByDataTypeId(item.Id) .FormatAsDictionary(); List<string> preValsToRemove = new List<string>(); foreach (var preValue in itemPreValues) { var preValNode = preValueRootNode.Elements("PreValue") .Where(x => x.Attribute("Alias") != null && ((string)x.Attribute("Alias").Value == preValue.Key)) .FirstOrDefault(); if (preValNode != null) { // if the xml still has MapGuid on it, then the mapping didn't work // so we just don't set this value, its a value that the site does have // but its possible the content or whatever is set diffrently on this install // if (preValNode.Attribute("MapGuid") == null) { // set the value of preValue value to the value of the value attribute :) preValue.Value.Value = preValNode.Attribute("Value").Value; } } else { preValsToRemove.Add(preValue.Key); } } // remove things that we didn't find foreach (var key in preValsToRemove) { itemPreValues.Remove(key); } // now add any new prevalues from the xml /* var valuesWithKeys = preValueRootNode.Elements("PreValue") .Where(x => (string.IsNullOrWhiteSpace((string)x.Attribute("Alias")) == false)) .ToDictionary(key => (string)key.Attribute("Alias"), val => (string)val.Attribute("Value")); */ foreach (var nodeValue in preValueRootNode.Elements("PreValue")) { var alias = nodeValue.Attribute("Alias").ValueOrDefault(string.Empty); var value = nodeValue.Attribute("Value").ValueOrDefault(string.Empty); if (!string.IsNullOrEmpty(alias)) { if (!itemPreValues.ContainsKey(alias)) { LogHelper.Debug<DataTypeSerializer>("Adding PreValue {0} for {1}", () => alias, () => item.Name); itemPreValues.Add(alias, new PreValue(value)); } } } _dataTypeService.SavePreValues(item, itemPreValues); /* var valuesSansKeys = preValueRootNode.Elements("PreValue") .Where(x => ((string)x.Attribute("Alias")).IsNullOrWhiteSpace() == false) .Select(x => x.Attribute("Value").Value); /// this is marked as obsolete? but don't some prevalues still have no keys? if (valuesSansKeys.Any()) { _dataTypeService.SavePreValues(item.Id, valuesSansKeys); } */ } }
/// <summary> /// Deletes an <see cref="IDataTypeDefinition"/> /// </summary> /// <remarks> /// Please note that deleting a <see cref="IDataTypeDefinition"/> will remove /// all the <see cref="PropertyType"/> data that references this <see cref="IDataTypeDefinition"/>. /// </remarks> /// <param name="dataTypeDefinition"><see cref="IDataTypeDefinition"/> to delete</param> /// <param name="userId">Optional Id of the user issueing the deletion</param> public void Delete(IDataTypeDefinition dataTypeDefinition, int userId = 0) { if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs<IDataTypeDefinition>(dataTypeDefinition), this)) return; var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateContentTypeRepository(uow)) { //Find ContentTypes using this IDataTypeDefinition on a PropertyType var query = Query<PropertyType>.Builder.Where(x => x.DataTypeDefinitionId == dataTypeDefinition.Id); var contentTypes = repository.GetByQuery(query); //Loop through the list of results and remove the PropertyTypes that references the DataTypeDefinition that is being deleted foreach (var contentType in contentTypes) { if (contentType == null) continue; foreach (var group in contentType.PropertyGroups) { var types = @group.PropertyTypes.Where(x => x.DataTypeDefinitionId == dataTypeDefinition.Id).ToList(); foreach (var propertyType in types) { @group.PropertyTypes.Remove(propertyType); } } repository.AddOrUpdate(contentType); } var dataTypeRepository = _repositoryFactory.CreateDataTypeDefinitionRepository(uow); dataTypeRepository.Delete(dataTypeDefinition); uow.Commit(); Deleted.RaiseEvent(new DeleteEventArgs<IDataTypeDefinition>(dataTypeDefinition, false), this); } Audit.Add(AuditTypes.Delete, string.Format("Delete DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id); }
/// <summary> /// Saves an <see cref="IDataTypeDefinition"/> /// </summary> /// <param name="dataTypeDefinition"><see cref="IDataTypeDefinition"/> to save</param> /// <param name="userId">Id of the user issueing the save</param> public void Save(IDataTypeDefinition dataTypeDefinition, int userId = 0) { if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition), this)) return; using (new WriteLock(Locker)) { var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateDataTypeDefinitionRepository(uow)) { dataTypeDefinition.CreatorId = userId; repository.AddOrUpdate(dataTypeDefinition); uow.Commit(); Saved.RaiseEvent(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition, false), this); } } Audit.Add(AuditTypes.Save, string.Format("Save DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id); }
/// <summary> /// This will save a data type and it's pre-values in one transaction /// </summary> /// <param name="dataTypeDefinition"></param> /// <param name="values"></param> /// <param name="userId"></param> public void SaveDataTypeAndPreValues(IDataTypeDefinition dataTypeDefinition, IDictionary<string, PreValue> values, int userId = 0) { if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition), this)) return; using (new WriteLock(Locker)) { var uow = (PetaPocoUnitOfWork)_uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateDataTypeDefinitionRepository(uow)) { dataTypeDefinition.CreatorId = userId; repository.AddOrUpdate(dataTypeDefinition); //complete the transaction, but run the delegate before the db transaction is finalized uow.Commit(database => AddOrUpdatePreValues(dataTypeDefinition.Id, values, uow)); Saved.RaiseEvent(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition, false), this); } } Audit.Add(AuditTypes.Save, string.Format("Save DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id); }
internal XElement Export(IDataTypeDefinition dataTypeDefinition) { var prevalues = new XElement("PreValues"); var prevalueList = ((DataTypeService)_dataTypeService).GetDetailedPreValuesByDataTypeId(dataTypeDefinition.Id); foreach (var tuple in prevalueList) { var prevalue = new XElement("PreValue"); prevalue.Add(new XAttribute("Id", tuple.Item1)); prevalue.Add(new XAttribute("Value", tuple.Item4)); prevalue.Add(new XAttribute("Alias", tuple.Item2)); prevalue.Add(new XAttribute("SortOrder", tuple.Item3)); prevalues.Add(prevalue); } var xml = new XElement("DataType", prevalues); xml.Add(new XAttribute("Name", dataTypeDefinition.Name)); //The 'ID' when exporting is actually the property editor alias (in pre v7 it was the IDataType GUID id) xml.Add(new XAttribute("Id", dataTypeDefinition.ControlId)); xml.Add(new XAttribute("Definition", dataTypeDefinition.Key)); xml.Add(new XAttribute("DatabaseType", dataTypeDefinition.DatabaseType.ToString())); return xml; }
internal virtual PropertyEditor GetPropertyEditor(IDataTypeDefinition dtd) { if(dtd.Id != 0) return PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias); return dtd.PropertyEditorAlias.Equals(Constants.PropertyEditorAlias) ? new ArchetypePropertyEditor() : (PropertyEditor) new TextboxPropertyEditor(); }
internal XElement Export(IDataTypeDefinition dataTypeDefinition) { var prevalues = new XElement("PreValues"); var prevalueList = ((DataTypeService)_dataTypeService).GetDetailedPreValuesByDataTypeId(dataTypeDefinition.Id); foreach (var tuple in prevalueList) { var prevalue = new XElement("PreValue"); prevalue.Add(new XAttribute("Id", tuple.Item1)); prevalue.Add(new XAttribute("Value", tuple.Item4)); prevalue.Add(new XAttribute("Alias", tuple.Item2)); prevalue.Add(new XAttribute("SortOrder", tuple.Item3)); prevalues.Add(prevalue); } var xml = new XElement("DataType", prevalues); xml.Add(new XAttribute("Name", dataTypeDefinition.Name)); xml.Add(new XAttribute("Id", dataTypeDefinition.Id)); xml.Add(new XAttribute("Definition", dataTypeDefinition.Key)); xml.Add(new XAttribute("DatabaseType", dataTypeDefinition.DatabaseType.ToString())); return xml; }
public XElement Export(IDataTypeDefinition dataTypeDefinition, bool raiseEvents = true) { return realPackagingService.Export(dataTypeDefinition, raiseEvents); }