CoreUtils.cs 117 KB

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