CoreUtils.cs 118 KB

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