CoreUtils.cs 112 KB

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