CoreUtils.cs 116 KB

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