CoreUtils.cs 118 KB

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