Esempio n. 1
0
        public IEnumerable <TextResourceEntity> GetByGroupName(string groupName, string locale)
        {
            if (TextCache.ContainsKey(groupName))
            {
                return(TextCache[groupName].Where(e =>
                                                  string.Equals(e.Lang.Name, locale, StringComparison.InvariantCultureIgnoreCase) ||
                                                  string.Equals(e.Lang.TwoLetterISOLanguageName, locale, StringComparison.InvariantCultureIgnoreCase) ||
                                                  string.Equals(e.Lang.ThreeLetterWindowsLanguageName, locale,
                                                                StringComparison.InvariantCultureIgnoreCase)));
            }

            return(Enumerable.Empty <TextResourceEntity>());
        }
Esempio n. 2
0
        public object Compile(string key, CultureInfo culture, out bool found)
        {
            var translation = TextCache.SelectMany(e => e.Value)
                              .FirstOrDefault(e => string.Equals(e.Key, key, StringComparison.OrdinalIgnoreCase) && Equals(e.Lang, culture));

            if (translation.Text == null)
            {
                found = false;
                return("[MISSING: " + key + "]");
            }
            found = true;
            return(translation.Text);
        }
        /// <summary>
        ///		Gets the stored <see cref="TextResourceEntity"/> that matches the key and the culture (or <see cref="CultureInfo.CurrentUICulture"/> if null)
        /// </summary>
        public TextResourceEntity?GetEntryOrNull(string key, CultureInfo culture = null)
        {
            culture = culture ?? CultureInfo.CurrentUICulture;

            if (TextCache.TryGetValue(TransformKey(key), out var res))
            {
                return(res.FirstOrDefault(e => e.Lang.Equals(culture)));
            }

            if (NotFound.TryGetValue(culture, out var nf))
            {
                return(nf);
            }

            return(null);
        }
Esempio n. 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IApplicationSettings appSettings = new ApplicationSettings();

            Configuration.Bind(appSettings);

            services.AddSingleton(appSettings);
            services.AddSingleton <IAppMongoClient, AppMongoClient>();

            ILanguage languageProvider = new TextCache();

            languageProvider.Initialise(_env.IsDevelopment());

            services.AddSingleton(languageProvider);

            services.AddIdentity <ApplicationUserMongo, ApplicationRoleMongo>()
            .AddMongoDbStores <ApplicationUserMongo, ApplicationRoleMongo, Guid>
            (
                appSettings.ConnectionString, appSettings.DatabaseName
            )
            .AddDefaultTokenProviders();

            // Add application services.
            services.AddScoped <INotification, EmailSender>();
            CommonStartup.AddCommonServices(services);

            services.AddScoped <IAuthService, AuthService <ApplicationUserMongo, ApplicationRoleMongo> >();

            services.AddScoped <IExpensesData, ExpensesDataMongo>();

            services.AddScoped <ISessionInfo, SessionInfo>();

            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                //options.IdleTimeout = TimeSpan.FromSeconds(10);
                options.Cookie.HttpOnly = true;
                // Make the session cookie essential
                options.Cookie.IsEssential = true;
            });

            services.AddAutoMapper();
            services.AddMvc();
        }
Esempio n. 5
0
        public void TextCache_Get()
        {
            TextCache         cache         = new TextCache(Connection);
            FileSpecification specification = new FileSpecification
                                              (
                IrbisPath.MasterFile,
                "IBIS",
                "!101.PFT"
                                              );
            string first = cache.Get(specification);

            Debug.Assert(first == null);
            first = cache.GetOrRequest(specification);
            Debug.Assert(first != null);
            Debug.Assert(cache.RequestCount == 1);

            string second = cache.Get(specification);

            Debug.Assert(second != null);
            Debug.Assert(cache.RequestCount == 1);
        }
Esempio n. 6
0
 private void GetTextParameters(string textToBuild, Rect textRect, FontFile.FontSize fontSize, RectAlignment alignment, out TextCache cachedText, out float scale, out float textWidth, out Rect realTextRect)
 {
     realTextRect = textRect;
     scale        = 1f;
     textWidth    = 0f;
     if (!string.IsNullOrEmpty(textToBuild))
     {
         cachedText = gui.textCache.GetCached((fontSize, textToBuild, uint.MaxValue));
         textWidth  = gui.PixelsToUnits(cachedText.texRect.w);
         if (textWidth > realTextRect.Width)
         {
             scale = realTextRect.Width / textWidth;
         }
         else
         {
             realTextRect = ImGui.AlignRect(textRect, alignment, textWidth, textRect.Height);
         }
     }
     else
     {
         realTextRect = ImGui.AlignRect(textRect, alignment, 0f, textRect.Height);
         cachedText   = null;
     }
 }
Esempio n. 7
0
 // Initializes state used across a measure/arrange calculation.
 private void EnsureCache()
 {
     if (_cache == null)
     {
         _cache = new TextCache(this);
     }
 }
Esempio n. 8
0
        static public bool FilterIndexable(Indexable indexable, TextCache text_cache, out Filter filter)
        {
            filter = null;
            ICollection filters = null;

            if (indexable.Filtering == IndexableFiltering.AlreadyFiltered)
            {
                return(true);
            }

            if (!ShouldWeFilterThis(indexable))
            {
                return(false);
            }

            string path = null;

            // First, figure out which filter we should use to deal with
            // the indexable.

            // If a specific mime type is specified, try to index as that type.
            if (indexable.MimeType != null)
            {
                filters = CreateFiltersFromMimeType(indexable.MimeType);
            }

            if (indexable.ContentUri.IsFile)
            {
                path = indexable.ContentUri.LocalPath;

                // Otherwise, set the mime type for a directory,
                // or sniff it from the file.
                if (indexable.MimeType == null)
                {
                    if (Directory.Exists(path))
                    {
                        indexable.MimeType  = "inode/directory";
                        indexable.NoContent = true;
                    }
                    else if (File.Exists(path))
                    {
                        indexable.MimeType = null;                        // XdgMime.GetMimeType(path);
                    }
                    else
                    {
                        //Log.Warn ("Unable to filter {0}.  {1} not found.", indexable.DisplayUri, path);
                        return(false);
                    }
                }

                // Set the timestamp to the last write time, if it isn't
                // set by the backend.
                if (!indexable.ValidTimestamp && indexable.IsNonTransient)
                {
                    indexable.Timestamp = System.IO.File.GetLastWriteTimeUtc(path);
                }
                //FileSystem.GetLastWriteTimeUtc (path);

                // Check the timestamp to make sure the file hasn't
                // disappeared from underneath us.
                //if (! System.IO.File.ExistsByDateTime (indexable.Timestamp)) {
                //Log.Warn ("Unable to filter {0}.  {1} appears to have disappeared from underneath us", indexable.DisplayUri, path);
                //	return false;
                //}

                if (filters == null || filters.Count == 0)
                {
                    filters = CreateFiltersFromIndexable(indexable);
                }
            }

            // We don't know how to filter this, so there is nothing else to do.
            if (filters.Count == 0)
            {
                //if (! indexable.NoContent)
                //	Logger.Log.Debug ("No filter for {0} ({1}) [{2}]", indexable.DisplayUri, path, indexable.MimeType);

                return(false);
            }

            foreach (Filter candidate_filter in filters)
            {
                //if (Debug)
                //	Logger.Log.Debug ("Testing filter: {0}", candidate_filter);

                // Hook up the snippet writer.
                if (candidate_filter.SnippetMode && text_cache != null)
                {
                    /*
                     * if (candidate_filter.OriginalIsText && indexable.IsNonTransient) {
                     *      text_cache.MarkAsSelfCached (indexable.Uri);
                     * } else if (indexable.CacheContent) {
                     *      TextWriter writer = text_cache.GetWriter (indexable.Uri);
                     *      candidate_filter.AttachSnippetWriter (writer);
                     * }
                     * */
                }

                // Set the indexable on the filter.
                candidate_filter.Indexable = indexable;

                // Open the filter, copy the file's properties to the indexable,
                // and hook up the TextReaders.

                bool       successful_open = false;
                TextReader text_reader;
                Stream     binary_stream;

                if (path != null)
                {
                    successful_open = candidate_filter.Open(path);
                }
                else if ((text_reader = indexable.GetTextReader()) != null)
                {
                    successful_open = candidate_filter.Open(text_reader);
                }
                else if ((binary_stream = indexable.GetBinaryStream()) != null)
                {
                    successful_open = candidate_filter.Open(binary_stream);
                }

                if (successful_open)
                {
                    // Set FileType
                    indexable.AddProperty(Property.NewKeyword("beagle:FileType", candidate_filter.FileType));

                    indexable.SetTextReader(candidate_filter.GetTextReader());
                    indexable.SetHotTextReader(candidate_filter.GetHotTextReader());
#if ENABLE_RDF_ADAPTER
                    indexable.Links = candidate_filter.Links;
#endif

                    //if (Debug)
                    //	Logger.Log.Debug ("Successfully filtered {0} with {1}", path, candidate_filter);

                    filter = candidate_filter;
                    return(true);
                }
                else
                {
                    //Log.Warn ("Error in filtering {0} with {1}, falling back", path, candidate_filter);
                    candidate_filter.Cleanup();
                }
            }

            //if (Debug)
            //	Logger.Log.Debug ("None of the matching filters could process the file: {0}", path);

            return(false);
        }
Esempio n. 9
0
        public async Task LoadTexts()
        {
            TextCache.Clear();
            TranslationCacheState.Clear();

            var textResources = new Dictionary <string, List <TextResourceEntity> >();

            foreach (var cultureInfo in SupportedCultures)
            {
                var resources        = new Dictionary <string, object>();
                var translationCache = new StringBuilder();

                foreach (var translationResource in TranslationResources)
                {
                    if (translationResource is IAsyncTranslationProvider asyncTranslationProvider)
                    {
                        foreach (var provideTranslation in
                                 await asyncTranslationProvider.ProvideTranslationsAsync(cultureInfo))
                        {
                            resources.Add(provideTranslation.Key, provideTranslation.Value);
                        }
                    }

                    foreach (var provideTranslation in
                             translationResource.ProvideTranslations(cultureInfo))
                    {
                        resources.Add(provideTranslation.Key, provideTranslation.Value);
                    }
                }

                var localResources = new List <TextResourceEntity>();
                foreach (var textResource in resources)
                {
                    var key      = textResource.Key;
                    var keyParts = key.Split('/');
                    localResources.Add(new TextResourceEntity
                    {
                        Key  = key,
                        Page = keyParts[0],
                        Text = textResource.Value,
                        Lang = cultureInfo
                    });
                }

                var transformedResources = localResources
                                           .Select(localResource => new TextResourceEntity
                {
                    Key  = localResource.Key,
                    Text = TransformText(localResource, localResources),
                    Lang = localResource.Lang,
                    Page = localResource.Page
                }).ToList();

                //Process References
                foreach (var group in transformedResources.GroupBy(e => e.Page))
                {
                    foreach (var textResourceEntity in group)
                    {
                        translationCache.AppendLine(textResourceEntity.Page + "-" + textResourceEntity.Text);
                    }

                    List <TextResourceEntity> cache;
                    if (!textResources.ContainsKey(group.Key))
                    {
                        textResources[group.Key] = cache = new List <TextResourceEntity>();
                    }
                    else
                    {
                        cache = textResources[group.Key];
                    }

                    cache.AddRange(group.ToArray());
                }

                var hash = MD5
                           .Create()
                           .ComputeHash(Encoding.Unicode.GetBytes(translationCache.ToString()))
                           .Select(e => e.ToString("X2").ToUpper())
                           .Aggregate((e, f) => e + f);
                TranslationCacheState.Add(cultureInfo, hash);
            }

            if (_loaderExceptions.Any())
            {
                throw new AggregateException(_loaderExceptions.GroupBy(e => e.Message).Select(e => e.First()).ToArray())
                      .Flatten();
            }

            foreach (var textResource in textResources)
            {
                TextCache[textResource.Key] = textResource.Value.ToArray();
            }
        }