Last active
July 14, 2019 19:11
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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