CoreUtils.cs 103 KB

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