Line data Source code
1 : #region Copyright
2 : // // -----------------------------------------------------------------------
3 : // // <copyright company="Chinchilla Software Limited">
4 : // // Copyright Chinchilla Software Limited. All rights reserved.
5 : // // </copyright>
6 : // // -----------------------------------------------------------------------
7 : #endregion
8 :
9 : using System;
10 : using System.IO;
11 : using System.Runtime.Serialization;
12 : using Cqrs.Events;
13 : using Microsoft.WindowsAzure.Storage.Table;
14 : using Newtonsoft.Json;
15 :
16 : namespace Cqrs.Azure.BlobStorage
17 : {
18 : /// <summary>
19 : /// A projection/entity especially designed to work with Azure Table storage.
20 : /// </summary>
21 : [Serializable]
22 : [DataContract]
23 : public abstract class TableEntity<TData>
24 : : TableEntity
25 1 : {
26 : /// <summary>
27 : /// The default <see cref="JsonSerializerSettings"/> to use.
28 : /// </summary>
29 : public static JsonSerializerSettings DefaultSettings { get; private set; }
30 :
31 : static TableEntity()
32 : {
33 : DefaultSettings = DefaultJsonSerializerSettings.DefaultSettings;
34 : }
35 :
36 : /// <summary>
37 : /// Deserialise the provided <paramref name="json"/> from its <see cref="string"/> representation.
38 : /// </summary>
39 : /// <param name="json">A <see cref="string"/> representation of an <typeparamref name="TData"/> to deserialise.</param>
40 1 : protected virtual TData Deserialise(string json)
41 : {
42 : using (var stringReader = new StringReader(json))
43 : using (var jsonTextReader = new JsonTextReader(stringReader))
44 : return GetSerialiser().Deserialize<TData>(jsonTextReader);
45 : }
46 :
47 : /// <summary>
48 : /// Serialise the provided <paramref name="data"/>.
49 : /// </summary>
50 : /// <param name="data">The <typeparamref name="TData"/> being serialised.</param>
51 : /// <returns>A <see cref="string"/> representation of the provided <paramref name="data"/>.</returns>
52 1 : protected virtual string Serialise(TData data)
53 : {
54 : string dataContent = JsonConvert.SerializeObject(data, GetSerialisationSettings());
55 :
56 : return dataContent;
57 : }
58 :
59 : /// <summary>
60 : /// Returns <see cref="DefaultSettings"/>
61 : /// </summary>
62 : /// <returns><see cref="DefaultSettings"/></returns>
63 1 : protected virtual JsonSerializerSettings GetSerialisationSettings()
64 : {
65 : return DefaultSettings;
66 : }
67 :
68 : /// <summary>
69 : /// Creates a new <see cref="JsonSerializer"/> using the settings from <see cref="GetSerialisationSettings"/>.
70 : /// </summary>
71 : /// <returns>A new instance of <see cref="JsonSerializer"/>.</returns>
72 1 : protected virtual JsonSerializer GetSerialiser()
73 : {
74 : JsonSerializerSettings settings = GetSerialisationSettings();
75 : return JsonSerializer.Create(settings);
76 : }
77 : }
78 : }
|