예제 #1
0
 public FileController(IUploadStorage uploadStorage, ITextLocalizer localizer)
 {
     UploadStorage = uploadStorage ??
                     throw new ArgumentNullException(nameof(uploadStorage));
     Localizer = localizer ??
                 throw new ArgumentNullException(nameof(localizer));
 }
예제 #2
0
        /// <summary>
        /// Formats the enum.
        /// </summary>
        /// <param name="localizer">Text localizer</param>
        /// <param name="enumType">Type of the enum.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string FormatEnum(this ITextLocalizer localizer, Type enumType, object value)
        {
            if (value == null)
            {
                return(string.Empty);
            }

            if (enumType != null &&
                enumType.IsEnum &&
                System.Enum.GetName(enumType, value) != null)
            {
                var enumName = System.Enum.GetName(enumType, value);
                var enumKey  = GetEnumTypeKey(enumType);
                var key      = "Enums." + enumKey + "." + enumName;
                var text     = localizer?.TryGet(key);
                if (text == null)
                {
                    var memInfo = enumType.GetMember(enumName);
                    if (memInfo != null && memInfo.Length == 1)
                    {
                        var attribute = memInfo[0].GetCustomAttribute <DescriptionAttribute>(false);
                        if (attribute != null)
                        {
                            text = attribute.Description;
                        }
                    }
                }

                return(text ?? enumName);
            }
            else
            {
                return(value.ToString());
            }
        }
 public MultipleImageUploadBehavior(ITextLocalizer localizer, IUploadStorage storage,
                                    IExceptionLogger logger = null)
 {
     this.localizer = localizer;
     this.storage   = storage;
     this.logger    = logger;
 }
예제 #4
0
            public static string ValidateUsername(IDbConnection connection, string username, int?existingUserId,
                                                  ITextLocalizer localizer)
            {
                username = username.TrimToNull();

                if (username == null)
                {
                    throw DataValidation.RequiredError(fld.Username, localizer);
                }

                if (!IsValidUsername(username))
                {
                    throw new ValidationError("InvalidUsername", "Username",
                                              "Usernames should start with letters, only contain letters and numbers!");
                }

                var existing = GetUser(connection,
                                       new Criteria(fld.Username) == username |
                                       new Criteria(fld.Username) == username.Replace('I', 'İ'));

                if (existing != null && existingUserId != existing.UserId)
                {
                    throw new ValidationError("UniqueViolation", "Username",
                                              "A user with same name exists. Please choose another!");
                }

                return(username);
            }
예제 #5
0
 public ReportRegistry(ITypeSource typeSource, IPermissionService permissions, ITextLocalizer localizer)
 {
     types = (typeSource ?? throw new ArgumentNullException(nameof(types)))
             .GetTypesWithAttribute(typeof(ReportAttribute));
     this.permissions = permissions ?? throw new ArgumentNullException(nameof(permissions));
     this.localizer   = localizer ?? throw new ArgumentNullException(nameof(localizer));
 }
예제 #6
0
 public static ValidationError EntityWriteAccessError(IRow row, long id, ITextLocalizer localizer)
 {
     return(new ValidationError("EntityWriteAccessError", null,
                                Texts.Validation.EntityWriteAccessViolation.ToString(localizer),
                                Convert.ToString(id, CultureInfo.CurrentCulture),
                                GetEntitySingular(row.Table, localizer)));
 }
예제 #7
0
 public static void ValidateEnum(this IRow row, Field field, Type enumType, ITextLocalizer localizer)
 {
     if (!Enum.IsDefined(enumType, field.AsObject(row)))
     {
         throw InvalidValueError(row, field, localizer);
     }
 }
예제 #8
0
 public virtual void CheckRights(IPermissionService permissions, ITextLocalizer localizer)
 {
     if (Permission != null)
     {
         permissions.ValidatePermission(Permission, localizer);
     }
 }
예제 #9
0
        public String GetDisplayNameLocalized(ITextLocalizer localizer)
        {
            String identifierString = null;

            if (Position != null)
            {
                identifierString += String.Format("{0}", Position);
            }
            if (identifierString == null)
            {
                if (String.IsNullOrEmpty(Artist) == false)
                {
                    identifierString += String.Format("{0}", Artist);
                }
                if (String.IsNullOrEmpty(Title) == false)
                {
                    if (identifierString != null)
                    {
                        identifierString += ",";
                    }
                    identifierString += String.Format("{0}", Title);
                }
            }
            return(String.Format("{0} ({1})", localizer[nameof(Track)], identifierString));
        }
예제 #10
0
 public static void ValidateEnum <T>(T value, ITextLocalizer localizer)
 {
     if (!Enum.IsDefined(typeof(T), value))
     {
         throw ArgumentOutOfRange(typeof(T).Name, localizer);
     }
 }
 public CustomerGrossSalesReport(ISqlConnections sqlConnections,
                                 ITextLocalizer localizer, IServiceProvider serviceProvider)
 {
     SqlConnections  = sqlConnections ?? throw new ArgumentNullException(nameof(sqlConnections));
     Localizer       = localizer ?? throw new ArgumentNullException(nameof(localizer));
     ServiceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
 }
예제 #12
0
 public static void ValidateEnum <T>(this IRow row, GenericValueField <T> field,
                                     ITextLocalizer localizer) where T : struct, IComparable <T>
 {
     if (!Enum.IsDefined(field.EnumType, field.AsObject(row)))
     {
         throw InvalidValueError(row, field, localizer);
     }
 }
 /// <summary>
 /// Checks if there is a currently logged user and throws a validation error with
 /// "NotLoggedIn" error code if not.
 /// </summary>
 public static void ValidateLoggedIn(this IUserAccessor userAccessor, ITextLocalizer localizer)
 {
     if (!IsLoggedIn(userAccessor))
     {
         throw new ValidationError("NotLoggedIn", null,
                                   Core.Texts.Authorization.NotLoggedIn.ToString(localizer));
     }
 }
 public ExtendedValidationAttributeAdapter(TAttribute attribute, IStringLocalizer?stringLocalizer)
     : base(attribute, stringLocalizer)
 {
     _textLocalizer =
         stringLocalizer != null ?
         stringLocalizer as StringLocalizerAdapter ?? new StringLocalizerAdapter(stringLocalizer) :
         (ITextLocalizer)NullTextLocalizer.Instance;
 }
        /// <summary>
        /// Gets translation for a key
        /// </summary>
        /// <param name="localTexts">The local texts</param>
        /// <param name="key">Key</param>
        /// <returns>Translated text or key itself if no translation found</returns>
        public static string Get(this ITextLocalizer localTexts, string key)
        {
            if (localTexts == null)
            {
                throw new ArgumentNullException(nameof(localTexts));
            }

            return(localTexts.TryGet(key) ?? key);
        }
        public static void HandleDeleteForeignKeyException(Exception e, ITextLocalizer localizer)
        {
            ForeignKeyExceptionInfo fk;

            if (SqlExceptionHelper.IsForeignKeyException(e, out fk))
            {
                throw new ValidationError(String.Format(Texts.Validation.DeleteForeignKeyError.ToString(localizer), fk.TableName));
            }
        }
예제 #17
0
 public DynamicScriptManager(ITwoLevelCache cache, IPermissionService permissions, ITextLocalizer localizer)
 {
     this.cache        = cache ?? throw new ArgumentNullException(nameof(cache));
     this.permissions  = permissions ?? throw new ArgumentNullException(nameof(permissions));
     this.localizer    = localizer;
     registeredScripts = new ConcurrentDictionary <string, IDynamicScript>(StringComparer.OrdinalIgnoreCase);
     scriptLastChange  = new ConcurrentDictionary <string, DateTime>();
     Register(new RegisteredScripts(this));
 }
예제 #18
0
        /// <summary>
        /// Gets the display text of the enum value.
        /// </summary>
        /// <param name="localizer">Text localizer</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string GetText(this Enum value, ITextLocalizer localizer)
        {
            if (value == null)
            {
                return(string.Empty);
            }

            return(FormatEnum(localizer, value.GetType(), value));
        }
예제 #19
0
        /// <summary>
        /// Handles the localization of datagrid based on the built-int localizer and a custom localizer handler.
        /// </summary>
        /// <param name="textLocalizer">Default localizer.</param>
        /// <param name="textLocalizerHandler">Custom localizer.</param>
        /// <param name="name">Localization name.</param>
        /// <param name="arguments">Arguments to format the text.</param>
        /// <returns>Returns the localized text.</returns>
        public static string Localize(this ITextLocalizer textLocalizer, TextLocalizerHandler textLocalizerHandler, string name, params object[] arguments)
        {
            if (textLocalizerHandler != null)
            {
                return(textLocalizerHandler.Invoke(name, arguments));
            }

            return(textLocalizer[name, arguments]);
        }
        public static void HandleSavePrimaryKeyException(Exception e, ITextLocalizer localizer, string fieldName = "ID")
        {
            PrimaryKeyExceptionInfo fk;

            if (SqlExceptionHelper.IsPrimaryKeyException(e, out fk))
            {
                throw new ValidationError(String.Format(Texts.Validation.SavePrimaryKeyError.ToString(localizer), fk.TableName, fieldName));
            }
        }
예제 #21
0
 public static void ValidateDateRange(this IRow row, DateTimeField start, DateTimeField finish,
                                      ITextLocalizer localizer)
 {
     if (!start.IsNull(row) &&
         !finish.IsNull(row) &&
         start[row].Value > finish[row].Value)
     {
         throw InvalidDateRangeError(start, finish, localizer);
     }
 }
        public String GetValidationErrors(ITextLocalizer localizer, String property = null, ValidationErrorFilterType validationErrorFilterType = ValidationErrorFilterType.All, String seperator = "<br />")
        {
            var errorsFiltered = GetValidationErrorsFiltered(property, validationErrorFilterType);

            if (errorsFiltered.Any())
            {
                return(String.Join(seperator, errorsFiltered.OrderBy(y => y.Type).Select(x => x.Message.GetMessageLocalized(localizer))));
            }
            return(null);
        }
예제 #23
0
        public static void ValidateRequired(this IRow row, Field field, ITextLocalizer localizer)
        {
            var str = field as StringField;

            if ((str is object && str[row].IsTrimmedEmpty()) ||
                (str is null && field.AsObject(row) == null))
            {
                throw RequiredError(field, localizer);
            }
        }
예제 #24
0
        public override string FormatErrorMessage(string localizedName, ITextLocalizer textLocalizer, IServiceProvider?serviceProvider = null)
        {
            var validator = serviceProvider != null?GetValidator(serviceProvider) : null;

            if (validator == null)
            {
                return(FormatErrorMessageFallback(localizedName, textLocalizer, serviceProvider));
            }

            return(_validatorHelper.FormatErrorMessage(validator, localizedName, textLocalizer, this));
        }
예제 #25
0
        public static void CheckParentNotDeleted(IDbConnection connection, string tableName,
                                                 Action <SqlQuery> filter, ITextLocalizer localizer)
        {
            var query = new SqlQuery().Dialect(connection.GetDialect()).Select("1").From(tableName, Alias.T0);

            filter(query);
            if (query.Take(1).Exists(connection))
            {
                throw DataValidation.ParentRecordDeleted(tableName, localizer);
            }
        }
예제 #26
0
        public static string GetReportCategoryTitle(string key, ITextLocalizer localizer)
        {
            var title = localizer?.TryGet("Report.Category." + key.Replace("/", "."));

            if (title == null)
            {
                key ??= "";
                var idx = key.LastIndexOf('/');
                if (idx >= 0 && idx < key.Length - 1)
                {
                    key = key[(idx + 1)..];
예제 #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LocalizationManager" /> class.
        /// </summary>
        /// <param name="configurationManager">The configuration manager.</param>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="jsonSerializer">The json serializer.</param>
        public LocalizationManager(IServerConfigurationManager configurationManager, IFileSystem fileSystem, IJsonSerializer jsonSerializer, ILogger logger, IAssemblyInfo assemblyInfo, ITextLocalizer textLocalizer)
        {
            _configurationManager = configurationManager;
            _fileSystem           = fileSystem;
            _jsonSerializer       = jsonSerializer;
            _logger        = logger;
            _assemblyInfo  = assemblyInfo;
            _textLocalizer = textLocalizer;

            ExtractAll();
        }
예제 #28
0
        public static List <ReportColumn> EntityTypeToList(IRow instance, ITextLocalizer localizer)
        {
            var list = new List <ReportColumn>();

            foreach (var field in instance.GetFields())
            {
                list.Add(FromField(field, localizer));
            }

            return(list);
        }
예제 #29
0
        public static string ValidateDisplayName(string displayName, ITextLocalizer localizer)
        {
            displayName = displayName.TrimToNull();

            if (displayName == null)
            {
                throw DataValidation.RequiredError(fld.DisplayName, localizer);
            }

            return(displayName);
        }
예제 #30
0
 public NullRequestContext(IBehaviorProvider behaviors    = null,
                           ITwoLevelCache cache           = null,
                           ITextLocalizer localizer       = null,
                           IPermissionService permissions = null,
                           IUserAccessor userAccessor     = null)
 {
     Behaviors    = behaviors ?? new NullBehaviorProvider();
     Cache        = cache ?? new NullTwoLevelCache();
     Localizer    = localizer ?? NullTextLocalizer.Instance;
     Permissions  = permissions ?? new NullPermissions();
     UserAccessor = userAccessor ?? new NullUserAccessor();
 }
예제 #31
0
파일: NuggetLocalizer.cs 프로젝트: uQr/i18n
        public NuggetLocalizer(
            i18nSettings settings,
            ITextLocalizer textLocalizer)
        {
            _settings = settings;
            _textLocalizer = textLocalizer;

            _nuggetParser = new NuggetParser(new NuggetTokens(
                _settings.NuggetBeginToken,
                _settings.NuggetEndToken,
                _settings.NuggetDelimiterToken,
                _settings.NuggetCommentToken),
                NuggetParser.Context.ResponseProcessing);
        }