CoreUtils.cs 118 KB

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