Example #1
0
        public void Shutdown(Action <StreamHandle, Exception> completion = null)
        {
            if (!this.IsValid)
            {
                return;
            }

            StreamShutdown streamShutdown = null;

            try
            {
                streamShutdown = new StreamShutdown(this, completion);
            }
            catch (Exception exception)
            {
                Exception error = exception;

                ErrorCode?errorCode = (error as OperationException)?.ErrorCode;
                if (errorCode == ErrorCode.EPIPE)
                {
                    // It is ok if the stream is already down
                    error = null;
                }
                if (error != null)
                {
                    Log.Error($"{this.HandleType} {this.InternalHandle} failed to shutdown.", error);
                }

                StreamShutdown.Completed(completion, this, error);
                streamShutdown?.Dispose();
            }
        }
Example #2
0
        private void TraceExecuteReaderFailed(Exception e, string commandText, ErrorCode?specificErrorCode)
        {
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append("An error occured running the query for DataSet: \"");
            stringBuilder.Append(m_dataSet.Name.MarkAsPrivate());
            stringBuilder.Append("\"");
            if (specificErrorCode.HasValue)
            {
                stringBuilder.Append(" ErrorCode: \"").Append(specificErrorCode.Value).Append("\"");
            }
            if (m_dataSet.Query != null && m_dataSet.Query.TimeOut > 0)
            {
                stringBuilder.Append(" Timeout: \"").Append(m_dataSet.Query.TimeOut).Append("\"");
            }
            if (!string.IsNullOrEmpty(m_dataSource.ConnectionCategory))
            {
                stringBuilder.Append(" ConnectionCategory: \"").Append(m_dataSource.ConnectionCategory).Append("\"");
            }
            stringBuilder.Append("Error: \"").Append(e.Message).Append("\"");
            if (!string.IsNullOrEmpty(commandText))
            {
                stringBuilder.Append("Query: ");
                if (commandText.Length > 2048)
                {
                    stringBuilder.Append(commandText.Substring(0, 2048).MarkAsPrivate());
                    stringBuilder.Append(" ...");
                }
                else
                {
                    stringBuilder.Append(commandText.MarkAsPrivate());
                }
            }
            Global.Tracer.Trace(TraceLevel.Error, stringBuilder.ToString());
        }
        /**
         * Gets the reason for certain errors.
         *
         * @param errorCodeString string form of {@link ErrorCodes}
         * @param message the original received error message, which may or may not be used depending on
         *     the {@code errorCode}
         */
        private static string GetReason(ErrorCode?errorCode, string message)
        {
            if (message == null)
            {
                message = "no details";
            }

            if (!errorCode.HasValue)
            {
                // Unknown errorCodeString
                return("unknown: " + message);
            }

            if (errorCode == ErrorCode.ManifestInvalid || errorCode == ErrorCode.BlobUnknown)
            {
                return(message + " (something went wrong)");
            }
            else if (errorCode == ErrorCode.ManifestUnknown ||
                     errorCode == ErrorCode.TagInvalid ||
                     errorCode == ErrorCode.ManifestUnverified)
            {
                return(message);
            }
            else
            {
                return("other: " + message);
            }
        }
Example #4
0
        private static string GetUserFriendlyMessage(ErrorCode?code)
        {
            switch (code)
            {
            case ErrorCode.InvalidApiKey:
                return("The API Key is invalid.");

            case ErrorCode.ServiceOffline:
                return("The Last.FM service is offline");

            case ErrorCode.ApiKeySuspended:
                return("The API Key is suspended");

            case ErrorCode.RateLimitExceeded:
                return("The rate limit was exceeded");

            case ErrorCode.InvalidSessionKey:
                return("The API Session Key is invalid");

            case ErrorCode.UnauthorizedToken:
                return("The API token is not authorized");

            case ErrorCode.AuthenticationFailed:
                return("Authentication failed");

            case ErrorCode.UserNotLoggedIn:
                return("The user must be logged in");
            }

            return("An unexpected error was encountered");
        }
        /// <summary>
        ///     Runs all steps and user interaction that is required during the conversion
        /// </summary>
        public WorkflowResult RunWorkflow(Job job)
        {
            try
            {
                _stopwatch = new Stopwatch();
                _stopwatch.Start();
                JobEventsManager.RaiseJobStarted(job, Thread.CurrentThread.ManagedThreadId.ToString());

                PrepareAndRun(job);
            }
            catch (AbortWorkflowException ex)
            {
                // we need to clean up the job when it was cancelled
                _logger.Warn(ex.Message + " No output will be created.");
                WorkflowResult = WorkflowResult.AbortedByUser;

                SendJobEvents(job);
            }
            catch (WorkflowException ex)
            {
                _logger.Error(ex.Message);
                WorkflowResult = WorkflowResult.Error;

                SendJobEvents(job);
            }
            catch (ProcessingException ex)
            {
                var errorMessage = ex.ErrorCode + " / " + ex.Message;
                if (ex.InnerException != null)
                {
                    errorMessage += Environment.NewLine + ex.InnerException;
                }
                _logger.Error(errorMessage);

                LastError = ex.ErrorCode;

                HandleError(ex.ErrorCode);
                WorkflowResult = WorkflowResult.Error;

                SendJobEvents(job);
            }
            catch (ManagePrintJobsException)
            {
                throw;
            }
            catch (InterruptWorkflowException)
            {
                throw;
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                WorkflowResult = WorkflowResult.Error;
                SendJobEvents(job);

                throw;
            }

            return(WorkflowResult);
        }
        private static string GetErrorMessage(string name, ErrorCode?ec, params KeyValuePair <string, object>[] infos)
        {
            string message = ec == null?StoreProgress.Get(name).Message() : ec.Value.Message();

            var info = string.Join(", ", infos.Select(s => s.Key + "=" + s.Value.ToString()));

            return("[" + name + "] " + message + (string.IsNullOrEmpty(info) ? string.Empty : " -> ") + info);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ApiException"/> class.
 /// </summary>
 /// <param name="errorMessage">The <see cref="ErrorMessageResponse"/> returned from the API.</param>
 /// <param name="responseMessage">The <see cref="HttpResponseMessage"/>.</param>
 protected ApiException(ErrorMessageResponse?errorMessage, HttpResponseMessage responseMessage) : base(
         responseMessage,
         errorMessage?.Message ?? $"HTTP {responseMessage?.StatusCode ?? throw new ArgumentNullException(nameof(responseMessage))}. Unknown API error, ErrorMessage payload not present!")
 {
     ServerApiVersion     = errorMessage?.ServerApiVersion;
     AdditionalServerData = errorMessage?.AdditionalData;
     ErrorCode            = errorMessage?.ErrorCode;
 }
Example #8
0
        public bool Equals(ErrorCode?other)
        {
            if (ReferenceEquals(other, null))
            {
                return(false);
            }

            return(Id == other.Id);
        }
 private void Set(decimal?value, ErrorCode?error)
 {
     lock (this)
     {
         this.value = value;
         this.error = error;
         Monitor.Pulse(this);
     }
 }
Example #10
0
        private void ParseErrorCode(string str)
        {
            ErrorCode code;

            if (Enum.TryParse(str, out code))
            {
                ErrorCode = code;
            }
        }
Example #11
0
        public bool TryGetGetErrorCode(short code, [MaybeNullWhen(false)] out ErrorCode?errorCode)
        {
            if (Errors.TryGetValue(code, out errorCode))
            {
                return(true);
            }

            return(false);
        }
Example #12
0
 public Error(ErrorCode?errorCode)
 {
     if (errorCode == null)
     {
         return;
     }
     Code        = errorCode.ToString();
     Description = errorCode.GetDescription();
 }
        private static T GetAttribute <T>(this ErrorCode?value) where T : Attribute
        {
            Debug.Assert(value != null, "value != null");
            var type       = value.GetType();
            var memberInfo = type.GetMember(value.ToString());
            var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);

            return((T)attributes[0]);
        }
        private IActionResult Failure(ErrorCode?errorCategory)
        {
            switch (errorCategory)
            {
            case ErrorCode.NotFound:
                return(NotFound());

            default:
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }
        }
Example #15
0
        /// <summary>
        /// Returns an appropriate error code if scanning this verbatim literal ran into an error.
        /// </summary>
        private ErrorCode?ScanVerbatimStringLiteral(ref TokenInfo info, bool allowNewlines)
        {
            _builder.Length = 0;

            Debug.Assert(TextWindow.PeekChar() == '@' && TextWindow.PeekChar(1) == '"');
            TextWindow.AdvanceChar(2);

            ErrorCode?error = null;

            while (true)
            {
                var ch = TextWindow.PeekChar();
                if (ch == '"')
                {
                    TextWindow.AdvanceChar();
                    if (TextWindow.PeekChar() == '"')
                    {
                        // Doubled quote -- skip & put the single quote in the string and keep going.
                        TextWindow.AdvanceChar();
                        _builder.Append(ch);
                        continue;
                    }

                    // otherwise, the string is finished.
                    break;
                }

                if (ch == SlidingTextWindow.InvalidCharacter && TextWindow.IsReallyAtEnd())
                {
                    // Reached the end of the source without finding the end-quote.  Give an error back at the
                    // starting point. And finish lexing this string.
                    error ??= ErrorCode.ERR_UnterminatedStringLit;
                    break;
                }

                // If we hit a new line when it's not allowed.  Give an error at that new line, but keep on consuming
                // the verbatim literal to the end to avoid the contents of the string being lexed as C# (which will
                // cause a ton of cascaded errors).  Only need to do this on the first newline we hit.
                if (!allowNewlines && SyntaxFacts.IsNewLine(ch))
                {
                    error ??= ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString;
                }

                TextWindow.AdvanceChar();
                _builder.Append(ch);
            }

            info.Kind        = SyntaxKind.StringLiteralToken;
            info.Text        = TextWindow.GetText(intern: false);
            info.StringValue = _builder.ToString();

            return(error);
        }
Example #16
0
        private void OnError(ErrorMessage errorMessage)
        {
            this.LastError = errorMessage.Message;
            this.LastErrorCode = errorMessage.ErrorCode;

            if (this.LastErrorCode == ErrorCode.OrderRejected)
            {
                this.State = OrderState.Rejected;
            }

            this.OrderChanged(this, new OrderChangedEventArgs{Order = this});
        }
Example #17
0
        private void BoundaryTest(char heading, ErrorCode ec)
        {
            var       rover  = new PessimisticRover(new ParsedRoverCommand($"1 1 {heading}", "MMM"));
            var       rovers = new List <BaseRover>();
            var       bounds = new Coordinant(2, 2);
            ErrorCode?result = rover.DoCommand('M', bounds, rovers);

            Assert.IsNull(result);
            result = rover.DoCommand('M', bounds, rovers);
            Assert.IsTrue(result.HasValue);
            Assert.IsTrue(result.Value == ec);
        }
 public decimal?Get(out ErrorCode?e)
 {
     lock (this)
     {
         if (!value.HasValue && !error.HasValue)
         {
             Monitor.Wait(this);
         }
         e = error;
         return(value);
     }
 }
Example #19
0
        public static ErrorProp ErrorDesc(ErrorCode?code, string main_error)
        {
            ErrorProp error = new ErrorProp();

            switch (code)
            {
            case ErrorCode.OK:
                error.message = Constants.MessageText.OperationOK;
                error.status  = HttpStatusCode.OK;
                break;

            case ErrorCode.BadRequest:
                error.message = main_error;
                error.status  = HttpStatusCode.BadRequest;
                break;

            case ErrorCode.UnexpectedError:
                error.message = Constants.MessageText.UnexpectedError;
                error.status  = HttpStatusCode.InternalServerError;
                break;

            case ErrorCode.DbSaveNotDone:
                error.message = Constants.MessageText.DbSaveNotDone;
                error.status  = HttpStatusCode.ExpectationFailed;
                break;

            case ErrorCode.DbUpdateException:
                error.message = Constants.MessageText.DbUpdateException;
                //error.status = HttpStatusCode.FailedDependency;
                error.status = HttpStatusCode.UnprocessableEntity;
                break;

            case ErrorCode.AddRepeatedEntity:
                error.message = Constants.MessageText.AddRepeatedEntity;
                error.status  = HttpStatusCode.Conflict;
                break;

            case ErrorCode.NoContent:
                error.message = Constants.MessageText.NoContent;
                error.status  = HttpStatusCode.NoContent;
                break;

            case null:
                break;

            default:
                error = GetErrorProp((ErrorCode)code);
                break;
            }
            return(error);
        }
Example #20
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            try
            {
                long?  signInTokenId = context.HttpContext?.User?.GetSignInTokenId();
                long?  userId        = context.HttpContext?.User?.GetUserId();
                string?ip            = context.HttpContext?.GetIpAddress();
                string?url           = context.HttpContext?.Request?.GetDisplayUrl();
                string?httpMethod    = context.HttpContext?.Request?.Method;
                string?arguments     = SerializeUtil.TryToJson(context.ActionArguments);

                if (arguments != null && arguments.Length > UserActivity.MAX_ARGUMENTS_LENGTH)
                {
                    arguments = arguments.Substring(0, UserActivity.MAX_ARGUMENTS_LENGTH);
                }

                ActionExecutedContext?resultContext = await next().ConfigureAwait(false);

                int?      resultStatusCode = null;
                ErrorCode?errorCode        = null;
                string?   resultType       = null;

                if (resultContext?.Result != null)
                {
                    resultType = resultContext.Result.ToString();

                    if (resultContext.Result is BadRequestObjectResult badRequestObjectResult)
                    {
                        resultStatusCode = badRequestObjectResult.StatusCode;

                        if (badRequestObjectResult.Value is ErrorCode err)
                        {
                            errorCode = err;
                        }
                    }
                    else if (resultContext.Result is IStatusCodeActionResult statusCodeResult)
                    {
                        resultStatusCode = statusCodeResult.StatusCode;
                    }
                }

                _userActivityService.RecordUserActivityAsync(signInTokenId, userId, ip, url, httpMethod, arguments, resultStatusCode, resultType, errorCode).Fire();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "UserActivityFilter中捕捉到错误,不应该。请检查,是否有漏捕捉。{url}", context.HttpContext?.Request?.GetDisplayUrl());
                OnError(context);
            }
        }
Example #21
0
        /// <summary>
        /// Test a given <typeparamref name="TApiException"/> is thrown when a given <paramref name="action"/> is called.
        /// </summary>
        /// <typeparam name="TApiException">The type of the expected <see cref="ApiException"/>.</typeparam>
        /// <param name="action">A <see cref="Func{TResult}"/> resulting in a <see cref="Task"/>.</param>
        /// <param name="expectedErrorCode">The expected <see cref="ApiException.ErrorCode"/>.</param>
        /// <returns>A <see cref="Task"/> representing the running operation,</returns>
        public static async Task ThrowsException <TApiException>(Func <Task> action, ErrorCode?expectedErrorCode)
            where TApiException : ApiException
        {
            try
            {
                await action().ConfigureAwait(false);
            }
            catch (TApiException ex)
            {
                Assert.AreEqual(expectedErrorCode, ex.ErrorCode, "Wrong error code for expected API exception!");
                return;
            }

            Assert.Fail($"Expected exception {typeof(TApiException)}!");
        }
Example #22
0
        private IAction BuildAction(ErrorCode?errorCode = null)
        {
            var result = new ActionResult();

            if (errorCode != null)
            {
                result.Add(errorCode.Value);
            }

            var action = Substitute.For <IAction>();

            action.ProcessJob(Arg.Any <Job>()).Returns(result);

            return(action);
        }
Example #23
0
        public void TestRoverCollision()
        {
            var rover  = new PessimisticRover(new ParsedRoverCommand("1 1 N", "MMM"));
            var rovers = new List <BaseRover>()
            {
                new PessimisticRover(new ParsedRoverCommand("1 3 N", "M"))
            };
            var       bounds = new Coordinant(3, 3);
            ErrorCode?result = rover.DoCommand('M', bounds, rovers);

            Assert.IsNull(result);
            result = rover.DoCommand('M', bounds, rovers);
            Assert.IsTrue(result.HasValue);
            Assert.IsTrue(result.Value == ErrorCode.Unexpected_Drone);
        }
Example #24
0
        /// <summary>
        /// Returns an appropriate error code if scanning this verbatim literal ran into an error.
        /// </summary>
        private ErrorCode?ScanVerbatimStringLiteral(ref TokenInfo info)
        {
            _builder.Length = 0;

            Debug.Assert(TextWindow.PeekChar() == '@' && TextWindow.PeekChar(1) == '"');
            TextWindow.AdvanceChar(2);

            ErrorCode?error = null;

            while (true)
            {
                var ch = TextWindow.PeekChar();
                if (ch == '"')
                {
                    TextWindow.AdvanceChar();
                    if (TextWindow.PeekChar() == '"')
                    {
                        // Doubled quote -- skip & put the single quote in the string and keep going.
                        TextWindow.AdvanceChar();
                        _builder.Append(ch);
                        continue;
                    }

                    // otherwise, the string is finished.
                    break;
                }

                if (ch == SlidingTextWindow.InvalidCharacter && TextWindow.IsReallyAtEnd())
                {
                    // Reached the end of the source without finding the end-quote.  Give an error back at the
                    // starting point. And finish lexing this string.
                    error ??= ErrorCode.ERR_UnterminatedStringLit;
                    break;
                }

                TextWindow.AdvanceChar();
                _builder.Append(ch);
            }

            info.Kind        = SyntaxKind.StringLiteralToken;
            info.Text        = TextWindow.GetText(intern: false);
            info.StringValue = _builder.ToString();

            return(error);
        }
        private static string GetKeyFromRequest(HttpRequestMessage request, out ErrorCode?error)
        {
            var authHeader = request?.Headers?.Authorization;

            if (string.IsNullOrWhiteSpace(authHeader?.Parameter))
            {
                error = ErrorCode.SECURITY_TOKEN_MISSING;
                return(string.Empty);
            }

            if (authHeader.Scheme != "Bearer")
            {
                error = ErrorCode.SECURITY_TOKEN_INVALID;
                return(string.Empty);
            }

            error = null;
            return(authHeader.Parameter);
        }
Example #26
0
        private void SetErrorOrState(ErrorCode?error = null, StateCode?state = null)
        {
            var doInterrupt = _dcpu16 != null && _interruptMessage != 0 && (error != _lastErrorCode || state != _currentStateCode);

            if (error != null)
            {
                _lastErrorCode = error.Value;
            }

            if (state != null)
            {
                _currentStateCode = state.Value;
            }

            if (doInterrupt)
            {
                _dcpu16.Interrupt(_interruptMessage);
            }
        }
        /// <exception cref="ApiException"></exception>
        public static async Task ThrowIfNotSuccessedAsync(HttpResponseMessage responseMessage)
        {
            if (responseMessage.IsSuccessStatusCode)
            {
                return;
            }

            //TODO: 可以处理404等ProblemDetails的返回
            ErrorCode?errorCode = await responseMessage.DeSerializeJsonAsync <ErrorCode>().ConfigureAwait(false);

            responseMessage.Dispose();

            if (errorCode == null)
            {
                throw ApiExceptions.ServerUnkownError(response: responseMessage);
            }
            else
            {
                throw ApiExceptions.ServerReturnError(errorCode);
            }
        }
        public static SecurityToken GetTokenFromRequest(HttpRequestMessage request, out ErrorCode?error)
        {
            SecurityToken token = null;
            string        key   = GetKeyFromRequest(request, out error);

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

            if (string.IsNullOrEmpty(key))
            {
                error = ErrorCode.SECURITY_TOKEN_INVALID;
                return(null);
            }

            try
            {
                token = GetTokenFromCache(key);
            }
            catch
            {
                error = ErrorCode.SECURITY_TOKEN_VALIDATION_ERROR;
                return(null);
            }

            if (null == token)
            {
                error = ErrorCode.SECURITY_TOKEN_INVALID;
                return(null);
            }

            if (IsTokenExpired(token))
            {
                error = ErrorCode.SECURITY_TOKEN_EXPIRED;
                return(null);
            }

            return(token);
        }
Example #29
0
        public bool Process(TurnMessage request, out TurnMessage response)
        {
            lock (syncRoot)
            {
                ErrorCode?errorCode = ValidateRequest(request);

                if (errorCode != null)
                {
                    response = new TurnMessage()
                    {
                        MessageType        = request.MessageType.GetErrorResponseType(),
                        TransactionId      = request.TransactionId,
                        MagicCookie        = new MagicCookie(),
                        ErrorCodeAttribute = new ErrorCodeAttribute()
                        {
                            ErrorCode    = (int)errorCode,
                            ReasonPhrase = ((ErrorCode)errorCode).GetReasonPhrase(),
                        },
                        Realm = new Realm(TurnMessageRfc.MsTurn)
                        {
                            Value = Realm,
                        },
                        Nonce = new Nonce(TurnMessageRfc.MsTurn)
                        {
                            Value = NewNonce(),
                        },
                        MsVersion = new MsVersion()
                        {
                            Value = 1,
                        },
                    };
                }
                else
                {
                    response = null;
                }

                return(response == null);
            }
        }
        /// <summary>
        ///     Runs all steps and user interaction that is required during the conversion
        /// </summary>
        public WorkflowResult RunWorkflow(Job job)
        {
            try
            {
                PrepareAndRun(job);
            }
            catch (AbortWorkflowException ex)
            {
                // we need to clean up the job when it was cancelled
                _logger.Warn(ex.Message + " No output will be created.");
                WorkflowResult = WorkflowResult.AbortedByUser;
            }
            catch (WorkflowException ex)
            {
                _logger.Error(ex.Message);
                WorkflowResult = WorkflowResult.Error;
            }
            catch (ProcessingException ex)
            {
                _logger.Error("Error " + ex.ErrorCode + ": " + ex.Message);
                LastError = ex.ErrorCode;

                HandleError(ex.ErrorCode);
                WorkflowResult = WorkflowResult.Error;
            }
            catch (ManagePrintJobsException)
            {
                throw;
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                WorkflowResult = WorkflowResult.Error;
                throw;
            }

            return(WorkflowResult);
        }
Example #31
0
 public ApiException(HttpStatusCode statusCode, string description, ResponseParameters apiResponseParameters, ErrorCode?errorCode) : base(statusCode)
 {
     Description           = description;
     ApiResponseParameters = apiResponseParameters;
     ErrorCode             = errorCode;
 }
 public ExpectedDomainExceptionAttribute(ErrorCode errorCode)
 {
     this.errorCode = errorCode;
 }