CoreUtils.cs 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Diagnostics;
  7. using System.Diagnostics.CodeAnalysis;
  8. using System.Globalization;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Linq.Expressions;
  12. using System.Net.Mail;
  13. using System.Reflection;
  14. using System.Text;
  15. using System.Text.RegularExpressions;
  16. using System.Diagnostics.CodeAnalysis;
  17. using Newtonsoft.Json;
  18. using Newtonsoft.Json.Linq;
  19. //using Serialize.Linq.Serializers;
  20. namespace InABox.Core
  21. {
  22. public enum DatabaseProvider
  23. {
  24. //LiteDb,
  25. //MongoDb,
  26. SQLite
  27. }
  28. //public class DateTimeJsonConverter : JsonConverter<DateTime>
  29. //{
  30. // public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)
  31. // {
  32. // String result = String.Format("{0:o}", value);
  33. // writer.WriteValue(result);
  34. // }
  35. // public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)
  36. // {
  37. // if (reader.Value is DateTime)
  38. // return (DateTime)reader.Value;
  39. // else
  40. // {
  41. // String value = reader.Value.ToString().Replace("\"","");
  42. // DateTime.TryParse(value, out DateTime result);
  43. // return result;
  44. // }
  45. // }
  46. // public override bool CanRead => true;
  47. // public override bool CanWrite => true;
  48. //}
  49. //public class TimeSpanJsonConverter : JsonConverter<TimeSpan>
  50. //{
  51. // public override void WriteJson(JsonWriter writer, TimeSpan value, JsonSerializer serializer)
  52. // {
  53. // TimeSpan timespan = (TimeSpan)value;
  54. // writer.WriteValue(timespan.Ticks.ToString());
  55. // }
  56. // public override TimeSpan ReadJson(JsonReader reader, Type objectType, TimeSpan existingValue, bool hasExistingValue, JsonSerializer serializer)
  57. // {
  58. // Int64 ticks = Int64.Parse(reader.Value.ToString().Replace("\"", ""));
  59. // return new TimeSpan(ticks);
  60. // }
  61. //}
  62. public enum SyncfusionVersion
  63. {
  64. v16_3,
  65. v16_4,
  66. v17_1,
  67. v17_2,
  68. v17_4,
  69. v18_1,
  70. v18_4,
  71. v19_1,
  72. v19_3,
  73. v19_4,
  74. v20_1,
  75. v20_2,
  76. v20_3,
  77. v22_1,
  78. Unspecified
  79. }
  80. [LibraryInitializer]
  81. public static class CoreUtils
  82. {
  83. private static readonly List<Type> entities = new List<Type>();
  84. public static Dictionary<string, long> TypeListSummary = new Dictionary<string, long>();
  85. private static readonly ConcurrentDictionary<Type, IColumns> _columnscache = new ConcurrentDictionary<Type, IColumns>();
  86. private static readonly Regex StripHtmlStyles = new Regex(@"<style(.|\n)*?</style>", RegexOptions.Compiled);
  87. private static readonly Regex StripHtmlTags = new Regex(@"<(.|\n)*?>", RegexOptions.Compiled);
  88. private static readonly Regex StripSpecialCharacters = new Regex(@"&#(.|\n)*?;|&nbsp;|&gt;|&lt;&quot;", RegexOptions.Compiled);
  89. private static readonly Regex StripLineBreaks = new Regex(@"( |\r?\n|\r|\n)\1+", RegexOptions.Compiled);
  90. public static IEnumerable<Type> Entities => entities;
  91. public static long GenerateSequence()
  92. {
  93. return (DateTime.Now - new DateTime(2019, 1, 1)).Ticks;
  94. }
  95. public static string SyncfusionLicense(SyncfusionVersion version = SyncfusionVersion.Unspecified)
  96. {
  97. var licenses = new Dictionary<SyncfusionVersion, string>
  98. {
  99. {
  100. SyncfusionVersion.v16_3,
  101. "MTE0MTMyQDMxMzYyZTMzMmUzMFYwZ1YvdG4vNWVlb2JmMGdLSWJVd2l3cmpWVU9nYXVLYmdZbXkzUkpWK3M9;MTE0MTMzQDMxMzYyZTMzMmUzMGFraS9ZQkgxdXlQdDJNdWVIaHFXS0I0S29HY1JrVERYT1hEUVpmczlCYW89;MTE0MTM0QDMxMzYyZTMzMmUzMGozZGw2bERQVHFVaUkrOWZ0Z0swNVQzWkM5OEdCN042VTNnUzdZWENMMk09;MTE0MTM1QDMxMzYyZTMzMmUzMERTYTIzVmlSKzllZnQ2T3ZTVXVLbEJmRnh2UUQ2d0pFb2JLRWVlcHdwMWc9;MTE0MTM2QDMxMzYyZTMzMmUzMFowVmxDMmlXUVVPVVowR2sxaWJxVVJ6M1NORW81clF2KzJhbXN3K2ZkZWs9;MTE0MTM3QDMxMzYyZTMzMmUzMEQxMnRUMjJOLzU3dTdwaGZzRmUvS0ZVRWVkc3dZMSszYWQ1ZkpueDZNS2c9;MTE0MTM4QDMxMzYyZTMzMmUzMENZcDRIS0N6U2psbmFiM1BIdGJzZUU4Y1lWWm5oNm52T1FsVmVDK3g5RG89;MTE0MTM5QDMxMzYyZTMzMmUzMEdjbHhYbExwU1VYblJGM3F4TC94R2cvd3J4MGJMc21qelpNbHg2cUZjckk9;MTE0MTQwQDMxMzYyZTMzMmUzMGNPZDFCcklTSkJVakFtVlhDdlgwdDgzeWNwZnliZmVqQUExUWNhRjhzVHc9;MTE0MTQxQDMxMzYyZTMzMmUzMFowVmxDMmlXUVVPVVowR2sxaWJxVVJ6M1NORW81clF2KzJhbXN3K2ZkZWs9"
  102. },
  103. {
  104. SyncfusionVersion.v16_4,
  105. "MTE0MTQyQDMxMzYyZTM0MmUzMGJ4UzVnMEJkOFpUM2pqanhPbnUrclk3c3lzQjVMdnV0eExnb3ljdGhqUjQ9;MTE0MTQzQDMxMzYyZTM0MmUzME5pY1I4ZWI1TnIwVFZVQXlBYWlEb0lsVTcxc1RUWEVOMWxESUIzVEJ6QXM9;MTE0MTQ0QDMxMzYyZTM0MmUzMG8wWjY0bml1QWVDeXI0TkI3STZWZEs2TkJjOFNaQWxTUCttL2tSNVUzbjA9;MTE0MTQ1QDMxMzYyZTM0MmUzMFNvanpRenpST2FtWHNJbzFwcnZ0djhuRjd3NnlGcVA4N3ljWFpCcExDVjg9;MTE0MTQ2QDMxMzYyZTM0MmUzMFJXMkVxT29WN0tMWEhDbTl5Uko5ak12RjV0dU1SODlZcGY1TkFudmVnR009;MTE0MTQ3QDMxMzYyZTM0MmUzMGU1U0dpZm5UTVBCclQvVmxBQkhNUlhoWUw0cmw5WFpRK0hKNUFpVitlSVU9;MTE0MTQ4QDMxMzYyZTM0MmUzMFRZa1NvdzV4NUNYTDJHaVdnL1k0SEh6ZjhocTYwZUkrVmt4eVdKOEJNR289;MTE0MTQ5QDMxMzYyZTM0MmUzMEMyM21MSEZUdmo4Qk1WNGZWekVBSkE4V2Zva2ZrNnh0WmwvN20rTWxhZzg9;MTE0MTUwQDMxMzYyZTM0MmUzMGt2N0wvMml1MHp3MVNVblJSeDZTaXUwdGxvWmlxcXZ2blFJNzNJSDhRV1k9;MTE0MTUxQDMxMzYyZTM0MmUzMFJXMkVxT29WN0tMWEhDbTl5Uko5ak12RjV0dU1SODlZcGY1TkFudmVnR009"
  106. },
  107. {
  108. SyncfusionVersion.v17_1,
  109. "MTE0MTUyQDMxMzcyZTMxMmUzMGJxNHN0ZU9tVmNWK0RCUlRDeXpMU0hnenBid2xiTTZKemVpTmRlTFJOT3c9;MTE0MTUzQDMxMzcyZTMxMmUzMG1Qak9CaW9yd1dVUUxvNDJoY3dFOE5lSGd6dGtNQlJ1am55d2twQkR4ZXM9;MTE0MTU0QDMxMzcyZTMxMmUzMFJXTDlNVnVQc25uL25QMFR2WVFMS054RUpVckFtUWljVjM2MkZCRkNLTDQ9;MTE0MTU1QDMxMzcyZTMxMmUzMEJ4YUJRc2dVSWJVaVlzWjN1a3FMdEZnQnpmTWd0cUlSS0dqK0RkRU9FSUk9;MTE0MTU2QDMxMzcyZTMxMmUzMEo2UGVucVZ3eVpkWmFJQnVqdnlLU0dERXlpdzBwb3IwcTNBMXBVbzNveVU9;MTE0MTU3QDMxMzcyZTMxMmUzME9BUXVITzhwK2tlay9qTmc5cXFzVEJ1ZUJvOUU0dmNDUXNYZ2FEQ1R3YzA9;MTE0MTU4QDMxMzcyZTMxMmUzMEpEUzFLNi91U2FocXNwRGdnL2xrZzdvYTd6OXBKRmI4S0RXckRoZENFZDA9;MTE0MTU5QDMxMzcyZTMxMmUzMGVxSk9wNDVOUGluZDhFYXpMWVZKTklCK0M5R29JMG5RTmw1T002T3YrUzA9;MTE0MTYwQDMxMzcyZTMxMmUzMEtQZnBMczBYWDJKSll5LzdqN21QcVRHd2hYeEgzMXkrM3JSdmNTVXpHYXM9;MTE0MTYxQDMxMzcyZTMxMmUzMEo2UGVucVZ3eVpkWmFJQnVqdnlLU0dERXlpdzBwb3IwcTNBMXBVbzNveVU9"
  110. },
  111. {
  112. SyncfusionVersion.v17_2,
  113. "MTIwNTA0QDMxMzcyZTMyMmUzMGxuSUVyYmtQYWdYSFlsdmYyV29FYXRKNXJiOVlkSjhYQ0djS2NQazd5czA9;MTIwNTA1QDMxMzcyZTMyMmUzMGJEb3VvekNxaUFXa3N5b2l4eXpxZ3NqRkMvbnpjQjFUMHpWbmlMaktBSlU9"
  114. },
  115. {
  116. SyncfusionVersion.v17_4,
  117. "MTgzNDc1QDMxMzcyZTM0MmUzMFhkYlgrZXhMYjVLMFY3MStXZTExTkRJMVhjRGg3S3B2TXRzTloxVHpHc289;MTgzNDc2QDMxMzcyZTM0MmUzME9wZ01lakhTT04zOGJybFp5KzVBYjdFamFqV2Jpd01Wckdnd1dTd3JUeDQ9"
  118. },
  119. {
  120. SyncfusionVersion.v18_1,
  121. "MzU3NDMwQDMxMzgyZTMxMmUzME1VV29JM0Z2aVpZenBSaThtbmphSTBGZ0djNnoyUGNsZk5zU0dGVTR4TFE9;MzU3NDMxQDMxMzgyZTMxMmUzMGhsUUZJaXRmRjNkb1hCeWZiMG03QWo0S1UxRnEwRFhTbHUvN3FUWnZvRVU9"
  122. },
  123. {
  124. SyncfusionVersion.v18_4,
  125. "NDI2MzEzQDMxMzgyZTM0MmUzMGxsVE9iRkMrckpDdjNZcUZYVGZCaHloNTFRQnd6c1FKSDc5ZWRYcWgrR0U9;NDI2MzE0QDMxMzgyZTM0MmUzME1JZzhPTC84b01kVGlzdDlmNUljMmZtblJBTVdHTHF6V00wZGpVNm5sWkE9"
  126. },
  127. {
  128. SyncfusionVersion.v19_1,
  129. "NDI2MzA4QDMxMzkyZTMxMmUzMG9DaFBkRXRPKzZISTBLejVpYlBCM3hJVUxjNEgwMnBqdlZmTmRmOXVjdGM9;NDI2MzA5QDMxMzkyZTMxMmUzMGRoNDJVNDNKUldmbytZQ3dzTWJPY0VuZEMwT1phM09vMStEajhYMzZ2WGc9"
  130. },
  131. {
  132. SyncfusionVersion.v19_3,
  133. "NTI0MzQxQDMxMzkyZTMzMmUzME44d0c4ME9lYmZGNW5nK3B0Vm1GQTNZeUFLeDhNSWh0SWZ0bzUxWHNEU3M9;NTI0MzQyQDMxMzkyZTMzMmUzMGpGdkdnQmtxbHdic0QvaktPa2pZcG0zMU5tV2NxZ3lhdks4N01HREJtYU09;NTI0MzQzQDMxMzkyZTMzMmUzME10dy9uUGp1OTJhc095S3RiQXhsclN5MUhUcVJNd1N2TEFCWThSWkp5Q289"
  134. },
  135. {
  136. SyncfusionVersion.v19_4,
  137. "NTUwNDcyQDMxMzkyZTM0MmUzMG9QaUZGdHNGWVpXRU90clpIZ2JJVkVXU2Q2VHFRdEZMY1Z3U3RySUF3a1k9;NTUwNDczQDMxMzkyZTM0MmUzMGtzdlcwYmlwZUVzNTZsNUJQMFN3K1hMYXdmZVlVNms1N2RtcWFvWHdBczg9"
  138. },
  139. {
  140. SyncfusionVersion.v20_1,
  141. "NjYxMzYzQDMyMzAyZTMxMmUzMGpLV2tKMkl1bjRXOVNRMkRjYkxlNFNXQ3g5OGI2V2RoWkNpSk9HY3dyakE9; NjYxMzY0QDMyMzAyZTMxMmUzMGFaK2JxYzhTVnpTdXNEckVEM2x5ckVXdTJkVThpV3ZZRVE0emI1ekl2eWM9"
  142. },
  143. {
  144. SyncfusionVersion.v20_2,
  145. "Mgo+DSMBaFt/QHJqVVhjWlpFdEBBXHxAd1p/VWJYdVt5flBPcDwsT3RfQF9jTn9QdkZiXX9YcHxXQw==;Mgo+DSMBPh8sVXJ0S0R+XE9HcFRDX3xKf0x/TGpQb19xflBPallYVBYiSV9jS3xTcURgWXxfdHRTRmlYVA==;ORg4AjUWIQA/Gnt2VVhiQlFadVlJXGFWfVJpTGpQdk5xdV9DaVZUTWY/P1ZhSXxRdkJiWn9dcXBVQGFcVEE=;Njc1MTQ1QDMyMzAyZTMyMmUzMGdvdWNsV3podC9LTC9MamF2YXNpT3pjR3Rsa3NGQzBxdWNtSGUvV0dsOGc9;Njc1MTQ2QDMyMzAyZTMyMmUzMFdhQkYvdkFwa3NTWXo4MnkxVWY4VnlyMHJlbmVud3N6TWQ3dkN6b3RmVm89;NRAiBiAaIQQuGjN/V0Z+Xk9EaFxEVmJLYVB3WmpQdldgdVRMZVVbQX9PIiBoS35RdEVkWHxec3VRRmZdVkRz;Njc1MTQ4QDMyMzAyZTMyMmUzMFcyaWFYL0dGZXFwanNIMHFEcnZ1d2pSMWhQR21PWEVwdjJjMjRuUVQxYjA9;Njc1MTQ5QDMyMzAyZTMyMmUzMGJjWHhqbkRRYXJkd3RFV2FXbFlGREZVd2FuaFNXM21qa1dha1lNWC8rWDA9;Mgo+DSMBMAY9C3t2VVhiQlFadVlJXGFWfVJpTGpQdk5xdV9DaVZUTWY/P1ZhSXxRdkJiWn9dcXBVQGJfWEE=;Njc1MTUxQDMyMzAyZTMyMmUzMGNBTUpQbGxtS3E3NDV1M1pEUFVjMjR6eEg5S3ZiRGhUalVHNk5oenNybWs9;Njc1MTUyQDMyMzAyZTMyMmUzMGk1U1lKR3lKUTMwWEdJb2JVbG5WYWVkMUwwbFpPMG9SbSszZmt2MGRoZUU9;Njc1MTUzQDMyMzAyZTMyMmUzMFcyaWFYL0dGZXFwanNIMHFEcnZ1d2pSMWhQR21PWEVwdjJjMjRuUVQxYjA9"
  146. },
  147. {
  148. SyncfusionVersion.v20_3,
  149. "NzY3MzEzQDMyMzAyZTMzMmUzMGR2bk5Bb1lOK2pJV2lLdys4YlVDMGViYUhCY21PM2xITTRWZlhYYmRlVm89;NzY3MzE0QDMyMzAyZTMzMmUzMG9vSEdIY1d1NDFPYjBGSnJMcTlQSmpMUzYwNk9HZUNXWHNJZWlXZloyT0U9"
  150. },
  151. {
  152. SyncfusionVersion.v22_1,
  153. "MjU0OTIyM0AzMjMyMmUzMDJlMzBhMTc2SkUzUFkyUzcyUFVhNzFLWDRCOElLTkVjQ2JQOG9zZ09CUTBuZjN3PQ==;MjU0OTIyNEAzMjMyMmUzMDJlMzBtaG5naUZPVVRwdENBWGRNSDdYK3orQ3NCcjVkYjRVUzQ4ZHoyRkloeStVPQ==;MjU0OTIyNUAzMjMyMmUzMDJlMzBtaG5naUZPVVRwdENBWGRNSDdYK3orQ3NCcjVkYjRVUzQ4ZHoyRkloeStVPQ=="
  154. },
  155. {
  156. SyncfusionVersion.Unspecified,
  157. "NjcyNDdAMzEzNjJlMzQyZTMwbWZlcXhUQW80NjUrTENRTVM0c2J5empYZDFUcHhDcEE0T3gwZDZZVGVtQT0=;NjcyNDhAMzEzNjJlMzQyZTMwZWtuc0VlSXVteWNtUE8zQ1V1azcrZmRjTFBqUGFHenU1YzNwbUVTdlcxVT0="
  158. }
  159. };
  160. return licenses[version];
  161. }
  162. public static void RegisterClasses()
  163. {
  164. RegisterClasses(typeof(CoreUtils).GetTypeInfo().Assembly);
  165. ImportFactory.Register(typeof(CSVImporter<>), "Comma Separated", "Comma Separated Files (*.csv)|*.csv");
  166. ImportFactory.Register(typeof(TabImporter<>), "Tab Delimited", "Tab-Delimited Files (*.txt)|*.txt");
  167. ImportFactory.Register(typeof(FixedWidthImporter<>), "Fixed Width", "Text Files (*.txt)|*.txt");
  168. }
  169. public static void CheckLicensing()
  170. {
  171. var entities = TypeList(
  172. AppDomain.CurrentDomain.GetAssemblies(),
  173. myType =>
  174. myType.IsClass
  175. && !myType.IsAbstract
  176. && !myType.IsGenericType
  177. && myType.IsSubclassOf(typeof(Entity))
  178. ).ToArray();
  179. foreach (var entity in entities)
  180. {
  181. var lic = entity.GetInterfaces()
  182. .FirstOrDefault(x => x.IsConstructedGenericType && x.GetGenericTypeDefinition() == typeof(ILicense<>));
  183. if (lic == null)
  184. Logger.Send(LogType.Error, "", "License Configuration Error: " + entity.EntityName().Split('.').Last());
  185. }
  186. }
  187. public static void RegisterClasses(params Assembly[] assemblies)
  188. {
  189. foreach (var assembly in assemblies)
  190. {
  191. var types = TypeList(
  192. new[] { assembly },
  193. myType =>
  194. //myType.GetTypeInfo().IsClass &&
  195. !myType.GetTypeInfo().IsAbstract
  196. //&& !myType.GetTypeInfo().IsGenericType
  197. //&& myType.GetTypeInfo().IsSubclassOf(typeof(Entity))
  198. && !entities.Contains(myType)
  199. );
  200. entities.AddRange(types);
  201. //foreach (var type in types.Where(x=>x.IsSubclassOf(typeof(BaseObject))))
  202. //{
  203. // // Register Serializers for Entities
  204. // var sertype = typeof(MsgPackBaseObjectSerializer<>).MakeGenericType(type);
  205. // var method = typeof(MsgPackSerializer).GetMethod("Register", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(type, sertype);
  206. // method.Invoke(null, new object[] { });
  207. // if (type.IsSubclassOf(typeof(Entity)))
  208. // {
  209. // Type flttype = typeof(Filter<>).MakeGenericType(type);
  210. // var fsertype = typeof(MsgPackFilterSerializer<>).MakeGenericType(type);
  211. // var fmethod = typeof(MsgPackSerializer).GetMethod("Register", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(flttype, fsertype);
  212. // fmethod.Invoke(null, new object[] { });
  213. // Type coltype = typeof(Columns<>).MakeGenericType(type);
  214. // var csertype = typeof(MsgPackColumnsSerializer<>).MakeGenericType(type);
  215. // var cmethod = typeof(MsgPackSerializer).GetMethod("Register", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(coltype, csertype);
  216. // cmethod.Invoke(null, new object[] { });
  217. // Type srttype = typeof(SortOrder<>).MakeGenericType(type);
  218. // sertype = typeof(MsgPackSortOrderSerializer<>).MakeGenericType(type);
  219. // method = typeof(MsgPackSerializer).GetMethod("Register", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(srttype, sertype);
  220. // method.Invoke(null, new object[] { });
  221. // }
  222. //}
  223. }
  224. }
  225. public static Guid FullGuid = Guid.Parse("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF");
  226. public static string EntityName(this Type t)
  227. {
  228. if (t.GetTypeInfo().IsGenericType)
  229. {
  230. var basename = t.FullName.Split(new[] { "[[" }, StringSplitOptions.RemoveEmptyEntries)[0];
  231. var types = new List<string>();
  232. foreach (var type in t.GenericTypeArguments)
  233. types.Add(type.EntityName());
  234. var result = string.Format("{0}<{1}>", basename, string.Join(",", types));
  235. return result;
  236. }
  237. if (string.IsNullOrEmpty(t.FullName))
  238. return t.Name;
  239. return t.FullName.Split(',')[0];
  240. }
  241. private static Type? FindType(string name)
  242. {
  243. var result = entities.FirstOrDefault(x => x.EntityName().Equals(name));
  244. if (result is null)
  245. result = Type.GetType(name);
  246. return result;
  247. }
  248. public static bool HasInterface(this Type type, Type interfaceType)
  249. {
  250. return type.GetInterfaces(interfaceType).Any();
  251. }
  252. public static bool HasInterface<T>(this Type type) => type.HasInterface(typeof(T));
  253. public static Type? GetInterfaceDefinition(this Type type, Type interfaceType)
  254. {
  255. return type.GetInterfaces(interfaceType).FirstOrDefault();
  256. }
  257. public static IEnumerable<Type> GetInterfaces(this Type type, Type interfaceType)
  258. {
  259. return type
  260. .GetInterfaces()
  261. .Where(x => x.IsGenericType ? x.GetGenericTypeDefinition() == interfaceType : x == interfaceType);
  262. }
  263. public static IEnumerable<Type> GetInterfaceDefinitions(this Type type, Type interfaceType)
  264. {
  265. foreach(var inter in type.GetInterfaces())
  266. {
  267. if (inter == interfaceType)
  268. {
  269. yield return inter;
  270. }
  271. else if (inter.IsGenericType)
  272. {
  273. var genericTypeDefinition = inter.GetGenericTypeDefinition();
  274. if (genericTypeDefinition == interfaceType)
  275. yield return genericTypeDefinition;
  276. }
  277. }
  278. }
  279. public static bool IsSubclassOfRawGeneric(this Type toCheck, Type generic)
  280. {
  281. while (toCheck != typeof(object))
  282. {
  283. var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
  284. if (generic == cur) return true;
  285. toCheck = toCheck.BaseType;
  286. }
  287. return false;
  288. }
  289. public static Type? GetSuperclassDefinition(this Type toCheck, Type generic)
  290. {
  291. while (toCheck != typeof(object))
  292. {
  293. var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
  294. if (generic == cur) return toCheck;
  295. toCheck = toCheck.BaseType;
  296. }
  297. return null;
  298. }
  299. public static bool TryGetEntity(string entityname, [NotNullWhen(true)] out Type? type)
  300. {
  301. if (string.IsNullOrWhiteSpace(entityname))
  302. {
  303. type = null;
  304. return false;
  305. }
  306. if (entityname.Contains("<"))
  307. {
  308. var comps = entityname.Replace(">", "").Split('<');
  309. var basetype = FindType(comps[0]);
  310. var types = new List<Type>();
  311. var generics = comps[1].Split(',');
  312. foreach (var generic in generics)
  313. {
  314. var genericArg = FindType(generic);
  315. if (genericArg is null)
  316. {
  317. type = null;
  318. return false;
  319. }
  320. types.Add(genericArg);
  321. }
  322. type = basetype?.MakeGenericType(types.ToArray());
  323. }
  324. else
  325. {
  326. type = FindType(entityname);
  327. }
  328. return type != null;
  329. }
  330. public static Type GetEntity(string entityname)
  331. {
  332. if (TryGetEntity(entityname, out var type))
  333. return type;
  334. throw new Exception($"Entity {entityname} does not exist!");
  335. }
  336. public static Type? GetEntityOrNull(string entityname)
  337. {
  338. TryGetEntity(entityname, out var type);
  339. return type;
  340. }
  341. //private static List<Type> TypeCache = null;
  342. /// <summary>
  343. /// Returns a list of types that have been loaded by the various calls to RegisterClasses, e.g.
  344. /// CoreUtils.RegisterClasses
  345. /// </summary>
  346. /// <param name="Predicate"></param>
  347. /// <returns></returns>
  348. public static IEnumerable<Type> TypeList(Func<Type, bool> Predicate)
  349. {
  350. var result = new List<Type>();
  351. try
  352. {
  353. try
  354. {
  355. foreach (var type in entities.Where(x => x != null).Cast<TypeInfo>())
  356. try
  357. {
  358. if (Predicate(type.AsType()) && !result.Contains(type.AsType()))
  359. result.Add(type.AsType());
  360. }
  361. catch (Exception e)
  362. {
  363. //Console.WriteLine(type.Name + " : " + tl.Message);
  364. Logger.Send(LogType.Error, "", $"Error in CoreUtils.TypeList: {CoreUtils.FormatException(e)}");
  365. }
  366. }
  367. catch (Exception e)
  368. {
  369. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  370. }
  371. }
  372. catch (Exception e)
  373. {
  374. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  375. }
  376. return result;
  377. }
  378. /// <summary>
  379. /// Returns a list of types present within the assemblies.
  380. /// </summary>
  381. /// <param name="assemblies"></param>
  382. /// <param name="Predicate"></param>
  383. /// <returns></returns>
  384. public static IList<Type> TypeList(IEnumerable<Assembly> assemblies, Func<Type, bool> Predicate)
  385. {
  386. var result = new List<Type>();
  387. try
  388. {
  389. try
  390. {
  391. foreach (var assembly in assemblies) //.Where(x=>!x.IsDynamic))
  392. try
  393. {
  394. Type[] types;
  395. try
  396. {
  397. types = assembly.GetTypes();
  398. }
  399. catch (ReflectionTypeLoadException e0)
  400. {
  401. types = e0.Types;
  402. }
  403. catch (Exception)
  404. {
  405. types = Array.Empty<Type>();
  406. }
  407. foreach (var type in types.Where(x => x != null).Cast<TypeInfo>())
  408. try
  409. {
  410. var asType = type.AsType();
  411. if (Predicate(asType) && !result.Contains(asType))
  412. result.Add(asType);
  413. }
  414. catch (Exception el)
  415. {
  416. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", el.Message, el.StackTrace));
  417. //Console.WriteLine(type.Name + " : " + tl.Message);
  418. }
  419. }
  420. catch (Exception e)
  421. {
  422. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  423. }
  424. }
  425. catch (Exception e)
  426. {
  427. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  428. }
  429. }
  430. catch (Exception e)
  431. {
  432. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  433. }
  434. return result;
  435. }
  436. public static object? ChangeType(object? value, Type type)
  437. {
  438. if ((value == null || value is DBNull) && type.GetTypeInfo().IsGenericType)
  439. return Activator.CreateInstance(type);
  440. if (value == null)
  441. return null;
  442. if (value is DBNull)
  443. return null;
  444. if (type == value.GetType())
  445. return value;
  446. if (type == typeof(bool))
  447. return value.Equals(bool.TrueString) || value.Equals(1) || value.Equals("1");
  448. if (type.GetTypeInfo().IsEnum)
  449. {
  450. if (value.GetType().IsArray)
  451. return (value as Array).Cast<object>().Select(x => Enum.ToObject(type, x)).ToArray();
  452. if (value is string)
  453. return Enum.Parse(type, value as string);
  454. if (value is IEnumerable<object> list)
  455. return list.Select(x => Enum.ToObject(type, x)).ToArray();
  456. return Enum.ToObject(type, value);
  457. }
  458. if (!type.GetTypeInfo().IsInterface && type.GetTypeInfo().IsGenericType)
  459. {
  460. var innerType = type.GetTypeInfo().GetGenericArguments()[0];
  461. var innerValue = ChangeType(value, innerType);
  462. return Activator.CreateInstance(type, innerValue);
  463. }
  464. if (value is string && type == typeof(Guid))
  465. try
  466. {
  467. return new Guid(value as string);
  468. }
  469. catch
  470. {
  471. return Guid.Empty;
  472. }
  473. if (value is IEnumerable<object> objList && type == typeof(Guid))
  474. return objList.Select(x => ChangeType<Guid>(x)).ToArray();
  475. if (value is byte[] && type == typeof(Guid))
  476. return new Guid(value as byte[]);
  477. if (value is string && type == typeof(Version))
  478. return new Version(value as string);
  479. if (value is byte && type == typeof(TimeSpan))
  480. return new TimeSpan((byte)value);
  481. if (value is string && type == typeof(TimeSpan))
  482. return TimeSpan.Parse(value as string);
  483. if (value is string && type == typeof(DateTime))
  484. return DateTime.Parse(value as string);
  485. if (value is bool && type == typeof(string))
  486. return (bool)value ? bool.TrueString : bool.FalseString;
  487. if (value is JArray && type == typeof(string[]))
  488. return (value as JArray).Select(x => x.ToString()).ToArray();
  489. if (value is string && type == typeof(byte[]))
  490. return Convert.FromBase64String(value as string);
  491. if (value is FilterConstant && type == typeof(DateTime))
  492. {
  493. if (Equals(FilterConstant.Now, value))
  494. return DateTime.Now;
  495. if (Equals(FilterConstant.Today, value))
  496. return DateTime.Today;
  497. }
  498. if (!(value is IConvertible))
  499. return value;
  500. return Convert.ChangeType(value, type);
  501. }
  502. [return: MaybeNull]
  503. public static T ChangeType<T>(object? value)
  504. {
  505. var newValue = ChangeType(value, typeof(T));
  506. if (newValue is T tValue)
  507. return tValue;
  508. return default;
  509. }
  510. public static string RandomHexString(int length)
  511. {
  512. var rdm = new Random((int)DateTime.Now.Ticks);
  513. var hexValue = string.Empty;
  514. int num;
  515. for (var i = 0; i < length; i++)
  516. {
  517. num = rdm.Next(0, 16);
  518. hexValue += num.ToString("X1");
  519. }
  520. return hexValue;
  521. }
  522. public static bool IsEmpty(this DateTime value)
  523. {
  524. return value.Ticks <= DateTime.MinValue.AddHours(8).Ticks;
  525. }
  526. #region Properties
  527. public static string GetFullPropertyName<Type, TProperty>(Expression<Func<Type, TProperty>> exp, string separator)
  528. {
  529. try
  530. {
  531. if (!TryFindMemberExpression(exp.Body, out var memberExp))
  532. return string.Empty;
  533. return GetFullPropertyName(memberExp, separator);
  534. }
  535. catch (Exception e)
  536. {
  537. throw e;
  538. }
  539. }
  540. public static string GetFullPropertyName(MemberExpression exp, string separator)
  541. {
  542. try
  543. {
  544. var currentExpression = exp;
  545. var memberNames = new Stack<string>();
  546. do
  547. {
  548. memberNames.Push(currentExpression.Member.Name);
  549. } while (TryFindMemberExpression(currentExpression.Expression, out currentExpression));
  550. var result = string.Join(separator, memberNames.ToArray());
  551. return result;
  552. }
  553. catch (Exception e)
  554. {
  555. throw e;
  556. }
  557. }
  558. // code adjusted to prevent horizontal overflow
  559. public static bool TryFindMemberExpression(Expression exp, [NotNullWhen(true)] out MemberExpression? memberExp)
  560. {
  561. memberExp = exp as MemberExpression;
  562. if (memberExp != null)
  563. return true;
  564. if (IsConversion(exp) && exp is UnaryExpression unary)
  565. {
  566. memberExp = unary.Operand as MemberExpression;
  567. if (memberExp != null)
  568. return true;
  569. }
  570. return false;
  571. }
  572. public static Expression<Func<T, TType>> GetPropertyExpression<T, TType>(string name)
  573. {
  574. var param = Expression.Parameter(typeof(T), "x");
  575. Expression body = param;
  576. foreach (var member in name.Split('.')) body = Expression.PropertyOrField(body, member);
  577. var p = Expression.Parameter(typeof(TType));
  578. var conversion = body.Type == typeof(TType) ? body : Expression.Convert(body, typeof(TType));
  579. return Expression.Lambda<Func<T, TType>>(conversion, param);
  580. }
  581. public static Expression<Func<T, object?>> GetPropertyExpression<T>(string name)
  582. {
  583. var param = Expression.Parameter(typeof(T), "x");
  584. Expression body = param;
  585. foreach (var member in name.Split('.')) body = Expression.PropertyOrField(body, member);
  586. var p = Expression.Parameter(typeof(object));
  587. var conversion = Expression.Convert(body, typeof(object));
  588. return Expression.Lambda<Func<T, object?>>(conversion, param);
  589. }
  590. public static MemberExpression GetMemberExpression(Type t, string name)
  591. {
  592. var param = Expression.Parameter(t, "x");
  593. Expression body = param;
  594. foreach (var member in name.Split('.'))
  595. body = Expression.PropertyOrField(body, member);
  596. var me = Expression.Lambda(body, param).Body as MemberExpression;
  597. return me;
  598. }
  599. public static Expression GetPropertyExpression(Type t, string name, Type? type = null)
  600. {
  601. var param = Expression.Parameter(t, "x");
  602. Expression body = param;
  603. foreach (var member in name.Split('.')) body = Expression.PropertyOrField(body, member);
  604. if (type != null)
  605. body = Expression.Convert(body, typeof(object));
  606. return Expression.Lambda(body, param);
  607. //var p2 = Expression.Parameter(t, "x");
  608. //Expression e2 = Expression.Lambda(Expression.Property(p2, name), p2);
  609. //return e2;
  610. }
  611. public static PropertyInfo GetProperty(Type t, string name)
  612. {
  613. if (TryGetProperty(t, name, out var info))
  614. return info;
  615. throw new Exception($"Property {name} does not exist for {t.Name}");
  616. }
  617. public static PropertyInfo GetProperty<T>(string name) => GetProperty(typeof(T), name);
  618. public static bool TryGetProperty(Type t, string name, [NotNullWhen(true)] out PropertyInfo? propertyInfo)
  619. {
  620. propertyInfo = null;
  621. var typeinfo = t.GetTypeInfo();
  622. var props = name.Split('.');
  623. foreach (var prop in props)
  624. {
  625. propertyInfo = typeinfo.GetProperty(prop);
  626. if (propertyInfo is null)
  627. return false;
  628. typeinfo = propertyInfo.PropertyType.GetTypeInfo();
  629. }
  630. if (propertyInfo is null)
  631. return false;
  632. return true;
  633. }
  634. public static bool TryGetProperty<T>(string name, [NotNullWhen(true)] out PropertyInfo? propertyInfo) =>
  635. TryGetProperty(typeof(T), name, out propertyInfo);
  636. public static bool HasProperty(Type t, string name)
  637. {
  638. PropertyInfo property;
  639. var typeinfo = t.GetTypeInfo();
  640. var props = name.Split('.');
  641. foreach (var prop in props)
  642. {
  643. property = typeinfo.GetProperty(prop);
  644. if (property == null)
  645. return false;
  646. typeinfo = property.PropertyType.GetTypeInfo();
  647. }
  648. return true;
  649. }
  650. public static object? GetPropertyParent(object o, string name)
  651. {
  652. var comps = name.Split('.').ToList();
  653. comps.Remove(comps.Last());
  654. if (comps.Count == 0)
  655. return o;
  656. return GetPropertyValue(o, string.Join(".", comps));
  657. }
  658. /// <summary>
  659. /// Gets the value of the object's given property.
  660. /// </summary>
  661. /// <param name="o">The object to get the property from.</param>
  662. /// <param name="name">The name of the property.</param>
  663. /// <returns>
  664. /// <see langword="null"/> if <paramref name="o"/> or any intermediate properties are <see langword="null"/>;
  665. /// otherwise the value of the property <paramref name="name"/>, which can be <see langword="null"/>.
  666. /// </returns>
  667. /// <exception cref="Exception">if the property does not exist.</exception>
  668. public static object? GetPropertyValue(object? o, string name)
  669. {
  670. if (o is null)
  671. return null;
  672. var t = o.GetType().GetTypeInfo();
  673. if (o is BaseObject)
  674. {
  675. var property = DatabaseSchema.Property(t, name);
  676. if (property != null && (property is CustomProperty || !name.Contains(".")))
  677. return property.Getter().Invoke(o);
  678. }
  679. var props = name.Split('.');
  680. foreach (var prop in props)
  681. {
  682. var rprop = t.GetProperty(prop);
  683. if (rprop == null)
  684. throw new Exception(string.Format("Property {0} does not exist for {1}", prop, o.GetType().Name));
  685. o = rprop.GetValue(o, null);
  686. if (o is null)
  687. return null;
  688. t = o.GetType().GetTypeInfo();
  689. }
  690. return o;
  691. }
  692. /// <summary>
  693. /// Sets a property on the given object, doing nothing if the property does not exist.
  694. /// </summary>
  695. /// <param name="o">The object to set the property of.</param>
  696. /// <param name="name">The property to set.</param>
  697. /// <param name="value">The value to set the property to.</param>
  698. public static void SetPropertyValue(object o, string name, object? value)
  699. {
  700. var bits = name.Split('.');
  701. for (var i = 0; i < bits.Length - 1; i++)
  702. {
  703. var propertyToGet = o.GetType().GetTypeInfo().GetProperty(bits[i]);
  704. if (propertyToGet == null)
  705. return;
  706. var newo = propertyToGet.GetValue(o, null);
  707. if (newo == null)
  708. {
  709. newo = Activator.CreateInstance(propertyToGet.PropertyType);
  710. propertyToGet.SetValue(o, newo);
  711. }
  712. o = newo;
  713. }
  714. var propertyToSet = o.GetType().GetTypeInfo().GetProperty(bits.Last());
  715. if (propertyToSet is null)
  716. {
  717. var iprop = DatabaseSchema.Property(o.GetType(), name);
  718. if (iprop is CustomProperty)
  719. {
  720. ((BaseObject)o).UserProperties[name] = value;
  721. return;
  722. }
  723. return;
  724. }
  725. //PropertyInfo propertyToSet = GetProperty(o.GetType(), name);
  726. object? convertedvalue = null;
  727. if (value != null)
  728. {
  729. if (propertyToSet.PropertyType.Equals(typeof(Type)))
  730. {
  731. convertedvalue = Type.GetType(value.ToString(), true, true);
  732. }
  733. else if (propertyToSet.PropertyType.GetTypeInfo().IsEnum)
  734. {
  735. convertedvalue = Enum.Parse(propertyToSet.PropertyType, value.ToString(), true);
  736. }
  737. //else if (propertyToSet.PropertyType.Equals(typeof(Memo)))
  738. // convertedvalue = (Memo)value.ToString();
  739. else if (propertyToSet.PropertyType.Equals(typeof(Guid)))
  740. {
  741. var guidvalue = Guid.Empty;
  742. Guid.TryParse(value.ToString(), out guidvalue);
  743. convertedvalue = guidvalue;
  744. }
  745. //else if (propertyToSet.PropertyType.IsSubclassOf(value.GetType()))
  746. // convertedvalue = value;
  747. else if (propertyToSet.PropertyType.IsAssignableFrom(value.GetType()))
  748. {
  749. convertedvalue = value;
  750. }
  751. else if (!(value is DBNull))
  752. {
  753. convertedvalue = Convert.ChangeType(value, propertyToSet.PropertyType);
  754. }
  755. }
  756. if (propertyToSet.CanWrite)
  757. {
  758. var method = propertyToSet.GetSetMethod();
  759. //if (method == null)
  760. var oldval = propertyToSet.GetValue(o);
  761. propertyToSet.SetValue(o, convertedvalue, null);
  762. if (o is BaseObject)
  763. ((BaseObject)o).OnPropertyChanged(propertyToSet.Name, oldval, convertedvalue);
  764. //else
  765. // method.Invoke(o, new Object[] { convertedvalue });
  766. //if (o.GetType().IsSubclassOf(typeof(BaseObject)))
  767. // ((BaseObject)o).OnPropertyChanged(name, propertyToSet.GetValue(o), convertedvalue);
  768. }
  769. }
  770. public static PropertyInfo[] GetInheritedProperties(Type type)
  771. {
  772. if (type.IsInterface)
  773. {
  774. var propertyInfos = new List<PropertyInfo>();
  775. var considered = new List<Type>();
  776. var queue = new Queue<Type>();
  777. considered.Add(type);
  778. queue.Enqueue(type);
  779. while (queue.Count > 0)
  780. {
  781. var subType = queue.Dequeue();
  782. foreach (var subInterface in subType.GetInterfaces())
  783. {
  784. if (considered.Contains(subInterface)) continue;
  785. considered.Add(subInterface);
  786. queue.Enqueue(subInterface);
  787. }
  788. var typeProperties = subType.GetProperties(
  789. BindingFlags.FlattenHierarchy
  790. | BindingFlags.Public
  791. | BindingFlags.Instance);
  792. var newPropertyInfos = typeProperties
  793. .Where(x => !propertyInfos.Contains(x));
  794. propertyInfos.InsertRange(0, newPropertyInfos);
  795. }
  796. return propertyInfos.ToArray();
  797. }
  798. return type.GetProperties(BindingFlags.FlattenHierarchy
  799. | BindingFlags.Public | BindingFlags.Instance);
  800. }
  801. public static Dictionary<string, Type> PropertyList(Type T, Func<PropertyInfo, bool> Predicate, bool Recursive)
  802. {
  803. Dictionary<string, Type> properties;
  804. if (T.GetTypeInfo().BaseType != null)
  805. properties = PropertyList(T.GetTypeInfo().BaseType, Predicate, Recursive);
  806. else
  807. properties = new Dictionary<string, Type>();
  808. //TypeInfo entitytype = typeof(Entity).GetTypeInfo();
  809. //TypeInfo componenttype = typeof(EnclosedEntity).GetTypeInfo();
  810. foreach (var prop in T.GetRuntimeProperties())
  811. // '.' contains check for explicit implementation of interface properties
  812. if (!properties.ContainsKey(prop.Name) && Predicate(prop) && !prop.Name.Contains('.'))
  813. {
  814. var propertytype = prop.PropertyType.GetTypeInfo();
  815. if (
  816. Recursive &&
  817. (
  818. propertytype.IsSubclassOf(typeof(Entity)) ||
  819. propertytype.GetInterfaces().Contains(typeof(IEnclosedEntity)) ||
  820. propertytype.GetInterfaces().Contains(typeof(IEntityLink))
  821. )
  822. )
  823. {
  824. var props = PropertyList(prop.PropertyType, Predicate, Recursive);
  825. foreach (var key in props.Keys) properties[string.Format("{0}.{1}", prop.Name, key)] = props[key];
  826. }
  827. else
  828. {
  829. properties[prop.Name] = prop.PropertyType;
  830. }
  831. }
  832. return properties;
  833. }
  834. public static Dictionary<string, PropertyInfo> PropertyInfoList(Type T, Func<PropertyInfo, bool> Predicate, bool Recursive)
  835. {
  836. Dictionary<string, PropertyInfo> properties;
  837. if (T.GetTypeInfo().BaseType != null)
  838. properties = PropertyInfoList(T.GetTypeInfo().BaseType, Predicate, Recursive);
  839. else
  840. properties = new Dictionary<string, PropertyInfo>();
  841. //TypeInfo entitytype = typeof(Entity).GetTypeInfo();
  842. //TypeInfo componenttype = typeof(EnclosedEntity).GetTypeInfo();
  843. foreach (var prop in T.GetRuntimeProperties())
  844. // '.' contains check for explicit implementation of interface properties
  845. if (!properties.ContainsKey(prop.Name) && Predicate(prop) && !prop.Name.Contains('.'))
  846. {
  847. var propertytype = prop.PropertyType.GetTypeInfo();
  848. if (
  849. Recursive &&
  850. (
  851. propertytype.IsSubclassOf(typeof(Entity)) ||
  852. propertytype.GetInterfaces().Contains(typeof(IEnclosedEntity)) ||
  853. propertytype.GetInterfaces().Contains(typeof(IEntityLink))
  854. )
  855. )
  856. {
  857. var props = PropertyInfoList(prop.PropertyType, Predicate, Recursive);
  858. foreach (var key in props.Keys) properties[string.Format("{0}.{1}", prop.Name, key)] = props[key];
  859. }
  860. else
  861. {
  862. properties[prop.Name] = prop;
  863. }
  864. }
  865. return properties;
  866. }
  867. public static IEnumerable<PropertyInfo> PropertyList(Type T, Func<PropertyInfo, bool> Predicate)
  868. {
  869. return T.GetRuntimeProperties().Where(x => Predicate(x));
  870. }
  871. private static PropertyInfo InternalGetPropertyFromExpression<TObject, TType>(Expression<Func<TObject, TType>> GetPropertyLambda)
  872. {
  873. MemberExpression Exp;
  874. //this line is necessary, because sometimes the expression comes in as Convert(originalexpression)
  875. if (GetPropertyLambda.Body is UnaryExpression unary)
  876. {
  877. Exp = unary.Operand as MemberExpression ?? throw new ArgumentException();
  878. }
  879. else if (GetPropertyLambda.Body is MemberExpression)
  880. {
  881. Exp = (MemberExpression)GetPropertyLambda.Body;
  882. }
  883. else
  884. {
  885. throw new ArgumentException();
  886. }
  887. return (PropertyInfo)Exp.Member;
  888. }
  889. public static PropertyInfo GetPropertyFromExpression<TObject, TStruct>(Expression<Func<TObject, TStruct>> lambda)
  890. {
  891. return InternalGetPropertyFromExpression(lambda);
  892. }
  893. public static PropertyInfo GetPropertyFromExpression<T>(Expression<Func<T, object>> GetPropertyLambda)
  894. {
  895. MemberExpression Exp;
  896. //this line is necessary, because sometimes the expression comes in as Convert(originalexpression)
  897. if (GetPropertyLambda.Body is UnaryExpression)
  898. {
  899. var UnExp = (UnaryExpression)GetPropertyLambda.Body;
  900. if (UnExp.Operand is MemberExpression)
  901. Exp = (MemberExpression)UnExp.Operand;
  902. else
  903. throw new ArgumentException();
  904. }
  905. else if (GetPropertyLambda.Body is MemberExpression)
  906. {
  907. Exp = (MemberExpression)GetPropertyLambda.Body;
  908. }
  909. else
  910. {
  911. throw new ArgumentException();
  912. }
  913. return (PropertyInfo)Exp.Member;
  914. }
  915. #endregion
  916. public static bool IsCollection(PropertyInfo prop)
  917. {
  918. if (!typeof(string).Equals(prop.PropertyType))
  919. if (typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(prop.PropertyType))
  920. if (!prop.PropertyType.IsArray)
  921. if (prop.PropertyType.GenericTypeArguments[0].GetTypeInfo().IsSubclassOf(typeof(Entity)))
  922. return true;
  923. return false;
  924. }
  925. private static bool IsConversion(Expression exp)
  926. {
  927. return exp.NodeType == ExpressionType.Convert ||
  928. exp.NodeType == ExpressionType.ConvertChecked;
  929. }
  930. //public static Dictionary<String, Type> PropertyList(Type T, bool Public = true, bool Static = false)
  931. //{
  932. // Dictionary<String, Type> properties = new Dictionary<String, Type>();
  933. // foreach (PropertyInfo prop in T.GetRuntimeProperties())
  934. // {
  935. // if ((prop.GetMethod.IsPublic == Public) && (prop.GetMethod.IsStatic == Static))
  936. // {
  937. // if (prop.PropertyType.GetTypeInfo().IsAssignableFrom(typeof(Entity).GetTypeInfo()))
  938. // {
  939. // Dictionary<String, Type> props = PropertyList(prop.PropertyType);
  940. // foreach (String key in props.Keys)
  941. // {
  942. // properties[String.Format("{0}.{1}", prop.Name, key)] = props[key];
  943. // }
  944. // }
  945. // else if (!prop.PropertyType.Equals(typeof(Guid)))
  946. // {
  947. // properties[prop.Name] = prop.GetType();
  948. // }
  949. // }
  950. // }
  951. // return properties;
  952. //}
  953. /// <summary>
  954. /// Get all the child properties of an object that match a given type
  955. /// </summary>
  956. /// <typeparam name="T">The class of property to search for</typeparam>
  957. /// <param name="parent">The object to search</param>
  958. /// <returns>A list of the objects found</returns>
  959. public static IEnumerable<PropertyInfo> GetChildrenProperties<T>(Type parentType)
  960. {
  961. return PropertyList(
  962. parentType,
  963. x => typeof(T).IsAssignableFrom(x.PropertyType)
  964. );
  965. }
  966. /// <summary>
  967. /// Get all the child properties of an object that match a given type
  968. /// </summary>
  969. /// <typeparam name="T">The class of property to search for</typeparam>
  970. /// <param name="parent">The object to search</param>
  971. /// <returns>A list of the objects found</returns>
  972. public static IEnumerable<T> GetChildren<T>(object parent)
  973. {
  974. var children = new List<T>();
  975. var props = PropertyList(
  976. parent.GetType(),
  977. x => typeof(T).IsAssignableFrom(x.PropertyType)
  978. );
  979. foreach (var prop in props)
  980. {
  981. var child = (T)prop.GetValue(parent);
  982. if (child != null)
  983. children.Add(child);
  984. }
  985. return children;
  986. }
  987. /// <summary>
  988. /// Get all list properties of an object that are collections of a given type
  989. /// </summary>
  990. /// <typeparam name="T">The class of child object to search for</typeparam>
  991. /// <param name="parent">The object to search</param>
  992. /// <returns>A list of the collections found</returns>
  993. public static IEnumerable<TType>[] GetCollectionsOfType<TType>(object parent)
  994. {
  995. var lists = new List<IEnumerable<TType>>();
  996. var props = PropertyList(parent.GetType(), x => true); // !typeof(String).Equals(x.PropertyType));
  997. foreach (var prop in props)
  998. if (typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(prop.PropertyType))
  999. if (prop.PropertyType.GenericTypeArguments.Length == 1)
  1000. if (prop.PropertyType.GenericTypeArguments[0].GetTypeInfo().GetInterfaces().Contains(typeof(TType)))
  1001. lists.Add((IEnumerable<TType>)prop.GetValue(parent));
  1002. return lists.ToArray();
  1003. }
  1004. //public static IEnumerable<Assembly> GetReferencingAssemblies(string assemblyName)
  1005. //{
  1006. // var assemblies = new List<Assembly>();
  1007. // var dependencies = DependencyContext.Default.RuntimeLibraries;
  1008. // foreach (var library in dependencies)
  1009. // {
  1010. // if (IsCandidateLibrary(library, assemblyName))
  1011. // {
  1012. // var assembly = Assembly.Load(new AssemblyName(library.Name));
  1013. // assemblies.Add(assembly);
  1014. // }
  1015. // }
  1016. // return assemblies;
  1017. //}
  1018. //private static bool IsCandidateLibrary(RuntimeLibrary library, assemblyName)
  1019. //{
  1020. // return library.Name == (assemblyName)
  1021. // || library.Dependencies.Any(d => d.Name.StartsWith(assemblyName));
  1022. //}
  1023. //public static IEnumerable<Assembly> AssemblyList(Expression<Func<Type,bool>> Predicate)
  1024. //{
  1025. // Func<Type, bool> lambda = Predicate.Compile();
  1026. // List<Assembly> assemblies = new List<Assembly>();
  1027. // IEnumerable<Assembly> allassemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).ToArray();
  1028. // foreach (Assembly assembly in allassemblies)
  1029. // {
  1030. // IEnumerable<Type> types = CoreUtils.TypeList(
  1031. // new Assembly[] { assembly },
  1032. // Predicate
  1033. // );
  1034. // if (types.Count() > 0)
  1035. // assemblies.Add(assembly);
  1036. // }
  1037. // return assemblies;
  1038. //}
  1039. //public static string SerializeExpression<T>(Expression obj)
  1040. //{
  1041. // JsonSerializerSettings _settings;
  1042. // var defaultSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects };
  1043. // defaultSettings.Converters.Add(new ExpressionJsonConverter(typeof(T)));
  1044. // _settings = defaultSettings;
  1045. // return Serialization.Serialize(obj, _settings);
  1046. //}
  1047. //public static Expression DeserializeExpression<T>(string json)
  1048. //{
  1049. // JsonSerializerSettings _settings;
  1050. // var defaultSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects };
  1051. // defaultSettings.Converters.Add(new ExpressionJsonConverter(typeof(T)));
  1052. // _settings = defaultSettings;
  1053. // return Serialization.Deserialize<Expression>(json, _settings);
  1054. //}
  1055. /// <summary>
  1056. /// [ <c>public static object GetDefault(this Type type)</c> ]
  1057. /// <para></para>
  1058. /// Retrieves the default value for a given Type
  1059. /// </summary>
  1060. /// <param name="type">The Type for which to get the default value</param>
  1061. /// <returns>The default value for <paramref name="type" /></returns>
  1062. /// <remarks>
  1063. /// If a null Type, a reference Type, or a System.Void Type is supplied, this method always returns null. If a value
  1064. /// type
  1065. /// is supplied which is not publicly visible or which contains generic parameters, this method will fail with an
  1066. /// exception.
  1067. /// </remarks>
  1068. /// <example>
  1069. /// To use this method in its native, non-extension form, make a call like:
  1070. /// <code>
  1071. /// object Default = DefaultValue.GetDefault(someType);
  1072. /// </code>
  1073. /// To use this method in its Type-extension form, make a call like:
  1074. /// <code>
  1075. /// object Default = someType.GetDefault();
  1076. /// </code>
  1077. /// </example>
  1078. /// <seealso cref="GetDefault&lt;T&gt;" />
  1079. public static object? GetDefault(this Type type)
  1080. {
  1081. // If no Type was supplied, if the Type was a reference type, or if the Type was a System.Void, return null
  1082. if (type == null || !type.GetTypeInfo().IsValueType || type == typeof(void))
  1083. return null;
  1084. // If the supplied Type has generic parameters, its default value cannot be determined
  1085. if (type.GetTypeInfo().ContainsGenericParameters)
  1086. throw new ArgumentException(
  1087. "Error:\n\nThe supplied value type <" + type.Name +
  1088. "> contains generic parameters, so the default value cannot be retrieved\n\n");
  1089. // If the Type is a primitive type, or if it is another publicly-visible value type (i.e. struct/enum), return a
  1090. // default instance of the value type
  1091. if (type.GetTypeInfo().IsPrimitive || !type.GetTypeInfo().IsNotPublic)
  1092. try
  1093. {
  1094. return Activator.CreateInstance(type);
  1095. }
  1096. catch (Exception e)
  1097. {
  1098. throw new ArgumentException(
  1099. "Error:\n\nThe Activator.CreateInstance method could not " +
  1100. "create a default instance of the supplied value type <" + type.Name +
  1101. "> (Inner Exception message: \"" + e.Message + "\")");
  1102. }
  1103. // Fail with exception
  1104. throw new ArgumentException("Error:\n\nThe supplied value type <" + type +
  1105. "> is not a publicly-visible type, so the default value cannot be retrieved");
  1106. }
  1107. /// <summary>
  1108. /// [ <c>public static T GetDefault&lt; T &gt;()</c> ]
  1109. /// <para></para>
  1110. /// Retrieves the default value for a given Type
  1111. /// </summary>
  1112. /// <typeparam name="T">The Type for which to get the default value</typeparam>
  1113. /// <returns>The default value for Type T</returns>
  1114. /// <remarks>
  1115. /// If a reference Type or a System.Void Type is supplied, this method always returns null. If a value type
  1116. /// is supplied which is not publicly visible or which contains generic parameters, this method will fail with an
  1117. /// exception.
  1118. /// </remarks>
  1119. /// <seealso cref="GetDefault(Type)" />
  1120. [return: MaybeNull]
  1121. public static T GetDefault<T>()
  1122. {
  1123. return (T)GetDefault(typeof(T));
  1124. }
  1125. public static bool IsDefault<T>(T value)
  1126. {
  1127. return IsDefault(typeof(T), value);
  1128. }
  1129. /// <summary>
  1130. /// [ <c>public static bool IsObjectSetToDefault(this Type ObjectType, object ObjectValue)</c> ]
  1131. /// <para></para>
  1132. /// Reports whether a value of type T (or a null reference of type T) contains the default value for that Type
  1133. /// </summary>
  1134. /// <remarks>
  1135. /// Reports whether the object is empty or unitialized for a reference type or nullable value type (i.e. is null) or
  1136. /// whether the object contains a default value for a non-nullable value type (i.e. int = 0, bool = false, etc.)
  1137. /// <para></para>
  1138. /// NOTE: For non-nullable value types, this method introduces a boxing/unboxing performance penalty.
  1139. /// </remarks>
  1140. /// <param name="ObjectType">Type of the object to test</param>
  1141. /// <param name="ObjectValue">The object value to test, or null for a reference Type or nullable value Type</param>
  1142. /// <returns>
  1143. /// true = The object contains the default value for its Type.
  1144. /// <para></para>
  1145. /// false = The object has been changed from its default value.
  1146. /// </returns>
  1147. public static bool IsDefault(this Type ObjectType, object? ObjectValue)
  1148. {
  1149. // If no ObjectType was supplied, attempt to determine from ObjectValue
  1150. if (ObjectType == null)
  1151. {
  1152. // If no ObjectValue was supplied, abort
  1153. if (ObjectValue == null) throw new ArgumentNullException("Error:\n\nCannot determine the ObjectType from a null Value");
  1154. // Determine ObjectType from ObjectValue
  1155. ObjectType = ObjectValue.GetType();
  1156. }
  1157. // Get the default value of type ObjectType
  1158. var Default = ObjectType.GetDefault();
  1159. // If a non-null ObjectValue was supplied, compare Value with its default value and return the result
  1160. if (ObjectValue != null)
  1161. return ObjectValue.Equals(Default);
  1162. // Since a null ObjectValue was supplied, report whether its default value is null
  1163. return Default == null;
  1164. }
  1165. public static bool IsBase64String(this string s)
  1166. {
  1167. s = s.Trim();
  1168. return s.Length % 4 == 0 && Regex.IsMatch(s, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None);
  1169. }
  1170. public static string CalculateCRC(byte[] data)
  1171. {
  1172. var hash = Crc32.Compute(data);
  1173. return string.Format("{0:X8}", hash);
  1174. }
  1175. //public static TimeSpan Round(this TimeSpan timespan, TimeSpan interval)
  1176. //{
  1177. // // The round number, here is a quarter... in seconds
  1178. // double Round = interval.TotalSeconds;
  1179. // // Count of round number in this total Seconds...
  1180. // double CountRound = (timespan.TotalSeconds / Round);
  1181. // // The main formula to calculate round time...
  1182. // int Sec = (int)(Math.Truncate(CountRound + 0.5) * Round);
  1183. // // Now show the result...
  1184. // TimeSpan tRes = new TimeSpan(0, 0, Sec);
  1185. // return tRes;
  1186. //}
  1187. public static bool IsNumeric(this Type dataType)
  1188. {
  1189. return dataType.IsFloatingPoint() || dataType.IsOrdinal();
  1190. }
  1191. public static bool IsFloatingPoint(this Type dataType)
  1192. {
  1193. if (dataType == null)
  1194. return false;
  1195. return dataType == typeof(double)
  1196. || dataType == typeof(float)
  1197. || dataType == typeof(float);
  1198. }
  1199. public static bool IsOrdinal(this Type dataType)
  1200. {
  1201. if (dataType == null)
  1202. return false;
  1203. return dataType == typeof(int)
  1204. || dataType == typeof(long)
  1205. || dataType == typeof(short)
  1206. || dataType == typeof(short)
  1207. || dataType == typeof(int)
  1208. || dataType == typeof(long)
  1209. || dataType == typeof(uint)
  1210. || dataType == typeof(ushort)
  1211. || dataType == typeof(uint)
  1212. || dataType == typeof(ulong)
  1213. || dataType == typeof(sbyte);
  1214. }
  1215. //Extension method for MailMessage to save to a file on disk
  1216. public static string GenerateEMLFile(this MailMessage message, bool addUnsentHeader = true)
  1217. {
  1218. var filename = Path.ChangeExtension(Path.GetTempFileName(), ".eml");
  1219. using (var filestream = File.Open(filename, FileMode.Create))
  1220. {
  1221. if (addUnsentHeader)
  1222. {
  1223. var binaryWriter = new BinaryWriter(filestream);
  1224. //Write the Unsent header to the file so the mail client knows this mail must be presented in "New message" mode
  1225. binaryWriter.Write(Encoding.UTF8.GetBytes("X-Unsent: 1" + Environment.NewLine));
  1226. }
  1227. var assembly = typeof(SmtpClient).Assembly;
  1228. var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
  1229. // Get reflection info for MailWriter contructor
  1230. var mailWriterContructor =
  1231. mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
  1232. // Construct MailWriter object with our FileStream
  1233. var mailWriter = mailWriterContructor.Invoke(new object[] { filestream });
  1234. // Get reflection info for Send() method on MailMessage
  1235. var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
  1236. sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null);
  1237. // Finally get reflection info for Close() method on our MailWriter
  1238. var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);
  1239. // Call close method
  1240. closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
  1241. }
  1242. return filename;
  1243. }
  1244. public static Columns<T> GetColumns<T>(Columns<T>? columns)
  1245. => (GetColumns(typeof(T), columns) as Columns<T>)!;
  1246. public static IColumns GetColumns(Type T, IColumns? columns)
  1247. {
  1248. //var cols = columns;
  1249. if (columns == null || !columns.Any())
  1250. {
  1251. if (!_columnscache.TryGetValue(T, out var result))
  1252. {
  1253. result = Columns.Create(T);
  1254. var props = PropertyList(T,
  1255. x =>
  1256. x.GetCustomAttribute<DoNotSerialize>() == null &&
  1257. x.GetCustomAttribute<DoNotPersist>() == null &&
  1258. x.CanWrite && x.PropertyType != typeof(UserProperties), true);
  1259. foreach (var prop in props)
  1260. result.Add(prop.Key);
  1261. var custom = DatabaseSchema.Properties(T).Where(x => x is CustomProperty);
  1262. foreach (var prop in custom)
  1263. result.Add(prop.Name);
  1264. _columnscache[T] = result;
  1265. }
  1266. return result;
  1267. }
  1268. return columns;
  1269. //{
  1270. // foreach (var col in cols.Items)
  1271. // {
  1272. // try
  1273. // {
  1274. // result.Add(col.Property);
  1275. // //PropertyInfo prop = null;
  1276. // //IProperty iprop = null;
  1277. // //if (col.Property != null)
  1278. // //{
  1279. // // try
  1280. // // {
  1281. // // iprop = DatabaseSchema.Property(typeof(T), col.Property);
  1282. // // }
  1283. // // catch (Exception e2)
  1284. // // {
  1285. // // }
  1286. // // if ((iprop != null) && (iprop is CustomProperty))
  1287. // // result.Add(col.Property);
  1288. // // else
  1289. // // {
  1290. // // prop = CoreUtils.GetProperty(typeof(T), col.Property);
  1291. // // if ((prop.GetCustomAttribute<DoNotSerialize>() == null) && (prop.GetCustomAttribute<DoNotPersist>() == null) && prop.CanWrite)
  1292. // // result.Add(col.Property);
  1293. // // }
  1294. // //}
  1295. // //else
  1296. // //{
  1297. // // String property = CoreUtils.GetFullPropertyName((MemberExpression)col.Expression, ".");
  1298. // // prop = CoreUtils.GetProperty(typeof(T), property);
  1299. // // if ((prop.GetCustomAttribute<DoNotSerialize>() == null) && (prop.GetCustomAttribute<DoNotPersist>() == null) && prop.CanWrite)
  1300. // // result.Add(property);
  1301. // //}
  1302. // }
  1303. // catch (Exception e)
  1304. // {
  1305. // }
  1306. // }
  1307. //}
  1308. //return result;
  1309. }
  1310. public static List<string> GetColumnNames(Type T, Func<PropertyInfo, bool> Predicate)
  1311. {
  1312. //var cols = columns;
  1313. var result = new List<string>();
  1314. var props = PropertyList(T,
  1315. x =>
  1316. x.GetCustomAttribute<DoNotSerialize>() == null &&
  1317. x.GetCustomAttribute<DoNotPersist>() == null &&
  1318. x.CanWrite && x.PropertyType != typeof(UserProperties) && Predicate(x), true);
  1319. foreach (var prop in props)
  1320. result.Add(prop.Key);
  1321. var custom = DatabaseSchema.Properties(T).Where(x => x is CustomProperty);
  1322. foreach (var prop in custom)
  1323. result.Add(prop.Name);
  1324. return result;
  1325. }
  1326. public static string TypedValueToString(object value)
  1327. {
  1328. var type = value.GetType();
  1329. var Culture = CultureInfo.CurrentCulture;
  1330. if (type == typeof(string))
  1331. return (string)value;
  1332. if (type == typeof(string[]))
  1333. return Serialization.Serialize(value);
  1334. if (IsNumeric(type))
  1335. return string.Format(Culture.NumberFormat, "{0}", value);
  1336. // TimeSpan - use constant pattern
  1337. if (type == typeof(TimeSpan))
  1338. return string.Format("{0:c}", value);
  1339. // DateTime - use round-trip pattern
  1340. if (type == typeof(DateTime))
  1341. return string.Format("{0:o}", value);
  1342. if (type == typeof(Guid))
  1343. return ((Guid)value).ToString();
  1344. var converter = TypeDescriptor.GetConverter(type);
  1345. if (converter != null && converter.CanConvertTo(typeof(string)))
  1346. return converter.ConvertToString(value);
  1347. throw new Exception(string.Format("Cannot Convert {0} to String", type.Name));
  1348. }
  1349. public static object? StringToTypedValue(string value, Type type)
  1350. {
  1351. var Culture = CultureInfo.CurrentCulture;
  1352. if (type == typeof(object) && string.IsNullOrEmpty(value))
  1353. return null;
  1354. if (type == typeof(string))
  1355. return value;
  1356. if (type == typeof(string[]))
  1357. return Serialization.Deserialize<string[]>(value);
  1358. if (type == typeof(sbyte))
  1359. return sbyte.Parse(value, NumberStyles.Integer, Culture);
  1360. if (type == typeof(byte))
  1361. return byte.Parse(value, NumberStyles.Integer, Culture);
  1362. if (type == typeof(ushort))
  1363. return ushort.Parse(value, NumberStyles.Integer, Culture);
  1364. if (type == typeof(uint))
  1365. return uint.Parse(value, NumberStyles.Integer, Culture);
  1366. if (type == typeof(ulong))
  1367. return ulong.Parse(value, NumberStyles.Integer, Culture);
  1368. if (type == typeof(short))
  1369. return short.Parse(value, NumberStyles.Integer, Culture);
  1370. if (type == typeof(int))
  1371. return int.Parse(value, NumberStyles.Integer, Culture);
  1372. if (type == typeof(long))
  1373. return long.Parse(value, NumberStyles.Integer, Culture);
  1374. if (type == typeof(float))
  1375. return float.Parse(value, NumberStyles.Any, Culture);
  1376. if (type == typeof(double))
  1377. return double.Parse(value, NumberStyles.Any, Culture);
  1378. if (type == typeof(decimal))
  1379. return decimal.Parse(value, NumberStyles.Any, Culture);
  1380. if (type == typeof(TimeSpan))
  1381. return TimeSpan.ParseExact(value, "c", null);
  1382. if (type == typeof(DateTime))
  1383. return DateTime.ParseExact(value, "o", null);
  1384. if (type == typeof(Guid))
  1385. return Guid.Parse(value);
  1386. var converter = TypeDescriptor.GetConverter(type);
  1387. if (converter != null && converter.CanConvertFrom(typeof(string)))
  1388. return converter.ConvertFromString(value);
  1389. throw new Exception(string.Format("Cannot Convert String to {0}", type.Name));
  1390. }
  1391. public static bool ContainsInheritedGenericType(this Type type, Type generic)
  1392. {
  1393. if (type == null)
  1394. return false;
  1395. if (type.GenericTypeArguments.Contains(generic))
  1396. return true;
  1397. if (type.BaseType == null)
  1398. return false;
  1399. return type.BaseType.ContainsInheritedGenericType(generic);
  1400. }
  1401. public static IEnumerable<Type> GetInheritedGenericTypeArguments(this Type type)
  1402. {
  1403. if (type == null)
  1404. return new Type[] { };
  1405. if (type.GetGenericArguments().Any())
  1406. return type.GenericTypeArguments;
  1407. if (type.BaseType == null)
  1408. return new Type[] { };
  1409. return type.BaseType.GetInheritedGenericTypeArguments();
  1410. }
  1411. //static readonly Regex StripQuotes = new Regex(@"&quot;", RegexOptions.Compiled);
  1412. public static string StripHTML(this string html)
  1413. {
  1414. if (string.IsNullOrWhiteSpace(html))
  1415. return "";
  1416. var result = StripHtmlStyles.Replace(html, "");
  1417. result = StripHtmlTags.Replace(result, "");
  1418. result = StripSpecialCharacters.Replace(result, "");
  1419. //result = StripQuotes.Replace(result, "\"");
  1420. result = StripLineBreaks.Replace(result, "$1");
  1421. result = result.Replace("\0", "").Trim();
  1422. return result;
  1423. }
  1424. public static string GetCaption(this Type type, bool usedefault = true)
  1425. {
  1426. var attribute = type.GetCustomAttribute<Caption>();
  1427. var result = attribute != null
  1428. ? attribute.Text
  1429. : usedefault
  1430. ? type.Name
  1431. : "";
  1432. return result;
  1433. }
  1434. public static string SanitiseFileName(string filename)
  1435. {
  1436. var invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
  1437. var invalidReStr = string.Format(@"[{0}]+", invalidChars);
  1438. var reservedWords = new[]
  1439. {
  1440. "CON", "PRN", "AUX", "CLOCK$", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4",
  1441. "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4",
  1442. "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
  1443. };
  1444. var sanitisedNamePart = Regex.Replace(filename, invalidReStr, "_");
  1445. foreach (var reservedWord in reservedWords)
  1446. {
  1447. var reservedWordPattern = string.Format("^{0}\\.", reservedWord);
  1448. sanitisedNamePart = Regex.Replace(sanitisedNamePart, reservedWordPattern, "_reservedWord_.", RegexOptions.IgnoreCase);
  1449. }
  1450. return sanitisedNamePart;
  1451. }
  1452. private static Regex NeatifyRegex = new Regex(@"
  1453. (?<=[A-Z])(?=[A-Z][a-z]) |
  1454. (?<=[^A-Z])(?=[A-Z]) |
  1455. (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace);
  1456. public static string Neatify(string caption)
  1457. {
  1458. if (string.Equals(caption, "ID"))
  1459. return caption;
  1460. var result = NeatifyRegex.Replace(caption.Replace(".", ""), " ");
  1461. while (result.Contains(" "))
  1462. result = result.Replace(" ", " ");
  1463. if (result.EndsWith(" ID"))
  1464. result = string.Join(" ", result.Split(' ').Reverse().Skip(1).Reverse());
  1465. return result.Trim();
  1466. }
  1467. private static List<Tuple<Type, String, decimal>> _columnsequences = new List<Tuple<Type, string, decimal>>();
  1468. public static decimal GetPropertySequence(Type type, string column)
  1469. {
  1470. var tuple = _columnsequences.FirstOrDefault(x => Type.Equals(x.Item1, type) && String.Equals(x.Item2, column));
  1471. if (tuple == null)
  1472. {
  1473. decimal result = 0.0M;
  1474. var customprop = DatabaseSchema.Property(type, column);
  1475. if (customprop != null && customprop is CustomProperty)
  1476. {
  1477. result = customprop.Sequence;
  1478. }
  1479. else
  1480. {
  1481. var bits = column.Split('.');
  1482. for (var i = 0; i < bits.Length; i++)
  1483. {
  1484. var sProp = string.Join(".", bits.Take(bits.Length - i));
  1485. PropertyInfo? prop = null;
  1486. try
  1487. {
  1488. prop = GetProperty(type, sProp);
  1489. }
  1490. catch (Exception e)
  1491. {
  1492. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1493. }
  1494. if (prop != null)
  1495. {
  1496. result = prop.GetSequence() + (result / 1000.0M);
  1497. }
  1498. else
  1499. {
  1500. var cprop = DatabaseSchema.Property(type, sProp);
  1501. if (cprop != null)
  1502. result = cprop.Sequence;
  1503. else
  1504. result = result / 1000.0M;
  1505. }
  1506. }
  1507. //result = double.MinValue + result;
  1508. }
  1509. _columnsequences.Add(new Tuple<Type, string, decimal>(type, column, result));
  1510. return result;
  1511. }
  1512. else
  1513. return tuple.Item3;
  1514. }
  1515. /// <summary>
  1516. /// Gets the AppData folder for this application.
  1517. /// </summary>
  1518. /// <returns>The path of the AppData folder.</returns>
  1519. public static string GetPath()
  1520. {
  1521. if (Assembly.GetEntryAssembly() != null)
  1522. return Path.Combine(
  1523. Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
  1524. Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)
  1525. );
  1526. return Path.Combine(
  1527. Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
  1528. Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location)
  1529. );
  1530. }
  1531. public static string GetCommonAppData(string? folderName = null)
  1532. {
  1533. folderName ??= Assembly.GetEntryAssembly() != null
  1534. ? Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)
  1535. : Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location);
  1536. return Path.Combine(
  1537. Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
  1538. folderName
  1539. );
  1540. }
  1541. public static string GetVersion()
  1542. {
  1543. // 2022-10-13 FVB First look in the executable directory
  1544. var curfile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "version.txt");
  1545. if (File.Exists(curfile))
  1546. return File.ReadAllText(curfile);
  1547. // Then look in the app data directory if you cannot find it
  1548. curfile = Path.Combine(GetPath(), "version.txt");
  1549. if (File.Exists(curfile))
  1550. return File.ReadAllText(curfile);
  1551. return "???";
  1552. }
  1553. public static string SplitCamelCase(this string value)
  1554. {
  1555. return string.Join(" ", Regex.Split(value, @"(?<!^)(?=[A-Z](?![A-Z]|$))")).Replace(" ", " ");
  1556. }
  1557. public static bool IsEffectivelyEqual(double a, double b, double threshold = 0.00001F)
  1558. {
  1559. return Math.Abs(a - b) < threshold;
  1560. }
  1561. public static bool IsEntityLinkValid<T, U>(this CoreRow arg, Expression<Func<T, U>> expression) where U : IEntityLink
  1562. {
  1563. var col = CoreUtils.GetFullPropertyName(expression, ".");
  1564. return arg.Get<Guid>(col + ".ID") != Guid.Empty && arg.Get<Guid>(col + ".Deleted") == Guid.Empty;
  1565. }
  1566. /// <summary>
  1567. /// Gets the ID of an entity link of an entity, doing a validity check (see <see cref="IsEntityLinkValid{T, U}(CoreRow, Expression{Func{T, U}})"/>)
  1568. /// </summary>
  1569. /// <typeparam name="T">The entity type</typeparam>
  1570. /// <typeparam name="U">The entity link type</typeparam>
  1571. /// <param name="arg">The row representing the entity of type <typeparamref name="T"/></param>
  1572. /// <param name="expression">An expression to the entity link of type <typeparamref name="U"/></param>
  1573. /// <returns>The ID on the entity link, or <c>null</c> if the entity link is invalid</returns>
  1574. public static Guid? EntityLinkID<T, U>(this CoreRow arg, Expression<Func<T, U>> expression) where U : IEntityLink
  1575. {
  1576. var col = CoreUtils.GetFullPropertyName(expression, ".");
  1577. var id = arg.Get<Guid>(col + ".ID");
  1578. if (id != Guid.Empty && arg.Get<Guid>(col + ".Deleted") == Guid.Empty)
  1579. return id;
  1580. return null;
  1581. }
  1582. public static Filter<T> LinkValid<T>(this Filter<T> filter, Guid entityID = default)
  1583. {
  1584. var mExp = filter.Expression as MemberExpression;
  1585. if (mExp == null)
  1586. throw new ArgumentException("Filter expression is not a MemberExpression");
  1587. var idExp = Expression.PropertyOrField(mExp, "ID");
  1588. var deletedExp = Expression.PropertyOrField(mExp, "Deleted");
  1589. filter.Expression = idExp;
  1590. if (entityID != Guid.Empty)
  1591. filter.IsEqualTo(entityID);
  1592. else
  1593. filter.IsNotEqualTo(Guid.Empty);
  1594. var delFilter = new Filter<T>();
  1595. delFilter.Expression = deletedExp;
  1596. delFilter.IsEqualTo(Guid.Empty);
  1597. filter.And(delFilter);
  1598. return filter.Parent ?? filter;
  1599. }
  1600. public static Filter<T> NotLinkValid<T>(this Filter<T> filter)
  1601. {
  1602. var mExp = filter.Expression as MemberExpression;
  1603. if (mExp == null)
  1604. throw new ArgumentException("Filter expression is not a MemberExpression");
  1605. filter.All();
  1606. var subFilter = new Filter<T>();
  1607. var idExp = Expression.PropertyOrField(mExp, "ID");
  1608. var deletedExp = Expression.PropertyOrField(mExp, "Deleted");
  1609. subFilter.Expression = idExp;
  1610. subFilter.IsEqualTo(Guid.Empty);
  1611. var delFilter = new Filter<T>();
  1612. delFilter.Expression = deletedExp;
  1613. delFilter.IsNotEqualTo(Guid.Empty);
  1614. subFilter.Or(delFilter);
  1615. filter.And(subFilter);
  1616. return filter.Parent ?? filter;
  1617. }
  1618. #region DeepClone Utility
  1619. //public static object Clone(object from)
  1620. //{
  1621. // if (from == null)
  1622. // throw new ArgumentNullException("Source is null");
  1623. // if (into == null)
  1624. // throw new ArgumentNullException("Target is null");
  1625. // return DoClone(from, null);
  1626. //}
  1627. /// <summary>
  1628. /// Get the deep clone of an object.
  1629. /// </summary>
  1630. /// <typeparam name="T">The type of the obj.</typeparam>
  1631. /// <param name="from">It is the object used to deep clone.</param>
  1632. /// <returns>Return the deep clone.</returns>
  1633. public static T Clone<T>(T from, T into) where T : new()
  1634. {
  1635. if (from == null)
  1636. throw new ArgumentNullException("Source is null");
  1637. return (T)DoClone(from, into);
  1638. }
  1639. private static FieldInfo[] GetFieldInfosIncludingBaseClasses(Type type, BindingFlags bindingFlags)
  1640. {
  1641. var fieldInfos = type.GetFields(bindingFlags);
  1642. // If this class doesn't have a base, don't waste any time
  1643. if (type.BaseType == null ||
  1644. type.BaseType == typeof(object)) return fieldInfos; // Otherwise, collect all types up to the furthest base class
  1645. var currentType = type;
  1646. var fieldComparer = new FieldInfoComparer();
  1647. var fieldInfoList = new HashSet<FieldInfo>(fieldInfos, fieldComparer);
  1648. while (currentType != typeof(object))
  1649. {
  1650. fieldInfos = currentType.GetFields(bindingFlags);
  1651. fieldInfoList.UnionWith(fieldInfos);
  1652. currentType = currentType.BaseType;
  1653. }
  1654. return fieldInfoList.ToArray();
  1655. }
  1656. private class FieldInfoComparer : IEqualityComparer<FieldInfo>
  1657. {
  1658. public bool Equals(FieldInfo x, FieldInfo y)
  1659. {
  1660. return x.DeclaringType == y.DeclaringType && x.Name == y.Name;
  1661. }
  1662. public int GetHashCode(FieldInfo obj)
  1663. {
  1664. return obj.Name.GetHashCode() ^ obj.DeclaringType.GetHashCode();
  1665. }
  1666. }
  1667. /// <summary>
  1668. /// The method implements deep clone using reflection.
  1669. /// </summary>
  1670. /// <param name="from">It is the object used to deep clone.</param>
  1671. /// <returns>Return the deep clone.</returns>
  1672. private static object? DoClone(object from, object? into = null)
  1673. {
  1674. if (from == null) return null;
  1675. if (from is MulticastDelegate)
  1676. return null;
  1677. var type = from.GetType();
  1678. // If the type of object is the value type, we will always get a new object when
  1679. // the original object is assigned to another variable. So if the type of the
  1680. // object is primitive or enum, we just return the object. We will process the
  1681. // struct type subsequently because the struct type may contain the reference
  1682. // fields.
  1683. // If the string variables contain the same chars, they always refer to the same
  1684. // string in the heap. So if the type of the object is string, we also return the
  1685. // object.
  1686. if (type.GetTypeInfo().IsPrimitive || type.GetTypeInfo().IsEnum || type == typeof(string)) return from;
  1687. // If the type of the object is the Array, we use the CreateInstance method to get
  1688. // a new instance of the array. We also process recursively this method in the
  1689. // elements of the original array because the type of the element may be the reference
  1690. // type.
  1691. if (type.IsArray)
  1692. {
  1693. var basename = type.FullName.Replace("[]", string.Empty);
  1694. var typeElement = Type.GetType(basename);
  1695. if (typeElement == null)
  1696. typeElement = FindType(basename);
  1697. var array = (from as Array)!; // not-null because type.IsArray
  1698. var copiedArray = Array.CreateInstance(typeElement, array.Length);
  1699. for (var i = 0; i < array.Length; i++)
  1700. // Get the deep clone of the element in the original array and assign the
  1701. // clone to the new array.
  1702. copiedArray.SetValue(DoClone(array.GetValue(i)), i);
  1703. return copiedArray;
  1704. }
  1705. // If the type of the object is class or struct, it may contain the reference fields,
  1706. // so we use reflection and process recursively this method in the fields of the object
  1707. // to get the deep clone of the object.
  1708. // We use Type.IsValueType method here because there is no way to indicate directly whether
  1709. // the Type is a struct type.
  1710. if (type.GetTypeInfo().IsClass || type.GetTypeInfo().IsValueType)
  1711. {
  1712. var copiedObject = into;
  1713. if (copiedObject == null)
  1714. try
  1715. {
  1716. copiedObject = Activator.CreateInstance(from.GetType());
  1717. }
  1718. catch (Exception e)
  1719. {
  1720. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1721. }
  1722. if (copiedObject != null)
  1723. {
  1724. // Get all FieldInfo.
  1725. var fields = GetFieldInfosIncludingBaseClasses(type.GetTypeInfo(),
  1726. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  1727. foreach (var field in fields.Where(x => !x.IsNotSerialized))
  1728. {
  1729. var fieldValue = field.GetValue(from);
  1730. if (fieldValue != null)
  1731. // Get the deep clone of the field in the original object and assign the
  1732. // clone to the field in the new object.
  1733. field.SetValue(copiedObject, DoClone(fieldValue));
  1734. }
  1735. }
  1736. return copiedObject;
  1737. }
  1738. throw new ArgumentException("The object is unknown type");
  1739. }
  1740. #endregion
  1741. #region DeepCompare Utility
  1742. public static bool CompareObjects(string prefix, object inputObjectA, object inputObjectB, string[] ignorePropertiesList,
  1743. List<Tuple<string, object?, object?>> results)
  1744. {
  1745. var areObjectsEqual = true;
  1746. //check if both objects are not null before starting comparing children
  1747. if (inputObjectA != null && inputObjectB != null)
  1748. {
  1749. //create variables to store object values
  1750. object value1, value2;
  1751. var properties = inputObjectA.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
  1752. //get all public properties of the object using reflection
  1753. foreach (var propertyInfo in properties)
  1754. {
  1755. var name = string.IsNullOrWhiteSpace(prefix) ? propertyInfo.Name : prefix + "." + propertyInfo.Name;
  1756. //if it is not a readable property or if it is a ignorable property
  1757. //ingore it and move on
  1758. if (!propertyInfo.CanRead || ignorePropertiesList.Contains(name))
  1759. continue;
  1760. //get the property values of both the objects
  1761. value1 = propertyInfo.GetValue(inputObjectA, null);
  1762. value2 = propertyInfo.GetValue(inputObjectB, null);
  1763. // if the objects are primitive types such as (integer, string etc)
  1764. //that implement IComparable, we can just directly try and compare the value
  1765. if (IsAssignableFrom(propertyInfo.PropertyType) || IsPrimitiveType(propertyInfo.PropertyType) ||
  1766. IsValueType(propertyInfo.PropertyType))
  1767. {
  1768. //compare the values
  1769. if (!CompareValues(name, value1, value2, results))
  1770. {
  1771. //Console.WriteLine("Property Name {0}", propertyInfo.Name);
  1772. areObjectsEqual = false;
  1773. }
  1774. }
  1775. //if the property is a collection (or something that implements IEnumerable)
  1776. //we have to iterate through all items and compare values
  1777. else if (IsEnumerableType(propertyInfo.PropertyType))
  1778. {
  1779. //Console.WriteLine("Property Name {0}", propertyInfo.Name);
  1780. if (!CompareEnumerations(name, value1, value2, ignorePropertiesList, results))
  1781. areObjectsEqual = false;
  1782. }
  1783. //if it is a class object, call the same function recursively again
  1784. else if (propertyInfo.PropertyType.IsClass)
  1785. {
  1786. if (!CompareObjects(name, propertyInfo.GetValue(inputObjectA, null), propertyInfo.GetValue(inputObjectB, null),
  1787. ignorePropertiesList, results))
  1788. areObjectsEqual = false;
  1789. }
  1790. else
  1791. {
  1792. areObjectsEqual = false;
  1793. }
  1794. }
  1795. }
  1796. else
  1797. {
  1798. areObjectsEqual = false;
  1799. }
  1800. return areObjectsEqual;
  1801. }
  1802. //true if c and the current Type represent the same type, or if the current Type is in the inheritance
  1803. //hierarchy of c, or if the current Type is an interface that c implements,
  1804. //or if c is a generic type parameter and the current Type represents one of the constraints of c. false if none of these conditions are true, or if c is null.
  1805. private static bool IsAssignableFrom(Type type)
  1806. {
  1807. return typeof(IComparable).IsAssignableFrom(type);
  1808. }
  1809. private static bool IsPrimitiveType(Type type)
  1810. {
  1811. return type.IsPrimitive;
  1812. }
  1813. private static bool IsValueType(Type type)
  1814. {
  1815. return type.IsValueType;
  1816. }
  1817. private static bool IsEnumerableType(Type type)
  1818. {
  1819. return typeof(IEnumerable).IsAssignableFrom(type);
  1820. }
  1821. /// <summary>
  1822. /// Compares two values and returns if they are the same.
  1823. /// </summary>
  1824. private static bool CompareValues(string name, object? value1, object? value2, List<Tuple<string, object?, object?>> results)
  1825. {
  1826. var areValuesEqual = true;
  1827. var selfValueComparer = value1 as IComparable;
  1828. // one of the values is null
  1829. if ((value1 == null && value2 != null) || (value1 != null && value2 == null))
  1830. areValuesEqual = false;
  1831. else if (selfValueComparer != null && selfValueComparer.CompareTo(value2) != 0)
  1832. areValuesEqual = false;
  1833. else if (!Equals(value1, value2))
  1834. areValuesEqual = false;
  1835. if (!areValuesEqual)
  1836. results.Add(new Tuple<string, object?, object?>(name, value1, value2));
  1837. return areValuesEqual;
  1838. }
  1839. private static bool CompareEnumerations(string name, object value1, object value2, string[] ignorePropertiesList,
  1840. List<Tuple<string, object?, object?>> results)
  1841. {
  1842. // if one of the values is null, no need to proceed return false;
  1843. if (value1 == null && value2 != null)
  1844. {
  1845. results.Add(new Tuple<string, object?, object?>(string.Format("{0}.Null", name), true, false));
  1846. return false;
  1847. }
  1848. if (value1 != null && value2 == null)
  1849. {
  1850. results.Add(new Tuple<string, object?, object?>(string.Format("{0}.Null", name), false, true));
  1851. return false;
  1852. }
  1853. if (value1 != null && value2 != null)
  1854. {
  1855. IEnumerable<object> enumValue1, enumValue2;
  1856. enumValue1 = ((IEnumerable)value1).Cast<object>();
  1857. enumValue2 = ((IEnumerable)value2).Cast<object>();
  1858. // if the items count are different return false
  1859. if (enumValue1.Count() != enumValue2.Count())
  1860. {
  1861. results.Add(new Tuple<string, object?, object?>(string.Format("{0}.Count", name), enumValue1.Count(), enumValue2.Count()));
  1862. return false;
  1863. }
  1864. // if the count is same, compare individual item
  1865. object enumValue1Item, enumValue2Item;
  1866. Type enumValue1ItemType;
  1867. for (var itemIndex = 0; itemIndex < enumValue1.Count(); itemIndex++)
  1868. {
  1869. enumValue1Item = enumValue1.ElementAt(itemIndex);
  1870. enumValue2Item = enumValue2.ElementAt(itemIndex);
  1871. enumValue1ItemType = enumValue1Item.GetType();
  1872. if (IsAssignableFrom(enumValue1ItemType) || IsPrimitiveType(enumValue1ItemType) || IsValueType(enumValue1ItemType))
  1873. {
  1874. if (!CompareValues(string.Format("{0}[{1}]", name, itemIndex), enumValue1Item, enumValue2Item, results))
  1875. return false;
  1876. }
  1877. else if (!CompareObjects(name, enumValue1Item, enumValue2Item, ignorePropertiesList, results))
  1878. {
  1879. return false;
  1880. }
  1881. }
  1882. }
  1883. return true;
  1884. }
  1885. #endregion
  1886. #region Expression Serialisation
  1887. public static string MemberExpressionToString(MemberExpression mExpression)
  1888. {
  1889. var mOriginal = mExpression;
  1890. var path = "";
  1891. while (true)
  1892. {
  1893. if (mExpression.Expression.NodeType == ExpressionType.MemberAccess)
  1894. {
  1895. var propInfo = mExpression.Expression
  1896. .GetType().GetTypeInfo().GetProperty("Member");
  1897. var propValue = (propInfo.GetValue(mExpression.Expression, null) as PropertyInfo)!;
  1898. path = propValue.Name + "." + path;
  1899. mExpression = (mExpression.Expression as MemberExpression)!;
  1900. }
  1901. else if (mExpression.Expression.NodeType == ExpressionType.Convert)
  1902. {
  1903. mExpression = MemberExpression.PropertyOrField((mExpression.Expression as UnaryExpression)?.Operand as MemberExpression, mExpression.Member.Name);
  1904. }
  1905. else
  1906. {
  1907. break;
  1908. }
  1909. }
  1910. return path + mOriginal.Member.Name;
  1911. }
  1912. private enum SerialisedExpressionType
  1913. {
  1914. Member,
  1915. Index,
  1916. Parameter
  1917. }
  1918. public static void SerialiseExpression(this CoreBinaryWriter writer, Type t, Expression expression, bool includeType)
  1919. {
  1920. if (includeType)
  1921. {
  1922. writer.Write(t.EntityName());
  1923. }
  1924. if (expression.NodeType == ExpressionType.MemberAccess)
  1925. {
  1926. writer.Write((byte)SerialisedExpressionType.Member);
  1927. writer.Write(MemberExpressionToString((expression as MemberExpression)!));
  1928. }
  1929. else if (expression.NodeType == ExpressionType.Index)
  1930. {
  1931. writer.Write((byte)SerialisedExpressionType.Index);
  1932. var iexp = (IndexExpression)expression;
  1933. var sexp = expression.ToString().Split('[');
  1934. writer.Write(sexp[0]); // Member
  1935. writer.Write(sexp[1].Replace("]", "").Replace("\"", "")); // Key
  1936. }
  1937. else
  1938. {
  1939. writer.Write((byte)SerialisedExpressionType.Parameter);
  1940. }
  1941. }
  1942. public static Expression DeserialiseExpression(this CoreBinaryReader reader, Type t)
  1943. {
  1944. var expressionType = (SerialisedExpressionType)reader.ReadByte();
  1945. switch (expressionType)
  1946. {
  1947. case SerialisedExpressionType.Member:
  1948. var member = reader.ReadString();
  1949. return CreateMemberExpression(t, member);
  1950. case SerialisedExpressionType.Index:
  1951. member = reader.ReadString();
  1952. var key = reader.ReadString();
  1953. return CreateIndexExpression(t, member, key);
  1954. case SerialisedExpressionType.Parameter:
  1955. default:
  1956. return Expression.Parameter(t, "x");
  1957. }
  1958. }
  1959. /// <summary>
  1960. /// Deserialise the expression, with type information included in the serialised form.
  1961. /// </summary>
  1962. /// <param name="reader"></param>
  1963. /// <returns></returns>
  1964. public static Expression DeserialiseExpression(this CoreBinaryReader reader)
  1965. {
  1966. var entityName = reader.ReadString();
  1967. var t = GetEntity(entityName);
  1968. return reader.DeserialiseExpression(t);
  1969. }
  1970. public static string ExpressionToString(Type t, Expression expression)
  1971. {
  1972. if (expression.NodeType == ExpressionType.MemberAccess)
  1973. {
  1974. var mexp = (MemberExpression)expression;
  1975. var morg = (MemberExpression)expression;
  1976. var Path = "";
  1977. while (mexp.Expression.NodeType == ExpressionType.MemberAccess)
  1978. {
  1979. var propInfo = mexp.Expression
  1980. .GetType().GetTypeInfo().GetProperty("Member");
  1981. var propValue = propInfo.GetValue(mexp.Expression, null)
  1982. as PropertyInfo;
  1983. Path = propValue.Name + "." + Path;
  1984. mexp = mexp.Expression as MemberExpression;
  1985. }
  1986. return Path + morg.Member.Name;
  1987. }
  1988. else if (expression.NodeType == ExpressionType.Index)
  1989. {
  1990. var iexp = (IndexExpression)expression;
  1991. var sexp = expression.ToString().Split('[');
  1992. return sexp[0];
  1993. }
  1994. return expression.ToString();
  1995. }
  1996. public static string ExpressionToString(Type t, Expression expression, bool includetype)
  1997. {
  1998. var result = new Dictionary<string, string>();
  1999. if (expression.NodeType == ExpressionType.MemberAccess)
  2000. {
  2001. var mexp = (expression as MemberExpression)!;
  2002. result["Member"] = MemberExpressionToString(mexp);
  2003. }
  2004. else if (expression.NodeType == ExpressionType.Index)
  2005. {
  2006. var iexp = (IndexExpression)expression;
  2007. var sexp = expression.ToString().Split('[');
  2008. result["Member"] = sexp[0];
  2009. result["Key"] = sexp[1].Replace("]", "").Replace("\"", "");
  2010. }
  2011. result["Type"] = t.EntityName();
  2012. return JsonConvert.SerializeObject(result);
  2013. //ExpressionSerializer ser = new ExpressionSerializer(new Serialize.Linq.Serializers.JsonSerializer(),new Serialize.Linq.Factories.FactorySettings() { UseRelaxedTypeNames=true } );
  2014. //String result = ser.SerializeText(expression);
  2015. //return result;
  2016. //if (expression.NodeType == ExpressionType.MemberAccess)
  2017. //{
  2018. // MemberExpression memberExpression = expression as MemberExpression;
  2019. // MemberExpression memberExpressionOrg = memberExpression as MemberExpression;
  2020. // string Path = "";
  2021. // while (memberExpression.Expression.NodeType == ExpressionType.MemberAccess)
  2022. // {
  2023. // var propInfo = memberExpression.Expression
  2024. // .GetType().GetTypeInfo().GetProperty("Member");
  2025. // var propValue = propInfo.GetValue(memberExpression.Expression, null)
  2026. // as PropertyInfo;
  2027. // Path = propValue.Name + "." + Path;
  2028. // memberExpression = memberExpression.Expression as MemberExpression;
  2029. // }
  2030. // if (includetype)
  2031. // return t.FullName + " => " + Path + memberExpressionOrg.Member.Name;
  2032. // else
  2033. // return Path + memberExpressionOrg.Member.Name;
  2034. //}
  2035. //else if (expression.NodeType == ExpressionType.Index)
  2036. //{
  2037. // if (includetype)
  2038. // return t.FullName + " => " + expression.ToString();
  2039. // else
  2040. // return expression.ToString();
  2041. //}
  2042. //else
  2043. //{
  2044. // if (includetype)
  2045. // return t.FullName + " => " + expression.ToString();
  2046. // else
  2047. // return expression.ToString();
  2048. //}
  2049. }
  2050. public static Expression StringToExpression(string expression)
  2051. {
  2052. var comps = JsonConvert.DeserializeObject<Dictionary<string, string>>(expression);
  2053. var t = GetEntity(comps["Type"]);
  2054. if (comps.TryGetValue("Key", out var key))
  2055. return CreateIndexExpression(t, comps["Member"], key);
  2056. else if (comps.TryGetValue("Member", out var member))
  2057. return CreateMemberExpression(t, member);
  2058. else
  2059. return Expression.Parameter(t, "x");
  2060. //ExpressionSerializer ser = new ExpressionSerializer(new Serialize.Linq.Serializers.JsonSerializer(), new Serialize.Linq.Factories.FactorySettings() { UseRelaxedTypeNames = true });
  2061. //Expression result = ser.DeserializeText(expression);
  2062. //return result;
  2063. //String[] comps = expression.Split(new String[] { " => " }, StringSplitOptions.None);
  2064. //Type type = comps.Length > 1 ? CoreUtils.GetEntity(comps[0]) : t;
  2065. //return CreateExpression(type, comps[comps.Length - 1]);
  2066. }
  2067. public static Expression<Func<T, object?>> CreateLambdaExpression<T>(string column)
  2068. {
  2069. var parameter = Expression.Parameter(typeof(T), "x");
  2070. var property = CreateMemberExpression(typeof(T), column);
  2071. var converted = Expression.Convert(property, typeof(object));
  2072. //var property = Expression.Convert(Expression.Property(parameter, column),typeof(object));
  2073. return Expression.Lambda<Func<T, object?>>(converted, parameter);
  2074. }
  2075. public static Expression ConvertExpression(Type source, Expression lambda, Type target, Expression anchor)
  2076. {
  2077. var parent = ExpressionToString(target, anchor, false);
  2078. var child = ExpressionToString(source, lambda, false);
  2079. var property = string.Join(".", parent, child);
  2080. return CreateMemberExpression(target, property);
  2081. }
  2082. public static Expression CreateMemberExpression(Type type, string propertyName)
  2083. {
  2084. var param = Expression.Parameter(type, "x");
  2085. Expression body = param;
  2086. foreach (var member in propertyName.Split('.')) body = Expression.PropertyOrField(body, member);
  2087. return (MemberExpression)body;
  2088. }
  2089. public static IndexExpression CreateIndexExpression(Type type, string propertyname, string key)
  2090. {
  2091. var param = Expression.Parameter(type, "x");
  2092. var propmod = propertyname.Replace("x.", "").Replace(".Item", "");
  2093. var bar = Expression.Property(param, propmod);
  2094. var dictionaryType = type.GetProperty(propmod).PropertyType;
  2095. var indexerProp = dictionaryType.GetProperty("Item");
  2096. var dictKeyConstant = Expression.Constant(key);
  2097. var dictAccess = Expression.MakeIndex(bar, indexerProp, new[] { dictKeyConstant });
  2098. return dictAccess;
  2099. //var propertyType = indexerProp.PropertyType;
  2100. //var right = Expression.Constant(Convert.ChangeType("newValue", propertyType));
  2101. //var expression = Expression.MakeBinary(ExpressionType.Equal, dictAccess, right);
  2102. }
  2103. public static MemberExpression ExtractMemberExpression<T>(Expression<Func<T, object?>> expression)
  2104. {
  2105. if(!TryFindMemberExpression(expression.Body, out var me))
  2106. {
  2107. throw new Exception("Expression is not a member expression!");
  2108. }
  2109. return me;
  2110. }
  2111. public static MemberExpression ExtractMemberExpression<T, TValue>(Expression<Func<T, TValue>> expression)
  2112. {
  2113. TryFindMemberExpression(expression.Body, out var me);
  2114. return me;
  2115. }
  2116. public static MemberExpression ExtractMemberExpression(Expression expression)
  2117. {
  2118. TryFindMemberExpression(Expression.Lambda(expression).Body, out var me);
  2119. return me;
  2120. }
  2121. #endregion
  2122. public static string FormatException(Exception err)
  2123. {
  2124. var messages = new List<string>();
  2125. var e2 = err;
  2126. while (e2 != null)
  2127. {
  2128. messages.InsertRange(0, new[] { e2.Message, e2.StackTrace, "============================================" });
  2129. e2 = e2.InnerException;
  2130. }
  2131. return string.Join("\n", messages);
  2132. }
  2133. #region OneToMany Relationships
  2134. public static Type? GetOneToMany(Type TMany, Type TOne)
  2135. {
  2136. var o2m = TMany.GetInterfaces().FirstOrDefault(i =>
  2137. i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IOneToMany<>)
  2138. && i.GenericTypeArguments.Contains(TOne)
  2139. );
  2140. return o2m;
  2141. }
  2142. public static PropertyInfo GetOneToManyProperty(Type TMany, Type TOne)
  2143. {
  2144. return TMany.GetProperties().FirstOrDefault(x =>
  2145. x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink))
  2146. && x.PropertyType.GetInheritedGenericTypeArguments().FirstOrDefault() == TOne
  2147. && !Attribute.IsDefined(x, typeof(ObsoleteAttribute))
  2148. );
  2149. }
  2150. #endregion
  2151. #region ManyToMany Relationships
  2152. public static Type? GetManyToMany(Type TManyToMany, Type TThis)
  2153. {
  2154. var m2m = TManyToMany.GetInterfaces().FirstOrDefault(i =>
  2155. i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>)
  2156. && i.GenericTypeArguments.Contains(TThis)
  2157. );
  2158. return m2m;
  2159. }
  2160. public static Type GetManyToManyOtherType(Type TManyToMany, Type TThis)
  2161. {
  2162. var m2m = TManyToMany.GetInterfaces().FirstOrDefault(i =>
  2163. i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>)
  2164. && i.GenericTypeArguments.Contains(TThis)
  2165. );
  2166. return m2m.GenericTypeArguments.FirstOrDefault(x => x != TThis);
  2167. }
  2168. public static PropertyInfo GetManyToManyThisProperty(Type TManyToMany, Type TThis)
  2169. {
  2170. return TManyToMany.GetProperties().FirstOrDefault(x =>
  2171. x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink))
  2172. && x.PropertyType.GetInheritedGenericTypeArguments().FirstOrDefault() == TThis
  2173. && !Attribute.IsDefined(x, typeof(ObsoleteAttribute))
  2174. );
  2175. }
  2176. public static PropertyInfo GetManyToManyOtherProperty(Type TManyToMany, Type TThis)
  2177. {
  2178. var otherType = GetManyToManyOtherType(TManyToMany, TThis);
  2179. return TManyToMany.GetProperties().FirstOrDefault(x =>
  2180. x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink))
  2181. && x.PropertyType.GetInheritedGenericTypeArguments().FirstOrDefault() == otherType
  2182. && !Attribute.IsDefined(x, typeof(ObsoleteAttribute))
  2183. );
  2184. }
  2185. #endregion
  2186. /// <summary>
  2187. /// Get a dictionary of values representing the current state of an entity
  2188. /// </summary>
  2189. /// <param name="item">The Entity being scanned</param>
  2190. /// <param name="props">The list of properties to scan, or null for all</param>
  2191. /// <returns>A dictionary containing the properties and values for the entity</returns>
  2192. public static Dictionary<string, object?> GetValues(BaseObject item, IEnumerable<IProperty>? props = null)
  2193. {
  2194. var result = new Dictionary<string, object?>();
  2195. props ??= DatabaseSchema.Properties(item.GetType());//.Where(x => !(x.Editor is NullEditor));
  2196. foreach (var prop in props)
  2197. if (prop is CustomProperty)
  2198. try
  2199. {
  2200. result[prop.Name] = item.UserProperties[prop.Name];
  2201. }
  2202. catch (Exception e)
  2203. {
  2204. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2205. }
  2206. else
  2207. try
  2208. {
  2209. object? value;
  2210. var getter = prop.Getter();
  2211. if (getter != null)
  2212. value = getter.Invoke(item);
  2213. else
  2214. value = CoreUtils.GetPropertyValue(item, prop.Name);
  2215. result[prop.Name] = value;
  2216. }
  2217. catch (Exception e)
  2218. {
  2219. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2220. }
  2221. return result;
  2222. }
  2223. /// <summary>
  2224. /// Given a certain entity, merge the changes with the current state of the entity into an updated list
  2225. /// </summary>
  2226. /// <param name="item">Th Entity being updated</param>
  2227. /// <param name="previous">The previous set of changes to this entity</param>
  2228. /// <param name="props">The list of properties to scan, or null for all</param>
  2229. /// <param name="changes">The resulting updated list of changes</param>
  2230. public static void MergeChanges(Dictionary<string, object?> previous, Dictionary<string, object?> current, Dictionary<string, object?> changes)
  2231. {
  2232. foreach (var key in previous.Keys)
  2233. if (previous[key] == null)
  2234. {
  2235. if (current[key] != null)
  2236. changes[key] = current[key];
  2237. }
  2238. else
  2239. {
  2240. if (current[key] == null)
  2241. changes[key] = current[key];
  2242. else if (!object.Equals(previous[key], current[key]))
  2243. changes[key] = current[key];
  2244. }
  2245. }
  2246. public static Dictionary<String, object?> MonitorChanges<T>(T item, Action action, Dictionary<String, object?>? changes = null, IEnumerable<IProperty>? props = null) where T : BaseObject
  2247. {
  2248. var result = changes == null
  2249. ? new Dictionary<String, object?>()
  2250. : changes;
  2251. var previous = GetValues(item, props);
  2252. action.Invoke();
  2253. var current = GetValues(item, props);
  2254. MergeChanges(previous, current, result);
  2255. return result;
  2256. }
  2257. public static string Codify(string? text)
  2258. {
  2259. char[] numbers = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
  2260. if (string.IsNullOrWhiteSpace(text))
  2261. return "??";
  2262. var result = "";
  2263. var comps = text.ToUpper().Split(' ');
  2264. foreach (var comp in comps)
  2265. {
  2266. List<char> chars = new List<char>();
  2267. foreach (char c in comp.ToCharArray())
  2268. {
  2269. chars.Add(c);
  2270. if (!numbers.Contains(c))
  2271. break;
  2272. }
  2273. var comb = new String(chars.ToArray());
  2274. result += comb;
  2275. }
  2276. return string.IsNullOrWhiteSpace(result) ? "??" : result;
  2277. }
  2278. public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
  2279. {
  2280. int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
  2281. return dt.AddDays(-1 * diff).Date;
  2282. }
  2283. }
  2284. }