コード例 #1
0
    /// <summary>
    /// Invokes the specified input.
    /// </summary>
    /// <param name="input">The input.</param>
    /// <param name="getNext">The get next.</param>
    /// <returns>The method return result.</returns>
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
      foreach (var argument in input.Arguments)
      {
        string target = argument as string;

        if (string.IsNullOrEmpty(target))
        {
          continue;
        }

        if (Regex.Match(target, @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?").Success)
        {
          continue;
        }

        ArgumentException argumentException = new ArgumentException("Invalid e-mail format", input.MethodBase.Name);

        Log.Error("Argument exception", argumentException, this);

        return input.CreateExceptionMethodReturn(argumentException);
      }

      return getNext()(input, getNext);
    }
コード例 #2
0
		public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
		{
			Dictionary<Type, Validator> validators = new Dictionary<Type, Validator>();
			Int32 i = 0;
			ValidationResults results = new ValidationResults();
			IMethodReturn result = null;

			foreach (Type type in input.MethodBase.GetParameters().Select(p => p.ParameterType))
			{
				if (validators.ContainsKey(type) == false)
				{
					validators[type] = ValidationFactory.CreateValidator(type, this.Ruleset);
				}

				Validator validator = validators[type];
				validator.Validate(input.Arguments[i], results);

				++i;
			}

			if (results.IsValid == false)
			{
				result = input.CreateExceptionMethodReturn(new Exception(String.Join(Environment.NewLine, results.Select(r => r.Message).ToArray())));
			}
			else
			{
				result = getNext()(input, getNext);
			}

			return (result);
		}
        private IMethodReturn InvokeINotifyPropertyChangedMethod(IMethodInvocation input)
        {
            if (input.MethodBase.DeclaringType == typeof(INotifyPropertyChanged))
            {
                switch (input.MethodBase.Name)
                {
                    case "add_PropertyChanged":
                        lock (handlerLock)
                        {
                            handler = (PropertyChangedEventHandler)Delegate.Combine(handler, (Delegate)input.Arguments[0]);
                        }
                        break;

                    case "remove_PropertyChanged":
                        lock (handlerLock)
                        {
                            handler = (PropertyChangedEventHandler)Delegate.Remove(handler, (Delegate)input.Arguments[0]);
                        }
                        break;

                    default:
                        return input.CreateExceptionMethodReturn(new InvalidOperationException());
                }

                return input.CreateMethodReturn(null);
            }

            return null;
        }
コード例 #4
0
        public IMethodReturn Invoke(
            IMethodInvocation input, 
            GetNextHandlerDelegate getNext)
        {
            if (this.allowedRoles.Length > 0)
            {
                IPrincipal currentPrincipal = Thread.CurrentPrincipal;

                if (currentPrincipal != null)
                {
                    bool allowed = false;
                    foreach (string role in this.allowedRoles)
                    {
                        if (allowed = currentPrincipal.IsInRole(role))
                        {
                            break;
                        }
                    }

                    if (!allowed)
                    {
                        // short circuit the call
                        return input.CreateExceptionMethodReturn(
                            new UnauthorizedAccessException(
                                "User not allowed to invoke the method"));
                    }
                }
            }

            return getNext()(input, getNext);
        }
コード例 #5
0
ファイル: ValidationCallHandler.cs プロジェクト: tmont/portoa
 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
     var results = input.Arguments.Cast<object>().SelectMany(entity => validator.Validate(entity));
     return !results.Any()
         ? getNext()(input, getNext) //no errors
         : input.CreateExceptionMethodReturn(new ValidationFailedException(results));
 }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var methodReturn = InvokeINotifyPropertyChangedMethod(input);

            if (methodReturn != null)
            {
                return methodReturn;
            }

            methodReturn = getNext()(input, getNext);

            if (methodReturn.Exception == null && input.MethodBase.IsSpecialName)
            {
                var property = GetPropertyInfoForSetMethod(input);

                if (property != null)
                {
                    var currentHandler = this.handler;
                    if (currentHandler != null)
                    {
                        try
                        {
                            currentHandler(input.Target, new PropertyChangedEventArgs(property.Name));
                        }
                        catch (Exception e)
                        {
                            return input.CreateExceptionMethodReturn(e);
                        }
                    }
                }
            }

            return methodReturn;
        }
コード例 #7
0
 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
     User user = input.Inputs[0] as User;
     if (user.PassWord.Length < 0) {
         return input.CreateExceptionMethodReturn(new Exception("密码长度不能小于10位"));
     }
     Console.WriteLine("参数检测无误");
     return getNext()(input, getNext);
 }
コード例 #8
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            if (!this.IsValidUser())
            {
                return input.CreateExceptionMethodReturn(new UnauthorizedAccessException("..."));
            }

            return getNext()(input, getNext);
        }
コード例 #9
0
        /// <summary>
        /// Handler de invocação do método com atributo
        /// </summary>
        /// <param name="input">Informações da chamada</param>
        /// <param name="getNext">Próximo handler de execução do método</param>
        /// <returns>Caso estejamos fora dum UoW, retorna exception, caso contrário segue a execução</returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (UnitOfWork.Current == null)
            {
                return input.CreateExceptionMethodReturn(new Exception("Método " + input.MethodBase.Name + " chamado fora de UnitOfWork."));
            }

            // Retornamos normalmente
            return getNext()(input, getNext);
        }
コード例 #10
0
ファイル: Temp.cs プロジェクト: alexisjojo/ktibiax
 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
     for (int i = 0; i < input.Inputs.Count; i++) {
         object target = input.Inputs[i];
         if (target == null) {
             ParameterInfo parameterInfo = input.Inputs.GetParameterInfo(i);
             ArgumentNullException ex = new ArgumentNullException(parameterInfo.Name);
             return input.CreateExceptionMethodReturn(ex);
         }
     }
     return getNext()(input, getNext);
 }
コード例 #11
0
 private IMethodReturn MethodWithGenericReturnType_Delegate <T>(IMethodInvocation inputs, GetNextInterceptionBehaviorDelegate getNext)
 {
     try
     {
         T result = base.MethodWithGenericReturnType((T)inputs.Arguments[0]);
         return(inputs.CreateMethodReturn(result, inputs.Arguments));
     }
     catch (Exception ex)
     {
         return(inputs.CreateExceptionMethodReturn(ex));
     }
 }
コード例 #12
0
 /// <summary>
 /// Méthode de traitement après appel
 /// </summary>
 /// <param name="pInput">Description de l'appel intercepté</param>
 /// <param name="pReturn">Description du résultat de l'appel</param>
 /// <returns>Résultat final de l'appel</returns>
 private IMethodReturn PostProcessHandlerInternal(IMethodInvocation pInput, IMethodReturn pReturn)
 {
     try
     {
         return(PostProcessHandler(pInput, pReturn));
     }
     catch (Exception ex)
     {
         // En cas d'exception non gérée, la définir comme message de retour
         return(pInput.CreateExceptionMethodReturn(ex));
     }
 }
コード例 #13
0
 private IMethodReturn Reverse_DelegateImpl <TItem>(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
 {
     try
     {
         string baseResult = BaseReverse((TItem)input.Arguments[0]);
         return(input.CreateMethodReturn(baseResult));
     }
     catch (Exception ex)
     {
         return(input.CreateExceptionMethodReturn(ex));
     }
 }
コード例 #14
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            User user = input.Inputs[0] as User;

            if (user.Password.Length < 10)
            {
                return(input.CreateExceptionMethodReturn(new Exception("密码长度不能小于10位")));
            }
            Console.WriteLine("参数检测无误");
            IMethodReturn methodReturn = getNext()(input, getNext);

            return(methodReturn);
        }
コード例 #15
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            User user = input.Inputs[0] as User;

            if (user.Name != "ELEVEN")
            {
                return(input.CreateExceptionMethodReturn(new Exception("用户名必须为ELEVEN")));
            }
            Console.WriteLine("用户名必须为ELEVEN");
            IMethodReturn methodReturn = getNext()(input, getNext);

            return(methodReturn);
        }
コード例 #16
0
        /// <summary>
        /// Performs the operation of the handler.
        /// </summary>
        /// <param name="input">Input to the method call.</param>
        /// <param name="getNext">Delegate used to get the next delegate in the call handler pipeline.</param>
        /// <returns>Returns value from the target method, or an <see cref="UnauthorizedAccessException"/>
        /// if the call fails the authorization check.</returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IAuthorizationProvider authProvider = GetAuthorizationProvider();
            ReplacementFormatter   formatter    = new MethodInvocationFormatter(input);

            if (!authProvider.Authorize(Thread.CurrentPrincipal, formatter.Format(operationName)))
            {
                UnauthorizedAccessException unauthorizedExeption = new UnauthorizedAccessException(Resources.AuthorizationFailed);
                return(input.CreateExceptionMethodReturn(unauthorizedExeption));
            }

            return(getNext().Invoke(input, getNext));
        }
コード例 #17
0
 public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
 {
     Console.WriteLine("Check the authorization of the user role ");
     if (true)
     {
         Console.WriteLine("The user pass the authorization check");
         return(getNext()(input, getNext));
     }
     else
     {
         return(input.CreateExceptionMethodReturn(new Exception("Authorization check failed.")));
     }
 }
コード例 #18
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            Category user = input.Inputs[0] as Category;

            if (user.Id == 0)
            {
                return(input.CreateExceptionMethodReturn(new Exception("密码不能为空")));
            }

            IMethodReturn iMethodResult = getNext()(input, getNext);

            return(iMethodResult);
        }
コード例 #19
0
 private IMethodReturn MethodWithRefParameters_Delegate(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
     try
     {
         string refParam    = (string)input.Arguments[1];
         int    returnValue = BaseMethodWithRefParameters((int)input.Arguments[0], ref refParam, (float)input.Arguments[2]);
         return(input.CreateMethodReturn(returnValue, input.Inputs[0], refParam, input.Inputs[2]));
     }
     catch (Exception ex)
     {
         return(input.CreateExceptionMethodReturn(ex));
     }
 }
コード例 #20
0
 public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
 {
     Console.WriteLine("检查当前用户的权限");
     if (true)
     {
         Console.WriteLine("经检查当前用户拥有权限操作");
         return(getNext()(input, getNext));//执行后面的全部动作
     }
     else
     {
         return(input.CreateExceptionMethodReturn(new Exception("没有权限")));
     }
 }
コード例 #21
0
ファイル: MyLogFrame.cs プロジェクト: fr4nky80/LearnCSharp
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (input.Inputs.Count == 0) { return getNext()(input, getNext); }
            Order order = input.Inputs[0] as Order;
            if (order == null) { return getNext()(input, getNext); }
            if (order.OrderDate > DateTime.Today)
            {
                return input.CreateExceptionMethodReturn(new OrderValidationException("The order date is later than the current date!"));
            }

            if (order.Items.Count == 0)
            {
                return input.CreateExceptionMethodReturn(new OrderValidationException("There are not any items for the order!"));
            }

            if (this.ValidateSupplier)
            {
                if (!LegalSuppliers.Contains<string>(order.Supplier))
                {
                    return input.CreateExceptionMethodReturn(new OrderValidationException("The supplier is inllegal!"));
                }
            }

            if (this.ValidateTotalPrice)
            {
                double totalPrice = 0;
                foreach (OrderItem item in order.Items)
                {
                    totalPrice += item.Quantity * item.UnitPrice;
                }
                if (totalPrice != order.TotalPrice)
                {
                    return input.CreateExceptionMethodReturn(new OrderValidationException("The sum of the order item is not equal to the order total price!"));
                }
            }

            return getNext()(input, getNext);
        }
コード例 #22
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Console.WriteLine("ParameterCheckBehavior");
            User user = input.Inputs[0] as User;

            if (user.MotPass.Length < 10)
            {
                return(input.CreateExceptionMethodReturn(new Exception("MotPass est inférieur au 10 chiffres")));
            }
            else
            {
                return(getNext().Invoke(input, getNext));
            }
        }
		public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
		{
			IMethodReturn result = null;

			if (Transaction.Current == null)
			{
				result = input.CreateExceptionMethodReturn(new Exception("Ambient transaction required"));
			}
			else
			{
				result = getNext()(input, getNext);
			}

			return (result);
		}
コード例 #24
0
        private IMethodReturn OutParams_Delegate(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            try
            {
                int outParam1;
                int outParam2;

                BaseOutParams((int)input.Arguments[0], out outParam1, out outParam2);
                return(input.CreateMethodReturn(null, input.Arguments[0], outParam1, outParam2));
            }
            catch (Exception ex)
            {
                return(input.CreateExceptionMethodReturn(ex));
            }
        }
コード例 #25
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Console.WriteLine("Parameter check");

            User user = input.Inputs[0] as User; //可以不写死类型, 用反射 + 特性完成数据有效性检测

            if (user?.Password.Length < 10)
            {
                //返回异常
                return(input.CreateExceptionMethodReturn(new Exception("Password length must > 10")));
                //throw new Exception("xxx");
            }

            return(getNext()(input, getNext));
        }
コード例 #26
0
        /// <summary>
        /// Performs the operation of the handler.
        /// </summary>
        /// <param name="input">Input to the method call.</param>
        /// <param name="getNext">Delegate used to get the next delegate in the call handler pipeline.</param>
        /// <returns>Returns value from the target method, or an <see cref="UnauthorizedAccessException"/>
        /// if the call fails the authorization check.</returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (input == null) throw new ArgumentNullException("input");
            if (getNext == null) throw new ArgumentNullException("getNext");

            ReplacementFormatter formatter = new MethodInvocationFormatter(input);
            if (!this.AuthorizationProvider.Authorize(Thread.CurrentPrincipal, formatter.Format(OperationName)))
            {
                UnauthorizedAccessException unauthorizedExeption =
                    new UnauthorizedAccessException(Resources.AuthorizationFailed);
                return input.CreateExceptionMethodReturn(unauthorizedExeption);
            }

            return getNext().Invoke(input, getNext);
        }
コード例 #27
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            bool autenticado = true;
            autenticado = ControladorDeSessao.EstaAutenticado();

            if (autenticado)
            {
                IMethodReturn result = getNext()(input, getNext);
                return result;
            }
            else
            {
                // TODO: criar tratamento de erro para autenticacao
                return input.CreateExceptionMethodReturn(new ApplicationValidationErrorsException("Usuário não autenticado."));
            }
        }
コード例 #28
0
ファイル: ParameterCheck.cs プロジェクト: zjza1z/MyCode
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Console.WriteLine("ParameterCheckBehavior");
            User user = input.Inputs[0] as User;//可以不写死类型,反射+特性完成数据有效性监测

            if (user.Password.Length < 5)
            {
                //返回一个包含异常的IMethodReturn
                return(input.CreateExceptionMethodReturn(new Exception("密码长度不能小于10位")));
            }
            else
            {
                Console.WriteLine("参数检测无误");
                return(getNext().Invoke(input, getNext));
            }
        }
コード例 #29
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            System.Console.WriteLine("ParameterCheckBehavior");
            User user = input.Inputs[0] as User;

            if (user.Age < 18)//检查参数
            {
                //返回一个异常
                return(input.CreateExceptionMethodReturn(new Exception("未成年人")));
            }
            else
            {
                System.Console.WriteLine("成年了");
                return(getNext().Invoke(input, getNext));
            }
        }
コード例 #30
0
 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
     try
     {
         using (TransactionScope transactionScope = new TransactionScope())
         {
             IMethodReturn methodReturn = getNext()(input, getNext);
             transactionScope.Complete();
             return methodReturn;
         }
     }
     catch (Exception ex)
     {
         return input.CreateExceptionMethodReturn(ex);
     }
 }
コード例 #31
0
 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
     try
     {
         using (TransactionScope transactionScope = new TransactionScope())
         {
             IMethodReturn methodReturn = getNext()(input, getNext);
             transactionScope.Complete();
             return(methodReturn);
         }
     }
     catch (Exception ex)
     {
         return(input.CreateExceptionMethodReturn(ex));
     }
 }
コード例 #32
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Console.WriteLine("ParameterCheckBehavior");
            //通过特性校验
            User user = input.Inputs[0] as User;

            if (user.Password.Length < 10)
            {
                //throw new Exception();
                return(input.CreateExceptionMethodReturn(new Exception("密码长度不能小于10位")));
            }
            else
            {
                Console.WriteLine("参数检测无误");
                return(getNext().Invoke(input, getNext));
            }
        }
コード例 #33
0
    private static IMethodReturn HandleException(IMethodInvocation input, object[] args, Exception e, IClientChannel channel)
    {
        if (Logger.IsWarnEnabled)
        {
            // we log at Warn, caller might handle this without need to log
            string msg = string.Format("Exception from " + input.MethodBase.Name + "(" + string.Join(", ", args) + ")");
            Logger.Warn(msg, e);
        }
        IMethodReturn result = input.CreateExceptionMethodReturn(e);

        if (channel != null)
        {
            Logger.Trace("Aborting channel");
            channel.Abort();
        }
        return(result);
    }
コード例 #34
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            bool autenticado = true;

            autenticado = ControladorDeSessao.EstaAutenticado();

            if (autenticado)
            {
                IMethodReturn result = getNext()(input, getNext);
                return(result);
            }
            else
            {
                // TODO: criar tratamento de erro para autenticacao
                return(input.CreateExceptionMethodReturn(new AppException("Usuário não autenticado.")));
            }
        }
コード例 #35
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            //throw new NotImplementedException();
            Console.WriteLine("parameter Check behavior");
            User user = input.Inputs[0] as User; //May also constraint to User, use relection+attribute to implement data validation

            if (user.Password.Length < 10)       // Check the length of the password, should over 10
            {
                //Return an exception
                return(input.CreateExceptionMethodReturn(new Exception("Length of password should over 10.")));
            }
            else
            {
                Console.WriteLine("The length of the password is valid");
                return(getNext().Invoke(input, getNext));
            }
        }
コード例 #36
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Console.WriteLine(this.GetType().Name + " Before");

            User user = input.Inputs[0] as User;

            if (user.Name.Length <= 0)
            {
                //返回异常
                return(input.CreateExceptionMethodReturn(new Exception("密码不得为空")));
            }
            else
            {
                Console.WriteLine(this.GetType().Name + " 密码检测正常");
                return(getNext()(input, getNext));
            }
        }
コード例 #37
0
        private IMethodReturn run(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext, TransactionScope transaction = null)
        {
            var result = getNext()(input, getNext);

            if (result.Exception == null)
            {
                if (transaction != null)
                {
                    transaction.Complete();
                }
                return(result);
            }
            else
            {
                return(input.CreateExceptionMethodReturn(result.Exception));
            }
        }
コード例 #38
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            IMethodReturn msg = null;

            if (BUser.CurrentUser != null)
            {
                bool IsAuthorizableService = false;
                foreach (var customAttribute in input.MethodBase.GetCustomAttributes(false))
                {
                    if (customAttribute is ServiceAuthorizeBehavior)
                    {
                        IsAuthorizableService = true;
                        ServiceAuthorizeBehavior SAB = (ServiceAuthorizeBehavior)customAttribute;
                        switch (SAB.serviceAuthorizeState)
                        {
                        case ServiceAuthorizeState.Enforce:
                            ServiceAuthorizeType SAT = this.resourceRepository.CheckServiceAuthorize(BUser.CurrentUser.Role.ID, input);
                            switch (SAT)
                            {
                            case ServiceAuthorizeType.Illegal:
                                msg = input.CreateExceptionMethodReturn(new IllegalServiceAccess("دسترسی غیر مجاز به سرویس", input.Target.ToString()));
                                BaseBusiness <Entity> .LogException(new IllegalServiceAccess("دسترسی غیر مجاز به سرویس", input.Target.ToString()), input.Target.GetType().Name, input.MethodBase.Name);

                                break;

                            case ServiceAuthorizeType.Legal:
                                msg = getNext()(input, getNext);
                                break;
                            }
                            break;

                        case ServiceAuthorizeState.Avoid:
                            msg = getNext()(input, getNext);
                            break;
                        }
                        break;
                    }
                }
                if (!IsAuthorizableService)
                {
                    msg = getNext()(input, getNext);
                }
            }
            return(msg);
        }
コード例 #39
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var methodInfo = (MethodInfo)input.MethodBase;

            // Catch the Dispose() function
            if (ReflectionHelper.IsExplicitMethod(methodInfo, typeof(IDisposable), "Dispose"))
            {
                Dispose();
                return(input.CreateMethodReturn(null));
            }

            if (_connection == null)
            {
                _connection = new PowerShellConnection(_filePath);
            }

            try
            {
                object result    = null;
                var    arguments = input.Arguments.Cast <object>().ToArray();

                // Handle GET property
                if (ReflectionHelper.IsGetProperty(methodInfo))
                {
                    result = _connection.ReadGlobalVariable(ReflectionHelper.GetPropertyName(methodInfo), methodInfo.ReturnType);
                }
                // Handle SET property
                else if (ReflectionHelper.IsSetProperty(methodInfo))
                {
                    _connection.AssignGlobalVariable(ReflectionHelper.GetPropertyName(methodInfo), arguments[0]);
                }
                // Run the function
                else
                {
                    result = _connection.Run(input.MethodBase.Name, methodInfo.ReturnType, arguments);
                }

                // Return the results from the script
                return(input.CreateMethodReturn(result, arguments));
            }
            catch (Exception ex)
            {
                return(input.CreateExceptionMethodReturn(ex));
            }
        }
コード例 #40
0
 /// <summary>
 /// Invoking the Audit Trail related operation.
 /// </summary>
 /// <param name="input">Method Invocation Message.</param>
 /// <param name="getNext">A GetNextHandlerDelegate object delegating the invocation to the next CallHandler or Target instance.</param>
 /// <returns>The return message of the method invocation.</returns>
 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
     IMethodReturn result;
     try
     {
         IMethodReturn methodReturn = getNext()(input, getNext);
         if (methodReturn != null)
         {
             //todo audit
         }
         result = methodReturn;
     }
     catch (Exception ex)
     {
         result = input.CreateExceptionMethodReturn(ex);
     }
     return result;
 }
コード例 #41
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            UserMatch user = input.Inputs[0] as UserMatch;

            if (!user.IsMatch <UserMatch>())
            {
                Console.WriteLine($"显示如下错误信息,发生时间:{DateTime.Now}");
                StringBuilder sb = new StringBuilder();
                foreach (var item in user.MatchesWarnInfo <UserMatch>())
                {
                    var message = $"报错名:{item.Key},数据值:{item.Value}";
                    sb.AppendLine(message);
                    Console.WriteLine(message);
                }
                return(input.CreateExceptionMethodReturn(new Exception(sb.ToString())));
            }
            return(getNext()(input, getNext));
        }
コード例 #42
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Console.WriteLine("ParameterCheckBehavior");

            //业务逻辑执行前,检查一下第一个参数是不是User
            User user = input.Inputs[0] as User;//可以不写死类型,反射+特性完成数据有效性监测
            if (user.Password.Length < 10)//可以过滤一下敏感词
            {
                //返回一个异常
                return input.CreateExceptionMethodReturn(new Exception("密码长度不能小于10位"));
                //注意只要抛出异常, 那么后面的都不会再执行了, 在这里也就是说后的 logafterbehavior是不会再执行了
                //throw new Exception("密码长度不能小于10位");
            }
            else
            {
                Console.WriteLine("参数检测无误");
                return getNext().Invoke(input, getNext);
            }
        }
コード例 #43
0
        /// <summary>
        /// Invokes the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="getNext">The get next.</param>
        /// <returns></returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            Exception ex = null;
            if (input.Inputs.Count != 1) { ex = new ArgumentOutOfRangeException("Action methods can only contains one argument!"); }
            if (input.Inputs[0].GetType() != typeof(string[])) { ex = new ArgumentException("The action method argument must be of type string[]!"); }

            if (Length > -1) {
                var arg = (string[])input.Arguments[0];
                if (arg.Length != Length) { ex = new ArgumentOutOfRangeException("Invalid number of arguments!"); }
            }
            var types = input.MethodBase.GetCustomAttributes(typeof(ArgumentTypeAttribute), true);
            if (types != null && types.Count() > 0) {
                foreach (var tp in types.Cast<ArgumentTypeAttribute>()) {
                    try { Convert.ChangeType(input.Arguments[tp.Index], tp.Type); }
                    catch (InvalidCastException) { ex = new InvalidCastException(string.Format("The argument index: {0} must be of type: {1}!", tp.Index, tp.Type.ToString())); }
                }
            }
            return ex != null ? input.CreateExceptionMethodReturn(ex) : getNext()(input, getNext);
        }
コード例 #44
0
        /// <summary>
        /// Runs the call handler. This does validation on the parameters, and if validation
        /// passes it calls the handler. It throws <see cref="ArgumentValidationException"/>
        /// if validation fails.
        /// </summary>
        /// <param name="input"><see cref="IMethodInvocation"/> containing details of the current call.</param>
        /// <param name="getNext">delegate to call to get the next handler in the pipeline.</param>
        /// <returns>Return value from the target.</returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            for (int index = 0; index < input.Inputs.Count; ++index)
            {
                ParameterInfo inputParameter = input.Inputs.GetParameterInfo(index);
                Validator     validator      = CreateValidator(inputParameter);

                object            parameterValue = input.Inputs[index];
                ValidationResults results        = validator.Validate(parameterValue);

                if (!results.IsValid)
                {
                    ArgumentValidationException exception =
                        new ArgumentValidationException(results, inputParameter.Name);
                    return(input.CreateExceptionMethodReturn(exception));
                }
            }
            return(getNext().Invoke(input, getNext));
        }
コード例 #45
0
    /// <summary>
    /// Invokes the specified input.
    /// </summary>
    /// <param name="input">The input.</param>
    /// <param name="getNext">The get next.</param>
    /// <returns>The method return result.</returns>
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
      foreach (var argument in input.Arguments)
      {
        object target = argument;

        if (target != null)
        {
          continue;
        }

        ArgumentNullException argumentException = new ArgumentNullException(input.MethodBase.Name);
        
        Log.Error("Argument null exception", argumentException, this);
        
        return input.CreateExceptionMethodReturn(argumentException);
      }

      return getNext()(input, getNext);
    }
コード例 #46
0
		/// <summary>
		/// Invokes the Argument Not Null Handler.
		/// </summary>
		/// <param name="input">Inputs to the current call to the target.</param>
		/// <param name="getNext">Delegate to execute to get the next delegate in the handler chain.</param>
		/// <returns>Return value from the target.</returns>
		public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
		{
			for (int argument = 0; argument < input.Inputs.Count; argument++)
			{
				if (input.Inputs[argument] != null)
					continue;

				var parameterInfo = input.Inputs.GetParameterInfo(argument);

				if (parameterInfo.ParameterType.IsValueType ||
					parameterInfo.IsOptional)
				{
					continue;
				}

				return input.CreateExceptionMethodReturn(new ArgumentNullException(parameterInfo.Name));
			}

			return getNext()(input, getNext);
		}
コード例 #47
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            /////自定义代码部分 开始  这部分的代码 会在方法UserProcessor.RegUser 执行前执行
            Users user = input.Inputs[0] as Users;

            if (user.Password.Length < 10)
            {
                return(input.CreateExceptionMethodReturn(new Exception("密码长度不能小于10位")));
            }
            Console.WriteLine("参数检测无误");

            /////自定义代码部分 结束
            IMethodReturn methodReturn = getNext.Invoke().Invoke(input, getNext);

            /////自定义代码部分 开始  这部分的代码 会在方法UserProcessor.RegUser 执行后执行
            /////这里可以写方法
            /////自定义代码部分 结束

            return(methodReturn);
        }
コード例 #48
0
        /// <summary>
        /// Invokes the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="getNext">The get next.</param>
        /// <returns>The method return result.</returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            foreach (var argument in input.Arguments)
            {
                object target = argument;

                if (target != null)
                {
                    continue;
                }

                ArgumentNullException argumentException = new ArgumentNullException(input.MethodBase.Name);

                Log.Error("Argument null exception", argumentException, this);

                return(input.CreateExceptionMethodReturn(argumentException));
            }

            return(getNext()(input, getNext));
        }
コード例 #49
0
		public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
		{
			Boolean isSetter = input.MethodBase.Name.StartsWith("set_");
			IMethodReturn result = null;

			if (isSetter == true)
			{
				if (input.Arguments[0] == null)
				{
					result = input.CreateExceptionMethodReturn(new NullReferenceException("Value is null"));
				}
			}

			if (result == null)
			{
				result = getNext()(input, getNext);
			}

			return (result);
		}
コード例 #50
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (this.allowedRoles.Length > 0)
            {
                IPrincipal currentPrincipal = Thread.CurrentPrincipal;

                if (currentPrincipal != null)
                {
                    bool allowed = allowedRoles.Any(currentPrincipal.IsInRole);
                    if (!allowed)
                    {
                        // short circuit the call
                        return input.CreateExceptionMethodReturn(
                            new UnauthorizedAccessException(
                                "User NOT allowed to invoke the method."));
                    }
                }
            }

            return getNext()(input, getNext);
        }
コード例 #51
0
        /// <summary>
        /// Performs the operation of the handler.
        /// </summary>
        /// <param name="input">Input to the method call.</param>
        /// <param name="getNext">Delegate used to get the next delegate in the call handler pipeline.</param>
        /// <returns>Returns value from the target method, or an <see cref="UnauthorizedAccessException"/>
        /// if the call fails the authorization check.</returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            if (getNext == null)
            {
                throw new ArgumentNullException("getNext");
            }

            ReplacementFormatter formatter = new MethodInvocationFormatter(input);

            if (!this.AuthorizationProvider.Authorize(Thread.CurrentPrincipal, formatter.Format(OperationName)))
            {
                UnauthorizedAccessException unauthorizedExeption =
                    new UnauthorizedAccessException(Resources.AuthorizationFailed);
                return(input.CreateExceptionMethodReturn(unauthorizedExeption));
            }

            return(getNext().Invoke(input, getNext));
        }
コード例 #52
0
 public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
 {
     if(input.Inputs.Count > 0)
     {
         foreach(var inputValue in input.Inputs)
         {
             if(inputValue is Decimal)
             {
                 if((Decimal)inputValue > maxAmount)
                 {
                     MessageBox.Show(
                         string.Format("Amount of {0} is beyond max limit of {1}",
                             inputValue, maxAmount),
                         "Limit Exceeded");
                     return input.CreateExceptionMethodReturn(
                         new InvalidOperationException("Limit Exceeded"));
                 }
             }
         }
     }
     return getNext()(input, getNext);
 }
コード例 #53
0
 /// <summary>
 ///     Invoking the Audit Trail related operation.
 /// </summary>
 /// <param name="input">Method Invocation Message.</param>
 /// <param name="getNext">
 ///     A GetNextHandlerDelegate object delegating the invocation to the next CallHandler or Target
 ///     instance.
 /// </param>
 /// <returns>The return message of the method invocation.</returns>
 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
     IMethodReturn result;
     try
     {
         var auditLogger = AuditLogger.CreateAuditLogger(FunctionName);
         var methodReturn = getNext()(input, getNext);
         if (methodReturn != null)
         {
             //var data = new AuditLogModel()
             //{
             //    ID = Guid.NewGuid().ToString(),
             //    AuditName = FunctionName,
             //    AuditType = input.MethodBase.Name,
             //    Arguments = input.Arguments,
             //    LogDateTime = DateTime.Now,
             //    Result = methodReturn.ReturnValue,
             //    Target = input.Target,
             //    TransactionID = "TransactionID"
             //};
             //try
             //{
             //    auditservice.InsertAuditLog(data);
             //}
             //catch (Exception e)
             //{
             //    //todo add log
             //}
             if (methodReturn.Exception == null)
             {
                 auditLogger.Write(input.MethodBase.Name, string.Empty,
                     JsonConvert.SerializeObject(input.Arguments),
                     JsonConvert.SerializeObject(methodReturn.ReturnValue));
                 auditLogger.Flush();
             }
         }
         result = methodReturn;
     }
     catch (Exception ex)
     {
         result = input.CreateExceptionMethodReturn(ex);
     }
     return result;
 }
コード例 #54
0
        private IMethodReturn HandleCookieExpirationExceptionForIntegration(CommunicationException exception, IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            //Application crashes when launched while Active Directory credentials are expired (often due to not logging off overnight)
             //string ADExpired = "Your credentials have expired";
            string ADExpired = WebSealSettings.GetADAccountExpiredExceptionKeySetting();
             if (exception.Message.Contains(ADExpired))
             {
                 //It will immediately quit
                 return input.CreateExceptionMethodReturn(new ADCredentialsExpiredException());
             }

            WebException webException = exception.InnerException as WebException;
             if (webException == null)
             {
                 //Even if it is sessionRenewException, also will come to here.
                 return input.CreateExceptionMethodReturn(exception);
             }

             if ((!webException.Message.Contains("403")) && (!webException.Message.Contains("401")))
             {
                 return input.CreateExceptionMethodReturn(exception);
             }

             if (HiiP.Framework.Security.AccessControl.Authentication.AuthenticationManager.AuthenticationMode == AuthenticationMode.Integration)
             {
                 HiiP.Framework.Security.AccessControl.Authentication.AuthenticationManager.Login();
                 return this.Invoke(input, getNext);
             }

             return input.CreateExceptionMethodReturn(exception);
        }
コード例 #55
0
        private IMethodReturn HandleCookieExpirationExceptionForForm(Exception exception, IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            //Modify to resolve the password is expired by Qiu Ming on 05/12/2008
            //string passwordExpiredMessage = "<meta name =\"DC.Title\" content=\"Expired Password,";
            string passwordExpiredMessage = WebSealSettings.GetPasswordExpiredExceptionKeySetting();
            if (!string.IsNullOrEmpty(passwordExpiredMessage)
                && exception.Message.Contains(passwordExpiredMessage))
            {
                //It will immediately quit
                return input.CreateExceptionMethodReturn(new UserPasswordExpiredException());
            }

            //Sessino is expired
            //string sessionExpiredKey = "BEGIN Cookie check block";
            string sessionExpiredKey = WebSealSettings.GetSessionExpiredExceptionKeySetting();
            if (!string.IsNullOrEmpty(sessionExpiredKey)
                && exception.Message.Contains(sessionExpiredKey))
            {

                try
                {

                    if (!(input.MethodBase.Module.Name.Contains(".Logging.") && input.MethodBase.Name == "Write")
                       &&  (AppContext.Current.UserID.Length > 0)
                      && (!HiiP.Framework.Security.AccessControl.Authentication.AuthenticationManager.IsOpenLoginForm)
                        )
                    {
                        ExceptionManager.ShowingErrorMessageBox = true;

                        var friendlyExMessage = WebSealSettings.GetSessionExpiredExceptionMessageSetting();

                        if (string.IsNullOrEmpty(friendlyExMessage))
                        {
                            friendlyExMessage = "Your eBusiness Gateway session has expired. Please re-login.";
                        }

                        SessionCredentialsExpiredException sessionCredentialsExpiredException = new SessionCredentialsExpiredException(friendlyExMessage);
                        ExtendedMessageBoxExceptionHandler _messageHandler = new ExtendedMessageBoxExceptionHandler("Error", typeof(NCS.IConnect.ExceptionHandling.TextExceptionFormatter), "{message}", true);
                        _messageHandler.HandleException(sessionCredentialsExpiredException, Guid.NewGuid());

                        StoreExceptionInMemory(sessionCredentialsExpiredException,true);

                        if (HiiP.Framework.Security.AccessControl.Authentication.AuthenticationManager.LoginFormOnCookieOut())
                        {
                            StoreExceptionInMemory(null, false);
                            return this.Invoke(input, getNext);
                        }

                        //return input.CreateExceptionMethodReturn(new SessionCredentialsExpiredException());
                    }
                    return input.CreateExceptionMethodReturn(new SessionCredentialsExpiredException());
                }
                finally
                {
                    ExceptionManager.ShowingErrorMessageBox = false;
                }

            }
            return input.CreateExceptionMethodReturn(exception);
        }
コード例 #56
0
        private IMethodReturn AttachCredentialCookie(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            HttpRequestMessageProperty request;
            if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name))
            {
                request = OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            }
            else
            {
                request = new HttpRequestMessageProperty();
            }

            if (string.IsNullOrEmpty(AppContext.Current.CredentialCookie))
            {
                return input.CreateExceptionMethodReturn(new CredentialCookieAttachingException("No credential cookie is attached in HTTP header."));
            }

            if (request==null)
            {
                throw new BusinessException("No valid request");
            }

            request.Headers[HttpRequestHeader.Cookie] = AppContext.Current.CredentialCookie;
            OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = request;

            return getNext()(input, getNext);
        }
コード例 #57
0
        /// <summary>
        /// Runs the call handler. This does validation on the parameters, and if validation
        /// passes it calls the handler. It throws <see cref="ArgumentValidationException"/>
        /// if validation fails.
        /// </summary>
        /// <param name="input"><see cref="IMethodInvocation"/> containing details of the current call.</param>
        /// <param name="getNext">delegate to call to get the next handler in the pipeline.</param>
        /// <returns>Return value from the target.</returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            if (input == null) throw new ArgumentNullException("input");
            if (getNext == null) throw new ArgumentNullException("getNext");

            for (int index = 0; index < input.Inputs.Count; ++index)
            {
                ParameterInfo inputParameter = input.Inputs.GetParameterInfo(index);
                Validator validator = CreateValidator(inputParameter);

                object parameterValue = input.Inputs[index];
                ValidationResults results = validator.Validate(parameterValue);

                if (!results.IsValid)
                {
                    ArgumentValidationException exception =
                        new ArgumentValidationException(results, inputParameter.Name);
                    return input.CreateExceptionMethodReturn(exception);
                }
            }
            return getNext().Invoke(input, getNext);
        }
コード例 #58
0
 /// <summary>
 ///     Invoking the Audit Trail related operation.
 /// </summary>
 /// <param name="input">Method Invocation Message.</param>
 /// <param name="getNext">
 ///     A GetNextHandlerDelegate object delegating the invocation to the next CallHandler or Target
 ///     instance.
 /// </param>
 /// <returns>The return message of the method invocation.</returns>
 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
     IMethodReturn result;
     try
     {
         var methodReturn = getNext()(input, getNext);
         if (methodReturn != null)
         {
             if (methodReturn.Exception == null)
             {
                 //Task.Run(() => { Log(input, methodReturn); });
             }
         }
         result = methodReturn;
     }
     catch (Exception ex)
     {
         result = input.CreateExceptionMethodReturn(ex);
     }
     return result;
 }