CoreUtils.cs 118 KB

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