CoreUtils.cs 118 KB

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