using System; using System.Web.Script.Serialization; using umbraco.BusinessLogic; using umbraco.cms.businesslogic.datatype; namespace umbraco.editorControls { /// /// Abstract class for the PreValue Editor. /// Specifically designed to serialize/deserialize the options as JSON. /// public abstract class AbstractJsonPrevalueEditor : AbstractPrevalueEditor { /// /// The underlying base data-type. /// protected readonly umbraco.cms.businesslogic.datatype.BaseDataType m_DataType; /// /// An object to temporarily lock writing to the database. /// private static readonly object m_Locker = new object(); /// /// Initializes a new instance of the class. /// /// Type of the data. public AbstractJsonPrevalueEditor(umbraco.cms.businesslogic.datatype.BaseDataType dataType) { this.m_DataType = dataType; } /// /// Initializes a new instance of the class. /// /// Type of the data. /// Type of the database field. public AbstractJsonPrevalueEditor(umbraco.cms.businesslogic.datatype.BaseDataType dataType, umbraco.cms.businesslogic.datatype.DBTypes dbType) : base() { this.m_DataType = dataType; this.m_DataType.DBType = dbType; } /// /// Gets the PreValue options for the data-type. /// /// The type of the resulting object. /// /// Returns the options for the PreValue Editor /// public T GetPreValueOptions() { var prevalues = PreValues.GetPreValues(this.m_DataType.DataTypeDefinitionId); if (prevalues.Count > 0) { var prevalue = (PreValue)prevalues[0]; if (!string.IsNullOrEmpty(prevalue.Value)) { try { // deserialize the options var serializer = new JavaScriptSerializer(); // return the options return serializer.Deserialize(prevalue.Value); } catch (Exception ex) { Log.Add(LogTypes.Error, this.m_DataType.DataTypeDefinitionId, string.Concat("umbraco.editorControls: Execption thrown: ", ex)); } } } // if all else fails, return default options return default(T); } /// /// Saves the data-type PreValue options. /// public void SaveAsJson(object options) { // serialize the options into JSON var serializer = new JavaScriptSerializer(); var json = serializer.Serialize(options); lock (m_Locker) { var prevalues = PreValues.GetPreValues(this.m_DataType.DataTypeDefinitionId); if (prevalues.Count > 0) { var prevalue = (PreValue)prevalues[0]; // update prevalue.Value = json; prevalue.Save(); } else { // insert PreValue.MakeNew(this.m_DataType.DataTypeDefinitionId, json); } } } } }