Пример #1
0
        public static void Main(string[] args)
        {
            // <SnippetReadAttributes>
            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();
            // </SnippetReadAttributes>
        }
Пример #2
0
        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="action"></param>
        private void Authorize(string action)
        {
            if (this.JsonProcessor.ContainsKey(action) ||
                this.ImageProcessor.ContainsKey(action) ||
                this.FileDownloadProcessor.ContainsKey(action)
                )
            {
                System.Reflection.MethodInfo methodInfo = this.JsonProcessor.ContainsKey(action)
                    ? this.JsonProcessor[action].Method
                    : this.ImageProcessor.ContainsKey(action)
                        ? this.ImageProcessor[action].Method
                        : this.FileDownloadProcessor[action].Method;

                var attr = methodInfo.GetCustomAttributes(false).OfType <AuthorizeAttribute>().FirstOrDefault();
                if (attr != null)
                {
                    if (SccService.Authorized() &&
                        SccService.IsInRole(attr.Role, this.FunctionCode))
                    {
                        //通过权限检查
                    }
                    else
                    {
                        this.ReturnJson(JsonConvert.SerializeObject(new AjaxResult
                        {
                            Message = Commons.Language.GetText("UnAuthorized",
                                                               "CN:你无权访问!~EN:UnAuthorized",
                                                               SccService.CurrentLanguageType),
                            IsSuccess = false
                        }));
                    }
                }
            }
        }
Пример #3
0
            private PluginMethod CreateFrom(System.Reflection.MethodInfo method, string logicalname)
            {
                var result = new PluginMethod();

                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;
                }
                return(result);
            }
Пример #4
0
        private IList <System.Reflection.MethodInfo> findMatchingAnnotatedMethods(string parameterName)
        {
            IList <System.Reflection.MethodInfo> result = new List <System.Reflection.MethodInfo>();

            System.Reflection.MethodInfo[] methods = this.GetType().GetMethods();
            for (int i = 0; i < methods.Length; i++)
            {
                System.Reflection.MethodInfo method = methods[i];
                Annotation[] methodAnnotations      = method.GetCustomAttributes(true);

                for (int j = 0; j < methodAnnotations.Length; j++)
                {
                    Annotation annotation = methodAnnotations[j];
                    if (annotation is CamundaQueryParam)
                    {
                        CamundaQueryParam parameterAnnotation = (CamundaQueryParam)annotation;
                        if (parameterAnnotation.value().Equals(parameterName))
                        {
                            result.Add(method);
                        }
                    }
                }
            }
            return(result);
        }
Пример #5
0
        public void Before(System.Reflection.MethodInfo method, object[] args, object target)
        {
            String currentUser = HttpContext.Current.User.Identity.Name;

            object[] permissionAttributes = method.GetCustomAttributes(typeof(RequiredPermission), false);

            if (permissionAttributes.Count() == 1)
            {
                RequiredPermission permissionAttribute = permissionAttributes[0] as RequiredPermission;
                int accountId = (int)args[permissionAttribute.AccountIdParamIndex];


                Permission permission = _userRepository.GetUserPermission(accountId, currentUser);

                var result = permissionAttribute.Permission & permission;
                if (result != permissionAttribute.Permission)
                {
                    throw new SecurityException("Not enough user rights");
                }
            }

            bool isUserGoodType = false;

            object[] userTypeAttributes = method.GetCustomAttributes(typeof(RequiredUserType), false);

            if (userTypeAttributes != null && userTypeAttributes.Count() == 1)
            {
                UserType currentUserType = _userRepository.GetUserType(currentUser);

                UserType[] userTypes = (userTypeAttributes[0] as RequiredUserType).UserTypes;
                foreach (UserType requestedUserType in userTypes)
                {
                    if (currentUserType == requestedUserType)
                    {
                        isUserGoodType = true;
                        break;
                    }
                }

                if (!isUserGoodType)
                {
                    throw new SecurityException(String.Format("This method is not allowed for user type: {0}", currentUserType));
                }
            }
        }
Пример #6
0
 public static bool IsOn(System.Reflection.MethodInfo m)
 {
     foreach (System.Attribute attr in m.GetCustomAttributes(false))
     {
         if (attr is SetUp)
         {
             return(true);
         }
     }
     return(false);
 }
Пример #7
0
        internal CILMethodImpl(
            CILReflectionContextImpl ctx,
            Int32 anID,
            System.Reflection.MethodInfo method
            )
            : base(ctx, anID, method)
        {
            var nGDef = method.IsGenericMethodDefinition ? method : null;

            var dllImportAttr = method.GetCustomAttributes(typeof(System.Runtime.InteropServices.DllImportAttribute), true).FirstOrDefault() as System.Runtime.InteropServices.DllImportAttribute;

            InitFields(
                ref this.name,
                ref this.returnParameter,
                ref this.gArgs,
                ref this.gArgsLock,
                ref this.gDef,
                ref this.overriddenMethods,
                ref this.overriddenMethodsLock,
                ref this.pInvokeAttributes,
                ref this.pInvokeName,
                ref this.pInvokeModule,
                new SettableValueForClasses <String>(method.Name),
                () => ctx.Cache.GetOrAdd(method.ReturnParameter),
                () => ctx.CollectionsFactory.NewListProxy <CILTypeBase>(method.GetGenericArguments().Select(gArg => ctx.Cache.GetOrAdd(gArg)).ToList()),
                () => ctx.Cache.GetOrAdd(nGDef),
                () =>
            {
                var result = this.context.CollectionsFactory.NewListProxy <CILMethod>();

                if (!method.DeclaringType
#if WINDOWS_PHONE_APP
                    .GetTypeInfo()
#endif
                    .IsInterface&& !method.IsPublic)
                {
                    var args = new ExplicitMethodImplementationLoadArgs(method.DeclaringType);
                    ctx.LaunchInterfaceMappingLoadEvent(args);
                    System.Reflection.MethodInfo[] resultNMethods;
                    if (args.ExplicitlyImplementedMethods.TryGetValue(method, out resultNMethods))
                    {
                        result.AddRange(resultNMethods.Select(nMethod => ctx.Cache.GetOrAdd(nMethod)));
                    }
                }
                return(result);
            },
                new SettableValueForEnums <PInvokeAttributes>(dllImportAttr == null ? (PInvokeAttributes)0 : dllImportAttr.GetCorrespondingPInvokeAttributes()),
                new SettableValueForClasses <String>(dllImportAttr == null ? null : dllImportAttr.EntryPoint),
                new SettableValueForClasses <String>(dllImportAttr == null ? null : dllImportAttr.Value),
                true
                );
        }
Пример #8
0
        /// <summary>
        /// returns true if the method is an extension method
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public static bool IsExtensionMethod(System.Reflection.MethodInfo method)
        {
            if ((!method.IsPublic) || (!method.IsStatic))
            {
                // By definition an extension method must be public and static
                return(false);
            }

            System.Type ext_attr_type = typeof(System.Runtime.CompilerServices.ExtensionAttribute);
            var         ext_attrs     =
                (System.Runtime.CompilerServices.ExtensionAttribute[])method.GetCustomAttributes(ext_attr_type, false);

            return(ext_attrs.Length > 0);
        }
Пример #9
0
        private static bool HasPreserveAttribute(System.Reflection.MethodInfo method)
        {
            Console.Write("Checking " + method.Name + " ...");
            AssertNotEqual(method, null);
            foreach (object attr in method.GetCustomAttributes(true))
            {
                Console.WriteLine("    " + attr.GetType().Name);
                if (attr.GetType().Name == "PreserveAttribute")
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #10
0
        private Type findAnnotatedTypeConverter(System.Reflection.MethodInfo method)
        {
            Annotation[] methodAnnotations = method.GetCustomAttributes(true);

            for (int j = 0; j < methodAnnotations.Length; j++)
            {
                Annotation annotation = methodAnnotations[j];
                if (annotation is CamundaQueryParam)
                {
                    CamundaQueryParam parameterAnnotation = (CamundaQueryParam)annotation;
                    return(parameterAnnotation.converter());
                }
            }
            return(null);
        }
 public static void Main(string[] args)
 {
     System.Reflection.MethodInfo mi = typeof(Program).GetMethod("bar",
                                                                 System.Reflection.BindingFlags.Static
                                                                 | System.Reflection.BindingFlags.Public
                                                                 | System.Reflection.BindingFlags.NonPublic);
     object[] attrs = mi.GetCustomAttributes(true);
     foreach (object attr in attrs)
     {
         MyAttribute authAttr = attr as MyAttribute;
         if (authAttr != null)
         {
             System.Console.WriteLine(authAttr.Name);
         }
     }
 }
Пример #12
0
        private static bool HasMonoCallbackAttr(Type parentType, string methodName, System.Reflection.BindingFlags flags)
        {
            Console.Write("Checking " + methodName + " ...");
            System.Reflection.MethodInfo callback = parentType.GetMethod(methodName, flags | System.Reflection.BindingFlags.Static);
            AssertNotEqual(callback, null);
            foreach (object attr in callback.GetCustomAttributes(true))
            {
                Console.WriteLine("    " + attr.GetType().Name);
                if (attr.GetType().Name == "MonoPInvokeCallbackAttribute")
                {
                    return(true);
                }
            }

            return(false);
        }
        // NetStandardReporting.DynamicDllImportTest.Test();
        public static void Test()
        {
            System.Reflection.MethodInfo mi = typeof(DynamicDllImportTest).GetMethod("bar",
                                                                                     System.Reflection.BindingFlags.Static
                                                                                     | System.Reflection.BindingFlags.Public
                                                                                     | System.Reflection.BindingFlags.NonPublic);

            object[] attrs = mi.GetCustomAttributes(true);
            foreach (object attr in attrs)
            {
                DynamicDllImportAttribute importAttr = attr as DynamicDllImportAttribute;
                if (importAttr != null)
                {
                    System.Console.WriteLine(importAttr.Name);
                }
            } // Next attr
        }     // End Sub Test
        private static void GenerateTransitions(SerializedObject target, Type type)
        {
            var fsm  = target.targetObject as FStateMachineMono;
            var prop = target.FindProperty("m_Transitions");

            object[] methods = Ref.GetMethodsWithAttribute <FStateTransitionAttribute>(type, true);
            if (methods == null)
            {
                prop.ClearArray();
                return;
            }
            List <FiniteStateTransition> transitions = new List <FiniteStateTransition>();

            for (int i = 0; i < methods.Length; i++)
            {
                System.Reflection.MethodInfo mtd = methods[i] as System.Reflection.MethodInfo;
                if (!Ref.MatchMethodRetAndParams(mtd, typeof(bool), null))
                {
                    RTLog.LogError(LogCat.AI, string.Format("{0} 不能作为状态方法,因为类型不能和 \" bool Method() \" 匹配.", mtd.Name));
                    continue;
                }
                object[] trans = mtd.GetCustomAttributes(typeof(FStateTransitionAttribute), true);
                for (int j = 0; j < trans.Length; j++)
                {
                    FStateTransitionAttribute t  = trans[j] as FStateTransitionAttribute;
                    FiniteStateTransition     ft = new FiniteStateTransition();
                    ft.m_FromState = t.From ?? "";
                    //if (!string.IsNullOrEmpty(ft.m_FromState) && !fsm.HasState(ft.m_FromState))
                    //    continue;
                    ft.m_ToState = t.To ?? "";
                    //if (!string.IsNullOrEmpty(ft.m_ToState) && !fsm.HasState(ft.m_ToState))
                    //    continue;
                    ft.m_ConditionMethod = mtd.Name ?? "";
                    transitions.Add(ft);
                }
            }
            GlobalUtil.Sort(transitions, (x, y) => string.IsNullOrEmpty(x.m_FromState) || string.IsNullOrEmpty(x.m_ToState) ? 1 : -1);
            prop.arraySize = transitions.Count;
            for (int i = 0; i < transitions.Count; i++)
            {
                var p = prop.GetArrayElementAtIndex(i);
                CopyTransitionToSerializedField(transitions[i], p);
            }
        }
Пример #15
0
        public static void Usage()
        {
            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}");
            }
        }
Пример #16
0
        string[] GetCommandNamesForCurrentState(System.Reflection.MethodInfo state, System.Collections.ArrayList commandList)
        {
            StateCommandAttribute[] commands = (StateCommandAttribute[])state.GetCustomAttributes(typeof(StateCommandAttribute), false);
            if (commands != null)
            {
                foreach (StateCommandAttribute command in commands)
                {
                    commandList.Add(command.CommandName);
                }
            }
            object result = state.Invoke(this, new object[] { new QEvent(QSignals.Empty) });

            if (null != result)
            {
                state = ((QState)result).Method;
                GetCommandNamesForCurrentState(state, commandList);
            }
            string[] commandNames = (string[])commandList.ToArray(typeof(string));
            return(commandNames);
        }
Пример #17
0
        private void GenerateTransitions(Type type)
        {
            object[] methods = Utility.Ref.GetMethodsWithAttribute <FStateTransitionAttribute>(type, true);
            if (methods == null)
            {
                m_Transitions = new FiniteStateTransition[0];
                return;
            }
            List <FiniteStateTransition> transitions = new List <FiniteStateTransition>();

            for (int i = 0; i < methods.Length; i++)
            {
                System.Reflection.MethodInfo mtd = methods[i] as System.Reflection.MethodInfo;
                if (!Utility.Ref.MatchMethodRetAndParams(mtd, typeof(bool), null))
                {
                    Debug.LogError(string.Format("{0} 不能作为状态方法,因为类型不能和 \" bool Method() \" 匹配.", mtd.Name));
                    continue;
                }
                object[] trans = mtd.GetCustomAttributes(typeof(FStateTransitionAttribute), true);
                for (int j = 0; j < trans.Length; j++)
                {
                    FStateTransitionAttribute t  = trans[j] as FStateTransitionAttribute;
                    FiniteStateTransition     ft = new FiniteStateTransition();
                    ft.m_FromState = t.From ?? "";
                    if (!string.IsNullOrEmpty(ft.m_FromState) && !HasState(ft.m_FromState))
                    {
                        continue;
                    }
                    ft.m_ToState = t.To ?? "";
                    if (!string.IsNullOrEmpty(ft.m_ToState) && !HasState(ft.m_ToState))
                    {
                        continue;
                    }
                    ft.m_ConditionMethod = mtd.Name ?? "";
                    transitions.Add(ft);
                }
            }
            transitions.Sort((x, y) => string.IsNullOrEmpty(x.m_FromState) || string.IsNullOrEmpty(x.m_ToState) ? 1 : -1);
            m_Transitions = transitions.ToArray();
        }
 /// <summary>
 /// 按方法RepositoryInterceptorAttribute特性设置token值
 /// </summary>
 /// <param name="context">Aspect上下文</param>
 /// <param name="methodInfo">方法</param>
 /// <returns></returns>
 private bool SetTokenValueByMethod(AspectContext context, System.Reflection.MethodInfo methodInfo, string userName)
 {
     foreach (var atr in methodInfo.GetCustomAttributes(false))
     {
         //获取上RepositoryInterceptorAttribute的方法
         if (atr is RepositoryInterceptorAttribute)
         {
             int index = 0;
             foreach (var par in context.ProxyMethod.GetParameters())
             {
                 //参数名为token的切面输入token
                 if (par.Name == "token")
                 {
                     context.Parameters[index] = GetToken(HttpContextAccessor.HttpContext, userName);
                     return(true);
                 }
                 index++;
             }
         }
     }
     return(false);
 }
        protected override PageHandlerModel CreateHandlerModel(System.Reflection.MethodInfo method)
        {
            if (method == null)
            {
                throw new ArgumentNullException(nameof(method));
            }

            if (!IsHandler(method))
            {
                return(null);
            }

            if (!TryParseHandlerMethod(method.Name, out var httpMethod, out var handlerName))
            {
                return(null);
            }

            var handlerModel = new PageHandlerModel(
                method,
                method.GetCustomAttributes(inherit: true))
            {
                Name        = method.Name,
                HandlerName = handlerName,
                HttpMethod  = httpMethod,
            };

            var methodParameters = handlerModel.MethodInfo.GetParameters();

            for (var i = 0; i < methodParameters.Length; i++)
            {
                var parameter      = methodParameters[i];
                var parameterModel = CreateParameterModel(parameter);
                parameterModel.Handler = handlerModel;

                handlerModel.Parameters.Add(parameterModel);
            }

            return(handlerModel);
        }
        public void DisplayMethodProperties(System.Reflection.MethodInfo Method)
        {
            ThisMethod = Method;

            // Show the method name

            Label2.Text = ThisMethod.Name;

            // Show the calling convention

            Label4.Text = "0x" + ThisMethod.CallingConvention.ToString("x") +
                " = " + ThisMethod.CallingConvention.ToString();

            // Show the method's standard attributes

            Label6.Text = "0x" + ThisMethod.Attributes.ToString("x") +
                " = " + ThisMethod.Attributes.ToString();

            // Show the return type

            Label8.Text = ThisMethod.ReturnType.FullName;

            // Show the parameters

            foreach (System.Reflection.ParameterInfo parm in ThisMethod.GetParameters())
            {
                //ListBox1.Items.Add(parm.Name + " as " + parm.ParameterType.FullName);
                ListBox1.Items.Add(parm.ParameterType);//changed because I need the type later
            }

            // Show the custom attributes

            foreach (object attr in ThisMethod.GetCustomAttributes(true))
            {
                ListBox2.Items.Add(attr);
            }
        }
        /// <summary>
        /// Initializes a type.
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="type"></param>
        protected static void InitializeType(ModelValidationController controller, System.Type type)
        {
            object[] attr = type.GetCustomAttributes(typeof(ModelValidationStateAttribute), false);

            bool isEnabled = false;

            foreach (ModelValidationStateAttribute attribute in attr)
            {
                if (attribute.ValidationState == ModelValidationState.Enabled)
                {
                    isEnabled = true;
                    break;
                }
            }
            if (isEnabled)
            {
                controller.ValidationIsEnabled.Add(type, isEnabled);
            }

            // continue with methods
            if (isEnabled)
            {
                System.Collections.Generic.Dictionary <System.Reflection.MethodInfo, ModelValidationCategories> dictionary = new System.Collections.Generic.Dictionary <System.Reflection.MethodInfo, ModelValidationCategories>();
                System.Reflection.MethodInfo[] methodInfoArr = type.GetMethods(System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
                for (int i = 0; i < methodInfoArr.Length; i++)
                {
                    System.Reflection.MethodInfo methodInfo = methodInfoArr[i];
                    object[] objArr = methodInfo.GetCustomAttributes(typeof(ModelValidationMethodAttribute), false);
                    if ((objArr != null) && (objArr.Length != 0))
                    {
                        dictionary.Add(methodInfo, (objArr[0] as ModelValidationMethodAttribute).Categories);
                    }
                }
                controller.ValidationMap.Add(type, dictionary);
            }
        }
Пример #22
0
        private static string BuildScript(Type service, System.Reflection.MethodInfo methodInfo)
        {
            StringBuilder script = new StringBuilder();

            script.AppendLine(@"Dictionary<string, string> input = new Dictionary<string, string>();");
            var attributes       = service.GetCustomAttributes(typeof(AnnoProxyAttribute), true);
            var methodAttributes = methodInfo.GetCustomAttributes(typeof(AnnoProxyAttribute), true);

            /*
             * 接口模块 通道设置
             */
            if (attributes.Length > 0 || methodAttributes.Length > 0)
            {
                AnnoProxyAttribute attribute = null;
                if (attributes.Length > 0)
                {
                    attribute = (AnnoProxyAttribute)attributes[0];
                }
                if (attribute == null && methodAttributes.Length > 0)
                {
                    attribute = (AnnoProxyAttribute)methodAttributes[0];
                }
                else if (attribute != null && methodAttributes.Length > 0)
                {
                    AnnoProxyAttribute mAttribute = (AnnoProxyAttribute)methodAttributes[0];
                    if (!string.IsNullOrWhiteSpace(mAttribute.Channel))
                    {
                        attribute.Channel = mAttribute.Channel;
                    }
                    if (!string.IsNullOrWhiteSpace(mAttribute.Router))
                    {
                        attribute.Router = mAttribute.Router;
                    }
                    if (!string.IsNullOrWhiteSpace(mAttribute.Method))
                    {
                        attribute.Method = mAttribute.Method;
                    }
                }

                if (string.IsNullOrWhiteSpace(attribute.Channel) || string.IsNullOrWhiteSpace(attribute.Router) || string.IsNullOrWhiteSpace(attribute.Method))
                {
                    throw new ArgumentNullException("管道参数 AnnoProxyAttribute[Channel、Router、Method] 不能为空");
                }
                script.AppendLine($"input.Add(\"channel\", \"{attribute.Channel}\");");
                script.AppendLine($"input.Add(\"router\", \"{attribute.Router}\");");
                script.AppendLine($"input.Add(\"method\", \"{attribute.Method}\");");
            }
            else
            {
                throw new ArgumentNullException("请设置管道参数 AnnoProxyAttribute[Channel、Router、Method]");
            }
            var parameters = methodInfo.GetParameters();

            for (int i = 0; i < parameters.Length; i++)
            {
                if (parameters[i].Name.Equals("channel") || parameters[i].Name.Equals("router") || parameters[i].Name.Equals("method"))
                {
                    throw new ArgumentException("服务接口参数不能出现关键字[channel、router、method]");
                }
                if (parameters[i].ParameterType.IsClass && !parameters[i].ParameterType.Equals("".GetType()))
                {
                    script.AppendLine($"input.Add(\"{parameters[i].Name}\", Newtonsoft.Json.JsonConvert.SerializeObject({parameters[i].Name}));");
                }
                else
                {
                    script.AppendLine($"input.Add(\"{parameters[i].Name}\", {parameters[i].Name}.ToString());");
                }
            }
            if (methodInfo.ReturnType != typeof(void))
            {
                script.AppendLine("string rlt = Anno.Rpc.Client.Connector.BrokerDns(input);");
                if (typeof(IActionResult).IsAssignableFrom(methodInfo.ReturnType))
                {
                    script.AppendLine($"return Newtonsoft.Json.JsonConvert.DeserializeObject<{methodInfo.ReturnType.FullName}>(rlt);");
                }
                else
                {
                    script.AppendLine($"var data= Newtonsoft.Json.JsonConvert.DeserializeObject<ActionResult<{methodInfo.ReturnType.FullName}>>(rlt);");
                    script.AppendLine(@"
                    if (data.Status == false && data.OutputData == null&&!string.IsNullOrWhiteSpace(data.Msg))
                    {
                        throw new InvalidOperationException(data.Msg);
                    }
                    else
                    {
                        return data.OutputData;
                    }");
                }
            }
            else
            {
                script.AppendLine("Anno.Rpc.Client.Connector.BrokerDns(input);");
            }
            return(script.ToString());
        }
Пример #23
0
 protected void CalculateIsDirectional(System.Reflection.MethodInfo mInfo)
 {
     object[] directionalAttributes = mInfo.GetCustomAttributes(typeof(DirectionalGlyphAttribute), true);
     _IsDirectionalGlyph = directionalAttributes != null && directionalAttributes.Length > 0;
 }
Пример #24
0
 private static IEnumerable <InterceptorAttribute> GetInterceptorAttributes(MethodInfo methodInfo)
 {
     return(methodInfo?.GetCustomAttributes(typeof(InterceptorAttribute), true).Cast <InterceptorAttribute>() ?? new InterceptorAttribute[0]);
 }
Пример #25
0
 public object[] GetCustomAttributes(bool inherit)
 {
     return(internalInfo.GetCustomAttributes(inherit));
 }
Пример #26
0
        private void GenerateStates(Type type)
        {
            object[] methods = Utility.Ref.GetMethodsWithAttribute <FStateAttribute>(type, true);
            if (methods == null)
            {
                m_States = new FiniteState[0];
                return;
            }
            FiniteState tmp;
            FiniteState defaultState = null;
            FiniteState firstState   = null;
            Dictionary <string, FiniteState> allstates = new Dictionary <string, FiniteState>();

            for (int i = 0; i < methods.Length; i++)
            {
                System.Reflection.MethodInfo mtd = methods[i] as System.Reflection.MethodInfo;
                if (!Utility.Ref.MatchMethodRetAndParams(mtd, typeof(void), null))
                {
                    Debug.LogError(string.Format("{0} 不能作为状态方法,因为类型不能和 \" void Method() \" 匹配.", mtd.Name));
                    continue;
                }
                object[] states = mtd.GetCustomAttributes(typeof(FStateAttribute), true);
                for (int j = 0; j < states.Length; j++)
                {
                    FStateAttribute state = states[j] as FStateAttribute;
                    string          sname = state.Name;
                    if (string.IsNullOrEmpty(sname))
                    {
                        sname = mtd.Name;
                    }
                    if (!allstates.TryGetValue(sname, out tmp))
                    {
                        tmp              = new FiniteState();
                        tmp.m_StateName  = sname;
                        allstates[sname] = tmp;
                    }
                    if (firstState == null)
                    {
                        firstState = tmp;
                    }
                    if (state.IsDefault)
                    {
                        tmp.m_IsDefaultState = true;
                        if (defaultState != null)
                        {
                            defaultState.m_IsDefaultState = false;
                        }
                        defaultState = tmp;
                    }
                    if (state.KeepInStack)
                    {
                        tmp.m_KeepInStack = true;
                    }
                    if ((state.Event & EStateEvent.OnBegin) != 0)
                    {
                        tmp.m_BeginMethod = mtd.Name;
                    }
                    if ((state.Event & EStateEvent.OnTick) != 0)
                    {
                        tmp.m_TickMethod = mtd.Name;
                    }
                    if ((state.Event & EStateEvent.OnEnd) != 0)
                    {
                        tmp.m_EndMethod = mtd.Name;
                    }
                }
            }
            if (defaultState == null && firstState != null)
            {
                firstState.m_IsDefaultState = true;
            }
            m_States = new FiniteState[allstates.Count];
            allstates.Values.CopyTo(m_States, 0);
        }
        private static void GenerateStates(SerializedObject target, Type type)
        {
            var prop = target.FindProperty("m_States");

            object[] methods = Ref.GetMethodsWithAttribute <FStateAttribute>(type, true);
            if (methods == null)
            {
                prop.ClearArray();
                return;
            }
            FiniteState tmp;
            FiniteState defaultState = null;
            FiniteState firstState   = null;
            Dictionary <string, FiniteState> allstates = new Dictionary <string, FiniteState>();

            for (int i = 0; i < methods.Length; i++)
            {
                System.Reflection.MethodInfo mtd = methods[i] as System.Reflection.MethodInfo;
                if (!Ref.MatchMethodRetAndParams(mtd, typeof(void), null))
                {
                    RTLog.LogError(LogCat.AI, string.Format("{0} 不能作为状态方法,因为类型不能和 \" void Method() \" 匹配.", mtd.Name));
                    continue;
                }
                object[] states = mtd.GetCustomAttributes(typeof(FStateAttribute), true);
                for (int j = 0; j < states.Length; j++)
                {
                    FStateAttribute state = states[j] as FStateAttribute;
                    string          sname = state.Name;
                    if (string.IsNullOrEmpty(sname))
                    {
                        sname = mtd.Name;
                    }
                    if (!allstates.TryGetValue(sname, out tmp))
                    {
                        tmp              = new FiniteState();
                        tmp.m_StateName  = sname;
                        allstates[sname] = tmp;
                    }
                    if (firstState == null)
                    {
                        firstState = tmp;
                    }
                    if (state.IsDefault)
                    {
                        tmp.m_IsDefaultState = true;
                        if (defaultState != null)
                        {
                            defaultState.m_IsDefaultState = false;
                        }
                        defaultState = tmp;
                    }
                    if (state.KeepInStack)
                    {
                        tmp.m_KeepInStack = true;
                    }
                    if (state.IsSubState)
                    {
                        tmp.m_UseSubState = true;
                    }
                    if ((state.Event & EStateEvent.OnBegin) != 0)
                    {
                        tmp.m_BeginMethod = mtd.Name;
                    }
                    if ((state.Event & EStateEvent.OnTick) != 0)
                    {
                        tmp.m_TickMethod = mtd.Name;
                    }
                    if ((state.Event & EStateEvent.OnEnd) != 0)
                    {
                        tmp.m_EndMethod = mtd.Name;
                    }
                }
            }
            if (defaultState == null && firstState != null)
            {
                firstState.m_IsDefaultState = true;
            }
            prop.arraySize = allstates.Count;
            int num = 0;

            foreach (var stat in allstates.Values)
            {
                var p = prop.GetArrayElementAtIndex(num++);
                CopyStateToSerializedField(stat, p);
            }
        }
        private void mnuHelperItemViewFunction_Click(object sender, EventArgs e)
        {
            Controller.MainForm.Cursor = Cursors.WaitCursor;
            TreeListNode selectedNode = treeListAPIHelper.Selection[0];
            Type         objectType   = (Type)selectedNode.ParentNode.Tag;
            string       methodName   = selectedNode[0].ToString();
            string       functionName = objectType.FullName.Replace("ArchAngel.Providers.Database.", "") + "." + methodName;

            functionName = functionName.Replace(".", "_");

            Project.FunctionInfo function = Project.Instance.FindFunction(functionName);

            if (function == null)
            {
                System.Reflection.MethodInfo method = objectType.GetMethod(methodName);
                ArchAngel.Interfaces.Attributes.ApiExtensionAttribute[] attributes = (ArchAngel.Interfaces.Attributes.ApiExtensionAttribute[])method.GetCustomAttributes(typeof(ArchAngel.Interfaces.Attributes.ApiExtensionAttribute), true);

                if (attributes.Length == 0)
                {
                    throw new NotImplementedException(string.Format("DefaultCodeAttribute not implemented for {0}.{1} yet.", objectType.FullName, methodName));
                }
                Type returnType = method.ReturnType;

                function = new Project.FunctionInfo(functionName, returnType, "XXX", false, Project.ScriptLanguageTypes.CSharp, string.Format("Override of helper function: {0}.{1}.", objectType.Name, methodName), "XXX", "Helper Overrides");
                System.Reflection.ParameterInfo[] parameters = method.GetParameters();

                foreach (System.Reflection.ParameterInfo parameter in parameters)
                {
                    ArchAngel.Designer.Project.ParamInfo par = new Project.ParamInfo(parameter.Name, parameter.ParameterType);
                    function.AddParameter(par);
                }
                Project.Instance.AddFunction(function);
                //int funcCount = Project.Instance.Functions.Length;
                //Project.FunctionInfo[] coll = new Project.FunctionInfo[funcCount + 1];
                //coll[coll.Length - 1] = function;
                //Array.Copy(Project.Instance.Functions, coll, funcCount);
                //Project.Instance.Functions = coll;
            }
            Project.DefaultValueFunction defValFunc = Project.Instance.FindDefaultValueFunction(functionName);

            if (defValFunc == null)
            {
                Project.ParamInfo[] parameterTypes = new Project.ParamInfo[function.Parameters.Length];

                for (int i = 0; i < function.Parameters.Length; i++)
                {
                    parameterTypes[i] = new Project.ParamInfo(Slyce.Common.Utility.GetCamelCase(function.Parameters[i].Name), function.Parameters[i].DataType);
                }
                defValFunc = new Project.DefaultValueFunction(objectType, methodName, false, Project.DefaultValueFunction.FunctionTypes.HelperOverride, false);
                defValFunc.ParameterTypes = parameterTypes;
                Project.Instance.DefaultValueFunctions.Add(defValFunc);
                function.Body            = defValFunc.GetFormattedDefaultCode();
                Project.Instance.IsDirty = true;
            }
            Controller.MainForm.ShowFunction(functionName, defValFunc, false, this);
            Controller.MainForm.Cursor = Cursors.Default;
        }
Пример #29
0
        public static string MakeMethodExecuterCode(MethodDesc desc, bool bIsClient)
        {
            System.Reflection.MethodInfo mi = desc.mi;
            System.Type ctype = desc.hostType;

            int LimitLevel = 0;

            if (!bIsClient)
            {
                object[] propAttrs = mi.GetCustomAttributes(typeof(RPC.RPCMethodAttribute), false);
                if (propAttrs != null && propAttrs.Length == 1)
                {
                    RPC.RPCMethodAttribute propAtt = propAttrs[0] as RPC.RPCMethodAttribute;
                    if (propAtt != null)
                    {
                        LimitLevel = propAtt.LimitLevel;
                    }
                }
            }

            string strOut = "";

            strOut += "[RPC.RPCMethordExecuterTypeAttribute(" + RPC.RPCEntrance.GetMethodHashCode(mi, ctype.FullName) + ",\"" + mi.Name + "\",typeof(HExe_" + RPC.RPCEntrance.GetMethodHashCode(mi, ctype.FullName) + "))]" + EndLine;
            strOut += "public class HExe_" + RPC.RPCEntrance.GetMethodHashCode(mi, ctype.FullName) + ": RPC.RPCMethodExecuter" + EndLine;
            strOut += "{" + EndLine;
            strOut += TabStr + "public override int LimitLevel" + EndLine;
            strOut += TabStr + "{" + EndLine;
            strOut += TabStr + TabStr + "get { return " + LimitLevel + "; }" + EndLine;
            strOut += TabStr + "}" + EndLine;

            if (bIsClient)
            {
                strOut += TabStr + "public override object Execute(RPC.RPCObject obj,RPC.PackageProxy pkg)" + EndLine;
            }
            else
            {
                strOut += TabStr + "public override object Execute(Iocp.NetConnection connect,RPC.RPCObject obj,RPC.PackageProxy pkg,RPC.RPCForwardInfo fwd)" + EndLine;
            }
            strOut += TabStr + "{" + EndLine;
            strOut += TabStr + TabStr + ctype.FullName + " host = obj as " + ctype.FullName + ";" + EndLine;
            strOut += TabStr + TabStr + "if (host == null) return null;" + EndLine;

            string strCall = "";

            System.Reflection.ParameterInfo[] parameters = mi.GetParameters();
            for (int i = 0; i < parameters.Length; i++)
            {
                string finalName = parameters[i].Name;

                bool isNew    = false;
                Type baseType = parameters[i].ParameterType;
                while (!isNew)
                {
                    baseType = baseType.BaseType;
                    if (baseType == null)
                    {
                        break;
                    }
                    if (baseType.Name == "IAutoSaveAndLoad")
                    {
                        isNew = true;
                        break;
                    }
                }

                if (parameters[i].ParameterType.FullName == "Iocp.NetConnection")
                {
                    finalName = "connect";
                }
                else if (parameters[i].ParameterType.FullName == "RPC.RPCForwardInfo")
                {
                    finalName = "fwd";
                }
                else if (isNew)
                {
                    strOut += TabStr + TabStr + parameters[i].ParameterType.FullName + " " + parameters[i].Name + " = new " + parameters[i].ParameterType.FullName + "();" + EndLine;
                    strOut += TabStr + TabStr + "pkg.Read( " + parameters[i].Name + ");" + EndLine;
                }
                else
                {
                    strOut += TabStr + TabStr + parameters[i].ParameterType.FullName + " " + parameters[i].Name + ";" + EndLine;
                    strOut += TabStr + TabStr + "pkg.Read(out " + parameters[i].Name + ");" + EndLine;
                }

                if (i == parameters.Length - 1)
                {
                    strCall += finalName;
                }
                else
                {
                    strCall += finalName + ",";
                }
            }

            if (mi.ReturnType == typeof(void))
            {
                strOut += TabStr + TabStr + "host." + mi.Name + "(" + strCall + ");" + EndLine + "return null;" + EndLine;
            }
            else
            {
                strOut += TabStr + TabStr + "return host." + mi.Name + "(" + strCall + ");" + EndLine;
            }

            strOut += TabStr + "}" + EndLine;
            strOut += "}" + EndLine;
            return(strOut);
        }
Пример #30
0
        /// <summary>
        /// Returns some dashboard content that shows the background operations and their current status.
        /// </summary>
        /// <returns>The dashboard content.</returns>
        public IEnumerable <DashboardListItem> GetDashboardContent(TaskQueueResolver taskQueueResolver)
        {
            if (null == taskQueueResolver)
            {
                yield break;
            }

            foreach (var queue in taskQueueResolver.GetQueues())
            {
                // Sanity.
                if (string.IsNullOrWhiteSpace(queue))
                {
                    continue;
                }

                // Get information about the queues.
                TaskQueueAttribute          queueSettings = null;
                System.Reflection.FieldInfo fieldInfo     = null;
                try
                {
                    queueSettings = taskQueueResolver.GetQueueSettings(queue);
                    fieldInfo     = taskQueueResolver.GetQueueFieldInfo(queue);
                }
                catch
                {
                    // Throws if the queue is incorrect.
                    SysUtils.ReportToEventLog
                        ($"Cannot load details for queue {queue}; is there a static field with the [TaskQueue] attribute?",
                        System.Diagnostics.EventLogEntryType.Warning
                        );
                    continue;
                }


                // Skip anything broken.
                if (null == queueSettings || null == fieldInfo)
                {
                    continue;
                }

                // If it's marked as hidden then skip.
                {
                    var attributes = fieldInfo.GetCustomAttributes(typeof(HideOnDashboardAttribute), true)
                                     ?? new HideOnDashboardAttribute[0];
                    if (attributes.Length != 0)
                    {
                        continue;
                    }
                }

                // Get each task processor.
                foreach (var processor in taskQueueResolver.GetTaskProcessors(queue))
                {
                    // Sanity.
                    if (null == processor)
                    {
                        continue;
                    }

                    // Get information about the processor..
                    TaskProcessorAttribute       taskProcessorSettings = null;
                    System.Reflection.MethodInfo methodInfo            = null;
                    try
                    {
                        taskProcessorSettings = taskQueueResolver.GetTaskProcessorSettings(queue, processor.Type);
                        methodInfo            = taskQueueResolver.GetTaskProcessorMethodInfo(queue, processor.Type);
                    }
                    catch
                    {
                        // Throws if the task processor is not found.
                        SysUtils.ReportToEventLog
                        (
                            $"Cannot load processor details for task type {processor.Type} on queue {queue}.",
                            System.Diagnostics.EventLogEntryType.Warning
                        );
                        continue;
                    }


                    // Skip anything broken.
                    if (null == taskProcessorSettings || null == methodInfo)
                    {
                        continue;
                    }

                    // If it's marked as hidden then skip.
                    {
                        var attributes = methodInfo.GetCustomAttributes(typeof(HideOnDashboardAttribute), true)
                                         ?? new HideOnDashboardAttribute[0];
                        if (attributes.Length != 0)
                        {
                            continue;
                        }
                    }

                    // This should be shown.  Do we have any extended details?
                    var showOnDashboardAttribute = methodInfo.GetCustomAttributes(typeof(ShowOnDashboardAttribute), true)?
                                                   .FirstOrDefault() as ShowOnDashboardAttribute;

                    // Show the description?
                    var htmlString = "";
                    if (false == string.IsNullOrWhiteSpace(showOnDashboardAttribute?.Description))
                    {
                        htmlString += new DashboardCustomContent($"<p><em>{System.Security.SecurityElement.Escape(showOnDashboardAttribute?.Description)}</em></p>").ToXmlString();
                    }

                    // Does it have any configuration instructions?
                    IRecurrenceConfiguration recurrenceConfiguration = null;
                    if (this
                        .VaultApplication?
                        .RecurringOperationConfigurationManager?
                        .TryGetValue(queue, processor.Type, out recurrenceConfiguration) ?? false)
                    {
                        htmlString += recurrenceConfiguration.ToDashboardDisplayString();
                    }
                    else
                    {
                        htmlString += "<p>Does not repeat.<br /></p>";
                    }

                    // Get known executions (prior, running and future).
                    var executions = this
                                     .GetAllExecutions <TaskDirective>(queue, processor.Type)
                                     .ToList();
                    var isRunning   = executions.Any(e => e.State == MFilesAPI.MFTaskState.MFTaskStateInProgress);
                    var isScheduled = executions.Any(e => e.State == MFilesAPI.MFTaskState.MFTaskStateWaiting);

                    // Create the (basic) list item.
                    var listItem = new DashboardListItemWithNormalWhitespace()
                    {
                        Title         = showOnDashboardAttribute?.Name ?? processor.Type,
                        StatusSummary = new DomainStatusSummary()
                        {
                            Label = isRunning
                                                        ? "Running"
                                                        : isScheduled ? "Scheduled" : "Stopped"
                        }
                    };

                    // Should we show the run command?
                    {
                        var key = $"{queue}-{processor.Type}";
                        lock (this._lock)
                        {
                            if (this.TaskQueueRunCommands.ContainsKey(key))
                            {
                                var cmd = new DashboardDomainCommand
                                {
                                    DomainCommandID = this.TaskQueueRunCommands[key].ID,
                                    Title           = this.TaskQueueRunCommands[key].DisplayName,
                                    Style           = DashboardCommandStyle.Link
                                };
                                listItem.Commands.Add(cmd);
                            }
                        }
                    }

                    // Set the list item content.
                    listItem.InnerContent = new DashboardCustomContent
                                            (
                        htmlString
                        + executions?
                        .AsDashboardContent()?
                        .ToXmlString()
                                            );

                    // Add the list item.
                    yield return(listItem);
                }
            }
        }
Пример #31
0
 // Depuis que j'ai passé le truk à .NET framework 4 au lieu de .NET Framework 4.5
 // Plusieurs fonctions n'étaient plus définies
 // TODO: Voir s'il y a moyen de compiler (à l'avenir) pour plusieurs version du framework avec les statements #if NET20, NET30, etc
 internal static T GetCustomAttribute <T>(this System.Reflection.MethodInfo method) where T : System.Attribute
 {
     object[] attributes = method.GetCustomAttributes(false);
     return(attributes.OfType <T>().FirstOrDefault());
 }