CoreUtils.cs 116 KB

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