CoreUtils.cs 117 KB

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