CoreUtils.cs 117 KB

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