CoreUtils.cs 115 KB

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