CoreUtils.cs 110 KB

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