Пример #1
0
        public void Response_does_equal_ctor_parameter()
        {
            var response = new Response("Something bad happened.");
            var ex       = new ResponseException(response);

            Assert.True(ex.Response == response);
        }
Пример #2
0
        public void ToString_does_include_response_message()
        {
            var response = new Response("Something bad happened.");
            var ex       = new ResponseException(response);

            Assert.Equal("ResponseException: ErrorMessage: Something bad happened.", ex.ToString());
        }
Пример #3
0
        public void ctor_String_does_create_error_response()
        {
            var ex = new ResponseException("*Error*");

            Assert.False(ex.Response.Success);
            Assert.Equal("*Error*", ex.Response.ErrorMessage);
        }
Пример #4
0
        public void ToString_does_indicate_success_string_if_response_success()
        {
            var response = new Response(success: true);
            var ex       = new ResponseException(response);

            Assert.Equal("ResponseException: Success: True", ex.ToString());
        }
        public void TestCreateException_获取单个商品失败()
        {
            string xml = ""
                + "<error_rsp>"
                + "    <args>"
                + "        <arg name=\"api_key\"><![CDATA[12003014]]></arg>"
                + "        <arg name=\"fields\"><![CDATA[iid,title,nick,detail_url,type,cid,desc,product_id,pic_path,num,approve_status,itemimg,propImg]]></arg>"
                + "        <arg name=\"format\"><![CDATA[xml]]></arg>"
                + "        <arg name=\"iid\"><![CDATA[302a0499bf58d002ee05aa07f523f3f9]]></arg>"
                + "        <arg name=\"method\"><![CDATA[taobao.item.get]]></arg>"
                + "        <arg name=\"nick\"><![CDATA[fengxiangxia]]></arg>"
                + "        <arg name=\"sign\"><![CDATA[3055A4992C1D523D68FE1EA35C1576F3]]></arg>"
                + "        <arg name=\"timestamp\"><![CDATA[2009-07-28 05:08:24]]></arg>"
                + "        <arg name=\"v\"><![CDATA[1.0]]></arg>"
                + "    </args>"
                + "    <code>551</code>"
                + "    <msg><![CDATA[Item service unavailable:获取单个商品失败]]></msg>"
                + "</error_rsp>";

            ResponseException ex = new ResponseException(xml);
            Assert.AreEqual(xml, ex.ErrorXml);
            Assert.AreEqual("551", ex.ErrorCode);
            Assert.AreEqual("Item service unavailable:获取单个商品失败", ex.ErrorDescription);
            Assert.AreEqual(9, ex.ArgList.Count);
            string msg = "api_key: 12003014\n"
                + "fields: iid,title,nick,detail_url,type,cid,desc,product_id,pic_path,num,approve_status,itemimg,propImg\n"
                + "format: xml\n"
                + "iid: 302a0499bf58d002ee05aa07f523f3f9\n"
                + "method: taobao.item.get\n"
                + "nick: fengxiangxia\n"
                + "sign: 3055A4992C1D523D68FE1EA35C1576F3\n"
                + "timestamp: 2009-07-28 05:08:24\n"
                + "v: 1.0\n";
            Assert.AreEqual(msg, ex.ToArgListString());
        }
Пример #6
0
        private Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            var error = new ResponseException();
            var code  = HttpStatusCode.InternalServerError; // 500 if unexpected

            if (exception is NotFoundException)
            {
                code = HttpStatusCode.NotFound;
                NotFoundException notFoundException = (NotFoundException)exception;
                error = ConvertToExceptionResponse(notFoundException.code, notFoundException.message, notFoundException.messageObject);
            }
            else if (exception is ValidationException)
            {
                code = HttpStatusCode.BadRequest;
                ValidationException validationException = (ValidationException)exception;
                error = ConvertToExceptionResponse(validationException.code, validationException.message, validationException.messageObject);
            }
            else
            {
                code  = HttpStatusCode.InternalServerError;
                error = ConvertToExceptionResponse("999999", exception.Message, exception.Message);
            }

            //else if (exception is MyUnauthorizedException) code = HttpStatusCode.Unauthorized;
            //else if (exception is MyException) code = HttpStatusCode.BadRequest;
            //if (exception is BaseException) code = HttpStatusCode.BadRequest;

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)code;
            return(context.Response.WriteAsync(JsonConvert.SerializeObject(error)));
        }
Пример #7
0
        public void TestNoStatusCode()
        {
            Response          response = new Response(null);
            ResponseException error    = new ResponseException(response);

            Assert.IsTrue(error.ToString() == "amadeus.exceptions.ResponseException: [---]");
        }
Пример #8
0
        public async static Task MainAsync(string[] args)
        {
            MasterFile masterFile = new MasterFile();
            DnsServer  server     = new DnsServer(masterFile, "8.8.8.8");

            masterFile.remo

            foreach (string domain in args)
            {
                Console.WriteLine("Redirecting {0} to localhost", domain);
                masterFile.AddIPAddressResourceRecord(domain, "127.0.0.1");
            }

            server.Responded += (sender, e) => Console.WriteLine("{0} => {1}", e.Request, e.Response);
            server.Listening += (sender, e) => Console.WriteLine("Listening");
            server.Errored   += (sender, e) => {
                Console.WriteLine("Errored: {0}", e.Exception);
                ResponseException responseError = e.Exception as ResponseException;
                if (responseError != null)
                {
                    Console.WriteLine(responseError.Response);
                }
            };

            await server.Listen();
        }
Пример #9
0
        // Detects of any exceptions have occured and throws the appropriate exceptions.
        protected internal virtual void DetectError(HTTPClient client)
        {
            ResponseException exception = null;
            string            reason    = string.Format("{0} {1}", StatusCode, ReasonPhrase);

            if (StatusCode >= 500)
            {
                exception = new ServerException(this, new Exception(reason));
            }
            else if (StatusCode == 404)
            {
                exception = new NotFoundException(this, new Exception(reason));
            }
            else if (StatusCode == 401)
            {
                exception = new AuthenticationException(this, new Exception(reason));
            }
            else if (StatusCode >= 400)
            {
                exception = new ClientException(this, new Exception(reason));
            }
            else if (!Parsed)
            {
                exception = new ParserException(this, new Exception(reason));
            }

            if (exception != null)
            {
                exception.Log(client.Configuration, this);
                throw exception;
            }
        }
Пример #10
0
                public void ReadSSET(out int LogUploadPeriod, out int LogMaxSize, out string AppTraceLevel, out string ComTraceLevel, bool optionalCloseConn = false)
                {
                    List <string> resps = SendCommand("SSET?", 1, optionalCloseConn);

                    string[] Vals = resps[0].Split('=');
                    if (Vals.Length != 2)
                    {
                        ResponseException ex = new ResponseException("Invalid response received.", "SSET?", resps);
                        LogMsg(TraceEventType.Warning, ex.ToString());
                        throw ex;
                    }

                    Vals = Vals[1].Split(',');

                    if (Vals.Length != 4)
                    {
                        ResponseException ex = new ResponseException("Invalid response received.", "SSET?", resps);
                        LogMsg(TraceEventType.Warning, ex.ToString());
                        throw ex;
                    }

                    try
                    {
                        LogUploadPeriod = Convert.ToInt32(Vals[0]);
                        LogMaxSize      = Convert.ToInt32(Vals[1]);
                        AppTraceLevel   = Vals[2];
                        ComTraceLevel   = Vals[3];
                    }
                    catch (Exception ex)
                    {
                        ResponseException exe = new ResponseException("Exception occured when parsing the response received.", "SSET?", resps, ex);
                        LogMsg(TraceEventType.Warning, exe.ToString());
                        throw ex;
                    }
                }
Пример #11
0
        // Detects of any exceptions have occured and throws the appropriate exceptions.
        internal void detectError()
        {
            ResponseException exception = null;

            if (statusCode >= 500)
            {
                exception = new ServerException(this);
            }
            else if (statusCode == 404)
            {
                exception = new NotFoundException(this);
            }
            else if (statusCode == 401)
            {
                exception = new AuthenticationException(this);
            }
            else if (statusCode >= 400)
            {
                exception = new ClientException(this);
            }
            else if (!parsed)
            {
                exception = new ParserException(this);
            }

            if (exception != null)
            {
                throw exception;
            }
        }
        private async Task HandleResponseException(string compileQuery, ResponseException responseException, int retry)
        {
            if (responseException.StatusAttributes.TryGetValue("x-ms-status-code", out var s))
            {
                if ((long)s == 429)
                {
                    var waitTime = responseException.StatusAttributes["x-ms-retry-after-ms"] as long? ?? 200;
                    await Task.Delay((int)waitTime);

                    if (retry > 5)
                    {
                        Log(compileQuery, responseException);
                        throw responseException;
                    }
                }
                else
                {
                    Log(compileQuery, responseException);
                    throw responseException;
                }
            }
            else
            {
                Log(compileQuery, responseException);
                throw responseException;
            }
        }
Пример #13
0
        public void ResponseException_ShouldHaveCustomError()
        {
            var errorResponse     = new ErrorResponse("", System.Net.HttpStatusCode.NotFound);
            var responseException = new ResponseException(errorResponse);

            responseException.Should().NotBeNull();
            responseException.ResponseError.Should().NotBeNull();
        }
Пример #14
0
        public void ResponseException_ShouldNotHaveCustomError()
        {
            var responseException = new ResponseException("Response Error Message", new System.Exception());

            responseException.Should().NotBeNull();
            responseException.Message.Should().NotBeNullOrWhiteSpace().And.Should().Equals("Response Error Message");
            responseException.InnerException.Should().NotBeNull();
            responseException.ResponseError.Should().BeNull();
        }
Пример #15
0
        public IEnumerable <T> ParseCollection <T>(IServerResponse modelElementJSON) where T : ModelElement
        {
            ResponseException ex = null;

            try { ex = JsonConvert.DeserializeObject <ResponseException>(modelElementJSON.Data); }
            catch { return(JsonConvert.DeserializeObject <IEnumerable <T> >(modelElementJSON.Data)); }

            throw ex;
        }
Пример #16
0
        public static int CosmosDbStatusCode(this ResponseException source)
        {
            if (!source.StatusAttributes.TryGetValue("x-ms-status-code", out var code))
            {
                throw new InvalidOperationException("Header 'x-ms-status-code' is not presented.");
            }

            return(int.Parse(code.ToString()));
        }
Пример #17
0
        public static TimeSpan CosmosDbRetryAfter(this ResponseException source)
        {
            if (!source.StatusAttributes.TryGetValue("x-ms-retry-after-ms", out var time))
            {
                throw new InvalidOperationException("Header 'x-ms-retry-after-ms' is not presented.");
            }

            return(TimeSpan.Parse(time.ToString()));
        }
Пример #18
0
        public async static Task DNSAsync(string[] Domains, string[] localIPs, List <string> BlackList)
        {
            if (localIPs != null && localIPs.Length > 0)
            {
                // if one wants to use a remote DNS server for requests that cannot be solved:
                // DnsServer server = new DnsServer("8.8.8.8");
                DnsServer server = new DnsServer("0.0.0.0", true);
                MainWindow.dnsServerList.Add(server);

                if (BlackList != null && BlackList.Count > 0)
                {
                    foreach (string blacklistentry in BlackList)
                    {
                        Console.WriteLine(MainWindow.InfoTag + " Redirecting {0} to 0.0.0.0", blacklistentry);
                        MainWindow.AddToLogDNS(String.Format(MainWindow.InfoTag + " Redirecting {0} to 0.0.0.0", blacklistentry));
                        server.MasterFile.AddIPAddressResourceRecord(blacklistentry, "0.0.0.0");
                    }
                }

                foreach (string localIP in localIPs)
                {
                    Console.WriteLine(MainWindow.InfoTag + " DNSAsync localIP: " + localIP);

                    foreach (string domain in Domains)
                    {
                        Console.WriteLine();
                        MainWindow.AddToLogDNS(String.Format(MainWindow.InfoTag + " Redirecting {0} to " + localIP, domain));
                        server.MasterFile.AddIPAddressResourceRecord(domain, localIP);
                    }
                }


                //server.Responded += (request, response) => Console.WriteLine("{0} => {1}", request, response);
                server.Responded += (request, response) => MainWindow.AddToLogDNS(String.Format("{0} => {1}", request, response));
                server.Errored   += (e) =>
                {
                    Console.WriteLine(MainWindow.ErrorTag + ": {0}", e);
                    MainWindow.AddToLogDNS(String.Format(MainWindow.ErrorTag + ": {0}", e));
                    ResponseException responseError = e as ResponseException;
                    if (responseError != null)
                    {
                        Console.WriteLine(responseError.Response);
                    }
                };

                try
                {
                    await server.Listen();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(MainWindow.ErrorTag + " DNSAsync: " + ex.ToString());
                }
            }
        }
Пример #19
0
        public void TestGetExceptionMessage_系统级错误()
        {
            string errMsg = "<error_rsp><args><arg name=\"api_key\"><![CDATA[12003014]]></arg></args><code>25</code><msg><![CDATA[Item service unavailable:获取单个商品失败]]></msg></error_rsp>";

            ResponseException ex = new ResponseException(errMsg);

            Assert.AreEqual("25", ex.ErrorCode);
            Assert.AreEqual("Item service unavailable:获取单个商品失败", ex.ErrorDescription);
            Assert.AreEqual("签名无效", ex.ErrorMessageCh);
            Assert.AreEqual("Invalid signature", ex.ErrorMessageEn);
            Assert.AreEqual(ResponseErrorType.System, ex.ErrorType);
        }
        public void TestGetExceptionMessage_系统级错误()
        {
            string errMsg = "<error_rsp><args><arg name=\"api_key\"><![CDATA[12003014]]></arg></args><code>25</code><msg><![CDATA[Item service unavailable:获取单个商品失败]]></msg></error_rsp>";

            ResponseException ex = new ResponseException(errMsg);

            Assert.AreEqual("25", ex.ErrorCode);
            Assert.AreEqual("Item service unavailable:获取单个商品失败", ex.ErrorDescription);
            Assert.AreEqual("签名无效", ex.ErrorMessageCh);
            Assert.AreEqual("Invalid signature", ex.ErrorMessageEn);
            Assert.AreEqual(ResponseErrorType.System, ex.ErrorType);
        }
        public void TestGetExceptionMessage_业务级错误()
        {
            string errMsg = "<error_rsp><args><arg name=\"api_key\"><![CDATA[12003014]]></arg></args><code>551</code><msg><![CDATA[Item service unavailable:获取单个商品失败]]></msg></error_rsp>";

            ResponseException ex = new ResponseException(errMsg);

            Assert.AreEqual("551", ex.ErrorCode);
            Assert.AreEqual("Item service unavailable:获取单个商品失败", ex.ErrorDescription);
            Assert.AreEqual("商品数据服务不可用", ex.ErrorMessageCh);
            Assert.AreEqual("Item service unavailable", ex.ErrorMessageEn);
            Assert.AreEqual(ResponseErrorType.Business, ex.ErrorType);
        }
Пример #22
0
        public void TestGetExceptionMessage_业务级错误()
        {
            string errMsg = "<error_rsp><args><arg name=\"api_key\"><![CDATA[12003014]]></arg></args><code>551</code><msg><![CDATA[Item service unavailable:获取单个商品失败]]></msg></error_rsp>";

            ResponseException ex = new ResponseException(errMsg);

            Assert.AreEqual("551", ex.ErrorCode);
            Assert.AreEqual("Item service unavailable:获取单个商品失败", ex.ErrorDescription);
            Assert.AreEqual("商品数据服务不可用", ex.ErrorMessageCh);
            Assert.AreEqual("Item service unavailable", ex.ErrorMessageEn);
            Assert.AreEqual(ResponseErrorType.Business, ex.ErrorType);
        }
Пример #23
0
        public void Send(string address, string subject, string content)
        {
            if (!Mail.LimitCheck(address, subject))
            {
                throw ResponseException.LogicalError("操作过于频繁");
            }

            EventPublisher.Publish(new SendMailEvent()
            {
                Address = address,
                Subject = subject,
                Content = content
            });
        }
Пример #24
0
        public static void WriteError(ResponseException ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;

            Console.WriteLine("");
            Console.WriteLine("Ops! There was an error.");

            Console.ForegroundColor = ConsoleColor.Gray;

            Console.WriteLine("");
            Console.WriteLine("HttpStatusCode".PadRight(20, ' ') + $": {ex.ResponseError.HttpStatusCode.ToString()}");
            Console.WriteLine("Id".PadRight(20, ' ') + $": {ex.ResponseError.Id}");
            Console.WriteLine("Message".PadRight(20, ' ') + $": {ex.ResponseError.Message}");
        }
        public async Task WhenGettingWalletsFromUnknownUser_ItShouldThrowResponseException()
        {
            // Arrange:
            // Act:
            ResponseException ex = await Assert.ThrowsAsync <ResponseException>(() => _objectToTest.GetWallets("12345"));

            // Assert:
            Assert.Equal(404, ex.ResponseStatusCode);
            Assert.NotNull(ex.Message);
            Assert.NotNull(ex.ResponseErrorRaw);
            Assert.NotNull(ex.ResponseError);
            Assert.NotEmpty(ex.ResponseError.errors);
            Assert.True(ex.ResponseError.errors.ContainsKey("RessourceNotFound"));
        }
Пример #26
0
                public string ReadCBT(string ID, BNAC_Table.ID_Type idType, bool optionalCloseConn = false)
                {
                    string        command = "CBT=" + BNAC_Table.CreateID(ID, idType) + "?";
                    List <string> resps   = SendCommand(command, 1, optionalCloseConn);

                    string[] Vals = resps[0].Split('=');
                    if (Vals.Length != 2)
                    {
                        ResponseException ex = new ResponseException("Invalid response received.", command, resps);
                        LogMsg(TraceEventType.Warning, ex.ToString());
                        throw ex;
                    }

                    return(Vals[1]);
                }
        /// <summary>
        /// Handling response if request got an exception
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task OnExceptionAsync(ExceptionContext context)
        {
            await base.OnExceptionAsync(context);

            ResponseException    apiError;
            ApiResponse <object> apiResponse;
            List <string>        apiMessage = new List <string>();
            int    code;
            string displayMessage;

            if (context.Exception is ApiException apiException)
            {
                apiError = new ResponseException(apiException.Message, ErrorTypes.ApiError)
                {
                    ValidationErrors = apiException.Errors
                };
                code = apiException.StatusCode;
            }
            else if (context.Exception is UnauthorizedAccessException unauthorizedException)
            {
                apiError = new ResponseException(unauthorizedException.Message, ErrorTypes.UnauthorizedAccess, unauthorizedException.InnerException.Message);
                code     = (int)HttpStatusCode.Unauthorized;
            }
            else if (context.Exception is CoreException coreException)
            {
                apiError = new ResponseException(coreException.Message, coreException.ErrorType);
                code     = coreException.StatusCode;
            }
            else
            {
#if !DEBUG
                var    msg   = _stringLocalizer[ApiResponseMessage.Unhandled];
                string stack = null;
#else
                var    msg   = context.Exception.GetBaseException().Message;
                string stack = context.Exception.StackTrace;
#endif

                apiError = new ResponseException(msg, ErrorTypes.SystemError, stack);
                code     = (int)HttpStatusCode.InternalServerError;
            }

            displayMessage = _stringLocalizer[ApiResponseMessage.Exception];
            apiResponse    = new ApiResponse <object>(code, null, displayMessage, apiError);

            context.HttpContext.Response.StatusCode = code;
            context.Result = new JsonResult(apiResponse);
        }
Пример #28
0
        /// <summary>
        /// Identify if the error or exception comes from the business logic.
        /// </summary>
        /// <param name="exception">Exception to analize.</param>
        /// <returns></returns>
        private static ResponseException GetServerError(Exception exception)
        {
            ResponseException responseException = null;

            while (exception != null)
            {
                responseException = exception as ResponseException;
                if (responseException != null)
                {
                    break;
                }
                exception = exception.InnerException;
            }

            return(responseException);
        }
        public async Task Test_Users_GetLegal_FailsForNaturalUser()
        {
            UserNaturalDTO john = null;

            john = TestHelper.GetJohn();

            ResponseException ex = await Assert.ThrowsAsync <ResponseException>(() => _objectToTest.GetLegal(john.Id));

            // Assert:
            Assert.Equal(404, ex.ResponseStatusCode);
            Assert.NotNull(ex.Message);
            Assert.NotNull(ex.ResponseErrorRaw);
            Assert.NotNull(ex.ResponseError);
            Assert.NotEmpty(ex.ResponseError.errors);
            Assert.True(ex.ResponseError.errors.ContainsKey("RessourceNotFound"));
        }
Пример #30
0
        public void Send(string address, string subject, string content, ITransactionContext?transactionContext)
        {
            if (subject.IsNullOrEmpty())
            {
                throw ResponseException.ArgError("邮件标题不能为空");
            }

            if (!Mail.LimitCheck(address, subject))
            {
                throw ResponseException.LogicalError("操作过于频繁");
            }

            EventPublisher.PublishAsync(new SendMailEvent()
            {
                Address = address, Subject = subject, Content = content
            }, transactionContext).Wait();
        }
Пример #31
0
        /// <summary>
        /// Task for handling request if failure
        /// </summary>
        /// <param name="context"></param>
        /// <param name="body"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private Task HandleNotSuccessRequestAsync(HttpContext context, object body, int code)
        {
            string               bodyText;
            string               displayMessage;
            string               jsonString;
            ResponseException    responseException;
            ApiResponse <object> apiResponse;
            List <string>        apiMessage = new List <string>();

            if (code == (int)HttpStatusCode.NotFound)
            {
                displayMessage    = _stringLocalizer[ApiResponseMessage.NotFound];
                responseException = new ResponseException(displayMessage, ErrorTypes.ResourceNotFound);
            }
            else if (code == (int)HttpStatusCode.Unauthorized || code == (int)HttpStatusCode.Forbidden)
            {
                displayMessage    = _stringLocalizer[ApiResponseMessage.Unauthorized];
                responseException = new ResponseException(displayMessage, ErrorTypes.UnauthorizedAccess);
            }
            else if (code == (int)HttpStatusCode.BadRequest)
            {
                bodyText = body.ToString().IsValidJson() ? body.ToString() : JsonConvert.SerializeObject(body);

                ModelValidation      modelValidation = JsonConvert.DeserializeObject <ModelValidation>(bodyText);
                ModelStateDictionary modelState      = new ModelStateDictionary();
                foreach (var item in modelValidation.Errors)
                {
                    modelState.AddModelError(item.Key, string.Join(" ", item.Value.ToArray()));
                }

                displayMessage    = _stringLocalizer[ApiResponseMessage.ValidationError];
                responseException = new ResponseException(modelState, modelValidation.Message);
            }
            else
            {
                displayMessage    = _stringLocalizer[ApiResponseMessage.ContactSupport];
                responseException = new ResponseException(displayMessage, ErrorTypes.SystemError);
            }

            apiResponse = new ApiResponse <object>(code, null, displayMessage, responseException);
            jsonString  = JsonConvert.SerializeObject(apiResponse);

            context.Response.StatusCode = code;
            return(context.Response.WriteAsync(jsonString));
        }
Пример #32
0
        /// <summary>
        /// Translate strings from the business logic layer depending on the current culture.
        /// </summary>
        /// <param name="exception">Business logic exception.</param>
        /// <returns>Translated string.</returns>
        public static string TranslateBusinessLogicException(ResponseException exception)
        {
            string lTranslatedString = string.Empty;

            if (exception == null)
            {
                return(lTranslatedString);
            }

            // If there is not multilanguage, return the business logic exception message directly.
            if (SupportedLanguages.Count <= 1)
            {
                return(exception.Message);
            }
            // If there is multilanguage, translate the business logic exception message depending on the culture.
            else
            {
                lTranslatedString = TranslateString("e" + exception.Number, exception.Message);
                if (exception.Parameters != null)
                {
                    string lSearchedKey = string.Empty;
                    for (int lKeyIndex = 0; lKeyIndex < exception.Parameters.Count; lKeyIndex++)
                    {
                        lSearchedKey = "{" + exception.Parameters[lKeyIndex].Key + "}";

                        // Keyed value.
                        if (exception.Parameters[lKeyIndex].Type == ErrorParamType.Key)
                        {
                            // The text to replace must be taken from language resources.
                            string lTranslatedKey = TranslateString(exception.Parameters[lKeyIndex].Text, string.Empty);
                            lTranslatedString = lTranslatedString.Replace(lSearchedKey, lTranslatedKey);
                        }
                        // Literal value.
                        else if (exception.Parameters[lKeyIndex].Type == ErrorParamType.Literal)
                        {
                            // The text to replace must be taken directly from the exception.
                            lTranslatedString = lTranslatedString.Replace(lSearchedKey, exception.Parameters[lKeyIndex].Text);
                        }
                    }
                }
            }

            return(lTranslatedString);
        }
        public void Response_AfterSerialized_CanDeserialize()
        {
            var responseException = new ResponseException
            {
                Message    = "message",
                Source     = "source",
                StackTrace = "stacktrace"
            };
            var response = new ResponseWrapper
            {
                ResponseException = responseException
            };
            string xml = Serialization.SerializeResponse(response);
            var    deserializedResponse = Serialization.DeserializeResponse(xml);

            Assert.That(deserializedResponse.ResponseException.Message.Equals(responseException.Message));
            Assert.That(deserializedResponse.ResponseException.Source.Equals(responseException.Source));
            Assert.That(deserializedResponse.ResponseException.StackTrace.Equals(responseException.StackTrace));
        }
Пример #34
0
 /// <summary>
 /// Deserializes an XML Error file.
 /// </summary>
 /// <param name="reader">XML Error file.</param>
 /// <returns>ResponseException.</returns>
 public static ResponseException Deserialize(XmlReader reader )
 {
     ResponseException lResult=null;
     if(reader.IsStartElement(DTD.Error.TagError))
     {
         lResult = new ResponseException();
         // Read the Attributes from Error element.
         lResult.SetErrorType(reader.GetAttribute(DTD.Error.TagType));
         lResult.Number = int.Parse(reader.GetAttribute(DTD.Error.TagNumber));
         if (!reader.IsEmptyElement)
         {
             reader.ReadStartElement(DTD.Error.TagError);
             do
             {
                 #region Read Message Element.
                 if (reader.IsStartElement(DTD.Error.TagErrorMessage))
                 {
                     if (!reader.IsEmptyElement)
                     {
                         lResult.SetMessage(reader.ReadString());
                     }
                 }
                 #endregion Read Message Element.
                 else
                 {
                     #region Read the Error.Params.
                     if (reader.IsStartElement(DTD.Error.TagErrorParams))
                     {
                         lResult.Parameters = XMLErrorParamsSerialize.Deserialize(reader.ReadSubtree(), lResult.Parameters);
                     }
                     #endregion Read the Error.Params.
                     else
                     {
                         #region Read the Trace Items.
                         if (reader.IsStartElement(DTD.Error.TagErrorTrace))
                         {
                             lResult.Traces = XMLErrorTracesSerialize.Deserialize(reader.ReadSubtree(),null);
                         }
                         #endregion Read the Trace Items.
                         else
                         {
                             #region Read the Changed Items.
                             if (reader.IsStartElement(DTD.Error.TagChangedItems))
                             {
                                 lResult.ChangedItems = XMLChangedItemsSerializer.Deserialize(reader.ReadSubtree()); ;
                             }
                             #endregion Read the Changed Items.
                             else
                             {
                                 #region Read the <?>.
                                 reader.Skip();
                                 if (reader.NodeType == XmlNodeType.None)
                                 {
                                     break;
                                 }
                                 else
                                 {
                                     continue;
                                 }
                                 #endregion Read the <?>.
                             }
                         }
                     }
                 }
             } while (reader.Read());
         }
     }
     return lResult;
 }
Пример #35
0
        /// <summary>
        /// Translate strings from the business logic layer depending on the current culture.
        /// </summary>
        /// <param name="exception">Business logic exception.</param>
        /// <returns>Translated string.</returns>
        public static string TranslateBusinessLogicException(ResponseException exception)
        {
            string lTranslatedString = string.Empty;

            if (exception == null)
            {
                return lTranslatedString;
            }

            // If there is not multilanguage, return the business logic exception message directly.
            if (SupportedLanguages.Count <= 1)
            {
                return exception.Message;
            }
            // If there is multilanguage, translate the business logic exception message depending on the culture.
            else
            {
                lTranslatedString = TranslateString("e" + exception.Number, exception.Message);
                if (exception.Parameters != null)
                {
                    string lSearchedKey = string.Empty;
                    for (int lKeyIndex = 0; lKeyIndex < exception.Parameters.Count; lKeyIndex++)
                    {
                        lSearchedKey = "{" + exception.Parameters[lKeyIndex].Key + "}";

                        // Keyed value.
                        if (exception.Parameters[lKeyIndex].Type == ErrorParamType.Key)
                        {
                            // The text to replace must be taken from language resources.
                            string lTranslatedKey = TranslateString(exception.Parameters[lKeyIndex].Text, string.Empty);
                            lTranslatedString = lTranslatedString.Replace(lSearchedKey, lTranslatedKey);
                        }
                        // Literal value.
                        else if (exception.Parameters[lKeyIndex].Type == ErrorParamType.Literal)
                        {
                            // The text to replace must be taken directly from the exception.
                            lTranslatedString = lTranslatedString.Replace(lSearchedKey, exception.Parameters[lKeyIndex].Text);
                        }
                    }
                }
            }

            return lTranslatedString;
        }
Пример #36
0
 /// <summary>
 /// Initializes the 'ErrorForm' of the application.
 /// </summary>
 /// <param name="exception">Bussiness logic exception.</param>
 public void Initialize(ResponseException exception)
 {
     // Show the business logic exception.
     ShowBusinessLogicError(exception);
 }
Пример #37
0
        /// <summary>
        /// Show the business logic errors and exceptions.
        /// </summary>
        /// <param name="exception">ResponseException.</param>
        private void ShowBusinessLogicError(ResponseException exception)
        {
            // Exception message translated depending on the culture.
            this.labelErrorDesciption.Text = CultureManager.TranslateBusinessLogicException(exception);

            // Show all the exception traces.
            if ((exception != null) && (exception.Traces != null))
            {
                this.richTextBoxDetails.Clear();
                this.richTextBoxDetails.AppendText("Bussines Logic Traces:");
                this.richTextBoxDetails.AppendText("\r");

                this.richTextBoxDetails.SelectionBullet = true;

                // Show traces as a LIFO (Last In First Out) stack.
                for (int i = exception.Traces.Count - 1; i >= 0; i--)
                {
                    this.richTextBoxDetails.AppendText("Error Number " + exception.Traces[i].Number + ": " + CultureManager.TranslateBusinessLogicException(exception.Traces[i]) + ".");
                    this.richTextBoxDetails.AppendText("\r");
                }

                this.richTextBoxDetails.SelectionBullet = false;
            }
        }