public async Task OnExceptionAsync(ExceptionContext context)
        {
            _logger.LogError(context.Exception, $"Error occured in context of {_context}");
            switch (context.Exception)
            {
            case ForbiddenException forbiden:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                var errorMessage = localizationManager.GetResource("Forbidden Exception");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case NotFoundException alreadyExist:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                var errorMessage = localizationManager.GetResource("Not Found Exception");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            default:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                var errorMessage = localizationManager.GetResource("UnhandeledException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            };
            }
            context.ExceptionHandled = true;
        }
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            logger.LogError(context.Exception, $"Error occurred in context of {context}");
            switch (context.Exception)
            {
            case EntityNotFoundException entityNotFound:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                var errorMessage = localizationManager.GetResource("ResourceNotFound");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case ValidationException validationException:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.ExpectationFailed;
                var errorMessage = localizationManager.GetResource(validationException.Message);
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            default:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                var message = localizationManager.GetResource("UnhandeledException");
                await context.HttpContext.Response.WriteAsync(message);

                break;
            }
            }
            context.ExceptionHandled = true;
        }
Exemplo n.º 3
0
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            logger.LogError(context.Exception, $"Error occurred in context of {_context}");
            switch (context.Exception)
            {
            case LoanAlreadyPaidException LoanAlreadyPaid:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                var errorMessage = _localizationManager.GetResource("Loanpaid");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case EntityNotFoundException entityNotFound:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                var errorMessage = _localizationManager.GetResource("ResourceNotFound");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            default:
            {
                logger.LogError($"Method: {context.Exception.TargetSite}.");
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                var errorMessage = _localizationManager.GetResource("UnhandeledException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }
            }
            context.ExceptionHandled = true;
        }
Exemplo n.º 4
0
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            var _context = context.ActionDescriptor.DisplayName;

            _logger.LogError(context.Exception, $"Error occurred in context of {_context}");
            switch (context.Exception)
            {
            case EntityNotFoundException entityNotFound:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                _logger.LogWarning(entityNotFound, entityNotFound.Message + $" Method: {entityNotFound.TargetSite}.");
                var errorMessage = _localizationManager.GetResource("EntityNotFoundException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case BlockedCardException blockedCard:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                _logger.LogWarning(blockedCard, blockedCard.Message + $" Method: {blockedCard.TargetSite}.");
                var errorMessage = _localizationManager.GetResource("BlockedCardException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case InvalidBusinessOperationException invalidBusinessOperation:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                _logger.LogWarning(invalidBusinessOperation, invalidBusinessOperation.Message + $" Method: {invalidBusinessOperation.TargetSite}.");
                var errorMessage = _localizationManager.GetResource("InvalidBusinessOperationException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case PastDateException pastDate:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                _logger.LogWarning(pastDate, pastDate.Message + $" Method: {pastDate.TargetSite}.");
                var errorMessage = _localizationManager.GetResource("PastDateException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            default:
            {
                _logger.LogError(context.Exception.Message + $"Method: {context.Exception.TargetSite}.");
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                var errorMessage = _localizationManager.GetResource("UnhandeledException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }
            }
            context.ExceptionHandled = true; // this flag should be set to true to stop exception propagation
        }
Exemplo n.º 5
0
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            var _context = context.ActionDescriptor.DisplayName;

            logger.LogError(context.Exception, $"Error occurred in context of ");
            switch (context.Exception)
            {
            case EntityNotExistException EntityNotExistException:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;

                logger.LogWarning($"Type : {EntityNotExistException.EntityType.AssemblyQualifiedName},EntityId {EntityNotExistException.EntityId}. Method: {EntityNotExistException.TargetSite}.");
                var errorMessageage = _localizationManager.GetResource("EntityNotExists");

                await context.HttpContext.Response.WriteAsync(errorMessageage);

                break;
            }

            case IncorrectParamsFormatException incorrectParamsFormat:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                logger.LogWarning(incorrectParamsFormat, $"Param name: {incorrectParamsFormat.ParamName}. Method: {incorrectParamsFormat.TargetSite}");
                var errorMessageage = _localizationManager.GetResource("IncorrectParamsFormat");
                await context.HttpContext.Response.WriteAsync(errorMessageage);

                break;
            }

            case СompanyStocksIsPrivateException сompanyStocksIsPrivate:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                logger.LogWarning(сompanyStocksIsPrivate, $"CompanyId: {сompanyStocksIsPrivate.CompanyId}. Method: {сompanyStocksIsPrivate.TargetSite}");
                var errorMessage = _localizationManager.GetResource("СompanyStocksIsPrivate");

                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            default:
            {
                logger.LogError($"Method: {context.Exception.TargetSite}.");
                var errorMessageage = _localizationManager.GetResource("Unhandeled");

                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                await context.HttpContext.Response.WriteAsync(errorMessageage);

                break;
            }
            }
            context.ExceptionHandled = true;
        }
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            var _context = context.ActionDescriptor.DisplayName;

            _logger.LogError(context.Exception, $"Error occurred in context of {_context}");

            switch (context.Exception)
            {
            case EntityNotFoundException entityNotFound:
            {
                _logger.LogWarning(entityNotFound, $"Method: {entityNotFound.TargetSite}. " +
                                   $"Entity Id: {entityNotFound.EntityId}.");
                context.HttpContext.Response.StatusCode = StatusCodes.Status404NotFound;
                var errorMessage = _localizationManager.GetResource("EntityNotFoundException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case EntityNullException entityNull:
            {
                _logger.LogWarning(entityNull, $"Method: {entityNull.TargetSite}. ");
                context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
                var errorMessage = _localizationManager.GetResource("EntityIsNullException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case ArgumentException argumentException:
            {
                _logger.LogWarning(argumentException, $"Method: {argumentException.TargetSite}. " +
                                   $"Parameter Name: {argumentException.ParamName}.");
                context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
                var errorMessage = _localizationManager.GetResource("InvalidOperationException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            default:
            {
                _logger.LogError($"Method: {context.Exception.TargetSite}.");
                context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                var errorMessage = _localizationManager.GetResource("UnhandledException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }
            }
            context.ExceptionHandled = true;
        }
Exemplo n.º 7
0
        /// <summary>
        /// Sets the left.
        /// </summary>
        /// <param name="definition">The definition.</param>
        public void SetLeft(IDefinition definition)
        {
            async Task parseImage()
            {
                var mutex = await leftImageLock.LockAsync();

                var left = LeftImage;

                if (definition != null)
                {
                    LeftImageInfo = string.Empty;
                    LeftImage     = null;
                    left?.Dispose();
                    LeftHeight   = LeftWidth = 0;
                    using var ms = await modService.GetImageStreamAsync(definition?.ModName, definition?.File);

                    if (ms != null)
                    {
                        try
                        {
                            LeftImage = new Bitmap(ms);
                            var imageHeight = (LeftImage?.PixelSize.Width).GetValueOrDefault();
                            var imageWidth  = (LeftImage?.PixelSize.Height).GetValueOrDefault();
                            var info        = localizationManager.GetResource(LocalizationResources.Conflict_Solver.ImageInfo);
                            LeftImageInfo = Smart.Format(info, new { Width = imageWidth, Height = imageHeight });
                            LeftHeight    = imageHeight;
                            LeftWidth     = imageWidth;
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex);
                            LeftImageInfo = string.Empty;
                            LeftImage     = null;
                            left?.Dispose();
                            LeftHeight = LeftWidth = 0;
                        }
                    }
                }
                else
                {
                    LeftImageInfo = string.Empty;
                    LeftImage     = null;
                    left?.Dispose();
                    LeftHeight = LeftWidth = 0;
                }
                await Task.Delay(10);

                mutex.Dispose();
            }

            Task.Run(() => parseImage().ConfigureAwait(false)).ConfigureAwait(false);
        }
        /// <summary>
        /// Sets the left.
        /// </summary>
        /// <param name="definition">The definition.</param>
        public void SetLeft(IDefinition definition)
        {
            async Task parseImage(IDefinition definition)
            {
                LeftImageInfo = string.Empty;
                LeftImage     = null;
                LeftHeight    = LeftWidth = 0;
                if (definition != null)
                {
                    try
                    {
                        var image = await GetBitmapAsync(definition);

                        if (image != null)
                        {
                            LeftImage = image;
                            var imageHeight = image.PixelSize.Height;
                            var imageWidth  = image.PixelSize.Width;
                            var info        = localizationManager.GetResource(LocalizationResources.Conflict_Solver.ImageInfo);
                            LeftImageInfo = Smart.Format(info, new { Width = imageWidth, Height = imageHeight });
                            LeftHeight    = imageHeight;
                            LeftWidth     = imageWidth;
                        }
                        else
                        {
                            LeftImageInfo = string.Empty;
                            LeftImage     = null;
                            LeftHeight    = LeftWidth = 0;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                        LeftImageInfo = string.Empty;
                        LeftImage     = null;
                        LeftHeight    = LeftWidth = 0;
                    }
                }
                else
                {
                    LeftImageInfo = string.Empty;
                    LeftImage     = null;
                    LeftHeight    = LeftWidth = 0;
                }
                await Task.Delay(10);
            }

            Task.Run(() => parseImage(definition).ConfigureAwait(false)).ConfigureAwait(false);
        }
Exemplo n.º 9
0
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            _logger.LogError(context.Exception, $"Error occurred in context of {_context}.");
            switch (context.Exception)
            {
            case EntityNotFoundException entityNotFound:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                await context.HttpContext.Response.WriteAsync(entityNotFound.Message);

                break;
            }

            case ArgumentException argument:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                await context.HttpContext.Response.WriteAsync(argument.Message);

                break;
            }

            default:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                var message = _localizationManager.GetResource("UnhandledException");
                await context.HttpContext.Response.WriteAsync(message);

                break;
            }
            }
            context.ExceptionHandled = true;
        }
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            logger.LogWarning($"ErrorType : {context.Exception.GetType()}");

            switch (context.Exception)
            {
            case EntityNotFoundException entityNotFound:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                var errorMessageage = _localizationManager.GetResource("EntityNotFound");
                await context.HttpContext.Response.WriteAsync(errorMessageage);

                break;
            }

            case BlockedException blockedException:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                var errorMessageage = _localizationManager.GetResource("CardBlocked");
                await context.HttpContext.Response.WriteAsync(errorMessageage);

                break;
            }

            case LimitException limitException:
            {
                var message    = limitException.Message;
                var actionName = limitException.LimitAction;
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                var errorMessageage = _localizationManager.GetResource("CardLimit");
                await context.HttpContext.Response.WriteAsync(errorMessageage);

                break;
            }

            default:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                var errorMessageage = _localizationManager.GetResource("UnhandeletedErrorOccurred");
                await context.HttpContext.Response.WriteAsync(errorMessageage);

                break;
            }
            }
            context.ExceptionHandled = true; // this flag should be set to true to stop exception propagation
        }
Exemplo n.º 11
0
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            var _context = context.ActionDescriptor.DisplayName;

            _logger.LogError(context.Exception, $"Error occurred in context of {_context}");
            switch (context.Exception)
            {
            case AccountAlreadyBlockedException accountAlreadyBlocked:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                var errorMessage = _localizationManager.GetResource("Account alredy blocked");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case AccountAlreadyUnblockedException accountAlreadyUnblocked:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                var errorMessage = _localizationManager.GetResource("Account already unblocked");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case EntityNotFoundException entityNotFound:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                var errorMessage = _localizationManager.GetResource("Entity Not Found");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            default:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                var errorMessage = _localizationManager.GetResource("Unhandled exception");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }
            }
            context.ExceptionHandled = true;             // this flag should be set to true to stop exception propagation
        }
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            var _context = context.ActionDescriptor.DisplayName;

            logger.LogError(context.Exception, $"Error occurred in context of {_context}");
            switch (context.Exception)
            {
            case NotFoundException notFound:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                var errorMessage = _localizationManager.GetResource("ResourceNotFound");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case IncorrectParamException incorrectParam:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                var errorMessage = _localizationManager.GetResource("InvalidParam");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case PrivateCompanyException privateCompany:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                var errorMessage = _localizationManager.GetResource("PrivateCompany");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            default:
            {
                var errorMessage = _localizationManager.GetResource("Unhandled");
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                await context.HttpContext.Response.WriteAsync("Unhandled exception!");

                break;
            }
            }
            context.ExceptionHandled = true;
        }
Exemplo n.º 13
0
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            var _context = context.ActionDescriptor.DisplayName;

            _logger.LogError(context.Exception, $"Error occurred in context of {_context}");
            switch (context.Exception)
            {
            case EntityNotFoundException entityNotFound:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                var errorMessage = _localizationManager.GetResource("Entity Not Found");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case InvalidStatusException invalidStatusException:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                var errorMessage = _localizationManager.GetResource("Invalid status");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case NumberAlreadyExists numberAlreadyExists:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                var errorMessage = _localizationManager.GetResource("Payment number already exists");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            default:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                var errorMessage = _localizationManager.GetResource("UnhandeledException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }
            }
            context.ExceptionHandled = true;
        }
Exemplo n.º 14
0
 public ConversionRate GetConversionRate(DateTime date)
 {
     if (date > DateTime.Today)
     {
         var message = _localizationManager.GetResource("FutureDateException");
         throw new FutureDateException(message, date, nameof(date));
     }
     return(_dbContext.ConversionRates.Where(cr => cr.Date == date).FirstOrDefault());
 }
Exemplo n.º 15
0
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            logger.LogError(context.Exception, $"Error occurred in context of {context}");

            switch (context.Exception)
            {
            case InvalidDataDTOException e:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;

                var errorMessage = localizationManager.GetResource("InvalidDataDTO");

                logger.LogWarning($"{e.Message}. Method: {e.TargetSite}.");

                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case EntityNotExistException e:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;

                var errorMessage = localizationManager.GetResource("EntityNotExist");

                logger.LogWarning($"Type : {e.EntityType.AssemblyQualifiedName},EntityId {e.EntityId}. Method: {e.TargetSite}.");

                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            default:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                var errorMessage = localizationManager.GetResource("UnhandledException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }
            }

            context.ExceptionHandled = true;
        }
Exemplo n.º 16
0
        public IEnumerable <KeyValuePair <string, decimal> > GetExchangeRate(string fromCode, DateTime date)
        {
            _logger.LogDebug("call GetExchangeRate method with code {code} and date {date}", fromCode, date.ToString("yyyy-MM-dd"));
            if (fromCode == null)
            {
                throw new ArgumentNullException(nameof(fromCode));
            }
            if (!Regex.IsMatch(fromCode, "(?i)^[A-Z]{3}$"))
            {
                var message = _localizationManager.GetResource("CurrencyCodeFormatException");
                throw new CurrencyCodeFormatException(message, fromCode, nameof(fromCode));
            }
            if (date > DateTime.Today)
            {
                var message = _localizationManager.GetResource("FutureDateException");
                throw new FutureDateException(message, date, nameof(date));
            }

            var result = new Dictionary <string, decimal>();

            var conversionRate = _repository.GetConversionRate(date);

            if (conversionRate == null)
            {
                var message = _localizationManager.GetResource("EntityNotFoundException");
                throw new EntityNotFoundException(message, typeof(ConversionRate));
            }

            var exchangeRates = conversionRate.Currencies.ToDictionary(x => x.Key, x => x.Value);

            if (!exchangeRates.Keys.Contains(fromCode))
            {
                var message = _localizationManager.GetResource("EntityNotFoundException");
                throw new EntityNotFoundException(message, typeof(ConversionRate));
            }

            foreach (var rate in exchangeRates)
            {
                result.Add(rate.Key, GetConversionRate(exchangeRates, fromCode, rate.Key));
            }

            result.Remove(fromCode);
            return(result);
        }
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            logger.LogError(context.Exception, $"Error occurred in context of {_context}");

            switch (context.Exception)
            {
            case EntityNotFoundException entityNotFound:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                var errorMessage = _localizationManager.GetResource("ResourceNotFound");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case BillAlreadyBlockedException blockedException:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                var errorMessage = _localizationManager.GetResource("BillIsBlocked");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case BillAlreadyUnlockedException unlockedException:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                var errorMessage = _localizationManager.GetResource("BillIsUnblocked");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            default:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                var errorMessage = _localizationManager.GetResource("UnhandledException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }
            }
            context.ExceptionHandled = true;
        }
Exemplo n.º 18
0
        /// <summary>
        /// Maps the sort order.
        /// </summary>
        /// <param name="order">The order.</param>
        protected virtual void MapSortOrder(SortOrder order)
        {
            var text = string.Empty;

            switch (order)
            {
            case SortOrder.Asc:
                text = localizationManager.GetResource(LocalizationResources.Sorting.Sort_A_Z);
                break;

            case SortOrder.Desc:
                text = localizationManager.GetResource(LocalizationResources.Sorting.Sort_Z_A);
                break;

            default:
                break;
            }
            SortOrderText = text;
        }
Exemplo n.º 19
0
        /// <summary>
        /// Initializes the model.
        /// </summary>
        /// <param name="currentLocale">The current locale.</param>
        /// <param name="locale">The locale.</param>
        /// <returns>ILanguage.</returns>
        protected virtual ILanguage InitModel(string currentLocale, string locale)
        {
            var culture = new CultureInfo(locale);
            var model   = GetModelInstance <ILanguage>();

            model.IsSelected = currentLocale.Equals(locale, StringComparison.OrdinalIgnoreCase);
            model.Abrv       = locale;
            model.Name       = $"{culture.TextInfo.ToTitleCase(culture.NativeName)}";
            model.Font       = localizationManager.GetResource(locale, LocalizationResources.App.FontFamily);
            return(model);
        }
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            string contexName = context.ActionDescriptor.DisplayName;

            _logger.LogError(context.Exception, $"Error ocurred in context of {contexName}");

            switch (context.Exception)
            {
            case ProductNotFoundException productNotFound:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;

                string productIds   = string.Join(", ", productNotFound.ProductIds);
                var    errorMessage = _localizationManager.GetResource("ProductNotFound") + productIds;
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case EmptyOrderException emptyOrder:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                var errorMessage = _localizationManager.GetResource(emptyOrder.Message);
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            default:
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                var errorMessage = _localizationManager.GetResource("UnhandledException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }
            }

            context.ExceptionHandled = true;
        }
        /// <summary>
        /// load images as an asynchronous operation.
        /// </summary>
        protected virtual async Task LoadImagesAsync()
        {
            while (loadingImages)
            {
                await Task.Delay(25);
            }
            loadingImages = true;
            if (prevLeftDefinition != LeftDefinition)
            {
                LeftImageInfo = string.Empty;
                var left = LeftImage;
                LeftImage = null;
                left?.Dispose();
                using var ms = await modService.GetImageStreamAsync(LeftDefinition?.ModName, LeftDefinition?.File);

                if (ms != null)
                {
                    LeftImage = new Bitmap(ms);
                    var info = localizationManager.GetResource(LocalizationResources.Conflict_Solver.ImageInfo);
                    LeftImageInfo = Smart.Format(info, new { LeftImage.PixelSize.Width, LeftImage.PixelSize.Height });
                }
            }
            if (prevRightDefinition != RightDefinition)
            {
                RightImageInfo = string.Empty;
                var right = RightImage;
                RightImage = null;
                right?.Dispose();
                using var ms = await modService.GetImageStreamAsync(RightDefinition?.ModName, RightDefinition?.File);

                if (ms != null)
                {
                    RightImage = new Bitmap(ms);
                    var info = localizationManager.GetResource(LocalizationResources.Conflict_Solver.ImageInfo);
                    RightImageInfo = Smart.Format(info, new { RightImage.PixelSize.Width, RightImage.PixelSize.Height });
                }
            }
            loadingImages = false;
        }
        /// <summary>
        /// Sets the left.
        /// </summary>
        /// <param name="definition">The definition.</param>
        public void SetLeft(IDefinition definition)
        {
            var loadingImage = false;

            async Task loadImage()
            {
                while (loadingImage)
                {
                    await Task.Delay(25);
                }
                loadingImage  = true;
                LeftImageInfo = string.Empty;
                var left = LeftImage;

                LeftImage = null;
                left?.Dispose();
                using var ms = await modService.GetImageStreamAsync(definition?.ModName, definition?.File);

                if (ms != null)
                {
                    LeftImage = new Bitmap(ms);
                    var info = localizationManager.GetResource(LocalizationResources.Conflict_Solver.ImageInfo);
                    LeftImageInfo = Smart.Format(info, new { LeftImage.PixelSize.Width, LeftImage.PixelSize.Height });
                }
                loadingImage = false;
            }

            if (definition != null)
            {
                Task.Run(() => loadImage().ConfigureAwait(false)).ConfigureAwait(false);
            }
            else
            {
                LeftImageInfo = string.Empty;
                var left = LeftImage;
                LeftImage = null;
                left?.Dispose();
            }
        }
Exemplo n.º 23
0
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            logger.LogError(context.Exception, $"Error occurred in context of {context.ActionDescriptor.DisplayName}");
            switch (context.Exception)
            {
            case EntityNotFoundException entityNotFound:
            {
                logger.LogWarning(entityNotFound, $"Method: {entityNotFound.TargetSite}");
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                var errorMessage = localizationManager.GetResource("EntityNotFound");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            case BadRequestException badRequestException:
            {
                logger.LogWarning(badRequestException, $"Method: {badRequestException.TargetSite}");
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                var errorMessage = localizationManager.GetResource("UnableProcessUser");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }

            default:
            {
                logger.LogError($"Method: {context.Exception.TargetSite}.");
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                var errorMessage = localizationManager.GetResource("UnhandledException");
                await context.HttpContext.Response.WriteAsync(errorMessage);

                break;
            }
            }
            context.ExceptionHandled = true;
        }
Exemplo n.º 24
0
 public string this[string key]
 {
     get
     {
         if (!listeningForChanges)
         {
             listeningForChanges = true;
             var listener = MessageBus.Current.Listen <LocaleChangedEventArgs>();
             listener.SubscribeObservable(x =>
             {
                 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item"));
                 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
             });
         }
         if (localizationManager == null)
         {
             localizationManager = DIResolver.Get <ILocalizationManager>();
         }
         return(localizationManager.GetResource(key));
     }
 }
        /// <summary>
        /// Binds the asynchronous.
        /// </summary>
        /// <param name="game">The game.</param>
        /// <returns>Task.</returns>
        protected virtual async Task BindAsync(IGame game = null)
        {
            var id = idGenerator.GetNextId();

            await TriggerOverlayAsync(id, true, localizationManager.GetResource(LocalizationResources.Installed_Mods.LoadingMods));

            if (game == null)
            {
                game = gameService.GetSelected();
            }
            ModFilePopulationInCompleted = false;
            ActiveGame = game;
            if (game != null)
            {
                var mods = await Task.Run(() => modService.GetInstalledMods(game));

                await Task.Run(async() =>
                {
                    await PopulateModFilesAsyncAsync(mods).ConfigureAwait(false);
                    ModFilePopulationInCompleted = true;
                    EvalAchievementCompatibility(mods);
                });

                await Task.Delay(100);

                Mods    = mods.ToObservableCollection();
                AllMods = Mods.ToHashSet();
                var invalidMods = AllMods.Where(p => !p.IsValid);
                if (invalidMods.Any())
                {
                    await RemoveInvalidModsPromptAsync(invalidMods).ConfigureAwait(false);
                }
                var searchString = FilterMods.Text ?? string.Empty;
                FilteredMods = Mods.Where(p => p.Name.Contains(searchString, StringComparison.InvariantCultureIgnoreCase) ||
                                          (p.RemoteId.HasValue && p.RemoteId.GetValueOrDefault().ToString().Contains(searchString))).ToObservableCollection();
                AllModsEnabled = FilteredMods.Where(p => p.IsValid).Any() && FilteredMods.Where(p => p.IsValid).All(p => p.IsSelected);

                if (Disposables != null)
                {
                    modChanged?.Dispose();
                    modChanged = null;
                    modChanged = Mods.ToSourceList().Connect().WhenPropertyChanged(s => s.IsSelected).Subscribe(s =>
                    {
                        if (!checkingState)
                        {
                            CheckModEnabledStateAsync().ConfigureAwait(false);
                        }
                    }).DisposeWith(Disposables);
                }

                var state = appStateService.Get();
                InitSortersAndFilters(state);

                ApplyDefaultSort();
            }
            else
            {
                Mods    = FilteredMods = new System.Collections.ObjectModel.ObservableCollection <IMod>();
                AllMods = Mods.ToHashSet();
            }
            await TriggerOverlayAsync(id, false);
        }
Exemplo n.º 26
0
        /// <summary>
        /// check for updates as an asynchronous operation.
        /// </summary>
        /// <param name="autoUpdateCheck">if set to <c>true</c> [automatic update check].</param>
        protected virtual async Task CheckForUpdatesAsync(bool autoUpdateCheck = false)
        {
            CheckingForUpdates = true;
            UpdateInfoVisible  = false;
            var updatesAvailable = await updater.CheckForUpdatesAsync();

            if (updatesAvailable)
            {
                Changelog         = updater.GetChangeLog();
                VersionContent    = updater.GetVersion();
                UpdateInfoVisible = true;
                var openState = IsOpen;
                IsOpen = false;
                IsOpen = openState;
                if (autoUpdateCheck)
                {
                    var title   = localizationManager.GetResource(LocalizationResources.Options.Updates.UpdateNotification.Title);
                    var message = localizationManager.GetResource(LocalizationResources.Options.Updates.UpdateNotification.Message);
                    notificationAction.ShowNotification(title, message, NotificationType.Info, 30, onClick: () => { IsOpen = true; });
                }
            }
            else
            {
                if (!autoUpdateCheck)
                {
                    var title   = localizationManager.GetResource(LocalizationResources.Notifications.NoUpdatesAvailable.Title);
                    var message = localizationManager.GetResource(LocalizationResources.Notifications.NoUpdatesAvailable.Message);
                    notificationAction.ShowNotification(title, message, NotificationType.Info);
                }
            }
            CheckingForUpdates = false;
        }
Exemplo n.º 27
0
        /// <summary>
        /// get merged collection as an asynchronous operation.
        /// </summary>
        /// <returns>IModCollection.</returns>
        protected virtual async Task <IModCollection> GetMergedCollectionAsync()
        {
            string prefix        = localizationManager.GetResource(LocalizationResources.Collection_Mods.MergeCollection.MergedCollectionPrefix);
            var    requestedName = $"{prefix} {ActiveCollection.Name}";
            var    exists        = modCollectionService.GetAll().Any(p => p.Name.Equals(requestedName, StringComparison.OrdinalIgnoreCase));
            bool   skipNameCheck = false;

            if (exists)
            {
                var title   = localizationManager.GetResource(LocalizationResources.Collection_Mods.MergeCollection.OverwritePrompt.Title);
                var message = localizationManager.GetResource(LocalizationResources.Collection_Mods.MergeCollection.OverwritePrompt.Message);
                skipNameCheck = await notificationAction.ShowPromptAsync(title, title, message, NotificationType.Info);
            }
            var copy = CopyCollection(requestedName, skipNameCheck);

            copy.MergedFolderName = copy.Name.GenerateValidFileName();
            return(copy);
        }
        /// <summary>
        /// Analyzes the mods asynchronous.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="mode">The mode.</param>
        /// <returns>Task.</returns>
        protected virtual async Task AnalyzeModsAsync(long id, PatchStateMode mode)
        {
            SubscribeToProgressReport(id, Disposables);

            var overlayProgress = Smart.Format(localizationManager.GetResource(LocalizationResources.Mod_Actions.Overlay_Conflict_Solver_Progress), new
            {
                PercentDone = 0.ToLocalizedPercentage(),
                Count       = 1,
                TotalCount  = 4
            });
            var message = localizationManager.GetResource(LocalizationResources.Mod_Actions.Overlay_Conflict_Solver_Loading_Definitions);

            await TriggerOverlayAsync(id, true, message, overlayProgress);

            modPatchCollectionService.InvalidatePatchModState(CollectionMods.SelectedModCollection.Name);
            modPatchCollectionService.ResetPatchStateCache();

            var definitions = await Task.Run(async() =>
            {
                return(await modPatchCollectionService.GetModObjectsAsync(gameService.GetSelected(), CollectionMods.SelectedMods, CollectionMods.SelectedModCollection.Name).ConfigureAwait(false));
            }).ConfigureAwait(false);

            var conflicts = await Task.Run(() =>
            {
                if (definitions != null)
                {
                    return(modPatchCollectionService.FindConflicts(definitions, CollectionMods.SelectedMods.Select(p => p.Name).ToList(), mode));
                }
                return(null);
            }).ConfigureAwait(false);

            var syncedConflicts = await Task.Run(async() =>
            {
                return(await modPatchCollectionService.SyncPatchStateAsync(conflicts, CollectionMods.SelectedModCollection.Name).ConfigureAwait(false));
            }).ConfigureAwait(false);

            if (syncedConflicts != null)
            {
                conflicts = syncedConflicts;
            }
            var args = new NavigationEventArgs()
            {
                SelectedCollection = CollectionMods.SelectedModCollection,
                Results            = conflicts,
                State        = NavigationState.ConflictSolver,
                SelectedMods = CollectionMods.SelectedMods.Select(p => p.Name).ToList()
            };

            ReactiveUI.MessageBus.Current.SendMessage(args);
            await TriggerOverlayAsync(id, false);

            definitionAnalyzeLoadHandler?.Dispose();
            definitionLoadHandler?.Dispose();
            definitionSyncHandler?.Dispose();
        }
Exemplo n.º 29
0
        /// <summary>
        /// Analyzes the mods asynchronous.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="mode">The mode.</param>
        /// <param name="version">The version.</param>
        /// <returns>Task.</returns>
        protected virtual async Task AnalyzeModsAsync(long id, PatchStateMode mode, string version)
        {
            var totalSteps = !string.IsNullOrWhiteSpace(version) ? 6 : 4;

            SubscribeToProgressReport(id, Disposables, totalSteps);

            var overlayProgress = Smart.Format(localizationManager.GetResource(LocalizationResources.Mod_Actions.ConflictSolver.Overlay_Conflict_Solver_Progress), new
            {
                PercentDone = 0.ToLocalizedPercentage(),
                Count       = 1,
                TotalCount  = totalSteps
            });
            var message = localizationManager.GetResource(LocalizationResources.Mod_Actions.ConflictSolver.Overlay_Conflict_Solver_Loading_Definitions);

            await TriggerOverlayAsync(id, true, message, overlayProgress);

            modPatchCollectionService.InvalidatePatchModState(CollectionMods.SelectedModCollection.Name);
            modPatchCollectionService.ResetPatchStateCache();

            var game        = gameService.GetSelected();
            var definitions = await Task.Run(async() =>
            {
                var result = await modPatchCollectionService.GetModObjectsAsync(gameService.GetSelected(), CollectionMods.SelectedMods, CollectionMods.SelectedModCollection.Name).ConfigureAwait(false);
                // To stop people from whining
                GC.Collect();
                return(result);
            }).ConfigureAwait(false);

            if (!string.IsNullOrWhiteSpace(version))
            {
                await Task.Run(async() =>
                {
                    await gameIndexService.IndexDefinitionsAsync(game, version, definitions);
                    // To stop people from whining
                    GC.Collect();
                });

                definitions = await Task.Run(async() =>
                {
                    var result = await gameIndexService.LoadDefinitionsAsync(definitions, game, version);
                    // To stop people from whining
                    GC.Collect();
                    return(result);
                }).ConfigureAwait(false);
            }
            var conflicts = await Task.Run(() =>
            {
                if (definitions != null)
                {
                    // To stop people from whining
                    var result = modPatchCollectionService.FindConflicts(definitions, CollectionMods.SelectedMods.Select(p => p.Name).ToList(), mode);
                    GC.Collect();
                    return(result);
                }
                return(null);
            }).ConfigureAwait(false);

            var syncedConflicts = await Task.Run(async() =>
            {
                var result = await modPatchCollectionService.InitializePatchStateAsync(conflicts, CollectionMods.SelectedModCollection.Name).ConfigureAwait(false);
                // To stop people from whining
                GC.Collect();
                return(result);
            }).ConfigureAwait(false);

            if (syncedConflicts != null)
            {
                conflicts = syncedConflicts;
            }
            var args = new NavigationEventArgs()
            {
                SelectedCollection = CollectionMods.SelectedModCollection,
                Results            = conflicts,
                State        = NavigationState.ConflictSolver,
                SelectedMods = CollectionMods.SelectedMods.Select(p => p.Name).ToList()
            };

            ReactiveUI.MessageBus.Current.SendMessage(args);
            await TriggerOverlayAsync(id, false);

            definitionAnalyzeLoadHandler?.Dispose();
            definitionLoadHandler?.Dispose();
            definitionSyncHandler?.Dispose();
            gameIndexHandler?.Dispose();
            gameDefinitionLoadHandler?.Dispose();
            // I know, I know... but I wanna force a cleanup
            GC.Collect();
        }
Exemplo n.º 30
0
        /// <summary>
        /// Filters the hierarchal conflicts asynchronous.
        /// </summary>
        /// <param name="conflictResult">The conflict result.</param>
        /// <param name="selectedDefinitionOverride">The selected definition override.</param>
        /// <returns>Task.</returns>
        protected virtual async Task FilterHierarchalConflictsAsync(IConflictResult conflictResult, IHierarchicalDefinitions selectedDefinitionOverride = null)
        {
            while (filteringConflicts)
            {
                await Task.Delay(25);
            }
            filteringConflicts = true;
            var index = PreviousConflictIndex;

            PreviousConflictIndex = null;
            if (conflictResult != null && conflictResult.Conflicts != null)
            {
                var conflicts = conflictResult.Conflicts.GetHierarchicalDefinitions().ToList();

                var resolved = new List <IHierarchicalDefinitions>();
                if (conflictResult.ResolvedConflicts != null)
                {
                    resolved.AddRange(conflictResult.ResolvedConflicts.GetHierarchicalDefinitions());
                }
                if (conflictResult.IgnoredConflicts != null)
                {
                    resolved.AddRange(conflictResult.IgnoredConflicts.GetHierarchicalDefinitions());
                }
                if (conflictResult.RuleIgnoredConflicts != null)
                {
                    resolved.AddRange(conflictResult.RuleIgnoredConflicts.GetHierarchicalDefinitions());
                }
                foreach (var topLevelResolvedConflicts in resolved)
                {
                    IEnumerable <IHierarchicalDefinitions> topLevelConflicts;
                    if (topLevelResolvedConflicts.Name.StartsWith(LocalizationDirectory, StringComparison.OrdinalIgnoreCase))
                    {
                        topLevelConflicts = conflicts.Where(p => p.Name.StartsWith(LocalizationDirectory, StringComparison.OrdinalIgnoreCase));
                    }
                    else
                    {
                        topLevelConflicts = conflicts.Where(p => p.Name.Equals(topLevelResolvedConflicts.Name));
                    }
                    if (topLevelConflicts.Any())
                    {
                        foreach (var topLevelConflict in topLevelConflicts)
                        {
                            foreach (var childResolvedConflict in topLevelResolvedConflicts.Children)
                            {
                                var child = topLevelConflict.Children.FirstOrDefault(p => p.Key.Equals(childResolvedConflict.Key));
                                if (child != null)
                                {
                                    topLevelConflict.Children.Remove(child);
                                }
                            }
                        }
                    }
                    conflicts.RemoveAll(p => p.Children == null || p.Children.Count == 0);
                }
                var invalid = conflictResult.AllConflicts.GetByValueType(ValueType.Invalid);
                if (invalid?.Count() > 0)
                {
                    var invalidDef = DIResolver.Get <IHierarchicalDefinitions>();
                    invalidDef.Name = Invalid;
                    invalidDef.Key  = InvalidKey;
                    var children = new List <IHierarchicalDefinitions>();
                    foreach (var item in invalid)
                    {
                        var invalidChild = DIResolver.Get <IHierarchicalDefinitions>();
                        invalidChild.Name = item.File;
                        var message = item.ErrorColumn.HasValue || item.ErrorLine.HasValue ?
                                      localizationManager.GetResource(LocalizationResources.Conflict_Solver.InvalidConflicts.Error) :
                                      localizationManager.GetResource(LocalizationResources.Conflict_Solver.InvalidConflicts.ErrorNoLine);
                        invalidChild.Key = Smart.Format(message, new
                        {
                            item.ModName,
                            Line   = item.ErrorLine,
                            Column = item.ErrorColumn,
                            Environment.NewLine,
                            Message = item.ErrorMessage,
                            item.File
                        });
                        invalidChild.AdditionalData = item;
                        children.Add(invalidChild);
                    }
                    invalidDef.Children = children;
                    conflicts.Add(invalidDef);
                }
                HierarchalConflicts      = conflicts.ToObservableCollection();
                NumberOfConflictsCaption = Smart.Format(localizationManager.GetResource(LocalizationResources.Conflict_Solver.ConflictCount), new { Count = conflicts.Where(p => p.Key != InvalidKey).SelectMany(p => p.Children).Count() });
                if (HierarchalConflicts.Any() && SelectedParentConflict == null)
                {
                    SelectedParentConflict = HierarchalConflicts.FirstOrDefault();
                }
                if (SelectedParentConflict != null)
                {
                    var conflictName = SelectedParentConflict.Name;
                    SelectedParentConflict = null;
                    var newSelected = HierarchalConflicts.FirstOrDefault(p => p.Name.Equals(conflictName));
                    if (newSelected != null)
                    {
                        PreviousConflictIndex = index;
                        if (selectedDefinitionOverride != null)
                        {
                            var overrideMatch = newSelected.Children.FirstOrDefault(p => p.Key.Equals(selectedDefinitionOverride.Key));
                            if (overrideMatch != null)
                            {
                                PreviousConflictIndex = newSelected.Children.ToList().IndexOf(overrideMatch);
                            }
                        }
                        if (PreviousConflictIndex.GetValueOrDefault() > (newSelected.Children.Count - 1))
                        {
                            PreviousConflictIndex = newSelected.Children.Count - 1;
                        }
                        SelectedParentConflict = newSelected;
                    }
                }
            }
            else
            {
                HierarchalConflicts = null;
            }
            filteringConflicts = false;
        }