CoreUtils.cs 117 KB

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