CoreUtils.cs 110 KB

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