DigitalForm.cs 13 KB

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