CoreUtils.cs 117 KB

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