System.Type.GetProperty(string)

Here are the examples of the csharp api System.Type.GetProperty(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3421 Examples 7

19 Source : GeneralSettings.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

private string GetEnvironmentOrPropertyValue(string propertyName)
        {
            var prop = this.GetType().GetProperty(propertyName);
            if (prop == null)
            {
                throw new ArgumentException($"This clreplaced does not have any property with the name {propertyName}");
            }

            string envValue = Environment.GetEnvironmentVariable("GeneralSettings__" + propertyName);

            return envValue ?? prop.GetValue(this).ToString();
        }

19 Source : PropertyViewModel.cs
with MIT License
from Aminator

private void Fill()
        {
            if (HasUnrealizedChildren)
            {
                IList list = (IList)Value!;

                if (list.Count == 0) return;

                PropertyInfo itemProperty = typeof(IList).GetProperty("Item");

                Items = new ObservableViewModelCollection<PropertyViewModel>(list, vm => vm.Value, (m, i) => PropertyViewModelFactory.Default.Create(list, itemProperty, i));

                HasUnrealizedChildren = false;
            }
        }

19 Source : GeneratedCodeAttributeGeneratorTests.cs
with MIT License
from amis92

[Fact]
        public void ReflectedClreplacedNestedTypeProperty_DoesHaveGeneratedCodeAttribute()
        {
            var recordType = typeof(Item);
            var nestedTypeMember = recordType.GetNestedType(nameof(Item.Builder))
                .GetProperty(nameof(Item.Builder.Name));

            nestedTypeMember.Should()
                .BeDecoratedWith(GeneratedCodeAttributeWithCorrectToolNameAndVersion);
        }

19 Source : ObjectInfo.cs
with MIT License
from amolines

public PropertyInfo GetProperty(Type type, string name)
        {
            return type.GetProperty(name);
        }

19 Source : ThemingService.GetTheme.cs
with Apache License 2.0
from AmpScm

private bool GetThemeViaApi(out Guid themeGuid)
        {
            if (_themeService == null)
            {
                _themeService = GetService<IAnkhQueryService>().QueryService<object>(new Guid("0D915B59-2ED7-472A-9DE8-9161737EA1C5"));
            }

            if (_themeService != null && _currentThemeProperty == null)
            {
                _currentThemeProperty = _themeService.GetType().GetProperty("CurrentTheme");
            }

            if (_currentThemeProperty != null)
            {
                object currentTheme = _currentThemeProperty.GetValue(_themeService, null);

                if (currentTheme != null)
                {
                    if (_themeIdProperty == null)
                        _themeIdProperty = currentTheme.GetType().GetProperty("ThemeId");

                    if (_themeIdProperty != null)
                    {
                        themeGuid = (Guid)_themeIdProperty.GetValue(currentTheme, null);
                        return true;
                    }
                }
            }

            themeGuid = Guid.Empty;
            return false;
        }

19 Source : ThemingService.cs
with Apache License 2.0
from AmpScm

private void SetProperty(PropertyGrid grid, string propertyName, object value)
        {
            PropertyInfo pi = typeof(PropertyGrid).GetProperty(propertyName);

            Debug.replacedert(pi != null, "Grid Property exists");
            if (pi != null)
                pi.SetValue(grid, value, null);
        }

19 Source : Program.cs
with MIT License
from anastasios-stamoulis

static void Main(string[] args) {
      // make sure that the hard-coded values have been set up correctly
      if ( System.IO.Directory.Exists(PYTHON_HOME_)==false ) {
        throw new NotSupportedException("Please set PYTHON_HOME_ properly");
      }
      if ( System.IO.File.Exists(PYTHONNET_DLL_)==false ) {
        throw new NotSupportedException("Probably you have not pip-installed pythonnet");
      }
      if ( System.IO.Directory.Exists(KERAS_PORTED_CODE_)==false ) {
        throw new NotSupportedException("Need to initialize KERAS_PORTED_CODE_");
      }
      System.Console.replacedle = "Ch_08_Deep_Dream";

      // set model_path, and image_path
      var vgg16_model_path = DeepLearningWithCNTK.VGG16.download_model_if_needed();
      var image_path = DeepLearningWithCNTK.Util.get_the_path_of_the_elephant_image();

      // modify the environment variables
      var to_be_added_to_path = PYTHON_HOME_ + ";" + KERAS_PORTED_CODE_;
      var path = Environment.GetEnvironmentVariable("PATH");
      path = to_be_added_to_path + ";" + path;
      Environment.SetEnvironmentVariable("PATH", path);
      Environment.SetEnvironmentVariable("PYTHONPATH", path);

      // load the Python.NET dll, and start the (embedded) Python engine
      var dll = System.Reflection.replacedembly.LoadFile(PYTHONNET_DLL_);
      var PythonEngine = dll.GetType("Python.Runtime.PythonEngine");

      // to be on the safe side, update the PythonPath of the local engine
      var PythonPathProperty = PythonEngine.GetProperty("PythonPath");
      var pythonPath = (string)PythonPathProperty.GetValue(null);
      pythonPath += ";" + KERAS_PORTED_CODE_;
      pythonPath += ";" + PYTHON_HOME_ + "\\Lib\\site-packages";
      PythonPathProperty.SetValue(null, pythonPath);

      // let's start executing some python code
      dynamic Py = dll.GetType("Python.Runtime.Py");
      dynamic GIL = Py.GetMethod("GIL").Invoke(null, null);

      // import "ch8-2.py"
      dynamic ch8_2 = Py.GetMethod("Import").Invoke(null, new object[] { "ch8-2" });

      // response = ch8_2.get_response("Hi From C#")
      var response = ch8_2.get_response("Hi From C#");
      Console.WriteLine("C# received: "+response);
      Console.WriteLine("\n\n");

      // let's call the run_cntk function from the Python script
      var img = ch8_2.run_cntk(image_path, vgg16_model_path);

      // convert the python numpy array to byte[]
      byte[] img_data = convert_uint8_numpy_array_to_byte_array(img);

      // display the image with OpenCV
      var mat = new OpenCvSharp.Mat(224, 224, OpenCvSharp.MatType.CV_8UC3, img_data, 3 * 224);
      OpenCvSharp.Cv2.ImShow("The Dream", mat);

      // Show also the original image
      OpenCvSharp.Cv2.ImShow("Original", OpenCvSharp.Cv2.ImRead(image_path).Resize(new OpenCvSharp.Size(224, 224)));

      OpenCvSharp.Cv2.WaitKey(0);

      GIL.Dispose();
    }

19 Source : TypeExtensions.cs
with Apache License 2.0
from AndcultureCode

public static PropertyInfo GetPublicPropertyInfo(this Type type, string propertyName)
        {
            if (!type.HasPublicProperty(propertyName))
            {
                return null;
            }

            return type.GetProperty(propertyName);
        }

19 Source : TypeExtensions.cs
with Apache License 2.0
from AndcultureCode

public static object GetPublicPropertyValue(this object src, string propertyName)
        {
            if (src == null)
            {
                return null;
            }

            if (!src.GetType().HasPublicProperty(propertyName))
            {
                return null;
            }

            return src.GetType().GetProperty(propertyName)?.GetValue(src);
        }

19 Source : UI.cs
with GNU General Public License v3.0
from AndrasMumm

public static MethodBase TargetMethod()
        {
            return typeof(WGText).GetProperty("Text").GetSetMethod();
        }

19 Source : ListMarshalerFactory.cs
with GNU General Public License v3.0
from AndreiFedarets

public bool CanMarshal(Type type)
        {
            if (!IsList(type))
            {
                return false;
            }
            Type elementType = type.GetProperty("Item").PropertyType;
            return MarshalingManager.IsKnownType(elementType);
        }

19 Source : ListMarshalerFactory.cs
with GNU General Public License v3.0
from AndreiFedarets

public bool TryCreate(Type type, out ITypeMarshaler typeMarshaler)
        {
            if (!IsList(type))
            {
                typeMarshaler = null;
                return false;
            }
            Type elementType = type.GetProperty("Item").PropertyType;
            ITypeMarshaler elementMarshaler = MarshalingManager.GetMarshaler(elementType);
            if (elementMarshaler == null)
            {
                typeMarshaler = null;
                return false;
            }
            typeMarshaler = new ListMarshaler(type, elementMarshaler);
            return true;
        }

19 Source : MappingExtensions.cs
with GNU General Public License v3.0
from andysal

public static EnreplacedyTypeConfiguration<TEnreplacedy> FixedOrderItemHasKey<TEnreplacedy>(this EnreplacedyTypeConfiguration<TEnreplacedy> mapper, String columnKey1, String columnKey2)
            where TEnreplacedy : clreplaced
        {
            Type type = typeof(TEnreplacedy);
            PropertyInfo p1 = type.GetProperty(columnKey1, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
            PropertyInfo p2 = type.GetProperty(columnKey2, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

            ParameterExpression parameterExpression = Expression.Parameter(type, "x");

            MemberExpression memberExpression1 = Expression.Property(parameterExpression, p1);
            MemberExpression memberExpression2 = Expression.Property(parameterExpression, p2);

            Type anType = new { OrderId = 1, ProductId = 2 }.GetType();

            PropertyInfo p3 = anType.GetProperty(columnKey1);
            PropertyInfo p4 = anType.GetProperty(columnKey2);

            ConstructorInfo cInfo = anType.GetConstructor(new Type[] { typeof(int), typeof(int) });

            NewExpression expr = Expression.New(cInfo,
                new MemberExpression[] { memberExpression1, memberExpression2 },
                new MemberInfo[] { p3, p4 });

            LambdaExpression lambda = Expression.Lambda<Func<TEnreplacedy, dynamic>>(expr, parameterExpression);

            Expression<Func<TEnreplacedy, dynamic>> hasKeyExpression = (Expression<Func<TEnreplacedy, dynamic>>)lambda;

            return mapper.HasKey(hasKeyExpression);
        }

19 Source : Sql.cs
with MIT License
from anet-team

public static string And(object clause)
        {
            if (clause == null) return "1=1";

            var names = GetParamNames(clause);
            var type = clause.GetType();

            return string.Join(" AND ", names.Select(x =>
            {
                var propertyValue = type.GetProperty(x).GetValue(clause);
                if (propertyValue == null) return x + " IS NULL";
                else if (propertyValue is IEnumerable && !(propertyValue is string))
                    return x + " IN @" + x;
                else return x + "=@" + x;
            }));
        }

19 Source : AxisConverters.cs
with MIT License
from AngeloCresta

public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) 
		{  
			if (context != null && context.Instance != null)
			{
				// Convert to string
				if (destinationType == typeof(string)) 
				{
					DateTimeIntervalType	intervalType = DateTimeIntervalType.Auto;
					double					interval = 0;

					// Get IntervalType property using reflection
					PropertyInfo	propertyInfo = context.Instance.GetType().GetProperty("IntervalType");
					if(propertyInfo != null)
					{
						intervalType = (DateTimeIntervalType)propertyInfo.GetValue(context.Instance, null);
					}

					// Get Interval property using reflection
					propertyInfo = context.Instance.GetType().GetProperty("Interval");
					if(propertyInfo != null)
					{
						interval = (double)propertyInfo.GetValue(context.Instance, null);
					}

					// Try to get interval information from the axis
					if(intervalType == DateTimeIntervalType.Auto) 
					{
						// Get object's axis
						Axis	axis = null;
						if(context.Instance is Axis)
						{
							axis = (Axis)context.Instance;
						}
						else
						{
							MethodInfo	methodInfo = context.Instance.GetType().GetMethod("GetAxis");
							if(methodInfo != null)
							{
								// Get axis object
								axis = (Axis)methodInfo.Invoke(context.Instance, null);
							}
						}

						// Get axis value type
						if(axis != null)
						{
							intervalType = axis.GetAxisIntervalType();
						}
					}
						
					// Convert value to date/time string
					if(context.Instance.GetType() != typeof(StripLine) || interval == 0)
					{
						if(intervalType != DateTimeIntervalType.Number && intervalType != DateTimeIntervalType.Auto) 
						{
							// Covert value to date/time
							if(intervalType < DateTimeIntervalType.Hours)
							{
								return DateTime.FromOADate((double)value).ToShortDateString();
							}
							return DateTime.FromOADate((double)value).ToString("g", System.Globalization.CultureInfo.CurrentCulture);
						}
					}
				}
			}
			return base.ConvertTo(context, culture, value, destinationType);
		}

19 Source : AxisConverters.cs
with MIT License
from AngeloCresta

public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
		{
			object	result = null;
			bool	convertFromDate = false;
            string stringValue = value as string;

			// If context interface provided check if we are dealing with DateTime values
			if (context != null && context.Instance != null)
			{
				DateTimeIntervalType intervalType = DateTimeIntervalType.Auto;

				// Get intervalType property using reflection
				PropertyInfo	propertyInfo = context.Instance.GetType().GetProperty("intervalType");
				if(propertyInfo != null)
				{
					intervalType = (DateTimeIntervalType)propertyInfo.GetValue(context.Instance, null);
				}
				
				// Try to get interval information from the axis
				if(intervalType == DateTimeIntervalType.Auto) 
				{
					// Get object's axis
					Axis	axis = null;
					if(context.Instance is Axis)
					{
						axis = (Axis)context.Instance;
					}
					else
					{
						MethodInfo	methodInfo = context.Instance.GetType().GetMethod("GetAxis");
						if(methodInfo != null)
						{
							// Get axis object
							axis = (Axis)methodInfo.Invoke(context.Instance, null);
						}
					}

					// Get axis value type
					if(axis != null)
					{
						intervalType = axis.GetAxisIntervalType();
					}
				}

				if (stringValue != null && intervalType != DateTimeIntervalType.Number && intervalType != DateTimeIntervalType.Auto) 
				{
					convertFromDate = true;
				}

			}

			// Try to convert from double string
            try
            {
                result = base.ConvertFrom(context, culture, value);
            }
            catch (ArgumentException)
            {
                result = null;
            }
            catch (NotSupportedException)
            {
                result = null;
            }

			// Try to convert from date/time string
            if (stringValue != null && (convertFromDate || result == null))
            {
                DateTime valueAsDate;
                bool parseSucceed = DateTime.TryParse(stringValue, CultureInfo.InvariantCulture, DateTimeStyles.None, out valueAsDate);

                if (parseSucceed)
                {
                    // Succeded converting from date format
                    return valueAsDate.ToOADate();
                }
            }

			// Call base converter
			return base.ConvertFrom(context, culture, value);
		}

19 Source : DynamicLinqFactory.cs
with Apache License 2.0
from anjoy8

public static void RemoveSpecialPropertyValue(this object source)
        {
            var properties = source.GetType().GetProperties();
            foreach (var x in properties)
            {
                if (x.GetAccessors().Any(y => y.IsVirtual))
                {
                    source.GetType().GetProperty(x.Name).SetValue(source, null, null);
                }
            }
        }

19 Source : DynamicLinqFactory.cs
with Apache License 2.0
from anjoy8

public static IOrderedQueryable<TSource> ISort<TSource>(this IQueryable<TSource> source, string orderByProperty, bool asc)
        {
            string command = asc ? "OrderBy" : "OrderByDescending";
            var type = typeof(TSource);
            var property = type.GetProperty(orderByProperty);
            var parameter = Expression.Parameter(type, "p");
            var propertyAccess = Expression.MakeMemberAccess(parameter, property);
            var orderByExpression = Expression.Lambda(propertyAccess, parameter);
            var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExpression));
            return (IOrderedQueryable<TSource>)source.Provider.CreateQuery<TSource>(resultExpression);
        }

19 Source : RecursionHelper.cs
with Apache License 2.0
from anjoy8

public static void LoopToAppendChildrenT<T>(List<T> all, T curItem, string parentIdName = "Pid", string idName = "value", string childrenName = "children")
        {
            var subItems = all.Where(ee => ee.GetType().GetProperty(parentIdName).GetValue(ee, null).ToString() == curItem.GetType().GetProperty(idName).GetValue(curItem, null).ToString()).ToList();

            if (subItems.Count > 0) curItem.GetType().GetField(childrenName).SetValue(curItem, subItems);
            foreach (var subItem in subItems)
            {
                LoopToAppendChildrenT(all, subItem);
            }
        }

19 Source : DynamicLinqFactory.cs
with Apache License 2.0
from anjoy8

public static void CopyTo<T>(this object source, T target) where T : clreplaced, new()
        {
            if (source == null)
                return;

            if (target == null)
            {
                target = new T();
            }

            foreach (var property in target.GetType().GetProperties())
            {
                // 这里可以判断一下当前属性值是否为空的 source.GetType().GetProperty(property.Name).GetValue(source, null)
                target.GetType().InvokeMember(property.Name, BindingFlags.SetProperty, null, target, new object[] { source.GetType().GetProperty(property.Name).GetValue(source, null) });
            }
        }

19 Source : Engine.cs
with GNU Affero General Public License v3.0
from ankenyr

static System.Linq.Expressions.Expression BuildExpr<T>(Expression r, ParameterExpression param)
        {
            var left = MemberExpression.Property(param, r.MemberName);
            var tProp = typeof(T).GetProperty(r.MemberName).PropertyType;
            ExpressionType tBinary;
            // is the operator a known .NET operator?
            if (ExpressionType.TryParse(r.Operator, out tBinary))
            {
                var right = System.Linq.Expressions.Expression.Constant(Convert.ChangeType(r.TargetValue, tProp));
                // use a binary operation, e.g. 'Equal' -> 'u.Age == 15'
                return System.Linq.Expressions.Expression.MakeBinary(tBinary, left, right);
            }

            if (r.Operator == "MatchRegex" || r.Operator == "NotMatchRegex")
            {
                var regex = new Regex(r.TargetValue);
                var method = typeof(Regex).GetMethod("IsMatch", new[] {typeof(string)});
                Debug.replacedert(method != null, nameof(method) + " != null");
                var callInstance = System.Linq.Expressions.Expression.Constant(regex);

                var toStringMethod = tProp.GetMethod("ToString", new Type[0]);
                Debug.replacedert(toStringMethod != null, nameof(toStringMethod) + " != null");
                var methodParam = System.Linq.Expressions.Expression.Call(left, toStringMethod);

                var call = System.Linq.Expressions.Expression.Call(callInstance, method, methodParam);
                if (r.Operator == "MatchRegex") return call;
                if (r.Operator == "NotMatchRegex") return System.Linq.Expressions.Expression.Not(call);
            }

            if (tProp.Name == "String")
            { 
                var method = tProp.GetMethod(r.Operator, new Type[] { typeof(string) });
                var tParam = method.GetParameters()[0].ParameterType;
                var right = System.Linq.Expressions.Expression.Constant(Convert.ChangeType(r.TargetValue, tParam));
                // use a method call, e.g. 'Contains' -> 'u.Tags.Contains(some_tag)'
                return System.Linq.Expressions.Expression.Call(left, method, right);
            }
            else { 
                var method = tProp.GetMethod(r.Operator);
                var tParam = method.GetParameters()[0].ParameterType;
                var right = System.Linq.Expressions.Expression.Constant(Convert.ChangeType(r.TargetValue, tParam));
                // use a method call, e.g. 'Contains' -> 'u.Tags.Contains(some_tag)'
                return System.Linq.Expressions.Expression.Call(left, method, right);
            }
        }

19 Source : AnkiSharpDynamic.cs
with MIT License
from AnkiTools

public T ToObject<T>(T obj = null) where T : clreplaced, new()
        {
            T result = obj ?? new T();
            PropertyInfo propertyInfo;

            foreach (var pair in _dictionary)
            {
                    propertyInfo = result.GetType().GetProperty(pair.Key);
                    propertyInfo.SetValue(result, Convert.ChangeType(pair.Value, propertyInfo.PropertyType), null);
            }

            return result;
        }

19 Source : SpellPanelConfigViewModel.Visual.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

private void FirstSpell_PropertyChanged(
            object sender,
            PropertyChangedEventArgs e)
        {
            var targets = new[]
            {
                nameof(Spell.WarningTime),
                nameof(Spell.ChangeFontColorsWhenWarning),
                nameof(Spell.IsReverse),
                nameof(Spell.BarWidth),
                nameof(Spell.BarHeight),
                nameof(Spell.SpellIconSize),
                nameof(Spell.HideSpellName),
                nameof(Spell.OverlapRecastTime),
                nameof(Spell.ReduceIconBrightness),
                nameof(Spell.ProgressBarVisible),
                nameof(Spell.HideCounter),
                nameof(Spell.DontHide),
            };

            if (!targets.Contains(e.PropertyName))
            {
                return;
            }

            var pi = typeof(Spell).GetProperty(e.PropertyName);
            var value = pi.GetValue(this.FirstSpell);

            foreach (var spell in this.Spells)
            {
                pi.SetValue(spell, value);
            }
        }

19 Source : ITrigger.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public static async void ImportProperties(
            this ITrigger t,
            ITrigger source)
        {
            if (source == null ||
                t == null)
            {
                return;
            }

            var properties = source.GetType().GetProperties(
                BindingFlags.Public |
                BindingFlags.Instance)
                .Where(x =>
                    x.CanRead &&
                    x.CanWrite);

            await WPFHelper.InvokeAsync(() =>
            {
                foreach (var pi in properties)
                {
                    if (t.GetType().GetProperty(pi.Name) == null ||
                        ImportIgnoreProperties.Contains(pi.Name))
                    {
                        continue;
                    }

                    var attrs = pi.GetCustomAttributes(true);
                    if (attrs.Any(a => a is XmlIgnoreAttribute))
                    {
                        continue;
                    }

                    pi.SetValue(t, pi.GetValue(source));
                    Thread.Yield();

                    (t as TreeItemBase)?.ExecuteRaisePropertyChanged(pi.Name);
                    Thread.Yield();
                }

                switch (t)
                {
                    case Spell spell:
                        spell.Enabled = true;
                        break;

                    case Ticker ticker:
                        ticker.Enabled = true;
                        break;
                }
            });
        }

19 Source : MemberExpression.cs
with MIT License
from ansel86castro

public override System.Linq.Expressions.Expression GenerateLinqExpression(IASTContext context)
        {
            var leftExp = Left.GenerateLinqExpression(context);
            var leftModelType = ((PropertyInfo)((System.Linq.Expressions.MemberExpression)leftExp).Member).PropertyType;

            NavigationPropertyAttribute navAttr = pi.GetCustomAttribute<NavigationPropertyAttribute>();
            if (navAttr != null)
            {
                var modelProperty = leftModelType.GetProperty(navAttr.NavigationProperty);
                var linqExp = System.Linq.Expressions.Expression.Property(leftExp, modelProperty);
                modelProperty = modelProperty.PropertyType.GetProperty(navAttr.Property);
                linqExp = System.Linq.Expressions.Expression.Property(linqExp, modelProperty);
                return linqExp;
            }

            var expression = System.Linq.Expressions.Expression.Property(leftExp,  pi.Name);
            return expression;
        }

19 Source : ExpressionBuilder.cs
with MIT License
from ansel86castro

public static IncludeTree[] Build(string include, Type resposeType, Type modelType, Expression parameter)
            {
                string[][] includesArray = include.Split(',').Select(x => x.Split('.')).ToArray();

                Dictionary<string, IncludeTree> dic = new Dictionary<string, IncludeTree>();

                for (int i = 0; i < includesArray.Length; i++)
                {
                    IncludeTree incTree = null;
                    for (int j = 0; j < includesArray[i].Length; j++)
                    {
                        var propertyName = includesArray[i][j];

                        if (j == 0)
                        {
                            if (!dic.TryGetValue(propertyName, out incTree))
                            {
                                incTree = new IncludeTree
                                {
                                    PropertyName = propertyName,
                                    ResponseProperty = resposeType.GetProperty(propertyName),
                                    ModelProperty = Expression.Property(parameter, modelType.GetProperty(propertyName))
                                };
                                dic.Add(propertyName, incTree);
                            }
                        }
                        else
                        {
                            IncludeTree child;
                            if (!incTree.Includes.TryGetValue(propertyName, out child))
                            {
                                child = new IncludeTree
                                {
                                    PropertyName = propertyName,
                                    ResponseProperty = incTree.ResponseProperty.PropertyType.GetProperty(propertyName),
                                    ModelProperty = Expression.Property(incTree.ModelProperty, ((PropertyInfo)incTree.ModelProperty.Member).PropertyType.GetProperty(propertyName))
                                };
                                incTree.Includes.Add(propertyName, child);
                            }

                            incTree = child;
                        }

                    }
                }

                return dic.Values.ToArray();
            }

19 Source : ExpressionBuilder.cs
with MIT License
from ansel86castro

public Expression CreateInitExpression()
            {
                List<MemberBinding> bindings = new List<MemberBinding>();

                var modelType = ((PropertyInfo)ModelProperty.Member).PropertyType;
                var responseType = ResponseProperty.PropertyType;
                var props = responseType.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(x => x.CanWrite);

                foreach (var p in props)
                {
                    IncludeTree include;
                    Expression bind = null;

                    if (!Includes.TryGetValue(p.Name, out include))
                    {
                        NavigationPropertyAttribute navAttr = p.GetCustomAttribute<NavigationPropertyAttribute>();

                        if (navAttr != null)
                        {
                            var navModelProp = Expression.Property(ModelProperty, modelType.GetProperty(navAttr.NavigationProperty));
                            var navProp = Expression.Property(navModelProp, ((PropertyInfo)navModelProp.Member).PropertyType.GetProperty(navAttr.Property));
                            bind = navProp;

                        }
                        else if (IsMappeable(p))
                        {
                            bind = Expression.Property(ModelProperty, modelType.GetProperty(p.Name));
                        }

                    }
                    else
                    {
                        bind = include.CreateInitExpression();
                    }

                    if (bind != null)
                    {
                        bindings.Add(Expression.Bind(p, bind));
                    }

                }

                NewExpression newResponse = Expression.New(responseType);
                MemberInitExpression initExpression = Expression.MemberInit(newResponse, bindings);

                return initExpression;
            }

19 Source : ASTContext.cs
with MIT License
from ansel86castro

public VariableDeclaration GetVariableDeclaration(string name)
        {           
            if (!variables.TryGetValue(name, out VariableDeclaration v))
            {
                var targetType = ResponseType ?? ModelType;

                PropertyInfo modelProperty;
                System.Linq.Expressions.Expression linqExpression;

                var responseProperty = targetType.GetProperty(name);
                if (responseProperty == null)
                {                    
                    responseProperty = targetType.GetProperty(name.Pascal());
                }

                if (responseProperty == null)
                    throw new RecognitionException("Property not found " + name + " in " + targetType.Name);

                if (ResponseType == null || ResponseType == ModelType)
                {
                    modelProperty = responseProperty;
                    linqExpression = Parameter;
                }
                else
                {
                    NavigationPropertyAttribute navAttr = responseProperty.GetCustomAttribute<NavigationPropertyAttribute>();
                    if (navAttr != null)
                    {
                        modelProperty = ModelType.GetProperty(navAttr.NavigationProperty);
                        linqExpression = System.Linq.Expressions.Expression.Property(Parameter, modelProperty);

                        modelProperty = modelProperty.PropertyType.GetProperty(navAttr.Property);
                    }
                    else
                    {
                        modelProperty = ModelType.GetProperty(name);
                        linqExpression = Parameter;
                    }
                }

                v = new PropertyVariableDeclaration(linqExpression, modelProperty);
                variables.Add(name, v);
            }

            return v;
        }

19 Source : ASTContext.cs
with MIT License
from ansel86castro

public VariableDeclaration GetVariableDeclaration(string name)
        {           
            if (!variables.TryGetValue(name, out VariableDeclaration v))
            {
                var targetType = ResponseType ?? ModelType;

                PropertyInfo modelProperty;
                System.Linq.Expressions.Expression linqExpression;

                var responseProperty = targetType.GetProperty(name);
                if (responseProperty == null)
                {                    
                    responseProperty = targetType.GetProperty(name.Pascal());
                }

                if (responseProperty == null)
                    throw new RecognitionException("Property not found " + name + " in " + targetType.Name);

                if (ResponseType == null || ResponseType == ModelType)
                {
                    modelProperty = responseProperty;
                    linqExpression = Parameter;
                }
                else
                {
                    NavigationPropertyAttribute navAttr = responseProperty.GetCustomAttribute<NavigationPropertyAttribute>();
                    if (navAttr != null)
                    {
                        modelProperty = ModelType.GetProperty(navAttr.NavigationProperty);
                        linqExpression = System.Linq.Expressions.Expression.Property(Parameter, modelProperty);

                        modelProperty = modelProperty.PropertyType.GetProperty(navAttr.Property);
                    }
                    else
                    {
                        modelProperty = ModelType.GetProperty(name);
                        linqExpression = Parameter;
                    }
                }

                v = new PropertyVariableDeclaration(linqExpression, modelProperty);
                variables.Add(name, v);
            }

            return v;
        }

19 Source : ExpressionBuilder.cs
with MIT License
from ansel86castro

public Expression CreateInitExpression()
            {
                List<MemberBinding> bindings = new List<MemberBinding>();

                var modelType = ((PropertyInfo)ModelProperty.Member).PropertyType;
                var responseType = ResponseProperty.PropertyType;
                var props = responseType.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(x => x.CanWrite);

                foreach (var p in props)
                {
                    IncludeTree include;
                    Expression bind = null;

                    if (!Includes.TryGetValue(p.Name, out include))
                    {
                        NavigationPropertyAttribute navAttr = p.GetCustomAttribute<NavigationPropertyAttribute>();

                        if (navAttr != null)
                        {
                            var navModelProp = Expression.Property(ModelProperty, modelType.GetProperty(navAttr.NavigationProperty));
                            var navProp = Expression.Property(navModelProp, ((PropertyInfo)navModelProp.Member).PropertyType.GetProperty(navAttr.Property));
                            bind = navProp;

                        }
                        else if (IsMappeable(p))
                        {
                            bind = Expression.Property(ModelProperty, modelType.GetProperty(p.Name));
                        }

                    }
                    else
                    {
                        bind = include.CreateInitExpression();
                    }

                    if (bind != null)
                    {
                        bindings.Add(Expression.Bind(p, bind));
                    }

                }

                NewExpression newResponse = Expression.New(responseType);
                MemberInitExpression initExpression = Expression.MemberInit(newResponse, bindings);

                return initExpression;
            }

19 Source : FuzzyLogicCore.cs
with MIT License
from antonio-leonardo

private bool ProcessFilter(string filter, TEnreplacedy invalidData, string propertyName)
        {
            if (typeof(TEnreplacedy).GetProperty(propertyName).PropertyType == typeof(Double) && filter.Contains(","))
            {
                filter = filter.Replace(",", ".");
            }
            bool ratingResult = false;
            const char FIRST_BRACKET = '(',
                       LAST_BRACKET = ')';
            string newFilter = filter;

            ConcurrentBag<int> charsIdWithStartParentesesParallel = new ConcurrentBag<int>();
            ConcurrentBag<int> charsIdWithEndParentesesParallel = new ConcurrentBag<int>();
            char[] filterChars = filter.ToCharArray();
            Parallel.For(0, filterChars.Length, i =>
            {
                if (filterChars[i] == FIRST_BRACKET)
                {
                    charsIdWithStartParentesesParallel.Add(i);
                }
                else if (filterChars[i] == LAST_BRACKET)
                {
                    charsIdWithEndParentesesParallel.Add(i);
                }
            });

            List<int> charsIdWithStartParenteses = charsIdWithStartParentesesParallel.ToList();
            List<int> charsIdWithEndParenteses = charsIdWithEndParentesesParallel.ToList();

            bool isMatch = false;
            while (!isMatch)
            {
                try
                {
                    this.SubsreplaceduteChars(ref newFilter);
                    ratingResult = DynamicLinq.DynamicExpression.ParseLambda<TEnreplacedy, bool>(newFilter).Compile().Invoke(invalidData);
                    isMatch = true;
                }
                catch
                {
                    if (charsIdWithStartParenteses.Count > charsIdWithEndParenteses.Count)
                    {
                        filter = filter.Remove(filter.IndexOf(FIRST_BRACKET), 1);
                        newFilter = filter;
                        charsIdWithStartParenteses.Remove(charsIdWithStartParenteses.FirstOrDefault());
                    }
                    else if (charsIdWithStartParenteses.Count < charsIdWithEndParenteses.Count)
                    {
                        filter = filter.Remove(filter.LastIndexOf(LAST_BRACKET) - 1, 1);
                        newFilter = filter;
                        charsIdWithEndParenteses.Remove(charsIdWithEndParenteses.LastOrDefault());
                    }
                    else
                    {
                        if (charsIdWithStartParenteses.SequenceEqual(Enumerable.Range(1, charsIdWithStartParenteses.Count)))
                        {
                            filter = filter.Remove(filter.LastIndexOf(LAST_BRACKET) - 1, 1);
                            newFilter = filter;
                            charsIdWithEndParenteses.Remove(charsIdWithEndParenteses.LastOrDefault());
                        }
                        else if (charsIdWithEndParenteses.SequenceEqual(Enumerable.Range(1, charsIdWithEndParenteses.Count)))
                        {
                            filter = filter.Remove(filter.IndexOf(FIRST_BRACKET), 1);
                            newFilter = filter;
                            charsIdWithStartParenteses.Remove(charsIdWithStartParenteses.FirstOrDefault());
                        }
                    }
                }
            }
            return ratingResult;
        }

19 Source : MdSerializationOptionsTest.cs
with MIT License
from ap0llo

[Theory]
        [MemberData(nameof(DefaultInstancesAndProperties))]
        public void Properties_of_the_default_instances_cannot_be_modified(MdSerializationOptions instance, string propertyName)
        {
            // ARRANGE
            var property = typeof(MdSerializationOptions).GetProperty(propertyName)!;

            var testValue = GetTestValue(property.PropertyType);

            // ACT / replacedERT
            var exception = replacedert.Throws<TargetInvocationException>(() => property.SetMethod!.Invoke(instance, new[] { testValue }));
            replacedert.NotNull(exception.InnerException);
            var innerException = replacedert.IsType<InvalidOperationException>(exception.InnerException);

            // exception message should indicate which property cannot be set
            replacedert.Contains(propertyName, innerException.Message);
        }

19 Source : MdSerializationOptionsTest.cs
with MIT License
from ap0llo

[Theory]
        [MemberData(nameof(Properties))]
        public void Properties_of_non_default_instance_can_be_modified(string propertyName)
        {
            // ARRANGE
            var instance = new MdSerializationOptions();

            var property = typeof(MdSerializationOptions).GetProperty(propertyName);

            var newValue = GetTestValue(property!.PropertyType);

            // ACT / replacedERT
            property.SetMethod!.Invoke(instance, new[] { newValue });
            var actualValue = property.GetMethod!.Invoke(instance, Array.Empty<object>());
            replacedert.Equal(newValue, actualValue);
        }

19 Source : MdSerializationOptionsTest.cs
with MIT License
from ap0llo

[Theory]
        [MemberData(nameof(Properties))]
        public void Clone_returns_a_copy_of_the_instance(string propertyName)
        {
            // ARRANGE
            var property = typeof(MdSerializationOptions).GetProperty(propertyName);
            var instance = new MdSerializationOptions();

            var value = GetTestValue(property!.PropertyType);

            property.SetMethod!.Invoke(instance, new[] { value });

            // ACT
            var copy = instance.Clone();

            // replacedERT
            var clonedValue = property.GetMethod!.Invoke(copy, Array.Empty<object>());
            replacedert.Equal(value, clonedValue);
        }

19 Source : MdSerializationOptionsTest.cs
with MIT License
from ap0llo

[Theory]
        [MemberData(nameof(DefaultInstancesAndProperties))]
        public void Cloning_a_readonly_instance_returns_a_non_readonly_instance(MdSerializationOptions instance, string propertyName)
        {
            // ARRANGE
            var property = typeof(MdSerializationOptions).GetProperty(propertyName);
            var testValue = GetTestValue(property!.PropertyType);

            // Create a copy of the default instance
            // The default instance is read-only and cannot be modified
            // The copy must not be read-only and thus can be modified             
            var copy = instance.Clone();

            // ACT
            property!.SetMethod!.Invoke(copy, new[] { testValue });

            // replacedERT
            var setValue = property.GetMethod!.Invoke(copy, Array.Empty<object>());
            replacedert.Equal(testValue, setValue);
        }

19 Source : MdSerializationOptionsTest.cs
with MIT License
from ap0llo

[Theory]
        [MemberData(nameof(Properties))]
        public void With_creates_a_copy_and_applies_changes(string propertyName)
        {
            // ARRANGE
            var property = typeof(MdSerializationOptions).GetProperty(propertyName);
            var testValue = GetTestValue(property!.PropertyType);

            var sut = new MdSerializationOptions();

            // ACT
            var copy = sut.With(opts =>
                property.SetMethod!.Invoke(opts, new[] { testValue })
            );

            // replacedERT
            var newValue = property.GetMethod!.Invoke(copy, Array.Empty<object>());
            replacedert.Equal(testValue, newValue);
        }

19 Source : RepairUtility.cs
with GNU Lesser General Public License v3.0
from ApexGameTools

private Type ResolveExpectedBaseType(StageItem el, bool elementType)
        {
            var parent = el.parent;
            if (parent == null)
            {
                return null;
            }

            var parentElement = parent as StageElement;
            if (parentElement != null)
            {
                var parentTypeName = parentElement.AttributeValueOrDefault<string>("type");
                if (parentTypeName == null)
                {
                    /* For custom types that have no type attribute, the entire type will be validated at once, so we ignore individual members. */
                    return null;
                }

                Type parentType;
                if (!_identifiedTypes.TryGetValue(parentTypeName, out parentType))
                {
                    return null;
                }

                var prop = parentType.GetProperty(el.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                if (prop != null)
                {
                    return prop.PropertyType;
                }

                var field = parentType.GetField(el.name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                if (field != null)
                {
                    return field.FieldType;
                }

                return null;
            }

            var parentList = parent as StageList;
            if (parentList == null)
            {
                return null;
            }

            var listType = ResolveExpectedBaseType(parentList, elementType);
            if (!elementType)
            {
                return listType;
            }

            while (typeof(IList).IsreplacedignableFrom(listType))
            {
                if (listType.IsArray)
                {
                    listType = listType.GetElementType();
                }
                else if (listType.IsGenericType)
                {
                    listType = listType.GetGenericArguments()[0];
                }
                else
                {
                    listType = null;
                }
            }

            return listType;
        }

19 Source : TypeCompat.cs
with Apache License 2.0
from Appdynamics

public static object GetPropertyValue(object v, string name)
        {
#if (Core)
            return v.GetType().GetTypeInfo().GetProperty(name).GetValue(v, null);
#else
            return v.GetType().GetProperty(name).GetValue(v, null);
#endif
        }

19 Source : Issues.cs
with Apache License 2.0
from Appdynamics

[TestMethod]
        public void LoadFromColIssue()
        {
            var l = new List<cls1>();

            l.Add(new cls1() { prop1 = 1 });
            l.Add(new cls2() { prop1 = 1, prop2 = "test1" });

            var p = new ExcelPackage();
            var ws = p.Workbook.Worksheets.Add("Test");

            ws.Cells["A1"].LoadFromCollection(l, true, TableStyles.Light16, BindingFlags.Instance | BindingFlags.Public,
                new MemberInfo[] { typeof(cls2).GetProperty("prop2") });
        }

19 Source : WorkSheet.cs
with Apache License 2.0
from Appdynamics

public void LoadFromCollectionTest()
        {
            var ws = _pck.Workbook.Worksheets.Add("LoadFromCollection");
            List<TestDTO> list = new List<TestDTO>();
            list.Add(new TestDTO() { Id = 1, Name = "Item1", Boolean = false, Date = new DateTime(2011, 1, 1), dto = null, NameVar = "Field 1" });
            list.Add(new TestDTO() { Id = 2, Name = "Item2", Boolean = true, Date = new DateTime(2011, 1, 15), dto = new TestDTO(), NameVar = "Field 2" });
            list.Add(new TestDTO() { Id = 3, Name = "Item3", Boolean = false, Date = new DateTime(2011, 2, 1), dto = null, NameVar = "Field 3" });
            list.Add(new TestDTO() { Id = 4, Name = "Item4", Boolean = true, Date = new DateTime(2011, 4, 19), dto = list[1], NameVar = "Field 4" });
            list.Add(new TestDTO() { Id = 5, Name = "Item5", Boolean = false, Date = new DateTime(2011, 5, 8), dto = null, NameVar = "Field 5" });
            list.Add(new TestDTO() { Id = 6, Name = "Item6", Boolean = true, Date = new DateTime(2010, 3, 27), dto = null, NameVar = "Field 6" });
            list.Add(new TestDTO() { Id = 7, Name = "Item7", Boolean = false, Date = new DateTime(2009, 1, 5), dto = list[3], NameVar = "Field 7" });
            list.Add(new TestDTO() { Id = 8, Name = "Item8", Boolean = true, Date = new DateTime(2018, 12, 31), dto = null, NameVar = "Field 8" });
            list.Add(new TestDTO() { Id = 9, Name = "Item9", Boolean = false, Date = new DateTime(2010, 2, 1), dto = null, NameVar = "Field 9" });

            ws.Cells["A1"].LoadFromCollection(list, true);
            ws.Cells["A30"].LoadFromCollection(list, true, OfficeOpenXml.Table.TableStyles.Medium9, BindingFlags.Instance | BindingFlags.Instance, typeof(TestDTO).GetFields());

            ws.Cells["A45"].LoadFromCollection(list, true, OfficeOpenXml.Table.TableStyles.Light1, BindingFlags.Instance | BindingFlags.Instance, new MemberInfo[] { typeof(TestDTO).GetMethod("GetNameID"), typeof(TestDTO).GetField("NameVar") });
            ws.Cells["J1"].LoadFromCollection(from l in list where l.Boolean orderby l.Date select new { Name = l.Name, Id = l.Id, Date = l.Date, NameVariable = l.NameVar }, true, OfficeOpenXml.Table.TableStyles.Dark4);

            var ints = new int[] { 1, 3, 4, 76, 2, 5 };
            ws.Cells["A15"].Value = ints;

            ws = _pck.Workbook.Worksheets.Add("LoadFromCollection_Inherited");
            List<InheritTestDTO> inhList = new List<InheritTestDTO>();
            inhList.Add(new InheritTestDTO() { Id = 1, Name = "Item1", Boolean = false, Date = new DateTime(2011, 1, 1), dto = null, NameVar = "Field 1", InheritedProp="Inherited 1" });
            inhList.Add(new InheritTestDTO() { Id = 2, Name = "Item2", Boolean = true, Date = new DateTime(2011, 1, 15), dto = new TestDTO(), NameVar = "Field 2", InheritedProp = "Inherited 2" });
            ws.Cells["A1"].LoadFromCollection(inhList, true);
            replacedert.AreEqual("Inherited 2", ws.Cells[3, 1].Value);

            ws.Cells["A5"].LoadFromCollection(inhList, true, TableStyles.None, BindingFlags.Public | BindingFlags.Instance, new MemberInfo[]{typeof(InheritTestDTO).GetProperty("InheritedProp"), typeof(TestDTO).GetProperty("Name") });
            replacedert.AreEqual("Inherited 2", ws.Cells[7, 1].Value);

        }

19 Source : Sample13.cs
with Apache License 2.0
from Appdynamics

public static void RunSample13()
        {
            var pck = new ExcelPackage();

            //Create a datatable with the directories and files from the root directory...
            DataTable dt = GetDataTable(Utils.GetDirectoryInfo("."));

            var wsDt = pck.Workbook.Worksheets.Add("FromDataTable");

            //Load the datatable and set the number formats...
            wsDt.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.Medium9);
            wsDt.Cells[2, 2, dt.Rows.Count + 1, 2].Style.Numberformat.Format = "#,##0";
            wsDt.Cells[2, 3, dt.Rows.Count + 1, 4].Style.Numberformat.Format = "mm-dd-yy";
            wsDt.Cells[wsDt.Dimension.Address].AutoFitColumns();
            //Select Name and Created-time...
            var collection = (from row in dt.Select() select new { Name = row["Name"], Created_time = (DateTime)row["Created"] });

            var wsEnum = pck.Workbook.Worksheets.Add("FromAnonymous");

            //Load the collection starting from cell A1...
            wsEnum.Cells["A1"].LoadFromCollection(collection, true, TableStyles.Medium9);

            //Add some formating...
            wsEnum.Cells[2, 2, dt.Rows.Count - 1, 2].Style.Numberformat.Format = "mm-dd-yy";
            wsEnum.Cells[wsEnum.Dimension.Address].AutoFitColumns();

            //Load a list of FileDTO objects from the datatable...
            var wsList = pck.Workbook.Worksheets.Add("FromList");
            List<FileDTO> list = (from row in dt.Select()
                                  select new FileDTO
                                  {
                                      Name = row["Name"].ToString(),
                                      Size = row["Size"].GetType() == typeof(long) ? (long)row["Size"] : 0,
                                      Created = (DateTime)row["Created"],
                                      LastModified = (DateTime)row["Modified"],
                                      IsDirectory = (row["Size"] == DBNull.Value)
                                  }).ToList<FileDTO>();

            //Load files ordered by size...
            wsList.Cells["A1"].LoadFromCollection(from file in list
                                                  orderby file.Size descending
                                                  where file.IsDirectory == false
                                                  select file, true, TableStyles.Medium9);

            wsList.Cells[2, 2, dt.Rows.Count + 1, 2].Style.Numberformat.Format = "#,##0";
            wsList.Cells[2, 3, dt.Rows.Count + 1, 4].Style.Numberformat.Format = "mm-dd-yy";


            //Load directories ordered by Name...
            wsList.Cells["F1"].LoadFromCollection(from file in list
                                                  orderby file.Name ascending
                                                  where file.IsDirectory == true
                                                  select new
                                                  {
                                                      Name = file.Name,
                                                      Created = file.Created,
                                                      Last_modified = file.LastModified
                                                  }, //Use an underscore in the property name to get a space in the replacedle.
                                                  true, TableStyles.Medium11);

            wsList.Cells[2, 7, dt.Rows.Count + 1, 8].Style.Numberformat.Format = "mm-dd-yy";

            //Load the list using a specified array of MemberInfo objects. Properties, fields and methods are supported.
            var rng = wsList.Cells["J1"].LoadFromCollection(list,
                                                  true,
                                                  TableStyles.Medium10,
                                                  BindingFlags.Instance | BindingFlags.Public,
                                                  new MemberInfo[] {
                                                      typeof(FileDTO).GetProperty("Name"),
                                                      typeof(FileDTO).GetField("IsDirectory"),
                                                      typeof(FileDTO).GetMethod("ToString")}
                                                  );

            wsList.Tables.GetFromRange(rng).Columns[2].Name = "Description";

            wsList.Cells[wsList.Dimension.Address].AutoFitColumns();

            //...and save
            var fi = Utils.GetFileInfo("sample13.xlsx");
            pck.SaveAs(fi);
        }

19 Source : PropertyValueSpecification.cs
with MIT License
from Aptacode

protected static object GetValue(object target, string propertyName)
        {
            return target?.GetType().GetProperty(propertyName)?.GetValue(target);
        }

19 Source : DataMapperConfiguration.cs
with MIT License
from aquilahkj

private static void LoadData(string configFilePath)
        {
            FileInfo fileInfo;
            if (UseEntryreplacedemblyDirectory) {
                fileInfo = FileHelper.GetFileInfo(configFilePath, out var absolute);
                if (!fileInfo.Exists && !absolute) {
                    fileInfo = new FileInfo(configFilePath);
                }
            }
            else {
                fileInfo = new FileInfo(configFilePath);
            }
            if (fileInfo.Exists) {
                using (var reader = fileInfo.OpenText()) {
                    var content = reader.ReadToEnd();
                    var dom = JObject.Parse(content);
                    var section = dom.GetValue("lightDataMapper");
                    if (section == null) {
                        return;
                    }
                    var optionList = section.ToObject<LightMapperOptions>();
                    if (optionList?.DataTypes != null && optionList.DataTypes.Length > 0) {
                        var typeIndex = 0;
                        foreach (var typeConfig in optionList.DataTypes) {
                            typeIndex++;
                            var typeName = typeConfig.Type;
                            if (typeName == null) {
                                throw new LightDataException(string.Format(SR.ConfigDataTypeNameIsNull, typeIndex));
                            }
                            var dataType = Type.GetType(typeName, true);
                            var dataTypeInfo = dataType.GetTypeInfo();
                            var dataTableMap = new DataTableMapperConfig(dataType);
                            var setting = new DataTableMapperSetting(dataTableMap);

                            dataTableMap.TableName = typeConfig.TableName;
                            dataTableMap.IsEnreplacedyTable = typeConfig.IsEnreplacedyTable ?? true;
                            var configParam = new ConfigParamSet();
                            var paramConfigs = typeConfig.ConfigParams;
                            if (paramConfigs != null && paramConfigs.Count > 0) {
                                foreach (var paramConfig in paramConfigs) {
                                    configParam.SetParamValue(paramConfig.Value, paramConfig.Value);
                                }
                            }
                            dataTableMap.ConfigParams = configParam;
                            var dataFieldConfigs = typeConfig.DataFields;

                            if (dataFieldConfigs != null && dataFieldConfigs.Length > 0) {
                                var fieldIndex = 0;
                                foreach (var fieldConfig in dataFieldConfigs) {
                                    fieldIndex++;
                                    var fieldName = fieldConfig.FieldName;
                                    if (fieldName == null) {
                                        throw new LightDataException(string.Format(SR.ConfigDataFieldNameIsNull, typeName, fieldIndex));
                                    }
                                    var property = dataTypeInfo.GetProperty(fieldName);
                                    if (property == null) {
                                        throw new LightDataException(string.Format(SR.ConfigDataFieldIsNotExists, typeName, fieldName));
                                    }

                                    object defaultValue;
                                    try {
                                        defaultValue = CreateDefaultValue(property.PropertyType, fieldConfig.DefaultValue);
                                    }
                                    catch (Exception ex) {
                                        throw new LightDataException(string.Format(SR.ConfigDataFieldLoadError, typeName, fieldName, ex.Message));
                                    }
                                    FunctionControl functionControl;
                                    try {
                                        functionControl = CreateFunctionControl(fieldConfig);
                                    }
                                    catch (Exception ex) {
                                        throw new LightDataException(string.Format(SR.ConfigDataFieldLoadError, typeName, fieldName, ex.Message));
                                    }
                                    var dataFieldMap = new DataFieldMapperConfig(fieldName) {
                                        Name = fieldConfig.Name,
                                        IsPrimaryKey = fieldConfig.IsPrimaryKey,
                                        IsIdenreplacedy = fieldConfig.IsIdenreplacedy,
                                        DbType = fieldConfig.DbType,
                                        DataOrder = fieldConfig.DataOrder,
                                        IsNullable = fieldConfig.IsNullable,
                                        DefaultValue = defaultValue,
                                        FunctionControl = functionControl
                                    };
                                    setting.AddDataFieldMapConfig(fieldName, dataFieldMap);
                                }
                            }
                            var relationFieldConfigs = typeConfig.RelationFields;
                            if (relationFieldConfigs != null && relationFieldConfigs.Length > 0) {
                                var fieldIndex = 0;
                                foreach (var fieldConfig in relationFieldConfigs) {
                                    fieldIndex++;
                                    if (fieldConfig.RelationPairs != null && fieldConfig.RelationPairs.Length > 0) {
                                        var fieldName = fieldConfig.FieldName;
                                        if (fieldName == null) {
                                            throw new LightDataException(string.Format(SR.ConfigDataFieldNameIsNull, typeName, fieldIndex));
                                        }
                                        var property = dataTypeInfo.GetProperty(fieldName);
                                        if (property == null) {
                                            throw new LightDataException(string.Format(SR.ConfigDataFieldIsNotExists, typeName, fieldName));
                                        }
                                        var dataFieldMap = new RelationFieldMapConfig(fieldName);
                                        foreach (var pair in fieldConfig.RelationPairs) {
                                            dataFieldMap.AddRelationKeys(pair.MasterKey, pair.RelateKey);
                                        }
                                        setting.AddRelationFieldMapConfig(fieldName, dataFieldMap);
                                    }
                                }
                            }
                            SettingDict[dataType] = setting;
                        }
                    }
                }
            }
        }

19 Source : AssertExtend.cs
with MIT License
from aquilahkj

private static void AreObjectsEqual(object expected, object actual, string expectedName, string actualName, bool checkType)
        {
            // 若为相同为空
            if (Object.Equals(expected, null) && Object.Equals(actual, null)) {
                return;
            }
            // 若为相同引用,则通过验证
            if (Object.ReferenceEquals(expected, actual)) {
                return;
            }

            if (!Object.Equals(expected, null) && Object.Equals(actual, null)) {
                throw new replacedertActualExpectedException(expected, actual, "actual value is null", expectedName, actualName);
            }
            else if (Object.Equals(expected, null) && !Object.Equals(actual, null)) {
                throw new replacedertActualExpectedException(expected, actual, "expected value is null", expectedName, actualName);
            }

            Type expectedType = expected.GetType();
            Type actualType = actual.GetType();
            if (checkType) {
                // 判断类型是否相同
                if (!Object.Equals(expectedType, actualType)) {
                    throw new replacedertActualExpectedException(expected, actual, "actual type is not equal expected type", expectedName, actualName);
                }
            }
            TypeCode typeCode = Type.GetTypeCode(expectedType);
            TypeCode typeCode2 = Type.GetTypeCode(actualType);
            if (!Object.Equals(typeCode, typeCode2)) {
                throw new replacedertActualExpectedException(typeCode, typeCode2, "actual typecode is not equal expected typecode", expectedName, actualName);
            }

            if (typeCode == TypeCode.Object) {
                if (expected is IEnumerable ie1) {
                    IEnumerable ie2 = actual as IEnumerable;
                    if (ie2 == null) {
                        throw new replacedertActualExpectedException(expected, actual, "actual type is not IEnumerable type", expectedName, actualName);
                    }
                    ArrayList list1 = new ArrayList();
                    ArrayList list2 = new ArrayList();
                    foreach (object item in ie1) {
                        list1.Add(item);
                    }
                    foreach (object item in ie2) {
                        list2.Add(item);
                    }
                    if (list1.Count != list2.Count) {
                        throw new replacedertActualExpectedException(list1.Count, list2.Count, "actual count is not equal expected count", expectedName, actualName);
                    }
                    for (int i = 0; i < list1.Count; i++) {
                        AreObjectsEqual(list1[i], list2[i], string.Format("{0}[{1}]", expectedName, i), string.Format("{0}[{1}]", actualName, i), checkType);
                    }
                }
                else {
                    PropertyInfo[] expectedProperties = expectedType.GetProperties(BindingFlags.Instance | BindingFlags.Public);

                    foreach (PropertyInfo property in expectedProperties) {
                        string propertyName = property.Name;
                        string expectedPropertyName = string.Format("{0}.{1}", expectedName, propertyName);
                        string actualPropertyName = string.Format("{0}.{1}", actualName, propertyName);
                        var expectedHandle = GetPropertyHandler.PropertyGetHandler(property);
                        object obj1 = expectedHandle(expected);
                        PropertyInfo property2 = actualType.GetProperty(propertyName);
                        if (property2 == null) {
                            throw new replacedertActualExpectedException(expected, actual, string.Format("actual property {0} is not exists", propertyName), expectedName, actualName);
                        }
                        if (!Object.Equals(property.PropertyType, property2.PropertyType)) {
                            throw new replacedertActualExpectedException(property.PropertyType, property2.PropertyType, string.Format("actual property {0} type is not equal expected property {0} type", propertyName), expectedPropertyName, actualPropertyName);
                        }
                        var actualHandle = GetPropertyHandler.PropertyGetHandler(property2);
                        object obj2 = actualHandle(actual);
                        AreObjectsEqual(obj1, obj2, expectedPropertyName, actualPropertyName, checkType);
                    }
                }
            }
            else if (typeCode == TypeCode.Empty) {
                return;
            }
            else {
                if (typeCode == TypeCode.Double) {
                    double d1 = Math.Round((double)expected, 4);
                    double d2 = Math.Round((double)actual, 4);
                    if (d1.CompareTo(d2) != 0) {
                        throw new replacedertActualExpectedException(expected, actual, "actual value is not equal expected value", expectedName, actualName);
                    }
                }
                else if (typeCode == TypeCode.Single) {
                    double d1 = Math.Round((float)expected, 4);
                    double d2 = Math.Round((float)actual, 4);
                    if (d1.CompareTo(d2) != 0) {
                        throw new replacedertActualExpectedException(expected, actual, "actual value is not equal expected value", expectedName, actualName);
                    }
                }
                else {
                    if (!Object.Equals(expected, actual)) {
                        throw new replacedertActualExpectedException(expected, actual, "actual value is not equal expected value", expectedName, actualName);
                    }
                }
            }
        }

19 Source : SettingsDefinitionWrapper.cs
with MIT License
from Aragas

private static string? GetSettingsId(object @object)
        {
            var propInfo = @object.GetType().GetProperty(nameof(SettingsId));
            return propInfo?.GetValue(@object) as string;
        }

19 Source : SettingsPropertyGroupDefinitionWrapper.cs
with MIT License
from Aragas

private static string? GetGroupName(object @object)
        {
            var propInfo = @object.GetType().GetProperty(nameof(GroupName));
            return propInfo?.GetValue(@object) as string;
        }

19 Source : SettingsPropertyGroupDefinitionWrapper.cs
with MIT License
from Aragas

private static string? GetGroupNameOverride(object @object)
        {
            var propInfo = @object.GetType().GetProperty("GroupNameOverride");
            return propInfo?.GetValue(@object) as string;
        }

19 Source : SettingsPropertyGroupDefinitionWrapper.cs
with MIT License
from Aragas

private static int? GetGroupOrder(object @object)
        {
            var propInfo = @object.GetType().GetProperty(nameof(Order));
            return propInfo?.GetValue(@object) as int?;
        }

19 Source : BuildingInputState.cs
with GNU General Public License v3.0
from architecture-building-systems

private bool ModifiedProperty([CallerMemberName] string callerMemberName = null)
        {
            var member = callerMemberName.Replace("Brush", "").Replace("FontWeight", "");
            var propertyInfo = typeof(Sia2024RecordEx).GetProperty(member);
            return !AreEqual((double) propertyInfo.GetValue(_siaRoom),
                (double) propertyInfo.GetValue(Sia2024Record.Lookup(_siaRoom)));
        }

19 Source : BaseEndpointClientTests.cs
with MIT License
from Archomeda

protected void replacedertJsonObject(JsonElement.ObjectEnumerator expected, object actual)
        {
            var type = actual.GetType();
            if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(ReadOnlyDictionary<,>) || type.GetGenericTypeDefinition() == typeof(Dictionary<,>)))
            {
                // Dictionary
                var keyType = type.GetGenericArguments()[0];
                var dic = (dynamic)actual;
                foreach (var kvp in expected)
                {
                    dynamic key;
                    if (keyType == typeof(string))
                    {
                        key = kvp.Name;
                    }
                    else
                    {
                        string keyString = string.Concat(kvp.Name.Split('_').Select(s => string.Concat(
                            s[0].ToString().ToUpper(),
                            s.Substring(1))));
                        key = Convert.ChangeType(keyString, keyType);
                        if (key == null)
                            throw new InvalidOperationException($"Expected property '{keyString}' to exist in type {type.FullName}");
                    }
                    var actualValue = dic[key];
                    this.replacedertJsonObject(kvp.Value, actualValue);
                }
            }
            else
            {
                // Specific object
                foreach (var kvp in expected)
                {
                    // Try matching with JsonPropertyNameAttribute first
                    var property = type.GetProperties()
                        .FirstOrDefault(x => x.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name == kvp.Name);
                    if (property == null)
                    {
                        // Try auto matching based on name
                        string key = string.Concat(kvp.Name.Split('_').Select(s => string.Concat(
                            s[0].ToString().ToUpper(),
                            s.Substring(1))));
                        property = type.GetProperty(key);
                        if (property == null)
                            throw new InvalidOperationException($"Expected property '{key}' to exist in type {type.FullName}");
                    }

                    var actualValue = property.GetValue(actual);
                    this.replacedertJsonObject(kvp.Value, actualValue);
                }
            }
        }

See More Examples