CoreUtils.cs 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913
  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. var elementType = type.GetElementType();
  522. var collection = value as ICollection<object?> ?? objList.ToList();
  523. var arr = Array.CreateInstance(elementType, collection.Count);
  524. var i = 0;
  525. foreach(var val in collection)
  526. {
  527. arr.SetValue(ChangeType(val, elementType), i);
  528. ++i;
  529. }
  530. return arr;
  531. }
  532. }
  533. if (value is byte[] && type == typeof(Guid))
  534. return new Guid(value as byte[]);
  535. if (value is string && type == typeof(Version))
  536. return new Version(value as string);
  537. if (value is byte && type == typeof(TimeSpan))
  538. return new TimeSpan((byte)value);
  539. if (value is string && type == typeof(TimeSpan))
  540. return TimeSpan.Parse(value as string);
  541. if (value is string && type == typeof(DateTime))
  542. return DateTime.Parse(value as string);
  543. if (value is bool && type == typeof(string))
  544. return (bool)value ? bool.TrueString : bool.FalseString;
  545. //if (value is JArray && type == typeof(string[]))
  546. // return (value as JArray).Select(x => x.ToString()).ToArray();
  547. if (value is string && type == typeof(byte[]))
  548. return Convert.FromBase64String(value as string);
  549. if(value is FilterConstant constant)
  550. {
  551. if (type == typeof(DateTime))
  552. {
  553. if (Equals(FilterConstant.Null, value))
  554. return DateTime.MinValue;
  555. return value;
  556. }
  557. if (type == typeof(Guid) && constant == FilterConstant.Null)
  558. {
  559. return Guid.Empty;
  560. }
  561. if (type == typeof(double))
  562. {
  563. return value;
  564. // if (Equals(FilterConstant.Zero, value))
  565. // return (double)0;
  566. }
  567. if (type == typeof(int))
  568. {
  569. return value;
  570. // if (Equals(FilterConstant.Zero, value))
  571. // return 0;
  572. }
  573. }
  574. if (type == typeof(String))
  575. return value?.ToString() ?? string.Empty;
  576. if (!(value is IConvertible))
  577. return value;
  578. return Convert.ChangeType(value, type);
  579. }
  580. [return: MaybeNull]
  581. public static T ChangeType<T>(object? value)
  582. {
  583. var newValue = ChangeType(value, typeof(T));
  584. if (newValue is T tValue)
  585. return tValue;
  586. return default;
  587. }
  588. public static string RandomHexString(int length)
  589. {
  590. var rdm = new Random((int)DateTime.Now.Ticks);
  591. var hexValue = "";
  592. int num;
  593. for (var i = 0; i < length; i++)
  594. {
  595. num = rdm.Next(0, 16);
  596. hexValue += num.ToString("X1");
  597. }
  598. return hexValue;
  599. }
  600. public static bool IsEmpty(this DateTime value)
  601. {
  602. return value.Ticks <= DateTime.MinValue.AddHours(8).Ticks;
  603. }
  604. #region Properties
  605. public static string GetFullPropertyName<Type, TProperty>(Expression<Func<Type, TProperty>> exp, string separator)
  606. {
  607. try
  608. {
  609. if (!TryFindMemberExpression(exp.Body, out var memberExp))
  610. return "";
  611. return GetFullPropertyName(memberExp, separator);
  612. }
  613. catch (Exception e)
  614. {
  615. throw e;
  616. }
  617. }
  618. public static string GetFullPropertyName(MemberExpression exp, string separator)
  619. {
  620. try
  621. {
  622. var currentExpression = exp;
  623. var memberNames = new Stack<string>();
  624. do
  625. {
  626. memberNames.Push(currentExpression.Member.Name);
  627. } while (TryFindMemberExpression(currentExpression.Expression, out currentExpression));
  628. var result = string.Join(separator, memberNames.ToArray());
  629. return result;
  630. }
  631. catch (Exception e)
  632. {
  633. throw e;
  634. }
  635. }
  636. // code adjusted to prevent horizontal overflow
  637. public static bool TryFindMemberExpression(Expression exp, [NotNullWhen(true)] out MemberExpression? memberExp)
  638. {
  639. memberExp = exp as MemberExpression;
  640. if (memberExp != null)
  641. return true;
  642. if (IsConversion(exp) && exp is UnaryExpression unary)
  643. {
  644. memberExp = unary.Operand as MemberExpression;
  645. if (memberExp != null)
  646. return true;
  647. }
  648. return false;
  649. }
  650. public static Expression<Func<T, TType>> GetPropertyExpression<T, TType>(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(TType));
  656. var conversion = body.Type == typeof(TType) ? body : Expression.Convert(body, typeof(TType));
  657. return Expression.Lambda<Func<T, TType>>(conversion, param);
  658. }
  659. public static Expression<Func<T, object?>> GetPropertyExpression<T>(string name)
  660. {
  661. var param = Expression.Parameter(typeof(T), "x");
  662. Expression body = param;
  663. foreach (var member in name.Split('.')) body = Expression.PropertyOrField(body, member);
  664. var p = Expression.Parameter(typeof(object));
  665. var conversion = Expression.Convert(body, typeof(object));
  666. return Expression.Lambda<Func<T, object?>>(conversion, param);
  667. }
  668. public static MemberExpression GetMemberExpression(Type t, string name)
  669. {
  670. var param = Expression.Parameter(t, "x");
  671. Expression body = param;
  672. foreach (var member in name.Split('.'))
  673. body = Expression.PropertyOrField(body, member);
  674. var me = Expression.Lambda(body, param).Body as MemberExpression;
  675. return me;
  676. }
  677. public static Expression GetPropertyExpression(Type t, string name, Type? type = null)
  678. {
  679. var param = Expression.Parameter(t, "x");
  680. Expression body = param;
  681. foreach (var member in name.Split('.')) body = Expression.PropertyOrField(body, member);
  682. if (type != null)
  683. body = Expression.Convert(body, typeof(object));
  684. return Expression.Lambda(body, param);
  685. //var p2 = Expression.Parameter(t, "x");
  686. //Expression e2 = Expression.Lambda(Expression.Property(p2, name), p2);
  687. //return e2;
  688. }
  689. public static PropertyInfo GetProperty(Type t, string name)
  690. {
  691. if (TryGetProperty(t, name, out var info))
  692. return info;
  693. throw new Exception($"Property {name} does not exist for {t.Name}");
  694. }
  695. public static PropertyInfo GetProperty<T>(string name) => GetProperty(typeof(T), name);
  696. public static bool TryGetProperty(Type t, string name, [NotNullWhen(true)] out PropertyInfo? propertyInfo)
  697. {
  698. propertyInfo = null;
  699. var typeinfo = t.GetTypeInfo();
  700. var props = name.Split('.');
  701. foreach (var prop in props)
  702. {
  703. propertyInfo = typeinfo.GetProperty(prop);
  704. if (propertyInfo is null)
  705. return false;
  706. typeinfo = propertyInfo.PropertyType.GetTypeInfo();
  707. }
  708. if (propertyInfo is null)
  709. return false;
  710. return true;
  711. }
  712. public static bool TryGetProperty<T>(string name, [NotNullWhen(true)] out PropertyInfo? propertyInfo) =>
  713. TryGetProperty(typeof(T), name, out propertyInfo);
  714. public static bool HasProperty(Type t, string name)
  715. {
  716. PropertyInfo property;
  717. var typeinfo = t.GetTypeInfo();
  718. var props = name.Split('.');
  719. foreach (var prop in props)
  720. {
  721. property = typeinfo.GetProperty(prop);
  722. if (property == null)
  723. return false;
  724. typeinfo = property.PropertyType.GetTypeInfo();
  725. }
  726. return true;
  727. }
  728. public static object? GetPropertyParent(object o, string name)
  729. {
  730. var comps = name.Split('.').ToList();
  731. comps.Remove(comps.Last());
  732. if (comps.Count == 0)
  733. return o;
  734. return GetPropertyValue(o, string.Join(".", comps));
  735. }
  736. public static TValue GetPropertyValue<T, TValue>(T obj, Expression<Func<T, TValue>> property)
  737. where T : BaseObject
  738. {
  739. var prop = DatabaseSchema.PropertyStrict(property);
  740. return (TValue)prop.Getter()(obj);
  741. }
  742. /// <summary>
  743. /// Gets the value of the object's given property.
  744. /// </summary>
  745. /// <param name="o">The object to get the property from.</param>
  746. /// <param name="name">The name of the property.</param>
  747. /// <returns>
  748. /// <see langword="null"/> if <paramref name="o"/> or any intermediate properties are <see langword="null"/>;
  749. /// otherwise the value of the property <paramref name="name"/>, which can be <see langword="null"/>.
  750. /// </returns>
  751. /// <exception cref="Exception">if the property does not exist.</exception>
  752. public static object? GetPropertyValue(object? o, string name)
  753. {
  754. if (o is null)
  755. return null;
  756. var t = o.GetType().GetTypeInfo();
  757. if (o is BaseObject)
  758. {
  759. var property = DatabaseSchema.Property(t, name);
  760. if (property != null && (property is CustomProperty || !name.Contains(".")))
  761. return property.Getter().Invoke(o);
  762. }
  763. var props = name.Split('.');
  764. foreach (var prop in props)
  765. {
  766. var rprop = t.GetProperty(prop) ?? throw new Exception(string.Format("Property {0} does not exist for {1}", prop, o.GetType().Name));
  767. o = rprop.GetValue(o, null);
  768. if (o is null)
  769. return null;
  770. t = o.GetType().GetTypeInfo();
  771. }
  772. return o;
  773. }
  774. /// <summary>
  775. /// Sets a property on the given object, doing nothing if the property does not exist.
  776. /// </summary>
  777. /// <param name="o">The object to set the property of.</param>
  778. /// <param name="name">The property to set.</param>
  779. /// <param name="value">The value to set the property to.</param>
  780. public static void SetPropertyValue(object o, string name, object? value)
  781. {
  782. var bits = name.Split('.');
  783. for (var i = 0; i < bits.Length - 1; i++)
  784. {
  785. var propertyToGet = o.GetType().GetTypeInfo().GetProperty(bits[i]);
  786. if (propertyToGet == null)
  787. return;
  788. var newo = propertyToGet.GetValue(o, null);
  789. if (newo == null)
  790. {
  791. newo = Activator.CreateInstance(propertyToGet.PropertyType);
  792. propertyToGet.SetValue(o, newo);
  793. }
  794. o = newo;
  795. }
  796. var propertyToSet = o.GetType().GetTypeInfo().GetProperty(bits.Last());
  797. if (propertyToSet is null)
  798. {
  799. var iprop = DatabaseSchema.Property(o.GetType(), name);
  800. if (iprop is CustomProperty)
  801. {
  802. ((BaseObject)o).UserProperties[name] = value;
  803. return;
  804. }
  805. return;
  806. }
  807. //PropertyInfo propertyToSet = GetProperty(o.GetType(), name);
  808. object? convertedvalue = null;
  809. if (value != null)
  810. {
  811. if (propertyToSet.PropertyType.Equals(typeof(Type)))
  812. {
  813. convertedvalue = Type.GetType(value.ToString(), true, true);
  814. }
  815. else if (propertyToSet.PropertyType.GetTypeInfo().IsEnum)
  816. {
  817. convertedvalue = Enum.Parse(propertyToSet.PropertyType, value.ToString(), true);
  818. }
  819. //else if (propertyToSet.PropertyType.Equals(typeof(Memo)))
  820. // convertedvalue = (Memo)value.ToString();
  821. else if (propertyToSet.PropertyType.Equals(typeof(Guid)))
  822. {
  823. var guidvalue = Guid.Empty;
  824. Guid.TryParse(value.ToString(), out guidvalue);
  825. convertedvalue = guidvalue;
  826. }
  827. //else if (propertyToSet.PropertyType.IsSubclassOf(value.GetType()))
  828. // convertedvalue = value;
  829. else if (propertyToSet.PropertyType.IsAssignableFrom(value.GetType()))
  830. {
  831. convertedvalue = value;
  832. }
  833. else if (!(value is DBNull))
  834. {
  835. convertedvalue = Convert.ChangeType(value, propertyToSet.PropertyType);
  836. }
  837. }
  838. if (propertyToSet.CanWrite)
  839. {
  840. var method = propertyToSet.GetSetMethod();
  841. //if (method == null)
  842. var oldval = propertyToSet.GetValue(o);
  843. propertyToSet.SetValue(o, convertedvalue, null);
  844. //else
  845. // method.Invoke(o, new Object[] { convertedvalue });
  846. //if (o.GetType().IsSubclassOf(typeof(BaseObject)))
  847. // ((BaseObject)o).OnPropertyChanged(name, propertyToSet.GetValue(o), convertedvalue);
  848. }
  849. }
  850. public static IEnumerable<PropertyInfo> GetInheritedProperties(Type type)
  851. {
  852. if (type.IsInterface)
  853. {
  854. var propertyInfos = new List<PropertyInfo>();
  855. var considered = new List<Type>();
  856. var queue = new Queue<Type>();
  857. considered.Add(type);
  858. queue.Enqueue(type);
  859. while (queue.Count > 0)
  860. {
  861. var subType = queue.Dequeue();
  862. foreach (var subInterface in subType.GetInterfaces())
  863. {
  864. if (considered.Contains(subInterface)) continue;
  865. considered.Add(subInterface);
  866. queue.Enqueue(subInterface);
  867. }
  868. var typeProperties = subType.GetProperties(
  869. BindingFlags.FlattenHierarchy
  870. | BindingFlags.Public
  871. | BindingFlags.Instance);
  872. var newPropertyInfos = typeProperties
  873. .Where(x => !propertyInfos.Contains(x));
  874. propertyInfos.InsertRange(0, newPropertyInfos);
  875. }
  876. return propertyInfos;
  877. }
  878. return type.GetProperties(BindingFlags.FlattenHierarchy
  879. | BindingFlags.Public | BindingFlags.Instance);
  880. }
  881. public static Dictionary<string, Type> PropertyList(Type T, Func<PropertyInfo, bool> Predicate, bool Recursive)
  882. {
  883. Dictionary<string, Type> properties;
  884. if (T.GetTypeInfo().BaseType != null)
  885. properties = PropertyList(T.GetTypeInfo().BaseType, Predicate, Recursive);
  886. else
  887. properties = new Dictionary<string, Type>();
  888. //TypeInfo entitytype = typeof(Entity).GetTypeInfo();
  889. //TypeInfo componenttype = typeof(EnclosedEntity).GetTypeInfo();
  890. foreach (var prop in T.GetRuntimeProperties())
  891. // '.' contains check for explicit implementation of interface properties
  892. if (!properties.ContainsKey(prop.Name) && Predicate(prop) && !prop.Name.Contains('.'))
  893. {
  894. var propertytype = prop.PropertyType.GetTypeInfo();
  895. if (
  896. Recursive &&
  897. (
  898. propertytype.IsSubclassOf(typeof(Entity)) ||
  899. propertytype.GetInterfaces().Contains(typeof(IEnclosedEntity)) ||
  900. propertytype.GetInterfaces().Contains(typeof(IEntityLink))
  901. )
  902. )
  903. {
  904. var props = PropertyList(prop.PropertyType, Predicate, Recursive);
  905. foreach (var key in props.Keys) properties[string.Format("{0}.{1}", prop.Name, key)] = props[key];
  906. }
  907. else
  908. {
  909. properties[prop.Name] = prop.PropertyType;
  910. }
  911. }
  912. return properties;
  913. }
  914. public static Dictionary<string, PropertyInfo> PropertyInfoList(Type T, Func<PropertyInfo, bool> Predicate, bool Recursive)
  915. {
  916. Dictionary<string, PropertyInfo> properties;
  917. if (T.GetTypeInfo().BaseType != null)
  918. properties = PropertyInfoList(T.GetTypeInfo().BaseType, Predicate, Recursive);
  919. else
  920. properties = new Dictionary<string, PropertyInfo>();
  921. //TypeInfo entitytype = typeof(Entity).GetTypeInfo();
  922. //TypeInfo componenttype = typeof(EnclosedEntity).GetTypeInfo();
  923. foreach (var prop in T.GetRuntimeProperties())
  924. // '.' contains check for explicit implementation of interface properties
  925. if (!properties.ContainsKey(prop.Name) && Predicate(prop) && !prop.Name.Contains('.'))
  926. {
  927. var propertytype = prop.PropertyType.GetTypeInfo();
  928. if (
  929. Recursive &&
  930. (
  931. propertytype.IsSubclassOf(typeof(Entity)) ||
  932. propertytype.GetInterfaces().Contains(typeof(IEnclosedEntity)) ||
  933. propertytype.GetInterfaces().Contains(typeof(IEntityLink))
  934. )
  935. )
  936. {
  937. var props = PropertyInfoList(prop.PropertyType, Predicate, Recursive);
  938. foreach (var key in props.Keys) properties[string.Format("{0}.{1}", prop.Name, key)] = props[key];
  939. }
  940. else
  941. {
  942. properties[prop.Name] = prop;
  943. }
  944. }
  945. return properties;
  946. }
  947. public static IEnumerable<PropertyInfo> PropertyList(Type T, Func<PropertyInfo, bool> Predicate)
  948. {
  949. return (T.IsInterface ? GetInheritedProperties(T) : T.GetRuntimeProperties()).Where(x => Predicate(x));
  950. }
  951. private static PropertyInfo InternalGetPropertyFromExpression<TObject, TType>(Expression<Func<TObject, TType>> GetPropertyLambda)
  952. {
  953. MemberExpression Exp;
  954. //this line is necessary, because sometimes the expression comes in as Convert(originalexpression)
  955. if (GetPropertyLambda.Body is UnaryExpression unary)
  956. {
  957. Exp = unary.Operand as MemberExpression ?? throw new ArgumentException();
  958. }
  959. else if (GetPropertyLambda.Body is MemberExpression)
  960. {
  961. Exp = (MemberExpression)GetPropertyLambda.Body;
  962. }
  963. else
  964. {
  965. throw new ArgumentException();
  966. }
  967. return (PropertyInfo)Exp.Member;
  968. }
  969. public static PropertyInfo GetPropertyFromExpression<TObject, TStruct>(Expression<Func<TObject, TStruct>> lambda)
  970. {
  971. return InternalGetPropertyFromExpression(lambda);
  972. }
  973. public static PropertyInfo GetPropertyFromExpression<T>(Expression<Func<T, object>> GetPropertyLambda)
  974. {
  975. MemberExpression Exp;
  976. //this line is necessary, because sometimes the expression comes in as Convert(originalexpression)
  977. if (GetPropertyLambda.Body is UnaryExpression)
  978. {
  979. var UnExp = (UnaryExpression)GetPropertyLambda.Body;
  980. if (UnExp.Operand is MemberExpression)
  981. Exp = (MemberExpression)UnExp.Operand;
  982. else
  983. throw new ArgumentException();
  984. }
  985. else if (GetPropertyLambda.Body is MemberExpression)
  986. {
  987. Exp = (MemberExpression)GetPropertyLambda.Body;
  988. }
  989. else
  990. {
  991. throw new ArgumentException();
  992. }
  993. return (PropertyInfo)Exp.Member;
  994. }
  995. #endregion
  996. public static bool IsCollection(PropertyInfo prop)
  997. {
  998. if (!typeof(string).Equals(prop.PropertyType))
  999. if (typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(prop.PropertyType))
  1000. if (!prop.PropertyType.IsArray)
  1001. if (prop.PropertyType.GenericTypeArguments[0].GetTypeInfo().IsSubclassOf(typeof(Entity)))
  1002. return true;
  1003. return false;
  1004. }
  1005. private static bool IsConversion(Expression exp)
  1006. {
  1007. return exp.NodeType == ExpressionType.Convert ||
  1008. exp.NodeType == ExpressionType.ConvertChecked;
  1009. }
  1010. //public static Dictionary<String, Type> PropertyList(Type T, bool Public = true, bool Static = false)
  1011. //{
  1012. // Dictionary<String, Type> properties = new Dictionary<String, Type>();
  1013. // foreach (PropertyInfo prop in T.GetRuntimeProperties())
  1014. // {
  1015. // if ((prop.GetMethod.IsPublic == Public) && (prop.GetMethod.IsStatic == Static))
  1016. // {
  1017. // if (prop.PropertyType.GetTypeInfo().IsAssignableFrom(typeof(Entity).GetTypeInfo()))
  1018. // {
  1019. // Dictionary<String, Type> props = PropertyList(prop.PropertyType);
  1020. // foreach (String key in props.Keys)
  1021. // {
  1022. // properties[String.Format("{0}.{1}", prop.Name, key)] = props[key];
  1023. // }
  1024. // }
  1025. // else if (!prop.PropertyType.Equals(typeof(Guid)))
  1026. // {
  1027. // properties[prop.Name] = prop.GetType();
  1028. // }
  1029. // }
  1030. // }
  1031. // return properties;
  1032. //}
  1033. /// <summary>
  1034. /// Get all the child properties of an object that match a given type
  1035. /// </summary>
  1036. /// <typeparam name="T">The class of property to search for</typeparam>
  1037. /// <param name="parent">The object to search</param>
  1038. /// <returns>A list of the objects found</returns>
  1039. public static IEnumerable<PropertyInfo> GetChildrenProperties<T>(Type parentType)
  1040. {
  1041. return PropertyList(
  1042. parentType,
  1043. x => typeof(T).IsAssignableFrom(x.PropertyType)
  1044. );
  1045. }
  1046. /// <summary>
  1047. /// Get all the child properties of an object that match a given type
  1048. /// </summary>
  1049. /// <typeparam name="T">The class of property to search for</typeparam>
  1050. /// <param name="parent">The object to search</param>
  1051. /// <returns>A list of the objects found</returns>
  1052. public static IEnumerable<T> GetChildren<T>(object parent)
  1053. {
  1054. var props = PropertyList(
  1055. parent.GetType(),
  1056. x => typeof(T).IsAssignableFrom(x.PropertyType)
  1057. );
  1058. foreach (var prop in props)
  1059. {
  1060. var child = (T)prop.GetValue(parent);
  1061. if (child != null)
  1062. yield return child;
  1063. }
  1064. }
  1065. /// <summary>
  1066. /// Get all list properties of an object that are collections of a given type
  1067. /// </summary>
  1068. /// <typeparam name="T">The class of child object to search for</typeparam>
  1069. /// <param name="parent">The object to search</param>
  1070. /// <returns>A list of the collections found</returns>
  1071. public static IEnumerable<TType>[] GetCollectionsOfType<TType>(object parent)
  1072. {
  1073. var lists = new List<IEnumerable<TType>>();
  1074. var props = PropertyList(parent.GetType(), x => true); // !typeof(String).Equals(x.PropertyType));
  1075. foreach (var prop in props)
  1076. if (typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(prop.PropertyType))
  1077. if (prop.PropertyType.GenericTypeArguments.Length == 1)
  1078. if (prop.PropertyType.GenericTypeArguments[0].GetTypeInfo().GetInterfaces().Contains(typeof(TType)))
  1079. lists.Add((IEnumerable<TType>)prop.GetValue(parent));
  1080. return lists.ToArray();
  1081. }
  1082. /// <summary>
  1083. /// [ <c>public static object GetDefault(this Type type)</c> ]
  1084. /// <para></para>
  1085. /// Retrieves the default value for a given Type
  1086. /// </summary>
  1087. /// <param name="type">The Type for which to get the default value</param>
  1088. /// <returns>The default value for <paramref name="type" /></returns>
  1089. /// <remarks>
  1090. /// If a null Type, a reference Type, or a System.Void Type is supplied, this method always returns null. If a value
  1091. /// type
  1092. /// is supplied which is not publicly visible or which contains generic parameters, this method will fail with an
  1093. /// exception.
  1094. /// </remarks>
  1095. /// <example>
  1096. /// To use this method in its native, non-extension form, make a call like:
  1097. /// <code>
  1098. /// object Default = DefaultValue.GetDefault(someType);
  1099. /// </code>
  1100. /// To use this method in its Type-extension form, make a call like:
  1101. /// <code>
  1102. /// object Default = someType.GetDefault();
  1103. /// </code>
  1104. /// </example>
  1105. /// <seealso cref="GetDefault&lt;T&gt;" />
  1106. public static object? GetDefault(this Type type)
  1107. {
  1108. // If no Type was supplied, if the Type was a reference type, or if the Type was a System.Void, return null
  1109. if (type == null || !type.GetTypeInfo().IsValueType || type == typeof(void))
  1110. return null;
  1111. // If the supplied Type has generic parameters, its default value cannot be determined
  1112. if (type.GetTypeInfo().ContainsGenericParameters)
  1113. throw new ArgumentException(
  1114. "Error:\n\nThe supplied value type <" + type.Name +
  1115. "> contains generic parameters, so the default value cannot be retrieved\n\n");
  1116. // If the Type is a primitive type, or if it is another publicly-visible value type (i.e. struct/enum), return a
  1117. // default instance of the value type
  1118. if (type.GetTypeInfo().IsPrimitive || !type.GetTypeInfo().IsNotPublic)
  1119. try
  1120. {
  1121. return Activator.CreateInstance(type);
  1122. }
  1123. catch (Exception e)
  1124. {
  1125. throw new ArgumentException(
  1126. "Error:\n\nThe Activator.CreateInstance method could not " +
  1127. "create a default instance of the supplied value type <" + type.Name +
  1128. "> (Inner Exception message: \"" + e.Message + "\")");
  1129. }
  1130. // Fail with exception
  1131. throw new ArgumentException("Error:\n\nThe supplied value type <" + type +
  1132. "> is not a publicly-visible type, so the default value cannot be retrieved");
  1133. }
  1134. /// <summary>
  1135. /// [ <c>public static T GetDefault&lt; T &gt;()</c> ]
  1136. /// <para></para>
  1137. /// Retrieves the default value for a given Type
  1138. /// </summary>
  1139. /// <typeparam name="T">The Type for which to get the default value</typeparam>
  1140. /// <returns>The default value for Type T</returns>
  1141. /// <remarks>
  1142. /// If a reference Type or a System.Void Type is supplied, this method always returns null. If a value type
  1143. /// is supplied which is not publicly visible or which contains generic parameters, this method will fail with an
  1144. /// exception.
  1145. /// </remarks>
  1146. /// <seealso cref="GetDefault(Type)" />
  1147. [return: MaybeNull]
  1148. public static T GetDefault<T>()
  1149. {
  1150. return (T)GetDefault(typeof(T));
  1151. }
  1152. public static bool IsDefault<T>(T value)
  1153. {
  1154. return IsDefault(typeof(T), value);
  1155. }
  1156. /// <summary>
  1157. /// [ <c>public static bool IsObjectSetToDefault(this Type ObjectType, object ObjectValue)</c> ]
  1158. /// <para></para>
  1159. /// Reports whether a value of type T (or a null reference of type T) contains the default value for that Type
  1160. /// </summary>
  1161. /// <remarks>
  1162. /// Reports whether the object is empty or unitialized for a reference type or nullable value type (i.e. is null) or
  1163. /// whether the object contains a default value for a non-nullable value type (i.e. int = 0, bool = false, etc.)
  1164. /// <para></para>
  1165. /// NOTE: For non-nullable value types, this method introduces a boxing/unboxing performance penalty.
  1166. /// </remarks>
  1167. /// <param name="ObjectType">Type of the object to test</param>
  1168. /// <param name="ObjectValue">The object value to test, or null for a reference Type or nullable value Type</param>
  1169. /// <returns>
  1170. /// true = The object contains the default value for its Type.
  1171. /// <para></para>
  1172. /// false = The object has been changed from its default value.
  1173. /// </returns>
  1174. public static bool IsDefault(this Type ObjectType, object? ObjectValue)
  1175. {
  1176. // If no ObjectType was supplied, attempt to determine from ObjectValue
  1177. if (ObjectType == null)
  1178. {
  1179. // If no ObjectValue was supplied, abort
  1180. if (ObjectValue == null) throw new ArgumentNullException("Error:\n\nCannot determine the ObjectType from a null Value");
  1181. // Determine ObjectType from ObjectValue
  1182. ObjectType = ObjectValue.GetType();
  1183. }
  1184. // Get the default value of type ObjectType
  1185. var Default = ObjectType.GetDefault();
  1186. // If a non-null ObjectValue was supplied, compare Value with its default value and return the result
  1187. if (ObjectValue != null)
  1188. return ObjectValue.Equals(Default);
  1189. // Since a null ObjectValue was supplied, report whether its default value is null
  1190. return Default == null;
  1191. }
  1192. //public static TimeSpan Round(this TimeSpan timespan, TimeSpan interval)
  1193. //{
  1194. // // The round number, here is a quarter... in seconds
  1195. // double Round = interval.TotalSeconds;
  1196. // // Count of round number in this total Seconds...
  1197. // double CountRound = (timespan.TotalSeconds / Round);
  1198. // // The main formula to calculate round time...
  1199. // int Sec = (int)(Math.Truncate(CountRound + 0.5) * Round);
  1200. // // Now show the result...
  1201. // TimeSpan tRes = new TimeSpan(0, 0, Sec);
  1202. // return tRes;
  1203. //}
  1204. public static bool IsNumeric(this Type dataType)
  1205. {
  1206. return dataType.IsFloatingPoint() || dataType.IsOrdinal();
  1207. }
  1208. public static bool IsFloatingPoint(this Type dataType)
  1209. {
  1210. if (dataType == null)
  1211. return false;
  1212. return dataType == typeof(double)
  1213. || dataType == typeof(float)
  1214. || dataType == typeof(float);
  1215. }
  1216. public static bool IsOrdinal(this Type dataType)
  1217. {
  1218. if (dataType == null)
  1219. return false;
  1220. return dataType == typeof(int)
  1221. || dataType == typeof(long)
  1222. || dataType == typeof(short)
  1223. || dataType == typeof(short)
  1224. || dataType == typeof(int)
  1225. || dataType == typeof(long)
  1226. || dataType == typeof(uint)
  1227. || dataType == typeof(ushort)
  1228. || dataType == typeof(uint)
  1229. || dataType == typeof(ulong)
  1230. || dataType == typeof(sbyte);
  1231. }
  1232. //Extension method for MailMessage to save to a file on disk
  1233. public static string GenerateEMLFile(this MailMessage message, bool addUnsentHeader = true)
  1234. {
  1235. var filename = Path.ChangeExtension(Path.GetTempFileName(), ".eml");
  1236. using (var filestream = File.Open(filename, FileMode.Create))
  1237. {
  1238. if (addUnsentHeader)
  1239. {
  1240. var binaryWriter = new BinaryWriter(filestream);
  1241. //Write the Unsent header to the file so the mail client knows this mail must be presented in "New message" mode
  1242. binaryWriter.Write(Encoding.UTF8.GetBytes("X-Unsent: 1" + Environment.NewLine));
  1243. }
  1244. var assembly = typeof(SmtpClient).Assembly;
  1245. var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
  1246. // Get reflection info for MailWriter contructor
  1247. var mailWriterContructor =
  1248. mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
  1249. // Construct MailWriter object with our FileStream
  1250. var mailWriter = mailWriterContructor.Invoke(new object[] { filestream });
  1251. // Get reflection info for Send() method on MailMessage
  1252. var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
  1253. sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null);
  1254. // Finally get reflection info for Close() method on our MailWriter
  1255. var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);
  1256. // Call close method
  1257. closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
  1258. }
  1259. return filename;
  1260. }
  1261. public static Columns<T> GetColumns<T>(Columns<T>? columns)
  1262. => (GetColumns(typeof(T), columns) as Columns<T>)!;
  1263. /// <summary>
  1264. /// Ensures that <paramref name="columns"/> is not <see langword="null"/>, by setting it to <b>all</b> columns that are
  1265. /// writable, serializable and persistable if it is.<br/>
  1266. /// If <paramref name="columns"/> is not <see langword="null"/>, it is returned unchanged.
  1267. /// </summary>
  1268. public static IColumns GetColumns(Type T, IColumns? columns)
  1269. {
  1270. if (columns == null || columns.Count == 0)
  1271. {
  1272. if (!_columnscache.TryGetValue(T, out var result))
  1273. {
  1274. result = Columns.None(T);
  1275. foreach(var prop in DatabaseSchema.Properties(T))
  1276. {
  1277. if (prop is StandardProperty stdProp
  1278. && (!stdProp.IsPersistable || !stdProp.IsSerializable || !stdProp.Property.CanWrite))
  1279. continue;
  1280. result.Add(prop);
  1281. }
  1282. _columnscache[T] = result;
  1283. }
  1284. return result;
  1285. }
  1286. return columns;
  1287. }
  1288. /// <summary>
  1289. /// Return a list of the names of the columns of <paramref name="T"/> which are serializable, persistable and writable (i.e., a
  1290. /// <see langword="null"/> set of columns), <i>and</i> that match the <paramref name="Predicate"/>.
  1291. /// </summary>
  1292. /// <param name="T"></param>
  1293. /// <param name="Predicate"></param>
  1294. /// <returns></returns>
  1295. public static List<string> GetColumnNames(Type T, Func<IProperty, bool> predicate)
  1296. {
  1297. var result = new List<string>();
  1298. foreach(var prop in DatabaseSchema.Properties(T))
  1299. {
  1300. if ((prop is StandardProperty stdProp && (!stdProp.IsPersistable || !stdProp.IsSerializable || !stdProp.Property.CanWrite))
  1301. || !predicate(prop))
  1302. continue;
  1303. result.Add(prop.Name);
  1304. }
  1305. return result;
  1306. }
  1307. public static string TypedValueToString(object value)
  1308. {
  1309. var type = value.GetType();
  1310. var Culture = CultureInfo.CurrentCulture;
  1311. if (type == typeof(string))
  1312. return (string)value;
  1313. if (type == typeof(string[]))
  1314. return Serialization.Serialize(value);
  1315. if (IsNumeric(type))
  1316. return string.Format(Culture.NumberFormat, "{0}", value);
  1317. // TimeSpan - use constant pattern
  1318. if (type == typeof(TimeSpan))
  1319. return string.Format("{0:c}", value);
  1320. // DateTime - use round-trip pattern
  1321. if (type == typeof(DateTime))
  1322. return string.Format("{0:o}", value);
  1323. if (type == typeof(Guid))
  1324. return ((Guid)value).ToString();
  1325. var converter = TypeDescriptor.GetConverter(type);
  1326. if (converter != null && converter.CanConvertTo(typeof(string)))
  1327. return converter.ConvertToString(value);
  1328. throw new Exception(string.Format("Cannot Convert {0} to String", type.Name));
  1329. }
  1330. public static object? StringToTypedValue(string value, Type type)
  1331. {
  1332. var Culture = CultureInfo.CurrentCulture;
  1333. if (type == typeof(object) && string.IsNullOrEmpty(value))
  1334. return null;
  1335. if (type == typeof(string))
  1336. return value;
  1337. if (type == typeof(string[]))
  1338. return Serialization.Deserialize<string[]>(value);
  1339. if (type == typeof(sbyte))
  1340. return sbyte.Parse(value, NumberStyles.Integer, Culture);
  1341. if (type == typeof(byte))
  1342. return byte.Parse(value, NumberStyles.Integer, Culture);
  1343. if (type == typeof(ushort))
  1344. return ushort.Parse(value, NumberStyles.Integer, Culture);
  1345. if (type == typeof(uint))
  1346. return uint.Parse(value, NumberStyles.Integer, Culture);
  1347. if (type == typeof(ulong))
  1348. return ulong.Parse(value, NumberStyles.Integer, Culture);
  1349. if (type == typeof(short))
  1350. return short.Parse(value, NumberStyles.Integer, Culture);
  1351. if (type == typeof(int))
  1352. return int.Parse(value, NumberStyles.Integer, Culture);
  1353. if (type == typeof(long))
  1354. return long.Parse(value, NumberStyles.Integer, Culture);
  1355. if (type == typeof(float))
  1356. return float.Parse(value, NumberStyles.Any, Culture);
  1357. if (type == typeof(double))
  1358. return double.Parse(value, NumberStyles.Any, Culture);
  1359. if (type == typeof(decimal))
  1360. return decimal.Parse(value, NumberStyles.Any, Culture);
  1361. if (type == typeof(TimeSpan))
  1362. return TimeSpan.ParseExact(value, "c", null);
  1363. if (type == typeof(DateTime))
  1364. return DateTime.ParseExact(value, "o", null);
  1365. if (type == typeof(Guid))
  1366. return Guid.Parse(value);
  1367. var converter = TypeDescriptor.GetConverter(type);
  1368. if (converter != null && converter.CanConvertFrom(typeof(string)))
  1369. return converter.ConvertFromString(value);
  1370. throw new Exception(string.Format("Cannot Convert String to {0}", type.Name));
  1371. }
  1372. public static bool ContainsInheritedGenericType(this Type type, Type generic)
  1373. {
  1374. if (type == null)
  1375. return false;
  1376. if (type.GenericTypeArguments.Contains(generic))
  1377. return true;
  1378. if (type.BaseType == null)
  1379. return false;
  1380. return type.BaseType.ContainsInheritedGenericType(generic);
  1381. }
  1382. public static IEnumerable<Type> GetInheritedGenericTypeArguments(this Type type)
  1383. {
  1384. if (type == null)
  1385. return new Type[] { };
  1386. if (type.GetGenericArguments().Any())
  1387. return type.GenericTypeArguments;
  1388. if (type.BaseType == null)
  1389. return new Type[] { };
  1390. return type.BaseType.GetInheritedGenericTypeArguments();
  1391. }
  1392. //static readonly Regex StripQuotes = new Regex(@"&quot;", RegexOptions.Compiled);
  1393. public static string GetCaption(this Type type, bool usedefault = true)
  1394. {
  1395. var attribute = type.GetCustomAttribute<Caption>();
  1396. var result = attribute != null
  1397. ? attribute.Text
  1398. : usedefault
  1399. ? type.Name
  1400. : "";
  1401. return result;
  1402. }
  1403. public static string? GetCaptionOrNull(this Type type, bool inherit = false)
  1404. {
  1405. return type.GetCustomAttribute<Caption>(inherit)?.Text;
  1406. }
  1407. public static string SanitiseFileName(string filename)
  1408. {
  1409. var invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
  1410. var invalidReStr = string.Format(@"[{0}]+", invalidChars);
  1411. var reservedWords = new[]
  1412. {
  1413. "CON", "PRN", "AUX", "CLOCK$", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4",
  1414. "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4",
  1415. "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
  1416. };
  1417. var sanitisedNamePart = Regex.Replace(filename, invalidReStr, "_");
  1418. foreach (var reservedWord in reservedWords)
  1419. {
  1420. var reservedWordPattern = string.Format("^{0}\\.", reservedWord);
  1421. sanitisedNamePart = Regex.Replace(sanitisedNamePart, reservedWordPattern, "_reservedWord_.", RegexOptions.IgnoreCase);
  1422. }
  1423. return sanitisedNamePart;
  1424. }
  1425. public static decimal GetPropertySequence(Type type, string column)
  1426. {
  1427. return DatabaseSchema.Property(type, column)?.PropertySequence() ?? 999;
  1428. }
  1429. /// <summary>
  1430. /// Gets the AppData folder for this application.
  1431. /// </summary>
  1432. /// <returns>The path of the AppData folder.</returns>
  1433. public static string GetPath()
  1434. {
  1435. if (Assembly.GetEntryAssembly() != null)
  1436. return Path.Combine(
  1437. Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
  1438. Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)
  1439. );
  1440. return Path.Combine(
  1441. Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
  1442. Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location)
  1443. );
  1444. }
  1445. public static string GetCommonAppData(string? folderName = null)
  1446. {
  1447. folderName ??= Assembly.GetEntryAssembly() != null
  1448. ? Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)
  1449. : Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location);
  1450. return Path.Combine(
  1451. Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
  1452. folderName
  1453. );
  1454. }
  1455. public static string GetVersion()
  1456. {
  1457. // 2022-10-13 FVB First look in the executable directory
  1458. var curfile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "version.txt");
  1459. if (File.Exists(curfile))
  1460. return File.ReadAllText(curfile);
  1461. // Then look in the app data directory if you cannot find it
  1462. curfile = Path.Combine(GetPath(), "version.txt");
  1463. if (File.Exists(curfile))
  1464. return File.ReadAllText(curfile);
  1465. return "???";
  1466. }
  1467. public static string GetLogFile()
  1468. {
  1469. return Path.Combine(GetPath(), string.Format("{0:yyyy-MM-dd}.log", DateTime.Today));
  1470. }
  1471. public static string SplitCamelCase(this string value)
  1472. {
  1473. return string.Join(" ", Regex.Split(value, @"(?<!^)(?=[A-Z](?![A-Z]|$))")).Replace(" ", " ");
  1474. }
  1475. public static bool IsEffectivelyEqual(this double a, double b, double threshold = 0.00001F)
  1476. {
  1477. return Math.Abs(a - b) < threshold;
  1478. }
  1479. public static bool IsEffectivelyGreaterThan(this double a, double b, double threshold = 0.00001F)
  1480. {
  1481. return a - b > threshold;
  1482. }
  1483. public static bool IsEffectivelyLessThan(this double a, double b, double threshold = 0.00001F)
  1484. {
  1485. return b - a > threshold;
  1486. }
  1487. public static bool IsEntityLinkValid<T, U>(this CoreRow arg, Expression<Func<T, U>> expression) where U : IEntityLink
  1488. {
  1489. var col = CoreUtils.GetFullPropertyName(expression, ".");
  1490. return arg.Get<Guid>(col + ".ID") != Guid.Empty && arg.Get<Guid>(col + ".Deleted") == Guid.Empty;
  1491. }
  1492. /// <summary>
  1493. /// 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}})"/>)
  1494. /// </summary>
  1495. /// <typeparam name="T">The entity type</typeparam>
  1496. /// <typeparam name="U">The entity link type</typeparam>
  1497. /// <param name="arg">The row representing the entity of type <typeparamref name="T"/></param>
  1498. /// <param name="expression">An expression to the entity link of type <typeparamref name="U"/></param>
  1499. /// <returns>The ID on the entity link, or <c>null</c> if the entity link is invalid</returns>
  1500. public static Guid? EntityLinkID<T, U>(this CoreRow arg, Expression<Func<T, U>> expression) where U : IEntityLink
  1501. {
  1502. var col = CoreUtils.GetFullPropertyName(expression, ".");
  1503. var id = arg.Get<Guid>(col + ".ID");
  1504. if (id != Guid.Empty && arg.Get<Guid>(col + ".Deleted") == Guid.Empty)
  1505. return id;
  1506. return null;
  1507. }
  1508. public static Filter<T> LinkValid<T>(this Filter<T> filter, Guid entityID = default)
  1509. {
  1510. filter.Property = filter.Property + ".ID";
  1511. if (entityID != Guid.Empty)
  1512. filter.IsEqualTo(entityID);
  1513. else
  1514. filter.IsNotEqualTo(Guid.Empty);
  1515. return filter.Parent ?? filter;
  1516. }
  1517. public static Filter<T> NotLinkValid<T>(this Filter<T> filter)
  1518. {
  1519. filter.All();
  1520. var subFilter = new Filter<T>();
  1521. subFilter.Property = filter.Property + ".ID";
  1522. subFilter.IsEqualTo(Guid.Empty);
  1523. filter.And(subFilter);
  1524. return filter.Parent ?? filter;
  1525. }
  1526. #region DeepClone Utility
  1527. //public static object Clone(object from)
  1528. //{
  1529. // if (from == null)
  1530. // throw new ArgumentNullException("Source is null");
  1531. // if (into == null)
  1532. // throw new ArgumentNullException("Target is null");
  1533. // return DoClone(from, null);
  1534. //}
  1535. /// <summary>
  1536. /// Get the deep clone of an object.
  1537. /// </summary>
  1538. /// <typeparam name="T">The type of the obj.</typeparam>
  1539. /// <param name="from">It is the object used to deep clone.</param>
  1540. /// <returns>Return the deep clone.</returns>
  1541. public static T Clone<T>(T from, T into) where T : new()
  1542. {
  1543. if (from == null)
  1544. throw new ArgumentNullException("Source is null");
  1545. return (T)DoClone(from, into);
  1546. }
  1547. private static FieldInfo[] GetFieldInfosIncludingBaseClasses(Type type, BindingFlags bindingFlags)
  1548. {
  1549. var fieldInfos = type.GetFields(bindingFlags);
  1550. // If this class doesn't have a base, don't waste any time
  1551. if (type.BaseType == null ||
  1552. type.BaseType == typeof(object)) return fieldInfos; // Otherwise, collect all types up to the furthest base class
  1553. var currentType = type;
  1554. var fieldComparer = new FieldInfoComparer();
  1555. var fieldInfoList = new HashSet<FieldInfo>(fieldInfos, fieldComparer);
  1556. while (currentType != typeof(object))
  1557. {
  1558. fieldInfos = currentType.GetFields(bindingFlags);
  1559. fieldInfoList.UnionWith(fieldInfos);
  1560. currentType = currentType.BaseType;
  1561. }
  1562. return fieldInfoList.ToArray();
  1563. }
  1564. private class FieldInfoComparer : IEqualityComparer<FieldInfo>
  1565. {
  1566. public bool Equals(FieldInfo x, FieldInfo y)
  1567. {
  1568. return x.DeclaringType == y.DeclaringType && x.Name == y.Name;
  1569. }
  1570. public int GetHashCode(FieldInfo obj)
  1571. {
  1572. return obj.Name.GetHashCode() ^ obj.DeclaringType.GetHashCode();
  1573. }
  1574. }
  1575. /// <summary>
  1576. /// The method implements deep clone using reflection.
  1577. /// </summary>
  1578. /// <param name="from">It is the object used to deep clone.</param>
  1579. /// <returns>Return the deep clone.</returns>
  1580. private static object? DoClone(object from, object? into = null)
  1581. {
  1582. if (from == null) return null;
  1583. if (from is MulticastDelegate)
  1584. return null;
  1585. var type = from.GetType();
  1586. // If the type of object is the value type, we will always get a new object when
  1587. // the original object is assigned to another variable. So if the type of the
  1588. // object is primitive or enum, we just return the object. We will process the
  1589. // struct type subsequently because the struct type may contain the reference
  1590. // fields.
  1591. // If the string variables contain the same chars, they always refer to the same
  1592. // string in the heap. So if the type of the object is string, we also return the
  1593. // object.
  1594. if (type.GetTypeInfo().IsPrimitive || type.GetTypeInfo().IsEnum || type == typeof(string)) return from;
  1595. // If the type of the object is the Array, we use the CreateInstance method to get
  1596. // a new instance of the array. We also process recursively this method in the
  1597. // elements of the original array because the type of the element may be the reference
  1598. // type.
  1599. if (type.IsArray)
  1600. {
  1601. var basename = type.FullName.Replace("[]", "");
  1602. var typeElement = Type.GetType(basename);
  1603. if (typeElement == null)
  1604. typeElement = FindType(basename);
  1605. var array = (from as Array)!; // not-null because type.IsArray
  1606. var copiedArray = Array.CreateInstance(typeElement, array.Length);
  1607. for (var i = 0; i < array.Length; i++)
  1608. // Get the deep clone of the element in the original array and assign the
  1609. // clone to the new array.
  1610. copiedArray.SetValue(DoClone(array.GetValue(i)), i);
  1611. return copiedArray;
  1612. }
  1613. // If the type of the object is class or struct, it may contain the reference fields,
  1614. // so we use reflection and process recursively this method in the fields of the object
  1615. // to get the deep clone of the object.
  1616. // We use Type.IsValueType method here because there is no way to indicate directly whether
  1617. // the Type is a struct type.
  1618. if (type.GetTypeInfo().IsClass || type.GetTypeInfo().IsValueType)
  1619. {
  1620. var copiedObject = into;
  1621. if (copiedObject == null)
  1622. try
  1623. {
  1624. copiedObject = Activator.CreateInstance(from.GetType());
  1625. }
  1626. catch (Exception e)
  1627. {
  1628. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1629. }
  1630. if (copiedObject != null)
  1631. {
  1632. // Get all FieldInfo.
  1633. var fields = GetFieldInfosIncludingBaseClasses(type.GetTypeInfo(),
  1634. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  1635. foreach (var field in fields.Where(x => !x.IsNotSerialized))
  1636. {
  1637. var fieldValue = field.GetValue(from);
  1638. if (fieldValue != null)
  1639. // Get the deep clone of the field in the original object and assign the
  1640. // clone to the field in the new object.
  1641. field.SetValue(copiedObject, DoClone(fieldValue));
  1642. }
  1643. }
  1644. return copiedObject;
  1645. }
  1646. throw new ArgumentException("The object is unknown type");
  1647. }
  1648. #endregion
  1649. #region DeepCompare Utility
  1650. public static bool CompareObjects(string prefix, object inputObjectA, object inputObjectB, string[] ignorePropertiesList,
  1651. List<Tuple<string, object?, object?>> results)
  1652. {
  1653. var areObjectsEqual = true;
  1654. //check if both objects are not null before starting comparing children
  1655. if (inputObjectA != null && inputObjectB != null)
  1656. {
  1657. //create variables to store object values
  1658. object value1, value2;
  1659. var properties = inputObjectA.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
  1660. //get all public properties of the object using reflection
  1661. foreach (var propertyInfo in properties)
  1662. {
  1663. var name = string.IsNullOrWhiteSpace(prefix) ? propertyInfo.Name : prefix + "." + propertyInfo.Name;
  1664. //if it is not a readable property or if it is a ignorable property
  1665. //ingore it and move on
  1666. if (!propertyInfo.CanRead || ignorePropertiesList.Contains(name))
  1667. continue;
  1668. //get the property values of both the objects
  1669. value1 = propertyInfo.GetValue(inputObjectA, null);
  1670. value2 = propertyInfo.GetValue(inputObjectB, null);
  1671. // if the objects are primitive types such as (integer, string etc)
  1672. //that implement IComparable, we can just directly try and compare the value
  1673. if (IsAssignableFrom(propertyInfo.PropertyType) || IsPrimitiveType(propertyInfo.PropertyType) ||
  1674. IsValueType(propertyInfo.PropertyType))
  1675. {
  1676. //compare the values
  1677. if (!CompareValues(name, value1, value2, results))
  1678. {
  1679. //Console.WriteLine("Property Name {0}", propertyInfo.Name);
  1680. areObjectsEqual = false;
  1681. }
  1682. }
  1683. //if the property is a collection (or something that implements IEnumerable)
  1684. //we have to iterate through all items and compare values
  1685. else if (IsEnumerableType(propertyInfo.PropertyType))
  1686. {
  1687. //Console.WriteLine("Property Name {0}", propertyInfo.Name);
  1688. if (!CompareEnumerations(name, value1, value2, ignorePropertiesList, results))
  1689. areObjectsEqual = false;
  1690. }
  1691. //if it is a class object, call the same function recursively again
  1692. else if (propertyInfo.PropertyType.IsClass)
  1693. {
  1694. if (!CompareObjects(name, propertyInfo.GetValue(inputObjectA, null), propertyInfo.GetValue(inputObjectB, null),
  1695. ignorePropertiesList, results))
  1696. areObjectsEqual = false;
  1697. }
  1698. else
  1699. {
  1700. areObjectsEqual = false;
  1701. }
  1702. }
  1703. }
  1704. else
  1705. {
  1706. areObjectsEqual = false;
  1707. }
  1708. return areObjectsEqual;
  1709. }
  1710. //true if c and the current Type represent the same type, or if the current Type is in the inheritance
  1711. //hierarchy of c, or if the current Type is an interface that c implements,
  1712. //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.
  1713. private static bool IsAssignableFrom(Type type)
  1714. {
  1715. return typeof(IComparable).IsAssignableFrom(type);
  1716. }
  1717. private static bool IsPrimitiveType(Type type)
  1718. {
  1719. return type.IsPrimitive;
  1720. }
  1721. private static bool IsValueType(Type type)
  1722. {
  1723. return type.IsValueType;
  1724. }
  1725. private static bool IsEnumerableType(Type type)
  1726. {
  1727. return typeof(IEnumerable).IsAssignableFrom(type);
  1728. }
  1729. /// <summary>
  1730. /// Compares two values and returns if they are the same.
  1731. /// </summary>
  1732. private static bool CompareValues(string name, object? value1, object? value2, List<Tuple<string, object?, object?>> results)
  1733. {
  1734. var areValuesEqual = true;
  1735. var selfValueComparer = value1 as IComparable;
  1736. // one of the values is null
  1737. if ((value1 == null && value2 != null) || (value1 != null && value2 == null))
  1738. areValuesEqual = false;
  1739. else if (selfValueComparer != null && selfValueComparer.CompareTo(value2) != 0)
  1740. areValuesEqual = false;
  1741. else if (!Equals(value1, value2))
  1742. areValuesEqual = false;
  1743. if (!areValuesEqual)
  1744. results.Add(new Tuple<string, object?, object?>(name, value1, value2));
  1745. return areValuesEqual;
  1746. }
  1747. private static bool CompareEnumerations(string name, object value1, object value2, string[] ignorePropertiesList,
  1748. List<Tuple<string, object?, object?>> results)
  1749. {
  1750. // if one of the values is null, no need to proceed return false;
  1751. if (value1 == null && value2 != null)
  1752. {
  1753. results.Add(new Tuple<string, object?, object?>(string.Format("{0}.Null", name), true, false));
  1754. return false;
  1755. }
  1756. if (value1 != null && value2 == null)
  1757. {
  1758. results.Add(new Tuple<string, object?, object?>(string.Format("{0}.Null", name), false, true));
  1759. return false;
  1760. }
  1761. if (value1 != null && value2 != null)
  1762. {
  1763. IEnumerable<object> enumValue1, enumValue2;
  1764. enumValue1 = ((IEnumerable)value1).Cast<object>();
  1765. enumValue2 = ((IEnumerable)value2).Cast<object>();
  1766. // if the items count are different return false
  1767. if (enumValue1.Count() != enumValue2.Count())
  1768. {
  1769. results.Add(new Tuple<string, object?, object?>(string.Format("{0}.Count", name), enumValue1.Count(), enumValue2.Count()));
  1770. return false;
  1771. }
  1772. // if the count is same, compare individual item
  1773. object enumValue1Item, enumValue2Item;
  1774. Type enumValue1ItemType;
  1775. for (var itemIndex = 0; itemIndex < enumValue1.Count(); itemIndex++)
  1776. {
  1777. enumValue1Item = enumValue1.ElementAt(itemIndex);
  1778. enumValue2Item = enumValue2.ElementAt(itemIndex);
  1779. enumValue1ItemType = enumValue1Item.GetType();
  1780. if (IsAssignableFrom(enumValue1ItemType) || IsPrimitiveType(enumValue1ItemType) || IsValueType(enumValue1ItemType))
  1781. {
  1782. if (!CompareValues(string.Format("{0}[{1}]", name, itemIndex), enumValue1Item, enumValue2Item, results))
  1783. return false;
  1784. }
  1785. else if (!CompareObjects(name, enumValue1Item, enumValue2Item, ignorePropertiesList, results))
  1786. {
  1787. return false;
  1788. }
  1789. }
  1790. }
  1791. return true;
  1792. }
  1793. #endregion
  1794. #region Expression Serialisation
  1795. public static string MemberExpressionToString(MemberExpression mExpression)
  1796. {
  1797. var mOriginal = mExpression;
  1798. var path = "";
  1799. while (true)
  1800. {
  1801. if (mExpression.Expression.NodeType == ExpressionType.MemberAccess)
  1802. {
  1803. var propInfo = mExpression.Expression
  1804. .GetType().GetTypeInfo().GetProperty("Member");
  1805. var propValue = (propInfo.GetValue(mExpression.Expression, null) as PropertyInfo)!;
  1806. path = propValue.Name + "." + path;
  1807. mExpression = (mExpression.Expression as MemberExpression)!;
  1808. }
  1809. else if (mExpression.Expression.NodeType == ExpressionType.Convert)
  1810. {
  1811. mExpression = MemberExpression.PropertyOrField((mExpression.Expression as UnaryExpression)?.Operand as MemberExpression, mExpression.Member.Name);
  1812. }
  1813. else
  1814. {
  1815. break;
  1816. }
  1817. }
  1818. return path + mOriginal.Member.Name;
  1819. }
  1820. private enum SerialisedExpressionType
  1821. {
  1822. Member,
  1823. Index,
  1824. Parameter
  1825. }
  1826. public static void SerialiseExpression(this CoreBinaryWriter writer, Type t, Expression expression, bool includeType)
  1827. {
  1828. if (includeType)
  1829. {
  1830. writer.Write(t.EntityName());
  1831. }
  1832. if (expression.NodeType == ExpressionType.MemberAccess)
  1833. {
  1834. writer.Write((byte)SerialisedExpressionType.Member);
  1835. writer.Write(MemberExpressionToString((expression as MemberExpression)!));
  1836. }
  1837. else if (expression.NodeType == ExpressionType.Index)
  1838. {
  1839. writer.Write((byte)SerialisedExpressionType.Index);
  1840. var iexp = (IndexExpression)expression;
  1841. var sexp = expression.ToString().Split('[');
  1842. writer.Write(sexp[0]); // Member
  1843. writer.Write(sexp[1].Replace("]", "").Replace("\"", "")); // Key
  1844. }
  1845. else
  1846. {
  1847. writer.Write((byte)SerialisedExpressionType.Parameter);
  1848. }
  1849. }
  1850. public static Expression DeserialiseExpression(this CoreBinaryReader reader, Type t)
  1851. {
  1852. return DeserialiseExpression(reader, t, reader.ReadByte());
  1853. }
  1854. public static Expression DeserialiseExpression(this CoreBinaryReader reader, Type t, byte type)
  1855. {
  1856. var expressionType = (SerialisedExpressionType)type;
  1857. switch (expressionType)
  1858. {
  1859. case SerialisedExpressionType.Member:
  1860. var member = reader.ReadString();
  1861. return CreateMemberExpression(t, member);
  1862. case SerialisedExpressionType.Index:
  1863. member = reader.ReadString();
  1864. var key = reader.ReadString();
  1865. return CreateIndexExpression(t, member, key);
  1866. case SerialisedExpressionType.Parameter:
  1867. default:
  1868. return Expression.Parameter(t, "x");
  1869. }
  1870. }
  1871. /// <summary>
  1872. /// Deserialise the expression, with type information included in the serialised form.
  1873. /// </summary>
  1874. /// <param name="reader"></param>
  1875. /// <returns></returns>
  1876. public static Expression DeserialiseExpression(this CoreBinaryReader reader)
  1877. {
  1878. var entityName = reader.ReadString();
  1879. var t = GetEntity(entityName);
  1880. return reader.DeserialiseExpression(t);
  1881. }
  1882. public static string ExpressionToString<T,TType>(Expression<Func<T, TType>> expression)
  1883. => ExpressionToString(typeof(T), expression);
  1884. public static string ExpressionToString(Type t, Expression expression)
  1885. {
  1886. if (expression.NodeType == ExpressionType.MemberAccess)
  1887. {
  1888. var mexp = (MemberExpression)expression;
  1889. var morg = (MemberExpression)expression;
  1890. var Path = "";
  1891. while (mexp.Expression.NodeType == ExpressionType.MemberAccess)
  1892. {
  1893. var propInfo = mexp.Expression
  1894. .GetType().GetTypeInfo().GetProperty("Member");
  1895. var propValue = propInfo.GetValue(mexp.Expression, null)
  1896. as PropertyInfo;
  1897. Path = propValue.Name + "." + Path;
  1898. mexp = mexp.Expression as MemberExpression;
  1899. }
  1900. return Path + morg.Member.Name;
  1901. }
  1902. else if (expression.NodeType == ExpressionType.Index)
  1903. {
  1904. var iexp = (IndexExpression)expression;
  1905. var sexp = expression.ToString().Split('[');
  1906. return sexp[0];
  1907. }
  1908. return expression.ToString();
  1909. }
  1910. public static string ExpressionToString(Type t, Expression expression, bool includetype)
  1911. {
  1912. var result = new Dictionary<string, string>();
  1913. if (expression.NodeType == ExpressionType.MemberAccess)
  1914. {
  1915. var mexp = (expression as MemberExpression)!;
  1916. result["Member"] = MemberExpressionToString(mexp);
  1917. }
  1918. else if (expression.NodeType == ExpressionType.Index)
  1919. {
  1920. var iexp = (IndexExpression)expression;
  1921. var sexp = expression.ToString().Split('[');
  1922. result["Member"] = sexp[0];
  1923. result["Key"] = sexp[1].Replace("]", "").Replace("\"", "");
  1924. }
  1925. result["Type"] = t.EntityName();
  1926. return Serialization.Serialize(result);
  1927. }
  1928. public static Expression StringToExpression(string expression)
  1929. {
  1930. var comps = Serialization.Deserialize<Dictionary<string, string>>(expression);
  1931. var t = GetEntity(comps["Type"]);
  1932. if (comps.TryGetValue("Key", out var key))
  1933. return CreateIndexExpression(t, comps["Member"], key);
  1934. else if (comps.TryGetValue("Member", out var member))
  1935. return CreateMemberExpression(t, member);
  1936. else
  1937. return Expression.Parameter(t, "x");
  1938. }
  1939. public static Expression<Func<T, object?>> CreateLambdaExpression<T>(string column)
  1940. {
  1941. var parameter = Expression.Parameter(typeof(T), "x");
  1942. var property = CreateMemberExpression(typeof(T), column);
  1943. var converted = Expression.Convert(property, typeof(object));
  1944. //var property = Expression.Convert(Expression.Property(parameter, column),typeof(object));
  1945. return Expression.Lambda<Func<T, object?>>(converted, parameter);
  1946. }
  1947. public static Expression<Func<T, TType>> CreateLambdaExpression<T,TType>(string column)
  1948. {
  1949. var parameter = Expression.Parameter(typeof(T), "x");
  1950. var property = CreateMemberExpression(typeof(T), column);
  1951. var result = Expression.Lambda<Func<T, TType>>(property, parameter);
  1952. return result;
  1953. }
  1954. public static Expression ConvertExpression(Type source, Expression lambda, Type target, Expression anchor)
  1955. {
  1956. var parent = ExpressionToString(target, anchor, false);
  1957. var child = ExpressionToString(source, lambda, false);
  1958. var property = string.Join(".", parent, child);
  1959. return CreateMemberExpression(target, property);
  1960. }
  1961. public static Expression CreateMemberExpression(Type type, string propertyName)
  1962. {
  1963. var param = Expression.Parameter(type, "x");
  1964. Expression body = param;
  1965. foreach (var member in propertyName.Split('.')) body = Expression.PropertyOrField(body, member);
  1966. return (MemberExpression)body;
  1967. }
  1968. public static IndexExpression CreateIndexExpression(Type type, string propertyname, string key)
  1969. {
  1970. var param = Expression.Parameter(type, "x");
  1971. var propmod = propertyname.Replace("x.", "").Replace(".Item", "");
  1972. var bar = Expression.Property(param, propmod);
  1973. var dictionaryType = type.GetProperty(propmod).PropertyType;
  1974. var indexerProp = dictionaryType.GetProperty("Item");
  1975. var dictKeyConstant = Expression.Constant(key);
  1976. var dictAccess = Expression.MakeIndex(bar, indexerProp, new[] { dictKeyConstant });
  1977. return dictAccess;
  1978. //var propertyType = indexerProp.PropertyType;
  1979. //var right = Expression.Constant(Convert.ChangeType("newValue", propertyType));
  1980. //var expression = Expression.MakeBinary(ExpressionType.Equal, dictAccess, right);
  1981. }
  1982. public static MemberExpression ExtractMemberExpression<T>(Expression<Func<T, object?>> expression)
  1983. {
  1984. if(!TryFindMemberExpression(expression.Body, out var me))
  1985. {
  1986. throw new Exception("Expression is not a member expression!");
  1987. }
  1988. return me;
  1989. }
  1990. public static MemberExpression ExtractMemberExpression<T, TValue>(Expression<Func<T, TValue>> expression)
  1991. {
  1992. TryFindMemberExpression(expression.Body, out var me);
  1993. return me;
  1994. }
  1995. public static MemberExpression ExtractMemberExpression(Expression expression)
  1996. {
  1997. TryFindMemberExpression(Expression.Lambda(expression).Body, out var me);
  1998. return me;
  1999. }
  2000. #endregion
  2001. public static string FormatException(Exception err)
  2002. {
  2003. var messages = new List<string>();
  2004. var e2 = err;
  2005. while (e2 != null)
  2006. {
  2007. messages.InsertRange(0, new[] { e2.Message, e2.StackTrace, "============================================" });
  2008. e2 = e2.InnerException;
  2009. }
  2010. return string.Join("\n", messages);
  2011. }
  2012. public static void LogException(string userid, Exception err, string? extra = null, Logger? logger = null)
  2013. {
  2014. Logger.Send(LogType.Error, userid, (extra != null ? $"{extra}: " : "") + CoreUtils.FormatException(err), transaction: logger?.Transaction);
  2015. }
  2016. #region OneToMany Relationships
  2017. public static Type? GetOneToMany(Type TMany, Type TOne)
  2018. {
  2019. var o2m = TMany.GetInterfaces().FirstOrDefault(i =>
  2020. i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IOneToMany<>)
  2021. && i.GenericTypeArguments.Contains(TOne)
  2022. );
  2023. return o2m;
  2024. }
  2025. public static PropertyInfo GetOneToManyProperty(Type TMany, Type TOne)
  2026. {
  2027. return TMany.GetProperties().FirstOrDefault(x =>
  2028. x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink))
  2029. && x.PropertyType.GetInheritedGenericTypeArguments().FirstOrDefault() == TOne
  2030. && !Attribute.IsDefined(x, typeof(ObsoleteAttribute))
  2031. );
  2032. }
  2033. #endregion
  2034. #region ManyToMany Relationships
  2035. public static Type? GetManyToMany(Type TManyToMany, Type TThis)
  2036. {
  2037. var m2m = TManyToMany.GetInterfaces().FirstOrDefault(i =>
  2038. i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>)
  2039. && i.GenericTypeArguments.Contains(TThis)
  2040. );
  2041. return m2m;
  2042. }
  2043. public static Type GetManyToManyOtherType(Type TManyToMany, Type TThis)
  2044. {
  2045. var m2m = TManyToMany.GetInterfaces().FirstOrDefault(i =>
  2046. i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>)
  2047. && i.GenericTypeArguments.Contains(TThis)
  2048. );
  2049. return m2m.GenericTypeArguments.FirstOrDefault(x => x != TThis);
  2050. }
  2051. public static PropertyInfo GetManyToManyThisProperty(Type TManyToMany, Type TThis)
  2052. {
  2053. return TManyToMany.GetProperties().FirstOrDefault(x =>
  2054. x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink))
  2055. && x.PropertyType.GetInheritedGenericTypeArguments().FirstOrDefault() == TThis
  2056. && !Attribute.IsDefined(x, typeof(ObsoleteAttribute))
  2057. );
  2058. }
  2059. public static PropertyInfo GetManyToManyOtherProperty(Type TManyToMany, Type TThis)
  2060. {
  2061. var otherType = GetManyToManyOtherType(TManyToMany, TThis);
  2062. return TManyToMany.GetProperties().FirstOrDefault(x =>
  2063. x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink))
  2064. && x.PropertyType.GetInheritedGenericTypeArguments().FirstOrDefault() == otherType
  2065. && !Attribute.IsDefined(x, typeof(ObsoleteAttribute))
  2066. );
  2067. }
  2068. #endregion
  2069. /// <summary>
  2070. /// Get a dictionary of values representing the current state of an entity
  2071. /// </summary>
  2072. /// <param name="item">The Entity being scanned</param>
  2073. /// <param name="props">The list of properties to scan, or null for all</param>
  2074. /// <returns>A dictionary containing the properties and values for the entity</returns>
  2075. public static Dictionary<string, object?> GetValues(BaseObject item, IEnumerable<IProperty>? props = null)
  2076. {
  2077. var result = new Dictionary<string, object?>();
  2078. props ??= DatabaseSchema.Properties(item.GetType());//.Where(x => !(x.Editor is NullEditor));
  2079. foreach (var prop in props)
  2080. if (prop is CustomProperty)
  2081. try
  2082. {
  2083. result[prop.Name] = item.UserProperties[prop.Name];
  2084. }
  2085. catch (Exception e)
  2086. {
  2087. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2088. }
  2089. else
  2090. try
  2091. {
  2092. object? value;
  2093. var getter = prop.Getter();
  2094. if (getter != null)
  2095. value = getter.Invoke(item);
  2096. else
  2097. value = CoreUtils.GetPropertyValue(item, prop.Name);
  2098. result[prop.Name] = value;
  2099. }
  2100. catch (Exception e)
  2101. {
  2102. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  2103. }
  2104. return result;
  2105. }
  2106. /// <summary>
  2107. /// Given a certain entity, merge the changes with the current state of the entity into an updated list
  2108. /// </summary>
  2109. /// <param name="item">Th Entity being updated</param>
  2110. /// <param name="previous">The previous set of changes to this entity</param>
  2111. /// <param name="props">The list of properties to scan, or null for all</param>
  2112. /// <param name="changes">The resulting updated list of changes</param>
  2113. public static void MergeChanges(Dictionary<string, object?> previous, Dictionary<string, object?> current, Dictionary<string, object?> changes)
  2114. {
  2115. foreach (var (key, prevVal) in previous)
  2116. if (prevVal is null)
  2117. {
  2118. if (current[key] != null)
  2119. changes[key] = current[key];
  2120. }
  2121. else
  2122. {
  2123. if (!current.TryGetValue(key, out var curVal) || curVal is null)
  2124. changes[key] = null;
  2125. else if (!object.Equals(previous[key], curVal))
  2126. changes[key] = curVal;
  2127. }
  2128. }
  2129. public static Dictionary<String, object?> MonitorChanges<T>(T item, Action action, Dictionary<String, object?>? changes = null, IEnumerable<IProperty>? props = null) where T : BaseObject
  2130. {
  2131. var result = changes == null
  2132. ? new Dictionary<String, object?>()
  2133. : changes;
  2134. var previous = GetValues(item, props);
  2135. action.Invoke();
  2136. var current = GetValues(item, props);
  2137. MergeChanges(previous, current, result);
  2138. return result;
  2139. }
  2140. public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
  2141. {
  2142. int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
  2143. return dt.AddDays(-1 * diff).Date;
  2144. }
  2145. public static DateTime StartOfMonth(this DateTime dt)
  2146. {
  2147. return new DateTime(dt.Year, dt.Month, 1);
  2148. }
  2149. public static DateTime StartOfYear(this DateTime dt)
  2150. {
  2151. return new DateTime(dt.Year, 1, 1);
  2152. }
  2153. #region String Utilities
  2154. /// <summary>
  2155. /// Check if <paramref name="s"/> <see cref="string.IsNullOrWhiteSpace(string)"/>.
  2156. /// If it is empty, returns <paramref name="def"/>, otherwise, returns <paramref name="s"/>.
  2157. /// </summary>
  2158. /// <remarks>
  2159. /// Basically the null-coalescing operator ?? for strings.
  2160. /// </remarks>
  2161. /// <param name="s"></param>
  2162. /// <param name="def"></param>
  2163. /// <returns></returns>
  2164. [return: NotNullIfNotNull("def")]
  2165. public static string? NotWhiteSpaceOr(this string? s, string? def = null)
  2166. {
  2167. if (string.IsNullOrWhiteSpace(s))
  2168. {
  2169. return def;
  2170. }
  2171. return s;
  2172. }
  2173. /// <summary>
  2174. /// Extension method version of <see cref="string.IsNullOrWhiteSpace(string)"/>.
  2175. /// </summary>
  2176. /// <param name="s">The string to check</param>
  2177. /// <returns>true if <paramref name="s"/> is <see langword="null"/> or composed only of whitespace.</returns>
  2178. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2179. public static bool IsNullOrWhiteSpace([NotNullWhen(false)] this string? s)
  2180. {
  2181. return string.IsNullOrWhiteSpace(s);
  2182. }
  2183. public static bool IsBase64String(this string s)
  2184. {
  2185. s = s.Trim();
  2186. return s.Length % 4 == 0 && Regex.IsMatch(s, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None);
  2187. }
  2188. public static string CalculateCRC(byte[] data)
  2189. {
  2190. var hash = Crc32.Compute(data);
  2191. return string.Format("{0:X8}", hash);
  2192. }
  2193. public static string StripHTML(this string? html)
  2194. {
  2195. if (string.IsNullOrWhiteSpace(html))
  2196. return "";
  2197. var result = StripHtmlStyles.Replace(html, "");
  2198. result = StripHtmlTags.Replace(result, "");
  2199. result = StripSpecialCharacters.Replace(result, "");
  2200. //result = StripQuotes.Replace(result, "\"");
  2201. result = StripLineBreaks.Replace(result, "$1");
  2202. result = result.Replace("\0", "").Trim();
  2203. return result;
  2204. }
  2205. private static Regex NeatifyRegex = new Regex(@"
  2206. (?<=[A-Z])(?=[A-Z][a-z]) |
  2207. (?<=[^A-Z])(?=[A-Z]) |
  2208. (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace);
  2209. public static string Neatify(string caption)
  2210. {
  2211. if (string.Equals(caption, "ID"))
  2212. return caption;
  2213. var result = NeatifyRegex.Replace(caption.Replace(".", ""), " ");
  2214. while (result.Contains(" "))
  2215. result = result.Replace(" ", " ");
  2216. if (result.EndsWith(" ID"))
  2217. result = string.Join(" ", result.Split(' ').Reverse().Skip(1).Reverse());
  2218. return result.Trim();
  2219. }
  2220. public static string Codify(string? text)
  2221. {
  2222. char[] numbers = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
  2223. if (string.IsNullOrWhiteSpace(text))
  2224. return "??";
  2225. var result = "";
  2226. var comps = text.ToUpper().Split(' ');
  2227. foreach (var comp in comps)
  2228. {
  2229. List<char> chars = new List<char>();
  2230. foreach (char c in comp.ToCharArray())
  2231. {
  2232. chars.Add(c);
  2233. if (!numbers.Contains(c))
  2234. break;
  2235. }
  2236. var comb = new String(chars.ToArray());
  2237. result += comb;
  2238. }
  2239. return string.IsNullOrWhiteSpace(result) ? "??" : result;
  2240. }
  2241. public static string Truncate(this string value, int maxLength)
  2242. {
  2243. if(value.Length > maxLength)
  2244. {
  2245. return value[..maxLength];
  2246. }
  2247. return value;
  2248. }
  2249. #endregion
  2250. #region IEnumerable Utilities
  2251. public static IEnumerable<T> NewEmpty<T>(this IEnumerable<T> enumerable)
  2252. {
  2253. yield break;
  2254. }
  2255. /// <summary>
  2256. /// Returns <paramref name="enumerable"/> as a <see cref="List{T}"/>;
  2257. /// if it is already a <see cref="List{T}"/>, it is directly returned, instead of copying.
  2258. /// </summary>
  2259. public static List<T> AsList<T>(this IEnumerable<T> enumerable)
  2260. {
  2261. if(enumerable is List<T> list)
  2262. {
  2263. return list;
  2264. }
  2265. return enumerable.ToList<T>();
  2266. }
  2267. /// <summary>
  2268. /// Returns <paramref name="enumerable"/> as an <see cref="IList{T}"/>;
  2269. /// if it is already a <see cref="IList{T}"/>, it is directly returned, instead of copying.
  2270. /// </summary>
  2271. public static IList<T> AsIList<T>(this IEnumerable<T> enumerable)
  2272. {
  2273. if (enumerable is IList<T> list)
  2274. {
  2275. return list;
  2276. }
  2277. return enumerable.ToList<T>();
  2278. }
  2279. /// <summary>
  2280. /// Returns <paramref name="enumerable"/> as an array;
  2281. /// if it is already an array, it is directly returned, instead of copying.
  2282. /// </summary>
  2283. public static T[] AsArray<T>(this IEnumerable<T> enumerable)
  2284. {
  2285. if (enumerable is T[] arr)
  2286. {
  2287. return arr;
  2288. }
  2289. return enumerable.ToArray<T>();
  2290. }
  2291. public static U[] ToArray<T, U>(this IList<T> from, Func<T, U> mapFunc)
  2292. {
  2293. var to = new U[from.Count];
  2294. for(int i = 0; i < from.Count; ++i)
  2295. {
  2296. to[i] = mapFunc(from[i]);
  2297. }
  2298. return to;
  2299. }
  2300. public static U[] ToArray<T, U>(this ICollection<T> from, Func<T, U> mapFunc)
  2301. {
  2302. var to = new U[from.Count];
  2303. var i = 0;
  2304. foreach(var item in from)
  2305. {
  2306. to[i] = mapFunc(item);
  2307. ++i;
  2308. }
  2309. return to;
  2310. }
  2311. public static List<U> ToList<T, U>(this IList<T> from, Func<T, U> mapFunc)
  2312. {
  2313. var to = new List<U>(from.Count);
  2314. for(int i = 0; i < from.Count; ++i)
  2315. {
  2316. to.Add(mapFunc(from[i]));
  2317. }
  2318. return to;
  2319. }
  2320. /// <summary>
  2321. /// Concatenate <paramref name="arr1"/> with <paramref name="arr2"/>, returning a new array.
  2322. /// </summary>
  2323. /// <typeparam name="T"></typeparam>
  2324. /// <param name="arr1"></param>
  2325. /// <param name="arr2"></param>
  2326. /// <returns></returns>
  2327. public static T[] Concatenate<T>(this T[] arr1, T[] arr2)
  2328. {
  2329. var newArr = new T[arr1.Length + arr2.Length];
  2330. arr1.CopyTo(newArr, 0);
  2331. arr2.CopyTo(newArr, arr1.Length);
  2332. return newArr;
  2333. }
  2334. /// <summary>
  2335. /// Concatenate all <paramref name="arrays"/> together.
  2336. /// </summary>
  2337. /// <typeparam name="T"></typeparam>
  2338. /// <param name="arrays"></param>
  2339. /// <returns></returns>
  2340. public static T[] Concatenate<T>(params T[][] arrays)
  2341. {
  2342. var newArr = new T[arrays.Sum(x => x.Length)];
  2343. for(int i = 0, idx = 0; i < arrays.Length; ++i)
  2344. {
  2345. var arr = arrays[i];
  2346. arr.CopyTo(newArr, idx);
  2347. idx += arr.Length;
  2348. }
  2349. return newArr;
  2350. }
  2351. public static IEnumerable<T> AnyOr<T>(this IEnumerable<T> enumerable, IEnumerable<T> or)
  2352. {
  2353. var any = false;
  2354. foreach(var item in enumerable)
  2355. {
  2356. any = true;
  2357. yield return item;
  2358. }
  2359. if (!any)
  2360. {
  2361. foreach(var item in or)
  2362. {
  2363. yield return item;
  2364. }
  2365. }
  2366. }
  2367. public static IEnumerable<T> One<T>(T item)
  2368. {
  2369. yield return item;
  2370. }
  2371. public static IEnumerable<T> One<T>(Func<T> fnc)
  2372. {
  2373. yield return fnc();
  2374. }
  2375. public static (List<T>, List<T>) PartitionToList<T>(this IEnumerable<T> enumerable, Func<T, bool> predicate)
  2376. {
  2377. var trueResult = new List<T>();
  2378. var falseResult = new List<T>();
  2379. foreach(var item in enumerable)
  2380. {
  2381. if (predicate(item))
  2382. {
  2383. trueResult.Add(item);
  2384. }
  2385. else
  2386. {
  2387. falseResult.Add(item);
  2388. }
  2389. }
  2390. return (trueResult, falseResult);
  2391. }
  2392. /// <summary>
  2393. /// Get the value in <paramref name="dictionary"/> for the given <paramref name="key"/>, adding a new instance of <typeparamref name="TValue"/>
  2394. /// if the value was not found.
  2395. /// </summary>
  2396. /// <typeparam name="TKey"></typeparam>
  2397. /// <typeparam name="TValue"></typeparam>
  2398. /// <param name="dictionary"></param>
  2399. /// <param name="key"></param>
  2400. /// <returns></returns>
  2401. public static TValue GetValueOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
  2402. where TValue : new()
  2403. {
  2404. if(!dictionary.TryGetValue(key, out var value))
  2405. {
  2406. value = new TValue();
  2407. dictionary.Add(key, value);
  2408. }
  2409. return value;
  2410. }
  2411. /// <summary>
  2412. /// Add a range of values to a dictionary, using the <see cref="IDictionary{TKey, TValue}.Add(TKey, TValue)"/> method.
  2413. /// </summary>
  2414. /// <remarks>
  2415. /// Throws an <see cref="ArgumentException"/> for duplicate keys.
  2416. /// </remarks>
  2417. /// <typeparam name="TDict"></typeparam>
  2418. /// <typeparam name="TKey"></typeparam>
  2419. /// <typeparam name="TValue"></typeparam>
  2420. /// <param name="dictionary"></param>
  2421. /// <param name="items"></param>
  2422. /// <returns></returns>
  2423. public static TDict AddRange<TDict, TKey, TValue>(this TDict dictionary, IEnumerable<KeyValuePair<TKey, TValue>> items)
  2424. where TDict : IDictionary<TKey, TValue>
  2425. {
  2426. foreach(var item in items)
  2427. {
  2428. dictionary.Add(item.Key, item.Value);
  2429. }
  2430. return dictionary;
  2431. }
  2432. public static IEnumerable<T> NotNull<T>(this IEnumerable<T?> enumerable)
  2433. where T : struct
  2434. {
  2435. foreach(var obj in enumerable)
  2436. {
  2437. if (obj.HasValue)
  2438. {
  2439. yield return obj.Value;
  2440. }
  2441. }
  2442. }
  2443. public static IEnumerable<T> NotNull<T>(this IEnumerable<T?> enumerable)
  2444. where T : class
  2445. {
  2446. foreach (var obj in enumerable)
  2447. {
  2448. if (obj != null)
  2449. {
  2450. yield return obj;
  2451. }
  2452. }
  2453. }
  2454. public static IEnumerable<TValue> NotNull<T, TValue>(this IEnumerable<T> enumerable, Func<T, TValue?> f)
  2455. where TValue : struct
  2456. {
  2457. foreach (var obj in enumerable)
  2458. {
  2459. var v = f(obj);
  2460. if (v.HasValue)
  2461. {
  2462. yield return v.Value;
  2463. }
  2464. }
  2465. }
  2466. public static IEnumerable<TValue> NotNull<T, TValue>(this IEnumerable<T> enumerable, Func<T, TValue?> f)
  2467. where TValue : class
  2468. {
  2469. foreach (var obj in enumerable)
  2470. {
  2471. var v = f(obj);
  2472. if (v != null)
  2473. {
  2474. yield return v;
  2475. }
  2476. }
  2477. }
  2478. public static IEnumerable<KeyValuePair<int, T>> WithIndex<T>(this IEnumerable<T> enumerable)
  2479. {
  2480. int i = 0;
  2481. foreach(var obj in enumerable)
  2482. {
  2483. yield return new KeyValuePair<int, T>(i, obj);
  2484. ++i;
  2485. }
  2486. }
  2487. public static IEnumerable<T> Dequeue<T>(this Queue<T> queue, int chunkSize)
  2488. {
  2489. for (int i = 0; i < chunkSize && queue.Count > 0; i++)
  2490. {
  2491. yield return queue.Dequeue();
  2492. }
  2493. }
  2494. public static Queue<T> ToQueue<T>(this IEnumerable<T> enumerable)
  2495. {
  2496. return new Queue<T>(enumerable.ToArray());
  2497. }
  2498. public static void SortBy<T, TProp>(this T[] list, Func<T, TProp> comparison)
  2499. where TProp : IComparable
  2500. {
  2501. Array.Sort(list, (a, b) => comparison(a).CompareTo(comparison(b)));
  2502. }
  2503. public static void SortBy<T, TProp>(this List<T> list, Func<T, TProp> comparison)
  2504. where TProp : IComparable
  2505. {
  2506. list.Sort((a, b) => comparison(a).CompareTo(comparison(b)));
  2507. }
  2508. /// <summary>
  2509. /// Compare the elements in this list to the other list, returning <see langword="true"/> if they have all the same
  2510. /// elements, regardless of order.
  2511. /// </summary>
  2512. public static bool CompareTo<T>(this IList<T> thisList, IList<T> list)
  2513. {
  2514. if(thisList.Count != list.Count)
  2515. {
  2516. return false;
  2517. }
  2518. return thisList.All(x => list.Contains(x));
  2519. }
  2520. /// <summary>
  2521. /// Compare the elements in this list to the other list, returning <see langword="true"/> if they have all the same
  2522. /// elements, regardless of order.
  2523. /// </summary>
  2524. public static bool CompareTo<T>(this IList<T> thisList, IList<T> list, IEqualityComparer<T> comparer)
  2525. {
  2526. if(thisList.Count != list.Count)
  2527. {
  2528. return false;
  2529. }
  2530. return thisList.All(x => list.Contains(x, comparer));
  2531. }
  2532. public static bool Contains<T>(this T[] arr, T value) => Array.IndexOf(arr, value) != -1;
  2533. #endregion
  2534. }
  2535. }