Esempio n. 1
0
        public static bool ExtendsType(MethodInfo method, Type type)
        {
            var ext = method.GetCustomAttributes(typeof(ExtendsAttribute), true);

            if (ext.Length != 0 && ((ExtendsAttribute)ext[0]).Type == type)
            {
                return true;
            }

            if (method.GetCustomAttributes(typeof(ExtensionAttribute), true).Length == 0)
            {
                return false;
            }

            var pars = method.GetParameters();
            if (pars.Length == 0)
            {
                return false;
            }

            if (type != pars[0].ParameterType)
            {
                // maybe test for subclass
                return false;
            }

            return true;
        }
        public IEnumerable<ExecutionStep> Scan(object testObject, MethodInfo candidateMethod)
        {
            var executableAttribute = (ExecutableAttribute)candidateMethod.GetCustomAttributes(typeof(ExecutableAttribute), false).FirstOrDefault();
            if(executableAttribute == null)
                yield break;

            string stepTitle = executableAttribute.StepTitle;
            if(string.IsNullOrEmpty(stepTitle))
                stepTitle = NetToString.Convert(candidateMethod.Name);

            var stepAsserts = IsAssertingByAttribute(candidateMethod);

            var runStepWithArgsAttributes = (RunStepWithArgsAttribute[])candidateMethod.GetCustomAttributes(typeof(RunStepWithArgsAttribute), false);
            if (runStepWithArgsAttributes.Length == 0)
            {
                yield return new ExecutionStep(GetStepAction(candidateMethod), stepTitle, stepAsserts, executableAttribute.ExecutionOrder, true);
            }

            foreach (var runStepWithArgsAttribute in runStepWithArgsAttributes)
            {
                var inputArguments = runStepWithArgsAttribute.InputArguments;
                var flatInput = inputArguments.FlattenArrays();
                var stringFlatInputs = flatInput.Select(i => i.ToString()).ToArray();
                var methodName = stepTitle + " " + string.Join(", ", stringFlatInputs);

                if (!string.IsNullOrEmpty(runStepWithArgsAttribute.StepTextTemplate))
                    methodName = string.Format(runStepWithArgsAttribute.StepTextTemplate, flatInput);
                else if (!string.IsNullOrEmpty(executableAttribute.StepTitle))
                    methodName = string.Format(executableAttribute.StepTitle, flatInput);

                yield return new ExecutionStep(GetStepAction(candidateMethod, inputArguments), methodName, stepAsserts, executableAttribute.ExecutionOrder, true);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Returns a ClientMethod instance to get the name of the class and method name on the client-side JavaScript.
        /// </summary>
        /// <param name="method">The MethodInfo.</param>
        /// <returns>
        /// Returns the ClientMethod info, if it is not a AjaxMethod it will return null.
        /// </returns>
		public static ClientMethod FromMethodInfo(MethodInfo method)
		{
			if(method.GetCustomAttributes(typeof(AjaxPro.AjaxMethodAttribute), true).Length == 0)
				return null;

			AjaxPro.AjaxNamespaceAttribute[] classns = (AjaxPro.AjaxNamespaceAttribute[])method.ReflectedType.GetCustomAttributes(typeof(AjaxPro.AjaxNamespaceAttribute), true);
			AjaxPro.AjaxNamespaceAttribute[] methodns = (AjaxPro.AjaxNamespaceAttribute[])method.GetCustomAttributes(typeof(AjaxPro.AjaxNamespaceAttribute), true);

			ClientMethod cm = new ClientMethod();

			if (classns.Length > 0)
				cm.ClassName = classns[0].ClientNamespace;
			else
			{
				if (Utility.Settings.UseSimpleObjectNaming)
					cm.ClassName = method.ReflectedType.Name;
				else
					cm.ClassName = method.ReflectedType.FullName;
			}

			if(methodns.Length > 0)
				cm.MethodName += methodns[0].ClientNamespace;
			else
				cm.MethodName += method.Name;

			return cm;
		}
Esempio n. 4
0
        public void PublicMethod_ThatReturnsReferenceType_MustBeTaggedWithNotNullOrCanBeNullAttributes(MethodInfo method)
        {
            bool hasNotNullAttribute = method.GetCustomAttributes(typeof(NotNullAttribute), true).Any();
            bool hasCanBeNullAttribute = method.GetCustomAttributes(typeof(CanBeNullAttribute), true).Any();

            Assume.That(method.DeclaringType != null);
            Assert.That(hasNotNullAttribute || hasCanBeNullAttribute, "Method " + method.Name + " of type " + method.DeclaringType.Name + " must be tagged with [NotNull] or [CanBeNull]");
        }
Esempio n. 5
0
 private static string[] GetMethods(MethodInfo methodInfo)
 {
     var list = new List<string>();
     list.AddRange(from customAttribute in methodInfo.GetCustomAttributes<HttpGetAttribute>() from httpMethod in customAttribute.HttpMethods select httpMethod.Method);
     list.AddRange(from customAttribute in methodInfo.GetCustomAttributes<HttpPostAttribute>() from httpMethod in customAttribute.HttpMethods select httpMethod.Method);
     list.AddRange(from customAttribute in methodInfo.GetCustomAttributes<HttpPutAttribute>() from httpMethod in customAttribute.HttpMethods select httpMethod.Method);
     list.AddRange(from customAttribute in methodInfo.GetCustomAttributes<HttpDeleteAttribute>() from httpMethod in customAttribute.HttpMethods select httpMethod.Method);
     return list.Distinct().ToArray();
 }
Esempio n. 6
0
        public void PrintUsage()
        {
            foreach (var kv in HandlerMap)
            {
                Console.WriteLine("/Function=" + kv.Key);
                Action <AppOptionValues> Handler       = kv.Value;
                DescriptionAttribute[]   customAttrs   = (DescriptionAttribute[])Handler.Method.GetCustomAttributes(typeof(DescriptionAttribute), true);
                ArgumentDescAttribute[]  customArgDesc = (ArgumentDescAttribute[])Handler.Method.GetCustomAttributes(typeof(ArgumentDescAttribute), true);


                if (customAttrs.Length == 0)
                {
                    Object       handlerTarget             = Handler.Target;
                    Type         handlerTargetType         = handlerTarget.GetType();
                    FieldInfo    handlerTargetMethod       = handlerTargetType.GetField("handler", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.Instance);
                    Object       handlerTargetHandlerValue = handlerTargetMethod.GetValue(handlerTarget);
                    PropertyInfo prop = handlerTargetHandlerValue.GetType().GetProperty("Method");


                    if (prop != null)
                    {
                        System.Reflection.MethodInfo trueMethod = (System.Reflection.MethodInfo)prop.GetValue(handlerTargetHandlerValue);
                        customAttrs   = (DescriptionAttribute[])trueMethod.GetCustomAttributes(typeof(DescriptionAttribute), true);
                        customArgDesc = (ArgumentDescAttribute[])trueMethod.GetCustomAttributes(typeof(ArgumentDescAttribute), true);
                    }
                }

                if (customAttrs.Length > 0)
                {
                    foreach (DescriptionAttribute desc in customAttrs)
                    {
                        Console.WriteLine("  " + desc.Description);
                    }
                }
                else
                {
                    customAttrs = (DescriptionAttribute[])Handler.Method.GetCustomAttributes(typeof(DescriptionAttribute), true);
                }

                if (customArgDesc.Length > 0)
                {
                    foreach (ArgumentDescAttribute desc in customArgDesc)
                    {
                        foreach (String descStr in desc.Description)
                        {
                            Console.WriteLine("    " + descStr);
                        }
                    }
                }
                Console.WriteLine();
            }
        }
 public ParameterizedTestMethod(TestFixture testFixture, MethodInfo methodInfo)
    : base(testFixture, methodInfo) {
    foreach(DataRow dataRow in methodInfo.GetCustomAttributes(typeof(DataRow), true)) {
       _dataSource.Add(dataRow);
    }
    if(_dataSource.Count == 0) {
       object[] attrs = methodInfo.GetCustomAttributes(typeof(DataSourceAttribute), true);
       if( attrs.Length > 0 ) {
          _dataSource.Add(attrs[0] as DataSourceAttribute);
       }
    }
    _expectedParameterNum = MethodInfo.GetParameters().Length;
 }
Esempio n. 8
0
        public ActionMethod(MethodInfo methodInfo)
        {
            _methodInfo = methodInfo;

            _filterAttributes = (ActionFilterAttribute[]) methodInfo.GetCustomAttributes(typeof(ActionFilterAttribute), false);

            OrderedAttribute.Sort(_filterAttributes);

            if (_methodInfo.IsDefined(typeof(LayoutAttribute), false))
                _defaultLayoutName = ((LayoutAttribute)_methodInfo.GetCustomAttributes(typeof(LayoutAttribute), false)[0]).LayoutName ?? "";

            if (_methodInfo.IsDefined(typeof(ViewAttribute), false))
                _defaultViewName = ((ViewAttribute)_methodInfo.GetCustomAttributes(typeof(ViewAttribute), false)[0]).ViewName ?? "";
        }
 public static bool IsWebMethod(MethodInfo method)
 {
     object[] customAttributes = method.GetCustomAttributes(typeof(SoapRpcMethodAttribute), true);
     if ((customAttributes != null) && (customAttributes.Length > 0))
     {
         return true;
     }
     customAttributes = method.GetCustomAttributes(typeof(SoapDocumentMethodAttribute), true);
     if ((customAttributes != null) && (customAttributes.Length > 0))
     {
         return true;
     }
     customAttributes = method.GetCustomAttributes(typeof(HttpMethodAttribute), true);
     return ((customAttributes != null) && (customAttributes.Length > 0));
 }
Esempio n. 10
0
        private bool ProceedValidatorAttribute(ICommand command, System.Reflection.MethodInfo methodHandlerAsync)
        {
            var customAttributes = methodHandlerAsync.GetCustomAttributes(false)
                                   .Where(x => x is EnableValidatorAttribute)
                                   .Select(x => (EnableValidatorAttribute)x);

            if (!customAttributes.Any())
            {
                foreach (var validator in customAttributes)
                {
                    object fluentValidation = serviceProvider.GetService(validator.Type);

                    ValidationResult validationResult = (ValidationResult)fluentValidation
                                                        .GetType()
                                                        .GetMethod("Validate", new Type[] { command.GetType() })
                                                        .Invoke(fluentValidation, new[] { command });

                    if (!validationResult.IsValid)
                    {
                        // log_error_here
                        return(false);
                    }
                }
            }

            return(true);
        }
Esempio n. 11
0
 public static bool IsAsyncOperation(MethodInfo method)
 {
     var name = method.ReturnType.FullName;
     if (name == null) return false;
     return name.StartsWith(TaskTypeName) ||
            method.GetCustomAttributes(false).Any(attr => AsyncAttributeTypeName == attr.GetType().FullName);
 }
        private static IEnumerable<VariantAttribute> GetCombinations(MethodInfo method)
        {
            var methodVariants
                = method
                    .GetCustomAttributes(typeof(VariantAttribute), true)
                    .Cast<VariantAttribute>()
                    .ToList();

            if (methodVariants.Any())
            {
                return methodVariants;
            }

            var typeVariants
                = method.DeclaringType
                        .GetCustomAttributes(typeof(VariantAttribute), true)
                        .Cast<VariantAttribute>()
                        .ToList();

            if (typeVariants.Any())
            {
                return typeVariants;
            }

            return new[] { new VariantAttribute(RepositoryProvider.EntityFramework) };
        }
Esempio n. 13
0
        private TestType GetTestType(MethodInfo testMethod)
        {
            var uniqueAttributeTypes = new HashSet<string>();
            var allAttributes = testMethod.GetCustomAttributes();
            foreach (var attr in allAttributes)
            {
                uniqueAttributeTypes.Add(attr.GetType().Name);
            }

            if (uniqueAttributeTypes.Contains(typeof (TestCaseAttribute).Name))
            {
                if (uniqueAttributeTypes.Contains(typeof (ShouldThrowAttribute).Name))
                {
                    return TestType.TestCasesShouldThrow;
                }
                
                return TestType.TestCasesNormal;
            }

            if (uniqueAttributeTypes.Contains(typeof (ShouldThrowAttribute).Name))
            {
                return TestType.ShouldThrow;
            }

            return TestType.Normal;
        }
Esempio n. 14
0
 /// <summary>
 /// Extracts the RestAttribute from a method's attributes
 /// </summary>
 /// <param name="method">The method to be inspected</param>
 /// <returns>The applied RestAttribute or a default RestAttribute.</returns>
 public static RestAttribute GetRestAttribute(MethodInfo method)
 {
     var customAttributes = method.GetCustomAttributes(typeof(RestAttribute), true);
     if (customAttributes.Length <= 0) return new RestAttribute();
     var restAttribute = customAttributes[0] as RestAttribute;
     return restAttribute ?? new RestAttribute();
 }
Esempio n. 15
0
        public IHqlGeneratorForMethod GetMethodGenerator(MethodInfo method)
        {
            IHqlGeneratorForMethod methodGenerator;

            if (method.IsGenericMethod)
            {
                method = method.GetGenericMethodDefinition();
            }

            if (_registeredMethods.TryGetValue(method, out methodGenerator))
            {
                return methodGenerator;
            }

            // No method generator registered.  Look to see if it's a standard LinqExtensionMethod
            var attr = method.GetCustomAttributes(typeof (LinqExtensionMethodAttribute), false);
            if (attr.Length == 1)
            {
                // It is
                // TODO - cache this?  Is it worth it?
                return new HqlGeneratorForExtensionMethod((LinqExtensionMethodAttribute) attr[0], method);
            }

            // Not that either.  Let's query each type generator to see if it can handle it
            foreach (var typeGenerator in _typeGenerators)
            {
                if (typeGenerator.SupportsMethod(method))
                {
                    return typeGenerator.GetMethodGenerator(method);
                }
            }

            throw new NotSupportedException(method.ToString());
        }
        private static string GetReasonForWhyMethodCanNotBeIntercepted(MethodInfo method)
        {
            if (method.IsFinal)
            {
                return "Sealed methods can not be intercepted.";
            }

            if (method.IsStatic)
            {
                if (method.GetCustomAttributes(typeof(System.Runtime.CompilerServices.ExtensionAttribute), false).Any())
                {
                    return "Extension methods can not be intercepted since they're static.";
                }
                else
                {
                    return "Static methods can not be intercepted.";
                }
            }

            if (!method.IsVirtual)
            {
                return "Non virtual methods can not be intercepted.";
            }

            return null;
        }
Esempio n. 17
0
        TestResultBitmap runMethodTest(object instance, MethodInfo method)
        {
            if (method.IsGenericMethod)
                throw new Exception("{0}: is not allowed to be generic".format(method));

            var parameters = method.GetParameters();
            if (parameters.Length != 1)
                throw new Exception("{0}: expect one parameter".format(method));

            var firstParameter = parameters[0];
            if (firstParameter.ParameterType != typeof(IDrawingContext))
                throw new Exception("{0}: expect IDrawingContext as first and only parameter");

            var attribute = (BitmapDrawingTestAttribute)method.GetCustomAttributes(typeof (BitmapDrawingTestAttribute), false)[0];

            using (var context = new BitmapDrawingContext(attribute.Width, attribute.Height))
            {
                IDrawingContext drawingContext;
                using (context.beginDraw(out drawingContext))
                {
                    method.Invoke(instance, new object[] { drawingContext });
                }

                return new TestResultBitmap(attribute.Width, attribute.Height, context.extractRawBitmap());
            }
        }
        public bool MustAuthenticate(Type type, MethodInfo method)
        {
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");

            return method.GetCustomAttributes(typeof(AuthenticateAttribute), false).Any();
        }
 private void RemoveActionImplementation(IAuthorizationService authService, MethodInfo method)
 {
     foreach (CommandHandlerAttribute attr in method.GetCustomAttributes(typeof(CommandHandlerAttribute), true))
     {
         //authService.UnRegisterCommand(attr.CommandName, GetAuthorizeResourcePath(method));
     }
 }
Esempio n. 20
0
        public bool HasRights(object t, string command)
        {
            if (t.GetType().IsClass)//Before check no permission class
            {
                object[] laClassAttributes = t.GetType().GetCustomAttributes(typeof(RightsAccessAttribute), false);
                if (laClassAttributes.Length > 0)
                {
                    return(CheckAttribute(t, laClassAttributes));
                }
            }

            //After check no permission method
            System.Reflection.MethodInfo met = t.GetType().GetMethod(command);
            if (met != null)
            {
                object[] laMethodAttributes = met.GetCustomAttributes(typeof(RightsAccessAttribute), false);
                if (laMethodAttributes.Length > 0)
                {
                    return(CheckAttribute(t, laMethodAttributes));
                }
                //ui no need check permission and not attribute login
                if (HasUi(t.ToString()))
                {
                    return(true);
                }
            }
            return(false);
        }
Esempio n. 21
0
        private void ProcessSwaggerTagsAttribute(SwaggerDocument document, SwaggerOperationDescription operationDescription, MethodInfo methodInfo)
        {
            dynamic tagsAttribute = methodInfo
                .GetCustomAttributes()
                .SingleOrDefault(a => a.GetType().Name == "SwaggerTagsAttribute");

            if (tagsAttribute != null)
            {
                var tags = ((string[])tagsAttribute.Tags).ToList();
                foreach (var tag in tags)
                {
                    if (operationDescription.Operation.Tags.All(t => t != tag))
                        operationDescription.Operation.Tags.Add(tag);

                    if (ObjectExtensions.HasProperty(tagsAttribute, "AddToDocument") && tagsAttribute.AddToDocument)
                    {
                        if (document.Tags == null)
                            document.Tags = new List<SwaggerTag>();

                        if (document.Tags.All(t => t.Name != tag))
                            document.Tags.Add(new SwaggerTag { Name = tag });
                    }
                }
            }
        }
 internal static WebMethodAttribute GetAttribute(MethodInfo implementation, MethodInfo declaration)
 {
     WebMethodAttribute attribute = null;
     WebMethodAttribute attribute2 = null;
     object[] customAttributes;
     if (declaration != null)
     {
         customAttributes = declaration.GetCustomAttributes(typeof(WebMethodAttribute), false);
         if (customAttributes.Length > 0)
         {
             attribute = (WebMethodAttribute) customAttributes[0];
         }
     }
     customAttributes = implementation.GetCustomAttributes(typeof(WebMethodAttribute), false);
     if (customAttributes.Length > 0)
     {
         attribute2 = (WebMethodAttribute) customAttributes[0];
     }
     if (attribute == null)
     {
         return attribute2;
     }
     if (attribute2 == null)
     {
         return attribute;
     }
     if (attribute2.MessageNameSpecified)
     {
         throw new InvalidOperationException(Res.GetString("ContractOverride", new object[] { implementation.Name, implementation.DeclaringType.FullName, declaration.DeclaringType.FullName, declaration.ToString(), "WebMethod.MessageName" }));
     }
     return new WebMethodAttribute(attribute2.EnableSessionSpecified ? attribute2.EnableSession : attribute.EnableSession) { TransactionOption = attribute2.TransactionOptionSpecified ? attribute2.TransactionOption : attribute.TransactionOption, CacheDuration = attribute2.CacheDurationSpecified ? attribute2.CacheDuration : attribute.CacheDuration, BufferResponse = attribute2.BufferResponseSpecified ? attribute2.BufferResponse : attribute.BufferResponse, Description = attribute2.DescriptionSpecified ? attribute2.Description : attribute.Description };
 }
Esempio n. 23
0
		private void Register(object commandHandler, MethodInfo handlerMethod)
		{
			foreach (CommandAttribute attr in handlerMethod.GetCustomAttributes<CommandAttribute>())
			{
				Subscribe(commandHandler, handlerMethod, attr);
			}
		}
 private Attribute GetAsyncStateMachineAttribute(MethodInfo method)
 {
     foreach (Attribute attribute in method.GetCustomAttributes(false) )
         if (attribute.GetType().FullName == "System.Runtime.CompilerServices.AsyncStateMachineAttribute")
             return attribute;
     return null;
 }
Esempio n. 25
0
        public string GetClientMethodCode(MethodInfo method, string url)
        {
            var model = new ClientMethodModel();

            var parameterInfos = method.GetParameters();
            var inputParameters = parameterInfos.Select(p => string.Format("{0}: {1}", p.Name, TypeMapper.GetTypeScriptType(p.ParameterType)))
                    .ToList();

            model.Traditional = parameterInfos.Any(p => p.ParameterType.IsArray);

            var returnType = method.ReturnType;
            if (returnType.Name != "Void")
            {
                var onSucces = "callback: (data: " + TypeMapper.GetTypeScriptType(returnType) + ") => any";
                inputParameters.Add(onSucces);
                model.OnSucces = "callback";
            }

            //hacky
            var isPost = method.GetCustomAttributes(typeof(HttpPostAttribute), true).Any() || returnType.IsJsonResult() || returnType == typeof(JsonResult);
            model.AjaxMethod = isPost ? "POST" : "";

            var allParameters = string.Join(", ", inputParameters);
            model.Signature = method.Name + "(" + allParameters + ")";

            model.Url = url;
            var inputJsonTuples = method.GetParameters().Select(p => string.Format("{0}: {0}", p.Name));
            model.Data = "{ " + string.Join(", ", inputJsonTuples) + " }";

            var template = GetTemplate("ClientMethod");

            return RemoveEmptyLines(Razor.Parse(template, model));//.Split("\r\n".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
        }
Esempio n. 26
0
        private bool ProceedPermisisonAttribute(System.Reflection.MethodInfo methodHandlerAsync)
        {
            var customAttributes = methodHandlerAsync.GetCustomAttributes(false)
                                   .Where(x => x is HasPermissionAttribute)
                                   .Select(x => (HasPermissionAttribute)x);

            if (!customAttributes.Any())
            {
                return(true);
            }

            foreach (var hasPermisison in customAttributes)
            {
                var permissionName = hasPermisison.PermissionName;

                var signInUser = (SignInUser)serviceProvider.GetService(typeof(SignInUser));
                if (!signInUser.Permissions.Any())
                {
                    return(false);
                }

                if (signInUser.Permissions.Contains(permissionName))
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 27
0
    static void Main(string[] args)
    {
        Type widgetType = typeof(Widget);

        //Gets every HelpAttribute defined for the Widget type
        object[] widgetClassAttributes = widgetType.GetCustomAttributes(typeof(HelpAttribute), false);

        if (widgetClassAttributes.Length > 0)
        {
            HelpAttribute attr = (HelpAttribute)widgetClassAttributes[0];
            Console.WriteLine($"Widget class help URL : {attr.Url} - Related topic : {attr.Topic}");
        }



        System.Reflection.MethodInfo displayMethod = widgetType.GetMethod(nameof(Widget.Display));
        //Gets every HelpAttribute defined for the Widget.Display method
        object[] displayMethodAttributes = displayMethod.GetCustomAttributes(typeof(HelpAttribute), false);

        if (displayMethodAttributes.Length > 0)
        {
            HelpAttribute attr = (HelpAttribute)displayMethodAttributes[0];
            Console.WriteLine($"Display method help URL : {attr.Url} - Related topic : {attr.Topic}");
        }

        Console.ReadLine();
    }
        private static IEnumerable<VariantAttribute> GetCombinations(MethodInfo method)
        {
            var methodVariants
                = method
                    .GetCustomAttributes(typeof(VariantAttribute), true)
                    .Cast<VariantAttribute>()
                    .ToList();

            if (methodVariants.Any())
            {
                return methodVariants;
            }

            var typeVariants
                = method.DeclaringType
                    .GetCustomAttributes(typeof(VariantAttribute), true)
                    .Cast<VariantAttribute>()
                    .ToList();

            if (typeVariants.Any())
            {
                return typeVariants;
            }

            return new[] { new VariantAttribute(DatabaseProvider.SqlClient, ProgrammingLanguage.CSharp) };
        }
Esempio n. 29
0
    static void Main()
    {
        double[]   a       = { 0.0, 0.5, 1.0 };
        double[]   squares = Apply(a, Square);
        double[]   sines   = Apply(a, Math.Sin);
        Multiplier m       = new Multiplier(2.0);

        double[] doubles    = Apply(a, m.Multiply);
        Type     widgetType = typeof(Widget);

        //Gets every HelpAttribute defined for the Widget type
        object[] widgetClassAttributes = widgetType.GetCustomAttributes(typeof(HelpAttribute), false);

        if (widgetClassAttributes.Length > 0)
        {
            HelpAttribute attr = (HelpAttribute)widgetClassAttributes[0];
            Console.WriteLine($"Widget class help URL : {attr.Url} - Related topic : {attr.Topic}");
        }

        System.Reflection.MethodInfo displayMethod = widgetType.GetMethod(nameof(Widget.Display));

        //Gets every HelpAttribute defined for the Widget.Display method
        object[] displayMethodAttributes = displayMethod.GetCustomAttributes(typeof(HelpAttribute), false);

        if (displayMethodAttributes.Length > 0)
        {
            HelpAttribute attr = (HelpAttribute)displayMethodAttributes[0];
            Console.WriteLine($"Display method help URL : {attr.Url} - Related topic : {attr.Topic}");
        }

        Console.ReadLine();

        Console.Read();
    }
Esempio n. 30
0
        IInterceptor[] IInterceptorSelector.SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
        {
            if (interceptors.Length == 0)
                return interceptors;

            var markers = new List<MarkerBaseAttribute>();
            if (type != null)
                markers.AddRange(type.GetCustomAttributes(typeof(MarkerBaseAttribute), true).Cast<MarkerBaseAttribute>());

            if (method != null)
                markers.AddRange(method.GetCustomAttributes(typeof(MarkerBaseAttribute), true).Cast<MarkerBaseAttribute>());

            if (markers.Count == 0) // no marker attributes found, no ordering required
                return interceptors;

            markers.Sort((a, b) => a.Order.CompareTo(b.Order));

            var sorted = new List<IInterceptor>();
            for (int i = 0; i < markers.Count; ++i)
            {
                var providers = interceptors.OfType<IInterceptorMarkerProvider>();
                var markerType = markers[i].GetType();
                var matchingInterceptor = providers.FirstOrDefault(x => x.MarkerType == markerType) as IInterceptor;
                if (matchingInterceptor != null)
                    sorted.Add(matchingInterceptor);
            }
            return sorted.ToArray();
        }
Esempio n. 31
0
 public override IEnumerable <ITestCase> CreateTests(IFixture fixture, System.Reflection.MethodInfo method)
 {
     foreach (RowAttribute rowAttribute in method.GetCustomAttributes(typeof(RowAttribute), true))
     {
         yield return(new RowTestCase(fixture.Name, method, rowAttribute));
     }
 }
Esempio n. 32
0
 /// <summary>
 /// 添加solr
 /// </summary>
 /// <param name="mi"></param>
 /// <param name="prams"></param>
 public static void AddHumorLucene(MethodInfo mi, object[] prams)
 {
     object[] attrs = mi.GetCustomAttributes(typeof(Attr_AddLuceneAttribute), false);
     foreach (Attr_AddLuceneAttribute attr in attrs)
     {
         if (attr == null)
         {
             continue;
         }
         int index = attr.PramIndex;
         if (index >= 0 && index < prams.Length)
         {
             //直接是传过来参数
             if (string.IsNullOrWhiteSpace(attr.Key))
             {
                 string id = prams[index].ToString();
                 srv_HumorLucene.AddLuceneHumor(Convert.ToInt32(id));
             }
             else
             {
                 Type type = attr.Key.GetType();
                 PropertyInfo pi = type.GetProperty(attr.Key);
                 var id = pi.GetValue(prams[index], null);
                 srv_HumorLucene.AddLuceneHumor(Convert.ToInt32(id));
             }
         }
     }
 }
Esempio n. 33
0
 private static void RegisterMethod(MethodInfo method)
 {
     foreach (ScriptableAttribute attribute in method.GetCustomAttributes(typeof(ScriptableAttribute),false))
     {
         globalmethods[attribute.Name ?? method.Name] = method;
     }
 }
Esempio n. 34
0
 public override IList<string> GetCategories(MethodInfo method)
 {
     return (method.GetCustomAttributes(typeof(TraitAttribute), true)
               .OfType<TraitAttribute>()
               .Where(trait => trait.Name == "Category")
               .Select(trait => trait.Value)).ToList();
 }
		/// <summary>
		/// Implementors should collect the transformfilter information
		/// and return descriptors instances, or an empty array if none
		/// was found.
		/// </summary>
		/// <param name="methodInfo">The action (MethodInfo)</param>
		/// <returns>
		/// An array of <see cref="TransformFilterDescriptor"/>
		/// </returns>
		public TransformFilterDescriptor[] CollectFilters(MethodInfo methodInfo)
		{
			if (logger.IsDebugEnabled)
			{
				logger.DebugFormat("Collecting transform filters for {0}", methodInfo.Name);
			}

			var attributes = methodInfo.GetCustomAttributes(typeof(ITransformFilterDescriptorBuilder), true);

			var filters = new List<TransformFilterDescriptor>();

			foreach(ITransformFilterDescriptorBuilder builder in attributes)
			{
				var descs = builder.BuildTransformFilterDescriptors();

				if (logger.IsDebugEnabled)
				{
					foreach(var desc in descs)
					{
						logger.DebugFormat("Collected transform filter {0} to execute in order {1}", desc.TransformFilterType, desc.ExecutionOrder);
					}
				}

				filters.AddRange(descs);
			}

			return filters.ToArray();
		}
        private List<MethodBoundaryAttribute> GetAttributes(MethodInfo methodInfo)
        {
            List<MethodBoundaryAttribute> attributes = new List<MethodBoundaryAttribute>();

            //Method level attributes
            MethodBoundaryAttribute[] methodAttributes = (MethodBoundaryAttribute[])methodInfo.GetCustomAttributes(typeof(MethodBoundaryAttribute), false);

            //Class level attributes
            MethodBoundaryAttribute[] classAttributes = (MethodBoundaryAttribute[])methodInfo.ReflectedType.GetCustomAttributes(typeof(MethodBoundaryAttribute), false);

            //add method level
            attributes.AddRange(methodAttributes);

            //add class attribute if not exist in method
            foreach (MethodBoundaryAttribute classAttr in classAttributes)
            {
                bool exist = false;
                foreach (MethodBoundaryAttribute methodAttr in methodAttributes)
                {
                    if (classAttr.TypeId == methodAttr.TypeId)
                        exist = true;
                }
                if (!exist)
                    attributes.Add(classAttr);
            }

            return attributes;
        }
        public IEnumerable<Step> Scan(ITestContext testContext, MethodInfo method, Example example)
        {
            var executableAttribute = (ExecutableAttribute)method.GetCustomAttributes(typeof(ExecutableAttribute), false).FirstOrDefault();
            if (executableAttribute == null)
                yield break;

            string stepTitle = executableAttribute.StepTitle;
            if (string.IsNullOrEmpty(stepTitle))
                stepTitle = Configurator.Scanners.Humanize(method.Name);

            var stepAsserts = IsAssertingByAttribute(method);
            var methodParameters = method.GetParameters();

            var inputs = new List<object>();
            var inputPlaceholders = Regex.Matches(stepTitle, " <(\\w+)> ");

            for (int i = 0; i < inputPlaceholders.Count; i++)
            {
                var placeholder = inputPlaceholders[i].Groups[1].Value;

                for (int j = 0; j < example.Headers.Length; j++)
                {
                    if (example.Values.ElementAt(j).MatchesName(placeholder))
                    {
                        inputs.Add(example.GetValueOf(j, methodParameters[inputs.Count].ParameterType));
                        break;
                    }
                }
            }

            var stepAction = StepActionFactory.GetStepAction(method, inputs.ToArray());
            yield return new Step(stepAction, new StepTitle(stepTitle), stepAsserts, executableAttribute.ExecutionOrder, true, new List<StepArgument>());
        }
Esempio n. 38
0
 /// <summary>
 /// Check to make sure there is a method that has the attribute [EventHandler]
 /// </summary>
 /// <param name="mi"></param>
 /// <returns></returns>
 private bool containsHandler(System.Reflection.MethodInfo mi)
 {
     foreach (object o in mi.GetCustomAttributes(false))
     {
         if (o.GetType() == typeof(EventHandlerAttribute))
         {
             return(true);
         }
     }
     return(false);
 }
Esempio n. 39
0
            /// <summary>
            /// 获取方法特性
            /// </summary>
            /// <param name="method">The method.</param>
            /// <returns></returns>
            public static Attribute[] GetAttributes(System.Reflection.MethodInfo method)
            {
                var list       = method.GetCustomAttributes(true);
                var attributes = new List <Attribute>(list.Length);

                foreach (var i in list)
                {
                    attributes.Add((Attribute)i);
                }

                return(attributes.ToArray());
            }
Esempio n. 40
0
 /// <summary>
 /// 根据方法名获取描述
 /// </summary>
 /// <param name="method">方法名</param>
 /// <param name="t">类型</param>
 /// <param name="types">参数类型</param>
 /// <returns></returns>
 public static string GetDescriptionByMethod(this string method, Type t)
 {
     System.Reflection.MethodInfo fi = t.GetMethod(method);
     if (fi != null)
     {
         DescriptionAttribute[] attributes =
             (DescriptionAttribute[])fi.GetCustomAttributes(
                 typeof(DescriptionAttribute), false);
         return(attributes.Length > 0 ? attributes[0].Description : "");
     }
     return("");
 }
Esempio n. 41
0
            private PluginMethod CreateFrom(System.Reflection.MethodInfo method, string logicalname)
            {
                var result = new PluginMethod();

                result.Name   = method.Name;
                result.method = method;
                var parameters = method.GetParameters().ToArray();

                result.Parameters = new TypeCache[parameters.Length];
                var ix = 0;

                foreach (var parameter in parameters)
                {
                    result.Parameters[ix] = TypeCache.ForParameter(parameter, logicalname);
                    ix++;
                }

                var sortAttr = method.GetCustomAttributes(Types.SortAttribute, false).SingleOrDefault();

                if (sortAttr != null)
                {
                    result.Sort = (int)sortAttr.GetType().GetProperty("Value").GetValue(sortAttr);
                }
                else
                {
                    result.Sort = 1;
                }

                var ifAttr = method.GetCustomAttributes(Types.IfAttribute, true).SingleOrDefault();

                if (ifAttr is Attributes.IfAttribute ia)
                {
                    result.IfAttribute = ia;
                }

                return(result);
            }
Esempio n. 42
0
        // </AsyncExample>


        private static void ReadAttributes()
        {
            // <ReadAttributes>
            Type widgetType = typeof(Widget);

            object[] widgetClassAttributes = widgetType.GetCustomAttributes(typeof(HelpAttribute), false);

            if (widgetClassAttributes.Length > 0)
            {
                HelpAttribute attr = (HelpAttribute)widgetClassAttributes[0];
                Console.WriteLine($"Widget class help URL : {attr.Url} - Related topic : {attr.Topic}");
            }

            System.Reflection.MethodInfo displayMethod = widgetType.GetMethod(nameof(Widget.Display));

            object[] displayMethodAttributes = displayMethod.GetCustomAttributes(typeof(HelpAttribute), false);

            if (displayMethodAttributes.Length > 0)
            {
                HelpAttribute attr = (HelpAttribute)displayMethodAttributes[0];
                Console.WriteLine($"Display method help URL : {attr.Url} - Related topic : {attr.Topic}");
            }
            // </ReadAttributes>
        }
Esempio n. 43
0
 private static bool HasAttribute <TAttribute>(this System.Reflection.MethodInfo methodInfo) where TAttribute : Attribute
 => methodInfo.GetCustomAttributes().Any(a => a is TAttribute);
Esempio n. 44
0
        public override void Execute(RouteData routeData)
        {
            //1.得到当前控制器的类型
            Type type = this.GetType();

            //2.从路由表中取到当前请求的action名称
            string actionName = routeData.RouteValue["action"].ToString();

            //3.从路由表中取到当前请求的Url参数
            object parameter = null;

            //url中的参数
            if (routeData.RouteValue.ContainsKey("parameters"))
            {
                parameter = routeData.RouteValue["parameters"];
            }


            var           paramTypes = new List <Type>();
            List <object> parameters = new List <object>();

            if (parameter != null)
            {
                var dicParam = (Dictionary <string, string>)parameter;
                foreach (var pair in dicParam)
                {
                    parameters.Add(pair.Value);
                    paramTypes.Add(pair.Value.GetType());
                }
            }

            //4.通过action名称和对应的参数反射对应方法。
            //这里第二个参数可以不理会action字符串的大小写,第四个参数决定了当前请求的action的重载参数类型
            System.Reflection.MethodInfo mi = type.GetMethod(actionName,
                                                             BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase, null, paramTypes.ToArray(), null);
            if (mi != null)
            {
                bool     flag        = false;
                object[] httpMethods = mi.GetCustomAttributes(typeof(HttpMethodAttribute), true);
                if (httpMethods != null && httpMethods.Length > 0)
                {
                    foreach (var m in httpMethods)
                    {
                        if (((HttpMethodAttribute)m).HttpMethods.Contains(routeData.RouteValue["HttpMethod"]))
                        {
                            flag = true;
                        }
                    }
                }



                if (flag)
                {
                    if (mi.ReturnType.Equals(typeof(void)))
                    {
                        mi.Invoke(this, parameters.ToArray());
                    }
                    else
                    {
                        //5.执行该Action方法
                        var actionResult = mi.Invoke(this, parameters.ToArray()) as ActionResult;

                        //6.得到action方法的返回值,并执行具体ActionResult的ExecuteResult()方法。
                        actionResult.ExecuteResult(routeData);
                    }
                }
                else
                {
                    HttpResponse response = HttpContext.Current.Response;
                    response.Write("参数错误:HttpMethod");
                    response.End();
                }
            }
            else
            {
                HttpResponse response = HttpContext.Current.Response;
                response.Write("找不到Action");
                response.End();
            }
        }
Esempio n. 45
0
 public override object[] GetCustomAttributes(bool inherit)
 {
     return(_realMethod.GetCustomAttributes(inherit));
 }
Esempio n. 46
0
        // 添加函数节点
        public static CodeGenerateSystem.Controls.NodeListAttributeClass AddMethodNode(CodeGenerateSystem.Controls.NodesContainerControl.ContextMenuFilterData filterData, System.Reflection.MethodInfo methodInfo, Type parentClassType, CodeGenerateSystem.Controls.NodeListControl hostNodesList, EngineNS.ECSType csType, string attributeName, CodeDomNode.MethodInfoAssist.enHostType hostType)
        {
            //"CSUtility.Event.Attribute.AllowMember"
            //

            CodeGenerateSystem.Controls.NodeListAttributeClass attribute = null;
            var att = EngineNS.Rtti.AttributeHelper.GetCustomAttribute(methodInfo, attributeName, true);

            if (att == null)
            {
                return(attribute);
            }

            var path = EngineNS.Rtti.AttributeHelper.GetCustomAttributePropertyValue(att, "Path")?.ToString();

            if (string.IsNullOrEmpty(path))
            {
                path = EngineNS.Rtti.RttiHelper.GetAppTypeString(methodInfo.ReflectedType) + "." + methodInfo.Name;
            }
            var description = EngineNS.Rtti.AttributeHelper.GetCustomAttributePropertyValue(att, "Description").ToString();

            //var refTypeStr = EngineNS.Rtti.RttiHelper.GetAppTypeString(methodInfo.ReflectedType);
            //var methodInfoString = GetParamFromMethodInfo(methodInfo, path);
            //methodInfoString += "," + csType.ToString() + "," + methodInfo.IsGenericMethodDefinition;
            //if (usefulMemberData != null)
            //{
            //    var usefulMemberStr = usefulMemberData.ToString().Replace(usefulMemberData.ClassTypeFullName, refTypeStr);
            //    methodInfoString += ";" + usefulMemberStr;
            //    if (!string.IsNullOrEmpty(usefulMemberData.MemberHostName))
            //    {
            //        path = usefulMemberData.MemberHostName + "." + path;
            //    }
            //    if (usefulMemberData.HostControl != null)
            //    {
            //        path = GetNodeName(usefulMemberData) + "." + path;
            //    }
            //}
            //path += "(" + refTypeStr + ")";
            var csParam = new CodeDomNode.MethodInvokeNode.MethodNodeConstructionParams()
            {
                CSType         = csType,
                ConstructParam = "",
                MethodInfo     = GetMethodInfoAssistFromMethodInfo(methodInfo, parentClassType, hostType, path),
            };

            var displayatt = methodInfo.GetCustomAttributes(typeof(EngineNS.Editor.DisplayParamNameAttribute), true);

            if (displayatt.Length > 0)
            {
                csParam.DisplayName = ((EngineNS.Editor.DisplayParamNameAttribute)displayatt[0]).DisplayName;
            }

            var attrs = methodInfo.GetCustomAttributes(typeof(EngineNS.Editor.MacrossPanelPathAttribute), true);

            if (attrs.Length == 0)
            {
                path = path.Replace('.', '/');
            }
            else
            {
                path = ((EngineNS.Editor.MacrossPanelPathAttribute)attrs[0]).Path;
            }

            attribute = hostNodesList.AddNodesFromType(filterData, typeof(CodeDomNode.MethodInvokeNode), path, csParam, description, "", hostNodesList.TryFindResource("Icon_Function") as ImageSource);
            return(attribute);
        }
        private void CreateParticleMethodCategory(string methodname, float x, float y)
        {
            Macross.NodesControlAssist NodesControlAssist = mLinkedNodesContainer.HostControl as Macross.NodesControlAssist;

            //加入列表信息
            Macross.Category category;
            var csparam = CSParam as ParticleShapeConeControlConstructionParams;

            if (!csparam.CategoryDic.TryGetValue(Macross.MacrossPanelBase.GraphCategoryName, out category))
            {
                return;
            }

            var HostControl = this.HostNodesContainer.HostControl;

            var item = new Macross.CategoryItem(null, category);

            item.CategoryItemType = Macross.CategoryItem.enCategoryItemType.OverrideFunction;
            var data = new Macross.CategoryItem.InitializeData();

            data.Reset();

            var MacrossOpPanel = NodesControlAssist.HostControl.MacrossOpPanel;

            item.Initialize(MacrossOpPanel.HostControl, data);
            //HostControl.CreateNodesContainer(item);

            //MainGridItem.Children.Add(item);
            item.Name = methodname;
            category.Items.Add(item);

            //加入结点信息
            Type type = typeof(EngineNS.Bricks.Particle.ParticleEmitShapeNode);

            System.Reflection.MethodInfo      methodInfo = type.GetMethod(methodname);
            System.Reflection.ParameterInfo[] paramstype = methodInfo.GetParameters();

            //拷貝方法的attribute.
            var    attrts      = methodInfo.GetCustomAttributes(true);
            string displayname = "";

            for (int i = 0; i < attrts.Length; i++)
            {
                var displayattr = attrts[i] as System.ComponentModel.DisplayNameAttribute;
                if (displayattr != null)
                {
                    displayname = displayattr.DisplayName;
                    break;
                }
            }

            //var CustomFunctionData = new Macross.ResourceInfos.MacrossResourceInfo.CustomFunctionData();
            var methodinfo = CodeDomNode.Program.GetMethodInfoAssistFromMethodInfo(methodInfo, type, CodeDomNode.MethodInfoAssist.enHostType.Base, "");
            var nodeType   = typeof(CodeDomNode.MethodOverride);
            var csParam    = new CodeDomNode.MethodOverride.MethodOverrideConstructParam()
            {
                CSType             = mLinkedNodesContainer.CSType,
                HostNodesContainer = mLinkedNodesContainer,
                ConstructParam     = "",
                MethodInfo         = methodinfo,
                DisplayName        = displayname,
            };

            //var center = nodesContainer.NodesControl.GetViewCenter();
            var node = mLinkedNodesContainer.AddOrigionNode(nodeType, csParam, x, y);

            node.IsDeleteable = true;

            //重写双击事件 不需要进入二级编辑
            //item.OnDoubleClick -= item.OnDoubleClick;
            Type      ItemType = item.GetType();
            FieldInfo _Field   = item.GetType().GetField("OnDoubleClick", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);

            if (_Field != null)
            {
                object _FieldValue = _Field.GetValue(item);
                if (_FieldValue != null && _FieldValue is Delegate)
                {
                    Delegate   _ObjectDelegate = (Delegate)_FieldValue;
                    Delegate[] invokeList      = _ObjectDelegate.GetInvocationList();

                    foreach (Delegate del in invokeList)
                    {
                        ItemType.GetEvent("OnDoubleClick").RemoveEventHandler(item, del);
                    }
                }
            }
            item.OnDoubleClick += (categoryItem) =>
            {
                mLinkedNodesContainer.FocusNode(node);
            };

            //NodesControlAssist.Save();
        }