CoreUtils.cs 118 KB

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