CoreUtils.cs 122 KB

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