CoreUtils.cs 116 KB

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