CoreUtils.cs 116 KB

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