CoreUtils.cs 115 KB

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