CoreUtils.cs 113 KB

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