CoreUtils.cs 110 KB

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