CoreUtils.cs 107 KB

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