DigitalForm.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using System.Text;
  6. using Newtonsoft.Json.Linq;
  7. using TextFieldParserStandard;
  8. namespace InABox.Core
  9. {
  10. [UserTracking("Digital Forms")]
  11. public class DigitalForm : Entity, IRemotable, IPersistent, ILicense<DigitalFormsLicense>//, IDuplicatable
  12. {
  13. /// <summary>
  14. /// The following functions support PNG, BMP and JPEG
  15. /// </summary>
  16. /// <param name="data"></param>
  17. /// <returns></returns>
  18. private static readonly byte[] bmpHeader = Encoding.ASCII.GetBytes("BM");
  19. private static readonly byte[] pngHeader = { 137, 80, 78, 71 };
  20. private static readonly byte[] jpegHeader = { 255, 216, 255, 224 };
  21. private static readonly byte[] jpeg2Header = { 255, 216, 255, 225 };
  22. [UniqueCodeEditor(Visible = Visible.Default, Editable = Editable.Enabled)]
  23. [EditorSequence(1)]
  24. public string Code { get; set; }
  25. [TextBoxEditor]
  26. [EditorSequence(2)]
  27. public string Description { get; set; }
  28. [ComboLookupEditor(typeof(DigitalFormCategoryLookups))]
  29. [EditorSequence(3)]
  30. public string AppliesTo { get; set; }
  31. [CheckBoxEditor]
  32. [EditorSequence(4)]
  33. public bool Active { get; set; }
  34. [CheckBoxEditor]
  35. [EditorSequence(5)]
  36. public bool Secure { get; set; }
  37. [EditorSequence(6)]
  38. public DigitalFormGroupLink Group { get; set; }
  39. [NullEditor]
  40. public string Report { get; set; }
  41. public IEntityDuplicator GetDuplicator()
  42. {
  43. var result = new EntityDuplicator<DigitalForm>();
  44. result.AddChild<DigitalForm, DigitalFormVariable>(x => x.Form);
  45. result.AddChild<DigitalForm, DigitalFormLayout>(x => x.Form);
  46. return result;
  47. }
  48. protected override void Init()
  49. {
  50. base.Init();
  51. Active = true;
  52. Secure = false;
  53. Group = new DigitalFormGroupLink();
  54. }
  55. public override string ToString()
  56. {
  57. return string.Format("{0}: {1}", Code, Description);
  58. }
  59. private static bool IsValidImage(byte[] data)
  60. {
  61. return bmpHeader.SequenceEqual(data.Take(bmpHeader.Length))
  62. || pngHeader.SequenceEqual(data.Take(pngHeader.Length))
  63. || jpegHeader.SequenceEqual(data.Take(jpegHeader.Length))
  64. || jpeg2Header.SequenceEqual(data.Take(jpeg2Header.Length));
  65. }
  66. private static bool IsValidImage(string base64Data)
  67. {
  68. var firstBytes = base64Data.Substring(0, Math.Min(8, base64Data.Length));
  69. return IsValidImage(Convert.FromBase64String(firstBytes));
  70. }
  71. /// <summary>
  72. /// Takes a serialized FormData string and BlobData string and deserializes into one dictionary.
  73. /// The result of this is just as if you were deserializing formData as per usual.
  74. /// </summary>
  75. /// <param name="formData"></param>
  76. /// <param name="blobData"></param>
  77. /// <returns></returns>
  78. public static Dictionary<string, object?>? DeserializeFormData(string formData, string? blobData)
  79. {
  80. var values = Serialization.Deserialize<Dictionary<string, object?>>(formData);
  81. if (values is null)
  82. return null;
  83. if(blobData != null)
  84. {
  85. var blobs = Serialization.Deserialize<Dictionary<string, object?>>(blobData);
  86. if(blobs != null)
  87. {
  88. var updates = new List<Tuple<string, object?>>();
  89. foreach (var (key, value) in values)
  90. {
  91. if ((value is string str && blobs.TryGetValue(str, out var blob))
  92. || (value is Guid guid && blobs.TryGetValue(guid.ToString(), out blob)))
  93. {
  94. updates.Add(new Tuple<string, object?>(key, blob));
  95. }
  96. }
  97. foreach(var (key, value) in updates)
  98. {
  99. values[key] = value;
  100. }
  101. }
  102. }
  103. return values;
  104. }
  105. /// <summary>
  106. /// Like <see cref="DeserializeFormData(string, string?)"/>, but takes the FormData and BlobData from <paramref name="form"/>,
  107. /// rather than having to specify them manually.
  108. /// </summary>
  109. /// <param name="form"></param>
  110. /// <returns></returns>
  111. public static Dictionary<string, object?>? DeserializeFormData(IDigitalFormInstance form)
  112. => DeserializeFormData(form.FormData, form.BlobData);
  113. /// <summary>
  114. /// Takes a form instance, set of variables and some saved values, and serializes the FormData and BlobData into the respective
  115. /// fields of <paramref name="form"/>.
  116. /// </summary>
  117. /// <remarks>
  118. /// Doesn't return anything, but saves the serialized results directly into form.FormData and form.BlobData.
  119. /// It choose which fields should be saved into BlobData based on whether the form field has the <see cref="IDFBlobField"/> interface.
  120. /// <br/>
  121. /// <paramref name="values"/> should be the same as what you pass into <see cref="Serialization.Serialize(object?, bool)"/>.
  122. /// </remarks>
  123. /// <param name="form">The form instance.</param>
  124. /// <param name="variables">The variables associated with the digital form.</param>
  125. /// <param name="values">The values to save.</param>
  126. public static void SerializeFormData(IDigitalFormInstance form, ICollection<DigitalFormVariable> variables, Dictionary<string, object?> values)
  127. {
  128. var blob = new Dictionary<string, object?>();
  129. foreach (var variable in variables)
  130. {
  131. if (variable.IsBlob() && values.TryGetValue(variable.Code, out var value))
  132. {
  133. var id = Guid.NewGuid().ToString();
  134. blob[id] = value;
  135. values[variable.Code] = id;
  136. }
  137. }
  138. form.FormData = Serialization.Serialize(values);
  139. form.BlobData = Serialization.Serialize(blob);
  140. }
  141. private static string? GetVariableData(DigitalFormVariable variable, object value)
  142. {
  143. // TODO: Replace with a function on DFLayoutField or something
  144. var fieldType = variable.FieldType();
  145. if (fieldType == typeof(DFLayoutEmbeddedImage)
  146. || fieldType == typeof(DFLayoutSignaturePad))
  147. {
  148. if (value is byte[]) return IsValidImage((byte[])value) ? Convert.ToBase64String((byte[])value) : null;
  149. var str = value.ToString();
  150. return IsValidImage(str) ? str : null;
  151. }
  152. else if(fieldType == typeof(DFLayoutMultiImage))
  153. {
  154. if (value is JArray || value is IEnumerable<string>) return Serialization.Serialize(value);
  155. return null;
  156. }
  157. return variable.FormatValue(value);
  158. }
  159. /// <summary>
  160. /// Generates a database FormData from a dictionary of objects. Returns null if the data is invalid (specifically if
  161. /// any required fields are not present.
  162. /// </summary>
  163. /// <param name="values">.NET objects</param>
  164. /// <param name="variables">The variables of the form needed to be encoded</param>
  165. /// <returns>A string with JSON-encoded FormData, or null if validation requirements are not met.</returns>
  166. public static string? GenerateFormData(Dictionary<string, object> values, IEnumerable<DigitalFormVariable> variables, Entity entity)
  167. {
  168. var data = new Dictionary<string, string>();
  169. foreach (var variable in variables)
  170. if (values.TryGetValue(variable.Code, out var value))
  171. {
  172. var properties = variable.CreateProperties();
  173. if (!string.IsNullOrWhiteSpace(properties.Property))
  174. {
  175. if (variable.FieldType() == typeof(DFLayoutLookupField))
  176. {
  177. if (values.TryGetValue($"{variable.Code}$ID", out var idStr) && Guid.TryParse((string)idStr, out var id))
  178. CoreUtils.SetPropertyValue(entity, properties.Property, id);
  179. }
  180. else
  181. {
  182. CoreUtils.SetPropertyValue(entity, properties.Property, value);
  183. }
  184. }
  185. if (value != null)
  186. {
  187. var varData = GetVariableData(variable, value);
  188. if (varData != null)
  189. data[variable.Code] = varData;
  190. }
  191. }
  192. else if (variable.Required)
  193. {
  194. return null;
  195. }
  196. return Serialization.Serialize(data);
  197. }
  198. /// <summary>
  199. /// Creates a dictionary of objects from a database FormData
  200. /// </summary>
  201. /// <param name="formData">A string with JSON-encoded FormData</param>
  202. /// <param name="variables">The variables of the form needed to be encoded</param>
  203. /// <returns></returns>
  204. public static Dictionary<string, object> ParseFormData(string formData, IEnumerable<DigitalFormVariable> variables, Entity entity)
  205. {
  206. var data = new Dictionary<string, object>();
  207. // Could be null
  208. var formObject = Serialization.Deserialize<Dictionary<string, object>>(formData);
  209. foreach (var variable in variables)
  210. {
  211. object? value = null;
  212. var code = variable.Code;
  213. var properties = variable.CreateProperties();
  214. if (!string.IsNullOrWhiteSpace(properties.Property))
  215. {
  216. value = CoreUtils.GetPropertyValue(entity, properties.Property);
  217. if (variable.FieldType() == typeof(DFLayoutLookupField))
  218. {
  219. code = variable.Code + "$ID";
  220. }
  221. }
  222. else if (value == null)
  223. formObject?.TryGetValue(variable.Code, out value);
  224. if (value != null)
  225. {
  226. data[code] = variable.ParseValue(value);
  227. }
  228. }
  229. return data;
  230. }
  231. }
  232. }