/// <summary>
        /// 将InnerException.Data转换为Xml字符串
        /// <para>不支持Data中Value是集合数组形式存储</para>
        /// </summary>
        /// <param name="frameworkException">FrameworkException</param>
        /// <returns>Xml字符串</returns>
        /// 时间:2016-02-26 13:19
        /// 备注:
        public static string ParseInnerDataToXmlString(this FrameworkException frameworkException)
        {
            ValidateOperator.Begin().NotNull(frameworkException, "FrameworkException");
            string _xmlString = string.Empty;

            if (frameworkException.InnerException != null)
            {
                if (frameworkException.InnerException.Data != null)
                {
                    SerializableDictionary <string, string> _seriableDic = new SerializableDictionary <string, string>();

                    foreach (DictionaryEntry data in frameworkException.InnerException.Data)
                    {
                        _seriableDic.Add(data.Key.ToStringOrDefault(string.Empty), data.Value.ToStringOrDefault(string.Empty));
                    }

                    using (StringWriter sw = new StringWriter())
                    {
                        using (XmlTextWriter writer = new XmlTextWriter(sw))
                        {
                            writer.Formatting = Formatting.Indented;
                            _seriableDic.WriteXml(writer);
                            writer.Flush();
                            _xmlString = sw.ToString().Trim();
                        }
                    }
                }
            }

            return(_xmlString);
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            try
            {
                ArgumentNullException argumentNull2 = new ArgumentNullException("yyyyyy is null");

                NotImplementedException e = new NotImplementedException("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", argumentNull2);

                ArgumentNullException argumentNull = new ArgumentNullException("xxx is null", e);


                argumentNull.Data["KeyArgument"] = "Null Argument";

                FrameworkException exception = new FrameworkException("a message from frameworkException", argumentNull);

                exception.Data["Key"] = "Some";

                throw exception;
            }
            catch (FrameworkException exception)
            {
                foreach (object item in exception.Data.Keys)
                {
                    Console.WriteLine($"{item.ToString()} : {exception.Data[item].ToString()}");
                }
                Console.WriteLine(exception);
            }
        }
Esempio n. 3
0
        public IFrameworkInterceptionReturn Invoker(IFrameworkInterceptionInput input)
        {
            var @return = new FrameworkInterceptionReturn();

            object    invokeResult = null;
            Exception exception    = null;

            try
            {
                if (input.Method.IsStatic)
                {
                    invokeResult = input.Method.Invoke(null, input.Arguments);
                }
                else
                {
                    invokeResult = input.Method.Invoke(input.TargetObject, input.Arguments);
                }
            }
            catch (Exception ex)
            {
                exception = new FrameworkException("Interceptor Exception", ex);
            }

            @return.Value     = invokeResult;
            @return.Exception = exception;

            return(@return);
        }
Esempio n. 4
0
        public static bool Login(string username, string password)
        {
            bool retVal = false;

            try
            {
                using (CruderUserRepository userRepository = new CruderUserRepository())
                {
                    string encryptedPassword = Definition.Cryptology.Encrypt(password);
                    UserEntity userInstance = userRepository.Query(q => q.Username == username && q.Password == encryptedPassword).SingleOrDefault();

                    if (userInstance != null)
                    {
                        UserModel model = MapUserEntityToModel(userInstance);
                        CruderPrincipal.Current.User = model;
                        RenewPrincipalIdentity();

                        retVal = true;
                    }
                }
            }
            catch (Exception e)
            {
                var exception = new FrameworkException("BaseAuthorization.Login()", "An error occurred while logging on.", e);
                throw exception;
            }

            return retVal;
        }
Esempio n. 5
0
        public static bool LoginIfDevelopmentEnvironment()
        {
            bool retVal = false;

            try
            {
                if (Definition.IsDevelopmentEnvironment && CruderPrincipal.Current.User == null)
                {
                    using(CruderUserRepository userRepository = new CruderUserRepository())
                    {
                        UserEntity userInstance = userRepository.Query(user => user.Id == ConfigurationFactory.Application.DevelopmentEnvironmentUserId).SingleOrDefault();

                        if (userInstance != null)
                        {
                            UserModel model = MapUserEntityToModel(userInstance);
                            CruderPrincipal.Current.User = model;
                            RenewPrincipalIdentity();

                            retVal = true;
                        }
                        else
                        {
                            throw new FrameworkException("BaseAuthorization.LoginIfDevelopmentEnvironment()", "Development mode user has not been found.");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                var exception = new FrameworkException("BaseAuthorization.LoginIfDevelopmentEnvironment()", "An error occurred while logging by development mode user.", e);
                throw exception;
            }

            return retVal;
        }
        public IFrameworkInterceptionReturn Invoker(IFrameworkInterceptionInput input)
        {
            var @return = new FrameworkInterceptionReturn();

            object invokeResult = null;
            Exception exception = null;

            try
            {
                if (input.Method.IsStatic)
                {
                    invokeResult = input.Method.Invoke(null, input.Arguments);
                }
                else
                {
                    invokeResult = input.Method.Invoke(input.TargetObject, input.Arguments);
                }
            }
            catch (Exception ex)
            {
                exception = new FrameworkException("Interceptor Exception", ex);
            }

            @return.Value = invokeResult;
            @return.Exception = exception;

            return @return;
        }
Esempio n. 7
0
        public void ProvideFault(
            Exception error,
            MessageVersion version,
            ref Message fault)
        {
            if (error is WebFaultException)
            {
                return;
            }

            object         responseMessage;
            HttpStatusCode responseStatusCode;
            var            localizer = AutofacServiceHostFactory.Container.Resolve <ILocalizer>();

            if (error is UserException)
            {
                var userError = (UserException)error;

                responseStatusCode = HttpStatusCode.BadRequest;
                responseMessage    = new ResponseMessage {
                    UserMessage = localizer[userError.Message, userError.MessageParameters], SystemMessage = userError.SystemMessage
                };
            }
            else if (error is LegacyClientException)
            {
                responseStatusCode = ((LegacyClientException)error).HttpStatusCode;
                responseMessage    = error.Message;
            }
            else if (error is ClientException)
            {
                responseStatusCode = HttpStatusCode.BadRequest;
                responseMessage    = new ResponseMessage {
                    SystemMessage = error.Message
                };
            }
            else
            {
                responseStatusCode = HttpStatusCode.InternalServerError;
                responseMessage    = new ResponseMessage {
                    SystemMessage = FrameworkException.GetInternalServerErrorMessage(localizer, error)
                };
            }

            fault = Message.CreateMessage(version, "", responseMessage,
                                          new System.Runtime.Serialization.Json.DataContractJsonSerializer(responseMessage.GetType()));

            fault.Properties.Add(WebBodyFormatMessageProperty.Name,
                                 new WebBodyFormatMessageProperty(WebContentFormat.Json));

            fault.Properties.Add(HttpResponseMessageProperty.Name,
                                 new HttpResponseMessageProperty {
                StatusCode = responseStatusCode
            });

            var response = WebOperationContext.Current.OutgoingResponse;

            response.ContentType = "application/json; charset=" + response.BindingWriteEncoding.WebName;
            response.StatusCode  = responseStatusCode;
        }
Esempio n. 8
0
 public static ActionResult HandleException(FrameworkException frameworkException, IExecutionContext executionCtx, ISessionContext sessionCtx)
 {
     IExceptionConfig expConfig = ExceptionBag.Get(frameworkException.ErrorId.ToString());
     IActionResultBuilder exceptionBuilder = ActionResultBuilderFactory.Create(expConfig.ResponseType, null);
     ExceptionCommand exceptionCommand = new ExceptionCommand(expConfig);
     ExceptionViewModel exceptionModel = exceptionCommand.Get(executionCtx, sessionCtx);
     return exceptionBuilder.Build(exceptionModel);
 }
Esempio n. 9
0
        public static ActionResult HandleException(FrameworkException frameworkException, IExecutionContext executionCtx, ISessionContext sessionCtx)
        {
            IExceptionConfig     expConfig        = ExceptionBag.Get(frameworkException.ErrorId.ToString());
            IActionResultBuilder exceptionBuilder = ActionResultBuilderFactory.Create(expConfig.ResponseType, null);
            ExceptionCommand     exceptionCommand = new ExceptionCommand(expConfig);
            ExceptionViewModel   exceptionModel   = exceptionCommand.Get(executionCtx, sessionCtx);

            return(exceptionBuilder.Build(exceptionModel));
        }
Esempio n. 10
0
        /// <summary>
        /// 组装失败响应的默认方法
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public virtual Resp BuildFailureResponse(FrameworkException exception)
        {
            Resp resp = new Resp();

            return(new Resp()
            {
                Header = new SoaResponseHeader()
                {
                    ResponseCode = exception.ErrorCode,
                    Remark = exception.Message
                }
            });
        }
Esempio n. 11
0
        public (object response, int statusCode) CreateResponseFromException(Exception error)
        {
            object responseMessage;
            int    responseStatusCode;

            if (error is UserException userException)
            {
                responseStatusCode = StatusCodes.Status400BadRequest;
                responseMessage    = new ResponseMessage
                {
                    UserMessage   = localizer[userException.Message, userException.MessageParameters],
                    SystemMessage = userException.SystemMessage
                };
            }
            else if (error is LegacyClientException legacyClientException)
            {
                responseStatusCode = (int)legacyClientException.HttpStatusCode;
                responseMessage    = legacyClientException.Message;
            }
            else if (error is ClientException clientException)
            {
                responseStatusCode = (int)clientException.HttpStatusCode;
                responseMessage    = new ResponseMessage {
                    SystemMessage = clientException.Message
                };

                // HACK: Old Rhetos plugins could not specify the status code. Here we match by message convention.
                if (clientException.Message == "User is not authenticated." && responseStatusCode == StatusCodes.Status400BadRequest)
                {
                    responseStatusCode = StatusCodes.Status401Unauthorized;
                }
            }
            else if (error is FrameworkException)
            {
                responseStatusCode = StatusCodes.Status500InternalServerError;
                responseMessage    = new ResponseMessage {
                    SystemMessage = FrameworkException.GetInternalServerErrorMessage(localizer, error)
                };
            }
            else
            {
                responseStatusCode = StatusCodes.Status500InternalServerError;
                responseMessage    = new ResponseMessage()
                {
                    SystemMessage = error.Message
                };
            }

            return(responseMessage, responseStatusCode);
        }
Esempio n. 12
0
        public void SendPasswordResetToken(SendPasswordResetTokenParameters parameters)
        {
            if (parameters == null)
            {
                throw new ClientException("It is not allowed to call this authentication service method with no parameters provided.");
            }
            _logger.Trace("SendPasswordResetToken " + parameters.UserName);
            parameters.Validate();

            const string logErrorFormat = "SendPasswordResetToken failed for {0}: {1}";

            try
            {
                string passwordResetToken;
                try
                {
                    var tokenParameters = new GeneratePasswordResetTokenParameters
                    {
                        UserName = parameters.UserName,
                        TokenExpirationInMinutesFromNow = Int32.Parse(ConfigUtility.GetAppSetting("AspNetFormsAuth.SendPasswordResetToken.ExpirationInMinutes") ?? "1440")
                    };
                    passwordResetToken = GeneratePasswordResetTokenInternal(tokenParameters);
                }
                // Providing an error information to the client might be a security issue, because this method allows anonymous access.
                catch (UserException ex)
                {
                    _logger.Trace(logErrorFormat, parameters.UserName, ex);
                    return;
                }
                catch (ClientException ex)
                {
                    _logger.Info(logErrorFormat, parameters.UserName, ex);
                    return;
                }

                // The plugin may choose it's own client error messages (UserException and ClientException will not be suppressed).
                _sendPasswordResetTokenPlugin.Value.SendPasswordResetToken(parameters.UserName, parameters.AdditionalClientInfo, passwordResetToken);
            }
            catch (Exception ex)
            {
                if (ex is UserException || ex is ClientException)
                {
                    ExceptionsUtility.Rethrow(ex);
                }

                // Don't return an internal error to the client. Log it and return a generic error message:
                _logger.Error(logErrorFormat, parameters.UserName, ex);
                throw new FrameworkException(FrameworkException.GetInternalServerErrorMessage(_localizer, ex));
            }
        }
        private Task _WriteFrameworkExceptionOutput(HttpContext context, FrameworkException ex)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)HttpStatusCode.Forbidden;


            var _response = JsonConvert.SerializeObject(new ApiResponse <object>
            {
                Code    = (int)context.Response.StatusCode,
                Message = ex.Message,
                Result  = ex.ResultValue
            });

            return(context.Response.WriteAsync(_response));
        }
Esempio n. 14
0
 /// <summary>
 /// 将字符串反序列化为指定的对象
 /// </summary>
 /// <param name="value"></param>
 /// <typeparam name="T">指定的对象</typeparam>
 /// <returns></returns>
 public static T DeserializeObject <T>(string value)
 {
     if (!string.IsNullOrEmpty(value))
     {
         try
         {
             return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(value));
         }
         catch (Exception ex)
         {
             logger.LogError(ex, "反序列化JSON失败");
             throw FrameworkException.CreateNew($"反序列化JSON失败,值:{value}");
         }
     }
     return(default(T));
 }
Esempio n. 15
0
        /// <summary>
        /// 将字符串反序列化为指定的对象
        /// </summary>
        /// <param name="value"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static object DeserializeObject(string value, Type t)
        {
            //保持与上面函数功能一致
            if (string.IsNullOrEmpty(value))
            {
                return(t.IsValueType ? Activator.CreateInstance(t) : null);
            }

            try
            {
                return(Newtonsoft.Json.JsonConvert.DeserializeObject(value, t));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "反序列化JSON失败");
                throw FrameworkException.CreateNew($"反序列化JSON失败,值:{value}");
            }
        }
Esempio n. 16
0
 /// <summary>
 /// </summary>
 /// <typeparam name="T">类型</typeparam>
 /// <param name="xml">xml文档</param>
 /// <returns></returns>
 public static T XmlToDeserializeObject <T>(string xml)
 {
     try
     {
         System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
         doc.LoadXml(xml);
         if (doc.DocumentElement != null)
         {
             string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc);
             return(JsonConvert.DeserializeObject <T>(json));
         }
     }
     catch (Exception ex)
     {
         logger.LogError(ex, "反序列化XML失败");
         throw FrameworkException.CreateNew($"反序列化XML失败,值:{xml}", ex);
     }
     return(default(T));
 }
Esempio n. 17
0
 /// <summary>ExceptionのMessageIDを返す。</summary>
 /// <param name="ex">Exception</param>
 /// <returns>ExceptionのMessageID</returns>
 private string GetExceptionMessageID(Exception ex)
 {
     // Check exception type
     if (ex is BusinessSystemException)
     {
         // システム例外
         BusinessSystemException bsEx = (BusinessSystemException)ex;
         return(bsEx.messageID);
     }
     else if (ex is FrameworkException)
     {
         // フレームワーク例外
         FrameworkException fxEx = (FrameworkException)ex;
         return(fxEx.messageID);
     }
     else
     {
         // それ以外の例外
         return("other Exception");
     }
 }
Esempio n. 18
0
        /// <summary>例外発生時に、エラー画面に画面遷移</summary>
        /// <param name="ex">例外オブジェクト</param>
        /// <remarks>他から呼び出し可能に変更(static)</remarks>
        public static void TransferErrorScreen2(Exception ex)
        {
            #region 例外型を判別しエラーメッセージIDを取得

            // エラーメッセージ
            string err_msg;

            // エラー情報をセッションから取得
            string err_info;

            // エラーのタイプ
            string[] arrErrType = ex.GetType().ToString().Split('.');
            string   errType    = arrErrType[arrErrType.Length - 1];

            // エラーメッセージID
            string errMsgId = "";

            // #21-start
            if (errType == "BusinessSystemException")
            {
                // システム例外
                BusinessSystemException bsEx = (BusinessSystemException)ex;
                errMsgId = bsEx.messageID;
            }
            else if (errType == "FrameworkException")
            {
                // フレームワーク例外
                FrameworkException fxEx = (FrameworkException)ex;
                errMsgId = fxEx.messageID;
            }
            else
            {
                // それ以外の例外
                errMsgId = "-";
            }
            // #21-end

            #endregion

            // 2009/07/31-start

            #region エラー時に、セッションを開放しないで、業務を続行可能にする処理を追加。

            // 不正操作エラー or 画面遷移制御チェック エラー
            if (errMsgId == "IllegalOperationCheckError" ||
                errMsgId == "ScreenControlCheckError")
            {
                // セッションをクリアしない
                HttpContext.Current.Items.Add(FxHttpContextIndex.SESSION_ABANDON_FLAG, false);
            }
            else
            {
                // セッションをクリアする
                HttpContext.Current.Items.Add(FxHttpContextIndex.SESSION_ABANDON_FLAG, true);
            }

            #endregion

            // 2009/07/31-end

            #region エラー画面に表示するエラー情報を作成

            err_msg = System.Environment.NewLine +
                      "エラーメッセージID: " + errMsgId + System.Environment.NewLine +
                      "エラーメッセージ: " + ex.Message.ToString();

            // #19-start
            err_info = System.Environment.NewLine +
                       "対象URL: " + HttpContext.Current.Request.Url.ToString() + System.Environment.NewLine +
                       "スタックトレース:" + ex.StackTrace.ToString() + System.Environment.NewLine +
                       "Exception.ToString():" + ex.ToString();
            // #19-end

            // Form情報を出力するために、遷移方法をServer.Transferに変更。
            // また、情報受け渡しを、HttpContextに変更。

            HttpContext.Current.Items.Add(FxHttpContextIndex.SYSTEM_EXCEPTION_MESSAGE, err_msg);
            HttpContext.Current.Items.Add(FxHttpContextIndex.SYSTEM_EXCEPTION_INFORMATION, err_info);

            #endregion

            // エラー画面へのパスを取得 --- チェック不要(ベースクラスでチェック済み)
            string errorScreenPath = GetConfigParameter.GetConfigValue(FxLiteral.ERROR_SCREEN_PATH);

            // エラー画面へ画面遷移
            HttpContext.Current.Server.Transfer(errorScreenPath);
        }
Esempio n. 19
0
        public void ProvideFault(
            Exception error,
            MessageVersion version,
            ref Message fault)
        {
            if (error is WebFaultException)
            {
                return;
            }

            object         responseMessage;
            HttpStatusCode responseStatusCode;
            var            localizer = AutofacServiceHostFactory.Container.Resolve <ILocalizer>();

            if (error is UserException userException)
            {
                responseStatusCode = HttpStatusCode.BadRequest;
                responseMessage    = new ResponseMessage
                {
                    UserMessage   = localizer[userException.Message, userException.MessageParameters],
                    SystemMessage = userException.SystemMessage
                };
            }
            else if (error is LegacyClientException legacyClientException)
            {
                responseStatusCode = legacyClientException.HttpStatusCode;
                responseMessage    = legacyClientException.Message;
            }
            else if (error is ClientException clientException)
            {
                responseStatusCode = clientException.HttpStatusCode;
                responseMessage    = new ResponseMessage {
                    SystemMessage = clientException.Message
                };

                // HACK: Old Rhetos plugins could not specify the status code. Here we match by message convention.
                if (clientException.Message == "User is not authenticated." && responseStatusCode == HttpStatusCode.BadRequest)
                {
                    responseStatusCode = HttpStatusCode.Unauthorized;
                }
            }
            else if (error is InvalidOperationException && error.Message.StartsWith("The incoming message has an unexpected message format 'Raw'"))
            {
                responseStatusCode = HttpStatusCode.BadRequest;
                responseMessage    = new ResponseMessage
                {
                    SystemMessage = "The incoming message has an unexpected message format 'Raw'. Set the Content-Type to 'application/json'." +
                                    " " + FrameworkException.SeeLogMessage(error)
                };
            }
            else if (error is SerializationException && !error.StackTrace.ToString().Contains("Rhetos"))
            {
                responseStatusCode = HttpStatusCode.BadRequest;
                responseMessage    = new ResponseMessage
                {
                    SystemMessage = "Serialization error: Please check if the request body has a valid JSON format."
                                    + " " + FrameworkException.SeeLogMessage(error)
                };
            }
            else
            {
                responseStatusCode = HttpStatusCode.InternalServerError;
                responseMessage    = new ResponseMessage {
                    SystemMessage = FrameworkException.GetInternalServerErrorMessage(localizer, error)
                };
            }

            fault = Message.CreateMessage(version, "", responseMessage,
                                          new System.Runtime.Serialization.Json.DataContractJsonSerializer(responseMessage.GetType()));

            fault.Properties.Add(WebBodyFormatMessageProperty.Name,
                                 new WebBodyFormatMessageProperty(WebContentFormat.Json));

            fault.Properties.Add(HttpResponseMessageProperty.Name,
                                 new HttpResponseMessageProperty {
                StatusCode = responseStatusCode
            });

            var response = WebOperationContext.Current.OutgoingResponse;

            response.ContentType = "application/json; charset=" + response.BindingWriteEncoding.WebName;
            response.StatusCode  = responseStatusCode;
        }
Esempio n. 20
0
        /// <summary>
        /// See ISqlUtility.InterpretSqlException.
        /// </summary>
        public RhetosException InterpretSqlException(Exception exception)
        {
            if (exception == null || exception is RhetosException)
            {
                return(null);
            }

            var sqlException = (SqlException)ExtractSqlException(exception);

            if (sqlException == null)
            {
                return(null);
            }

            //=========================
            // Detect user message in SQL error:

            const int userErrorCode = 101; // Rhetos convention for an error raised in SQL that is intended as a message to the end user.

            if (sqlException.State == userErrorCode)
            {
                return(new UserException(sqlException.Message, exception));
            }

            if (sqlException.Errors != null)
            {
                foreach (var sqlError in sqlException.Errors.Cast <SqlError>().OrderBy(e => e.LineNumber))
                {
                    if (sqlError.State == userErrorCode)
                    {
                        return(new UserException(sqlError.Message, exception));
                    }
                }
            }

            //=========================
            // Detect system errors:

            if (sqlException.Number == 229 || sqlException.Number == 230)
            {
                if (sqlException.Message.Contains("permission was denied"))
                {
                    return(new FrameworkException("Rhetos server lacks sufficient database permissions for this operation. Please make sure that Rhetos Server process has db_owner role for the database.", exception));
                }
            }

            //=========================
            // Detect UNIQUE constraint:

            if (sqlException.Number == 2601)
            {
                // See the InterpretUniqueConstraint unit test for regex coverage.
                Regex messageParser = new Regex(@"^Cannot insert duplicate key row in object '(.+)' with unique index '(.+)'\.( The duplicate key value is \((.+)\)\.)?");
                var   parts         = messageParser.Match(sqlException.Message).Groups;

                var interpretedException = new UserException("It is not allowed to enter a duplicate record.", exception);

                interpretedException.Info["Constraint"] = "Unique";
                if (parts[1].Success)
                {
                    interpretedException.Info["Table"] = parts[1].Value;
                }
                if (parts[2].Success)
                {
                    interpretedException.Info["ConstraintName"] = parts[2].Value;
                }
                if (parts[4].Success)
                {
                    interpretedException.Info["DuplicateValue"] = parts[4].Value;
                }

                return(interpretedException);
            }

            //=========================
            // Detect REFERENCE constraint:

            if (sqlException.Number == 547)
            {
                // See the InterpretReferenceConstraint unit test for regex coverage.
                Regex  messageParser  = new Regex(@"^(The )?(.+) statement conflicted with (the )?(.+) constraint [""'](.+)[""']. The conflict occurred in database [""'](.+)[""'], table [""'](.+?)[""'](, column [""'](.+?)[""'])?");
                var    parts          = messageParser.Match(sqlException.Message).Groups;
                string action         = parts[2].Value ?? "";
                string constraintType = parts[4].Value ?? "";

                if (_referenceConstraintTypes.Contains(constraintType))
                {
                    UserException interpretedException = null;
                    if (action == "DELETE")
                    {
                        interpretedException = new UserException("It is not allowed to delete a record that is referenced by other records.", new string[] { parts[7].Value, parts[9].Value }, null, exception);
                    }
                    else if (action == "INSERT")
                    {
                        interpretedException = new UserException("It is not allowed to enter the record. The entered value references nonexistent record.", new string[] { parts[7].Value, parts[9].Value }, null, exception);
                    }
                    else if (action == "UPDATE")
                    {
                        interpretedException = new UserException("It is not allowed to edit the record. The entered value references nonexistent record.", new string[] { parts[7].Value, parts[9].Value }, null, exception);
                    }

                    if (interpretedException != null)
                    {
                        interpretedException.Info["Constraint"] = "Reference";
                        interpretedException.Info["Action"]     = action;
                        if (parts[5].Success)
                        {
                            interpretedException.Info["ConstraintName"] = parts[5].Value; // The FK constraint name is ambiguous: The error does not show the schema name and the base table that the INSERT or UPDATE actually happened.
                        }
                        if (parts[7].Success)
                        {
                            interpretedException.Info[action == "DELETE" ? "DependentTable" : "ReferencedTable"] = parts[7].Value;
                        }
                        if (parts[9].Success)
                        {
                            interpretedException.Info[action == "DELETE" ? "DependentColumn" : "ReferencedColumn"] = parts[9].Value;
                        }

                        return(interpretedException);
                    }
                }
            }

            //=========================
            // Detect PRIMARY KEY constraint:

            if (sqlException.Number == 2627 && sqlException.Message.StartsWith("Violation of PRIMARY KEY constraint"))
            {
                Regex messageParser = new Regex(@"^Violation of PRIMARY KEY constraint '(.+)'\. Cannot insert duplicate key in object '(.+)'\.( The duplicate key value is \((.+)\)\.)?");
                var   parts         = messageParser.Match(sqlException.Message).Groups;

                var interpretedException = new FrameworkException(InsertingDuplicateIdMessage, exception);

                interpretedException.Info["Constraint"] = "Primary key";
                if (parts[1].Success)
                {
                    interpretedException.Info["ConstraintName"] = parts[1].Value;
                }
                if (parts[2].Success)
                {
                    interpretedException.Info["Table"] = parts[2].Value;
                }
                if (parts[4].Success)
                {
                    interpretedException.Info["DuplicateValue"] = parts[4].Value;
                }

                return(interpretedException);
            }

            return(null);
        }
Esempio n. 21
0
        public ProcessingResult ExecuteInner(IList <ICommandInfo> commands, Guid executionId)
        {
            var authorizationMessage = _authorizationManager.Authorize(commands);

            if (!string.IsNullOrEmpty(authorizationMessage))
            {
                return new ProcessingResult
                       {
                           UserMessage   = authorizationMessage,
                           SystemMessage = authorizationMessage,
                           Success       = false
                       }
            }
            ;

            var commandResults = new List <CommandResult>();
            var stopwatch      = Stopwatch.StartNew();

            foreach (var commandInfo in commands)
            {
                try
                {
                    _logger.Trace("Executing command {0}.", commandInfo);

                    var implementations = _commandRepository.GetImplementations(commandInfo.GetType());

                    if (implementations.Count() == 0)
                    {
                        throw new FrameworkException(string.Format(CultureInfo.InvariantCulture,
                                                                   "Cannot execute command \"{0}\". There are no command implementations loaded that implement the command.", commandInfo));
                    }

                    if (implementations.Count() > 1)
                    {
                        throw new FrameworkException(string.Format(CultureInfo.InvariantCulture,
                                                                   "Cannot execute command \"{0}\". It has more than one implementation registered: {1}.", commandInfo, String.Join(", ", implementations.Select(i => i.GetType().Name))));
                    }

                    var commandImplementation = implementations.Single();
                    _logger.Trace("Executing implementation {0}.", commandImplementation.GetType().Name);

                    var commandObserversForThisCommand = _commandObservers.GetImplementations(commandInfo.GetType());
                    stopwatch.Restart();

                    foreach (var commandObeserver in commandObserversForThisCommand)
                    {
                        commandObeserver.BeforeExecute(commandInfo);
                        _performanceLogger.Write(stopwatch, () => "ProcessingEngine: CommandObeserver.BeforeExecute " + commandObeserver.GetType().FullName);
                    }

                    CommandResult commandResult;
                    try
                    {
                        commandResult = commandImplementation.Execute(commandInfo);
                    }
                    finally
                    {
                        _performanceLogger.Write(stopwatch, () => "ProcessingEngine: Command executed (" + commandImplementation + ": " + commandInfo + ").");
                    }
                    _logger.Trace("Execution result message: {0}", commandResult.Message);

                    if (commandResult.Success)
                    {
                        foreach (var commandObeserver in commandObserversForThisCommand)
                        {
                            commandObeserver.AfterExecute(commandInfo, commandResult);
                            _performanceLogger.Write(stopwatch, () => "ProcessingEngine: CommandObeserver.AfterExecute " + commandObeserver.GetType().FullName);
                        }
                    }

                    commandResults.Add(commandResult);

                    if (!commandResult.Success)
                    {
                        _persistenceTransaction.DiscardChanges();

                        var systemMessage = "Command failed: " + commandImplementation + ", " + commandInfo + ".";
                        return(LogAndReturnError(commandResults, systemMessage + " " + commandResult.Message, systemMessage, commandResult.Message, null, commands, executionId));
                    }
                }
                catch (Exception ex)
                {
                    _persistenceTransaction.DiscardChanges();

                    if (ex is TargetInvocationException && ex.InnerException is RhetosException)
                    {
                        _logger.Trace(() => "Unwrapping exception: " + ex.ToString());
                        ex = ex.InnerException;
                    }

                    string userMessage   = null;
                    string systemMessage = null;

                    ex = _sqlUtility.InterpretSqlException(ex) ?? ex;

                    if (ex is UserException)
                    {
                        var userException = (UserException)ex;
                        userMessage   = _localizer[userException.Message, userException.MessageParameters]; // TODO: Remove this code after cleaning the double layer of exceptions in the server response call stack.
                        systemMessage = userException.SystemMessage;
                    }
                    else if (ex is ClientException)
                    {
                        userMessage   = _clientExceptionUserMessage;
                        systemMessage = ex.Message;
                    }
                    else
                    {
                        userMessage   = null;
                        systemMessage = FrameworkException.GetInternalServerErrorMessage(_localizer, ex);
                    }

                    return(LogAndReturnError(commandResults, "Command failed: " + commandInfo + ".", systemMessage, userMessage, ex, commands, executionId));
                }
            }

            return(new ProcessingResult
            {
                CommandResults = commandResults.ToArray(),
                Success = true,
                SystemMessage = null
            });
        }
Esempio n. 22
0
        public static DynamicQueryParameters Parse(QueryCriterias queryCriterias, Type entityType)
        {
            DynamicQueryParameters retVal = new DynamicQueryParameters();

            try
            {
                retVal.Values = new object[queryCriterias.Count()];
                int counter = 0;

                for (int i = 0; i < queryCriterias.Count(); i++)
                {
                    if (!string.IsNullOrWhiteSpace(retVal.Query))
                    {
                        retVal.Query = retVal.Query + " AND ";
                    }

                    var iterator = queryCriterias.Skip(i).Take(1).First();
                    string key = iterator.Key;
                    string value = iterator.Value;
                    string memberTypeName = string.Empty;
                    Type memberType = entityType;

                    foreach (var item in key.Split('.'))
                    {
                        if (memberType.GetProperty(item) != null)
                        {
                            memberType = memberType.GetProperty(item).PropertyType;
                        }
                        else if (memberType.GetField(item) != null)
                        {
                            memberType = memberType.GetField(item).FieldType;
                        }
                        else
                        {
                            throw new FrameworkException("QueryCriterias.ToDynamicQuery()", string.Format("No member found for given '{0}' property/field name.", item));
                        }
                    }

                    memberTypeName = memberType.Name.ToLowerInvariant();

                    if (memberTypeName.Contains("int") ||
                        memberTypeName.Contains("double") ||
                        memberTypeName.Contains("float") ||
                        memberTypeName.Contains("decimal"))
                    {
                        if (iterator.Option == CriteriaOptionEnum.Equals)
                            retVal.Query = retVal.Query + string.Format("{0}=@{1}", key, counter);
                        else if (iterator.Option == CriteriaOptionEnum.Greater)
                            retVal.Query = retVal.Query + string.Format("{0}>@{1}", key, counter);
                        else if (iterator.Option == CriteriaOptionEnum.NotEquals)
                            retVal.Query = retVal.Query + string.Format("{0}!=@{1}", key, counter);
                        else if (iterator.Option == CriteriaOptionEnum.Smaller)
                            retVal.Query = retVal.Query + string.Format("{0}<@{1}", key, counter);

                        retVal.Values[i] = decimal.Parse(value);
                        counter++;
                    }
                    else if (memberTypeName.Contains("bool") ||
                        memberTypeName.Contains("nullable"))
                    {
                        retVal.Query = retVal.Query + string.Format("{0}={1}", key, value.ToLowerInvariant() == "null" ? "null" : value);
                        counter++;
                    }
                    else if (memberType.IsEnum)
                    {
                        if (iterator.Option == CriteriaOptionEnum.Equals)
                            retVal.Query = retVal.Query + string.Format("{0}=\"{1}\"", key, value); 
                        else if (iterator.Option == CriteriaOptionEnum.NotEquals)
                            retVal.Query = retVal.Query + string.Format("{0}!=\"{1}\"", key, value);

                        counter++;
                    }
                    else if (memberTypeName.Contains("string"))
                    {
                        if (iterator.Option == CriteriaOptionEnum.Equals)
                            retVal.Query = retVal.Query + string.Format("{0}.Equals(@{1})", key, counter);
                        else if (iterator.Option == CriteriaOptionEnum.NotEquals)
                            retVal.Query = retVal.Query + string.Format("!{0}.Equals(@{1})", key, counter);
                        else if (iterator.Option == CriteriaOptionEnum.Contains)
                            retVal.Query = retVal.Query + string.Format("{0}.Contains(@{1})", key, counter);
                        else if (iterator.Option == CriteriaOptionEnum.NotContains)
                            retVal.Query = retVal.Query + string.Format("!{0}.Contains(@{1})", key, counter);

                        retVal.Values[i] = value;
                        counter++;
                    }
                    else if (memberTypeName.Contains("guid"))
                    {
                        retVal.Query = retVal.Query + string.Format("{0}.Equals(@{1})", key, counter);
                        retVal.Values[i] = value;
                        counter++;
                    }
                    else
                    {
                        retVal.Query = retVal.Query + string.Format("{0}.Contains(@{1})", key, counter);
                        retVal.Values[i] = value;
                        counter++;
                    }
                }
            }
            catch (Exception e)
            {
                var exception = new FrameworkException("QueryCriterias.ToDynamicQuery()", "An error occurred while Dynamic Query Parameter parsing.", e);
                throw exception;
            }

            return retVal;
        }
 public static void HandleFrameworkException(FrameworkException frameworkException)
 {
     MessageBox.Show(frameworkException.Message, "Defraser", MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1);
 }