Inheritance: System.Reflection.ICustomAttributeProvider
        /// <summary>
        /// Examine the a Test and either return it as is, modify it
        /// or return a different TestCase.
        /// </summary>
        /// <param name="test">The Test to be decorated</param>
        /// <param name="member">The MethodInfo used to construct the test</param>
        /// <returns>The resulting Test</returns>
        public Test Decorate(Test test, System.Reflection.MemberInfo member)
        {
            var attr = Reflect.GetAttribute(member, "SymformNUnitExtension.InconclusiveTestAttribute", false);

            if (attr == null)
            {
                return(test);
            }

            var nunitTest = test as NUnitTestMethod;

            if (nunitTest != null)
            {
                return(new InconclusiveTestCase(nunitTest));
            }

            var paramTests = test as ParameterizedMethodSuite;

            if (paramTests != null)
            {
                Decorate(paramTests);
            }

            return(test);
        }
        public MemberMetadata(MemberInfo memberInfo)
        {
            _type = MemberType.None;
            _memberType = null;
            _mi = null;
            _fp = null;

            memberInfo.ThrowIfNull("memberInfo", "Parameter cannot be null.");
            switch (memberInfo.MemberType)
            {
                case MemberTypes.Field:
                    _type = MemberType.Field;
                    _mi = memberInfo;
                    _memberType = (memberInfo as FieldInfo).FieldType;
                    break;
                case MemberTypes.Property:
                    _type = MemberType.Property;
                    _memberType = (memberInfo as PropertyInfo).PropertyType;
                    _fp = new FastReflection.FastProperty((memberInfo as PropertyInfo), true);
                    _mi = memberInfo;
                    break;
                default:
                    break;
            }
        }
        public string GetMemberModifiers(MemberInfo memberInfo)
        {
            ArgumentUtility.CheckNotNull ("memberInfo", memberInfo);

              switch (memberInfo.MemberType)
              {
            case MemberTypes.Method:
            case MemberTypes.Constructor:
              return GetMethodModifiers (memberInfo, memberInfo);
            case MemberTypes.Field:
              return GetFieldModifiers ((FieldInfo)memberInfo);

            case MemberTypes.Property:
              var propertyInfo = (PropertyInfo) memberInfo;
              return GetMethodModifiers (propertyInfo.GetGetMethod (true) ?? propertyInfo.GetSetMethod (true), memberInfo);

            case MemberTypes.Event:
              var eventInfo = (EventInfo) memberInfo;
              return GetMethodModifiers (eventInfo.GetAddMethod (true), memberInfo);

            case MemberTypes.NestedType:
              return _typeModifierUtility.GetTypeModifiers ((Type) memberInfo);

            case MemberTypes.Custom:
            case MemberTypes.TypeInfo:
              return "TODO special MemberTypes";

            default:
              throw new Exception ("unknown member type");
              }
        }
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) {
            JsonProperty property = base.CreateProperty(member, memberSerialization);

            Predicate<object> shouldSerialize = property.ShouldSerialize;
            property.ShouldSerialize = obj => (shouldSerialize == null || shouldSerialize(obj)) && !property.IsValueEmptyCollection(obj);
            return property;
        }
Example #5
0
 public MapCallInfo(Type targetType, Type[] genericTypes, Flags bindingFlags, MemberTypes memberTypes, string name, Type[] parameterTypes, MemberInfo memberInfo, bool isReadOperation, Type sourceType, MemberTypes sourceMemberTypes, MemberTypes targetMemberTypes, string[] names) : base(targetType, genericTypes, bindingFlags, memberTypes, name, parameterTypes, memberInfo, isReadOperation)
 {
     SourceType = sourceType;
     SourceMemberTypes = sourceMemberTypes;
     TargetMemberTypes = targetMemberTypes;
     Names = names;
 }
        protected virtual bool CanBeRouteParameter(MemberInfo info)
        {
            return (info.MemberType == MemberTypes.Field || info.MemberType == MemberTypes.Property)
                   && !info.HasCustomAttribute<ExcludeFromRouteAttribute>()
                   && IsValidForRoute(info.GetMemberType());

        }
Example #7
0
        public TestRunState RunMember(ITestListener testListener, Assembly assembly, MemberInfo member)
        {
            var method = member as MethodInfo;
            if (method != null)
            {
                if (method.IsDispose())
                {
                    var listener = new TestDrivenListener(testListener);
                    listener.CaseSkipped(new SkipResult(new Case(method), "Dispose() is not a test."));
                    return TestRunState.Success;
                }

                return Run(testListener, runner => runner.RunMethods(assembly, method));
            }

            var type = member as Type;
            if (type != null)
            {
                var types = GetTypeAndNestedTypes(type).ToArray();

                return Run(testListener, runner => runner.RunTypes(assembly, types));
            }

            return TestRunState.Error;
        }
Example #8
0
 public ObjectChangedEventArgs(Object obj, System.Reflection.MemberInfo memberInfo, Object oldValue, Object newValue)
     : base(obj)
 {
     this.newValue   = newValue;
     this.oldValue   = oldValue;
     this.memberInfo = memberInfo;
 }
Example #9
0
        static StackObject *GetCustomAttribute_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Boolean @inherit = ptr_of_this_method->Value == 1;

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Type @attributeType = (System.Type) typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Reflection.MemberInfo @element = (System.Reflection.MemberInfo) typeof(System.Reflection.MemberInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);


            var result_of_this_method = System.Attribute.GetCustomAttribute(@element, @attributeType, @inherit);

            object obj_result_of_this_method = result_of_this_method;

            if (obj_result_of_this_method is CrossBindingAdaptorType)
            {
                return(ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance));
            }
            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Example #10
0
        /// <summary>
        /// Examines the designated object type using reflections, extracts any defined
        /// TableAttribute and ColumnAttribute attributes, and builds a new
        /// TableSchema object that represents the database mappings for the type.
        /// </summary>
        /// <returns>The table schema defined for the designated object type.</returns>
        /// <remarks>This schema is used to generate standard Select and CRUD (Create,
        /// Update and Delete) commands and to rollback changes when an edit is
        /// aborted.</remarks>
        public static TableSchema <T> GetSchema()
        {
            TableSchema <T> schema = new TableSchema <T>();

            // use reflection to extract custom attributes from designated type
            System.Reflection.MemberInfo inf = typeof(T);

            // Get Table attribute
            object[] tableattributes;
            tableattributes = inf.GetCustomAttributes(typeof(Framework.TableAttribute), false);
            if (tableattributes.Length != 1)
            {
                throw new Exception("Unable to get schema for business object, missing Table attribute.");
            }
            schema._table = (TableAttribute)tableattributes[0];

            // Get Column attributes
            schema._cols = new Dictionary <string, ColumnAttribute>();
            schema._keys = new Dictionary <string, ColumnAttribute>();
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (props.Length == 0)
            {
                throw new Exception("Target type does not have any properties.");
            }
            foreach (PropertyInfo prop in props)
            {
                object[] columnattributes;
                columnattributes = prop.GetCustomAttributes(typeof(Framework.ColumnAttribute), false);
                if (columnattributes.Length > 0)
                {
                    ColumnAttribute col = (ColumnAttribute)columnattributes[0];
                    if (col.IsPrimaryKey)
                    {
                        schema._keys.Add(prop.Name, col);
                    }
                    schema._cols.Add(prop.Name, col);
                    if (col.IsDBGenerated)
                    {
                        schema._isAnyDBGenerated = true;
                    }
                    if (col.IsVersion)
                    {
                        schema._versioncolumn = prop.Name;
                    }
                    if (col.IsDBGenerated && col.IsPrimaryKey)
                    {
                        schema._identitycolumn = prop.Name;
                    }
                }
            }
            if (schema._cols.Count == 0)
            {
                throw new Exception("Target type does not define any data columns.");
            }
            if (schema._keys.Count == 0)
            {
                throw new Exception("Target type does not define any primary key columns.");
            }
            return(schema);
        }
Example #11
0
        public override void Initialize()
        {
            base.Initialize();

            V2DDefinition def = v2dWorld.GetDefinitionByName(this.definitionName);

            if (def != null)
            {
                for (int i = 0; i < def.Joints.Count; i++)
                {
                    this.AddJoint(def.Joints[i], this.X, this.Y);
                }
            }

            System.Reflection.MemberInfo inf   = this.GetType();
            System.Attribute[]           attrs = System.Attribute.GetCustomAttributes(inf);    // reflection
            foreach (System.Attribute attr in attrs)
            {
                if (attr is V2DScreenAttribute)
                {
                    V2DScreenAttribute a = (V2DScreenAttribute)attr;
                    if (a.gravityX != 0 | a.gravityY != 10)
                    {
                        Gravity = new Vector2(a.gravityX, a.gravityY);
                    }

                    useDebugDraw = a.debugDraw;
                }
            }
        }
Example #12
0
        private bool GetAttrValue(System.Reflection.MemberInfo member, System.Type type, string name, out object value)
        {
            value = null;
            XmlAttribute xmlAttribute = this.node.Attributes[name];
            bool         result;

            if (xmlAttribute != null)
            {
                string value2 = xmlAttribute.Value;
                if (!string.IsNullOrEmpty(value2))
                {
                    value  = System.Convert.ChangeType(value2, type);
                    result = true;
                    return(result);
                }
            }
            else
            {
                object[] customAttributes = member.GetCustomAttributes(false);
                object[] array            = customAttributes;
                for (int i = 0; i < array.Length; i++)
                {
                    object obj = array[i];
                    if (obj is DefaultValueAttribute)
                    {
                        value  = ((DefaultValueAttribute)obj).Value;
                        result = true;
                        return(result);
                    }
                }
            }
            result = false;
            return(result);
        }
Example #13
0
        private string GetPropStr(System.Reflection.MemberInfo member, object value)
        {
            object[] customAttributes = member.GetCustomAttributes(false);
            object[] array            = customAttributes;
            string   result;

            for (int i = 0; i < array.Length; i++)
            {
                object obj = array[i];
                if (obj is DefaultValueAttribute)
                {
                    object value2 = ((DefaultValueAttribute)obj).Value;
                    if (object.Equals(value, value2))
                    {
                        result = "";
                        return(result);
                    }
                }
            }
            if (value == null)
            {
                result = "";
                return(result);
            }
            string text = value.ToString();

            if (value is bool)
            {
                text = text.ToLower();
            }
            result = text;
            return(result);
        }
        static StackObject *GetCustomAttributes_6(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Boolean @inherit = ptr_of_this_method->Value == 1;

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Type @attributeType = (System.Type) typeof(System.Type).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Reflection.MemberInfo instance_of_this_method = (System.Reflection.MemberInfo) typeof(System.Reflection.MemberInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.GetCustomAttributes(true);

            //这里需要对反射进行改造,使其没那么残疾
            List <object> ret = new List <object>();

            foreach (var r in result_of_this_method)
            {
                var iltype = r as ILTypeInstance;
                if (iltype != null && iltype.Type.FullName == @attributeType.AssemblyQualifiedName)
                {
                    ret.Add(r);
                }
            }
            return(ILIntepreter.PushObject(__ret, __mStack, ret.ToArray()));
        }
		protected ISqlExpression[] ConvertArgs(MemberInfo member, ISqlExpression[] args)
		{
			if (member is MethodInfo)
			{
				var method = (MethodInfo)member;

				if (method.DeclaringType.IsGenericType)
					args = args.Concat(method.DeclaringType.GetGenericArguments().Select(t => (ISqlExpression)SqlDataType.GetDataType(t))).ToArray();

				if (method.IsGenericMethod)
					args = args.Concat(method.GetGenericArguments().Select(t => (ISqlExpression)SqlDataType.GetDataType(t))).ToArray();
			}

			if (ArgIndices != null)
			{
				var idxs = new ISqlExpression[ArgIndices.Length];

				for (var i = 0; i < ArgIndices.Length; i++)
					idxs[i] = args[ArgIndices[i]];

				return idxs;
			}

			return args;
		}
Example #16
0
        private static object GetMemberValueFromObject(System.Reflection.MemberInfo mi, object graph)
        {
            try
            {
                object data = null;

                switch (mi.MemberType)
                {
                case MemberTypes.Property:
                    PropertyInfo pi = (PropertyInfo)mi;
                    if (pi.CanRead)
                    {
                        data = pi.GetValue(graph, null);
                    }
                    break;

                case MemberTypes.Field:
                    FieldInfo fi = (FieldInfo)mi;
                    data = fi.GetValue(graph);
                    break;
                }
                return(data);
            }
            catch (Exception ex)
            {
                Exception realEx = ex.GetRealException();
                throw new ApplicationException(string.Format("读取属性{0}值的时候出错,{1}", mi.Name, realEx.Message));
            }
        }
Example #17
0
 public ComputedIndex(DocumentMapping mapping, MemberInfo[] members)
 {
     _members = members;
     var field = mapping.FieldFor(members);
     _locator = field.SqlLocator.Replace("d.", "");
     _table = mapping.Table;
 }
Example #18
0
        public static NHibernate.IQuery SetQuerySource(this NHibernate.IQuery query, System.Reflection.MemberInfo memberInfo)
        {
            var time = DateTime.Now - System.Diagnostics.Process.GetCurrentProcess().StartTime;

            query.SetComment(String.Format("Source:{0}.{1}; Start:{2}", memberInfo.DeclaringType.Name, memberInfo.Name, time.TotalSeconds));
            return(query);
        }
        /// <summary>
        /// Returns the attributes on <paramref name="member"/> that this convention applies to.
        /// </summary>
        /// <param name="member"></param>
        /// <returns></returns>
        public Attribute[] GetAttributes(MemberInfo member)
        {
            if (member == null)
            {
                throw Error.ArgumentNull("member");
            }

            Attribute[] attributes =
                member
                .GetCustomAttributes(inherit: true)
                .OfType<Attribute>()
                .Where(AttributeFilter)
                .ToArray();

            if (!AllowMultiple && attributes.Length > 1)
            {
                throw Error.InvalidOperation(
                    SRResources.MultipleAttributesFound,
                    member.Name,
                    member.ReflectedType.Name,
                    attributes.First().GetType().Name);
            }

            return attributes;
        }
        /// <summary>
        /// Instantiates the extended Test Case class and passes it the SpiraTest Test Case ID
        /// </summary>
        /// <param name="test">The NUnit Test</param>
        /// <param name="member">The method whose attribute we need to read</param>
        /// <returns></returns>
        public Test Decorate(Test test, System.Reflection.MemberInfo member)
        {
            const string METHOD_NAME = "Decorate: ";

            try
            {
                if (test is TestMethod)
                {
                    Attribute attribute = Reflect.GetAttribute(member, "Inflectra.SpiraTest.AddOns.SpiraTestNUnitAddIn.SpiraTestFramework.SpiraTestCaseAttribute", false);
                    if (attribute != null)
                    {
                        //Get the test case id from the test case attribute
                        int testCaseId = (int)Reflect.GetPropertyValue(attribute, "TestCaseId", BindingFlags.Public | BindingFlags.Instance);
                        test = new SpiraTestCase((TestMethod)test, testCaseId);
                    }
                }

                return(test);
            }
            catch (Exception exception)
            {
                //Log error then rethrow
                System.Diagnostics.EventLog.WriteEntry(SpiraTestAddin.SOURCE_NAME, CLASS_NAME + METHOD_NAME + exception.Message, System.Diagnostics.EventLogEntryType.Error);
                throw exception;
            }
        }
 /// <summary>
 /// Gets the Id generator for an Id member.
 /// </summary>
 /// <param name="memberInfo">The member.</param>
 /// <returns>An Id generator.</returns>
 public virtual IIdGenerator GetIdGenerator(MemberInfo memberInfo)
 {
     if (memberInfo.DeclaringType.GetInterfaces().Any(intf => intf == typeof(IEntity)) &&
         (memberInfo.Name == "ID" || memberInfo.Name == "Id" || memberInfo.Name == "iD" ||
         memberInfo.Name == "id" || memberInfo.Name == "_id"))
     {
         switch (memberInfo.MemberType)
         {
             case MemberTypes.Property:
                 PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
                 if (propertyInfo.PropertyType == typeof(Guid) ||
                     propertyInfo.PropertyType == typeof(Guid?))
                     return new GuidGenerator();
                 break;
             case MemberTypes.Field:
                 FieldInfo fieldInfo = (FieldInfo)memberInfo;
                 if (fieldInfo.FieldType == typeof(Guid) ||
                     fieldInfo.FieldType == typeof(Guid?))
                     return new GuidGenerator();
                 break;
             default:
                 break;
         }
     }
     return null;
 }
Example #22
0
    protected void ProcessAttributes()
    {
        m_allowedTypes = new List <Type>();
        int count = 0;

        System.Reflection.MemberInfo info = GetType();
        //B-Se pone true por los tuyos y los heredados
        object[] attributes = info.GetCustomAttributes(true);

        //Version 4.5 - info.GetCustomAttribute<AllowedTypeToStorage>();

        for (int i = 0; i < attributes.Length; ++i)
        {
            if (attributes[i].GetType() == typeof(AllowedTypeToStorage))
            {
                //TODO 1: Añadir a la lista de atributos permitidos. (solucion 001)
                AllowedTypeToStorage allowedType = attributes[i] as AllowedTypeToStorage;
                m_allowedTypes.Add(allowedType.m_type);

                count++;
            }
        }

        Debug.Assert(count > 0, "Error: It Must be defined a Allowed types Attributes");
    }
        /// <summary>
        /// This method supports the Fluorine infrastructure and is not intended to be used directly from your code.
        /// </summary>
        /// <param name="invocationManager"></param>
        /// <param name="memberInfo"></param>
        /// <param name="obj"></param>
        /// <param name="arguments"></param>
        /// <param name="result"></param>
        public void HandleResult(IInvocationManager invocationManager, MemberInfo memberInfo, object obj, object[] arguments, object result)
		{
			if( result is DataSet )
			{
				DataSet dataSet = result as DataSet;
				ASObject asoResult = new ASObject(_remoteClass);

#if !(NET_1_1)
                foreach (KeyValuePair<object, object> entry in invocationManager.Properties)
#else
				foreach(DictionaryEntry entry in invocationManager.Properties)
#endif
				{
					if( entry.Key is DataTable )
					{
						DataTable dataTable = entry.Key as DataTable;
						if( dataSet.Tables.IndexOf(dataTable) != -1 )
						{
							if( !dataTable.ExtendedProperties.ContainsKey("alias") )
								asoResult[dataTable.TableName] = entry.Value;
							else
								asoResult[ dataTable.ExtendedProperties["alias"] as string ] = entry.Value;
						}
					}
				}
				invocationManager.Result = asoResult;
			}
		}
Example #24
0
        private static bool MemberIsOverride(System.Reflection.MemberInfo member)
        {
            if (member is MethodInfo)
            {
                var method = (MethodInfo)member;

                if (method.IsVirtual && !ReferenceEquals(method.GetBaseDefinition(), method))
                {
                    return(true);
                }
            }

            if (member is PropertyInfo)
            {
                var property = (PropertyInfo)member;

                var getMethod = property.GetGetMethod();
                var setMethod = property.GetGetMethod();

                if ((getMethod == null || (getMethod.IsVirtual && MemberIsOverride(getMethod))) &&
                    (setMethod == null || (setMethod.IsVirtual && MemberIsOverride(setMethod))))
                {
                    return(true);
                }
            }

            return(false);
        }
        private object GetProviderObjectFromMember(MemberInfo member)
        {
            object providerObject = null;
            object instance = null;

            switch (member.MemberType)
            {
                case MemberTypes.Property:
                    PropertyInfo providerProperty = member as PropertyInfo;
                    MethodInfo getMethod = providerProperty.GetGetMethod(true);
                    if (!getMethod.IsStatic)
                        //instance = ProviderCache.GetInstanceOf(providerType);
                        instance = Reflect.Construct(providerType, providerArgs);
                    providerObject = providerProperty.GetValue(instance, null);
                    break;

                case MemberTypes.Method:
                    MethodInfo providerMethod = member as MethodInfo;
                    if (!providerMethod.IsStatic)
                        //instance = ProviderCache.GetInstanceOf(providerType);
                        instance = Reflect.Construct(providerType, providerArgs);
                    providerObject = providerMethod.Invoke(instance, null);
                    break;

                case MemberTypes.Field:
                    FieldInfo providerField = member as FieldInfo;
                    if (!providerField.IsStatic)
                        //instance = ProviderCache.GetInstanceOf(providerType);
                        instance = Reflect.Construct(providerType, providerArgs);
                    providerObject = providerField.GetValue(instance);
                    break;
            }

            return providerObject;
        }
Example #26
0
        public ServiceShell()
        {
            try
            {
                //Trace.WriteLine("Get service name");
                System.Reflection.MemberInfo info = GetType();
                var attribs = info.GetCustomAttributes(typeof(ServiceAttribute), true);
                //Trace.WriteLine("attribs: " + attribs.Length);
                for (int i = 0; i < attribs.Length; i++)
                {
                    ServiceName = ((ServiceAttribute)attribs[i]).ServiceName;
                    break;
                }

                Trace.WriteLine(ServiceName);

                CanStop             = true;
                CanPauseAndContinue = false;
                CanShutdown         = true;
                AutoLog             = true;
                Trace.WriteLine("constructor done");
                InitializeComponent();
            }
            catch (Exception ex)
            {
                throw new Exception("isntall error!", ex);
            }
        }
		private static void UpdateDefaultValue(MemberInfo memberInfo, MetaProperty info)
		{
			var defaultAttribute = memberInfo.GetCustomAttribute<DefaultValueAttribute>();
			if (defaultAttribute == null) return;

			info.DefaultValue = defaultAttribute.Value;
		}
        public static T[] GetAttributesInterface <T>(this System.Reflection.MemberInfo type,
                                                     bool inherit  = false,
                                                     bool multiple = false)
        {
            if (!typeof(T).IsInterface)
            {
                throw new ArgumentException($"{typeof(T).FullName} is not an interface.");
            }
            var attributes = type.GetCustomAttributes(inherit)
                             .Where(attr => typeof(T).IsAssignableFrom(attr.GetType()))
                             .Select(attr => (T)attr)
                             .ToArray();

            if (!multiple)
            {
                return(attributes);
            }
            if (!(type is Type))
            {
                return(attributes);
            }
            var typeType = type as Type;

            if (typeType.BaseType.IsDefaultOrNull())
            {
                return(attributes);
            }
            var baseAttrs = typeType.BaseType.GetAttributesInterface <T>(inherit, multiple);

            return(attributes.Concat(baseAttrs).Distinct().ToArray());
        }
Example #29
0
        public static bool IsSerializableMember(MemberInfo member)
        {
            if (member.MemberType == MemberTypes.Method)
                return false;

            var field = member as FieldInfo;
            if (field != null)
            {
                if (IsSerializableFieldPredicate != null)
                    return IsSerializableFieldPredicate(field);

                return DefaultIsSerializableField(field);
            }

            var property = member as PropertyInfo;
            if (property != null)
            {
                if (IsSerializablePropertyPredicate != null)
                    return IsSerializablePropertyPredicate(property);

                return DefaultIsSerializableProperty(property);
            }

            return false;
        }
        public static T[] GetAttributesAndPropertyAttributesInterface <T>(this System.Reflection.MemberInfo member,
                                                                          bool inherit = false)
        {
            if (!typeof(T).IsInterface)
            {
                throw new ArgumentException($"{typeof(T).FullName} is not an interface.");
            }
            var attributes = member.GetCustomAttributes(inherit)
                             .Where(attr => typeof(T).IsAssignableFrom(attr.GetType()))
                             .Select(attr => (T)attr)
                             .ToArray();

            var memberAttributes = GetMemberAttributes();

            return(attributes.Concat(memberAttributes).Distinct().ToArray());

            IEnumerable <T> GetMemberAttributes()
            {
                foreach (var subMember in member.GetMemberType().GetMembers(BindingFlags.Public))
                {
                    foreach (var attr in subMember.GetAttributesInterface <T>(inherit))
                    {
                        yield return(attr);
                    }
                }
            }
        }
        public static PropertyMap GetPropertyMap(this IMappingEngine mappingEngine, MemberInfo sourceMemberInfo, Type destinationMemberType)
        {
            var typeMap = mappingEngine.ConfigurationProvider.FindTypeMapFor(sourceMemberInfo.DeclaringType, destinationMemberType);

            if (typeMap == null)
            {
                const string MessageFormat = "Missing map from {0} to {1}. " +
                                             "Create using Mapper.CreateMap<{0}, {1}>.";
                var message = string.Format(MessageFormat, sourceMemberInfo.DeclaringType.Name, destinationMemberType.Name);
                throw new InvalidOperationException(message);
            }

            var propertyMap = typeMap.GetPropertyMaps()
                .FirstOrDefault(pm => pm.CanResolveValue() &&
                                      pm.SourceMember != null && pm.SourceMember.Name == sourceMemberInfo.Name);

            if (propertyMap == null)
            {
                const string MessageFormat = "Missing property map from {0} to {1} for {2} property. " +
                                             "Create using Mapper.CreateMap<{0}, {1}>.";
                var message = string.Format(MessageFormat, sourceMemberInfo.DeclaringType.Name, destinationMemberType.Name,
                    sourceMemberInfo.Name);
                throw new InvalidOperationException(message);
            }
            return propertyMap;
        }
        public static bool ContainsCustomAttribute <T>(this System.Reflection.MemberInfo type, bool inherit = false)
            where T : System.Attribute
        {
            var attributes = type.GetCustomAttributes <T>(inherit);

            return(attributes.Any());
        }
 public PersistAggregationInfo(object aggregatedObject,string[] keyMapping,MemberInfo mi)
 {
     p_aggregatedObject=aggregatedObject;
     p_mi=mi;
     foreach(string mapping in keyMapping)
         p_alKeyMapping.Add(new KeyMappingInfo(mapping));
 }
Example #34
0
        /// <summary>
        /// Tries to wrap the specified member.
        /// Returns the wrapped result if it succeeds (valid field/property)
        /// otherwise null
        /// </summary>
        public static RuntimeMember WrapMember(System.Reflection.MemberInfo member, object target)
        {
            var field = member as System.Reflection.FieldInfo;

            if (field != null)
            {
                RuntimeMember wrappedField;
                if (RuntimeMember.TryWrapField(field, target, out wrappedField))
                {
                    return(wrappedField);
                }
            }
            else
            {
                var property = member as System.Reflection.PropertyInfo;
                if (property == null)
                {
                    return(null);
                }

                RuntimeMember wrappedProperty;
                if (RuntimeMember.TryWrapProperty(property, target, out wrappedProperty))
                {
                    return(wrappedProperty);
                }
            }

            return(null);
        }
Example #35
0
 public SourceInfo(string source, string arg, MemberInfo memberInfo, Type type, CodeGenerator ilg) {
     this.Source = source;
     this.Arg = arg ?? source;
     this.MemberInfo = memberInfo;
     this.Type = type;
     this.ILG = ilg;
 }
Example #36
0
        private static object GetMemberValue(Ref.MemberInfo member, object obj, out Exception exception)
        {
            exception = null;
            try
            {
                switch (member.MemberType)
                {
                case Ref.MemberTypes.Field:
                    var field = (Ref.FieldInfo)member;
                    return(field.GetValue(obj));

                case Ref.MemberTypes.Method:
                    var method = (Ref.MethodInfo)member;
                    return((method.ReturnType == typeof(void)) ? s_voidValue : method.Invoke(obj, SpecializedCollections.EmptyObjects));

                case Ref.MemberTypes.Property:
                    var property = (Ref.PropertyInfo)member;
                    return(property.GetValue(obj, SpecializedCollections.EmptyObjects));

                default:
                    throw ExceptionUtilities.UnexpectedValue(member.MemberType);
                }
            }
            catch (Ref.TargetInvocationException e)
            {
                exception = e.InnerException;
            }
            return(null);
        }
        bool IsEncryptedMember(MemberInfo arg)
        {
            var propertyInfo = arg as PropertyInfo;
            if (propertyInfo != null)
            {
                if (propertyInfo.GetIndexParameters().Length > 0)
                {
                    if (conventions.IsEncryptedProperty(propertyInfo))
                    {
                        throw new Exception("Cannot encrypt or decrypt indexed properties that return a WireEncryptedString.");
                    }

                    return false;
                }

                return conventions.IsEncryptedProperty(propertyInfo);
            }

            var fieldInfo = arg as FieldInfo;
            if (fieldInfo != null)
            {
                return fieldInfo.FieldType == typeof(WireEncryptedString);
            }

            return false;
        }
Example #38
0
        private List <Attribute> ReadMemberCustomAttributes(System.Reflection.MemberInfo member)
        {
            List <Attribute> cachedAttributes    = null;
            bool             getMemberAttributes = false;

            // Now edit the attributes returned from the base type
            using (new ReadLock(this._lock))
            {
                if (!this._memberInfos.TryGetValue(member, out cachedAttributes))
                {
                    // If there is nothing for this member Cache any attributes for the DeclaringType
                    if (!this._memberInfos.TryGetValue(member.DeclaringType.UnderlyingSystemType, out cachedAttributes))
                    {
                        // If there is nothing for this parameter look to see if the declaring Member has been cached yet?
                        // need to do it outside of the lock, so set the flag we'll check it in a bit
                        getMemberAttributes = true;
                    }
                    cachedAttributes = null;
                }
            }

            if (getMemberAttributes)
            {
                GetCustomAttributes(member.DeclaringType, EmptyList);

                // We should have run the rules for the enclosing parameter so we can again
                using (new ReadLock(this._lock))
                {
                    this._memberInfos.TryGetValue(member, out cachedAttributes);
                }
            }

            return(cachedAttributes);
        }
 public ArrayArgumentHandler(Object aObj, MemberInfo aInfo, Type aType, int aMin, int aMax)
     : base(aObj, aInfo, aType, aMin, aMax)
 {
     elementType = type.GetElementType();
       listType = typeof(List<>).MakeGenericType(new Type[] { elementType });
       list = listType.GetConstructor(new Type[] { }).Invoke(null);
 }
Example #40
0
            static bool SignalFilter(System.Reflection.MemberInfo m, object filterCriteria)
            {
                string signame = (filterCriteria as string);

                object[] attrs = m.GetCustomAttributes(typeof(GLib.SignalAttribute), false);
                if (attrs.Length > 0)
                {
                    foreach (GLib.SignalAttribute a in attrs)
                    {
                        if (signame == a.CName)
                        {
                            return(true);
                        }
                    }
                    return(false);
                }
                else
                {
                    /* this tries to match the names when no attibutes are present.
                     * It is only a fallback. */
                    signame = signame.ToLower().Replace("_", "");
                    string evname = m.Name.ToLower();
                    return(signame == evname);
                }
            }
Example #41
0
        public override string Serialize(MemberInfo storageType, object value,
            ISerializationOperator serializationOperator) {

            if (value == null) return "null";

            if (_serializer == null) {
                throw new InvalidOperationException("No protobuf-net serializer is loaded");
            }

            UnityObjectReferenceHack.ActiveOperator = serializationOperator;

            using (var stream = new MemoryStream()) {
                _serializer.Serialize(stream, value, new SerializationContext() {
                    Context = serializationOperator
                });

                UnityObjectReferenceHack.ActiveOperator = null;

#if !UNITY_EDITOR && UNITY_WINRT
                return Convert.ToBase64String(stream.ToArray(), 0, (int)stream.Length);
#else
                return Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length);
#endif
            }
        }
Example #42
0
 protected override void CreateRelationship(Type entityType, System.Reflection.MemberInfo member, RelationshipAttribute relationshipAtt, RelationshipCollection relationships)
 {
     if (RelationshipPredicate(member))
     {
         relationships.Add(new Relationship(member));
     }
 }
Example #43
0
        static void Main(string[] args)
        {
            System.Reflection.MemberInfo info = typeof(Entity);
            //显示附加到类 Entity 上的自定义特性
            object[] objs = info.GetCustomAttributes(true);
            foreach (var obj in objs)
            {
                Console.WriteLine(obj);
            }
            Entity entity = new Entity("hhm");
            Type   type   = entity.GetType();

            foreach (MethodInfo m in type.GetMethods())
            {
                foreach (Attribute a in m.GetCustomAttributes(typeof(FildAttribute), false))
                {
                    FildAttribute fild = (FildAttribute)a;
                    if (null != fild)
                    {
                        //fild.F_Name是attribute设置的名字,m.Name是函数的名字
                        Console.WriteLine("fild.F_Name{0},Name{1}", fild.F_Name, m.Name);
                        Console.WriteLine(fild.F_Style);
                    }
                }
            }
            Console.ReadKey();
        }
Example #44
0
 private static Type TypeOfMember(System.Reflection.MemberInfo memberInfo)
 {
     if ((memberInfo.MemberType == MemberTypes.Field) && (memberInfo is FieldInfo))
     {
         return(((FieldInfo)memberInfo).FieldType);
     }
     if ((memberInfo.MemberType == MemberTypes.Property) && (memberInfo is PropertyInfo))
     {
         return(((PropertyInfo)memberInfo).PropertyType);
     }
     if ((memberInfo.MemberType == MemberTypes.Method) && (memberInfo is MethodInfo))
     {
         if (((MethodInfo)memberInfo).ReturnType.FullName != typeof(WhatToDoNext).FullName)
         {
             throw new NotSupportedException("Option method must return '" + typeof(WhatToDoNext).FullName + "'");
         }
         ParameterInfo[] infoArray1 = ((MethodInfo)memberInfo).GetParameters();
         if ((infoArray1 != null) && (infoArray1.Length != 0))
         {
             return(infoArray1[0].ParameterType);
         }
         return(null);
     }
     throw new NotSupportedException("'" + memberInfo.MemberType + "' memberType is not supported");
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="MonoMobile.Views.BindingExpression"/> class.
        /// </summary>
        /// <param name='binding'>
        /// Binding.
        /// </param>
        /// <param name='targetProperty'>
        /// ViewModel.<targetProperty>.
        /// </param>
        /// <param name='target'>
        /// ViewModel to hock into.
        /// </param>
        /// <exception cref='ArgumentNullException'>
        /// Is thrown when an argument passed to a method is invalid because it is <see langword="null" /> .
        /// </exception>
        public BindingExpression(Binding binding, MemberInfo targetProperty, object target)
        {
            if (binding == null)
                throw new ArgumentNullException("binding");

            if (targetProperty == null)
                throw new ArgumentNullException("targetProperty");

            if (target == null)
                throw new ArgumentNullException("target");

            Binding = binding;
            Binding.Target = target;
            TargetProperty = targetProperty;
            if(string.IsNullOrEmpty(binding.TargetPath))
            {
                binding.TargetPath = targetProperty.Name;
            }

            object viewSource = Binding.Source;
            _ViewProperty = viewSource.GetType().GetNestedMember(ref viewSource, Binding.SourcePath, true);
            Binding.ViewSource = viewSource;
            SourceProperty = _ViewProperty;

            var dataContext = viewSource as IDataContext;
            if (dataContext != null && dataContext.DataContext != null)
            {
                var source = dataContext.DataContext;

                SourceProperty = source.GetType().GetNestedMember(ref source, Binding.SourcePath, true);
                Binding.Source = source;
            }
        }
Example #46
0
        public IBinding ToBinding(System.Reflection.MemberInfo mi)
        {
            switch (mi.MemberType)
            {
            case MemberTypes.Method:
            {
                return(new ExternalMethodBinding(this, (System.Reflection.MethodInfo)mi));
            }

            case MemberTypes.Constructor:
            {
                return(new ExternalConstructorBinding(this, (System.Reflection.ConstructorInfo)mi));
            }

            case MemberTypes.Field:
            {
                return(new ExternalFieldBinding(this, (System.Reflection.FieldInfo)mi));
            }

            case MemberTypes.Property:
            {
                return(new ExternalPropertyBinding(this, (System.Reflection.PropertyInfo)mi));
            }

            case MemberTypes.Event:
            {
                return(new ExternalEventBinding(this, (System.Reflection.EventInfo)mi));
            }

            default:
            {
                throw new NotImplementedException(mi.ToString());
            }
            }
        }
Example #47
0
        internal MemberListBinding(MemberInfo member, ReadOnlyCollection<ElementInit> initializers)
#pragma warning disable 618
            : base(MemberBindingType.ListBinding, member)
        {
#pragma warning restore 618
            Initializers = initializers;
        }
Example #48
0
 protected internal static void Log(System.Reflection.MemberInfo callingMethod, string message, params object[] args)
 {
     if (args != null)
     {
         message = String.Format(message, args);
     }
 }
Example #49
0
        private static void ReflectAttr_early()
        {
            Console.WriteLine();
            Console.WriteLine("Early Binding");

            System.Reflection.MemberInfo info = typeof(Crow);
            object[] attributes = info.GetCustomAttributes(true);
            for (int i = 0; i < attributes.Length; i++)
            {
                System.Console.WriteLine(attributes[i]);
            }

            Console.WriteLine();
            Type tat = typeof(Crow);

            if (Attribute.IsDefined(tat, typeof(BirdSpeciesAttribute)))
            {
                var attributeValue = Attribute.GetCustomAttribute(tat, typeof(BirdSpeciesAttribute)) as BirdSpeciesAttribute;
                Console.WriteLine("BirdSpeciesAttribute - {0}\n", attributeValue.Classification);
            }

            if (Attribute.IsDefined(tat, typeof(System.SerializableAttribute)))
            {
                var attributeValue = Attribute.GetCustomAttribute(tat, typeof(System.SerializableAttribute)) as System.SerializableAttribute;
                Console.WriteLine("Serializable - {0}\n", attributeValue.TypeId);
            }
        }
Example #50
0
        private String objToStrimg(object o)
        {
            Type t = o.GetType();

            if (t.IsEnum)
            {
                //System.Reflection.MemberInfo[] mi = t.GetMembers();
                return(Enum.GetName(t, o));
            }
            if (t.IsValueType)
            {
                return(o.ToString());
                //
                //return ValueType GetName(t, o);
            }
            System.Reflection.MemberInfo[] mi = t.GetMembers();
            for (int i = 0; i < mi.Length; i++)
            {
                System.Reflection.MemberInfo m = mi[i];
                if (m.MemberType == MemberTypes.Field)
                {
                    t.GetField(m.Name).GetValue(o);
                }
            }
            return(o.ToString());
        }
		public ComponentAsIdMapper(System.Type componentType, MemberInfo declaringTypeMember, HbmCompositeId id, HbmMapping mapDoc)
		{
			this.id = id;
			this.mapDoc = mapDoc;
			id.@class = componentType.GetShortClassName(mapDoc);
			accessorPropertyMapper = new AccessorPropertyMapper(declaringTypeMember.DeclaringType, declaringTypeMember.Name, x => id.access = x);
		}
Example #52
0
        private ComboBoxWidget CreateComboBox(string caption, object o, System.Reflection.MemberInfo member, System.Object[] attributes)
        {
            Dictionary <string, object> dict = null;

            foreach (var attr in attributes)
            {
                if (attr is StaticListAttribute)
                {
                    dict = (Dictionary <string, object>)GetValue(((StaticListAttribute)attr).dictionaryName, o);
                }
            }

            List <string> entries = new List <string> ();

            foreach (string str in dict.Keys)
            {
                entries.Add(str);
            }

            ComboBoxWidget widget = new ComboBoxWidget(entries.ToArray());

            widget.Label = caption;
            widget.AddEvents((int)Gdk.EventMask.ButtonPressMask);
            widget.Active = entries.IndexOf((string)GetValue(member, o));

            widget.Changed += delegate(object sender, EventArgs e) {
                SetValue(member, o, widget.ActiveText);
            };

            return(widget);
        }
Example #53
0
        internal static TypeAttributeMapping FromMember(TypeMapping declaringType, MemberInfo memberInfo)
        {
            string name = null;
            SqlType sqlType = GetSqlType(memberInfo);
            int size = -1;
            int scale = -1;
            bool nullable = true;

            object[] attrs = memberInfo.GetCustomAttributes(true);
            for (int i = 0; i < attrs.Length; i++) {
                object attr = attrs[i];

                if (attr is ColumnAttribute) {
                    ColumnAttribute columnAttr = (ColumnAttribute)attr;
                    name = columnAttr.ColumnName;
                    sqlType = columnAttr.SqlType;
                    size = columnAttr.Size;
                    scale = columnAttr.Scale;
                } else if (attr is NotNullAttribute) {
                    nullable = false;
                }
            }

            TType type = GetTType(sqlType, size, scale);

            return new TypeAttributeMapping(declaringType, name, type, nullable);
        }
Example #54
0
 private void IncludeTypes(MemberInfo memberInfo, RecursionLimiter limiter)
 {
     foreach (Attribute attr in memberInfo.GetCustomAttributes(typeof(SoapIncludeAttribute), false))
     {
         IncludeType(((SoapIncludeAttribute)attr).Type, limiter);
     }
 }
Example #55
0
 //.........................................................................
 public CLSMethod(string name, Type type, MemberInfo[] methods, bool isStatic)
 {
     InnerIsStatic = isStatic;
     InnerType = type;
     InnerMethInfos = methods;
     InnerName = name;
 }
		public static object [] GetObjectData (object obj, MemberInfo [] members)
		{
			if (obj == null)
				throw new ArgumentNullException ("obj");

			if (members == null)
				throw new ArgumentNullException ("members");

			int n = members.Length;
			object [] result = new object [n];
			for (int i = 0; i < n; i++) {
				MemberInfo member = members [i];
				if (member == null)
					throw new ArgumentNullException (String.Format ("members[{0}]", i));

				if (member.MemberType != MemberTypes.Field)
					throw new SerializationException (
							String.Format ("members [{0}] is not a field.", i));

				FieldInfo fi = member as FieldInfo; // members must be fields
				result [i] = fi.GetValue (obj);
			}

			return result;
		}
        public bool IsOverriddenMember(MemberInfo memberInfo)
        {
            ArgumentUtility.CheckNotNull ("memberInfo", memberInfo);

              var methodInfo = memberInfo as MethodInfo;
              if (methodInfo != null)
            return IsOverriddenMethod (methodInfo);

              var propertyInfo = memberInfo as PropertyInfo;
              if (propertyInfo != null)
              {
            return IsOverriddenMethod (propertyInfo.GetGetMethod (true))
               || IsOverriddenMethod (propertyInfo.GetSetMethod (true));
              }

              var eventInfo = memberInfo as EventInfo;
              if (eventInfo != null)
              {
            return IsOverriddenMethod (eventInfo.GetAddMethod (true))
               || IsOverriddenMethod (eventInfo.GetRaiseMethod (true))
               || IsOverriddenMethod (eventInfo.GetRemoveMethod (true));
              }

              return false;
        }
Example #58
0
 public string AssignmentBodyCode(MemberInfo idMember)
 {
     return $@"
     document.{idMember.Name} = ""newId""; //your id generation algorithm here
     assigned = true;
     ";
 }
        /// <summary>
        /// Initializes a new instance of the MemberInfoData class 
        /// with the provided MemberInfo object's data.
        /// </summary>
        /// <param name="mi">The member info object.</param>
        public MemberInfoData(MemberInfo mi)
        {
            MemberInfo = mi;
            Name = mi.Name;

            if (mi is PropertyInfo)
            {
                IconName = "Property.png";
            }

            MethodInfo methodInfo = mi as MethodInfo;
            if (methodInfo != null)
            {
                IconName = methodInfo.IsStatic ? "Static.png" : "Method.png";
            }

            if (mi is EventInfo)
            {
                IconName = "Event.png";
            }

            FieldInfo field = mi as FieldInfo;
            if (field != null)
            {
                IconName = "Static.png";
            }
        }
        public static Type GetDataType(System.Reflection.MemberInfo memberInfo, Func <System.Reflection.MemberInfo, Type> fallbackType)
        {
            var field = memberInfo as System.Reflection.FieldInfo;

            if (field != null)
            {
                return(field.FieldType);
            }

            var property = memberInfo as System.Reflection.PropertyInfo;

            if (property != null)
            {
                return(property.PropertyType);
            }

            var method = memberInfo as System.Reflection.MethodInfo;

            if (method != null)
            {
                return(method.ReturnType);
            }

            if (fallbackType == null)
            {
                throw new InvalidOperationException("Member is not a field, property, method nor does it have a fallback type");
            }

            return(fallbackType(memberInfo));
        }