CoreUtils.cs 119 KB

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