CoreUtils.cs 117 KB

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