CoreUtils.cs 119 KB

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