System.Reflection.PropertyInfo.GetValue(object)

Here are the examples of the csharp api System.Reflection.PropertyInfo.GetValue(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2117 Examples 7

19 Source : XRayPipelineHandler.cs
with Apache License 2.0
from aws

private static bool TryReadPropertyValue(object obj, string propertyName, out object value)
        {
            value = 0;

            try
            {
                if (obj == null || propertyName == null)
                {
                    return false;
                }

                var property = obj.GetType().GetProperty(propertyName);

                if (property == null)
                {
                    _logger.DebugFormat("Property doesn't exist. {0}", propertyName);
                    return false;
                }

                value = property.GetValue(obj);
                return true;
            }
            catch (ArgumentNullException e)
            {
                _logger.Error(e, "Failed to read property because argument is null.");
                return false;
            }
            catch (AmbiguousMatchException e)
            {
                _logger.Error(e, "Failed to read property because of duplicate property name.");
                return false;
            }
        }

19 Source : Condition.cs
with Apache License 2.0
from aws

private void PopulateProperties(Dictionary<string, object> properties)
        {
            var thisType = GetType();
            foreach (var property in properties)
            {
                var propertyName = property.Key;
                var propertyInfo = thisType.GetProperty(propertyName);
                if (propertyInfo != null)
                {
                    object propertyValue;
                    if (property.Value is JObject dictionaryValue)
                    {
                        propertyValue = dictionaryValue.ToObject<Dictionary<string, object>>();
                    }
                    else if (property.Value is JArray arrayValue)
                    {
                        // convert JArray to destination type
                        propertyValue = propertyInfo.GetValue(this) switch
                        {
                            string[] stringArray => arrayValue.ToObject<string[]>(),
                            bool[] boolArray => arrayValue.ToObject<bool[]>(),
                            int[] intArray => arrayValue.ToObject<int[]>(),
                            long[] longArray => arrayValue.ToObject<long[]>(),
                            decimal[] decimalArray => arrayValue.ToObject<decimal[]>(),
                            _ => arrayValue.ToObject<object[]>()
                        };
                    }
                    else
                    {
                        propertyValue = property.Value;
                    }

                    try
                    {
                        propertyInfo.SetValue(this, propertyValue);
                    }
                    catch (ArgumentException ex)
                    {
                        throw new ArgumentException($"Cannot replacedign {propertyValue} ({propertyValue.GetType()} type) " +
                                                    $"to property {propertyName} ({propertyInfo.PropertyType} type).", ex);
                    }
                }
                else
                {
                    throw new MissingMemberException($"Property {propertyName} does not exist in {thisType}.");
                }
            }

19 Source : Envelope.cs
with Apache License 2.0
from awslabs

public virtual object ResolveLocalVariable(string variable)
        {
            if (_data == null) return null;

            variable = variable.Substring(1);
            if (_data is IDictionary dictionary) //Dictionary<,> and ReadOnlyDictionary<,> both implement this IDictionary
            {
                if (dictionary.Contains(variable))
                {
                    return dictionary[variable];
                }
            }
            else if (_data is IDictionary<string, JToken> jObject)
            {
                if (jObject.TryGetValue(variable, out JToken jToken))
                {
                    if (jToken is JValue jValue)
                    {
                        return jValue.Value;
                    }
                    return jToken;
                }
            }
            else
            {
                var prop = _data.GetType().GetProperty(variable, BindingFlags.Public | BindingFlags.Instance);
                if (prop != null)
                {
                    return prop.GetValue(_data);
                }
            }
            return null;
        }

19 Source : MemoryCacheManager.cs
with MIT License
from aykutsahin98

public void RemoveByPattern(string pattern)
        {
            var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic;
            List<ICacheEntry> cacheCollectionValues = new List<ICacheEntry>();

            foreach (var cacheItem in cacheEntriesCollection)
            {
                ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null);
                cacheCollectionValues.Add(cacheItemValue);
            }

            var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
            var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList();

            foreach (var key in keysToRemove)
            {
                _memoryCache.Remove(key);
            }
        }

19 Source : ErrorHandler.cs
with MIT License
from AyrA

public static Dictionary<string, string> GetEnv()
        {
            var Dict = new Dictionary<string, string>();
            foreach (var Entry in Environment.GetEnvironmentVariables())
            {
                Dict.Add(
                    Entry.GetType().GetProperty("Key").GetValue(Entry).ToString(),
                    Entry.GetType().GetProperty("Value").GetValue(Entry).ToString()
                    );
            }
            return Dict;
        }

19 Source : FieldAttribute.FixupInheritedTargets.cs
with MIT License
from azist

private static void inheritAttribute(FieldAttribute parent, FieldAttribute self, string callSite)
    {
      //merge attributes from parent into self prop by prop
      foreach(var pi in ALL_PROPS)
      {
        if (pi.Name==nameof(MetadataContent))
        {
          if (self.MetadataContent.IsNullOrWhiteSpace())
            self.MetadataContent = parent.MetadataContent;
          else if (parent.MetadataContent.IsNotNullOrWhiteSpace())
          { //merge
            var conf1 = ParseMetadataContent(parent.MetadataContent, callSite);
            var conf2 = ParseMetadataContent(self.MetadataContent, callSite);

            var merged = new LaconicConfiguration();
            merged.CreateFromMerge(conf1, conf2);
            self.MetadataContent = merged.SaveToString();
          }

          continue;
        }//metadata merge

        if (pi.Name==nameof(ValueList))
        {
          if (self.ValueList==null && self.PropertyWasreplacedigned(nameof(ValueList)))//explicit reset
          {
            self.ValueList = null;
            continue;
          }
          else if (!self.HasValueList)
            self.ValueList = parent.ValueList;
          else if (parent.HasValueList)
          { //merge
            var vl1 = parent.ParseValueList(true);
            var vl2 = self.ParseValueList(true);

            vl2.Append(vl1);//merge missing in self from parent



            //remove all that start with REMOVE
            // to remove a key include an override with:  `keyABC: #del#` (item keyed on `keyABC` will be removed)
            const string DELETE = "#del#";
            vl2.Where(kvp => kvp.Value.replacedtring().EqualsOrdIgnoreCase(DELETE))
               .ToArray()
               .ForEach( kvp => vl2.Remove(kvp.Key) );

            self.ValueList = BuildValueListString(vl2);//reconsreplacedute jsonmap back into string
          }

          continue;
        }

        if (self.PropertyWasreplacedigned(pi.Name)) continue;//was overridden
        pi.SetValue(self, pi.GetValue(parent));//set value
      }
    }

19 Source : ExternalParameterAttribute.cs
with MIT License
from azist

public static bool GetParameter(IApplication app, object target, string name, out object value, params string[] groups)
    {
      var pi = findByName(app, false, target, name, groups);
      if (pi == null)
      {
        value = null;
        return false;
      }

      value = pi.GetValue(target);
      return true;
    }

19 Source : TaskUtils.cs
with MIT License
from azist

public static (bool ok, object result) TryGetCompletedTaskResultAsObject(this Task task)
    {
      if (task==null) return (false, null);
      if (!task.IsCompleted) return (false, null);

      var t = task.GetType();

      //safeguard for theoretical future fx extension to more derivatives than Task<t>
      var tp = t;
      while(tp!=null)//must search parent chain as continuation return internal ContinuationResultTaskFromTask<TResult> : Task<TResult>
      {
        if (tp.IsGenericType && tp.GetGenericTypeDefinition() == typeof(Task<>)) break;
        tp = tp.BaseType;
      }
      if (tp==null) return (false, null);

      var result = t.GetProperty("Result").GetValue(task);
      return (ok: true, result);
    }

19 Source : StrUtils.cs
with MIT License
from azist

[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
    public static string ArgsTpl(this string tpl, object args, out bool matched)
    {
      matched = false;
      if (tpl == null || args == null) return null;
      var result = tpl;
      var t = args.GetType();
      var lst = new List<object>();
      foreach (var pi in t.GetProperties())
      {
        var val = pi.GetValue(args);
        if (val == null) val = string.Empty;
        lst.Add(val);

        var replacedResult = result.Replace('@' + pi.Name + '@', (lst.Count - 1).ToString());

        if (!string.Equals(result, replacedResult, StringComparison.Ordinal))
          matched = true;

        result = replacedResult;
      }
      return result.Args(lst.ToArray());
    }

19 Source : SyntaxNode.cs
with Apache License 2.0
from azizamari

public IEnumerable<SyntaxNode> GetChildren()
        {
            var properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach(var prop in properties)
            {
                if (typeof(SyntaxNode).IsreplacedignableFrom(prop.PropertyType))
                {
                    var child = (SyntaxNode)prop.GetValue(this);
                    if (child != null)
                        yield return child;
                }
                else if (typeof(SeparatedSyntaxList).IsreplacedignableFrom(prop.PropertyType))
                {
                    var separatedSyntaxList = (SeparatedSyntaxList)prop.GetValue(this);
                    foreach (var child in separatedSyntaxList.GetWithSeparators())
                        yield return child;
                }
                else if (typeof(IEnumerable<SyntaxNode>).IsreplacedignableFrom(prop.PropertyType))
                {
                    var children = (IEnumerable<SyntaxNode>)prop.GetValue(this);
                    foreach (var child in children)
                    {
                        if (child != null)
                            yield return child;
                    }
                }
            }
        }

19 Source : CacheEncryptionTests.cs
with MIT License
from AzureAD

private byte[] GetFirstCacheValue()
        {
            dynamic content = _testCacheAdapter._memoryCache
                .GetType()
                .GetField("_entries", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
                .GetValue(_testCacheAdapter._memoryCache);
            System.Collections.IDictionary dictionary = content as System.Collections.IDictionary;
            var firstEntry = dictionary.Values.OfType<object>().First();
            var firstEntryValue = firstEntry.GetType()
                .GetProperty("Value")
                .GetValue(firstEntry);
            return firstEntryValue as byte[];
        }

19 Source : ProjectDescriptionReader.cs
with MIT License
from AzureAD

private void ReadProjectDescriptions()
        {
            if (projectDescriptions.Any())
            {
                return;
            }

            var properties = typeof(Microsoft.Idenreplacedy.App.Properties.Resources).GetProperties(BindingFlags.Static | BindingFlags.NonPublic)
                .Where(p => p.PropertyType == typeof(byte[]))
                .ToArray();
            foreach (PropertyInfo propertyInfo in properties)
            {
                byte[] content = (propertyInfo.GetValue(null) as byte[])!;
                ProjectDescription? projectDescription = ReadDescriptionFromFileContent(content);

                if (projectDescription == null)
                {
                    throw new FormatException($"Resource file { propertyInfo.Name } could not be parsed. ");
                }
                if (!projectDescription.IsValid())
                {
                    throw new FormatException($"Resource file {propertyInfo.Name} is missing Idenreplacedier or ProjectRelativeFolder is null. ");
                }
                projectDescriptions.Add(projectDescription);
            }

            // TODO: provide an extension mechanism to add such files outside the tool.
            // In that case the validation would not be an exception? but would need to provide error messages
        }

19 Source : SettingRecord.cs
with MIT License
from b-editor

public record SettingRecord()
    {
        /// <summary>
        /// Saves this configuration to the specified file.
        /// </summary>
        /// <param name="filename">The file to save.</param>
        /// <returns>Returns <see langword="true"/> if the save was successful, <see langword="false"/> otherwise.</returns>
        public bool Save(string filename)
        {
            try
            {
                using var stream = new FileStream(filename, FileMode.Create);
                using var writer = new Utf8JsonWriter(stream, Serialize._options);

                writer.WriteStartObject();

                foreach (var (param, prop) in GetSerializable(GetType()))
                {
                    var value = prop.GetValue(this);
                    if (value is null) continue;
                    WriteSerializable(writer, param.Name!, value);
                }

                writer.WriteEndObject();
                writer.Flush();
                return true;
            }
            catch (Exception e)
            {
                ServicesLocator.Current.Logger.LogError(e, "Failed to save {0}.", GetType().Name);
                return false;
            }
        }

        /// <summary>
        /// Saves this configuration to the specified file.
        /// </summary>
        /// <param name="filename">The file to save.</param>
        /// <returns>Returns <see langword="true"/> if the save was successful, <see langword="false"/> otherwise.</returns>
        public async ValueTask<bool> SaveAsync(string filename)
        {
            try
            {
                await using var stream = new FileStream(filename, FileMode.Create);
                await using var writer = new Utf8JsonWriter(stream, Serialize._options);

                writer.WriteStartObject();

                foreach (var (param, prop) in GetSerializable(GetType()))
                {
                    var value = prop.GetValue(this);
                    if (value is null) continue;
                    WriteSerializable(writer, param.Name!, value);
                }

                writer.WriteEndObject();
                await writer.FlushAsync();
                return true;
            }
            catch (Exception e)
            {
                ServicesLocator.Current.Logger.LogError(e, "Failed to save {0}.", GetType().Name);
                return false;
            }
        }

        /// <summary>
        /// Loads the settings from a file.
        /// </summary>
        /// <typeparam name="T">Type of the object to be loaded.</typeparam>
        /// <param name="filename">The name of the file to load.</param>
        /// <returns>Returns the restored object on success, <see langword="null"/> otherwise.</returns>
        public static T? LoadFrom<T>(string filename)
            where T : SettingRecord
        {
            if (!File.Exists(filename)) return default;
            try
            {
                using var stream = new FileStream(filename, FileMode.Open);

                using var doc = JsonDoreplacedent.Parse(stream);
                var type = typeof(T);
                var args = new List<object>();

                foreach (var (param, prop) in GetSerializable(type))
                {
                    if (doc.RootElement.TryGetProperty(param.Name!, out var json))
                    {
                        var value = ReadSerializable(json, param.ParameterType);
                        args.Add(value);
                    }
                    else
                    {
                        args.Add(GetDefault(type));
                    }
                }

                return (T)Activator.CreateInstance(type, BindingFlags.CreateInstance, null, args.ToArray(), null)!;
            }
            catch (Exception e)
            {
                ServicesLocator.Current.Logger.LogError(e, "Failed to load {0}.", filename);
                return default;
            }
        }

        /// <summary>
        /// Loads the settings from a file.
        /// </summary>
        /// <typeparam name="T">Type of the object to be loaded.</typeparam>
        /// <param name="filename">The name of the file to load.</param>
        /// <returns>Returns the restored object on success, <see langword="null"/> otherwise.</returns>
        public static async ValueTask<T?> LoadFromAsync<T>(string filename)
            where T : SettingRecord
        {
            if (!File.Exists(filename)) return default;
            try
            {
                await using var stream = new FileStream(filename, FileMode.Open);

                using var doc = await JsonDoreplacedent.ParseAsync(stream);
                var type = typeof(T);
                var args = new List<object>();

                foreach (var (param, prop) in GetSerializable(type))
                {
                    if (doc.RootElement.TryGetProperty(param.Name!, out var json))
                    {
                        var value = ReadSerializable(json, param.ParameterType);
                        args.Add(value);
                    }
                    else
                    {
                        args.Add(GetDefault(type));
                    }
                }

                return (T)Activator.CreateInstance(type, BindingFlags.CreateInstance, null, args.ToArray(), null)!;
            }
            catch (Exception e)
            {
                ServicesLocator.Current.Logger.LogError(e, "Failed to load {0}.", filename);
                return default;
            }
        }

        private static IEnumerable<(ParameterInfo Parameter, PropertyInfo Property)> GetSerializable(Type type)
        {
            var constructor = type.GetConstructors()[0];
            foreach (var param in constructor.GetParameters())
            {
                var name = param.Name;

                if (name is not null && type.GetProperty(name) is var prop && prop is not null && IsSerializable(prop.PropertyType))
                {
                    yield return (param, prop);
                }
            }

19 Source : JITExtensions.cs
with MIT License
from badamczewski

public static DecompiledMethod ToAsm(this MethodInfo methodInfo)
        {
            var info = methodInfo;
            if (info.IsGenericMethod)
            {
                //
                // There's a reason why we are not using a type clreplaced called JITAttribute
                // (which we have in our lib), if we load the exact same code in two different
                // application domains the runtime will refuse to cast them and raise
                // InvalidCastException
                // 
                // We have to use reflection to be safe.
                //
                var attributes = info.GetCustomAttributes();
                foreach(var attribute in attributes)
                {
                    var type = attribute.GetType();
                    //
                    // If we find the correct attribute, then there's no turning back
                    // Use relection and should you fail, then fail fast.
                    //
                    // We need to make a generic method for each provided JIT attribute 
                    // So if we provide JIT[typeof(int)] JIT[typeof(string)] we are compiling not one,
                    // but two methods. 
                    //
                    // @TODO Multiple JIT attribute handling is not yet done.
                    //
                    if(type.Name == "JITAttribute")
                    {
                        var props = type.GetProperties();
                        var types = props.First(x => x.Name == "Types");
                        var value = (Type[])types.GetValue(attribute);
                        info = info.MakeGenericMethod(value);
                    }
                }               
            }
            RuntimeHelpers.PrepareMethod(info.MethodHandle);
            var decompiler = new JitCodeDecompiler();
            var decompiled = decompiler.DecompileMethod(info);

            return decompiled;
        }

19 Source : Schema.cs
with MIT License
from baking-bad

public virtual IMicheline MapObject(object obj, bool isValue = false)
        {
            if (isValue)
                return MapValue(obj);

            switch (obj)
            {
                case IEnumerator enumerator:
                    if (!enumerator.MoveNext())
                        throw MapFailedException($"enumerable is over");
                    return MapValue(enumerator.Current);
                case IEnumerable enumerable:
                    var e = enumerable.GetEnumerator();
                    if (!e.MoveNext())
                        throw MapFailedException($"enumerable is empty");
                    return MapValue(e.Current);
                case JsonElement json:
                    if (!json.TryGetProperty(Name, out var jsonProp))
                        throw MapFailedException($"no such property");
                    return MapValue(jsonProp);
                default:
                    var prop = obj?.GetType()?.GetProperty(Name)
                        ?? throw MapFailedException($"no such property");
                    return MapValue(prop.GetValue(obj));
            }
        }

19 Source : Extensions.cs
with The Unlicense
from BAndysc

public static IQuery BulkInsert(this ITable table, IEnumerable<object> objects, bool insertIgnore = false)
        {
            bool first = true;
            PropertyInfo[] properties = null!;
            var sb = new StringBuilder();
            var lines = new List<(string row, bool ignored, string? comment)>();
            PropertyInfo? commentProperty = null;
            PropertyInfo? ignoredProperty = null;
            foreach (var o in objects)
            {
                if (first)
                {
                    var type = o.GetType();
                    commentProperty = type.GetProperty("__comment", BindingFlags.Instance | BindingFlags.Public);
                    ignoredProperty = type.GetProperty("__ignored", BindingFlags.Instance | BindingFlags.Public);
                    properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                        .Where(prop => prop != commentProperty && prop != ignoredProperty)
                        .ToArray();
                    var cols = string.Join(", ", properties.Select(c => $"`{c.Name}`"));
                    var ignore = insertIgnore ? " IGNORE" : "";
                    sb.AppendLine($"INSERT{ignore} INTO `{table.TableName}` ({cols}) VALUES");
                    first = false;
                }

                var comment = (string?)commentProperty?.GetValue(o) ?? null;
                var ignored = (bool)((bool?)ignoredProperty?.GetValue(o) ?? false);
                var row = string.Join(", ", properties.Select(p => p.GetValue(o).ToSql()));
                lines.Add((row, ignored, comment));
            }

            if (first)
                return new Query(table, "");


            var lastNotIgnored = lines.FindLastIndex( row => !row.ignored);
            var lastIgnored = lines.FindLastIndex(row => row.ignored);
            
            for (var index = 0; index < lines.Count; index++)
            {
                var isLast = index == lines.Count - 1;
                var line = lines[index];

                if (line.ignored)
                    sb.Append(" -- ");
                
                sb.Append('(');
                sb.Append(line.Item1);
                sb.Append(')');
                
                if ((lastIgnored == -1 && !isLast) || (lastIgnored >= 0 && (lastIgnored < lastNotIgnored && !isLast) || (lastIgnored > lastNotIgnored && index < lastNotIgnored)))
                    sb.Append(',');
                else
                {
                    if (!line.ignored)
                        sb.Append(';');
                }
                
                if (line.comment != null)
                {
                    sb.Append(" -- ");
                    sb.Append(line.comment);
                }

                if (!isLast)
                    sb.AppendLine();
            }
            
            return new Query(table, sb.ToString());
        }

19 Source : RequiredIfAttribute.cs
with MIT License
from baratgabor

protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            object instance = context.ObjectInstance;
            Type type = instance.GetType();

            if (!bool.TryParse(type.GetProperty(_flagName).GetValue(instance)?.ToString(), out bool flagValue))
            {
                throw new InvalidOperationException($"{nameof(RequiredIfAttribute)} can be used only on bool properties.");
            }

            if (flagValue == _condition && (value == null || (value is string s && string.IsNullOrEmpty(s))))
            {
                return new ValidationResult($"Property {context.MemberName} must have a value when {_flagName} is {_condition}");
            }

            return ValidationResult.Success;
        }

19 Source : ReflectionExtensions.cs
with GNU General Public License v3.0
from BaoStorm

public static bool HasValue(this object obj, string name)
        {
            var currentProperty = obj.GetType().GetRuntimeProperty(name);
            if (currentProperty == null)
                return false;
            var caurrentValue = currentProperty.GetValue(obj);
            var defaultValue = Activator.CreateInstance(obj.GetType()).GetType().GetRuntimeProperty(name).GetValue(obj);
            return caurrentValue != defaultValue;
        }

19 Source : DictionaryExtensions.cs
with MIT License
from barnardos-au

public static IDictionary<string, object> WithParams(this IDictionary<string, object> dictionary, object parameters)
        {
            if (parameters == null) return dictionary;

            foreach (var propertyInfo in (parameters.GetType().GetTypeInfo().DeclaredProperties))
            {
                var key = propertyInfo.Name;
                var value = propertyInfo.GetValue(parameters);
                dictionary.Add(key, value);
            }

            return dictionary;
        }

19 Source : HolderInfo.cs
with MIT License
from bartoszlenar

public object CreateValidator()
        {
            var holderInstance = Activator.CreateInstance(HolderType);
            var holderInterfaceType = typeof(ISpecificationHolder<>).MakeGenericType(SpecifiedType);

            var specificationType = typeof(Specification<>).MakeGenericType(SpecifiedType);

            var specificationPropertyInfo = holderInterfaceType.GetProperty(nameof(ISpecificationHolder<object>.Specification), specificationType);

            var specification = specificationPropertyInfo.GetValue(holderInstance);

            Func<ValidatorSettings, ValidatorSettings> settingsBuilder;

            if (HoldsSettings)
            {
                var settingsPropertyInfo = typeof(ISettingsHolder).GetProperty(nameof(ISettingsHolder.Settings));

                settingsBuilder = settingsPropertyInfo?.GetValue(holderInstance) as Func<ValidatorSettings, ValidatorSettings>;
            }
            else
            {
                settingsBuilder = null;
            }

            var createArgs = new[]
            {
                specification,
                settingsBuilder
            };

            var createMethodInfo = typeof(ValidatorFactory).GetMethods()
                .Single(m =>
                    m.Name == nameof(ValidatorFactory.Create) &&
                    m.IsGenericMethod &&
                    m.GetGenericArguments().Length == 1 &&
                    m.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(Specification<>).GetGenericTypeDefinition() &&
                    m.GetParameters()[1].ParameterType == typeof(Func<ValidatorSettings, ValidatorSettings>))
                .MakeGenericMethod(SpecifiedType);

            var validator = createMethodInfo.Invoke(Validator.Factory, createArgs);

            return validator;
        }

19 Source : MessageKeyTests.cs
with MIT License
from bartoszlenar

[Fact]
        public void All_Should_ContainsAllPaths()
        {
            var counter = 0;

            var globalType = typeof(MessageKey);

            var innerTypes = globalType.GetNestedTypes(BindingFlags.Public | BindingFlags.Static);

            foreach (var innerType in innerTypes)
            {
                var properties = innerType.GetProperties(BindingFlags.Public | BindingFlags.Static);

                foreach (var property in properties)
                {
                    var value = property.GetValue(null);
                    value.Should().BeOfType<string>();
                    counter++;

                    MessageKey.All.Should().Contain(value as string);
                }
            }

            MessageKey.All.Should().NotContainNulls();
            MessageKey.All.Should().HaveCount(counter);
        }

19 Source : MessageKeyTests.cs
with MIT License
from bartoszlenar

[Fact]
        public void Should_HaveAllValuesAsThePathToTheProperty()
        {
            var globalType = typeof(MessageKey);

            var innerTypes = globalType.GetNestedTypes(BindingFlags.Public | BindingFlags.Static);

            foreach (var innerType in innerTypes)
            {
                var properties = innerType.GetProperties(BindingFlags.Public | BindingFlags.Static);

                foreach (var property in properties)
                {
                    var value = property.GetValue(null);

                    value.Should().BeOfType<string>();

                    value.Should().Be($"{innerType.Name}.{property.Name}");
                }
            }
        }

19 Source : ExceptionGuard.cs
with MIT License
from Baseflow

private static object? GetContextFromSender(object sender)
        {
            return sender?.GetType()?.GetProperties()?.FirstOrDefault(f => f.Name == "DataContext")?.GetValue(sender);
        }

19 Source : AddendumUtils.cs
with The Unlicense
from BattletechModders

public static bool LoadDataAddendum(DataAddendumEntry dataAddendumEntry, string modDefDirectory)
        {
            try
            {
                var type = typeof(FactionEnumeration).replacedembly.GetType(dataAddendumEntry.Name);
                if (type == null)
                {
                    Log("\tError: Could not find DataAddendum clreplaced named " + dataAddendumEntry.Name);
                    return false;
                }

                var property = type.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.GetProperty);
                if (property == null)
                {
                    Log("\tError: Could not find static method [Instance] on clreplaced named [" + dataAddendumEntry.Name + "]");
                    return false;
                }

                var bdataAddendum = property.GetValue(null);
                var pCachedEnumerationValueList = type.BaseType.GetProperty("CachedEnumerationValueList");
                if (pCachedEnumerationValueList == null)
                {
                    Log("\tError: Clreplaced does not implement property CachedEnumerationValueList property on clreplaced named [" + dataAddendumEntry.Name + "]");
                    return false;
                }

                var f_enumerationValueList = type.BaseType.GetField("enumerationValueList", BindingFlags.Instance | BindingFlags.NonPublic);
                if (f_enumerationValueList == null)
                {
                    Log("\tError: Clreplaced does not implement field enumerationValueList on clreplaced named [" + dataAddendumEntry.Name + "]");
                    return false;
                }

                var enumList = pCachedEnumerationValueList.GetValue(bdataAddendum, null) as IList;
                if (enumList == null)
                {
                    Log("\tError: Can't get CachedEnumerationValueList from [" + dataAddendumEntry.Name + "]");
                    return false;
                }

                Log("\tCurrent values [" + dataAddendumEntry.Name + "]");
                var maxIndex = 0;
                var names = new Dictionary<string, int>();
                var ids = new Dictionary<int, string>();
                for (var index = 0; index < enumList.Count; ++index)
                {
                    var val = enumList[index] as EnumValue;
                    if (val == null)
                    {
                        continue;
                    }

                    ;
                    Log("\t\t[" + val.Name + ":" + val.ID + "]");
                    if (maxIndex < val.ID)
                    {
                        maxIndex = val.ID;
                    }

                    ;
                    if (names.ContainsKey(val.Name) == false)
                    {
                        names.Add(val.Name, val.ID);
                    }
                    else
                    {
                        names[val.Name] = val.ID;
                    }

                    if (ids.ContainsKey(val.ID) == false)
                    {
                        ids.Add(val.ID, val.Name);
                    }
                    else
                    {
                        ids[val.ID] = val.Name;
                    }
                }

                var pRefreshStaticData = type.GetMethod("RefreshStaticData");
                if (pRefreshStaticData == null)
                {
                    Log("\tError: Clreplaced does not implement method pRefreshStaticData property on clreplaced named [" + dataAddendumEntry.Name + "]");
                    return false;
                }

                var jdataAddEnum = bdataAddendum as IJsonTemplated;
                if (jdataAddEnum == null)
                {
                    Log("\tError: not IJsonTemplated [" + dataAddendumEntry.Name + "]");
                    return false;
                }

                var fileData = File.ReadAllText(Path.Combine(modDefDirectory, dataAddendumEntry.Path));
                jdataAddEnum.FromJSON(fileData);
                enumList = pCachedEnumerationValueList.GetValue(bdataAddendum, null) as IList;
                if (enumList == null)
                {
                    Log("\tError: Can't get CachedEnumerationValueList from [" + dataAddendumEntry.Name + "]");
                    return false;
                }

                var needFlush = false;
                Log("\tLoading values [" + dataAddendumEntry.Name + "] from " + dataAddendumEntry.Path);
                for (var index = 0; index < enumList.Count; ++index)
                {
                    var val = enumList[index] as EnumValue;
                    if (val == null)
                    {
                        continue;
                    }

                    if (names.ContainsKey(val.Name))
                    {
                        val.ID = names[val.Name];
                    }
                    else
                    {
                        if (ids.ContainsKey(val.ID))
                        {
                            if (val.ID == 0)
                            {
                                val.ID = maxIndex + 1;
                                ++maxIndex;
                                names.Add(val.Name, val.ID);
                                ids.Add(val.ID, val.Name);
                            }
                            else
                            {
                                Log("\tError value with same id:" + val.ID + " but different name " + ids[val.ID] + " already exist. Value: " + val.Name + " will not be added");
                                continue;
                            }
                        }
                        else
                        {
                            names.Add(val.Name, val.ID);
                            ids.Add(val.ID, val.Name);
                            if (val.ID > maxIndex)
                            {
                                maxIndex = val.ID;
                            }
                        }
                    }

                    if (val.GetType() == typeof(FactionValue))
                    {
                        MetadataDatabase.Instance.InsertOrUpdateFactionValue(val as FactionValue);
                        Log("\t\tAddind FactionValue to db [" + val.Name + ":" + val.ID + "]");
                        needFlush = true;
                    }
                    else if (val.GetType() == typeof(WeaponCategoryValue))
                    {
                        MetadataDatabase.Instance.InsertOrUpdateWeaponCategoryValue(val as WeaponCategoryValue);
                        Log("\t\tAddind WeaponCategoryValue to db [" + val.Name + ":" + val.ID + "]");
                        needFlush = true;
                    }
                    else if (val.GetType() == typeof(AmmoCategoryValue))
                    {
                        MetadataDatabase.Instance.InsertOrUpdateAmmoCategoryValue(val as AmmoCategoryValue);
                        Log("\t\tAddind AmmoCategoryValue to db [" + val.Name + ":" + val.ID + "]");
                        needFlush = true;
                    }
                    else if (val.GetType() == typeof(ContractTypeValue))
                    {
                        MetadataDatabase.Instance.InsertOrUpdateContractTypeValue(val as ContractTypeValue);
                        Log("\t\tAddind ContractTypeValue to db [" + val.Name + ":" + val.ID + "]");
                        needFlush = true;
                    }
                    else if (val.GetType() == typeof(ShipUpgradeCategoryValue))
                    {
                        MetadataDatabase.Instance.InsertOrUpdateEnumValue(val, "ShipUpgradeCategory", true);
                        Log("\t\tAddind ShipUpgradeCategoryValue to db [" + val.Name + ":" + val.ID + "]");
                        needFlush = true;
                    }
                    else
                    {
                        Log("\t\tUnknown enum type");
                        break;
                    }
                }

                if (needFlush)
                {
                    Log("\tLog: DataAddendum successfully loaded name[" + dataAddendumEntry.Name + "] path[" + dataAddendumEntry.Path + "]");
                    pRefreshStaticData.Invoke(
                        bdataAddendum,
                        new object[]
                        {
                        }
                    );
                    f_enumerationValueList.SetValue(bdataAddendum, null);
                    enumList = pCachedEnumerationValueList.GetValue(bdataAddendum, null) as IList;
                    Log("\tUpdated values [" + dataAddendumEntry.Name + "]");
                    for (var index = 0; index < enumList.Count; ++index)
                    {
                        var val = enumList[index] as EnumValue;
                        if (val == null)
                        {
                            continue;
                        }

                        Log("\t\t[" + val.Name + ":" + val.ID + "]");
                    }
                }

                return needFlush;
            }
            catch (Exception ex)
            {
                Log("\tException: Exception caught while processing DataAddendum [" + dataAddendumEntry.Name + "]");
                Log(ex.ToString());
                return false;
            }
        }

19 Source : TestInitializationContext.cs
with MIT License
from bbepis

public T GetOrCreateSetting<T>( string section, string key, T defaultValue )
      {
         var sectionPropertyInfo = _config.GetType().GetProperty( section );
         if( sectionPropertyInfo == null ) return defaultValue;

         var sectionValue = sectionPropertyInfo.GetValue( _config );
         if( sectionValue == null ) return defaultValue;

         var keyPropertyInfo = sectionValue.GetType().GetProperty( key );
         if( keyPropertyInfo == null ) return defaultValue;

         var value = keyPropertyInfo.GetValue( sectionValue );

         return (T)value;
      }

19 Source : PimsAssert.cs
with Apache License 2.0
from bcgov

public static Paged<T> IsPaged<T>(object obj)
        {
            var type = obj.GetType();
            var itemsProp = type.GetProperty("Items");
            if (itemsProp == null) replacedert.True(false, $"The object is not of the specified type '{typeof(Paged<T>).Name}'.");

            var items = itemsProp.GetValue(obj) as IEnumerable<T>;
            if (items == null) replacedert.True(false, $"The object is not of the specified type '{typeof(Paged<T>).Name}'.");

            var pageProp = type.GetProperty("Page");
            var page = (int)pageProp.GetValue(obj);

            var quanreplacedyProp = type.GetProperty("Quanreplacedy");
            var quanreplacedy = (int)quanreplacedyProp.GetValue(obj);

            var totalProp = type.GetProperty("Total");
            var total = (int)totalProp.GetValue(obj);

            return new Paged<T>(items, page, quanreplacedy, total);

        }

19 Source : PropertiesMapper.cs
with MIT License
from BEagle1984

private static bool TryMapProperty(
            object source,
            object destination,
            PropertyInfo sourcePropertyInfo,
            IEnumerable<PropertyInfo> destPropertiesInfo,
            string destPropertyName)
        {
            var destPropertyInfo = destPropertiesInfo.SingleOrDefault(p => p.Name == destPropertyName);
            if (destPropertyInfo == null)
                return false;

            var setterMethod = destPropertyInfo.GetSetMethod(true);
            if (setterMethod == null)
                return false;

            try
            {
                setterMethod.Invoke(destination, new[] { sourcePropertyInfo.GetValue(source) });
                return true;
            }
            catch (Exception ex)
            {
                throw new EventSourcingException(
                    $"Couldn't map property {sourcePropertyInfo.DeclaringType?.Name}.{sourcePropertyInfo.Name} " +
                    $"to  {destPropertyInfo.DeclaringType?.Name}.{destPropertyInfo.Name}." +
                    "See inner exception for details.",
                    ex);
            }
        }

19 Source : TaskExtensions.cs
with MIT License
from BEagle1984

public static async Task<object?> GetReturnValueAsync(this Task task)
        {
            await task.ConfigureAwait(false);

            var resultProperty = task.GetType().GetProperty("Result");

            return resultProperty?.GetValue(task);
        }

19 Source : DocsGenerator.cs
with MIT License
from BEagle1984

public static void GenerateDocsTable(Type logEventsType)
        {
            Console.WriteLine("Id | Level | Message | Reference");
            Console.WriteLine(":-- | :-- | :-- | :--");

            foreach (var property in logEventsType.GetProperties())
            {
                var logEvent = (LogEvent)property.GetValue(null)!;

                EventIdSet.Add(logEvent.EventId.Id);

                var apiReferenceLink =
                    $"[{property.Name}]" +
                    $"(xref:{logEventsType.FullName}" +
                    $"#{logEventsType.FullName!.Replace(".", "_", StringComparison.Ordinal)}" +
                    $"_{property.Name})";

                var message = logEvent.Message.Replace("|", "|", StringComparison.Ordinal);

                Console.WriteLine(
                    $"{logEvent.EventId.Id} | {logEvent.Level} | {message} | {apiReferenceLink}");
            }
        }

19 Source : FrmProperties.cs
with Apache License 2.0
from beetlex-io

public virtual void Init()
			{

				SetControlData(this.Property.GetValue(this.Target));
			}

19 Source : XRPCClientDelegateExpend.cs
with Apache License 2.0
from beetlex-io

public object GetValue(object result)
        {
            if (mResultProperty != null)
                return mResultProperty.GetValue(result);
            return null;
        }

19 Source : ReflectionHelper.cs
with Apache License 2.0
from benaadams

public static IList<string>? GetTransformerNames(this Attribute attribute)
        {
            Debug.replacedert(attribute.IsTupleElementNameAttribute());

            var propertyInfo = GetTransformNamesPropertyInfo(attribute.GetType());
            return propertyInfo?.GetValue(attribute) as IList<string>;
        }

19 Source : PersistedHookedComponentBase.cs
with MIT License
from BerserkerDotNet

protected (T, Action<T>) UseState<T>(Expression<Func<TState, T>> propertyMap)
        {
            var state = GetStateProperty();
            if (state is null)
            {
                throw new ArgumentNullException(nameof(state));
            }

            var memberExp = propertyMap.Body as MemberExpression;
            if (memberExp is null)
            {
                throw new ArgumentException($"{nameof(propertyMap)} is not of type {nameof(MemberExpression)}.");
            }

            var property = memberExp.Member as PropertyInfo;
            if (property is null)
            {
                throw new ArgumentException("Couldn't extract property from member expression.");
            }

            var initialValue = property.GetValue(state);
            var (prop, setProp) = UseState((T)initialValue);
            if (!_isInitialized)
            {
                _properties.Add(property);
            }

            Action<T> persistedSetProp = p =>
            {
                if (!_isDeferred)
                {
                    property.SetValue(state, p);
                }

                setProp(p);
            };

            return (prop, persistedSetProp);
        }

19 Source : PersistedHookedComponentBase.cs
with MIT License
from BerserkerDotNet

protected virtual TState GetStateProperty()
        {
            const string defaultStatePropertyName = "Props";
            var stateProperty = GetType().GetProperty(defaultStatePropertyName);
            if (stateProperty is null)
            {
                throw new StatePropertyNotFoundException($"Couldn't find property '{defaultStatePropertyName}' on component {GetType()}");
            }

            if (stateProperty.PropertyType != typeof(TState))
            {
                throw new IncorrectPropertyTypeException($"Expected '{defaultStatePropertyName}' to be of type {typeof(TState)}, but found {stateProperty.PropertyType}");
            }

            return (TState)stateProperty.GetValue(this);
        }

19 Source : PersistedHookedComponentBase.cs
with MIT License
from BerserkerDotNet

protected void Persist()
        {
            var state = GetStateProperty();
            if (state is null)
            {
                throw new ArgumentNullException(nameof(state));
            }

            foreach (var property in _properties)
            {
                var initialValue = property.GetValue(state);
                var (value, _) = UseState(initialValue);
                property.SetValue(state, value);
            }

            Service.ComponentRendered(this);
        }

19 Source : BaseOptionModel.cs
with MIT License
from bert2

public virtual async Task SaveAsync() {
            ShellSettingsManager manager = await _settingsManager.GetValueAsync();
            WritableSettingsStore settingsStore = manager.GetWritableSettingsStore(SettingsScope.UserSettings);

            if (!settingsStore.CollectionExists(CollectionName)) {
                settingsStore.CreateCollection(CollectionName);
            }

            foreach (PropertyInfo property in GetOptionProperties()) {
                string output = SerializeValue(property.GetValue(this));
                settingsStore.SetString(CollectionName, property.Name, output);
            }

            T liveModel = await GetLiveInstanceAsync();

            if (this != liveModel) {
                await liveModel.LoadAsync();
            }
        }

19 Source : AggregateReducer.cs
with MIT License
from BerserkerDotNet

public TState Reduce(TState state, IAction action)
        {
            var stateType = typeof(TState);
            var newState = new TState();
            var properties = stateType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (var property in properties)
            {
                if (_reducersMap.ContainsKey(property.Name) && property.SetMethod != null)
                {
                    var reducer = _reducersMap[property.Name];
                    var currentValue = state == null ? null : property.GetValue(state);

                    // TODO: Cache?
                    var reducerType = reducer.GetType();
                    if (!IsreplacedignableToGenericType(reducerType, typeof(IReducer<>)))
                    {
                        throw new ArgumentException($"Type {reducerType} is not replacedignable to {typeof(IReducer<TState>)}");
                    }

                    var newValue = reducerType.InvokeMember(nameof(IReducer<TState>.Reduce), BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, reducer, new object[] { currentValue, action });
                    property.SetValue(newState, newValue);
                }
            }

            return newState;
        }

19 Source : Language.cs
with Mozilla Public License 2.0
from BibleBot

public string GetCommandKey(string value)
        {
            var commands = RawLanguage.GetType().GetProperty("Commands").GetValue(RawLanguage.Commands, null);

            foreach (var possibleCommandKey in commands.GetType().GetProperties())
            {
                var commandValue = (string)possibleCommandKey.GetValue(commands);

                if (value == commandValue)
                {
                    return (string)possibleCommandKey.Name;
                }
            }

            throw new StringNotFoundException();
        }

19 Source : SequelizeStructured.cs
with MIT License
from BigBigZBBing

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        static List<string> SequelizeCriteria(object m_where, string modelStr)
        {
            List<string> cache = new List<string>();
            // 等于 [2021-1-28 zhangbingbin]
            var eq = m_where.GetType().GetProperty("eq");
            if (eq != null) cache.Add(SequelizeWhere(eq.GetValue(m_where), modelStr, "="));
            // 不等于 [2021-1-28 zhangbingbin]
            var ne = m_where.GetType().GetProperty("ne");
            if (ne != null) cache.Add(SequelizeWhere(ne.GetValue(m_where), modelStr, "!="));
            // 大于 [2021-1-28 zhangbingbin]
            var gt = m_where.GetType().GetProperty("gt");
            if (gt != null) cache.Add(SequelizeWhere(gt.GetValue(m_where), modelStr, ">"));
            // 大于等于 [2021-1-28 zhangbingbin]
            var gte = m_where.GetType().GetProperty("gte");
            if (gte != null) cache.Add(SequelizeWhere(gte.GetValue(m_where), modelStr, ">="));
            // 小于 [2021-1-28 zhangbingbin]
            var lt = m_where.GetType().GetProperty("lt");
            if (lt != null) cache.Add(SequelizeWhere(lt.GetValue(m_where), modelStr, "<"));
            // 小于等于 [2021-1-28 zhangbingbin]
            var lte = m_where.GetType().GetProperty("lte");
            if (lte != null) cache.Add(SequelizeWhere(lte.GetValue(m_where), modelStr, "<="));
            // 包含 [2021-1-28 zhangbingbin]
            var In = m_where.GetType().GetProperty("In");
            if (In != null) cache.Add(SequelizeIn(In.GetValue(m_where), modelStr));
            // 不包含 [2021-1-28 zhangbingbin]
            var notIn = m_where.GetType().GetProperty("notIn");
            if (notIn != null) cache.Add(SequelizeNotIn(notIn.GetValue(m_where), modelStr));
            // 与 [2021-1-28 zhangbingbin]
            var and = m_where.GetType().GetProperty("and");
            if (and != null) cache.Add($"({string.Join(" AND ", SequelizeCriteria(and.GetValue(m_where), modelStr))})");
            // 或 [2021-1-28 zhangbingbin]
            var or = m_where.GetType().GetProperty("or");
            if (or != null) cache.Add($"({string.Join(" OR ", SequelizeCriteria(or.GetValue(m_where), modelStr))})");
            // 模糊匹配 [2021-1-28 zhangbingbin]
            var like = m_where.GetType().GetProperty("like");
            if (like != null) cache.Add(SequelizeLike(like.GetValue(m_where), modelStr, "LIKE"));
            // 反向模糊 [2021-1-28 zhangbingbin]
            var notlike = m_where.GetType().GetProperty("notlike");
            if (notlike != null) cache.Add(SequelizeLike(notlike.GetValue(m_where), modelStr, "NOT LIKE"));

            var not = m_where.GetType().GetProperty("not");
            var between = m_where.GetType().GetProperty("between");
            var notBetween = m_where.GetType().GetProperty("notBetween");

            return cache;
        }

19 Source : SequelizeStructured.cs
with MIT License
from BigBigZBBing

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        static void LoadDataSource(object instance, string filter = "")
        {
            var type = (Type)instance.GetType();
            var clreplacedName = type.Name;
            if (type.Name.Equals("List`1")) clreplacedName = type.GenericTypeArguments[0].Name;
            PropertyInfo[] props = null;
            object listinstance = null;
            // 如果是链表结构 [2021-1-23 zhangbingbin]
            if (type.IsGenericType)
            {
                listinstance = instance;
                props = type.GetGenericArguments()[0].GetProperties();
            }
            else props = type.GetProperties();

            var cre = "";
            if (clreplacedName[0].Equals('_')) cre = clreplacedName.Substring(1) + "->";
            var related = props.Where(x =>
            {
                if (x.PropertyType.Name.Equals("List`1"))
                    return x.PropertyType.GenericTypeArguments[0].Name[0] != '_';
                return x.PropertyType.Name[0] != '_';
            }).Select(x => cre + x.Name);
            List<string> fields = new List<string>();
            if (clreplacedName[0].Equals('_'))
            {
                foreach (DataColumn dc in DataSource.Columns)
                {
                    var value = related.Count(x => dc.ColumnName.IndexOf(x, StringComparison.OrdinalIgnoreCase) > -1);
                    if (value > 0) fields.Add(dc.ColumnName);
                }
            }
            else fields = related.ToList();

            // 获取对应的子集 [2021-2-6 zhangbingbin]
            DataTable table = null;
            if (!CacheDistinctTable.ContainsKey(clreplacedName))
            {
                CacheDistinctTable.Add(clreplacedName, DataSource.DefaultView.ToTable(true, fields.ToArray()));
                table = CacheDistinctTable[clreplacedName];
            }
            else table = CacheDistinctTable[clreplacedName];

            if (!string.IsNullOrEmpty(filter))
            {
                var drs = table.Select(filter);
                if (drs.Count() > 0)
                    table = drs.CopyToDataTable();
                else
                    table = table.Clone();
            }

            foreach (DataRow dr in table.Rows)
            {
                if (type.IsGenericType)
                    instance = Activator.CreateInstance(type.GetGenericArguments()[0]);

                foreach (var item in props)
                {
                    if (item.PropertyType.Name.Equals("List`1"))
                    {
                        item.SetValue(instance, Activator.CreateInstance(item.PropertyType));
                        filter = $" [({clreplacedName}){item.Name}->{UniqueMapping[item.Name]}] = '{props.FirstOrDefault(x => x.Name == UniqueMapping[item.Name]).GetValue(instance)}' ";
                        LoadDataSource(item.GetValue(instance), filter);
                    }
                    else
                    {
                        if (clreplacedName[0].Equals('_'))
                        {
                            var value = dr[fields.FirstOrDefault(x =>
                                            x.IndexOf(clreplacedName.Substring(1) + "->" + item.Name, StringComparison.OrdinalIgnoreCase) > -1)];
                            item.SetValue(instance, value == DBNull.Value ? null : value);
                        }
                        else
                        {
                            item.SetValue(instance, dr[item.Name] == DBNull.Value ? null : dr[item.Name]);
                        }
                    }
                }
                if (type.IsGenericType && listinstance != null)
                    type.GetMethod("Add").Invoke(listinstance, new object[] { instance });
            }
        }

19 Source : Kit.DataTable.cs
with MIT License
from BigBigZBBing

public static DataTable ToDataTable<T>(this IEnumerable<T> list)
        {
            DataTable dt = new DataTable();
            bool first = true;
            Type type = null;
            PropertyInfo[] properties = null;
            foreach (var item in list)
            {
                if (first)
                {
                    type = type ?? item.GetType();
                    properties = properties ?? type.GetProperties();
                    foreach (var prop in properties)
                        dt.Columns.Add(prop.Name, prop.PropertyType);
                    first = false;
                }
                DataRow value = dt.NewRow();
                foreach (DataColumn dc in dt.Columns)
                {
                    value[dc.ColumnName] = properties
                        .FirstOrDefault(x => x.Name == dc.ColumnName)
                        .GetValue(item);
                }
                dt.Rows.Add(value);
            }
            return dt;
        }

19 Source : SequelizeStructured.cs
with MIT License
from BigBigZBBing

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        static string SequelizeToSql(object config, string sql = "", string prev = "")
        {
            // 判断是否第一次 [2021-1-24 zhangbingbin]
            First = string.IsNullOrEmpty(sql);
            if (First)
            {
                // 初始化 [2021-1-24 zhangbingbin]
                Fields = new List<string>();
                UniqueMapping = new Dictionary<string, string>();
                CacheDistinctTable = new Dictionary<string, DataTable>();
            }
            List<string> cache = new List<string>();

            // 显示的字段名(必须带主键) [2021-1-25 zhangbingbin]
            var fieldsProp = config.GetType().GetProperty("fields");
            if (fieldsProp.IsNull()) throw new ArgumentNullException("fields不可为空 请使用数组格式展示字段");

            // 表名 [2021-1-25 zhangbingbin]
            var modelProp = config.GetType().GetProperty("model");
            if (modelProp.IsNull()) throw new ArgumentNullException("model不可为空 请输入表名");

            // 查询条件 [2021-1-25 zhangbingbin]
            var where = config.GetType().GetProperty("where");

            // 是否左外连接 [2021-1-25 zhangbingbin]
            var required = config.GetType().GetProperty("required");

            // 联合查询配置 [2021-1-25 zhangbingbin]
            var include = config.GetType().GetProperty("include");

            // 限制查询结果数量 [2021-2-6 zhangbingbin]
            var limit = config.GetType().GetProperty("limit");

            // 获取表名参数 [2021-1-24 zhangbingbin]
            string modelStr = modelProp.GetValue(config).ToString();
            if (First) MainTable = modelStr;

            // 获取结果显示字段 [2021-1-23 zhangbingbin]
            var fields = (object[])fieldsProp.GetValue(config);
            foreach (var item in fields)
            {
                string origin = "";
                string show = "";
                if (item is string[] asfield)
                {
                    origin = asfield[0];
                    show = asfield[1];
                }
                else if (item is string field)
                {
                    origin = field;
                    show = field;
                }
                if (First)
                {
                    Fields.Add($"`_{modelStr}`." + $"`{origin}` AS `{show}`");
                }
                else
                {
                    Fields.Add($"`_{modelStr}`." + $"`{origin}` AS `({prev}){modelStr}->{show}`");
                }
            }

            // 获取查询条件 [2021-1-23 zhangbingbin]
            if (where.NotNull())
            {
                cache = SequelizeCriteria(where.GetValue(config), modelStr);
            }

            // 第一次递归 [2021-1-23 zhangbingbin]
            if (First)
            {
                sql = $"SELECT {{0}} FROM `{modelStr}` AS `_{modelStr}`";
            }

            // 关联查询 [2021-1-23 zhangbingbin]
            else
            {
                // 联合关联字段 [2021-1-26 zhangbingbin]
                var join = config.GetType().GetProperty("join");
                if (join.IsNull()) throw new ArgumentNullException("关联模式必须填关联字段");

                var joinObj = join.GetValue(config);
                var keyOn = "";
                foreach (var item in joinObj.GetType().GetProperties())
                {
                    if (keyOn != "") keyOn += "=";
                    var value = item.GetValue(joinObj);
                    keyOn += $"`_{item.Name}`.`{value}`";
                    //缓存每个表对应的Key
                    if (!UniqueMapping.ContainsKey(item.Name))
                        UniqueMapping.Add(item.Name, value.ToString());
                }
                // 如果存在条件又不设置 则转成内连接 [2021-1-24 zhangbingbin]
                if (where.IsNull() || (required.NotNull() && !(bool)required.GetValue(config)))
                {
                    sql += $" LEFT OUTER JOIN `{modelStr}` AS `_{modelStr}` ON {keyOn} ";
                    if (cache.Count > 0) sql += "AND " + string.Join(" AND ", cache);
                }
                else
                {
                    sql += $" INNER JOIN `{modelStr}` AS `_{modelStr}` ON {keyOn} ";
                    if (cache.Count > 0) sql += "AND " + string.Join(" AND ", cache);
                }
            }

            if (include.NotNull())
            {
                var join = include.GetValue(config);
                if (join is Array includes)
                {
                    foreach (var item in includes)
                    {
                        sql = SequelizeToSql(item, sql, modelStr);
                    }
                }
            }
            sql = string.Format(sql, string.Join(",", Fields));

            if (prev == "" && cache.Count > 0)
                sql += " WHERE " + string.Join(" AND ", cache);

            if (limit.NotNull())
            {
                sql += $" LIMIT {limit.GetValue(config)} ";
            }

            return sql;
        }

19 Source : LessThanAttribute.cs
with MIT License
from BigEggTools

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null) { return new ValidationResult($"Property '{validationContext.MemberName}' have null value.", new List<string>() { validationContext.MemberName, dependentPropertyName }); }
            if (!(value is IComparable)) { return new ValidationResult($"Property '{validationContext.MemberName}' should be comparable."); }

            var dependentPropertyInfo = validationContext.ObjectType.GetProperty(this.dependentPropertyName);
            if (dependentPropertyInfo == null) { return new ValidationResult($"Cannot find the dependent property '{dependentPropertyName}'.", new List<string>() { validationContext.MemberName, dependentPropertyName }); }

            var dependentPropertyValue = dependentPropertyInfo.GetValue(validationContext.ObjectInstance);
            if (dependentPropertyValue == null) { return new ValidationResult($"Property '{dependentPropertyName}' have null value.", new List<string>() { validationContext.MemberName, dependentPropertyName }); }
            if (!(dependentPropertyValue is IComparable)) { return new ValidationResult($"Property '{dependentPropertyName}' should be comparable.", new List<string>() { validationContext.MemberName, dependentPropertyName }); }

            if (value.GetType() != dependentPropertyValue.GetType()) { return new ValidationResult($"Property '{validationContext.MemberName}' and property '{dependentPropertyName}' should have same type.", new List<string>() { validationContext.MemberName, dependentPropertyName }); }

            var compareResult = (value as IComparable).CompareTo(dependentPropertyValue as IComparable);
            if (compareResult > 0 || (compareResult == 0 && !allowEqual))
            {
                return new ValidationResult(ErrorMessage ?? $"Property '{validationContext.MemberName}' Should less than property '{dependentPropertyName}'.", new List<string>() { validationContext.MemberName, dependentPropertyName });
            }
            return ValidationResult.Success;
        }

19 Source : SequelizeStructured.cs
with MIT License
from BigBigZBBing

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        static string SequelizeWhere(object obj, string model, string symbol = "")
        {
            string result = "";
            var condition = obj.GetType().GetProperties();
            foreach (var item in condition)
            {
                if (result != "") result += " AND ";
                var value = item.GetValue(obj);
                var param = "";
                if (value == null) param = "NULL";
                else if (value is string str) param = $"'{str}'";
                else if (value is int m_int) param = $"{m_int}";
                else if (value is DateTime date) param = $"{date}";
                else param = "NULL";
                if (symbol == "=" && param == "NULL")
                    result += $"`_{model}`.`{item.Name}` IS NULL";
                else if (symbol == "!=" && param == "NULL")
                    result += $"`_{model}`.`{item.Name}` IS NOT NULL";
                else
                    result += $"`_{model}`.`{item.Name}` {symbol} {param}";
            }
            return result;
        }

19 Source : SequelizeStructured.cs
with MIT License
from BigBigZBBing

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        static string SequelizeLike(object obj, string model, string symbol = "")
        {
            string result = "";
            var condition = obj.GetType().GetProperties();
            foreach (var item in condition)
            {
                if (result != "") result += " AND ";
                var value = item.GetValue(obj);
                var param = "";
                if (value == null) param = "NULL";
                else if (value is string
                    && value.ToString().Length > 0
                    && value.ToString()[0] == '@') param = $"{value}";
                else if (value is string str) param = $"'%{str}%'";
                else param = "NULL";
                result += $"`_{model}`.`{item.Name}` {symbol} {param}";
            }
            return result;
        }

19 Source : SequelizeStructured.cs
with MIT License
from BigBigZBBing

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        static string SequelizeIn(object obj, string model)
        {
            string result = "";
            var condition = obj.GetType().GetProperties();
            foreach (var item in condition)
            {
                if (result != "") result += " AND ";
                var arr = item.GetValue(obj);
                var value = "";
                // 判断char类型 [2021-1-23 zhangbingbin]
                if (arr is string[] arr1)
                {
                    foreach (var item1 in arr1)
                    {
                        if (value != "") value += ",";
                        value += $"'{item1}'";
                    }
                }
                // 判断int类型 [2021-1-23 zhangbingbin]
                if (arr is int[] arr2)
                {
                    foreach (var item1 in arr2)
                    {
                        if (value != "") value += ",";
                        value += $"{item1}";
                    }
                }
                // 判断参数化 [2021-1-23 zhangbingbin]
                if (arr is string arr3)
                {
                    value += $"{arr3}";
                }
                if (First)
                    result += $"`_{model}`.`{item.Name}` IN ({value})";
                else
                    result += $"`_{model}`.`{model}->{item.Name}` IN ({value})";
            }

            return result;
        }

19 Source : Kit.cs
with MIT License
from BigBigZBBing

public static T XmlToEnreplacedy<T>(this XElement element) where T : clreplaced, new()
        {
            T obj = Activator.CreateInstance(typeof(T)) as T;
            AttrSetProp(element.Attributes(), obj);
            WhileElements(element, obj);
            return obj;

            void WhileElements(XElement eles, object param0)
            {
                Type type = param0.GetType();
                foreach (var ele in eles.Elements())
                {
                    var prop = type.GetProperty(ele.Name.LocalName);
                    if (prop.IsNull() || !prop.PropertyType.IsGenericType || prop.PropertyType.GenericTypeArguments.NotExist()) continue;
                    var List = prop.GetValue(param0) ?? Activator.CreateInstance(prop.PropertyType);
                    var itemType = prop.PropertyType.GenericTypeArguments.FirstOrDefault();
                    var Add = prop.PropertyType.GetMethod("Add", new[] { itemType });
                    if (Add.IsNull()) continue;
                    var instance = Activator.CreateInstance(itemType);
                    Add.Invoke(List, new object[] { instance });
                    AttrSetProp(ele.Attributes(), instance);
                    if (ele.HasElements)
                    {
                        WhileElements(ele, instance);
                    }
                    prop.SetValue(param0, List);
                }
            }

            void AttrSetProp(IEnumerable<XAttribute> attrs, object param1)
            {
                Type type = param1.GetType();
                foreach (var attr in attrs)
                {
                    var prop = type.GetProperty(attr.Name.LocalName);
                    if (prop.IsNull()) continue;
                    prop.SetValue(param1, attr.Value);
                }
            }
        }

19 Source : SequelizeStructured.cs
with MIT License
from BigBigZBBing

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        static string SequelizeNotIn(object obj, string model)
        {
            string result = "";
            var condition = obj.GetType().GetProperties();
            foreach (var item in condition)
            {
                if (result != "") result += " AND ";
                var arr = item.GetValue(obj);
                var value = "";
                // 判断char类型 [2021-1-23 zhangbingbin]
                if (arr is string[] arr1)
                {
                    foreach (var item1 in arr1)
                    {
                        if (value != "") value += ",";
                        value += $"'{item1}'";
                    }
                }
                // 判断int类型 [2021-1-23 zhangbingbin]
                if (arr is int[] arr2)
                {
                    foreach (var item1 in arr2)
                    {
                        if (value != "") value += ",";
                        value += $"{item1}";
                    }
                }
                // 判断参数化 [2021-1-23 zhangbingbin]
                if (arr is string arr3)
                {
                    value += $"{{{arr3}}}";
                }
                if (First)
                    result += $"`_{model}`.`{item.Name}` IN ({value})";
                else
                    result += $"`_{model}`.`{model}->{item.Name}` IN ({value})";
            }

            return result;
        }

19 Source : MethodDef.cs
with MIT License
from bilal-fazlani

private IEnumerable<IArgumentDef> GetArgsFromProperty(PropertyData propertyData, object modelInstance, ArgumentMode argumentMode)
            {
                var propertyInfo = propertyData.PropertyInfo;
                return propertyData.IsArgModel
                    ? GetArgumentsFromModel(
                        propertyInfo.PropertyType,
                        argumentMode,
                        propertyInfo.GetValue(modelInstance),
                        value => propertyInfo.SetValue(modelInstance, value), propertyData)
                    : new PropertyArgumentDef(
                            propertyInfo,
                            GetArgumentType(propertyInfo, argumentMode),
                            _appConfig,
                            modelInstance)
                        .ToEnumerable();
            }

19 Source : ExceptionExtensions.cs
with MIT License
from bilal-fazlani

public static void Print(this Exception ex, Action<string?> writeLine, Indent? indent = null, 
            bool includeProperties = false, bool includeData = false, bool includeStackTrace = false)
        {
            if (ex is null)
            {
                throw new ArgumentNullException(nameof(ex));
            }

            indent ??= new Indent();
            writeLine($"{indent}{ex.GetType().FullName}: {ex.Message}");
            
            if (includeProperties)
            {
                var properties = ex.GetType()
                    .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                    .Where(p => p.DeclaringType != typeof(Exception))
                    .ToList();
                if (properties.Any())
                {
                    writeLine($"{indent}{Resources.A.Exceptions_Properties}:");
                    indent = indent.Increment();
                    foreach (var property in properties)
                    {
                        writeLine($"{indent}{property.Name}: {property.GetValue(ex).ToIndentedString(indent)}");
                    }
                    indent = indent.Decrement();
                }
            }

            if (includeData && ex.Data.Count > 0)
            {
                writeLine($"{indent}{Resources.A.Exceptions_Data}:");
                indent = indent.Increment();
                foreach (DictionaryEntry entry in ex.Data)
                {
                    var skip = entry.Value is NonSerializableWrapper { SkipPrint: true };
                    if (!skip)
                    {
                        writeLine($"{indent}{entry.Key}: {entry.Value.ToIndentedString(indent)}");
                    }
                }
                indent = indent.Decrement();
            }

            if (includeStackTrace && ex.StackTrace is { })
            {
                writeLine($"{indent}{Resources.A.Exceptions_StackTrace}:");
                indent = indent.Increment();
                // replace default indents
                var stack = ex.StackTrace.Replace(
                    $"{Environment.NewLine}   {Resources.A.Exceptions_StackTrace_at} ", 
                    $"{Environment.NewLine}{indent}{Resources.A.Exceptions_StackTrace_at} ");
                writeLine($"{indent}{stack.Remove(0,3)}");
                indent.Decrement();
            }
        }

See More Examples