Exemplo n.º 1
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (TextFor.Metadata.MetadataKind != ModelMetadataKind.Property)
            {
                throw new InvalidOperationException(
                          $"The '{TextForHtmlAttributeName}' attribute is only valid to bind with a property.");
            }

            if (output.TagMode != TagMode.StartTagAndEndTag)
            {
                throw new InvalidOperationException(
                          $"The '{TextForHtmlAttributeName}' attribute can be only applied on elements that contains both start and end tags.");
            }

            if (!output.Content.IsEmptyOrWhiteSpace)
            {
                throw new InvalidOperationException(
                          $"You cannot used the '{TextForHtmlAttributeName}' attribute when the tag already has any real content in it.");
            }


            // get property definition
            var member = TextFor.Metadata.ContainerType.GetProperty(TextFor.Metadata.PropertyName,
                                                                    BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance);

            // get the localizer for the container type.
            var localizer = StringLocalizerFactory.Create(TextFor.Metadata.ContainerType);

            var memberText = member.GetTextForMember(TextSource);
            var realText   = localizer.TryGetLocalizedText(memberText);

            output.Content.SetContent(realText);
        }
        public override IStringLocalizer GetStringLocalizer()
        {
            var source = new DbStringLocalizerSource();
            var stringLocalizerFactory = new StringLocalizerFactory();

            stringLocalizerFactory.AddSource(source);
            return(stringLocalizerFactory.CreateStringLocalizer());
        }
        public override IStringLocalizer GetStringLocalizer()
        {
            var source = new ResourceManagerStringLocalizerSource(
                $"{baseName}.SharedResource",
                Assembly.GetExecutingAssembly());

            var stringLocalizerFactory = new StringLocalizerFactory();

            stringLocalizerFactory.AddSource(source);

            return(stringLocalizerFactory.CreateStringLocalizer());
        }
    protected virtual void TryToLocalizeExceptionMessage(Exception exception, RemoteServiceErrorInfo errorInfo)
    {
        //if (exception is ILocalizeErrorMessage localizeErrorMessageException)
        //{
        //    using (var scope = ServiceProvider.CreateScope())
        //    {
        //        errorInfo.Message = localizeErrorMessageException.LocalizeMessage(new LocalizationContext(scope.ServiceProvider));
        //    }

        //    return;
        //}

        if (!(exception is IHasErrorCode exceptionWithErrorCode))
        {
            return;
        }

        if (exceptionWithErrorCode.Code.IsNullOrWhiteSpace() ||
            !exceptionWithErrorCode.Code.Contains(":"))
        {
            return;
        }

        var codeNamespace = exceptionWithErrorCode.Code.Split(':')[0];

        var localizationResourceType = LocalizationOptions.ErrorCodeNamespaceMappings.GetOrDefault(codeNamespace);

        if (localizationResourceType == null)
        {
            return;
        }

        var stringLocalizer = StringLocalizerFactory.Create(localizationResourceType);
        var localizedString = stringLocalizer[exceptionWithErrorCode.Code];

        if (localizedString.ResourceNotFound)
        {
            return;
        }

        var localizedValue = localizedString.Value;

        if (exception.Data != null && exception.Data.Count > 0)
        {
            foreach (var key in exception.Data.Keys)
            {
                localizedValue = localizedValue.Replace("{" + key + "}", exception.Data[key]?.ToString());
            }
        }

        errorInfo.Message = localizedValue;
    }
        }                        // ToDo: utilize a much more powerful and ubiquitous timing and profiling tool than a stopwatch
        #endregion
        #region Constructor
        /// <summary>
        /// Constructor that populates all the injected services provided by a GenericHost, along with the injected services specific to this program that are needed by this HostedService (or derivative like BackgroundService)
        /// </summary>
        /// <param name="loggerFactory"></param>
        /// <param name="hostEnvironment"></param>
        /// <param name="hostConfiguration"></param>
        /// <param name="hostLifetime"></param>
        /// <param name="hostApplicationLifetime"></param>
        public GenerateProgramHostedService(ILoggerFactory loggerFactory, IStringLocalizerFactory stringLocalizerFactory, IHostEnvironment hostEnvironment, IConfiguration hostConfiguration, IHostLifetime hostLifetime, IConfiguration hostedServiceConfiguration, IHostApplicationLifetime hostApplicationLifetime)
        {
            StringLocalizerFactory = stringLocalizerFactory ?? throw new ArgumentNullException(nameof(stringLocalizerFactory));
            ExceptionLocalizer     = StringLocalizerFactory.Create(typeof(ATAP.Services.GenerateProgram.ExceptionResources));
            DebugLocalizer         = StringLocalizerFactory.Create(typeof(ATAP.Services.GenerateProgram.DebugResources));
            UiLocalizer            = StringLocalizerFactory.Create(typeof(ATAP.Services.GenerateProgram.UIResources));
            LoggerFactory          = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
            Logger = loggerFactory.CreateLogger <GenerateProgramHostedService>();
            // Logger = (Logger<GenerateProgramHostedService>) ATAP.Utilities.Logging.LogProvider.GetLogger("GenerateProgramHostedService");
            Logger.LogDebug(DebugLocalizer["{0} {1}: Starting"], "GenerateProgramHostedService", ".ctor"); // ToDo Fody for tracing constructors, via an optional switch
            HostEnvironment            = hostEnvironment ?? throw new ArgumentNullException(nameof(hostEnvironment));
            HostConfiguration          = hostConfiguration ?? throw new ArgumentNullException(nameof(hostConfiguration));
            HostLifetime               = hostLifetime ?? throw new ArgumentNullException(nameof(hostLifetime));
            HostedServiceConfiguration = hostedServiceConfiguration ?? throw new ArgumentNullException(nameof(hostedServiceConfiguration));
            HostApplicationLifetime    = hostApplicationLifetime ?? throw new ArgumentNullException(nameof(hostApplicationLifetime));
            InternalCancellationToken  = InternalCancellationTokenSource.Token;
            Stopwatch = new Stopwatch();
            #region Create the serviceData and initialize it from the StringConstants or this service's ConfigRoot
            Logger.LogDebug(DebugLocalizer["{0} {1}: Creating the ServiceData"], "GenerateProgramHostedService", ".ctor");

            ServiceData = new GenerateProgramHostedServiceData();
            // populate the servicedata tasks list with a single tuple for development

            // The following parameters are for each invocation of a InvokeGenerateProgramAsync call
            // invoking a GenerateProgram call may override any of these values, but absent an override, these are the
            //  default values that will be used for every InvokeGenerateProgramAsync call.
            //  the default values come from the IConfiguration HostedServiceConfiguration that is DI injected at service startup
            /// ToDo: Security: ensure the paths do not go above their Base directory

            // var gInvokeGenerateCodeSignilDefault = new GInvokeGenerateCodeSignil(
            //   new GAssemblyGroupSignil(), new GGlobalSettingsSignil(), new GSolutionSignil(),
            //   artifactsDirectoryBase: hostedServiceConfiguration.GetValue<string>(hostedServiceStringConstants.ArtifactsDirectoryBaseConfigRootKey, hostedServiceStringConstants.ArtifactsDirectoryBaseDefault), // ToDo: should validate in case the hostedServiceStringConstants assembly is messed up?
            //   artifactsFileRelativePath: hostedServiceConfiguration.GetValue<string>(hostedServiceStringConstants.ArtifactsFileRelativePathConfigRootKey, hostedServiceStringConstants.ArtifactsFileRelativePathDefault),
            //   enablePersistence: hostedServiceConfiguration.GetValue<bool>(hostedServiceStringConstants.EnablePersistenceBoolConfigRootKey, bool.Parse(hostedServiceStringConstants.EnablePersistenceBoolDefault)), // ToDo: should validate in case the hostedServiceStringConstants assembly is messed up?
            //   enablePickAndSave: hostedServiceConfiguration.GetValue<bool>(hostedServiceStringConstants.EnablePickAndSaveBoolConfigRootKey, bool.Parse(hostedServiceStringConstants.EnablePickAndSaveBoolDefault)), // ToDo: should validate in case the hostedServiceStringConstants assembly is messed up?
            //   enableProgress: hostedServiceConfiguration.GetValue<bool>(hostedServiceStringConstants.EnableProgressBoolConfigRootKey, bool.Parse(hostedServiceStringConstants.EnableProgressBoolDefault)), // ToDo: should validate in case the hostedServiceStringConstants assembly is messed up?
            //   temporaryDirectoryBase: hostedServiceConfiguration.GetValue<string>(hostedServiceStringConstants.TemporaryDirectoryBaseConfigRootKey, hostedServiceStringConstants.TemporaryDirectoryBaseDefault),
            //   persistenceMessageFileRelativePath: hostedServiceConfiguration.GetValue<string>(hostedServiceStringConstants.PersistenceMessageFileRelativePathConfigRootKey, hostedServiceStringConstants.PersistenceMessageFileRelativePathDefault),
            //   pickAndSaveMessageFileRelativePath: hostedServiceConfiguration.GetValue<string>(hostedServiceStringConstants.PickAndSaveMessageFileRelativePathConfigRootKey, hostedServiceStringConstants.PickAndSaveMessageFileRelativePathDefault),
            //   dBConnectionString: hostedServiceConfiguration.GetValue<string>(hostedServiceStringConstants.DBConnectionStringConfigRootKey, hostedServiceStringConstants.DBConnectionStringDefault),
            //   ormLiteDialectProviderStringDefault: hostedServiceConfiguration.GetValue<string>(hostedServiceStringConstants.OrmLiteDialectProviderConfigRootKey, hostedServiceStringConstants.OrmLiteDialectProviderDefault)
            // );
            // // Every invocation to GenerateProgram needs an instance of an EntryPoint class
            // gInvokeGenerateCodeSignilDefault.EntryPoints = new ATAP.Utilities.GenerateProgram.EntryPoints();
            // gInvokeGenerateCodeSignilDefault.ArtifactsFilePaths = new string[1] { gInvokeGenerateCodeSignilDefault.ArtifactsDirectoryBase + gInvokeGenerateCodeSignilDefault.ArtifactsFileRelativePath };
            // gInvokeGenerateCodeSignilDefault.PersistenceFilePaths = new string[1] { gInvokeGenerateCodeSignilDefault.TemporaryDirectoryBase + gInvokeGenerateCodeSignilDefault.PersistenceMessageFileRelativePath };
            // gInvokeGenerateCodeSignilDefault.PickAndSaveFilePaths = new string[1] { gInvokeGenerateCodeSignilDefault.TemporaryDirectoryBase + gInvokeGenerateCodeSignilDefault.PickAndSaveMessageFileRelativePath };
            // // ToDo ?: setup placeholders for the ProgressReport object
            // // ToDo ?: setup placeholders for the Persistence(File)
            // // ToDo ?: setup placeholders for the PickAndSave object
            #endregion
        }
        public override IStringLocalizer GetStringLocalizer()
        {
            var source = new JsonStringLocalizerSource
            {
                Directory       = Directory.GetCurrentDirectory() + "/Resource",
                FilePathPattern = $"SharedResource.*.json"
            };

            source.ResolveFileProvider();

            var stringLocalizerFactory = new StringLocalizerFactory();

            stringLocalizerFactory.AddSource(source);
            return(stringLocalizerFactory.CreateStringLocalizer());
        }
Exemplo n.º 7
0
        protected virtual IStringLocalizer CreateLocalizer()
        {
            if (LocalizationResourceType != null)
            {
                return(StringLocalizerFactory.Create(LocalizationResourceType));
            }

            var localizer = StringLocalizerFactory.CreateDefaultOrNull();

            if (localizer == null)
            {
                throw new AbpException($"Set {nameof(LocalizationResourceType)} or define the default localization resource type (by configuring the {nameof(AbpLocalizationOptions)}.{nameof(AbpLocalizationOptions.DefaultResourceType)}) to be able to use the {nameof(L)} object!");
            }

            return(localizer);
        }
Exemplo n.º 8
0
        private IStringLocalizer GetStringLocalizer()
        {
            string resourcesLocation = CustomResourcesLocation;

            if (string.IsNullOrWhiteSpace(resourcesLocation))
            {
                resourcesLocation = GetType().Assembly.GetName().Name;
            }

            string resourcesPath = CustomResourcesPath;

            if (string.IsNullOrWhiteSpace(resourcesPath))
            {
                resourcesPath = GetType().FullName;
            }

            return(StringLocalizerFactory.Create(resourcesPath, resourcesLocation));
        }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (output.TagMode != TagMode.SelfClosing)
            {
                throw new InvalidOperationException(
                          $"The '{TargetElementName}' element can only use the self closing mode.");
            }

            if (Value == null && For == null)
            {
                throw new InvalidOperationException(
                          $"Either the '{ValueHtmlAttributeName}' attribute or the '{ForHtmlAttributeName}' attribute should be specified.");
            }

            if (Value != null && For != null)
            {
                throw new InvalidOperationException(
                          $"Only one of the '{ValueHtmlAttributeName}' attribute and the '{ForHtmlAttributeName}' attribute can be specified.");
            }

            var realValue = Value ?? For.Model;

            if (!(realValue is Enum enumValue))
            {
                throw new InvalidOperationException(
                          $"Your specified value from the '{ValueHtmlAttributeName} attribute or the '{ForHtmlAttributeName}' attribute is not a valid enum value.");
            }

            // get property definition
            var member = enumValue.GetMember();

            // get the localizer for the container type.
            var localizer = StringLocalizerFactory?.Create(member.DeclaringType);

            var memberText = member.GetTextForMember(TextSource);
            var realText   = localizer.TryGetLocalizedText(memberText);

            output.TagName = null;
            output.Content.SetContent(realText);
        }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (output.TagMode != TagMode.SelfClosing)
            {
                throw new InvalidOperationException(
                          $"The '{TargetElementName}' element can only use the self closing mode.");
            }


            // get property definition
            var member = For.Metadata.ContainerType.GetProperty(For.Metadata.PropertyName,
                                                                BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance);

            // get the localizer for the container type.
            var localizer = StringLocalizerFactory?.Create(For.Metadata.ContainerType);

            var memberText = member.GetTextForMember(TextSource);
            var realText   = localizer.TryGetLocalizedText(memberText);

            output.TagName = null;
            output.Content.SetContent(realText);
        }
Exemplo n.º 11
0
        /// <summary>
        /// 应用字符串本地化。
        /// </summary>
        public void Apply()
        {
            var manager = StringLocalizerFactory.CreateManager();

            if (manager == null || string.IsNullOrEmpty(Name))
            {
                return;
            }

            var localizer = manager.GetLocalizer(Name);

            foreach (var kvp in _keys)
            {
                if (kvp.Key is Control control)
                {
                    control.Text = localizer[kvp.Value];
                }
                else if (kvp.Key is TreeListColumn column)
                {
                    column.Text = localizer[kvp.Value];
                }
            }
        }
Exemplo n.º 12
0
        public HomeController() : base()
        {
            StringLocalizerFactory sl = new StringLocalizerFactory();

            _htmlLocalizer = sl.Create("Translation", "Resources");
        }
Exemplo n.º 13
0
 private IStringLocalizer GetStringLocalizer(string resourceName)
 {
     return(StringLocalizerFactory.Create(resourceName, typeof(Program).Assembly.FullName));
 }
Exemplo n.º 14
0
        /// <summary>
        /// Get override string localizer
        /// </summary>
        /// <returns></returns>
        private static IStringLocalizer GetLocalizer()
        {
            StringLocalizerFactory sl = new StringLocalizerFactory();

            return(sl.Create("Translation", "Resources"));
        }
        public void TestNoExistsKey()
        {
            var localizer = StringLocalizerFactory.CreateManager().GetLocalizer("Localization.Test", typeof(DefaultStringLocalizerTest).Assembly);

            Console.WriteLine(localizer["String6"]);
        }
        public void TestNoExists()
        {
            var localizer = StringLocalizerFactory.CreateManager().GetLocalizer("Localization.Test", CultureInfo.GetCultureInfo("ru"), typeof(DefaultStringLocalizerTest).Assembly);

            Console.WriteLine(localizer["String3", "c:\\1.txt"]);
        }
Exemplo n.º 17
0
 public IStringLocalizer GetLocalizer <T>()
 {
     return(StringLocalizerFactory.Create <T>());
 }
Exemplo n.º 18
0
 public IStringLocalizer GetDefaultLocalizer()
 {
     return(StringLocalizerFactory.CreateDefaultOrNull());
 }
        public void TestWithCulture()
        {
            var localizer = StringLocalizerFactory.CreateManager().GetLocalizer("Localization.Test", CultureInfo.GetCultureInfo("en"), typeof(DefaultStringLocalizerTest).Assembly);

            Console.WriteLine(localizer["String1"]);
        }
Exemplo n.º 20
0
 public IStringLocalizer GetLocalizer(Type resourceType)
 {
     return(StringLocalizerFactory.Create(resourceType));
 }
        public void TestFormat()
        {
            var localizer = StringLocalizerFactory.CreateManager().GetLocalizer("Localization.Test", typeof(DefaultStringLocalizerTest).Assembly);

            Console.WriteLine(localizer["String3", "c:\\1.txt"]);
        }