CoreUtils.cs 115 KB

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