Skip to content

Instantly share code, notes, and snippets.

@joshhebb
Last active July 14, 2019 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshhebb/f397736e90dace6596e50cf33760e9cd to your computer and use it in GitHub Desktop.
Save joshhebb/f397736e90dace6596e50cf33760e9cd to your computer and use it in GitHub Desktop.
A couple of helper functions to store and retrieve objects stored in Tridions application data. Useful for "caching" costly reports generated by the CoreService, but also just storing and retrieving C# objects in application data.
/// <summary>
/// Save an object in appData (stored in the CM DB) by serializing the object into a string,
/// then converting it to an array of bytes and storing it via the CoreService client.
/// </summary>
/// <param name="applicationId">The ID which the appData can be retrieved.</param>
/// <param name="data">The object to be stored in appData by applicationId.</param>
public void SaveAppData<T> (string applicationId, T data)
{
using (var client = new SessionAwareCoreServiceClient(""))
{
try
{
string serializedData = JsonConvert.SerializeObject(data);
ApplicationData appData = new ApplicationData()
{
ApplicationId = applicationId,
Data = Encoding.Unicode.GetBytes(serializedData),
TypeId = "System.String"
};
client.SaveApplicationData(Settings.EMPTY_TCM_ID, new ApplicationData[] { appData });
}
catch (Exception ex)
{
throw ex;
}
}
}
/// <summary>
/// Read an object from appData and serialize it. The object is retrieved by applicationId.
/// </summary>
/// <param name="applicationId">The ID to retrieve the object by.</param>
/// <returns>Deserialized object retrieved from appData.</returns>
public T ReadAppData<T>(string applicationId)
{
T deserializedObject = default(T);
using (var client = new SessionAwareCoreServiceClient(""))
{
try
{
var appData = client.ReadApplicationData(Settings.EMPTY_TCM_ID, applicationId);
if(appData != null)
{
var content = Encoding.Unicode.GetString(appData.Data);
deserializedObject = JsonConvert.DeserializeObject<T>(content);
}
}
catch (Exception ex)
{
throw ex;
}
}
return deserializedObject;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment