CoreUtils.cs 123 KB

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