Пример #1
0
        private static void CreateErrorLogFile(Exception exception)
        {
            string currentDirectory = Directory.GetCurrentDirectory();

            Console.WriteLine($"{nameof(currentDirectory)}: {currentDirectory}");
            string currentDateTime      = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            string errorLogFileName     = $"DevVmPowerShellModule_ErrorLog_{currentDateTime}.txt";
            string errorLogFileFullPath = Path.Combine(currentDirectory, errorLogFileName);

            //Delete File if it already exists
            if (File.Exists(errorLogFileFullPath))
            {
                File.Delete(errorLogFileFullPath);
            }

            //Create File
            using (StreamWriter streamWriter = File.CreateText(errorLogFileFullPath))
            {
                string errorMessage         = exception.Message;
                string completeErrorMessage = ErrorMessageHelper.FormatErrorMessage(exception);
                string stackTrace           = exception.StackTrace;
                streamWriter.WriteLine($"ERROR MESSAGE:\n{errorMessage}");
                streamWriter.WriteLine();
                streamWriter.WriteLine($"COMPLETE ERROR MESSAGE:\n{completeErrorMessage}");
                streamWriter.WriteLine();
                streamWriter.WriteLine($"STACK TRACE:\n{stackTrace}");
            }
        }
Пример #2
0
        public bool Commit(ModelStateDictionary modelState)
        {
            try
            {
                _context.SaveChanges();
                return(true);
            }
            catch (DbUpdateException dbUpdateEx)
            {
                // logging

                string errorMessage = dbUpdateEx?.InnerException.Message ?? "An error occurred while updating the data";
                if (errorMessage.Contains(EnumErrorMessageHints.REFERENCE_CONSTRAINT.GetDesc()))
                {
                    ErrorMessageHelper.AddModelStateError(modelState, EnumErrorMessageHints.REFERENCE_CONSTRAINT);
                }
                else
                {
                    ErrorMessageHelper.AddModelStateError(modelState, EnumErrorMessageDescriptions.EXCEPTION);
                }

                return(false);
            }
            catch (Exception ex)
            {
                // logging

                ErrorMessageHelper.AddModelStateError(modelState, EnumErrorMessageDescriptions.EXCEPTION);
                return(false);
            }
        }
Пример #3
0
 private void Instance_LoginFailed(object sender, EventArgs e)
 {
     ErrorMessage = ErrorMessageHelper.GetErrorMessageResource("LoginDialogLoginFailed");
     IsEnabled    = true;
     IsBusy       = false;
     Bindings.Update();
 }
        public IActionResult Get([FromRoute] int event_id, [FromRoute] int sold_item_id)
        {
            Events e = db.Events.Where(r => r.Id == event_id).FirstOrDefault();

            if (e == null)
            {
                return(StatusCode(404, ErrorMessageHelper.GenerateResponse(404, "Event not found")));
            }

            SoldItems s = db.SoldItems.Where(r => r.EventId == event_id && r.Id == sold_item_id).FirstOrDefault();

            if (s == null)
            {
                return(StatusCode(404, ErrorMessageHelper.GenerateResponse(404, "Sold Item not found")));
            }

            if (!(DateTime.Now >= e.EndTime))
            {
                return(StatusCode(400, ErrorMessageHelper.GenerateResponse(400, "Event is not yet complete to generate the winning bid")));
            }

            List <Bids> b_l         = db.Bids.Where(r => r.SoldItemId == s.Id).ToList();
            int         winning_bid = (b_l.Count == 0) ? 0 : WinningBidService.GenerateWinningBid(b_l, s);

            return(Ok(new JObject {
                { "winning_bid", winning_bid }
            }));
        }
    internal async Task ProcessHandlerErrorAsync(Exception ex, string method, bool isStreaming, JsonSerializerOptions options)
    {
        Status status;

        if (ex is RpcException rpcException)
        {
            // RpcException is thrown by client code to modify the status returned from the server.
            // Log the status and detail. Don't log the exception to reduce log verbosity.
            GrpcServerLog.RpcConnectionError(Logger, rpcException.StatusCode, rpcException.Status.Detail);

            status = rpcException.Status;
        }
        else
        {
            GrpcServerLog.ErrorExecutingServiceMethod(Logger, method, ex);

            var message = ErrorMessageHelper.BuildErrorMessage("Exception was thrown by handler.", ex, Options.EnableDetailedErrors);

            // Note that the exception given to status won't be returned to the client.
            // It is still useful to set in case an interceptor accesses the status on the server.
            status = new Status(StatusCode.Unknown, message, ex);
        }

        await JsonRequestHelpers.SendErrorResponse(HttpContext.Response, RequestEncoding, status, options);

        if (isStreaming)
        {
            await HttpContext.Response.Body.WriteAsync(GrpcProtocolConstants.StreamingDelimiter);
        }
    }
 public ActionResult ViewApplicants()
 {
     return(View(new ScreenerSummaryPageViewModel()
     {
         ApplicationSummary = _screeningService.GetApplicantList(SSOUserManager.SiteUser),
         ErrorMessage = TempData["ErrorMessage"] != null
             ? TempData["ErrorMessage"].ToString()
             : ErrorMessageHelper.GetNonErrorMessage()
     }));
 }
 /// <summary>
 /// Updates the questions set data.
 /// </summary>
 /// <returns>The questions set data.</returns>
 /// <param name="pQuestionsSetName">Questions set name.</param>
 public ResponseDTO <object> UpdateQuestionsSetData(string pQuestionsSetName)
 {
     try
     {
         return(_questionsSetService.UpdateQuestionsSetData(pQuestionsSetName));
     }
     catch (Exception ex)
     {
         _logger.Error(ex, "Failed to update Questions Set data.");
         return(ResponseDTO.InternalError(ErrorMessageHelper.FailedOperation("updating questions set data")));
     }
 }
 /// <summary>
 /// Register a new User.
 /// </summary>
 /// <param name="pUsername">Username.</param>
 /// <param name="pPassword">Password.</param>
 /// <param name="pConfirmPassword">Confirmed password.</param>
 public ResponseDTO <object> SignUp(string pUsername, string pPassword, string pConfirmPassword)
 {
     try
     {
         return(_userService.SignUp(pUsername, pPassword, pConfirmPassword));
     }
     catch (Exception ex)
     {
         _logger.Error(ex, "Failed to sign up.");
         return(ResponseDTO.InternalError(ErrorMessageHelper.FailedOperation("signing up")));
     }
 }
 /// <summary>
 /// Save the specified pQuestionsSet.
 /// </summary>
 /// <param name="pQuestionsSet">Questions set DTO.</param>
 public ResponseDTO <object> SaveQuestionsSet(QuestionsSetDTO pQuestionsSet)
 {
     try
     {
         QuestionsSet modifiedQuestionsSet = _mapper.Map <QuestionsSet>(pQuestionsSet);
         return(_questionsSetService.Save(modifiedQuestionsSet));
     }
     catch (Exception ex)
     {
         _logger.Error(ex, $"Failed to save QuestionsSet. {ex.Message}");
         return(ResponseDTO.InternalError(ErrorMessageHelper.FailedOperation("saving questions set")));
     }
 }
 /// <summary>
 /// Login for the given username and password.
 /// </summary>
 /// <returns>The authorized user if login is successful.</returns>
 /// <param name="pUsername">Username.</param>
 /// <param name="pPassword">Password.</param>
 public ResponseDTO <UserDTO> Login(string pUsername, string pPassword)
 {
     try
     {
         return(_userService.Login(pUsername, pPassword));
     }
     catch (Exception ex)
     {
         _logger.Error(ex, "Failed to Login.");
         return(ResponseDTO <UserDTO> .InternalError(
                    ErrorMessageHelper.FailedOperation("logging in")));
     }
 }
 /// <summary>
 /// Record an answer for a question from an ongoing session.
 /// </summary>
 /// <returns>Answer result.</returns>
 /// <param name="pSessionAnswer">Session answer parameters.</param>
 public ResponseDTO <AnswerResultDTO> AddAnswer(SessionAnswerDTO pSessionAnswer)
 {
     try
     {
         return(_sessionService.AddAnswer(pSessionAnswer));
     }
     catch (Exception ex)
     {
         _logger.Error(ex, "Failed to add answer to the given session.");
         return(ResponseDTO <AnswerResultDTO> .InternalError(
                    ErrorMessageHelper.FailedOperation("recording your answer")));
     }
 }
 /// <summary>
 /// Show ranking of session results for a given Questions Set.
 /// </summary>
 /// <param name="pQuestionsSetId">Questions set identifier.</param>
 public ResponseDTO <IEnumerable <SessionResultDTO> > ShowRanking(int pQuestionsSetId)
 {
     try
     {
         return(_sessionService.GetSessionResults(pQuestionsSetId));
     }
     catch (Exception ex)
     {
         _logger.Error(ex, "Failed to fetch Session results.");
         return(ResponseDTO <IEnumerable <SessionResultDTO> > .InternalError(
                    ErrorMessageHelper.FailedOperation("fetching ranking")));
     }
 }
 /// <summary>
 /// Finish the given session and calculate its score.
 /// </summary>
 /// <param name="pSessionId">Session identifier</param>
 /// <returns>The session result <see cref="SessionResultDTO"/>.</returns>
 public ResponseDTO <SessionResultDTO> FinishSession(int pSessionId)
 {
     try
     {
         return(_sessionService.FinishSession(pSessionId));
     }
     catch (Exception ex)
     {
         _logger.Error(ex, "Failed to finish Session.");
         return(ResponseDTO <SessionResultDTO> .InternalError(
                    ErrorMessageHelper.FailedOperation("attempting to finish the current session")));
     }
 }
Пример #14
0
        /// <summary>
        /// Validates serie definition list.
        /// </summary>
        /// <exception cref="T:iTin.Export.Model.InvalidSeriesDefinitionException">Thrown if there are serie definition errors.</exception>
        public void Validate()
        {
            var hasFieldErrors = HasFieldErrors(this, out var fieldErrorDictionary);

            if (!hasFieldErrors)
            {
                return;
            }

            var message = ErrorMessageHelper.FormatSeriesErrorMessage(fieldErrorDictionary);

            throw new InvalidSeriesDefinitionException(message);
        }
Пример #15
0
        public BaseController()
        {
            if (Context == null)
            {
                Context = new AgriBookContext();
            }

            if (_errorMessageHelper == null)
            {
                _errorMessageHelper = new ErrorMessageHelper();
            }

            ExceptionMessageHelper = _errorMessageHelper;
        }
        protected virtual IRuleConfiguration GetRuleConfiguration(string ruleName, object parameters)
        {
            IRuleConfiguration ruleConfiguration;

            if (ErrorMessageHelper.HasCustomMessage(attribute))
            {
                var message = ErrorMessageHelper.GetErrorMessage(attribute);
                ruleConfiguration = new RuleWithMessageConfiguration(ruleName, parameters, message);
            }
            else
            {
                ruleConfiguration = new SimpleRuleConfiguration(ruleName, parameters);
            }

            return(ruleConfiguration);
        }
 /// <summary>
 /// Gets all Questions Sets available.
 /// </summary>
 /// <returns>Questions set list.</returns>
 public ResponseDTO <IEnumerable <QuestionsSetDTO> > GetQuestionsSets()
 {
     try
     {
         return(_questionsSetService.GetQuestionsSets());
     }
     catch (NoContentException)
     {
         return(ResponseDTO <IEnumerable <QuestionsSetDTO> > .NoContent("No questions sets were found."));
     }
     catch (Exception ex)
     {
         _logger.Error(ex, "Failed to fetch QuestionsSet list.");
         return(ResponseDTO <IEnumerable <QuestionsSetDTO> > .InternalError(
                    ErrorMessageHelper.FailedOperation("fetching Questions Sets available")));
     }
 }
Пример #18
0
        private async Task SendCloseAsync(HubConnectionContext connection, Exception exception)
        {
            var closeMessage = CloseMessage.Empty;

            if (exception != null)
            {
                var errorMessage = ErrorMessageHelper.BuildErrorMessage("Connection closed with an error.", exception, _enableDetailedErrors);
                closeMessage = new CloseMessage(errorMessage);
            }

            try
            {
                await connection.WriteAsync(closeMessage);
            }
            catch (Exception ex)
            {
                Log.ErrorSendingClose(_logger, ex);
            }
        }
Пример #19
0
        private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            if (string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(Password))
            {
                ErrorMessage = ErrorMessageHelper.GetErrorMessageResource("LoginDialogUserNameRequired");
            }
            else
            {
                ErrorMessage = string.Empty;
                IsEnabled    = false;
                IsBusy       = true;

                _ = AuthenticationService.Instance.LoginUser(UserName, Password);
            }

            Bindings.Update();

            // We only close if we log in successfully or cancel
            args.Cancel = true;
        }
Пример #20
0
        public async Task <SearchResult> GetResultsCountAsync(string term)
        {
            var requestMessage  = CreateRequestMessage(term);
            var responseMessage = await httpClient.SendAsync(requestMessage);

            if (!responseMessage.IsSuccessStatusCode)
            {
                var message = ErrorMessageHelper
                              .CreateResponseStatusErrorMessage(SearchEngineName, term, responseMessage.StatusCode);
                throw new System.Exception(message);
            }

            var responseStream = await responseMessage.Content.ReadAsStreamAsync();

            var count = await GetCountFromResponseAsync(responseStream);

            return(new SearchResult
            {
                Count = count,
                Source = SearchEngineName,
                Term = term
            });
        }
Пример #21
0
    private async Task SendCloseAsync(HubConnectionContext connection, Exception?exception, bool allowReconnect)
    {
        var closeMessage = CloseMessage.Empty;

        if (exception != null)
        {
            var errorMessage = ErrorMessageHelper.BuildErrorMessage("Connection closed with an error.", exception, _enableDetailedErrors);
            closeMessage = new CloseMessage(errorMessage, allowReconnect);
        }
        else if (allowReconnect)
        {
            closeMessage = new CloseMessage(error: null, allowReconnect);
        }

        try
        {
            await connection.WriteAsync(closeMessage, ignoreAbort : true);
        }
        catch (Exception ex)
        {
            Log.ErrorSendingClose(_logger, ex);
        }
    }
Пример #22
0
        protected override void EndProcessing()
        {
            try
            {
                WriteVerbose($"Start - {nameof(EndProcessing)} method");

                base.EndProcessing();
                EndProcessingCode();
            }
            catch (Exception ex)
            {
                string              formattedExceptionMessage = ErrorMessageHelper.FormatErrorMessage(ex);
                Exception           exception     = new Exception($"An error occured in {nameof(EndProcessing)} method. ErrorMessage: {formattedExceptionMessage}. StackTrace: {ex}", ex);
                string              errorId       = $"{nameof(EndProcessing)}";
                const ErrorCategory errorCategory = ErrorCategory.DeviceError;
                ErrorRecord         errorRecord   = new ErrorRecord(exception, errorId, errorCategory, null);
                WriteError(errorRecord);
            }
            finally
            {
                WriteVerbose($"End - {nameof(EndProcessing)} method");
            }
        }
Пример #23
0
 /// <summary>
 /// To send a mail
 /// </summary>
 public bool SendMail()
 {
     try
     {
         MailMessage mailMessage   = new MailMessage(FromAddress, ToAddress, Subject, Message);
         MailAddress mailToAddress = new MailAddress(ToAddress, DisplayName);
         //MailAddress mailFromAdress = new MailAddress(FromAddress, "");
         mailMessage.IsBodyHtml = IsBodyHtml;
         mailMessage.Subject    = Subject;
         mailMessage.Body       = Message;
         SmtpClient SmtpSettings = new SmtpClient(SmtpServer, HostPort);
         SmtpSettings.UseDefaultCredentials = false;
         SmtpSettings.EnableSsl             = IsMailHasSSLEnabled;
         SmtpSettings.Credentials           = new System.Net.NetworkCredential(SmtpLogInEmail, Password);
         SmtpSettings.Send(mailMessage);
         return(true);
     }
     catch (Exception exception)
     {
         ErrorMessageHelper.SetExceptionMessage(exception);
         return(false);
     }
 }
 /// <summary>
 /// Creates a new session for the given user,
 /// with <paramref name="pQuestionsQuantity"/> questions from the
 /// given category and level.
 /// </summary>
 /// <returns>The session.</returns>
 /// <param name="pUserId">User identifier</param>
 /// <param name="pCategoryId">Category identifier.</param>
 /// <param name="pLevelId">Level identifier.</param>
 /// <param name="pQuestionsQuantity">Questions quantity.</param>
 public ResponseDTO <SessionDTO> NewSession(int pUserId, int pCategoryId, int pLevelId, int pQuestionsQuantity)
 {
     try
     {
         return(_sessionService.NewSession(pUserId, pCategoryId, pLevelId, pQuestionsQuantity));
     }
     catch (Exception ex)
     {
         _logger.Error(ex, $"{ex.Message} ::" +
                       $" Parameters: pUserId={pUserId}, pCategoryId={pCategoryId}, pLevelId={pLevelId}," +
                       $" pQuestionsQuantity={pQuestionsQuantity}");
         ResponseCode errorCode = ResponseCode.InternalError;
         if (ex.GetType() == typeof(NotFoundException))
         {
             errorCode = ResponseCode.NotFound;
         }
         else if (ex.GetType() == typeof(BadRequestException))
         {
             errorCode = ResponseCode.BadRequest;
         }
         return(ResponseDTO <SessionDTO> .Error(ErrorMessageHelper.FailedOperation("creating a new session"), errorCode));
     }
 }
Пример #25
0
        public IActionResult Post([FromRoute] int event_id, [FromRoute] int sold_item_id, [FromBody] BidRequestRoot b_r)
        {
            //could avoid redundancy in this check
            Events e = db.Events.Where(r => r.Id == event_id).FirstOrDefault();

            if (e == null)
            {
                return(StatusCode(404, ErrorMessageHelper.GenerateResponse(404, "Event not found")));
            }

            SoldItems s = db.SoldItems.Where(r => r.EventId == event_id && r.Id == sold_item_id).FirstOrDefault();

            if (s == null)
            {
                return(StatusCode(404, ErrorMessageHelper.GenerateResponse(404, "Sold Item not found")));
            }

            if (!(DateTime.Now >= e.StartTime && DateTime.Now <= e.EndTime))
            {
                return(StatusCode(400, ErrorMessageHelper.GenerateResponse(400, "Event is not active to receive bids")));
            }

            Bids previous_bid = db.Bids.Where(r => r.SoldItemId == s.Id).FirstOrDefault();

            if (previous_bid != null)
            {
                return(StatusCode(400, ErrorMessageHelper.GenerateResponse(400, "Bid found already")));
            }

            Bids b = b_r.createBid(s.Id);

            db.Bids.Add(b);
            db.SaveChanges();
            return(Ok(new JObject {
                { "success", true }
            }));
        }
Пример #26
0
        protected override void ProcessRecord()
        {
            try
            {
                WriteVerbose($"Start - {nameof(ProcessRecord)} method");

                base.ProcessRecord();
                RetryProcessRecordCode(ProcessRecordCode, TimeSpan.FromSeconds(Constants.Module.TimeInSecondsBetweenRetry), Constants.Module.MaxAttemptCount);
            }
            catch (Exception ex)
            {
                CreateErrorLogFile(ex);
                string              formattedExceptionMessage = ErrorMessageHelper.FormatErrorMessage(ex);
                Exception           exception     = new Exception($"An error occured in {nameof(ProcessRecord)} method. ErrorMessage: {formattedExceptionMessage}. StackTrace: {ex}", ex);
                string              errorId       = $"{nameof(ProcessRecord)}";
                const ErrorCategory errorCategory = ErrorCategory.DeviceError;
                ErrorRecord         errorRecord   = new ErrorRecord(exception, errorId, errorCategory, null);
                WriteError(errorRecord);
            }
            finally
            {
                WriteVerbose($"End - {nameof(ProcessRecord)} method");
            }
        }
Пример #27
0
        public List <string> GetPossibleOptionsFromState(PlayerState state)
        {
            var handler = GetMessageHandlerForState("", state);

            try
            {
                return(handler.GetOptions(state.player));
            }
            catch (AdventureGameException e)
            {
                if (e.ShouldReset)
                {
                    var result = TryResetState(state);
                    _dataStore.SaveChanges();
                    result.MessagesToShow.Add(new MessageResult {
                        Message = "Your game was reset due to an error: " + e.Message
                    });
                    _reporter.ReportError(ErrorMessageHelper.MakeMessage(e, state));
                    return(result.OptionsToShow);
                }
            }
            catch (Exception e)
            {
                var result = TryResetState(state);
                _dataStore.SaveChanges();
                result.MessagesToShow.Add(new MessageResult {
                    Message = "Your game was reset due to an error: " + e.Message
                });
                _reporter.ReportError(ErrorMessageHelper.MakeMessage(e, state));
                return(result.OptionsToShow);
            }

            return(new List <string> {
                "Error occured. Retry."
            });
        }
Пример #28
0
        public void FormatValidationError_ShouldFormatTheMessageCorrectly(string specialMessgae, int line, int column, string tagName, string message)
        {
            IErrorMessageHelper helper = new ErrorMessageHelper();

            Assert.Equal(message, helper.FormatValidationError(specialMessgae, (line, column), tagName));
        }
Пример #29
0
        public ExecutionResult ProcessNewMessage(string message, PlayerState state)
        {
            ExecutionResult result = null;

            if (!_accessService.DoesPlayerHaveAccess(state.player))
            {
                result = HandleNoAccess(message, state.player);
                _dataStore.SaveChanges();
                return(result);
            }
            try
            {
                var handler = GetMessageHandlerForState(message, state);
                result = handler.HandleMessage(message, state.player);
                _dataStore.SaveChanges();
                return(result);
            }
            catch (AdventureGameException e)
            {
                if (e.ShouldReset)
                {
                    try
                    {
                        _reporter.ReportError(ErrorMessageHelper.MakeMessage(e, state, "Handling message: " + message));
                        result = TryResetState(state);
                        _dataStore.SaveChanges();
                        result.MessagesToShow.Add(new MessageResult {
                            Message = "Your game was reset due to an error: " + e.Message
                        });
                        return(result);
                    }
                    catch (Exception exc)
                    {
                        return(ExecutionResultHelper.SingleMessage("An error has been encountered and automatically reported. Apologies! We usually fix any errors within 24 hours. If you are in" +
                                                                   " a stuck state on Telegram or Discord, try typing '-Menu-'. If you are in browser, try refreshing. \n\nError message: " + exc.Message, null));
                    }
                }
                else
                {
                    _reporter.ReportError(ErrorMessageHelper.MakeMessage(e, state, "Game was NOT reset. Handling message: " + message));
                    return(ExecutionResultHelper.SingleMessage("An error has been encountered and automatically reported. Apologies! We usually fix any errors within 24 hours. If you are in" +
                                                               " a stuck state on Telegram or Discord, try typing '-Menu-'. If you are in browser, try refreshing. \n\nError message: " + e.Message, null));
                }
            }
            catch (DbUpdateConcurrencyException e)
            {
                e.Entries.Single().Reload();
                if (result != null)
                {
                    return(result);
                }
                else
                {
                    _reporter.ReportError(ErrorMessageHelper.MakeMessage(e, state, "DB Update Exception handling message: " + message));
                    return(new ExecutionResult
                    {
                        MessagesToShow = new List <MessageResult> {
                            new MessageResult {
                                Message = "DB Update error. Your game was NOT reset. Error message: " + e.Message
                            }
                        },
                        OptionsToShow = new List <string> {
                            Messages.GameMenu
                        }
                    });
                }
            }
            catch (Exception e)
            {
                _reporter.ReportError(ErrorMessageHelper.MakeMessage(e, state, "Handling message: " + message));
                result = TryResetState(state);
                _dataStore.SaveChanges();
                result.MessagesToShow.Add(new MessageResult {
                    Message = "Your game was reset due to an error: " + e.Message
                });
                return(result);
            }
        }
Пример #30
0
 private void HandleError(string identifyingText, Exception e, PlayerGameSave gameSave = null)
 {
     Log.LogMessage(ErrorMessageHelper.MakeMessage(e, gameSave, "Parsing text: " + identifyingText), LogType.Error);
     throw e;
 }