CoreUtils.cs 102 KB

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