System.Reflection.PropertyInfo.GetValue(object, object[])

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

1757 Examples 7

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

public static string GetDescription(this Type that)
    {
        object[] attrs = null;
        try
        {
            attrs = that.GetCustomAttributes(false).ToArray(); //.net core 反射存在版本冲突问题,导致该方法异常
        }
        catch { }

        var dyattr = attrs?.Where(a => {
            return ((a as Attribute)?.TypeId as Type)?.Name == "DescriptionAttribute";
        }).FirstOrDefault();
        if (dyattr != null)
        {
            var valueProp = dyattr.GetType().GetProperties().Where(a => a.PropertyType == typeof(string)).FirstOrDefault();
            var comment = valueProp?.GetValue(dyattr, null)?.ToString();
            if (string.IsNullOrEmpty(comment) == false)
                return comment;
        }
        return null;
    }

19 View Source File : TransformCopyTest.cs
License : MIT License
Project Creator : 39M

private void replacedertObjectsEqual(object a, object b) {
      if ((a == null) != (b == null)) {
        replacedert.Fail("One object was null an the other was not.");
        return;
      }

      Type typeA = a.GetType();
      Type typeB = b.GetType();

      if (typeA != typeB) {
        replacedert.Fail("Type " + typeA + " is not equal to type " + typeB + ".");
      }

      if (typeA.IsValueType) {
        replacedert.That(a, Is.EqualTo(b));
        return;
      }

      if (a is IList) {
        IList aList = a as IList;
        IList bList = b as IList;

        replacedert.That(aList.Count, Is.EqualTo(bList.Count));

        for (int i = 0; i < aList.Count; i++) {
          replacedertObjectsEqual(aList[i], bList[i]);
        }
      } else {
        FieldInfo[] fields = typeA.GetFields(BindingFlags.Public | BindingFlags.Instance);
        foreach (FieldInfo field in fields) {
          replacedertObjectsEqual(field.GetValue(a), field.GetValue(b));
        }

        PropertyInfo[] properties = typeA.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo property in properties) {
          if (property.GetIndexParameters().Length == 0) {
            object propA;
            try {
              propA = property.GetValue(a, null);
            } catch (Exception exceptionA) {
              try {
                property.GetValue(b, null);
                replacedert.Fail("One property threw an exception where the other did not.");
                return;
              } catch (Exception exceptionB) {
                replacedert.That(exceptionA.GetType(), Is.EqualTo(exceptionB.GetType()), "Both properties threw exceptions but their types were different.");
                return;
              }
            }

            object propB = property.GetValue(b, null);

            replacedertObjectsEqual(propA, propB);
          }
        }
      }
    }

19 View Source File : JsonMapper.cs
License : MIT License
Project Creator : 404Lcc

private static void WriteValue (object obj, JsonWriter writer,
                                        bool writer_is_private,
                                        int depth)
        {
            if (depth > max_nesting_depth)
                throw new JsonException (
                    String.Format ("Max allowed object depth reached while " +
                                   "trying to export from type {0}",
                                   obj.GetType ()));

            if (obj == null) {
                writer.Write (null);
                return;
            }
            
            Type obj_type;
            if (obj is ILRuntime.Runtime.Intepreter.ILTypeInstance)
            {
                obj_type = ((ILRuntime.Runtime.Intepreter.ILTypeInstance)obj).Type.ReflectionType;
            }
            else if(obj is ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)
            {
                obj_type = ((ILRuntime.Runtime.Enviorment.CrossBindingAdaptorType)obj).ILInstance.Type.ReflectionType;
            }
            else
                obj_type = obj.GetType();

            // See if there's a custom exporter for the object
            if (custom_exporters_table.ContainsKey (obj_type)) {
                ExporterFunc exporter = custom_exporters_table[obj_type];
                exporter (obj, writer);

                return;
            }

            // If not, maybe there's a base exporter
            if (base_exporters_table.ContainsKey (obj_type)) {
                ExporterFunc exporter = base_exporters_table[obj_type];
                exporter (obj, writer);

                return;
            }


            if (obj is IJsonWrapper) {
                if (writer_is_private)
                    writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
                else
                    ((IJsonWrapper) obj).ToJson (writer);

                return;
            }

            if (obj is String) {
                writer.Write ((string) obj);
                return;
            }

            if (obj is Double) {
                writer.Write ((double) obj);
                return;
            }

            if (obj is Int64) {
                writer.Write ((long) obj);
                return;
            }
            
            if (obj is Int32) {
                writer.Write ((int) obj);
                return;
            }

            if (obj is Boolean) {
                writer.Write ((bool) obj);
                return;
            }

            if (obj is Array) {
                writer.WriteArrayStart ();

                foreach (object elem in (Array) obj)
                    WriteValue (elem, writer, writer_is_private, depth + 1);

                writer.WriteArrayEnd ();

                return;
            }

            if (obj is IList) {
                writer.WriteArrayStart ();
                foreach (object elem in (IList) obj)
                    WriteValue (elem, writer, writer_is_private, depth + 1);
                writer.WriteArrayEnd ();

                return;
            }

            if (obj is IDictionary) {
                writer.WriteObjectStart ();
                foreach (DictionaryEntry entry in (IDictionary) obj) {
                    writer.WritePropertyName (entry.Key.ToString());
                    WriteValue (entry.Value, writer, writer_is_private,
                                depth + 1);
                }
                writer.WriteObjectEnd ();

                return;
            }

            
            // Last option, let's see if it's an enum
            if (obj is Enum) {
                Type e_type = Enum.GetUnderlyingType (obj_type);

                if (e_type == typeof (long)
                    || e_type == typeof (uint)
                    || e_type == typeof (ulong))
                    writer.Write ((ulong) obj);
                else
                    writer.Write ((int) obj);

                return;
            }

            // Okay, so it looks like the input should be exported as an
            // object
            AddTypeProperties (obj_type);
            IList<PropertyMetadata> props = type_properties[obj_type];

            writer.WriteObjectStart ();
            foreach (PropertyMetadata p_data in props) {
                if (p_data.IsField) {
                    writer.WritePropertyName (p_data.Info.Name);
                    WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
                                writer, writer_is_private, depth + 1);
                }
                else {
                    PropertyInfo p_info = (PropertyInfo) p_data.Info;

                    if (p_info.CanRead) {
                        writer.WritePropertyName (p_data.Info.Name);
                        WriteValue (p_info.GetValue (obj, null),
                                    writer, writer_is_private, depth + 1);
                    }
                }
            }
            writer.WriteObjectEnd ();
        }

19 View Source File : PropertyExtension.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public static string ComparisonTo<T1, T2>(this T1 source, T2 current)
        {
            string diff = "";
            try
            {
                Type t1 = source.GetType();
                Type t2 = current.GetType();
                PropertyInfo[] property2 = t2.GetProperties();
                //排除主键和基础字段
                List<string> exclude = new List<string>() { "Id" };
                foreach (PropertyInfo p in property2)
                {
                    string name = p.Name;
                    if (exclude.Contains(name)) { continue; }
                    var value1 = t1.GetProperty(name)?.GetValue(source, null)?.ToString();
                    var value2 = p.GetValue(current, null)?.ToString();
                    if (value1 != value2)
                    {
                        diff += $"[{name}]:'{value1}'=>'{value2}';\r\n";
                    }
                }
            }
            catch(Exception)
            {
              
            }
            return diff;
        }

19 View Source File : HighlightingBrush.cs
License : MIT License
Project Creator : Abdesol

public override Brush GetBrush(ITextRunConstructionContext context)
		{
			return (Brush)property.GetValue(null, null);
		}

19 View Source File : InspectorGenericFields.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static List<InspectorPropertySetting> GetSettings(T source)
        {
            Type myType = source.GetType();
            List<InspectorPropertySetting> settings = new List<InspectorPropertySetting>();

            List<PropertyInfo> propInfoList = new List<PropertyInfo>(myType.GetProperties());
            for (int i = 0; i < propInfoList.Count; i++)
            {
                PropertyInfo propInfo = propInfoList[i];
                var attrs = (InspectorField[])propInfo.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    settings.Add(InspectorField.FieldToProperty(attr, propInfo.GetValue(source, null), propInfo.Name));
                }
            }

            List<FieldInfo> fieldInfoList = new List<FieldInfo>(myType.GetFields());
            for (int i = 0; i < fieldInfoList.Count; i++)
            {
                FieldInfo fieldInfo = fieldInfoList[i];
                var attrs = (InspectorField[])fieldInfo.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    settings.Add(InspectorField.FieldToProperty(attr, fieldInfo.GetValue(source), fieldInfo.Name));
                }
            }

            return settings;
        }

19 View Source File : InspectorFieldsUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static List<InspectorFieldData> GetInspectorFields(System.Object target)
        {
            List<InspectorFieldData> fields = new List<InspectorFieldData>();
            Type myType = target.GetType();

            foreach (PropertyInfo prop in myType.GetProperties())
            {
                var attrs = (InspectorField[])prop.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    fields.Add(new InspectorFieldData() { Name = prop.Name, Attributes = attr, Value = prop.GetValue(target, null) });
                }
            }

            foreach (FieldInfo field in myType.GetFields())
            {
                var attrs = (InspectorField[])field.GetCustomAttributes(typeof(InspectorField), false);
                foreach (var attr in attrs)
                {
                    fields.Add(new InspectorFieldData() { Name = field.Name, Attributes = attr, Value = field.GetValue(target) });
                }
            }

            return fields;
        }

19 View Source File : SurfaceMeshWithPaletteProvider.xaml.cs
License : MIT License
Project Creator : ABTSoftware

private List<Color> GetCashedColorsCollection()
        {
            return typeof(Colors).GetProperties().Select(x => (Color)x.GetValue(null, null)).ToList();
        }

19 View Source File : WebRequestExtensions.cs
License : MIT License
Project Creator : Accelerider

public static void SetHeaderValue(this WebHeaderCollection header, string name, string value)
        {
            var property = typeof(WebHeaderCollection).GetProperty("InnerCollection",
                System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            if (property != null)
            {
                var collection = property.GetValue(header, null) as NameValueCollection;
                collection[name] = value;
            }
        }

19 View Source File : WorldObject.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public string DebugOutputString(WorldObject obj)
        {
            var sb = new StringBuilder();

            sb.AppendLine("ACE Debug Output:");
            sb.AppendLine("ACE Clreplaced File: " + GetType().Name + ".cs");
            sb.AppendLine("Guid: " + obj.Guid.Full + " (0x" + obj.Guid.Full.ToString("X") + ")");

            sb.AppendLine("----- Private Fields -----");
            foreach (var prop in obj.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).OrderBy(field => field.Name))
            {
                if (prop.GetValue(obj) == null)
                    continue;

                sb.AppendLine($"{prop.Name.Replace("<", "").Replace(">k__BackingField", "")} = {prop.GetValue(obj)}");
            }

            sb.AppendLine("----- Public Properties -----");
            foreach (var prop in obj.GetType().GetProperties().OrderBy(property => property.Name))
            {
                if (prop.GetValue(obj, null) == null)
                    continue;

                switch (prop.Name.ToLower())
                {
                    case "guid":
                        sb.AppendLine($"{prop.Name} = {obj.Guid.Full} (GuidType.{obj.Guid.Type.ToString()})");
                        break;
                    case "descriptionflags":
                        sb.AppendLine($"{prop.Name} = {ObjectDescriptionFlags.ToString()}" + " (" + (uint)ObjectDescriptionFlags + ")");
                        break;
                    case "weenieflags":
                        var weenieFlags = CalculateWeenieHeaderFlag();
                        sb.AppendLine($"{prop.Name} = {weenieFlags.ToString()}" + " (" + (uint)weenieFlags + ")");
                        break;
                    case "weenieflags2":
                        var weenieFlags2 = CalculateWeenieHeaderFlag2();
                        sb.AppendLine($"{prop.Name} = {weenieFlags2.ToString()}" + " (" + (uint)weenieFlags2 + ")");
                        break;
                    case "itemtype":
                        sb.AppendLine($"{prop.Name} = {obj.ItemType.ToString()}" + " (" + (uint)obj.ItemType + ")");
                        break;
                    case "creaturetype":
                        sb.AppendLine($"{prop.Name} = {obj.CreatureType.ToString()}" + " (" + (uint)obj.CreatureType + ")");
                        break;
                    case "containertype":
                        sb.AppendLine($"{prop.Name} = {obj.ContainerType.ToString()}" + " (" + (uint)obj.ContainerType + ")");
                        break;
                    case "usable":
                        sb.AppendLine($"{prop.Name} = {obj.ItemUseable.ToString()}" + " (" + (uint)obj.ItemUseable + ")");
                        break;
                    case "radarbehavior":
                        sb.AppendLine($"{prop.Name} = {obj.RadarBehavior.ToString()}" + " (" + (uint)obj.RadarBehavior + ")");
                        break;
                    case "physicsdescriptionflag":
                        var physicsDescriptionFlag = CalculatedPhysicsDescriptionFlag();
                        sb.AppendLine($"{prop.Name} = {physicsDescriptionFlag.ToString()}" + " (" + (uint)physicsDescriptionFlag + ")");
                        break;
                    case "physicsstate":
                        var physicsState = PhysicsObj.State;
                        sb.AppendLine($"{prop.Name} = {physicsState.ToString()}" + " (" + (uint)physicsState + ")");
                        break;
                    //case "propertiesspellid":
                    //    foreach (var item in obj.PropertiesSpellId)
                    //    {
                    //        sb.AppendLine($"PropertySpellId.{Enum.GetName(typeof(Spell), item.SpellId)} ({item.SpellId})");
                    //    }
                    //    break;
                    case "validlocations":
                        sb.AppendLine($"{prop.Name} = {obj.ValidLocations}" + " (" + (uint)obj.ValidLocations + ")");
                        break;
                    case "currentwieldedlocation":
                        sb.AppendLine($"{prop.Name} = {obj.CurrentWieldedLocation}" + " (" + (uint)obj.CurrentWieldedLocation + ")");
                        break;
                    case "priority":
                        sb.AppendLine($"{prop.Name} = {obj.ClothingPriority}" + " (" + (uint)obj.ClothingPriority + ")");
                        break;
                    case "radarcolor":
                        sb.AppendLine($"{prop.Name} = {obj.RadarColor}" + " (" + (uint)obj.RadarColor + ")");
                        break;
                    case "location":
                        sb.AppendLine($"{prop.Name} = {obj.Location.ToLOCString()}");
                        break;
                    case "destination":
                        sb.AppendLine($"{prop.Name} = {obj.Destination.ToLOCString()}");
                        break;
                    case "instantiation":
                        sb.AppendLine($"{prop.Name} = {obj.Instantiation.ToLOCString()}");
                        break;
                    case "sanctuary":
                        sb.AppendLine($"{prop.Name} = {obj.Sanctuary.ToLOCString()}");
                        break;
                    case "home":
                        sb.AppendLine($"{prop.Name} = {obj.Home.ToLOCString()}");
                        break;
                    case "portalsummonloc":
                        sb.AppendLine($"{prop.Name} = {obj.PortalSummonLoc.ToLOCString()}");
                        break;
                    case "houseboot":
                        sb.AppendLine($"{prop.Name} = {obj.HouseBoot.ToLOCString()}");
                        break;
                    case "lastoutsidedeath":
                        sb.AppendLine($"{prop.Name} = {obj.LastOutsideDeath.ToLOCString()}");
                        break;
                    case "linkedlifestone":
                        sb.AppendLine($"{prop.Name} = {obj.LinkedLifestone.ToLOCString()}");
                        break;                    
                    case "channelsactive":
                        sb.AppendLine($"{prop.Name} = {(Channel)obj.GetProperty(PropertyInt.ChannelsActive)}" + " (" + (uint)obj.GetProperty(PropertyInt.ChannelsActive) + ")");
                        break;
                    case "channelsallowed":
                        sb.AppendLine($"{prop.Name} = {(Channel)obj.GetProperty(PropertyInt.ChannelsAllowed)}" + " (" + (uint)obj.GetProperty(PropertyInt.ChannelsAllowed) + ")");
                        break;
                    case "playerkillerstatus":
                        sb.AppendLine($"{prop.Name} = {obj.PlayerKillerStatus}" + " (" + (uint)obj.PlayerKillerStatus + ")");
                        break;
                    default:
                        sb.AppendLine($"{prop.Name} = {prop.GetValue(obj, null)}");
                        break;
                }
            }

            sb.AppendLine("----- Property Dictionaries -----");

            foreach (var item in obj.GetAllPropertyBools())
                sb.AppendLine($"PropertyBool.{Enum.GetName(typeof(PropertyBool), item.Key)} ({(int)item.Key}) = {item.Value}");
            foreach (var item in obj.GetAllPropertyDataId())
                sb.AppendLine($"PropertyDataId.{Enum.GetName(typeof(PropertyDataId), item.Key)} ({(int)item.Key}) = {item.Value}");
            foreach (var item in obj.GetAllPropertyFloat())
                sb.AppendLine($"PropertyFloat.{Enum.GetName(typeof(PropertyFloat), item.Key)} ({(int)item.Key}) = {item.Value}");
            foreach (var item in obj.GetAllPropertyInstanceId())
                sb.AppendLine($"PropertyInstanceId.{Enum.GetName(typeof(PropertyInstanceId), item.Key)} ({(int)item.Key}) = {item.Value}");
            foreach (var item in obj.GetAllPropertyInt())
                sb.AppendLine($"PropertyInt.{Enum.GetName(typeof(PropertyInt), item.Key)} ({(int)item.Key}) = {item.Value}");
            foreach (var item in obj.GetAllPropertyInt64())
                sb.AppendLine($"PropertyInt64.{Enum.GetName(typeof(PropertyInt64), item.Key)} ({(int)item.Key}) = {item.Value}");
            foreach (var item in obj.GetAllPropertyString())
                sb.AppendLine($"PropertyString.{Enum.GetName(typeof(PropertyString), item.Key)} ({(int)item.Key}) = {item.Value}");

            sb.AppendLine("\n");

            return sb.ToString().Replace("\r", "");
        }

19 View Source File : SheetFilter.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public Predicate<object> GetFilter()
        {
            string properyName = FilterPropertyName;
            switch (FilterPropertyName)
            {
                case "Export Name":
                    var m = FirstDigitOfLastNumberInString(FilterValue);
                    if (m == null)
                    {
                        return null;
                    }
                    return item => m == FirstDigitOfLastNumberInString((item as ExportSheet).FullExportName);
                case "Number":
                    var n = FirstDigitOfLastNumberInString(FilterValue);
                    if (n == null)
                    {
                        return null;
                    }
                    return item => n == FirstDigitOfLastNumberInString((item as ExportSheet).SheetNumber);
                case "Name":
                    properyName = "SheetDescription";
                    var noNumbers = Regex.Replace(FilterValue, "[0-9-]", @" ");
                    string[] parts = noNumbers.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                    return item => parts.Any(item.GetType().GetProperty(properyName).GetValue(item, null).ToString().Contains);
                case "Revision":
                    properyName = "SheetRevision";
                    break;
                case "Revision Description":
                    properyName = "SheetRevisionDescription";
                    break;
                case "Revision Date":
                    properyName = "SheetRevisionDate";
                    break;
                case "Scale":
                    properyName = "Scale";
                    break;
                case "North Point":
                    properyName = "NorthPointVisibilityString";
                    break;
                default:
                    return null;
            }    
            return item => item.GetType().GetProperty(properyName).GetValue(item, null).ToString().Equals(FilterValue, StringComparison.InvariantCulture);
        }

19 View Source File : NeuralLearner.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence

private static object GetObjectPropertyValue(object src, string propName)
        {
            var result = src.GetType().GetProperty(propName).GetValue(src, null);
            return result;
        }

19 View Source File : CopyObjectExtensions.cs
License : MIT License
Project Creator : adospace

public static void CopyPropertiesTo(this object source, object dest, PropertyInfo[] destProps)
        {
            if (source.GetType().FullName != dest.GetType().FullName)
            {
                //can't copy state over a type with a different name: surely it's a different type
                return;
            }

            var sourceProps = source.GetType()
                .GetProperties()
                .Where(x => x.CanRead)
                .ToList();

            foreach (var sourceProp in sourceProps)
            {
                var targetProperty = destProps.FirstOrDefault(x => x.Name == sourceProp.Name);
                if (targetProperty != null)
                {
                    var sourceValue = sourceProp.GetValue(source, null);
                    if (sourceValue != null && sourceValue.GetType().IsEnum)
                    {
                        sourceValue = Convert.ChangeType(sourceValue, Enum.GetUnderlyingType(sourceProp.PropertyType));
                    }

                    try
                    {
                        targetProperty.SetValue(dest, sourceValue, null);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"Unable to copy property '{targetProperty.Name}' of state ({source.GetType()}) to new state after hot reload (Exception: '{DumpExceptionMessage(ex)}')");
                    }
                }
            }

        }

19 View Source File : AnonymousTypeWrapper.cs
License : MIT License
Project Creator : adoconnection

public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            PropertyInfo propertyInfo = this.model.GetType().GetProperty(binder.Name);

            if (propertyInfo == null)
            {
                result = null;
                return false;
            }

            result = propertyInfo.GetValue(this.model, null);

            if (result == null)
            {
                return true;
            }

            var type = result.GetType();

            if (result.IsAnonymous())
            {
                result = new AnonymousTypeWrapper(result);
            }

            bool isEnumerable = typeof(IEnumerable).IsreplacedignableFrom(type);

            if (isEnumerable && !(result is string))
            {
                result = ((IEnumerable<object>) result)
                        .Select(e =>
                        {
                            if (e.IsAnonymous())
                            {
                                return new AnonymousTypeWrapper(e);
                            }

                            return e;
                        })
                        .ToList();
            }
        

            return true;
        }

19 View Source File : ObjectShredder.cs
License : MIT License
Project Creator : Adoxio

public object[] ShredObject(DataTable table, T instance)
		{
			FieldInfo[] fi = _fi;
			PropertyInfo[] pi = _pi;

			if (instance.GetType() != typeof(T))
			{
				// If the instance is derived from T, extend the table schema
				// and get the properties and fields.
				ExtendTable(table, instance.GetType());
				fi = instance.GetType().GetFields();
				pi = instance.GetType().GetProperties();
			}

			// Add the property and field values of the instance to an array.
			var values = new object[table.Columns.Count];
			foreach (FieldInfo f in fi)
			{
				values[_ordinalMap[f.Name]] = f.GetValue(instance);
			}

			foreach (PropertyInfo p in pi)
			{
				values[_ordinalMap[p.Name]] = p.GetValue(instance, null);
			}

			// Return the property and field values of the instance.
			return values;
		}

19 View Source File : ConfigurationElementCollection.cs
License : MIT License
Project Creator : Adoxio

protected override object GetElementKey(ConfigurationElement element)
		{
			var pi = element.GetType().GetProperty("Name");
			return pi.GetValue(element, null);
		}

19 View Source File : AttributeInfo.cs
License : MIT License
Project Creator : Adoxio

public object GetValue(object enreplacedy)
		{
			return Property.GetValue(enreplacedy, null);
		}

19 View Source File : SignUpAttributeElementCollection.cs
License : MIT License
Project Creator : Adoxio

protected override object GetElementKey(ConfigurationElement element)
		{
			var pi = element.GetType().GetProperty("LogicalName");
			return pi.GetValue(element, null);
		}

19 View Source File : CrmOrganizationServiceContext.cs
License : MIT License
Project Creator : Adoxio

object IUpdatable.GetValue(object targetResource, string propertyName)
		{
			Tracing.FrameworkInformation("CrmOrganizationServiceContext", "GetValue", "targetResource={0}, propertyName={1}", targetResource, propertyName);

			var type = targetResource.GetType();
			var pi = type.GetProperty(propertyName);

			if (pi == null)
			{
				throw new DataServiceException("The target resource of type '{0}' does not contain a property named '{1}'.".FormatWith(type, propertyName));
			}

			return pi.GetValue(targetResource, null);
		}

19 View Source File : GenericExtensions.cs
License : MIT License
Project Creator : adrenak

public static T GetCopyOf<T>(this Component comp, T other) where T : Component {
            Type type = comp.GetType();
            if (type != other.GetType()) return null; // type mis-match
            BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly;
            PropertyInfo[] pinfos = type.GetProperties(flags);
            foreach (var pinfo in pinfos) {
                if (pinfo.CanWrite) {
                    try {
                        pinfo.SetValue(comp, pinfo.GetValue(other, null), null);
                    }
                    catch { } // In case of NotImplementedException being thrown. For some reason specifying that exception didn't seem to catch it, so I didn't catch anything specific.
                }
            }
            FieldInfo[] finfos = type.GetFields(flags);
            foreach (var finfo in finfos)
                finfo.SetValue(comp, finfo.GetValue(other));
            return comp as T;
        }

19 View Source File : HttpHelper.cs
License : GNU General Public License v3.0
Project Creator : aduskin

static HttpWebRequest Http_Core(string _type, string _url, Encoding _encoding, List<replacedem> _header, object _conmand = null)
      {
         #region 启动HTTP请求之前的初始化操作
         bool isget = false;
         if (_type == "GET")
         {
            isget = true;
         }

         if (isget)
         {
            if (_conmand is List<replacedem>)
            {
               List<replacedem> _conmand_ = (List<replacedem>)_conmand;

               string param = "";
               foreach (replacedem item in _conmand_)
               {
                  if (string.IsNullOrEmpty(param))
                  {
                     if (_url.Contains("?"))
                     {
                        param += "&" + item.Name + "=" + item.Value;
                     }
                     else
                     {
                        param = "?" + item.Name + "=" + item.Value;
                     }
                  }
                  else
                  {
                     param += "&" + item.Name + "=" + item.Value;
                  }
               }
               _url += param;
            }

         }
         Uri uri = null;
         try
         {
            uri = new Uri(_url);
         }
         catch { }
         #endregion
         if (uri != null)
         {
            //string _scheme = uri.Scheme.ToUpper();
            try
            {

               HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
               req.Proxy = null;
               req.Host = uri.Host;
               req.Method = _type;
               req.AllowAutoRedirect = false;
               bool isContentType = true;
               #region 设置请求头
               if (_header != null && _header.Count > 0)
               {
                  bool isnotHeader = true;
                  System.Collections.Specialized.NameValueCollection collection = null;

                  foreach (replacedem item in _header)
                  {
                     string _Lower_Name = item.Name.ToLower();
                     switch (_Lower_Name)
                     {
                        case "host":
                           req.Host = item.Value;
                           break;
                        case "accept":
                           req.Accept = item.Value;
                           break;
                        case "user-agent":
                           req.UserAgent = item.Value;
                           break;
                        case "referer":
                           req.Referer = item.Value;
                           break;
                        case "content-type":
                           isContentType = false;
                           req.ContentType = item.Value;
                           break;
                        case "cookie":
                           #region 设置COOKIE
                           string _cookie = item.Value;
                           CookieContainer cookie_container = new CookieContainer();
                           if (_cookie.IndexOf(";") >= 0)
                           {
                              string[] arrCookie = _cookie.Split(';');
                              //加载Cookie
                              //cookie_container.SetCookies(new Uri(url), cookie);
                              foreach (string sCookie in arrCookie)
                              {
                                 if (string.IsNullOrEmpty(sCookie))
                                 {
                                    continue;
                                 }
                                 if (sCookie.IndexOf("expires") > 0)
                                 {
                                    continue;
                                 }
                                 cookie_container.SetCookies(uri, sCookie);
                              }
                           }
                           else
                           {
                              cookie_container.SetCookies(uri, _cookie);
                           }
                           req.CookieContainer = cookie_container;
                           #endregion
                           break;
                        default:
                           if (isnotHeader && collection == null)
                           {
                              var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                              if (property != null)
                              {
                                 collection = property.GetValue(req.Headers, null) as System.Collections.Specialized.NameValueCollection;
                              }
                              isnotHeader = false;
                           }
                           //设置对象的Header数据
                           if (collection != null)
                           {
                              collection[item.Name] = item.Value;
                           }
                           break;

                     }
                  }
               }
               #endregion

               #region 设置POST数据 
               if (!isget)
               {
                  if (_conmand != null)
                  {
                     if (_conmand is List<replacedem>)
                     {
                        List<replacedem> _conmand_ = (List<replacedem>)_conmand;
                        //POST参数
                        if (isContentType)
                        {
                           req.ContentType = "application/x-www-form-urlencoded";
                        }
                        string param = "";
                        foreach (replacedem item in _conmand_)
                        {
                           if (string.IsNullOrEmpty(param))
                           {
                              param = item.Name + "=" + item.Value;
                           }
                           else
                           {
                              param += "&" + item.Name + "=" + item.Value;
                           }
                        }

                        byte[] bs = _encoding.GetBytes(param);

                        req.ContentLength = bs.Length;

                        using (Stream reqStream = req.GetRequestStream())
                        {
                           reqStream.Write(bs, 0, bs.Length);
                           reqStream.Close();
                        }
                     }
                     else if (_conmand is string[])
                     {
                        try
                        {
                           string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                           byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                           byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

                           req.ContentType = "multipart/form-data; boundary=" + boundary;


                           using (Stream reqStream = req.GetRequestStream())
                           {
                              string[] files = (string[])_conmand;

                              string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                              byte[] buff = new byte[1024];
                              for (int i = 0; i < files.Length; i++)
                              {
                                 string file = files[i];
                                 reqStream.Write(boundarybytes, 0, boundarybytes.Length);

                                 string contentType = MimeMappingProvider.Shared.GetMimeMapping(file);

                                 //string contentType = System.Web.MimeMapping.GetMimeMapping(file);

                                 //string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(file), contentType);
                                 string header = string.Format(headerTemplate, "media", Path.GetFileName(file), contentType);//微信
                                 byte[] headerbytes = _encoding.GetBytes(header);
                                 reqStream.Write(headerbytes, 0, headerbytes.Length);

                                 using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
                                 {

                                    int contentLen = fileStream.Read(buff, 0, buff.Length);

                                    int Value = contentLen;
                                    //文件上传开始
                                    //tProgress.Invoke(new Action(() =>
                                    //{
                                    //    tProgress.Maximum = (int)fileStream.Length;
                                    //    tProgress.Value = Value;
                                    //}));

                                    while (contentLen > 0)
                                    {
                                       //文件上传中

                                       reqStream.Write(buff, 0, contentLen);
                                       contentLen = fileStream.Read(buff, 0, buff.Length);
                                       Value += contentLen;

                                       //tProgress.Invoke(new Action(() =>
                                       //{
                                       //    tProgress.Value = Value;
                                       //}));
                                    }
                                 }
                              }

                              //文件上传结束
                              reqStream.Write(endbytes, 0, endbytes.Length);
                           }
                        }
                        catch
                        {
                           if (isContentType)
                           {
                              req.ContentType = null;
                           }
                           req.ContentLength = 0;
                        }

                     }
                     else
                     {
                        //POST参数 
                        if (isContentType)
                        {
                           req.ContentType = "application/x-www-form-urlencoded";
                        }
                        string param = _conmand.ToString();

                        byte[] bs = _encoding.GetBytes(param);

                        req.ContentLength = bs.Length;

                        using (Stream reqStream = req.GetRequestStream())
                        {
                           reqStream.Write(bs, 0, bs.Length);
                           reqStream.Close();
                        }
                     }

                  }
                  else
                  {
                     req.ContentLength = 0;
                  }
               }
               #endregion

               return req;
            }
            catch
            {
            }
         }
         return null;
      }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : Adyen

public static string ToClreplacedDefinitionString(this object o)
        {
            try
            {
                var t = o.GetType();

                var propertyString = new StringBuilder().AppendLine($"clreplaced {o.GetType().Name} {{");

                foreach (var prop in t.GetProperties())
                {
                    var propertyValue = prop.GetValue(o, null);

                    propertyString.Append("\t")
                        .AppendLine(propertyValue != null
                            ? $"{prop.Name}: {propertyValue}".ToIndentedString()
                            : $"{prop.Name}: null");
                }

                propertyString.AppendLine("}");

                return propertyString.ToString();
            }
            catch
            {
                return o.ToString();
            }
        }

19 View Source File : IRCompiler.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

void ReadType(Node node, ref ASTType type, ref TypeSig rawType) {
			for (int i = 0; i < node.Count; i++) {
				var child = node[i];
				if (child.Id == (int)IRConstants.ASTTYPE) {
					type = (ASTType)Enum.Parse(typeof(ASTType), ((Token)child).Image);
				}
				else if (child.Id == (int)IRConstants.RAW_TYPE) {
					var propertyName = ((Token)child[0]).Image;
					var property = typeof(ICorLibTypes).GetProperty(propertyName);
					rawType = (TypeSig)property.GetValue(module.CorLibTypes, null);
				}
			}
		}

19 View Source File : StickerEditor.cs
License : MIT License
Project Creator : agens-no

public override void OnInteractivePreviewGUI(Rect r, GUIStyle background)
        {
            if (textureEditors == null || textureEditors.Count == 0)
            {
                CreateTextureEditor();
            }

            if (currentTextureEditor != null)
            {
                currentTextureEditor.OnInteractivePreviewGUI(r, background);
            }

            if (playing && Sequence.boolValue && Frames.arraySize > 1)
            {
                if (RepaintMethod == null)
                {
                    var type = typeof(Editor).replacedembly.GetType("UnityEditor.GUIView");
                    var prop = type.GetProperty("current", BindingFlags.Static | BindingFlags.Public);
                    GUIView = prop.GetValue(null, null);
                    RepaintMethod = GUIView.GetType().GetMethod("Repaint", BindingFlags.Public | BindingFlags.Instance);
                }

                RepaintMethod.Invoke(GUIView, null);
            }
        }

19 View Source File : StickerPackEditor.cs
License : MIT License
Project Creator : agens-no

private void RepaintView()
        {
            if (repaintMethod == null)
            {
                var type = typeof(Editor).replacedembly.GetType("UnityEditor.GUIView");
                var prop = type.GetProperty("current", BindingFlags.Static | BindingFlags.Public);
                guiView = prop.GetValue(null, null);
                repaintMethod = guiView.GetType().GetMethod("Repaint", BindingFlags.Public | BindingFlags.Instance);
            }
            repaintMethod.Invoke(guiView, null);
        }

19 View Source File : StoredProc.cs
License : Apache License 2.0
Project Creator : agoda-com

public virtual SpParameter[] GetParameters(TRequest parameters)
        {
            var type = typeof(TRequest);
            return type.GetProperties()
                .OfType<PropertyInfo>()
                .Select(info => new SpParameter(info.Name, info.GetValue(parameters, null)))
                .ToArray();
        }

19 View Source File : Enumerations.cs
License : MIT License
Project Creator : ahmed-abdelrazek

public static DataTable ToDataTable<T>(List<T> items)
        {
            DataTable dataTable = new DataTable(typeof(T).Name);

            //Get all the properties
            PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in Props)
            {
                //Setting column names as Property names
                dataTable.Columns.Add(prop.Name);
            }
            foreach (T item in items)
            {
                var values = new object[Props.Length];
                for (int i = 0; i < Props.Length; i++)
                {
                    //inserting property values to datatable rows
                    values[i] = Props[i].GetValue(item, null);
                }
                dataTable.Rows.Add(values);
            }
            //put a breakpoint here and check datatable
            return dataTable;
        }

19 View Source File : Serialization.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static string ToXml(object obj, string rootElement = null)
		{
			System.Xml.XmlDoreplacedent doc = new System.Xml.XmlDoreplacedent();
			doc.LoadXml(string.Format(@"<{0}></{0}>", obj.GetType().Name));

			PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
			foreach (var p in props)
			{
				var node = doc.CreateElement(p.Name);
				node.InnerText = Convert.ToString(p.GetValue(obj, null));
				doc.DoreplacedentElement.AppendChild(node);
			}
			return doc.OuterXml;
		}

19 View Source File : Serialization.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static Dictionary<string, object> ToDictionary(object obj)
		{
			System.Diagnostics.Debug.replacedert(obj != null);
			Dictionary<string, object> dic = new Dictionary<string, object>();
			FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
			foreach (FieldInfo f in fields)
				dic.Add(f.Name, f.GetValue(obj));
			PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
			foreach (PropertyInfo p in props)
				dic.Add(p.Name, p.GetValue(obj, null));
			return dic;
		}

19 View Source File : ConfigurationBase.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public Dictionary<string, object> GetConfigurations()
		{
			lock (_root)
			{
				Dictionary<string, object> dic = new Dictionary<string, object>();
				FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
				foreach (FieldInfo f in fields)
					dic.Add(f.Name, f.GetValue(this));
				PropertyInfo[] props = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
				foreach (PropertyInfo p in props)
					dic.Add(p.Name, p.GetValue(this, null));
				return dic;
			}
		}

19 View Source File : DatabaseEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private void BindParameters(DbCommand cmd, params object[] pramsArray)
		{
			if (pramsArray != null)
			{
				foreach (object prams in pramsArray)
				{
					if (prams == null || prams is string)
						continue;

					foreach (System.Reflection.PropertyInfo prop in prams.GetType().GetProperties())
					{
						DbParameter p = cmd.CreateParameter();
						p.ParameterName = prop.Name;
						p.Value = prop.GetValue(prams, null);
						if (p.Value != null)
							cmd.Parameters.Add(p);
					}
				}
			}
		}

19 View Source File : DatabaseEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private void DumpException(Exception ex, string sql, params object[] pramsArray)
		{
			StringBuilder sb = new StringBuilder();
			if (pramsArray != null)
			{
				foreach (object prams in pramsArray)
				{
					if (prams != null)
					{
						System.Reflection.PropertyInfo[] props = prams.GetType().GetProperties();
						//props.ToList().ForEach(p => sb.AppendFormat("{0} = {1},", p.Name, p.GetValue(prams, null)));
						foreach (var p in props)
							sb.AppendFormat("{0} = {1},", p.Name, p.GetValue(prams, null));
					}
				}
			}
			TraceLogger.Instance.WriteLineError(string.Format(
@"Exception at DatabaseEngine.
sql : {0}
parameters : {1}
exception : {2}", sql, sb.ToString(), ex.Message));
			TraceLogger.Instance.WriteException(ex);
		}

19 View Source File : DatabaseEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

protected static string MakeInsert(string tableName, object prams)
		{
			string sql;
			List<string> cols = new List<string>();
			List<string> vals = new List<string>();
			{
				System.Reflection.PropertyInfo[] props = prams.GetType().GetProperties();
				foreach(var p in props)
				{
					if (p.GetValue(prams, null) != null)
					{
						cols.Add(p.Name);
						vals.Add("@" + p.Name);
					}
				};
			}
			sql = string.Format("INSERT INTO [{0}] ({1}) VALUES({2})", tableName, string.Join(",", cols.ToArray()), string.Join(",", vals.ToArray()));
			return sql;
		}

19 View Source File : DatabaseEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

protected static string MakeUpdate(string tableName, object prams, object condition)
		{
			string sql;
			string filter = MakeFilter(condition);
			List<string> vals = new List<string>();
			{
				System.Reflection.PropertyInfo[] props = prams.GetType().GetProperties();
				//props.Where(p => p.GetValue(prams, null) != null).ToList().ForEach(p => vals.Add(p.Name + "[email protected]" + p.Name));
				foreach (var p in props)
				{
					if (p.GetValue(prams, null) != null)
						vals.Add(p.Name + "[email protected]" + p.Name);
				}
			}
			sql = string.Format("UPDATE [{0}] SET {1} {2}", tableName, string.Join(",", vals.ToArray()), filter);
			return sql;
		}

19 View Source File : DatabaseEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private static string MakeFilter(object condition)
		{
			string filter = string.Empty;
			if (condition != null)
			{
				if (condition is string)
				{
					filter = string.IsNullOrEmpty(condition as string) ? "" : " WHERE " + condition;
				}
				else
				{
					List<string> vals = new List<string>();
					System.Reflection.PropertyInfo[] props = condition.GetType().GetProperties();
					//props.ToList().ForEach(p =>
					foreach(var p in props)
					{
						vals.Add((p.GetValue(condition, null) != null) ? (p.Name + "[email protected]" + p.Name) : (p.Name + " IS NULL"));
					};
					if (vals.Count > 0)
						filter = " WHERE " + string.Join(" AND ", vals.ToArray());
				}
			}
			return filter;
		}

19 View Source File : DatabaseEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private static string MakeOrder(object order)
		{
			string sql = string.Empty;
			if (order != null)
			{
				if (order is string)
				{
					sql = string.IsNullOrEmpty(order as string) ? "" : "ORDER BY " + order;
				}
				else
				{
					List<string> vals = new List<string>();
					System.Reflection.PropertyInfo[] props = order.GetType().GetProperties();
					foreach(var p in props)
					{
						string val = p.GetValue(order, null) as string;
						if (string.Equals(val, "DESC", StringComparison.OrdinalIgnoreCase))
							vals.Add(p.Name + " DESC");
						else
							vals.Add(p.Name);
					};
					if (vals.Count > 0)
					    sql = " ORDER BY " +string.Join(",", vals.ToArray());
				}
			}
			return sql;
		}

19 View Source File : ConfigurationBase.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public Dictionary<string, object> GetConfigurations()
		{
			BindingFlags flag = BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic;
			lock (_root)
			{
				Dictionary<string, object> dic = new Dictionary<string, object>();
				FieldInfo[] fields = this.GetType().GetFields(flag);
				foreach (FieldInfo f in fields)
				{
					if (!f.IsPrivate)
						dic.Add(f.Name, f.GetValue(this));
				}
				PropertyInfo[] props = this.GetType().GetProperties(flag);
				foreach (PropertyInfo p in props)
					dic.Add(p.Name, p.GetValue(this, null));
				return dic;
			}
		}

19 View Source File : DatabaseEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private void DumpException(Exception ex, string sql, params object[] pramsArray)
		{
			StringBuilder sb = new StringBuilder();
			if (pramsArray != null)
			{
				foreach (object prams in pramsArray)
				{
					if (prams != null)
					{
						System.Reflection.PropertyInfo[] props = prams.GetType().GetProperties();
						foreach (var p in props)
							sb.AppendFormat("{0} = {1},", p.Name, p.GetValue(prams, null));
					}
				}
			}
			TraceLog.WriteLineError(string.Format(
@"Exception at DatabaseEngine.
sql : {0}
parameters : {1}
exception : {2}", sql, sb.ToString(), ex.Message));
			TraceLog.WriteException(ex);
		}

19 View Source File : DatabaseEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

protected static string MakeUpdate(string tableName, object prams, object condition)
		{
			string sql;
			string filter = MakeFilter(condition);
			StringBuilder vals = new StringBuilder();
			{
				var props = prams.GetType().GetProperties();
				foreach (var p in props)
				{
					if (Attribute.IsDefined(p, typeof(UpdateIgnore)))
						continue;

					if (p.CanRead)
					{
						vals.Append(vals.Length > 0 ? "," : null);
						if (p.GetValue(prams, null) != null)
							vals.Append(p.Name).Append("[email protected]").Append(p.Name);
						else
							vals.Append(p.Name).Append("=NULL");
					}
				}
			}
			sql = string.Format("UPDATE [{0}] SET {1} {2}", tableName, vals, filter);
			return sql;
		}

19 View Source File : DatabaseEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

protected static string MakeFilter(object condition)
		{
			string filter = string.Empty;
			if (condition != null)
			{
				if (condition is string)
				{
					filter = string.IsNullOrEmpty(condition as string) ? "" : " WHERE " + condition;
				}
				else
				{
					StringBuilder vals = new StringBuilder();
					var props = condition.GetType().GetProperties();
					foreach (var p in props)
					{
						if (p.CanRead)
						{
							vals.Append(vals.Length > 0 ? " AND " : null);
							if (p.GetValue(condition, null) != null)
								vals.Append(p.Name).Append("[email protected]").Append(p.Name);
							else
								vals.Append(p.Name).Append(" IS NULL");
						}
					};
					if (vals.Length > 0)
						filter = vals.Insert(0, " WHERE ").Append(" ").ToString();
				}
			}
			return filter;
		}

19 View Source File : DataConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private static void StructToValues(object obj, SetValueCallback setValue, bool hasField, bool hasInternal)
		{
			Debug.replacedert(obj != null);
			try
			{
				// properties
				{
					var flags = BindingFlags.Instance | BindingFlags.Public | (hasInternal ? BindingFlags.NonPublic : 0);
					var props = obj.GetType().GetProperties(flags);
					foreach (var p in props)
					{
						if (hasInternal)
						{
							var m = p.GetSetMethod(true);
							if (m.IsPrivate || m.IsFamily)
								continue;
						}
						if (p.CanRead)
						{
							setValue(p.Name, p.GetValue(obj, null));
						}
					}
				}
				// fields
				if (hasField)
				{
					var flags = BindingFlags.Instance | BindingFlags.Public | (hasInternal ? BindingFlags.NonPublic : 0);
					var flds = obj.GetType().GetFields(flags);
					foreach (var f in flds)
					{
						if (f.IsPrivate || f.IsFamily || f.IsInitOnly)
							continue;
						setValue(f.Name, f.GetValue(obj));
					}
				}
			}
			catch (Exception ex) { TraceLog.WriteException(ex); throw; }
		}

19 View Source File : DatabaseEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private void BindParameters(DbCommand cmd, params object[] pramsArray)
		{
			if (pramsArray != null)
			{
				foreach (object prams in pramsArray)
				{
					if (prams == null || prams is string)
						continue;

					foreach (var prop in prams.GetType().GetProperties())
					{
						DbParameter p = cmd.CreateParameter();
						p.ParameterName = prop.Name;
						p.Value = prop.GetValue(prams, null);
						if (prop.PropertyType.IsArray)
							p.Value = DataConverter.Convert(p.Value);
						if (p.Value != null)
							cmd.Parameters.Add(p);
					}
				}
			}
		}

19 View Source File : DatabaseEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

protected static string MakeInsert(string tableName, object prams)
		{
			string sql;
			StringBuilder cols = new StringBuilder();
			StringBuilder vals = new StringBuilder();
			{
				var props = prams.GetType().GetProperties();
				foreach (var p in props)
				{
					if (Attribute.IsDefined(p, typeof(InsertIgnore)))
						continue;

					if (p.CanRead && p.GetValue(prams, null) != null)
					{
						cols.Append(cols.Length > 0 ? "," : null).Append(p.Name);
						vals.Append(vals.Length > 0 ? "," : null).Append("@").Append(p.Name);
					}
				};
			}
			sql = string.Format("INSERT INTO [{0}] ({1}) VALUES({2})", tableName, cols, vals);
			return sql;
		}

19 View Source File : DatabaseEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private static string MakeOrder(object order)
		{
			string sql = string.Empty;
			if (order != null)
			{
				if (order is string)
				{
					sql = string.IsNullOrEmpty(order as string) ? "" : "ORDER BY " + order;
				}
				else
				{
					StringBuilder cols = new StringBuilder();
					var props = order.GetType().GetProperties();
					foreach (var p in props)
					{
						string val = p.GetValue(order, null) as string;
						if (string.Equals(val, "DESC", StringComparison.OrdinalIgnoreCase))
							cols.Append(p.Name).Append(" DESC");
						else
							cols.Append(p.Name);
					};
					if (cols.Length > 0)
						sql = cols.Insert(0, " ORDER BY ").Append(" ").ToString();
				}
			}
			return sql;
		}

19 View Source File : DataConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private static void StructToValues(object obj, SetValueCallback setValue, bool hasField, bool hasInternal)
		{
			Debug.replacedert(obj != null);
			try
			{
				// properties
				{
					var flags = BindingFlags.Instance | BindingFlags.Public | (hasInternal ? BindingFlags.NonPublic : 0);
					var props = obj.GetType().GetProperties(flags);
					foreach (var p in props)
					{
						if (hasInternal)
						{
							var m = p.GetSetMethod(true);
							if (m == null)
								continue;
							if (m.IsPrivate || m.IsFamily)
								continue;
						}
						if (p.CanRead)
						{
							setValue(p.Name, p.GetValue(obj, null));
						}
					}
				}
				// fields
				if (hasField)
				{
					var flags = BindingFlags.Instance | BindingFlags.Public | (hasInternal ? BindingFlags.NonPublic : 0);
					var flds = obj.GetType().GetFields(flags);
					foreach (var f in flds)
					{
						if (f.IsPrivate || f.IsFamily || f.IsInitOnly)
							continue;
						setValue(f.Name, f.GetValue(obj));
					}
				}
			}
			catch (Exception ex) { TraceLog.WriteException(ex); throw; }
		}

19 View Source File : ReflectionHelper.cs
License : MIT License
Project Creator : aishang2015

public static object GetPropertyValue(object obj, string property)
        {
            PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
            return propertyInfo.GetValue(obj, null);
        }

19 View Source File : LateBoundReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela

public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo)
        {
            ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo));

            return o => propertyInfo.GetValue(o, null);
        }

19 View Source File : ReflectionUtils.cs
License : MIT License
Project Creator : akaskela

public static object GetMemberValue(MemberInfo member, object target)
        {
            ValidationUtils.ArgumentNotNull(member, nameof(member));
            ValidationUtils.ArgumentNotNull(target, nameof(target));

            switch (member.MemberType())
            {
                case MemberTypes.Field:
                    return ((FieldInfo)member).GetValue(target);
                case MemberTypes.Property:
                    try
                    {
                        return ((PropertyInfo)member).GetValue(target, null);
                    }
                    catch (TargetParameterCountException e)
                    {
                        throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(CultureInfo.InvariantCulture, member.Name), e);
                    }
                default:
                    throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture, member.Name), nameof(member));
            }
        }

19 View Source File : ObservableCollectionExtensions.cs
License : Apache License 2.0
Project Creator : AKruimink

public static void UpdateCollection<T>(this ObservableCollection<T> collection, IList<T> newCollection)
        {
            if (newCollection == null || newCollection.Count == 0)
            {
                collection.Clear();
                return;
            }

            var i = 0;
            foreach (var item in newCollection)
            {
                if (collection.Count > i)
                {
                    var itemIndex = collection.IndexOf(collection.Where(i => Comparer<T>.Default.Compare(i, item) == 0).FirstOrDefault());

                    if (itemIndex < 0)
                    {
                        // Item doesn't exist
                        collection.Insert(i, item);
                    }
                    else if (itemIndex > i || itemIndex < i)
                    {
                        // Item exists, but has moved up or down
                        collection.Move(itemIndex, i);
                    }
                    else
                    {
                        if ((!collection[i]?.Equals(item)) ?? false)
                        {
                            // Item has changed, replace it
                            if (item != null)
                            {
                                foreach (var sourceProperty in item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                                {
                                    var targetProperty = collection[i]?.GetType().GetProperty(sourceProperty.Name);

                                    if (targetProperty != null && targetProperty.CanWrite)
                                    {
                                        targetProperty.SetValue(collection[i], sourceProperty.GetValue(item, null), null);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    // Item doesn't exist
                    collection.Add(item);
                }

                i++;
            }

            // Remove all old items
            while (collection.Count > newCollection.Count)
            {
                collection.RemoveAt(i);
            }
        }

19 View Source File : Uncapsulator.cs
License : MIT License
Project Creator : albahari

public object GetValue (object instance)
            {
                if (_fastGetter == null)
                {
                    if (MemberInfo is FieldInfo fi && fi.IsStatic)
                        return fi.GetValue (null);
                    // In .NET Framework, we get a TypeAccessException when trying to access this via Reflection.Emit
                    else if (MemberInfo is PropertyInfo pi && ((pi.GetMethod?.IsStatic ?? true) || IsDotNetFramework && pi.DeclaringType.IsInterface))
                        return pi.GetValue (instance, null);
                    else
                        // Optimize the common case of getting a field or property.
                        _fastGetter = MemberInfo is FieldInfo fi2
                            ? TypeUtil.GenDynamicField (fi2)
                            : TypeUtil.GenDynamicProp ((PropertyInfo)MemberInfo);
                }
                return _fastGetter (instance);
            }

See More Examples