1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884 |
- using System;
- using System.Collections;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Diagnostics.CodeAnalysis;
- using System.Globalization;
- using System.IO;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Net.Mail;
- using System.Reflection;
- using System.Text;
- using System.Text.RegularExpressions;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using System.Runtime.CompilerServices;
- using System.Data.Common;
- //using Serialize.Linq.Serializers;
- namespace InABox.Core
- {
- public enum DatabaseProvider
- {
- //LiteDb,
- //MongoDb,
- SQLite
- }
- //public class DateTimeJsonConverter : JsonConverter<DateTime>
- //{
- // public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)
- // {
- // String result = String.Format("{0:o}", value);
- // writer.WriteValue(result);
- // }
- // public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)
- // {
- // if (reader.Value is DateTime)
- // return (DateTime)reader.Value;
- // else
- // {
- // String value = reader.Value.ToString().Replace("\"","");
- // DateTime.TryParse(value, out DateTime result);
- // return result;
- // }
- // }
- // public override bool CanRead => true;
- // public override bool CanWrite => true;
- //}
- //public class TimeSpanJsonConverter : JsonConverter<TimeSpan>
- //{
- // public override void WriteJson(JsonWriter writer, TimeSpan value, JsonSerializer serializer)
- // {
- // TimeSpan timespan = (TimeSpan)value;
- // writer.WriteValue(timespan.Ticks.ToString());
- // }
- // public override TimeSpan ReadJson(JsonReader reader, Type objectType, TimeSpan existingValue, bool hasExistingValue, JsonSerializer serializer)
- // {
- // Int64 ticks = Int64.Parse(reader.Value.ToString().Replace("\"", ""));
- // return new TimeSpan(ticks);
- // }
- //}
- public enum SyncfusionVersion
- {
- v16_3,
- v16_4,
- v17_1,
- v17_2,
- v17_4,
- v18_1,
- v18_4,
- v19_1,
- v19_3,
- v19_4,
- v20_1,
- v20_2,
- v20_3,
- v22_1,
- v23_1,
- v23_2,
- v25_2,
- v26_x,
- Unspecified
- }
- [LibraryInitializer]
- public static class CoreUtils
- {
-
- private static readonly Dictionary<string, Type> entities = new Dictionary<string, Type>();
- public static Dictionary<string, long> TypeListSummary = new Dictionary<string, long>();
- private static readonly ConcurrentDictionary<Type, IColumns> _columnscache = new ConcurrentDictionary<Type, IColumns>();
- private static readonly Regex StripHtmlStyles = new Regex(@"<style(.|\n)*?</style>", RegexOptions.Compiled);
- private static readonly Regex StripHtmlTags = new Regex(@"<(.|\n)*?>", RegexOptions.Compiled);
- private static readonly Regex StripSpecialCharacters = new Regex(@"&#(.|\n)*?;| |>|<"", RegexOptions.Compiled);
- private static readonly Regex StripLineBreaks = new Regex(@"( |\r?\n|\r|\n)\1+", RegexOptions.Compiled);
-
- /// <summary>
- /// Return all <see cref="Type"/> that have been loaded through use of the <see cref="RegisterClasses(Assembly[])"/> function.
- /// </summary>
- /// <remarks>
- /// This includes every non-abstract type.
- /// </remarks>
- public static IEnumerable<Type> Entities => entities.Values;
- public static long GenerateSequence()
- {
- return (DateTime.Now - new DateTime(2019, 1, 1)).Ticks;
- }
- #region Licensing
- public static string SyncfusionLicense(SyncfusionVersion version = SyncfusionVersion.Unspecified)
- {
- var licenses = new Dictionary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YmxqTDFKaUlLVHgvTmdXZk5Lcm5tNkhJT0RtWUZwM1JxQ1ZLVXVJaDJvPQ==;MzMwNDU5MEAzMjM1MmUzMDJlMzBoamJkMDY0QWFhWnVCbEZDelFCZWtkYXFoTGp3anlEUThrSGlReGxBOXdjPQ=="
- },
- {
- SyncfusionVersion.v26_x,
- "MzM0OTg1MUAzMjM2MmUzMDJlMzBCSy82eWowdW8rSUIzQmRseGlHTUx2WDNRVUJucnpQSGRiUUJEOWtISklNPQ==;MzM0OTg1MkAzMjM2MmUzMDJlMzBhL0lLS3FZMTNOL2dQZXVkTkNWM2psdU9obU1UVklyV2tVczFvcE13eHpNPQ==;MzM0OTg1M0AzMjM2MmUzMDJlMzBhL0lLS3FZMTNOL2dQZXVkTkNWM2psdU9obU1UVklyV2tVczFvcE13eHpNPQ=="
- },
- {
- SyncfusionVersion.Unspecified,
- "NjcyNDdAMzEzNjJlMzQyZTMwbWZlcXhUQW80NjUrTENRTVM0c2J5empYZDFUcHhDcEE0T3gwZDZZVGVtQT0=;NjcyNDhAMzEzNjJlMzQyZTMwZWtuc0VlSXVteWNtUE8zQ1V1azcrZmRjTFBqUGFHenU1YzNwbUVTdlcxVT0="
- }
- };
- return licenses[version];
- }
- public static void CheckLicensing()
- {
- var entities = TypeList(
- AppDomain.CurrentDomain.GetAssemblies(),
- myType =>
- myType.IsClass
- && !myType.IsAbstract
- && !myType.IsGenericType
- && myType.IsSubclassOf(typeof(Entity))
- );
- foreach (var entity in entities)
- {
- var lic = entity.GetInterfaces()
- .FirstOrDefault(x => x.IsConstructedGenericType && x.GetGenericTypeDefinition() == typeof(ILicense<>));
- if (lic == null)
- Logger.Send(LogType.Error, "", "License Configuration Error: " + entity.EntityName().Split('.').Last());
- }
- }
- #endregion
- public static Guid FullGuid = Guid.Parse("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF");
- #region Reflection
- public static bool HasInterface(this Type type, Type interfaceType)
- {
- return type.GetInterfaces(interfaceType).Any();
- }
- public static bool HasInterface<T>(this Type type) => type.HasInterface(typeof(T));
- public static Type? GetInterfaceDefinition(this Type type, Type interfaceType)
- {
- return type.GetInterfaces(interfaceType).FirstOrDefault();
- }
- public static IEnumerable<Type> GetInterfaces(this Type type, Type interfaceType)
- {
- return type
- .GetInterfaces()
- .Where(x => x.IsGenericType ? x.GetGenericTypeDefinition() == interfaceType : x == interfaceType);
- }
- public static IEnumerable<Type> GetInterfaceDefinitions(this Type type, Type interfaceType)
- {
- foreach(var inter in type.GetInterfaces())
- {
- if (inter == interfaceType)
- {
- yield return inter;
- }
- else if (inter.IsGenericType)
- {
- var genericTypeDefinition = inter.GetGenericTypeDefinition();
- if (genericTypeDefinition == interfaceType)
- yield return genericTypeDefinition;
- }
- }
- }
- public static bool IsSubclassOfRawGeneric(this Type toCheck, Type generic)
- {
- while (toCheck != typeof(object))
- {
- var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
- if (generic == cur) return true;
- toCheck = toCheck.BaseType;
- }
- return false;
- }
- public static Type? GetSuperclassDefinition(this Type toCheck, Type generic)
- {
- while (toCheck != typeof(object))
- {
- var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
- if (generic == cur) return toCheck;
- toCheck = toCheck.BaseType;
- }
- return null;
- }
- public static bool HasAttribute<T>(this Type type) where T : Attribute => type.GetCustomAttribute<T>() != null;
- #endregion
- #region Entities + Types
- public static void RegisterClasses()
- {
- RegisterClasses(typeof(CoreUtils).Assembly);
- ImportFactory.Register(typeof(CSVImporter<>), "Comma Separated", "Comma Separated Files (*.csv)|*.csv");
- ImportFactory.Register(typeof(TabImporter<>), "Tab Delimited", "Tab-Delimited Files (*.txt)|*.txt");
- ImportFactory.Register(typeof(FixedWidthImporter<>), "Fixed Width", "Text Files (*.txt)|*.txt");
- }
- /// <summary>
- /// Register into <see cref="Entities"/> all types in <paramref name="assemblies"/> that are not abstract.
- /// </summary>
- /// <param name="assemblies"></param>
- public static void RegisterClasses(params Assembly[] assemblies)
- {
- foreach(var type in assemblies.SelectMany(x => IterateTypes(x)).Where(x => !x.IsAbstract))
- {
- entities.TryAdd(type.EntityName(), type);
- }
- }
- /// <summary>
- /// Returns a namespaced name for <paramref name="t"/>, converting also generic arguments to an angle-bracketed form.
- /// </summary>
- /// <param name="t"></param>
- /// <returns></returns>
- public static string EntityName(this Type t)
- {
- if (t.GetTypeInfo().IsGenericType)
- {
- var basename = t.FullName.Split(new[] { "[[" }, StringSplitOptions.RemoveEmptyEntries)[0];
- var types = new List<string>();
- foreach (var type in t.GenericTypeArguments)
- types.Add(type.EntityName());
- var result = string.Format("{0}<{1}>", basename, string.Join(",", types));
- return result;
- }
- if (string.IsNullOrEmpty(t.FullName))
- return t.Name;
- return t.FullName.Split(',')[0];
- }
- private static Type? FindType(string name)
- {
- return entities.GetValueOrDefault(name) ?? Type.GetType(name);
- }
- public static bool TryGetEntity(string? entityname, [NotNullWhen(true)] out Type? type)
- {
- if (string.IsNullOrWhiteSpace(entityname))
- {
- type = null;
- return false;
- }
- if (entityname.Contains("<"))
- {
- var comps = entityname.Replace(">", "").Split('<');
- var basetype = FindType(comps[0]);
- var types = new List<Type>();
- var generics = comps[1].Split(',');
- foreach (var generic in generics)
- {
- var genericArg = FindType(generic);
- if (genericArg is null)
- {
- type = null;
- return false;
- }
- types.Add(genericArg);
- }
- type = basetype?.MakeGenericType(types.ToArray());
- }
- else
- {
- type = FindType(entityname);
- }
- return type != null;
- }
- public static Type GetEntity(string entityname)
- {
- if (TryGetEntity(entityname, out var type))
- return type;
- throw new Exception($"Entity {entityname} does not exist!");
- }
- public static Type? GetEntityOrNull(string? entityname)
- {
- TryGetEntity(entityname, out var type);
- return type;
- }
- //private static List<Type> TypeCache = null;
- /// <summary>
- /// Returns a list of types that have been loaded by the various calls to RegisterClasses, e.g.
- /// CoreUtils.RegisterClasses
- /// </summary>
- /// <param name="Predicate"></param>
- /// <returns></returns>
- public static IEnumerable<Type> TypeList(Func<Type, bool> Predicate)
- {
- var result = new List<Type>();
- try
- {
- foreach (var type in entities.Values.Where(x => x != null))
- try
- {
- if (Predicate(type))
- result.Add(type);
- }
- catch (Exception e)
- {
- LogException("", e, "Error in CoreUtils.TypeList");
- }
- }
- catch (Exception e)
- {
- Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
- }
- return result;
- }
- /// <summary>
- /// Returns a list of types present within the assemblies.
- /// </summary>
- /// <param name="assemblies"></param>
- /// <param name="Predicate"></param>
- /// <returns></returns>
- public static IEnumerable<Type> IterateTypes(Assembly assembly)
- {
- Type[] types;
- try
- {
- types = assembly.GetTypes();
- }
- catch (ReflectionTypeLoadException e0)
- {
- types = e0.Types;
- }
- catch (Exception)
- {
- types = Array.Empty<Type>();
- }
- foreach (var type in types)
- {
- if (type != null)
- {
- yield return type;
- }
- }
- }
- /// <summary>
- /// Returns a list of types present within the assemblies.
- /// </summary>
- /// <param name="assemblies"></param>
- /// <param name="Predicate"></param>
- /// <returns></returns>
- public static ICollection<Type> TypeList(IEnumerable<Assembly> assemblies, Func<Type, bool> Predicate)
- {
- var result = new HashSet<Type>();
- foreach (var assembly in assemblies)
- {
- try
- {
- foreach(var type in IterateTypes(assembly).Where(Predicate))
- {
- result.Add(type);
- }
- }
- catch (Exception e)
- {
- Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
- }
- }
- return result;
- }
- #endregion
- public static object? ChangeType(object? value, Type type)
- {
- if ((value == null || value is DBNull) && type.GetTypeInfo().IsGenericType)
- return Activator.CreateInstance(type);
- if (value == null)
- return null;
- if (value is DBNull)
- return null;
- if (type == value.GetType())
- return value;
- if (type == typeof(bool))
- return value.Equals(bool.TrueString) || value.Equals(1) || value.Equals("1");
- if (type.GetTypeInfo().IsEnum)
- {
- if (value.GetType().IsArray)
- return (value as Array).Cast<object>().Select(x => Enum.ToObject(type, x)).ToArray();
- if (value is string)
- return Enum.Parse(type, value as string);
- if (value is IEnumerable<object> list)
- return list.Select(x => Enum.ToObject(type, x)).ToArray();
- return Enum.ToObject(type, value);
- }
- if (!type.GetTypeInfo().IsInterface && type.GetTypeInfo().IsGenericType)
- {
- var innerType = type.GetTypeInfo().GetGenericArguments()[0];
- var innerValue = ChangeType(value, innerType);
- return Activator.CreateInstance(type, innerValue);
- }
- if (value is string && type == typeof(Guid))
- try
- {
- return new Guid(value as string);
- }
- catch
- {
- return Guid.Empty;
- }
- if (value is IEnumerable<object> objList && type == typeof(Guid))
- return objList.Select(x => ChangeType<Guid>(x)).ToArray();
- if (value is byte[] && type == typeof(Guid))
- return new Guid(value as byte[]);
- if (value is string && type == typeof(Version))
- return new Version(value as string);
- if (value is byte && type == typeof(TimeSpan))
- return new TimeSpan((byte)value);
- if (value is string && type == typeof(TimeSpan))
- return TimeSpan.Parse(value as string);
- if (value is string && type == typeof(DateTime))
- return DateTime.Parse(value as string);
- if (value is bool && type == typeof(string))
- return (bool)value ? bool.TrueString : bool.FalseString;
- if (value is JArray && type == typeof(string[]))
- return (value as JArray).Select(x => x.ToString()).ToArray();
- if (value is string && type == typeof(byte[]))
- return Convert.FromBase64String(value as string);
- if(value is FilterConstant constant)
- {
- if (type == typeof(DateTime))
- {
- if (Equals(FilterConstant.Null, value))
- return DateTime.MinValue;
- return value;
- }
- if (type == typeof(Guid) && constant == FilterConstant.Null)
- {
- return Guid.Empty;
- }
- if (type == typeof(double))
- {
- return value;
- // if (Equals(FilterConstant.Zero, value))
- // return (double)0;
- }
- if (type == typeof(int))
- {
- return value;
- // if (Equals(FilterConstant.Zero, value))
- // return 0;
- }
- }
- if (type == typeof(String))
- return value?.ToString() ?? "";
-
- if (!(value is IConvertible))
- return value;
- return Convert.ChangeType(value, type);
- }
- [return: MaybeNull]
- public static T ChangeType<T>(object? value)
- {
- var newValue = ChangeType(value, typeof(T));
- if (newValue is T tValue)
- return tValue;
- return default;
- }
- public static string RandomHexString(int length)
- {
- var rdm = new Random((int)DateTime.Now.Ticks);
- var hexValue = "";
- int num;
- for (var i = 0; i < length; i++)
- {
- num = rdm.Next(0, 16);
- hexValue += num.ToString("X1");
- }
- return hexValue;
- }
- public static bool IsEmpty(this DateTime value)
- {
- return value.Ticks <= DateTime.MinValue.AddHours(8).Ticks;
- }
- #region Properties
- public static string GetFullPropertyName<Type, TProperty>(Expression<Func<Type, TProperty>> exp, string separator)
- {
- try
- {
- if (!TryFindMemberExpression(exp.Body, out var memberExp))
- return "";
- return GetFullPropertyName(memberExp, separator);
- }
- catch (Exception e)
- {
- throw e;
- }
- }
- public static string GetFullPropertyName(MemberExpression exp, string separator)
- {
- try
- {
- var currentExpression = exp;
- var memberNames = new Stack<string>();
- do
- {
- memberNames.Push(currentExpression.Member.Name);
- } while (TryFindMemberExpression(currentExpression.Expression, out currentExpression));
- var result = string.Join(separator, memberNames.ToArray());
- return result;
- }
- catch (Exception e)
- {
- throw e;
- }
- }
- // code adjusted to prevent horizontal overflow
- public static bool TryFindMemberExpression(Expression exp, [NotNullWhen(true)] out MemberExpression? memberExp)
- {
- memberExp = exp as MemberExpression;
- if (memberExp != null)
- return true;
- if (IsConversion(exp) && exp is UnaryExpression unary)
- {
- memberExp = unary.Operand as MemberExpression;
- if (memberExp != null)
- return true;
- }
- return false;
- }
- public static Expression<Func<T, TType>> GetPropertyExpression<T, TType>(string name)
- {
- var param = Expression.Parameter(typeof(T), "x");
- Expression body = param;
- foreach (var member in name.Split('.')) body = Expression.PropertyOrField(body, member);
- var p = Expression.Parameter(typeof(TType));
- var conversion = body.Type == typeof(TType) ? body : Expression.Convert(body, typeof(TType));
- return Expression.Lambda<Func<T, TType>>(conversion, param);
- }
- public static Expression<Func<T, object?>> GetPropertyExpression<T>(string name)
- {
- var param = Expression.Parameter(typeof(T), "x");
- Expression body = param;
- foreach (var member in name.Split('.')) body = Expression.PropertyOrField(body, member);
- var p = Expression.Parameter(typeof(object));
- var conversion = Expression.Convert(body, typeof(object));
- return Expression.Lambda<Func<T, object?>>(conversion, param);
- }
- public static MemberExpression GetMemberExpression(Type t, string name)
- {
- var param = Expression.Parameter(t, "x");
- Expression body = param;
- foreach (var member in name.Split('.'))
- body = Expression.PropertyOrField(body, member);
- var me = Expression.Lambda(body, param).Body as MemberExpression;
- return me;
- }
- public static Expression GetPropertyExpression(Type t, string name, Type? type = null)
- {
- var param = Expression.Parameter(t, "x");
- Expression body = param;
- foreach (var member in name.Split('.')) body = Expression.PropertyOrField(body, member);
- if (type != null)
- body = Expression.Convert(body, typeof(object));
- return Expression.Lambda(body, param);
- //var p2 = Expression.Parameter(t, "x");
- //Expression e2 = Expression.Lambda(Expression.Property(p2, name), p2);
- //return e2;
- }
- public static PropertyInfo GetProperty(Type t, string name)
- {
- if (TryGetProperty(t, name, out var info))
- return info;
- throw new Exception($"Property {name} does not exist for {t.Name}");
- }
- public static PropertyInfo GetProperty<T>(string name) => GetProperty(typeof(T), name);
- public static bool TryGetProperty(Type t, string name, [NotNullWhen(true)] out PropertyInfo? propertyInfo)
- {
- propertyInfo = null;
- var typeinfo = t.GetTypeInfo();
- var props = name.Split('.');
- foreach (var prop in props)
- {
- propertyInfo = typeinfo.GetProperty(prop);
- if (propertyInfo is null)
- return false;
- typeinfo = propertyInfo.PropertyType.GetTypeInfo();
- }
- if (propertyInfo is null)
- return false;
- return true;
- }
- public static bool TryGetProperty<T>(string name, [NotNullWhen(true)] out PropertyInfo? propertyInfo) =>
- TryGetProperty(typeof(T), name, out propertyInfo);
- public static bool HasProperty(Type t, string name)
- {
- PropertyInfo property;
- var typeinfo = t.GetTypeInfo();
- var props = name.Split('.');
- foreach (var prop in props)
- {
- property = typeinfo.GetProperty(prop);
- if (property == null)
- return false;
- typeinfo = property.PropertyType.GetTypeInfo();
- }
- return true;
- }
- public static object? GetPropertyParent(object o, string name)
- {
- var comps = name.Split('.').ToList();
- comps.Remove(comps.Last());
- if (comps.Count == 0)
- return o;
- return GetPropertyValue(o, string.Join(".", comps));
- }
- /// <summary>
- /// Gets the value of the object's given property.
- /// </summary>
- /// <param name="o">The object to get the property from.</param>
- /// <param name="name">The name of the property.</param>
- /// <returns>
- /// <see langword="null"/> if <paramref name="o"/> or any intermediate properties are <see langword="null"/>;
- /// otherwise the value of the property <paramref name="name"/>, which can be <see langword="null"/>.
- /// </returns>
- /// <exception cref="Exception">if the property does not exist.</exception>
- public static object? GetPropertyValue(object? o, string name)
- {
- if (o is null)
- return null;
- var t = o.GetType().GetTypeInfo();
- if (o is BaseObject)
- {
- var property = DatabaseSchema.Property(t, name);
- if (property != null && (property is CustomProperty || !name.Contains(".")))
- return property.Getter().Invoke(o);
- }
- var props = name.Split('.');
- foreach (var prop in props)
- {
- var rprop = t.GetProperty(prop) ?? throw new Exception(string.Format("Property {0} does not exist for {1}", prop, o.GetType().Name));
- o = rprop.GetValue(o, null);
- if (o is null)
- return null;
- t = o.GetType().GetTypeInfo();
- }
- return o;
- }
- /// <summary>
- /// Sets a property on the given object, doing nothing if the property does not exist.
- /// </summary>
- /// <param name="o">The object to set the property of.</param>
- /// <param name="name">The property to set.</param>
- /// <param name="value">The value to set the property to.</param>
- public static void SetPropertyValue(object o, string name, object? value)
- {
- var bits = name.Split('.');
- for (var i = 0; i < bits.Length - 1; i++)
- {
- var propertyToGet = o.GetType().GetTypeInfo().GetProperty(bits[i]);
- if (propertyToGet == null)
- return;
- var newo = propertyToGet.GetValue(o, null);
- if (newo == null)
- {
- newo = Activator.CreateInstance(propertyToGet.PropertyType);
- propertyToGet.SetValue(o, newo);
- }
- o = newo;
- }
- var propertyToSet = o.GetType().GetTypeInfo().GetProperty(bits.Last());
- if (propertyToSet is null)
- {
- var iprop = DatabaseSchema.Property(o.GetType(), name);
- if (iprop is CustomProperty)
- {
- ((BaseObject)o).UserProperties[name] = value;
- return;
- }
- return;
- }
- //PropertyInfo propertyToSet = GetProperty(o.GetType(), name);
- object? convertedvalue = null;
- if (value != null)
- {
- if (propertyToSet.PropertyType.Equals(typeof(Type)))
- {
- convertedvalue = Type.GetType(value.ToString(), true, true);
- }
- else if (propertyToSet.PropertyType.GetTypeInfo().IsEnum)
- {
- convertedvalue = Enum.Parse(propertyToSet.PropertyType, value.ToString(), true);
- }
- //else if (propertyToSet.PropertyType.Equals(typeof(Memo)))
- // convertedvalue = (Memo)value.ToString();
- else if (propertyToSet.PropertyType.Equals(typeof(Guid)))
- {
- var guidvalue = Guid.Empty;
- Guid.TryParse(value.ToString(), out guidvalue);
- convertedvalue = guidvalue;
- }
- //else if (propertyToSet.PropertyType.IsSubclassOf(value.GetType()))
- // convertedvalue = value;
- else if (propertyToSet.PropertyType.IsAssignableFrom(value.GetType()))
- {
- convertedvalue = value;
- }
- else if (!(value is DBNull))
- {
- convertedvalue = Convert.ChangeType(value, propertyToSet.PropertyType);
- }
- }
- if (propertyToSet.CanWrite)
- {
- var method = propertyToSet.GetSetMethod();
- //if (method == null)
- var oldval = propertyToSet.GetValue(o);
- propertyToSet.SetValue(o, convertedvalue, null);
- if (o is BaseObject)
- ((BaseObject)o).OnPropertyChanged(propertyToSet.Name, oldval, convertedvalue);
- //else
- // method.Invoke(o, new Object[] { convertedvalue });
- //if (o.GetType().IsSubclassOf(typeof(BaseObject)))
- // ((BaseObject)o).OnPropertyChanged(name, propertyToSet.GetValue(o), convertedvalue);
- }
- }
-
- public static PropertyInfo[] GetInheritedProperties(Type type)
- {
- if (type.IsInterface)
- {
- var propertyInfos = new List<PropertyInfo>();
- var considered = new List<Type>();
- var queue = new Queue<Type>();
- considered.Add(type);
- queue.Enqueue(type);
- while (queue.Count > 0)
- {
- var subType = queue.Dequeue();
- foreach (var subInterface in subType.GetInterfaces())
- {
- if (considered.Contains(subInterface)) continue;
- considered.Add(subInterface);
- queue.Enqueue(subInterface);
- }
- var typeProperties = subType.GetProperties(
- BindingFlags.FlattenHierarchy
- | BindingFlags.Public
- | BindingFlags.Instance);
- var newPropertyInfos = typeProperties
- .Where(x => !propertyInfos.Contains(x));
- propertyInfos.InsertRange(0, newPropertyInfos);
- }
- return propertyInfos.ToArray();
- }
-
- return type.GetProperties(BindingFlags.FlattenHierarchy
- | BindingFlags.Public | BindingFlags.Instance);
- }
- public static Dictionary<string, Type> PropertyList(Type T, Func<PropertyInfo, bool> Predicate, bool Recursive)
- {
- Dictionary<string, Type> properties;
- if (T.GetTypeInfo().BaseType != null)
- properties = PropertyList(T.GetTypeInfo().BaseType, Predicate, Recursive);
- else
- properties = new Dictionary<string, Type>();
- //TypeInfo entitytype = typeof(Entity).GetTypeInfo();
- //TypeInfo componenttype = typeof(EnclosedEntity).GetTypeInfo();
- foreach (var prop in T.GetRuntimeProperties())
- // '.' contains check for explicit implementation of interface properties
- if (!properties.ContainsKey(prop.Name) && Predicate(prop) && !prop.Name.Contains('.'))
- {
- var propertytype = prop.PropertyType.GetTypeInfo();
- if (
- Recursive &&
- (
- propertytype.IsSubclassOf(typeof(Entity)) ||
- propertytype.GetInterfaces().Contains(typeof(IEnclosedEntity)) ||
- propertytype.GetInterfaces().Contains(typeof(IEntityLink))
- )
- )
- {
- var props = PropertyList(prop.PropertyType, Predicate, Recursive);
- foreach (var key in props.Keys) properties[string.Format("{0}.{1}", prop.Name, key)] = props[key];
- }
- else
- {
- properties[prop.Name] = prop.PropertyType;
- }
- }
- return properties;
- }
- public static Dictionary<string, PropertyInfo> PropertyInfoList(Type T, Func<PropertyInfo, bool> Predicate, bool Recursive)
- {
- Dictionary<string, PropertyInfo> properties;
- if (T.GetTypeInfo().BaseType != null)
- properties = PropertyInfoList(T.GetTypeInfo().BaseType, Predicate, Recursive);
- else
- properties = new Dictionary<string, PropertyInfo>();
- //TypeInfo entitytype = typeof(Entity).GetTypeInfo();
- //TypeInfo componenttype = typeof(EnclosedEntity).GetTypeInfo();
- foreach (var prop in T.GetRuntimeProperties())
- // '.' contains check for explicit implementation of interface properties
- if (!properties.ContainsKey(prop.Name) && Predicate(prop) && !prop.Name.Contains('.'))
- {
- var propertytype = prop.PropertyType.GetTypeInfo();
- if (
- Recursive &&
- (
- propertytype.IsSubclassOf(typeof(Entity)) ||
- propertytype.GetInterfaces().Contains(typeof(IEnclosedEntity)) ||
- propertytype.GetInterfaces().Contains(typeof(IEntityLink))
- )
- )
- {
- var props = PropertyInfoList(prop.PropertyType, Predicate, Recursive);
- foreach (var key in props.Keys) properties[string.Format("{0}.{1}", prop.Name, key)] = props[key];
- }
- else
- {
- properties[prop.Name] = prop;
- }
- }
- return properties;
- }
- public static IEnumerable<PropertyInfo> PropertyList(Type T, Func<PropertyInfo, bool> Predicate)
- {
- return T.GetRuntimeProperties().Where(x => Predicate(x));
- }
- private static PropertyInfo InternalGetPropertyFromExpression<TObject, TType>(Expression<Func<TObject, TType>> GetPropertyLambda)
- {
- MemberExpression Exp;
- //this line is necessary, because sometimes the expression comes in as Convert(originalexpression)
- if (GetPropertyLambda.Body is UnaryExpression unary)
- {
- Exp = unary.Operand as MemberExpression ?? throw new ArgumentException();
- }
- else if (GetPropertyLambda.Body is MemberExpression)
- {
- Exp = (MemberExpression)GetPropertyLambda.Body;
- }
- else
- {
- throw new ArgumentException();
- }
- return (PropertyInfo)Exp.Member;
- }
- public static PropertyInfo GetPropertyFromExpression<TObject, TStruct>(Expression<Func<TObject, TStruct>> lambda)
- {
- return InternalGetPropertyFromExpression(lambda);
- }
- public static PropertyInfo GetPropertyFromExpression<T>(Expression<Func<T, object>> GetPropertyLambda)
- {
- MemberExpression Exp;
- //this line is necessary, because sometimes the expression comes in as Convert(originalexpression)
- if (GetPropertyLambda.Body is UnaryExpression)
- {
- var UnExp = (UnaryExpression)GetPropertyLambda.Body;
- if (UnExp.Operand is MemberExpression)
- Exp = (MemberExpression)UnExp.Operand;
- else
- throw new ArgumentException();
- }
- else if (GetPropertyLambda.Body is MemberExpression)
- {
- Exp = (MemberExpression)GetPropertyLambda.Body;
- }
- else
- {
- throw new ArgumentException();
- }
- return (PropertyInfo)Exp.Member;
- }
- #endregion
- public static bool IsCollection(PropertyInfo prop)
- {
- if (!typeof(string).Equals(prop.PropertyType))
- if (typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(prop.PropertyType))
- if (!prop.PropertyType.IsArray)
- if (prop.PropertyType.GenericTypeArguments[0].GetTypeInfo().IsSubclassOf(typeof(Entity)))
- return true;
- return false;
- }
- private static bool IsConversion(Expression exp)
- {
- return exp.NodeType == ExpressionType.Convert ||
- exp.NodeType == ExpressionType.ConvertChecked;
- }
- //public static Dictionary<String, Type> PropertyList(Type T, bool Public = true, bool Static = false)
- //{
- // Dictionary<String, Type> properties = new Dictionary<String, Type>();
- // foreach (PropertyInfo prop in T.GetRuntimeProperties())
- // {
- // if ((prop.GetMethod.IsPublic == Public) && (prop.GetMethod.IsStatic == Static))
- // {
- // if (prop.PropertyType.GetTypeInfo().IsAssignableFrom(typeof(Entity).GetTypeInfo()))
- // {
- // Dictionary<String, Type> props = PropertyList(prop.PropertyType);
- // foreach (String key in props.Keys)
- // {
- // properties[String.Format("{0}.{1}", prop.Name, key)] = props[key];
- // }
- // }
- // else if (!prop.PropertyType.Equals(typeof(Guid)))
- // {
- // properties[prop.Name] = prop.GetType();
- // }
- // }
- // }
- // return properties;
- //}
-
- /// <summary>
- /// Get all the child properties of an object that match a given type
- /// </summary>
- /// <typeparam name="T">The class of property to search for</typeparam>
- /// <param name="parent">The object to search</param>
- /// <returns>A list of the objects found</returns>
- public static IEnumerable<PropertyInfo> GetChildrenProperties<T>(Type parentType)
- {
- return PropertyList(
- parentType,
- x => typeof(T).IsAssignableFrom(x.PropertyType)
- );
- }
- /// <summary>
- /// Get all the child properties of an object that match a given type
- /// </summary>
- /// <typeparam name="T">The class of property to search for</typeparam>
- /// <param name="parent">The object to search</param>
- /// <returns>A list of the objects found</returns>
- public static IEnumerable<T> GetChildren<T>(object parent)
- {
- var props = PropertyList(
- parent.GetType(),
- x => typeof(T).IsAssignableFrom(x.PropertyType)
- );
- foreach (var prop in props)
- {
- var child = (T)prop.GetValue(parent);
- if (child != null)
- yield return child;
- }
- }
- /// <summary>
- /// Get all list properties of an object that are collections of a given type
- /// </summary>
- /// <typeparam name="T">The class of child object to search for</typeparam>
- /// <param name="parent">The object to search</param>
- /// <returns>A list of the collections found</returns>
- public static IEnumerable<TType>[] GetCollectionsOfType<TType>(object parent)
- {
- var lists = new List<IEnumerable<TType>>();
- var props = PropertyList(parent.GetType(), x => true); // !typeof(String).Equals(x.PropertyType));
- foreach (var prop in props)
- if (typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(prop.PropertyType))
- if (prop.PropertyType.GenericTypeArguments.Length == 1)
- if (prop.PropertyType.GenericTypeArguments[0].GetTypeInfo().GetInterfaces().Contains(typeof(TType)))
- lists.Add((IEnumerable<TType>)prop.GetValue(parent));
- return lists.ToArray();
- }
- //public static IEnumerable<Assembly> GetReferencingAssemblies(string assemblyName)
- //{
- // var assemblies = new List<Assembly>();
- // var dependencies = DependencyContext.Default.RuntimeLibraries;
- // foreach (var library in dependencies)
- // {
- // if (IsCandidateLibrary(library, assemblyName))
- // {
- // var assembly = Assembly.Load(new AssemblyName(library.Name));
- // assemblies.Add(assembly);
- // }
- // }
- // return assemblies;
- //}
- //private static bool IsCandidateLibrary(RuntimeLibrary library, assemblyName)
- //{
- // return library.Name == (assemblyName)
- // || library.Dependencies.Any(d => d.Name.StartsWith(assemblyName));
- //}
- //public static IEnumerable<Assembly> AssemblyList(Expression<Func<Type,bool>> Predicate)
- //{
- // Func<Type, bool> lambda = Predicate.Compile();
- // List<Assembly> assemblies = new List<Assembly>();
- // IEnumerable<Assembly> allassemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).ToArray();
- // foreach (Assembly assembly in allassemblies)
- // {
- // IEnumerable<Type> types = CoreUtils.TypeList(
- // new Assembly[] { assembly },
- // Predicate
- // );
- // if (types.Count() > 0)
- // assemblies.Add(assembly);
- // }
- // return assemblies;
- //}
- //public static string SerializeExpression<T>(Expression obj)
- //{
- // JsonSerializerSettings _settings;
- // var defaultSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects };
- // defaultSettings.Converters.Add(new ExpressionJsonConverter(typeof(T)));
- // _settings = defaultSettings;
- // return Serialization.Serialize(obj, _settings);
- //}
- //public static Expression DeserializeExpression<T>(string json)
- //{
- // JsonSerializerSettings _settings;
- // var defaultSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects };
- // defaultSettings.Converters.Add(new ExpressionJsonConverter(typeof(T)));
- // _settings = defaultSettings;
- // return Serialization.Deserialize<Expression>(json, _settings);
- //}
- /// <summary>
- /// [ <c>public static object GetDefault(this Type type)</c> ]
- /// <para></para>
- /// Retrieves the default value for a given Type
- /// </summary>
- /// <param name="type">The Type for which to get the default value</param>
- /// <returns>The default value for <paramref name="type" /></returns>
- /// <remarks>
- /// If a null Type, a reference Type, or a System.Void Type is supplied, this method always returns null. If a value
- /// type
- /// is supplied which is not publicly visible or which contains generic parameters, this method will fail with an
- /// exception.
- /// </remarks>
- /// <example>
- /// To use this method in its native, non-extension form, make a call like:
- /// <code>
- /// object Default = DefaultValue.GetDefault(someType);
- /// </code>
- /// To use this method in its Type-extension form, make a call like:
- /// <code>
- /// object Default = someType.GetDefault();
- /// </code>
- /// </example>
- /// <seealso cref="GetDefault<T>" />
- public static object? GetDefault(this Type type)
- {
- // If no Type was supplied, if the Type was a reference type, or if the Type was a System.Void, return null
- if (type == null || !type.GetTypeInfo().IsValueType || type == typeof(void))
- return null;
- // If the supplied Type has generic parameters, its default value cannot be determined
- if (type.GetTypeInfo().ContainsGenericParameters)
- throw new ArgumentException(
- "Error:\n\nThe supplied value type <" + type.Name +
- "> contains generic parameters, so the default value cannot be retrieved\n\n");
- // If the Type is a primitive type, or if it is another publicly-visible value type (i.e. struct/enum), return a
- // default instance of the value type
- if (type.GetTypeInfo().IsPrimitive || !type.GetTypeInfo().IsNotPublic)
- try
- {
- return Activator.CreateInstance(type);
- }
- catch (Exception e)
- {
- throw new ArgumentException(
- "Error:\n\nThe Activator.CreateInstance method could not " +
- "create a default instance of the supplied value type <" + type.Name +
- "> (Inner Exception message: \"" + e.Message + "\")");
- }
- // Fail with exception
- throw new ArgumentException("Error:\n\nThe supplied value type <" + type +
- "> is not a publicly-visible type, so the default value cannot be retrieved");
- }
- /// <summary>
- /// [ <c>public static T GetDefault< T >()</c> ]
- /// <para></para>
- /// Retrieves the default value for a given Type
- /// </summary>
- /// <typeparam name="T">The Type for which to get the default value</typeparam>
- /// <returns>The default value for Type T</returns>
- /// <remarks>
- /// If a reference Type or a System.Void Type is supplied, this method always returns null. If a value type
- /// is supplied which is not publicly visible or which contains generic parameters, this method will fail with an
- /// exception.
- /// </remarks>
- /// <seealso cref="GetDefault(Type)" />
- [return: MaybeNull]
- public static T GetDefault<T>()
- {
- return (T)GetDefault(typeof(T));
- }
- public static bool IsDefault<T>(T value)
- {
- return IsDefault(typeof(T), value);
- }
- /// <summary>
- /// [ <c>public static bool IsObjectSetToDefault(this Type ObjectType, object ObjectValue)</c> ]
- /// <para></para>
- /// Reports whether a value of type T (or a null reference of type T) contains the default value for that Type
- /// </summary>
- /// <remarks>
- /// Reports whether the object is empty or unitialized for a reference type or nullable value type (i.e. is null) or
- /// whether the object contains a default value for a non-nullable value type (i.e. int = 0, bool = false, etc.)
- /// <para></para>
- /// NOTE: For non-nullable value types, this method introduces a boxing/unboxing performance penalty.
- /// </remarks>
- /// <param name="ObjectType">Type of the object to test</param>
- /// <param name="ObjectValue">The object value to test, or null for a reference Type or nullable value Type</param>
- /// <returns>
- /// true = The object contains the default value for its Type.
- /// <para></para>
- /// false = The object has been changed from its default value.
- /// </returns>
- public static bool IsDefault(this Type ObjectType, object? ObjectValue)
- {
- // If no ObjectType was supplied, attempt to determine from ObjectValue
- if (ObjectType == null)
- {
- // If no ObjectValue was supplied, abort
- if (ObjectValue == null) throw new ArgumentNullException("Error:\n\nCannot determine the ObjectType from a null Value");
- // Determine ObjectType from ObjectValue
- ObjectType = ObjectValue.GetType();
- }
- // Get the default value of type ObjectType
- var Default = ObjectType.GetDefault();
- // If a non-null ObjectValue was supplied, compare Value with its default value and return the result
- if (ObjectValue != null)
- return ObjectValue.Equals(Default);
- // Since a null ObjectValue was supplied, report whether its default value is null
- return Default == null;
- }
- //public static TimeSpan Round(this TimeSpan timespan, TimeSpan interval)
- //{
- // // The round number, here is a quarter... in seconds
- // double Round = interval.TotalSeconds;
- // // Count of round number in this total Seconds...
- // double CountRound = (timespan.TotalSeconds / Round);
- // // The main formula to calculate round time...
- // int Sec = (int)(Math.Truncate(CountRound + 0.5) * Round);
- // // Now show the result...
- // TimeSpan tRes = new TimeSpan(0, 0, Sec);
- // return tRes;
- //}
- public static bool IsNumeric(this Type dataType)
- {
- return dataType.IsFloatingPoint() || dataType.IsOrdinal();
- }
- public static bool IsFloatingPoint(this Type dataType)
- {
- if (dataType == null)
- return false;
- return dataType == typeof(double)
- || dataType == typeof(float)
- || dataType == typeof(float);
- }
- public static bool IsOrdinal(this Type dataType)
- {
- if (dataType == null)
- return false;
- return dataType == typeof(int)
- || dataType == typeof(long)
- || dataType == typeof(short)
- || dataType == typeof(short)
- || dataType == typeof(int)
- || dataType == typeof(long)
- || dataType == typeof(uint)
- || dataType == typeof(ushort)
- || dataType == typeof(uint)
- || dataType == typeof(ulong)
- || dataType == typeof(sbyte);
- }
- //Extension method for MailMessage to save to a file on disk
- public static string GenerateEMLFile(this MailMessage message, bool addUnsentHeader = true)
- {
- var filename = Path.ChangeExtension(Path.GetTempFileName(), ".eml");
- using (var filestream = File.Open(filename, FileMode.Create))
- {
- if (addUnsentHeader)
- {
- var binaryWriter = new BinaryWriter(filestream);
- //Write the Unsent header to the file so the mail client knows this mail must be presented in "New message" mode
- binaryWriter.Write(Encoding.UTF8.GetBytes("X-Unsent: 1" + Environment.NewLine));
- }
- var assembly = typeof(SmtpClient).Assembly;
- var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
- // Get reflection info for MailWriter contructor
- var mailWriterContructor =
- mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
- // Construct MailWriter object with our FileStream
- var mailWriter = mailWriterContructor.Invoke(new object[] { filestream });
- // Get reflection info for Send() method on MailMessage
- var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
- sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null);
- // Finally get reflection info for Close() method on our MailWriter
- var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);
- // Call close method
- closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
- }
- return filename;
- }
- public static Columns<T> GetColumns<T>(Columns<T>? columns)
- => (GetColumns(typeof(T), columns) as Columns<T>)!;
-
- public static IColumns GetColumns(Type T, IColumns? columns)
- {
- //var cols = columns;
- if (columns == null || columns.Count == 0)
- {
- if (!_columnscache.TryGetValue(T, out var result))
- {
- result = Columns.None(T);
- var props = PropertyList(T,
- x =>
- x.GetCustomAttribute<DoNotSerialize>() == null &&
- x.GetCustomAttribute<DoNotPersist>() == null &&
- x.CanWrite && x.PropertyType != typeof(UserProperties), true);
- foreach (var prop in props)
- result.Add(prop.Key);
- var custom = DatabaseSchema.Properties(T).Where(x => x is CustomProperty);
- foreach (var prop in custom)
- result.Add(prop.Name);
- _columnscache[T] = result;
- }
- return result;
- }
- return columns;
- //{
- // foreach (var col in cols.Items)
- // {
- // try
- // {
- // result.Add(col.Property);
- // //PropertyInfo prop = null;
- // //IProperty iprop = null;
- // //if (col.Property != null)
- // //{
- // // try
- // // {
- // // iprop = DatabaseSchema.Property(typeof(T), col.Property);
- // // }
- // // catch (Exception e2)
- // // {
- // // }
- // // if ((iprop != null) && (iprop is CustomProperty))
- // // result.Add(col.Property);
- // // else
- // // {
- // // prop = CoreUtils.GetProperty(typeof(T), col.Property);
- // // if ((prop.GetCustomAttribute<DoNotSerialize>() == null) && (prop.GetCustomAttribute<DoNotPersist>() == null) && prop.CanWrite)
- // // result.Add(col.Property);
- // // }
- // //}
- // //else
- // //{
- // // String property = CoreUtils.GetFullPropertyName((MemberExpression)col.Expression, ".");
- // // prop = CoreUtils.GetProperty(typeof(T), property);
- // // if ((prop.GetCustomAttribute<DoNotSerialize>() == null) && (prop.GetCustomAttribute<DoNotPersist>() == null) && prop.CanWrite)
- // // result.Add(property);
- // //}
- // }
- // catch (Exception e)
- // {
- // }
- // }
- //}
- //return result;
- }
- public static List<string> GetColumnNames(Type T, Func<PropertyInfo, bool> Predicate)
- {
- //var cols = columns;
- var result = new List<string>();
- var props = PropertyList(T,
- x =>
- x.GetCustomAttribute<DoNotSerialize>() == null &&
- x.GetCustomAttribute<DoNotPersist>() == null &&
- x.CanWrite && x.PropertyType != typeof(UserProperties) && Predicate(x), true);
- foreach (var prop in props)
- result.Add(prop.Key);
- var custom = DatabaseSchema.Properties(T).Where(x => x is CustomProperty);
- foreach (var prop in custom)
- result.Add(prop.Name);
- return result;
- }
- public static string TypedValueToString(object value)
- {
- var type = value.GetType();
- var Culture = CultureInfo.CurrentCulture;
- if (type == typeof(string))
- return (string)value;
- if (type == typeof(string[]))
- return Serialization.Serialize(value);
- if (IsNumeric(type))
- return string.Format(Culture.NumberFormat, "{0}", value);
- // TimeSpan - use constant pattern
- if (type == typeof(TimeSpan))
- return string.Format("{0:c}", value);
- // DateTime - use round-trip pattern
- if (type == typeof(DateTime))
- return string.Format("{0:o}", value);
- if (type == typeof(Guid))
- return ((Guid)value).ToString();
- var converter = TypeDescriptor.GetConverter(type);
- if (converter != null && converter.CanConvertTo(typeof(string)))
- return converter.ConvertToString(value);
- throw new Exception(string.Format("Cannot Convert {0} to String", type.Name));
- }
- public static object? StringToTypedValue(string value, Type type)
- {
- var Culture = CultureInfo.CurrentCulture;
- if (type == typeof(object) && string.IsNullOrEmpty(value))
- return null;
- if (type == typeof(string))
- return value;
- if (type == typeof(string[]))
- return Serialization.Deserialize<string[]>(value);
- if (type == typeof(sbyte))
- return sbyte.Parse(value, NumberStyles.Integer, Culture);
- if (type == typeof(byte))
- return byte.Parse(value, NumberStyles.Integer, Culture);
- if (type == typeof(ushort))
- return ushort.Parse(value, NumberStyles.Integer, Culture);
- if (type == typeof(uint))
- return uint.Parse(value, NumberStyles.Integer, Culture);
- if (type == typeof(ulong))
- return ulong.Parse(value, NumberStyles.Integer, Culture);
- if (type == typeof(short))
- return short.Parse(value, NumberStyles.Integer, Culture);
- if (type == typeof(int))
- return int.Parse(value, NumberStyles.Integer, Culture);
- if (type == typeof(long))
- return long.Parse(value, NumberStyles.Integer, Culture);
- if (type == typeof(float))
- return float.Parse(value, NumberStyles.Any, Culture);
- if (type == typeof(double))
- return double.Parse(value, NumberStyles.Any, Culture);
- if (type == typeof(decimal))
- return decimal.Parse(value, NumberStyles.Any, Culture);
- if (type == typeof(TimeSpan))
- return TimeSpan.ParseExact(value, "c", null);
- if (type == typeof(DateTime))
- return DateTime.ParseExact(value, "o", null);
- if (type == typeof(Guid))
- return Guid.Parse(value);
- var converter = TypeDescriptor.GetConverter(type);
- if (converter != null && converter.CanConvertFrom(typeof(string)))
- return converter.ConvertFromString(value);
- throw new Exception(string.Format("Cannot Convert String to {0}", type.Name));
- }
- public static bool ContainsInheritedGenericType(this Type type, Type generic)
- {
- if (type == null)
- return false;
- if (type.GenericTypeArguments.Contains(generic))
- return true;
- if (type.BaseType == null)
- return false;
- return type.BaseType.ContainsInheritedGenericType(generic);
- }
- public static IEnumerable<Type> GetInheritedGenericTypeArguments(this Type type)
- {
- if (type == null)
- return new Type[] { };
- if (type.GetGenericArguments().Any())
- return type.GenericTypeArguments;
- if (type.BaseType == null)
- return new Type[] { };
- return type.BaseType.GetInheritedGenericTypeArguments();
- }
- //static readonly Regex StripQuotes = new Regex(@""", RegexOptions.Compiled);
-
-
- public static string GetCaption(this Type type, bool usedefault = true)
- {
- var attribute = type.GetCustomAttribute<Caption>();
- var result = attribute != null
- ? attribute.Text
- : usedefault
- ? type.Name
- : "";
- return result;
- }
- public static string? GetCaptionOrNull(this Type type, bool inherit = false)
- {
- return type.GetCustomAttribute<Caption>(inherit)?.Text;
- }
- public static string SanitiseFileName(string filename)
- {
- var invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
- var invalidReStr = string.Format(@"[{0}]+", invalidChars);
- var reservedWords = new[]
- {
- "CON", "PRN", "AUX", "CLOCK$", "NUL", "COM0", "COM1", "COM2", "COM3", "COM4",
- "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4",
- "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
- };
- var sanitisedNamePart = Regex.Replace(filename, invalidReStr, "_");
- foreach (var reservedWord in reservedWords)
- {
- var reservedWordPattern = string.Format("^{0}\\.", reservedWord);
- sanitisedNamePart = Regex.Replace(sanitisedNamePart, reservedWordPattern, "_reservedWord_.", RegexOptions.IgnoreCase);
- }
- return sanitisedNamePart;
- }
- public static decimal GetPropertySequence(Type type, string column)
- {
- return DatabaseSchema.Property(type, column)?.PropertySequence() ?? 999;
- }
- /// <summary>
- /// Gets the AppData folder for this application.
- /// </summary>
- /// <returns>The path of the AppData folder.</returns>
- public static string GetPath()
- {
- if (Assembly.GetEntryAssembly() != null)
- return Path.Combine(
- Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
- Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)
- );
- return Path.Combine(
- Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
- Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location)
- );
- }
- public static string GetCommonAppData(string? folderName = null)
- {
- folderName ??= Assembly.GetEntryAssembly() != null
- ? Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)
- : Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location);
- return Path.Combine(
- Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
- folderName
- );
- }
- public static string GetVersion()
- {
- // 2022-10-13 FVB First look in the executable directory
- var curfile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "version.txt");
- if (File.Exists(curfile))
- return File.ReadAllText(curfile);
-
- // Then look in the app data directory if you cannot find it
- curfile = Path.Combine(GetPath(), "version.txt");
- if (File.Exists(curfile))
- return File.ReadAllText(curfile);
-
- return "???";
-
- }
- public static string SplitCamelCase(this string value)
- {
- return string.Join(" ", Regex.Split(value, @"(?<!^)(?=[A-Z](?![A-Z]|$))")).Replace(" ", " ");
- }
- public static bool IsEffectivelyEqual(this double a, double b, double threshold = 0.00001F)
- {
- return Math.Abs(a - b) < threshold;
- }
-
- public static bool IsEffectivelyGreaterThan(this double a, double b, double threshold = 0.00001F)
- {
- return a - b > threshold;
- }
-
- public static bool IsEffectivelyLessThan(this double a, double b, double threshold = 0.00001F)
- {
- return b - a > threshold;
- }
-
- public static bool IsEntityLinkValid<T, U>(this CoreRow arg, Expression<Func<T, U>> expression) where U : IEntityLink
- {
- var col = CoreUtils.GetFullPropertyName(expression, ".");
- return arg.Get<Guid>(col + ".ID") != Guid.Empty && arg.Get<Guid>(col + ".Deleted") == Guid.Empty;
- }
- /// <summary>
- /// 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}})"/>)
- /// </summary>
- /// <typeparam name="T">The entity type</typeparam>
- /// <typeparam name="U">The entity link type</typeparam>
- /// <param name="arg">The row representing the entity of type <typeparamref name="T"/></param>
- /// <param name="expression">An expression to the entity link of type <typeparamref name="U"/></param>
- /// <returns>The ID on the entity link, or <c>null</c> if the entity link is invalid</returns>
- public static Guid? EntityLinkID<T, U>(this CoreRow arg, Expression<Func<T, U>> expression) where U : IEntityLink
- {
- var col = CoreUtils.GetFullPropertyName(expression, ".");
- var id = arg.Get<Guid>(col + ".ID");
- if (id != Guid.Empty && arg.Get<Guid>(col + ".Deleted") == Guid.Empty)
- return id;
- return null;
- }
- public static Filter<T> LinkValid<T>(this Filter<T> filter, Guid entityID = default)
- {
- var mExp = filter.Expression as MemberExpression;
- if (mExp == null)
- throw new ArgumentException("Filter expression is not a MemberExpression");
- var idExp = Expression.PropertyOrField(mExp, "ID");
- var deletedExp = Expression.PropertyOrField(mExp, "Deleted");
- filter.Expression = idExp;
- if (entityID != Guid.Empty)
- filter.IsEqualTo(entityID);
- else
- filter.IsNotEqualTo(Guid.Empty);
- var delFilter = new Filter<T>();
- delFilter.Expression = deletedExp;
- delFilter.IsEqualTo(Guid.Empty);
- filter.And(delFilter);
- return filter.Parent ?? filter;
- }
- public static Filter<T> NotLinkValid<T>(this Filter<T> filter)
- {
- var mExp = filter.Expression as MemberExpression;
- if (mExp == null)
- throw new ArgumentException("Filter expression is not a MemberExpression");
- filter.All();
- var subFilter = new Filter<T>();
- var idExp = Expression.PropertyOrField(mExp, "ID");
- var deletedExp = Expression.PropertyOrField(mExp, "Deleted");
- subFilter.Expression = idExp;
- subFilter.IsEqualTo(Guid.Empty);
- var delFilter = new Filter<T>();
- delFilter.Expression = deletedExp;
- delFilter.IsNotEqualTo(Guid.Empty);
- subFilter.Or(delFilter);
-
- filter.And(subFilter);
- return filter.Parent ?? filter;
- }
- #region DeepClone Utility
- //public static object Clone(object from)
- //{
- // if (from == null)
- // throw new ArgumentNullException("Source is null");
- // if (into == null)
- // throw new ArgumentNullException("Target is null");
- // return DoClone(from, null);
- //}
- /// <summary>
- /// Get the deep clone of an object.
- /// </summary>
- /// <typeparam name="T">The type of the obj.</typeparam>
- /// <param name="from">It is the object used to deep clone.</param>
- /// <returns>Return the deep clone.</returns>
- public static T Clone<T>(T from, T into) where T : new()
- {
- if (from == null)
- throw new ArgumentNullException("Source is null");
- return (T)DoClone(from, into);
- }
- private static FieldInfo[] GetFieldInfosIncludingBaseClasses(Type type, BindingFlags bindingFlags)
- {
- var fieldInfos = type.GetFields(bindingFlags);
- // If this class doesn't have a base, don't waste any time
- if (type.BaseType == null ||
- type.BaseType == typeof(object)) return fieldInfos; // Otherwise, collect all types up to the furthest base class
- var currentType = type;
- var fieldComparer = new FieldInfoComparer();
- var fieldInfoList = new HashSet<FieldInfo>(fieldInfos, fieldComparer);
- while (currentType != typeof(object))
- {
- fieldInfos = currentType.GetFields(bindingFlags);
- fieldInfoList.UnionWith(fieldInfos);
- currentType = currentType.BaseType;
- }
- return fieldInfoList.ToArray();
- }
- private class FieldInfoComparer : IEqualityComparer<FieldInfo>
- {
- public bool Equals(FieldInfo x, FieldInfo y)
- {
- return x.DeclaringType == y.DeclaringType && x.Name == y.Name;
- }
- public int GetHashCode(FieldInfo obj)
- {
- return obj.Name.GetHashCode() ^ obj.DeclaringType.GetHashCode();
- }
- }
- /// <summary>
- /// The method implements deep clone using reflection.
- /// </summary>
- /// <param name="from">It is the object used to deep clone.</param>
- /// <returns>Return the deep clone.</returns>
- private static object? DoClone(object from, object? into = null)
- {
- if (from == null) return null;
- if (from is MulticastDelegate)
- return null;
- var type = from.GetType();
- // If the type of object is the value type, we will always get a new object when
- // the original object is assigned to another variable. So if the type of the
- // object is primitive or enum, we just return the object. We will process the
- // struct type subsequently because the struct type may contain the reference
- // fields.
- // If the string variables contain the same chars, they always refer to the same
- // string in the heap. So if the type of the object is string, we also return the
- // object.
- if (type.GetTypeInfo().IsPrimitive || type.GetTypeInfo().IsEnum || type == typeof(string)) return from;
- // If the type of the object is the Array, we use the CreateInstance method to get
- // a new instance of the array. We also process recursively this method in the
- // elements of the original array because the type of the element may be the reference
- // type.
- if (type.IsArray)
- {
- var basename = type.FullName.Replace("[]", "");
- var typeElement = Type.GetType(basename);
- if (typeElement == null)
- typeElement = FindType(basename);
- var array = (from as Array)!; // not-null because type.IsArray
- var copiedArray = Array.CreateInstance(typeElement, array.Length);
- for (var i = 0; i < array.Length; i++)
- // Get the deep clone of the element in the original array and assign the
- // clone to the new array.
- copiedArray.SetValue(DoClone(array.GetValue(i)), i);
- return copiedArray;
- }
- // If the type of the object is class or struct, it may contain the reference fields,
- // so we use reflection and process recursively this method in the fields of the object
- // to get the deep clone of the object.
- // We use Type.IsValueType method here because there is no way to indicate directly whether
- // the Type is a struct type.
- if (type.GetTypeInfo().IsClass || type.GetTypeInfo().IsValueType)
- {
- var copiedObject = into;
- if (copiedObject == null)
- try
- {
- copiedObject = Activator.CreateInstance(from.GetType());
- }
- catch (Exception e)
- {
- Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
- }
- if (copiedObject != null)
- {
- // Get all FieldInfo.
- var fields = GetFieldInfosIncludingBaseClasses(type.GetTypeInfo(),
- BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
- foreach (var field in fields.Where(x => !x.IsNotSerialized))
- {
- var fieldValue = field.GetValue(from);
- if (fieldValue != null)
- // Get the deep clone of the field in the original object and assign the
- // clone to the field in the new object.
- field.SetValue(copiedObject, DoClone(fieldValue));
- }
- }
- return copiedObject;
- }
- throw new ArgumentException("The object is unknown type");
- }
- #endregion
- #region DeepCompare Utility
- public static bool CompareObjects(string prefix, object inputObjectA, object inputObjectB, string[] ignorePropertiesList,
- List<Tuple<string, object?, object?>> results)
- {
- var areObjectsEqual = true;
- //check if both objects are not null before starting comparing children
- if (inputObjectA != null && inputObjectB != null)
- {
- //create variables to store object values
- object value1, value2;
- var properties = inputObjectA.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
- //get all public properties of the object using reflection
- foreach (var propertyInfo in properties)
- {
- var name = string.IsNullOrWhiteSpace(prefix) ? propertyInfo.Name : prefix + "." + propertyInfo.Name;
- //if it is not a readable property or if it is a ignorable property
- //ingore it and move on
- if (!propertyInfo.CanRead || ignorePropertiesList.Contains(name))
- continue;
- //get the property values of both the objects
- value1 = propertyInfo.GetValue(inputObjectA, null);
- value2 = propertyInfo.GetValue(inputObjectB, null);
- // if the objects are primitive types such as (integer, string etc)
- //that implement IComparable, we can just directly try and compare the value
- if (IsAssignableFrom(propertyInfo.PropertyType) || IsPrimitiveType(propertyInfo.PropertyType) ||
- IsValueType(propertyInfo.PropertyType))
- {
- //compare the values
- if (!CompareValues(name, value1, value2, results))
- {
- //Console.WriteLine("Property Name {0}", propertyInfo.Name);
- areObjectsEqual = false;
- }
- }
- //if the property is a collection (or something that implements IEnumerable)
- //we have to iterate through all items and compare values
- else if (IsEnumerableType(propertyInfo.PropertyType))
- {
- //Console.WriteLine("Property Name {0}", propertyInfo.Name);
- if (!CompareEnumerations(name, value1, value2, ignorePropertiesList, results))
- areObjectsEqual = false;
- }
- //if it is a class object, call the same function recursively again
- else if (propertyInfo.PropertyType.IsClass)
- {
- if (!CompareObjects(name, propertyInfo.GetValue(inputObjectA, null), propertyInfo.GetValue(inputObjectB, null),
- ignorePropertiesList, results))
- areObjectsEqual = false;
- }
- else
- {
- areObjectsEqual = false;
- }
- }
- }
- else
- {
- areObjectsEqual = false;
- }
- return areObjectsEqual;
- }
- //true if c and the current Type represent the same type, or if the current Type is in the inheritance
- //hierarchy of c, or if the current Type is an interface that c implements,
- //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.
- private static bool IsAssignableFrom(Type type)
- {
- return typeof(IComparable).IsAssignableFrom(type);
- }
- private static bool IsPrimitiveType(Type type)
- {
- return type.IsPrimitive;
- }
- private static bool IsValueType(Type type)
- {
- return type.IsValueType;
- }
- private static bool IsEnumerableType(Type type)
- {
- return typeof(IEnumerable).IsAssignableFrom(type);
- }
- /// <summary>
- /// Compares two values and returns if they are the same.
- /// </summary>
- private static bool CompareValues(string name, object? value1, object? value2, List<Tuple<string, object?, object?>> results)
- {
- var areValuesEqual = true;
- var selfValueComparer = value1 as IComparable;
- // one of the values is null
- if ((value1 == null && value2 != null) || (value1 != null && value2 == null))
- areValuesEqual = false;
- else if (selfValueComparer != null && selfValueComparer.CompareTo(value2) != 0)
- areValuesEqual = false;
- else if (!Equals(value1, value2))
- areValuesEqual = false;
- if (!areValuesEqual)
- results.Add(new Tuple<string, object?, object?>(name, value1, value2));
- return areValuesEqual;
- }
- private static bool CompareEnumerations(string name, object value1, object value2, string[] ignorePropertiesList,
- List<Tuple<string, object?, object?>> results)
- {
- // if one of the values is null, no need to proceed return false;
- if (value1 == null && value2 != null)
- {
- results.Add(new Tuple<string, object?, object?>(string.Format("{0}.Null", name), true, false));
- return false;
- }
- if (value1 != null && value2 == null)
- {
- results.Add(new Tuple<string, object?, object?>(string.Format("{0}.Null", name), false, true));
- return false;
- }
- if (value1 != null && value2 != null)
- {
- IEnumerable<object> enumValue1, enumValue2;
- enumValue1 = ((IEnumerable)value1).Cast<object>();
- enumValue2 = ((IEnumerable)value2).Cast<object>();
- // if the items count are different return false
- if (enumValue1.Count() != enumValue2.Count())
- {
- results.Add(new Tuple<string, object?, object?>(string.Format("{0}.Count", name), enumValue1.Count(), enumValue2.Count()));
- return false;
- }
- // if the count is same, compare individual item
- object enumValue1Item, enumValue2Item;
- Type enumValue1ItemType;
- for (var itemIndex = 0; itemIndex < enumValue1.Count(); itemIndex++)
- {
- enumValue1Item = enumValue1.ElementAt(itemIndex);
- enumValue2Item = enumValue2.ElementAt(itemIndex);
- enumValue1ItemType = enumValue1Item.GetType();
- if (IsAssignableFrom(enumValue1ItemType) || IsPrimitiveType(enumValue1ItemType) || IsValueType(enumValue1ItemType))
- {
- if (!CompareValues(string.Format("{0}[{1}]", name, itemIndex), enumValue1Item, enumValue2Item, results))
- return false;
- }
- else if (!CompareObjects(name, enumValue1Item, enumValue2Item, ignorePropertiesList, results))
- {
- return false;
- }
- }
- }
- return true;
- }
- #endregion
- #region Expression Serialisation
- public static string MemberExpressionToString(MemberExpression mExpression)
- {
- var mOriginal = mExpression;
- var path = "";
- while (true)
- {
- if (mExpression.Expression.NodeType == ExpressionType.MemberAccess)
- {
- var propInfo = mExpression.Expression
- .GetType().GetTypeInfo().GetProperty("Member");
- var propValue = (propInfo.GetValue(mExpression.Expression, null) as PropertyInfo)!;
- path = propValue.Name + "." + path;
- mExpression = (mExpression.Expression as MemberExpression)!;
- }
- else if (mExpression.Expression.NodeType == ExpressionType.Convert)
- {
- mExpression = MemberExpression.PropertyOrField((mExpression.Expression as UnaryExpression)?.Operand as MemberExpression, mExpression.Member.Name);
- }
- else
- {
- break;
- }
- }
- return path + mOriginal.Member.Name;
- }
- private enum SerialisedExpressionType
- {
- Member,
- Index,
- Parameter
- }
- public static void SerialiseExpression(this CoreBinaryWriter writer, Type t, Expression expression, bool includeType)
- {
- if (includeType)
- {
- writer.Write(t.EntityName());
- }
- if (expression.NodeType == ExpressionType.MemberAccess)
- {
- writer.Write((byte)SerialisedExpressionType.Member);
- writer.Write(MemberExpressionToString((expression as MemberExpression)!));
- }
- else if (expression.NodeType == ExpressionType.Index)
- {
- writer.Write((byte)SerialisedExpressionType.Index);
- var iexp = (IndexExpression)expression;
- var sexp = expression.ToString().Split('[');
- writer.Write(sexp[0]); // Member
- writer.Write(sexp[1].Replace("]", "").Replace("\"", "")); // Key
- }
- else
- {
- writer.Write((byte)SerialisedExpressionType.Parameter);
- }
- }
- public static Expression DeserialiseExpression(this CoreBinaryReader reader, Type t)
- {
- var expressionType = (SerialisedExpressionType)reader.ReadByte();
- switch (expressionType)
- {
- case SerialisedExpressionType.Member:
- var member = reader.ReadString();
- return CreateMemberExpression(t, member);
- case SerialisedExpressionType.Index:
- member = reader.ReadString();
- var key = reader.ReadString();
- return CreateIndexExpression(t, member, key);
- case SerialisedExpressionType.Parameter:
- default:
- return Expression.Parameter(t, "x");
- }
- }
- /// <summary>
- /// Deserialise the expression, with type information included in the serialised form.
- /// </summary>
- /// <param name="reader"></param>
- /// <returns></returns>
- public static Expression DeserialiseExpression(this CoreBinaryReader reader)
- {
- var entityName = reader.ReadString();
- var t = GetEntity(entityName);
- return reader.DeserialiseExpression(t);
- }
-
- public static string ExpressionToString<T,TType>(Expression<Func<T, TType>> expression)
- => ExpressionToString(typeof(T), expression);
- public static string ExpressionToString(Type t, Expression expression)
- {
- if (expression.NodeType == ExpressionType.MemberAccess)
- {
- var mexp = (MemberExpression)expression;
- var morg = (MemberExpression)expression;
- var Path = "";
- while (mexp.Expression.NodeType == ExpressionType.MemberAccess)
- {
- var propInfo = mexp.Expression
- .GetType().GetTypeInfo().GetProperty("Member");
- var propValue = propInfo.GetValue(mexp.Expression, null)
- as PropertyInfo;
- Path = propValue.Name + "." + Path;
- mexp = mexp.Expression as MemberExpression;
- }
- return Path + morg.Member.Name;
- }
- else if (expression.NodeType == ExpressionType.Index)
- {
- var iexp = (IndexExpression)expression;
- var sexp = expression.ToString().Split('[');
- return sexp[0];
- }
- return expression.ToString();
- }
-
- public static string ExpressionToString(Type t, Expression expression, bool includetype)
- {
- var result = new Dictionary<string, string>();
- if (expression.NodeType == ExpressionType.MemberAccess)
- {
- var mexp = (expression as MemberExpression)!;
- result["Member"] = MemberExpressionToString(mexp);
- }
- else if (expression.NodeType == ExpressionType.Index)
- {
- var iexp = (IndexExpression)expression;
- var sexp = expression.ToString().Split('[');
- result["Member"] = sexp[0];
- result["Key"] = sexp[1].Replace("]", "").Replace("\"", "");
- }
- result["Type"] = t.EntityName();
- return JsonConvert.SerializeObject(result);
- //ExpressionSerializer ser = new ExpressionSerializer(new Serialize.Linq.Serializers.JsonSerializer(),new Serialize.Linq.Factories.FactorySettings() { UseRelaxedTypeNames=true } );
- //String result = ser.SerializeText(expression);
- //return result;
- //if (expression.NodeType == ExpressionType.MemberAccess)
- //{
- // MemberExpression memberExpression = expression as MemberExpression;
- // MemberExpression memberExpressionOrg = memberExpression as MemberExpression;
- // string Path = "";
- // while (memberExpression.Expression.NodeType == ExpressionType.MemberAccess)
- // {
- // var propInfo = memberExpression.Expression
- // .GetType().GetTypeInfo().GetProperty("Member");
- // var propValue = propInfo.GetValue(memberExpression.Expression, null)
- // as PropertyInfo;
- // Path = propValue.Name + "." + Path;
- // memberExpression = memberExpression.Expression as MemberExpression;
- // }
- // if (includetype)
- // return t.FullName + " => " + Path + memberExpressionOrg.Member.Name;
- // else
- // return Path + memberExpressionOrg.Member.Name;
- //}
- //else if (expression.NodeType == ExpressionType.Index)
- //{
- // if (includetype)
- // return t.FullName + " => " + expression.ToString();
- // else
- // return expression.ToString();
- //}
- //else
- //{
- // if (includetype)
- // return t.FullName + " => " + expression.ToString();
- // else
- // return expression.ToString();
- //}
- }
- public static Expression StringToExpression(string expression)
- {
- var comps = JsonConvert.DeserializeObject<Dictionary<string, string>>(expression);
- var t = GetEntity(comps["Type"]);
- if (comps.TryGetValue("Key", out var key))
- return CreateIndexExpression(t, comps["Member"], key);
- else if (comps.TryGetValue("Member", out var member))
- return CreateMemberExpression(t, member);
- else
- return Expression.Parameter(t, "x");
- //ExpressionSerializer ser = new ExpressionSerializer(new Serialize.Linq.Serializers.JsonSerializer(), new Serialize.Linq.Factories.FactorySettings() { UseRelaxedTypeNames = true });
- //Expression result = ser.DeserializeText(expression);
- //return result;
- //String[] comps = expression.Split(new String[] { " => " }, StringSplitOptions.None);
- //Type type = comps.Length > 1 ? CoreUtils.GetEntity(comps[0]) : t;
- //return CreateExpression(type, comps[comps.Length - 1]);
- }
- public static Expression<Func<T, object?>> CreateLambdaExpression<T>(string column)
- {
- var parameter = Expression.Parameter(typeof(T), "x");
- var property = CreateMemberExpression(typeof(T), column);
- var converted = Expression.Convert(property, typeof(object));
- //var property = Expression.Convert(Expression.Property(parameter, column),typeof(object));
- return Expression.Lambda<Func<T, object?>>(converted, parameter);
- }
-
- public static Expression<Func<T, TType>> CreateLambdaExpression<T,TType>(string column)
- {
- var parameter = Expression.Parameter(typeof(T), "x");
- var property = CreateMemberExpression(typeof(T), column);
- var result = Expression.Lambda<Func<T, TType>>(property, parameter);
- return result;
- }
- public static Expression ConvertExpression(Type source, Expression lambda, Type target, Expression anchor)
- {
- var parent = ExpressionToString(target, anchor, false);
- var child = ExpressionToString(source, lambda, false);
- var property = string.Join(".", parent, child);
- return CreateMemberExpression(target, property);
- }
- public static Expression CreateMemberExpression(Type type, string propertyName)
- {
- var param = Expression.Parameter(type, "x");
- Expression body = param;
- foreach (var member in propertyName.Split('.')) body = Expression.PropertyOrField(body, member);
- return (MemberExpression)body;
- }
- public static IndexExpression CreateIndexExpression(Type type, string propertyname, string key)
- {
- var param = Expression.Parameter(type, "x");
- var propmod = propertyname.Replace("x.", "").Replace(".Item", "");
- var bar = Expression.Property(param, propmod);
- var dictionaryType = type.GetProperty(propmod).PropertyType;
- var indexerProp = dictionaryType.GetProperty("Item");
- var dictKeyConstant = Expression.Constant(key);
- var dictAccess = Expression.MakeIndex(bar, indexerProp, new[] { dictKeyConstant });
- return dictAccess;
- //var propertyType = indexerProp.PropertyType;
- //var right = Expression.Constant(Convert.ChangeType("newValue", propertyType));
- //var expression = Expression.MakeBinary(ExpressionType.Equal, dictAccess, right);
- }
- public static MemberExpression ExtractMemberExpression<T>(Expression<Func<T, object?>> expression)
- {
- if(!TryFindMemberExpression(expression.Body, out var me))
- {
- throw new Exception("Expression is not a member expression!");
- }
- return me;
- }
- public static MemberExpression ExtractMemberExpression<T, TValue>(Expression<Func<T, TValue>> expression)
- {
- TryFindMemberExpression(expression.Body, out var me);
- return me;
- }
- public static MemberExpression ExtractMemberExpression(Expression expression)
- {
- TryFindMemberExpression(Expression.Lambda(expression).Body, out var me);
- return me;
- }
- #endregion
- public static string FormatException(Exception err)
- {
- var messages = new List<string>();
- var e2 = err;
- while (e2 != null)
- {
- messages.InsertRange(0, new[] { e2.Message, e2.StackTrace, "============================================" });
- e2 = e2.InnerException;
- }
- return string.Join("\n", messages);
- }
- public static void LogException(string userid, Exception err, string? extra = null)
- {
- Logger.Send(LogType.Error, userid, (extra != null ? $"{extra}: " : "") + CoreUtils.FormatException(err));
- }
- #region OneToMany Relationships
- public static Type? GetOneToMany(Type TMany, Type TOne)
- {
- var o2m = TMany.GetInterfaces().FirstOrDefault(i =>
- i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IOneToMany<>)
- && i.GenericTypeArguments.Contains(TOne)
- );
- return o2m;
- }
- public static PropertyInfo GetOneToManyProperty(Type TMany, Type TOne)
- {
- return TMany.GetProperties().FirstOrDefault(x =>
- x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink))
- && x.PropertyType.GetInheritedGenericTypeArguments().FirstOrDefault() == TOne
- && !Attribute.IsDefined(x, typeof(ObsoleteAttribute))
- );
- }
- #endregion
- #region ManyToMany Relationships
- public static Type? GetManyToMany(Type TManyToMany, Type TThis)
- {
- var m2m = TManyToMany.GetInterfaces().FirstOrDefault(i =>
- i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>)
- && i.GenericTypeArguments.Contains(TThis)
- );
- return m2m;
- }
- public static Type GetManyToManyOtherType(Type TManyToMany, Type TThis)
- {
- var m2m = TManyToMany.GetInterfaces().FirstOrDefault(i =>
- i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IManyToMany<,>)
- && i.GenericTypeArguments.Contains(TThis)
- );
- return m2m.GenericTypeArguments.FirstOrDefault(x => x != TThis);
- }
- public static PropertyInfo GetManyToManyThisProperty(Type TManyToMany, Type TThis)
- {
- return TManyToMany.GetProperties().FirstOrDefault(x =>
- x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink))
- && x.PropertyType.GetInheritedGenericTypeArguments().FirstOrDefault() == TThis
- && !Attribute.IsDefined(x, typeof(ObsoleteAttribute))
- );
- }
- public static PropertyInfo GetManyToManyOtherProperty(Type TManyToMany, Type TThis)
- {
- var otherType = GetManyToManyOtherType(TManyToMany, TThis);
- return TManyToMany.GetProperties().FirstOrDefault(x =>
- x.PropertyType.GetInterfaces().Contains(typeof(IEntityLink))
- && x.PropertyType.GetInheritedGenericTypeArguments().FirstOrDefault() == otherType
- && !Attribute.IsDefined(x, typeof(ObsoleteAttribute))
- );
- }
- #endregion
-
- /// <summary>
- /// Get a dictionary of values representing the current state of an entity
- /// </summary>
- /// <param name="item">The Entity being scanned</param>
- /// <param name="props">The list of properties to scan, or null for all</param>
- /// <returns>A dictionary containing the properties and values for the entity</returns>
- public static Dictionary<string, object?> GetValues(BaseObject item, IEnumerable<IProperty>? props = null)
- {
- var result = new Dictionary<string, object?>();
- props ??= DatabaseSchema.Properties(item.GetType());//.Where(x => !(x.Editor is NullEditor));
- foreach (var prop in props)
- if (prop is CustomProperty)
- try
- {
- result[prop.Name] = item.UserProperties[prop.Name];
- }
- catch (Exception e)
- {
- Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
- }
- else
- try
- {
- object? value;
- var getter = prop.Getter();
- if (getter != null)
- value = getter.Invoke(item);
- else
- value = CoreUtils.GetPropertyValue(item, prop.Name);
- result[prop.Name] = value;
- }
- catch (Exception e)
- {
- Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
- }
- return result;
- }
-
- /// <summary>
- /// Given a certain entity, merge the changes with the current state of the entity into an updated list
- /// </summary>
- /// <param name="item">Th Entity being updated</param>
- /// <param name="previous">The previous set of changes to this entity</param>
- /// <param name="props">The list of properties to scan, or null for all</param>
- /// <param name="changes">The resulting updated list of changes</param>
- public static void MergeChanges(Dictionary<string, object?> previous, Dictionary<string, object?> current, Dictionary<string, object?> changes)
- {
- foreach (var (key, prevVal) in previous)
- if (prevVal is null)
- {
- if (current[key] != null)
- changes[key] = current[key];
- }
- else
- {
- if (!current.TryGetValue(key, out var curVal) || curVal is null)
- changes[key] = null;
- else if (!object.Equals(previous[key], curVal))
- changes[key] = curVal;
- }
- }
- public static Dictionary<String, object?> MonitorChanges<T>(T item, Action action, Dictionary<String, object?>? changes = null, IEnumerable<IProperty>? props = null) where T : BaseObject
- {
- var result = changes == null
- ? new Dictionary<String, object?>()
- : changes;
- var previous = GetValues(item, props);
- action.Invoke();
- var current = GetValues(item, props);
- MergeChanges(previous, current, result);
- return result;
- }
-
- public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
- {
- int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
- return dt.AddDays(-1 * diff).Date;
- }
- #region String Utilities
- /// <summary>
- /// Check if <paramref name="s"/> <see cref="string.IsNullOrWhiteSpace(string)"/>.
- /// If it is empty, returns <paramref name="def"/>, otherwise, returns <paramref name="s"/>.
- /// </summary>
- /// <remarks>
- /// Basically the null-coalescing operator ?? for strings.
- /// </remarks>
- /// <param name="s"></param>
- /// <param name="def"></param>
- /// <returns></returns>
- [return: NotNullIfNotNull("def")]
- public static string? NotWhiteSpaceOr(this string? s, string? def = null)
- {
- if (string.IsNullOrWhiteSpace(s))
- {
- return def;
- }
- return s;
- }
- /// <summary>
- /// Extension method version of <see cref="string.IsNullOrWhiteSpace(string)"/>.
- /// </summary>
- /// <param name="s">The string to check</param>
- /// <returns>true if <paramref name="s"/> is <see langword="null"/> or composed only of whitespace.</returns>
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static bool IsNullOrWhiteSpace([NotNullWhen(false)] this string? s)
- {
- return string.IsNullOrWhiteSpace(s);
- }
- public static bool IsBase64String(this string s)
- {
- s = s.Trim();
- return s.Length % 4 == 0 && Regex.IsMatch(s, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None);
- }
- public static string CalculateCRC(byte[] data)
- {
- var hash = Crc32.Compute(data);
- return string.Format("{0:X8}", hash);
- }
- public static string StripHTML(this string? html)
- {
- if (string.IsNullOrWhiteSpace(html))
- return "";
- var result = StripHtmlStyles.Replace(html, "");
- result = StripHtmlTags.Replace(result, "");
- result = StripSpecialCharacters.Replace(result, "");
- //result = StripQuotes.Replace(result, "\"");
- result = StripLineBreaks.Replace(result, "$1");
- result = result.Replace("\0", "").Trim();
- return result;
- }
- private static Regex NeatifyRegex = new Regex(@"
- (?<=[A-Z])(?=[A-Z][a-z]) |
- (?<=[^A-Z])(?=[A-Z]) |
- (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace);
- public static string Neatify(string caption)
- {
- if (string.Equals(caption, "ID"))
- return caption;
- var result = NeatifyRegex.Replace(caption.Replace(".", ""), " ");
- while (result.Contains(" "))
- result = result.Replace(" ", " ");
- if (result.EndsWith(" ID"))
- result = string.Join(" ", result.Split(' ').Reverse().Skip(1).Reverse());
- return result.Trim();
- }
- public static string Codify(string? text)
- {
- char[] numbers = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
- if (string.IsNullOrWhiteSpace(text))
- return "??";
- var result = "";
- var comps = text.ToUpper().Split(' ');
- foreach (var comp in comps)
- {
- List<char> chars = new List<char>();
- foreach (char c in comp.ToCharArray())
- {
- chars.Add(c);
- if (!numbers.Contains(c))
- break;
- }
- var comb = new String(chars.ToArray());
- result += comb;
- }
- return string.IsNullOrWhiteSpace(result) ? "??" : result;
- }
- public static string Truncate(this string value, int maxLength)
- {
- if(value.Length > maxLength)
- {
- return value[..maxLength];
- }
- return value;
- }
- #endregion
- #region IEnumerable Utilities
- /// <summary>
- /// Returns <paramref name="enumerable"/> as a <see cref="List{T}"/>;
- /// if it is already a <see cref="List{T}"/>, it is directly returned, instead of copying.
- /// </summary>
- public static List<T> AsList<T>(this IEnumerable<T> enumerable)
- {
- if(enumerable is List<T> list)
- {
- return list;
- }
- return enumerable.ToList<T>();
- }
- /// <summary>
- /// Returns <paramref name="enumerable"/> as an <see cref="IList{T}"/>;
- /// if it is already a <see cref="IList{T}"/>, it is directly returned, instead of copying.
- /// </summary>
- public static IList<T> AsIList<T>(this IEnumerable<T> enumerable)
- {
- if (enumerable is IList<T> list)
- {
- return list;
- }
- return enumerable.ToList<T>();
- }
- /// <summary>
- /// Returns <paramref name="enumerable"/> as an array;
- /// if it is already an array, it is directly returned, instead of copying.
- /// </summary>
- public static T[] AsArray<T>(this IEnumerable<T> enumerable)
- {
- if (enumerable is T[] arr)
- {
- return arr;
- }
- return enumerable.ToArray<T>();
- }
- public static U[] ToArray<T, U>(this T[] from, Func<T, U> mapFunc)
- {
- var to = new U[from.Length];
- for(int i = 0; i < from.Length; ++i)
- {
- to[i] = mapFunc(from[i]);
- }
- return to;
- }
- public static IEnumerable<T> AnyOr<T>(this IEnumerable<T> enumerable, IEnumerable<T> or)
- {
- var any = false;
- foreach(var item in enumerable)
- {
- any = true;
- yield return item;
- }
- if (!any)
- {
- foreach(var item in or)
- {
- yield return item;
- }
- }
- }
- public static IEnumerable<T> One<T>(T item)
- {
- yield return item;
- }
- public static IEnumerable<T> One<T>(Func<T> fnc)
- {
- yield return fnc();
- }
- public static (List<T>, List<T>) PartitionToList<T>(this IEnumerable<T> enumerable, Func<T, bool> predicate)
- {
- var trueResult = new List<T>();
- var falseResult = new List<T>();
- foreach(var item in enumerable)
- {
- if (predicate(item))
- {
- trueResult.Add(item);
- }
- else
- {
- falseResult.Add(item);
- }
- }
- return (trueResult, falseResult);
- }
- /// <summary>
- /// Get the value in <paramref name="dictionary"/> for the given <paramref name="key"/>, adding a new instance of <typeparamref name="TValue"/>
- /// if the value was not found.
- /// </summary>
- /// <typeparam name="TKey"></typeparam>
- /// <typeparam name="TValue"></typeparam>
- /// <param name="dictionary"></param>
- /// <param name="key"></param>
- /// <returns></returns>
- public static TValue GetValueOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
- where TValue : new()
- {
- if(!dictionary.TryGetValue(key, out var value))
- {
- value = new TValue();
- dictionary.Add(key, value);
- }
- return value;
- }
- /// <summary>
- /// Add a range of values to a dictionary, using the <see cref="IDictionary{TKey, TValue}.Add(TKey, TValue)"/> method.
- /// </summary>
- /// <remarks>
- /// Throws an <see cref="ArgumentException"/> for duplicate keys.
- /// </remarks>
- /// <typeparam name="TDict"></typeparam>
- /// <typeparam name="TKey"></typeparam>
- /// <typeparam name="TValue"></typeparam>
- /// <param name="dictionary"></param>
- /// <param name="items"></param>
- /// <returns></returns>
- public static TDict AddRange<TDict, TKey, TValue>(this TDict dictionary, IEnumerable<KeyValuePair<TKey, TValue>> items)
- where TDict : IDictionary<TKey, TValue>
- {
- foreach(var item in items)
- {
- dictionary.Add(item.Key, item.Value);
- }
- return dictionary;
- }
- public static IEnumerable<T> NotNull<T>(this IEnumerable<T?> enumerable)
- where T : struct
- {
- foreach(var obj in enumerable)
- {
- if (obj.HasValue)
- {
- yield return obj.Value;
- }
- }
- }
- public static IEnumerable<T> NotNull<T>(this IEnumerable<T?> enumerable)
- where T : class
- {
- foreach (var obj in enumerable)
- {
- if (obj != null)
- {
- yield return obj;
- }
- }
- }
- public static IEnumerable<TValue> NotNull<T, TValue>(this IEnumerable<T> enumerable, Func<T, TValue?> f)
- where TValue : struct
- {
- foreach (var obj in enumerable)
- {
- var v = f(obj);
- if (v.HasValue)
- {
- yield return v.Value;
- }
- }
- }
- public static IEnumerable<TValue> NotNull<T, TValue>(this IEnumerable<T> enumerable, Func<T, TValue?> f)
- where TValue : class
- {
- foreach (var obj in enumerable)
- {
- var v = f(obj);
- if (v != null)
- {
- yield return v;
- }
- }
- }
- public static IEnumerable<KeyValuePair<int, T>> WithIndex<T>(this IEnumerable<T> enumerable)
- {
- int i = 0;
- foreach(var obj in enumerable)
- {
- yield return new KeyValuePair<int, T>(i, obj);
- ++i;
- }
- }
- #endregion
- }
- }
|