Dictionary<string, Dictionary<string, string>> locDictionary;	// Collection of language dictionaries.

	void Awake()
	{
		// Register this script as the singleton instance.
		Instance = this;

		// Read the localization string data file.
		locDictionary = CSVReader.Read("Localization");
		var first = locDictionary.ElementAt(0).Value;
		if (first.Count <= 0)
		{
			Debug.Log("Invalid localization file. No language found!");
			return;
		}

		// Get the list of available languages.
		languages = new List<string>();
		foreach (string k in first.Keys)
		{
			languages.Add(k);
		}

		// If we don't have a language selected, default to the first language in our list.
		if (currentLanguage == null || currentLanguage.Length == 0)
		{
			currentLanguage = languages.First();
		}
	}
 /// <summary>
 /// Boot the game
 /// </summary>
 public override void Initialize()
 {
     ReferencesHolder.Instance.GameConfigurationHolder = new GameConfigurationHolder(CONFIGURATION_FILE_PATH);
     LocalizationManager localizationManager = new LocalizationManager();
     localizationManager.Initialize();
     ReferencesHolder.Instance.LocalizationManager = localizationManager;
     base.Initialize();
 }
        static ApplicationLocalizationContext()
        {
            Settings = ConfigurationManager.GetSection("localizationContext") as LocalizationContextConfigurationSection;

            LocalizationManager = new LocalizationManager(
                new SimpleLanguageContextProvider(), 
                Settings.FetchAllowedLanguages()
            );
        }
 void Awake() {
     if (instance == null) {
         // Primera instancia de LocalizationManager
         instance = this;
         DontDestroyOnLoad(gameObject);
         _language = "es";
         InitializationAndLocalization();
     } else if (!instance.Equals(this)) {
         // Otra instancia creada
         Destroy(gameObject);
     }
 }
示例#5
0
    public static void Init()
    {
        if ( !IsInitialized )
        {
            ResLoader = new LocalResourceLoader();
            Coroutines = new CoroutineManager();
            Settings = new LocalSettingsManager();
            Input = new InputManager();
            Logger = new Logger();
            Time = new TimeProvider();
            Random = new RandomGenerator();

            Localization = new LocalizationManager();

            Sound = new SoundManager( Settings.GetBool( SoundManager.SOUND_ON_KEY, true ), Settings.GetBool( SoundManager.MUSIC_ON_KEY, true ) );
            UI = new GUIManager( ResLoader );
            IsInitialized = true;
        }
    }
		public void Setup()
		{
			_collectionSettings = new CollectionSettings(new NewCollectionSettings()
			{
				PathToSettingsFile = CollectionSettings.GetPathForNewSettings(new TemporaryFolder("BookDataTests").Path, "test"),
				Language1Iso639Code = "xyz",
				Language2Iso639Code = "en",
				Language3Iso639Code = "fr"
			});
			ErrorReport.IsOkToInteractWithUser = false;

			var localizationDirectory = FileLocator.GetDirectoryDistributedWithApplication("localization");
			_localizationManager = LocalizationManager.Create("fr", "Bloom", "Bloom", "1.0.0", localizationDirectory, "SIL/Bloom",
				null, "", new string[] {});
			_palasoLocalizationManager = LocalizationManager.Create("fr", "Palaso","Palaso", "1.0.0", localizationDirectory, "SIL/Bloom",
				null, "", new string[] { });

			_brandingFolder = new TemporaryFolder("unitTestBrandingFolder");
			_pathToBrandingSettingJson = _brandingFolder.Combine("settings.json");
		}
示例#7
0
        internal string GetRtbText(SuperGridControl superGrid)
        {
            using (LocalizationManager lm = new LocalizationManager(superGrid))
            {
                string s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterSampleExpr);

                if (s == "")
                {
                    using (Stream stream = typeof(SampleExpr).Assembly.GetManifestResourceStream(
                        "DevComponents.DotNetBar.SuperGrid.SampleExpr.rtf"))
                    {
                        if (stream != null)
                        {
                            using (StreamReader reader = new StreamReader(stream))
                                s = reader.ReadToEnd();
                        }
                    }
                }

                return (s);
            }
        }
示例#8
0
        public async Task <PagedResultDto <LanguageTextListDto> > GetLanguageTexts(GetLanguageTextsInput input)
        {
            /* Note: This method is used by SPA without paging, MPA with paging.
             * So, it can both usable with paging or not */

            //Normalize base language name
            if (input.BaseLanguageName.IsNullOrEmpty())
            {
                var defaultLanguage = await _applicationLanguageManager.GetDefaultLanguageOrNullAsync(AbpSession.TenantId);

                if (defaultLanguage == null)
                {
                    defaultLanguage = (await _applicationLanguageManager.GetLanguagesAsync(AbpSession.TenantId)).FirstOrDefault();
                    if (defaultLanguage == null)
                    {
                        throw new Exception("No language found in the application!");
                    }
                }

                input.BaseLanguageName = defaultLanguage.Name;
            }

            var source        = LocalizationManager.GetSource(input.SourceName);
            var baseCulture   = CultureInfo.GetCultureInfo(input.BaseLanguageName);
            var targetCulture = CultureInfo.GetCultureInfo(input.TargetLanguageName);

            var languageTexts = source
                                .GetAllStrings()
                                .Select(localizedString => new LanguageTextListDto
            {
                Key         = localizedString.Name,
                BaseValue   = _applicationLanguageTextManager.GetStringOrNull(AbpSession.TenantId, source.Name, baseCulture, localizedString.Name),
                TargetValue = _applicationLanguageTextManager.GetStringOrNull(AbpSession.TenantId, source.Name, targetCulture, localizedString.Name, false)
            })
                                .AsQueryable();

            //Filters
            if (input.TargetValueFilter == "EMPTY")
            {
                languageTexts = languageTexts.Where(s => s.TargetValue.IsNullOrEmpty());
            }

            if (!input.FilterText.IsNullOrEmpty())
            {
                languageTexts = languageTexts.Where(
                    l => (l.Key != null && l.Key.IndexOf(input.FilterText, StringComparison.CurrentCultureIgnoreCase) >= 0) ||
                    (l.BaseValue != null && l.BaseValue.IndexOf(input.FilterText, StringComparison.CurrentCultureIgnoreCase) >= 0) ||
                    (l.TargetValue != null && l.TargetValue.IndexOf(input.FilterText, StringComparison.CurrentCultureIgnoreCase) >= 0)
                    );
            }

            var totalCount = languageTexts.Count();

            //Ordering
            if (!input.Sorting.IsNullOrEmpty())
            {
                languageTexts = languageTexts.OrderBy(input.Sorting);
            }

            //Paging
            if (input.SkipCount > 0)
            {
                languageTexts = languageTexts.Skip(input.SkipCount);
            }

            if (input.MaxResultCount > 0)
            {
                languageTexts = languageTexts.Take(input.MaxResultCount);
            }

            return(new PagedResultDto <LanguageTextListDto>(
                       totalCount,
                       languageTexts.ToList()
                       ));
        }
示例#9
0
        private async void ChangeSettingsAction()
        {
            MovingFiles = true;
            bool overwrite    = false;
            bool forceRestart = false;

            // Check if there are any settings files in the folder...
            if (FilesContainsSettingsFiles(Directory.GetFiles(LocationSelectedPath)))
            {
                MetroDialogSettings settings = AppearanceManager.MetroDialog;

                settings.AffirmativeButtonText    = LocalizationManager.GetStringByKey("String_Button_Overwrite");
                settings.NegativeButtonText       = LocalizationManager.GetStringByKey("String_Button_Cancel");
                settings.FirstAuxiliaryButtonText = LocalizationManager.GetStringByKey("String_Button_MoveAndRestart");
                settings.DefaultButtonFocus       = MessageDialogResult.FirstAuxiliary;

                MessageDialogResult result = await dialogCoordinator.ShowMessageAsync(this, LocalizationManager.GetStringByKey("String_Header_Overwrite"), LocalizationManager.GetStringByKey("String_OverwriteSettingsInTheDestinationFolder"), MessageDialogStyle.AffirmativeAndNegativeAndSingleAuxiliary, AppearanceManager.MetroDialog);

                if (result == MessageDialogResult.Negative)
                {
                    MovingFiles = false;
                    return;
                }
                else if (result == MessageDialogResult.Affirmative)
                {
                    overwrite = true;
                }
                else if (result == MessageDialogResult.FirstAuxiliary)
                {
                    forceRestart = true;
                }
            }

            // Try moving files (permissions, file is in use...)
            try
            {
                await SettingsManager.MoveSettingsAsync(SettingsManager.GetSettingsLocation(), LocationSelectedPath, overwrite);

                Properties.Settings.Default.Settings_CustomSettingsLocation = LocationSelectedPath;

                // Show the user some awesome animation to indicate we are working on it :)
                await Task.Delay(2000);
            }
            catch (Exception ex)
            {
                await dialogCoordinator.ShowMessageAsync(this, LocalizationManager.GetStringByKey("String_Header_Error") as string, ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog);
            }

            LocationSelectedPath = string.Empty;
            LocationSelectedPath = Properties.Settings.Default.Settings_CustomSettingsLocation;

            if (forceRestart)
            {
                SettingsManager.ForceRestart = true;
                CloseAction();
            }

            MovingFiles = false;
        }
示例#10
0
 public string GetItemDescription(int id, string overrideLanguage = null)
 {
     return(LocalizationManager.GetTranslation(string.Format("203_ItemDescription/{0}", id), true, 0, true, false, null, overrideLanguage));
 }
示例#11
0
 public string GetUI(string path, string overrideLanguage = null)
 {
     return(LocalizationManager.GetTranslation(string.Format("100_UI/{0}", path), true, 0, true, false, null, overrideLanguage));
 }
示例#12
0
 public string GetMissionCategory(int id, string overrideLanguage = null)
 {
     return(LocalizationManager.GetTranslation(string.Format("702_MissionCategory/{0}", id), true, 0, true, false, null, overrideLanguage));
 }
示例#13
0
 /// ------------------------------------------------------------------------------------
 public static string GetConvertingToStandardPcmAudioMsg()
 {
     return(LocalizationManager.GetString(
                "SoundFileUtils.ConvertToStandardWavPcmAudioMsg", "Converting..."));
 }
    /// <summary>
    /// Display an invalid item message.
    /// </summary>
    private void SayInvalidItem()
    {
        string text = LocalizationManager.GetText("blockbuster/movie shelf/invalid item");

        this.playerDialogEvent.Raise(new DialogCue(text, 2f));
    }
示例#15
0
        private void LoadLocalizedStrings()
        {
            if (_localizedStringsLoaded == false)
            {
                using (LocalizationManager lm = new LocalizationManager(_GridPanel.SuperGrid))
                {
                    string s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterExprError)) != "")
                        _exprErrorString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterMissingParen)) != "")
                        _missingParenString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterMissingQuote)) != "")
                        _missingQuoteString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterInvalidArgCount)) != "")
                        _invalidArgCountString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterInvalidArg)) != "")
                        _invalidArgString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterInvalidEmptyOp)) != "")
                        _invalidEmptyOpString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterInvalidDateTimeOp)) != "")
                        _invalidDateTimeOpString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterInvalidStringOp)) != "")
                        _invalidStringOpString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterInvalidBoolOp)) != "")
                        _invalidBoolOpString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterInvalidNumericOp)) != "")
                        _invalidNumericOpString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterInvalidEval)) != "")
                        _invalidEvalString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterUndefinedFunction)) != "")
                        _undefinedFunctionString = s;
                }

                _localizedStringsLoaded = true;
            }
        }
示例#16
0
	void Start()
	{
		field_settings = FindObjectOfType<Settings>();
		field_stateManager = FindObjectOfType<StateManager>();
		field_localizationManager = FindObjectOfType<LocalizationManager>();
		field_hudManager = FindObjectOfType<HudManager>();
		field_menuManager = FindObjectOfType<MenuManager>();
		field_audioManager = FindObjectOfType<AudioManager>();
		field_hapticsManager = FindObjectOfType<HapticsManager>();

		field_gameplay = FindObjectOfType<Gameplay>();
		field_scoreManager = FindObjectOfType<ScoreManager>();
	}
 void Awake()
 {
     Load();
     manager = this;
 }
示例#18
0
        private void LoadLocalizedStrings(SuperGridControl sg)
        {
            if (_localizedStringsLoaded == false)
            {
                using (LocalizationManager lm = new LocalizationManager(sg))
                {
                    string s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterCustomHelp)) != "")
                        _filterHelpString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterEnterExpr)) != "")
                        _filterEnterExprString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterClear)) != "")
                        _filterClearString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterCustomFilter)) != "")
                        _filterCustomFilterString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterHelpTitle)) != "")
                        _filterHelpTitle = s;
                }

                _localizedStringsLoaded = true;
            }
        }
示例#19
0
    public void StartLevel(TeamRoster selectedRoster)
    {
        // This oddly named object points to all sorts of useful things that exist in all levels
        instance = FindObjectOfType <PlayerRig>();

        if (instance == null)
        {
            instance = Instantiate <PlayerRig>(Core.theCore.playerRigPrefab);
            instance.transform.position = Vector3.zero;
        }

        GameObject sunObject = GameObject.Find("Directional Light");

        if (sunObject != null)
        {
            sun            = sunObject.GetComponent <Light>();
            originalSunPos = sun.transform.rotation;
        }

        instance.gameObject.SetActive(true);

        Range[] ranges = new Range[2] {
            Range.WIDE, Range.WIDE
        };

        bool bAgainstElement = false;

        fMeleeZoneSize = 1.0f;

        Core.theCore.fEnemyTimescale  = 1.0f;
        Core.theCore.fPlayerTimescale = 1.0f;

        // Spawn the player's minions immediately. Then give a countdown to start the game

        roster = selectedRoster;
        for (int i = 0; i < (int)MinionSlot.NUM_MINION_SLOTS; i++)
        {
            Transform spawnPoint = instance.playerSpawnPoints [i];
            Minion    minion     = roster.minions [i];
            if (spawnPoint != null && minion != null)
            {
                // Create new game object
                GameObject go = new GameObject("PlayerMinion_" + i + "_" + minion.template.name);

                // Fill it with actor components
                Actor_Player actor = go.AddComponent <Actor_Player>();
                actor.InitFromMinion(minion);
                actor.transform.position = spawnPoint.position;

                // Add renderer to actor
                RenderActor render = Instantiate <RenderActor>(minion.template.render);
                render.transform.SetParent(actor.transform);
                render.transform.localPosition = Vector3.zero;
                render.transform.localScale    = new Vector3(-1.0f, 1.0f, 1.0f);
                render.Init(actor);
                actor.render = render;

                // Add audio sources
                actor.soundEffect                       = go.AddComponent <AudioSource>();
                actor.soundEffect.clip                  = minion.template.soundEffect;
                actor.soundEffect.playOnAwake           = false;
                actor.soundEffect.outputAudioMixerGroup = Core.GetAudioManager().soundEffectGroup;

                // And combo numbers
                if ((minion.template.canCombo || minion.template.bDeathtoll || minion.template.bRelentless) && minion.template.comboNumbers != null)
                {
                    ComboNumbers combo = Instantiate <ComboNumbers>(minion.template.comboNumbers);
                    combo.transform.SetParent(actor.transform);
                    combo.transform.localPosition = new Vector3(-0.17f, 0.215f, -0.13f);
                    actor.comboNumbers            = combo;
                }

                // Save a reference for later
                playerActors [i] = actor;

                //
                if (((MinionSlot)i).GetSlotType() == MinionSlotType.RANGED && (minion.template is Minion_Ranged))
                {
                    ranges [i == (int)MinionSlot.RANGED_1 ? 0 : 1] = ((Minion_Ranged)minion.template).range;
                }

                if (minion.template is Minion_Support && ((Minion_Support)(minion.template)).bWalls)
                {
                    bWalls = true;
                }

                foreach (Resurrection res in minion.template.resurrectionTriggers)
                {
                    singleUseResurrections.Add(new Resurrection(res));
                }

                if (minion.template.element.GetDamageMultiplier(location.element) < 1.0f && ((MinionSlot)i).GetSlotType() != MinionSlotType.SUPPORT)
                {
                    bAgainstElement = true;
                }

                Core.theCore.fEnemyTimescale  += minion.GetBuff(Stat.ENEMY_TIMESCALE);
                Core.theCore.fPlayerTimescale += minion.GetBuff(Stat.PLAYER_TIMESCALE);

                fMeleeZoneSize += minion.GetBuff(Stat.MELEEZONE_SIZE);
            }
        }

        roster.bHasThreeResurrectsAvailable = singleUseResurrections.Count == 6;
        roster.bHasActiveCollector          = false;

        // After ALL player minions are created, then calculate their passive buffs and store them off.
        for (int i = 0; i < (int)MinionSlot.NUM_MINION_SLOTS; i++)
        {
            if (playerActors [i] != null)
            {
                playerActors [i].CalculateMyAggregateBuffs();
                playerActors [i].SetMaxHealthFromBuffs();
                playerActors [i].minion.ResetTemporaryData();
            }
        }

        roster.RecalculateHealths();

        fRangedZoneMin = Ranges.GetMinRangeForPair(ranges [0], ranges [1]);
        fRangedZoneMax = Ranges.GetMaxRangeForPair(ranges [0], ranges [1]);
        fLaneWidth     = bWalls ? 4.0f : 6.0f;
        InitZones(bWalls);

        aiNumKilledPerWave  = new int[location.numWaves];
        aiNumSpawnedPerWave = new int[location.numWaves];
        abNewlyUnlocked     = new bool[location.numWaves];


        iCurrentWave = -1;
        AdvanceWave();
        fGracePeriodDuration = location.gracePeriodDuration;

        instance.elementalHint.enabled = bAgainstElement;
        if (bAgainstElement)
        {
            instance.elementalHint.text = LocalizationManager.GetLoc(location.element.GetHintText());
        }

        Core.GetAudioManager().SetLevelMusic(location.music);

        RequestState(LevelState.PLAYING);
    }
        void OnGUI()
        {
            EditorGUILayout.Space();
            var rect = EditorGUILayout.GetControlRect();

            if (Application.isPlaying)
            {
                rect = EditorGUI.PrefixLabel(rect, EditorGUIKit.TempContent("Language"));

                string desc = string.Empty;
                if (LocalizationManager.languageIndex >= 0)
                {
                    desc = string.Format("{0} ({1})", LocalizationManager.languageName, LocalizationManager.languageType);
                }

                if (GUI.Button(rect, desc, EditorStyles.layerMaskField))
                {
                    GenericMenu menu = new GenericMenu();
                    for (int i = 0; i < LocalizationManager.languageCount; i++)
                    {
                        string text  = string.Format("{0} ({1})", LocalizationManager.GetLanguageName(i), LocalizationManager.GetLanguageType(i));
                        int    index = i;
                        menu.AddItem(new GUIContent(text), i == LocalizationManager.languageIndex, () => LocalizationManager.languageIndex = index);
                    }
                    menu.DropDown(rect);
                }
            }
            else
            {
                EditorGUI.LabelField(rect, "Can't set language in edit-mode");
            }
        }
示例#21
0
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            bool isValid = true;

            foreach (string ipHostOrRange in (value as string).Replace(" ", "").Split(';'))
            {
                // like 192.168.0.1
                if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressRegex))
                {
                    continue;
                }

                // like 192.168.0.0/24
                if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressCidrRegex))
                {
                    continue;
                }

                // like 192.168.0.0/255.255.255.0
                if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressSubnetmaskRegex))
                {
                    continue;
                }

                // like 192.168.0.0 - 192.168.0.100
                if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressRangeRegex))
                {
                    string[] range = ipHostOrRange.Split('-');

                    if (IPv4AddressHelper.ConvertToInt32(IPAddress.Parse(range[0])) >= IPv4AddressHelper.ConvertToInt32(IPAddress.Parse(range[1])))
                    {
                        isValid = false;
                    }

                    continue;
                }

                // like 192.168.[50-100].1
                if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressSpecialRangeRegex))
                {
                    string[] octets = ipHostOrRange.Split('.');

                    foreach (string octet in octets)
                    {
                        // Match [50-100]
                        if (Regex.IsMatch(octet, RegexHelper.SpecialRangeRegex))
                        {
                            foreach (string numberOrRange in octet.Substring(1, octet.Length - 2).Split(','))
                            {
                                if (numberOrRange.Contains("-"))
                                {
                                    // 50-100 --> {50, 100}
                                    string[] rangeNumber = numberOrRange.Split('-');

                                    if (int.Parse(rangeNumber[0]) > int.Parse(rangeNumber[1]))
                                    {
                                        isValid = false;
                                    }
                                }
                            }
                        }
                    }

                    continue;
                }

                // like server-01.example.com
                if (Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameRegex))
                {
                    continue;
                }

                // like server-01.example.com/24
                if (Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameCidrRegex))
                {
                    continue;
                }

                // like server-01.example.com/255.255.255.0
                if (Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameSubnetmaskRegex))
                {
                    continue;
                }

                isValid = false;
            }

            if (isValid)
            {
                return(ValidationResult.ValidResult);
            }
            else
            {
                return(new ValidationResult(false, LocalizationManager.GetStringByKey("String_ValidationError_EnterValidIPScanRange")));
            }
        }
示例#22
0
        private void LoadLocalizedStrings()
        {
            if (_LocalizedStringsLoaded == false)
            {
                using (LocalizationManager lm = new LocalizationManager(this))
                {
                    string s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterShowAll)) != "")
                        _FilterShowAllString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterCustom)) != "")
                        _FilterCustomString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterShowNull)) != "")
                        _FilterShowNullString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterShowNotNull)) != "")
                        _FilterShowNotNullString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterApply)) != "")
                        _FilterApplyString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterOk)) != "")
                        _FilterOkString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterCancel)) != "")
                        _FilterCancelString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterClose)) != "")
                        _FilterCloseString = s;
                }

                _LocalizedStringsLoaded = true;
            }
        }
示例#23
0
 public override string ToString()
 {
     return(LocalizationManager.GetTextForKey(this));
 }
		[TestFixtureSetUp] public void Setup ()
		{
			LocalizationManager mgr = new LocalizationManager("en", new MyTemplateSetLoader(), null, "Base");
			loc = mgr.DefaultLocalizer;
		}
    /// <summary>
    /// Broadcast an inventory full event.
    /// </summary>
    private void SayInventoryFull()
    {
        string text = LocalizationManager.GetText("player/inventory/no space");

        playerDialogEvent.Raise(new DialogCue(text, 2f));
    }
示例#26
0
 public string GetDungeonName(int id, string overrideLanguage = null)
 {
     return(LocalizationManager.GetTranslation(string.Format("800_DungeonName/{0}", id), true, 0, true, false, null, overrideLanguage));
 }
    /// <summary>
    /// Broadcast an invalid item.
    /// </summary>
    private void SayInvalidItem()
    {
        string text = LocalizationManager.GetText("player/inventory/invalid item");

        playerDialogEvent.Raise(new DialogCue(text, 2f));
    }
示例#28
0
 public string GetItemDisplayName(int id, string overrideLanguage = null)
 {
     return(LocalizationManager.GetTranslation(string.Format("200_ItemName/{0}", id), true, 0, true, false, null, overrideLanguage));
 }
 public void SetAction(UnityAction callToSetString)
 {
     LocalizationManager.UnregisterLanguageString(this);
     callToSet = callToSetString;
     LocalizationManager.RegisterLanguageString(this);
 }
示例#30
0
    public string GetLocalizeText(string _id)
    {
        string localizedText = LocalizationManager.GetText(_id);

        return(localizedText);
    }
 public void LanguageSwitch()
 {
     text = LocalizationManager.GetTextForTag(LanguageTag);
     callToSet?.Invoke();
 }
示例#32
0
        public async void ResetSettingsAction()
        {
            MetroDialogSettings settings = AppearanceManager.MetroDialog;

            settings.AffirmativeButtonText = LocalizationManager.GetStringByKey("String_Button_Continue");
            settings.NegativeButtonText    = LocalizationManager.GetStringByKey("String_Button_Cancel");

            settings.DefaultButtonFocus = MessageDialogResult.Affirmative;

            string message = LocalizationManager.GetStringByKey("String_SelectedSettingsAreReset");

            if (ResetEverything || ResetApplicationSettings)
            {
                message += Environment.NewLine + Environment.NewLine + string.Format("* {0}", LocalizationManager.GetStringByKey("String_TheSettingsLocationIsNotAffected"));
                message += Environment.NewLine + string.Format("* {0}", LocalizationManager.GetStringByKey("String_ApplicationIsRestartedAfterwards"));
            }

            if (await dialogCoordinator.ShowMessageAsync(this, LocalizationManager.GetStringByKey("String_Header_AreYouSure"), message, MessageDialogStyle.AffirmativeAndNegative, settings) != MessageDialogResult.Affirmative)
            {
                return;
            }

            bool forceRestart = false;

            if (ApplicationSettingsExists && (ResetEverything || ResetApplicationSettings))
            {
                SettingsManager.Reset();
                forceRestart = true;
            }

            if (NetworkInterfaceProfilesExists && (ResetEverything || ResetNetworkInterfaceProfiles))
            {
                NetworkInterfaceProfileManager.Reset();
            }

            if (IPScannerProfilesExists && (ResetEverything || ResetIPScannerProfiles))
            {
                IPScannerProfileManager.Reset();
            }

            if (WakeOnLANClientsExists && (ResetEverything || ResetWakeOnLANClients))
            {
                WakeOnLANClientManager.Reset();
            }

            if (PortScannerProfilesExists && (ResetEverything || ResetPortScannerProfiles))
            {
                PortScannerProfileManager.Reset();
            }

            if (RemoteDesktopSessionsExists && (ResetEverything || ResetRemoteDesktopSessions))
            {
                RemoteDesktopSessionManager.Reset();
            }

            if (PuTTYSessionsExists && (ResetEverything || ResetPuTTYSessions))
            {
                PuTTYSessionManager.Reset();
            }

            // Restart after reset or show a completed message
            if (forceRestart)
            {
                CloseAction();
            }
            else
            {
                settings.AffirmativeButtonText = LocalizationManager.GetStringByKey("String_Button_OK");

                await dialogCoordinator.ShowMessageAsync(this, LocalizationManager.GetStringByKey("String_Header_Success"), LocalizationManager.GetStringByKey("String_SettingsSuccessfullyReset"), MessageDialogStyle.Affirmative, settings);
            }
        }
示例#33
0
 private string L(string name)
 {
     return(LocalizationManager.GetString(CodeZeroConsts.LocalizationSourceName, name));
 }
示例#34
0
 public async Task UpdateLanguageText(UpdateLanguageTextInput input)
 {
     var culture = CultureHelper.GetCultureInfoByChecking(input.LanguageName);
     var source  = LocalizationManager.GetSource(input.SourceName);
     await _applicationLanguageTextManager.UpdateStringAsync(AbpSession.TenantId, source.Name, culture, input.Key, input.Value);
 }
示例#35
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // Parse the command line arguments and store them in the current configuration
            CommandLineManager.Parse();

            // If we have restart our application... wait until it has finished
            if (CommandLineManager.Current.RestartPid != 0)
            {
                var processList = Process.GetProcesses();

                var process = processList.FirstOrDefault(x => x.Id == CommandLineManager.Current.RestartPid);

                process?.WaitForExit();
            }

            // Detect the current configuration
            ConfigurationManager.Detect();

            // Get assembly informations
            AssemblyManager.Load();

            bool profileUpdateRequired = false;

            // Load application settings
            try
            {
                // Update integrated settings %LocalAppData%\NETworkManager\NETworkManager_GUID (custom settings path)
                if (Settings.Default.UpgradeRequired)
                {
                    Settings.Default.Upgrade();
                    Settings.Default.UpgradeRequired = false;
                }

                SettingsManager.Load();

                // Update settings (Default --> %AppData%\NETworkManager\Settings)
                Version assemblyVersion = AssemblyManager.Current.Version;
                Version settingsVersion = new Version(SettingsManager.Current.SettingsVersion);

                if (AssemblyManager.Current.Version > settingsVersion)
                {
                    SettingsManager.Update(AssemblyManager.Current.Version, settingsVersion);
                }
            }
            catch (InvalidOperationException)
            {
                SettingsManager.InitDefault();

                profileUpdateRequired = true; // Because we don't know if a profile update is required

                ConfigurationManager.Current.ShowSettingsResetNoteOnStartup = true;
            }

            // Upgrade profile if version has changed or settings have been reset (mthis happens mostly, because the version has changed and values are wrong)
            if (profileUpdateRequired)
            {
                try
                {
                    ProfileManager.Upgrade();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Failed to update profiles...\n\n" + ex.Message, "Profile Manager - Update Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            // Load localization (requires settings to be loaded first)
            LocalizationManager.Load();

            NETworkManager.Resources.Localization.Strings.Culture = LocalizationManager.Culture;

            if (CommandLineManager.Current.Help)
            {
                StartupUri = new Uri("/Views/CommandLineHelpWindow.xaml", UriKind.Relative);
                return;
            }

            // Create mutex
            _mutex = new Mutex(true, "{" + GUID + "}");
            var mutexIsAcquired = _mutex.WaitOne(TimeSpan.Zero, true);

            // Release mutex
            if (mutexIsAcquired)
            {
                _mutex.ReleaseMutex();
            }

            if (SettingsManager.Current.Window_MultipleInstances || mutexIsAcquired)
            {
                if (SettingsManager.Current.General_BackgroundJobInterval != 0)
                {
                    _dispatcherTimer = new DispatcherTimer
                    {
                        Interval = TimeSpan.FromMinutes(SettingsManager.Current.General_BackgroundJobInterval)
                    };

                    _dispatcherTimer.Tick += DispatcherTimer_Tick;

                    _dispatcherTimer.Start();
                }

                StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
            }
            else
            {
                // Bring the already running application into the foreground
                SingleInstance.PostMessage((IntPtr)SingleInstance.HWND_BROADCAST, SingleInstance.WM_SHOWME, IntPtr.Zero, IntPtr.Zero);

                _singleInstanceClose = true;
                Shutdown();
            }
        }
示例#36
0
        public override void OnGUI(Rect rect, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginProperty(rect, label, property);

            var keyField = property.FindPropertyRelative("_key");
            var msgInst  = new LocalizedString(keyField.stringValue);

            if (_textArea != null)
            {
                EditorGUI.LabelField(rect, label);
                rect.y += ReflectionDrawerStyles.singleLineHeight;

                LocalizationEditorUtility.DrawLanguagePicker(ref rect, keyField.stringValue, (newKeyName) =>
                {
                    keyField.stringValue = newKeyName;
                });

                rect.height = ReflectionDrawerStyles.singleLineHeight * Mathf.Max(_textArea.maxLines, 3);

                EditorGUI.BeginChangeCheck();

                if (LocalizationManager.currentDatabase != null && LocalizationManager.currentDatabase.ContainsString(keyField.stringValue) == false)
                {
                    GUI.color = new Color(1f, 1f, 1f, 0.5f);
                }

                var str2 = EditorGUI.TextArea(rect, msgInst.message ?? "");
                if (EditorGUI.EndChangeCheck() && LocalizationManager.defaultDatabase != null && str2 != LocalizationManager.defaultDatabase.GetString(keyField.stringValue))
                {
                    if (IsNullOrWhiteSpace(keyField.stringValue) || keyField.stringValue == LocalizationManager.NoKeyConstant)
                    {
                        keyField.stringValue = LocalizationManager.CreateNewStringKey();
                    }

                    msgInst.message = str2;
                }

                GUI.color = Color.white;
                return;
            }

            LocalizationEditorUtility.DrawLanguagePicker(ref rect, keyField.stringValue, (newKeyName) =>
            {
                keyField.stringValue = newKeyName;
            });
            EditorGUI.BeginChangeCheck();

            if (LocalizationManager.currentDatabase != null && LocalizationManager.currentDatabase.ContainsString(keyField.stringValue) == false)
            {
                GUI.color = new Color(1f, 1f, 1f, 0.5f);
            }

            rect.height = EditorGUIUtility.singleLineHeight;
            var str = EditorGUI.TextField(rect, label, msgInst.message ?? "");

            if (EditorGUI.EndChangeCheck() && LocalizationManager.defaultDatabase != null && str != LocalizationManager.defaultDatabase.GetString(keyField.stringValue))
            {
                if (IsNullOrWhiteSpace(keyField.stringValue) || keyField.stringValue == LocalizationManager.NoKeyConstant)
                {
                    keyField.stringValue = LocalizationManager.CreateNewStringKey();
                }

                msgInst.message = str;
            }

            GUI.color = Color.white;
            EditorGUI.EndProperty();
        }
示例#37
0
        public void Run(IHost ptHost, string activeProjectName)
        {
            lock (this)
            {
                if (host != null)
                {
                    // This should never happen, but just in case Host does something wrong...
                    ptHost.WriteLineToLog(this, "Run called more than once!");
                    return;
                }
            }

            try
            {
                Application.EnableVisualStyles();

                host          = ptHost;
                m_projectName = activeProjectName;
#if DEBUG
                MessageBox.Show("Attach debugger now (if you want to)", pluginName);
#endif
                ptHost.WriteLineToLog(this, "Starting " + pluginName);

                string preferredUiLocale = "en";
                try
                {
                    preferredUiLocale = host.GetApplicationSetting("InterfaceLanguageId");
                    if (String.IsNullOrWhiteSpace(preferredUiLocale))
                    {
                        preferredUiLocale = "en";
                    }
                }
                catch (Exception)
                {
                }

                SetUpLocalization(preferredUiLocale);

                Thread mainUIThread = new Thread(() =>
                {
                    InitializeErrorHandling(m_projectName);

                    const string kMajorList = "Major";

                    UNSQuestionsDialog formToShow;
                    lock (this)
                    {
                        splashScreen = new TxlSplashScreen();
                        splashScreen.Show(Screen.FromPoint(Properties.Settings.Default.WindowLocation));
                        splashScreen.Message = string.Format(
                            LocalizationManager.GetString("SplashScreen.MsgRetrievingDataFromCaller",
                                                          "Retrieving data from {0}...", "Param is host application name (Paratext)"),
                            host.ApplicationName);

                        int currRef           = host.GetCurrentRef(TxlCore.kEnglishVersificationName);
                        BCVRef startRef       = new BCVRef(currRef);
                        BCVRef endRef         = new BCVRef(currRef);
                        bool useSavedRefRange = false;
                        // See TXL-131 for explanation of this code, if needed.
                        if (Properties.Settings.Default.FilterStartRef > 0 &&
                            Properties.Settings.Default.FilterStartRef < Properties.Settings.Default.FilterEndRef)
                        {
                            var savedStartRef = new BCVRef(Properties.Settings.Default.FilterStartRef);
                            var savedEndRef   = new BCVRef(Properties.Settings.Default.FilterEndRef);
                            if (savedStartRef.Valid && savedEndRef.Valid &&
                                savedStartRef <= startRef && savedEndRef >= endRef)
                            {
                                useSavedRefRange = true;
                                startRef         = savedStartRef;
                                endRef           = savedEndRef;
                            }
                        }

                        if (!useSavedRefRange)
                        {
                            startRef.Chapter = 1;
                            startRef.Verse   = 1;
                            endRef.Chapter   = host.GetLastChapter(endRef.Book, TxlCore.kEnglishVersificationName);
                            endRef.Verse     = host.GetLastVerse(endRef.Book, endRef.Chapter, TxlCore.kEnglishVersificationName);
                        }

                        KeyboardController.Initialize();

                        Action <bool> activateKeyboard = vern =>
                        {
                            if (vern)
                            {
                                try
                                {
                                    string keyboard = host.GetProjectKeyboard(m_projectName);
                                    if (!string.IsNullOrEmpty(keyboard))
                                    {
                                        Keyboard.Controller.GetKeyboard(keyboard).Activate();
                                    }
                                }
                                catch (ApplicationException e)
                                {
                                    // For some reason, the very first time this gets called it throws a COM exception, wrapped as
                                    // an ApplicationException. Mysteriously, it seems to work just fine anyway, and then all subsequent
                                    // calls work with no exception. Paratext seems to make this same call without any exceptions. The
                                    // documentation for ITfInputProcessorProfiles.ChangeCurrentLanguage (which is the method call
                                    // in SIL.Windows.Forms.Keyboarding.Windows that throws the COM exception says that an E_FAIL is an
                                    // unspecified error, so that's fairly helpful.
                                    if (!(e.InnerException is COMException))
                                    {
                                        throw;
                                    }
                                }
                            }
                            else
                            {
                                Keyboard.Controller.ActivateDefaultKeyboard();
                            }
                        };

                        var fileAccessor = new ParatextDataFileAccessor(fileId => host.GetPlugInData(this, m_projectName, fileId),
                                                                        (fileId, reader) => host.PutPlugInData(this, m_projectName, fileId, reader),
                                                                        fileId => host.GetPlugInDataLastModifiedTime(this, m_projectName, fileId));

                        bool fEnableDragDrop = true;
                        try
                        {
                            string dragDropSetting = host.GetApplicationSetting("EnableDragAndDrop");
                            if (dragDropSetting != null)
                            {
                                fEnableDragDrop = bool.Parse(dragDropSetting);
                            }
                        }
                        catch (Exception)
                        {
                        }

                        formToShow = unsMainWindow = new UNSQuestionsDialog(splashScreen, m_projectName,
                                                                            () => host.GetFactoryKeyTerms(kMajorList, "en", 01001001, 66022021),
                                                                            termId => host.GetProjectTermRenderings(m_projectName, termId, true),
                                                                            host.GetProjectFont(m_projectName),
                                                                            host.GetProjectLanguageId(m_projectName, "generate templates"),
                                                                            host.GetProjectSetting(m_projectName, "Language"), host.GetProjectRtoL(m_projectName),
                                                                            fileAccessor, host.GetScriptureExtractor(m_projectName, ExtractorType.USFX),
                                                                            () => host.GetCssStylesheet(m_projectName), host.ApplicationName,
                                                                            new ScrVers(host, TxlCore.kEnglishVersificationName),
                                                                            new ScrVers(host, host.GetProjectVersificationName(m_projectName)), startRef,
                                                                            endRef, currRef, activateKeyboard, termId => host.GetTermOccurrences(kMajorList, m_projectName, termId),
                                                                            terms => host.LookUpKeyTerm(m_projectName, terms), fEnableDragDrop, preferredUiLocale);
                        splashScreen = null;
                    }

#if DEBUG
                    // Always track if this is a debug build, but track to a different segment.io project
                    const bool allowTracking = true;
                    const string key         = "0mtsix4obm";
#else
                    // If this is a release build, then allow an environment variable to be set to false
                    // so that testers aren't generating false analytics
                    string feedbackSetting = Environment.GetEnvironmentVariable("FEEDBACK");

                    var allowTracking = string.IsNullOrEmpty(feedbackSetting) || feedbackSetting.ToLower() == "yes" || feedbackSetting.ToLower() == "true";

                    const string key = "3iuv313n8t";
#endif
                    using (new Analytics(key, GetUserInfo(), allowTracking))
                    {
                        Analytics.Track("Startup", new Dictionary <string, string>
                        {
                            { "Specific version", Assembly.GetExecutingAssembly().GetName().Version.ToString() }
                        });

                        formToShow.ShowDialog();
                    }
                    ptHost.WriteLineToLog(this, "Closing " + pluginName);
                    Environment.Exit(0);
                });
                mainUIThread.Name         = pluginName;
                mainUIThread.IsBackground = false;
                mainUIThread.SetApartmentState(ApartmentState.STA);
                mainUIThread.Start();
                // Avoid putting any code after this line. Any exceptions thrown will not be able to be reported via the
                // "green screen" because we are not running in STA.
            }
            catch (Exception e)
            {
                MessageBox.Show(string.Format(LocalizationManager.GetString("General.ErrorStarting", "Error occurred attempting to start {0}: ",
                                                                            "Param is \"Transcelerator\" (plugin name)"), pluginName) + e.Message);
                throw;
            }
        }
示例#38
0
        /// <summary>
        /// Generates Error Reports for books with specific titles
        /// Facilitates manual testing of error reporting using specific books.
        /// </summary>
        private static void CheckForFakeTestErrors(string title)
        {
            const string fakeProblemMessage = "Fake problem for development/testing purposes";
            Exception    fakeException;

            // Throwing/catching the exception populates the stack trace
            try
            {
                throw new ApplicationException("Fake exception for development/testing purposes");
            }
            catch (ApplicationException e)
            {
                fakeException = e;
            }

            if (title == "Error NotifyUser NoReport")
            {
                // Exercises a path through libPalaso directly (goes thru overloads 1, 2, 4)
                ErrorReport.NotifyUserOfProblem(fakeProblemMessage);
            }
            else if (title == "Error NotifyUser NoReport 2")
            {
                // Exercises a path through libPalaso directly (goes thru overloads 3, 4)
                ErrorReport.NotifyUserOfProblem((Exception)null, fakeProblemMessage);
            }
            else if (title == "Error NotifyUser NoReport 3")
            {
                // Exercises a path where you go through the ErrorReportUtils adapters
                ErrorReportUtils.NotifyUserOfProblem(fakeProblemMessage);
            }
            else if (title == "Error NotifyUser LongMessage")
            {
                var longMessageBuilder = new StringBuilder();
                while (longMessageBuilder.Length < 3000)
                {
                    longMessageBuilder.Append(fakeProblemMessage + " ");
                }

                ErrorReport.NotifyUserOfProblem(longMessageBuilder.ToString());
            }
            else if (title == "Error NotifyUser Report NoRetry")
            {
                // Exercises another path through libPalaso directly (goes thru overloads 3, 4)
                ErrorReport.NotifyUserOfProblem(fakeException, fakeProblemMessage);
            }
            else if (title == "Error NotifyUser Report NoRetry 2")
            {
                // Exercises a path where you go through the ErrorReportUtils adapters
                ErrorReportUtils.NotifyUserOfProblem(fakeProblemMessage, fakeException);
            }
            else if (title == "Error NotifyUser Report Retry")
            {
                // Exercises a path where you need to go through the ErrorReportUtils adapters
                var secondaryButtonLabel = LocalizationManager.GetString("ErrorReportDialog.Retry", "Retry");
                ErrorReportUtils.NotifyUserOfProblem(fakeProblemMessage, fakeException, null, null, secondaryButtonLabel, ErrorReportUtils.TestAction);
            }
            else if (title == "Error NotifyUser Custom")
            {
                // Exercises a path where you need to go through the ErrorReportUtils adapters
                var secondaryButtonLabel = LocalizationManager.GetString("ErrorReportDialog.Retry", "Retry");
                ErrorReportUtils.NotifyUserOfProblem(fakeProblemMessage, fakeException, "CustomReport", (ex, msg) => { MessageBox.Show("CustomReport button pressed."); }, secondaryButtonLabel, ErrorReportUtils.TestAction);
            }
            else if (title == "Error NotifyUser LegacyInterface")
            {
                // Exercises the legacy 5-argument implementation in libpalaso
                // (follow-up actions are manually invoked by the caller)
                var result = ErrorReport.NotifyUserOfProblem(new ShowAlwaysPolicy(), "CustomReport", ErrorResult.Yes, fakeProblemMessage);

                string message = result == ErrorResult.Yes ? "Report button clicked. [Legacy]" : null;
                if (message != null)
                {
                    MessageBox.Show(message);
                }
            }
            else if (title == "Error ReportNonFatalException")
            {
                ErrorReport.ReportNonFatalException(fakeException);
            }
            else if (title == "Error ReportNonFatalExceptionWithMessage")
            {
                ErrorReport.ReportNonFatalExceptionWithMessage(fakeException, fakeProblemMessage);
            }
            else if (title == "Error ReportNonFatalExceptionWithMessage Scrollbar")
            {
                var longMessageBuilder = new StringBuilder();
                while (longMessageBuilder.Length < 500)
                {
                    longMessageBuilder.AppendLine(fakeProblemMessage);
                }
                ErrorReport.ReportNonFatalExceptionWithMessage(fakeException, longMessageBuilder.ToString());
            }
            else if (title == "Error ReportNonFatalMessageWithStackTrace")
            {
                ErrorReport.ReportNonFatalMessageWithStackTrace(fakeProblemMessage);
            }
            else if (title == "Error ReportFatalException")
            {
                ErrorReport.ReportFatalException(fakeException);
            }
            else if (title == "Error ReportFatalMessageWithStackTrace")
            {
                ErrorReport.ReportFatalMessageWithStackTrace(fakeProblemMessage);
            }
            else if (title == "Error ReportFatalMessageWithStackTrace Scrollbar")
            {
                var longMessageBuilder = new StringBuilder();
                while (longMessageBuilder.Length < 500)
                {
                    longMessageBuilder.AppendLine(fakeProblemMessage);
                }
                ErrorReport.ReportFatalMessageWithStackTrace(longMessageBuilder.ToString());
            }
        }
示例#39
0
        private void LoadLocalizedStrings(SuperGridControl sg)
        {
            if (_localizedStringsLoaded == false)
            {
                using (LocalizationManager lm = new LocalizationManager(sg))
                {
                    string s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterCustomHelp)) != "")
                        _filterHelpString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterEnterExpr)) != "")
                        _filterEnterExprString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterClear)) != "")
                        _filterClearString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterReset)) != "")
                        _filterResetString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterCustomFilter)) != "")
                        _filterCustomFilterString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridNewFilterExpr)) != "")
                        _newFilterExprString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridNewFilter)) != "")
                        _newFilterString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridDeleteFilter)) != "")
                        _deleteFilterString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterName)) != "")
                        _filterNameString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterDescription)) != "")
                        _filterDescriptionString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridShowInFilterPopup)) != "")
                        _showInFilterPopupString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterHelpTitle)) != "")
                        _filterHelpTitle = s;
                }

                _localizedStringsLoaded = true;
            }
        }
示例#40
0
        private async void MetroWindowMain_Closing(object sender, CancelEventArgs e)
        {
            // Force restart (if user has reset the settings or import them)
            if (SettingsManager.ForceRestart || ImportExportManager.ForceRestart)
            {
                RestartApplication(false);

                _closeApplication = true;
            }

            // Hide the application to tray
            if (!_closeApplication && (SettingsManager.Current.Window_MinimizeInsteadOfTerminating && WindowState != WindowState.Minimized))
            {
                e.Cancel = true;

                WindowState = WindowState.Minimized;

                return;
            }

            // Confirm close
            if (!_closeApplication && SettingsManager.Current.Window_ConfirmClose)
            {
                e.Cancel = true;

                // If the window is minimized, bring it to front
                if (WindowState == WindowState.Minimized)
                {
                    BringWindowToFront();
                }

                MetroDialogSettings settings = AppearanceManager.MetroDialog;

                settings.AffirmativeButtonText = LocalizationManager.GetStringByKey("String_Button_Close");
                settings.NegativeButtonText    = LocalizationManager.GetStringByKey("String_Button_Cancel");
                settings.DefaultButtonFocus    = MessageDialogResult.Affirmative;

                // Fix airspace issues
                ConfigurationManager.Current.FixAirspace = true;

                MessageDialogResult result = await this.ShowMessageAsync(LocalizationManager.GetStringByKey("String_Header_Confirm"), LocalizationManager.GetStringByKey("String_ConfirmCloseQuesiton"), MessageDialogStyle.AffirmativeAndNegative, settings);

                ConfigurationManager.Current.FixAirspace = false;

                if (result == MessageDialogResult.Affirmative)
                {
                    _closeApplication = true;
                    Close();
                }

                return;
            }

            // Unregister HotKeys
            if (RegisteredHotKeys.Count > 0)
            {
                UnregisterHotKeys();
            }

            // Dispose the notify icon to prevent errors
            if (notifyIcon != null)
            {
                notifyIcon.Dispose();
            }
        }
示例#41
0
        //autofac uses this
        public WorkspaceView(WorkspaceModel model,
							 Control libraryView,
							 EditingView.Factory editingViewFactory,
							 PublishView.Factory pdfViewFactory,
							 CollectionSettingsDialog.Factory settingsDialogFactory,
							 EditBookCommand editBookCommand,
							SendReceiveCommand sendReceiveCommand,
							 SelectedTabAboutToChangeEvent selectedTabAboutToChangeEvent,
							SelectedTabChangedEvent selectedTabChangedEvent,
							 FeedbackDialog.Factory feedbackDialogFactory,
							ChorusSystem chorusSystem,
							Sparkle sparkleApplicationUpdater,
							LocalizationManager localizationManager

			)
        {
            _model = model;
            _settingsDialogFactory = settingsDialogFactory;
            _selectedTabAboutToChangeEvent = selectedTabAboutToChangeEvent;
            _selectedTabChangedEvent = selectedTabChangedEvent;
            _feedbackDialogFactory = feedbackDialogFactory;
            _chorusSystem = chorusSystem;
            _sparkleApplicationUpdater = sparkleApplicationUpdater;
            _localizationManager = localizationManager;
            _model.UpdateDisplay += new System.EventHandler(OnUpdateDisplay);
            InitializeComponent();

            #if !DEBUG
            _sparkleApplicationUpdater.CheckOnFirstApplicationIdle();
            #endif
            _toolStrip.Renderer = new NoBorderToolStripRenderer();

            //we have a number of buttons which don't make sense for the remote (therefore vulnerable) low-end user
            //_settingsLauncherHelper.CustomSettingsControl = _toolStrip;

            _settingsLauncherHelper.ManageComponent(_settingsButton);

            //NB: the rest of these aren't really settings, but we're using that feature to simplify this menu down to what makes sense for the easily-confused user
            _settingsLauncherHelper.ManageComponent(_openCreateCollectionButton);
            _settingsLauncherHelper.ManageComponent(deepBloomPaperToolStripMenuItem);
            _settingsLauncherHelper.ManageComponent(_makeASuggestionMenuItem);
            _settingsLauncherHelper.ManageComponent(_webSiteMenuItem);
            _settingsLauncherHelper.ManageComponent(_showLogMenuItem);
            _settingsLauncherHelper.ManageComponent(_releaseNotesMenuItem);
            _settingsLauncherHelper.ManageComponent(_divider2);
            _settingsLauncherHelper.ManageComponent(_divider3);
            _settingsLauncherHelper.ManageComponent(_divider4);

            OnSettingsProtectionChanged(this, null);//initial setup
            SettingsProtectionSettings.Default.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(OnSettingsProtectionChanged);

            _uiLanguageMenu.Visible = true;
               _settingsLauncherHelper.ManageComponent(_uiLanguageMenu);

            editBookCommand.Subscribe(OnEditBook);
            sendReceiveCommand.Subscribe(OnSendReceive);

            //Cursor = Cursors.AppStarting;
            Application.Idle += new EventHandler(Application_Idle);
            Text = _model.ProjectName;

            //SetupTabIcons();

            //
            // _collectionView
            //
            this._collectionView = (LibraryView) libraryView;
            this._collectionView.Dock = System.Windows.Forms.DockStyle.Fill;

            //
            // _editingView
            //
            this._editingView = editingViewFactory();
            this._editingView.Dock = System.Windows.Forms.DockStyle.Fill;

            //
            // _pdfView
            //
            this._publishView = pdfViewFactory();
            this._publishView.Dock = System.Windows.Forms.DockStyle.Fill;

            _collectionTab.Tag = _collectionView;
            _publishTab.Tag = _publishView;
            _editTab.Tag = _editingView;

            this._collectionTab.Text = _collectionView.CollectionTabLabel;

            SetTabVisibility(_publishTab, false);
            SetTabVisibility(_editTab, false);

            //			if (Program.StartUpWithFirstOrNewVersionBehavior)
            //			{
            //				_tabStrip.SelectedTab = _infoTab;
            //				SelectPage(_infoView);
            //			}
            //			else
            //			{
                _tabStrip.SelectedTab = _collectionTab;
                SelectPage(_collectionView);
            //			}

            SetupUILanguageMenu();
        }
示例#42
0
 /// ------------------------------------------------------------------------------------
 private IEnumerable <IComponent> GetComponentsForId(LocalizationManager lm, string id)
 {
     return(lm.ComponentCache.Where(kvp => kvp.Value == id).Select(kvp => kvp.Key));
 }
		[TestFixtureSetUp] public void Setup ()
		{
			mgr = new LocalizationManager("en", new MyTemplateSetLoader(), null, "Base", "Scrum", "Custom");
		}
示例#44
0
        private void LoadLocalizedStrings(SuperGridControl sg)
        {
            if (_localizedStringsLoaded == false)
            {
                using (LocalizationManager lm = new LocalizationManager(sg))
                {
                    string s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterByRelativeDate)) != "")
                        _filterByRelativeDateString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterBySpecificDate)) != "")
                        _filterBySpecificDateString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterByDateRange)) != "")
                        _filterByDateRangeString = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterCurrentMonth)) != "")
                        _currentMonth = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterCurrentYear)) != "")
                        _currentYear = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterLastMonthPeriod)) != "")
                        _lastMonthPeriod = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterLast3MonthPeriod)) != "")
                        _last3MonthPeriod = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterLast6MonthPeriod)) != "")
                        _last6MonthPeriod = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterLast9MonthPeriod)) != "")
                        _last9MonthPeriod = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterLastYear)) != "")
                        _lastYear = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterLast5YearPeriod)) != "")
                        _last5YearPeriod = s;

                    if ((s = lm.GetLocalizedString(LocalizationKeys.SuperGridFilterLast10YearPeriod)) != "")
                        _last10YearPeriod = s;
                }

                _localizedStringsLoaded = true;
            }
        }
示例#45
0
        /// <summary>
        /// Formats attributes
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <param name="attributes">Attributes</param>
        /// <param name="customer">Customer</param>
        /// <param name="serapator">Serapator</param>
        /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
        /// <param name="renderPrices">A value indicating whether to render prices</param>
        /// <param name="renderProductAttributes">A value indicating whether to render product attributes</param>
        /// <param name="renderGiftCardAttributes">A value indicating whether to render gift card attributes</param>
        /// <returns>Attributes</returns>
        public static string FormatAttributes(ProductVariant productVariant, string attributes,
                                              Customer customer, string serapator, bool htmlEncode, bool renderPrices,
                                              bool renderProductAttributes, bool renderGiftCardAttributes)
        {
            var result = new StringBuilder();

            //attributes
            if (renderProductAttributes)
            {
                var pvaCollection = ParseProductVariantAttributes(attributes);
                for (int i = 0; i < pvaCollection.Count; i++)
                {
                    var pva       = pvaCollection[i];
                    var valuesStr = ParseValues(attributes, pva.ProductVariantAttributeId);
                    for (int j = 0; j < valuesStr.Count; j++)
                    {
                        string valueStr     = valuesStr[j];
                        string pvaAttribute = string.Empty;
                        if (!pva.ShouldHaveValues)
                        {
                            if (pva.AttributeControlType == AttributeControlTypeEnum.MultilineTextbox)
                            {
                                pvaAttribute = string.Format("{0}: {1}", pva.ProductAttribute.LocalizedName, HtmlHelper.FormatText(valueStr, false, true, true, false, false, false));
                            }
                            else
                            {
                                pvaAttribute = string.Format("{0}: {1}", pva.ProductAttribute.LocalizedName, valueStr);
                            }
                        }
                        else
                        {
                            var pvaValue = ProductAttributeManager.GetProductVariantAttributeValueById(Convert.ToInt32(valueStr));
                            if (pvaValue != null)
                            {
                                pvaAttribute = string.Format("{0}: {1}", pva.ProductAttribute.LocalizedName, pvaValue.LocalizedName);
                                if (renderPrices)
                                {
                                    decimal taxRate             = decimal.Zero;
                                    decimal priceAdjustmentBase = TaxManager.GetPrice(productVariant, pvaValue.PriceAdjustment, customer, out taxRate);
                                    decimal priceAdjustment     = CurrencyManager.ConvertCurrency(priceAdjustmentBase, CurrencyManager.PrimaryStoreCurrency, NopContext.Current.WorkingCurrency);
                                    if (priceAdjustmentBase > 0)
                                    {
                                        string priceAdjustmentStr = PriceHelper.FormatPrice(priceAdjustment, false, false);
                                        pvaAttribute += string.Format(" [+{0}]", priceAdjustmentStr);
                                    }
                                }
                            }
                        }

                        if (!String.IsNullOrEmpty(pvaAttribute))
                        {
                            if (i != 0 || j != 0)
                            {
                                result.Append(serapator);
                            }

                            //we don't encode multiline textbox input
                            if (htmlEncode &&
                                pva.AttributeControlType != AttributeControlTypeEnum.MultilineTextbox)
                            {
                                result.Append(HttpUtility.HtmlEncode(pvaAttribute));
                            }
                            else
                            {
                                result.Append(pvaAttribute);
                            }
                        }
                    }
                }
            }

            //gift cards
            if (renderGiftCardAttributes)
            {
                if (productVariant.IsGiftCard)
                {
                    string giftCardRecipientName  = string.Empty;
                    string giftCardRecipientEmail = string.Empty;
                    string giftCardSenderName     = string.Empty;
                    string giftCardSenderEmail    = string.Empty;
                    string giftCardMessage        = string.Empty;
                    GetGiftCardAttribute(attributes, out giftCardRecipientName, out giftCardRecipientEmail,
                                         out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage);

                    if (!String.IsNullOrEmpty(result.ToString()))
                    {
                        result.Append(serapator);
                    }

                    if (htmlEncode)
                    {
                        result.Append(HttpUtility.HtmlEncode(string.Format(LocalizationManager.GetLocaleResourceString("GiftCardAttribute.For"), giftCardRecipientName)));
                        result.Append(serapator);
                        result.Append(HttpUtility.HtmlEncode(string.Format(LocalizationManager.GetLocaleResourceString("GiftCardAttribute.From"), giftCardSenderName)));
                    }
                    else
                    {
                        result.Append(string.Format(LocalizationManager.GetLocaleResourceString("GiftCardAttribute.For"), giftCardRecipientName));
                        result.Append(serapator);
                        result.Append(string.Format(LocalizationManager.GetLocaleResourceString("GiftCardAttribute.From"), giftCardSenderName));
                    }
                }
            }
            return(result.ToString());
        }
示例#46
0
 public string GetNPCLine(int id, string overrideLanguage = null)
 {
     return(LocalizationManager.GetTranslation(string.Format("600_NPCLine/{0}", id), true, 0, true, false, null, overrideLanguage));
 }
示例#47
0
 public string GetMissionOriginDesc(int id, string overrideLanguage = null)
 {
     return(LocalizationManager.GetTranslation(string.Format("701_MissionDesc/{0}", id), true, 0, true, false, null, overrideLanguage));
 }
示例#48
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Prepares the selected files to be uploaded to REAP using RAMP.
		/// </summary>
		/// <param name="owner">RAMP dialog owner</param>
		/// <param name="dialogFont">RAMP dialog font (for localization and consistency)</param>
		/// <param name="localizationDialogIcon"></param>
		/// <param name="filesToArchive"></param>
		/// <param name="mediator"></param>
		/// <param name="thisapp"></param>
		/// <param name="cache"></param>
		/// <returns></returns>
		/// ------------------------------------------------------------------------------------
		public bool ArchiveNow(Form owner, Font dialogFont, Icon localizationDialogIcon,
			IEnumerable<string> filesToArchive, Mediator mediator, FwApp thisapp, FdoCache cache)
		{
			var viProvider = new VersionInfoProvider(Assembly.LoadFile(thisapp.ProductExecutableFile), false);
			var wsMgr = cache.ServiceLocator.GetInstance<IWritingSystemManager>();
			var appName = thisapp.ApplicationName;
			var title = cache.LanguageProject.ShortName;
			var uiLocale = wsMgr.Get(cache.DefaultUserWs).IcuLocale;
			var projectId = cache.LanguageProject.ShortName;

			var model = new RampArchivingDlgViewModel(Application.ProductName, title, projectId, GetFileDescription);

			// image files should be labeled as Graphic rather than Photograph (the default).
			model.ImagesArePhotographs = false;

			// show the count of media files, not the duration
			model.ShowRecordingCountNotLength = true;

			// set the general description, in each available language
			IMultiString descr = cache.LanguageProject.Description;
			var descriptions = new Dictionary<string, string>();
			foreach (int wsid in descr.AvailableWritingSystemIds)
			{
				var descrText = descr.get_String(wsid).Text;
				if ((!string.IsNullOrEmpty(descrText)) && (descrText != "***"))
					descriptions[wsMgr.Get(wsid).GetIso3Code()] = descrText;
			}

			if (descriptions.Count > 0)
				model.SetDescription(descriptions);

			AddMetsPairs(model, viProvider.ShortNumericAppVersion, cache);

			const string localizationMgrId = "Archiving";

			if (s_localizationMgr == null)
			{
				s_localizationMgr = LocalizationManager.Create(
					uiLocale,
					localizationMgrId, viProvider.ProductName, viProvider.NumericAppVersion,
					FwDirectoryFinder.GetCodeSubDirectory("ArchivingLocalizations"),
					Path.Combine(Application.CompanyName, appName),
					localizationDialogIcon, "*****@*****.**", "SIL.Archiving");
			}
			else
			{
				LocalizationManager.SetUILanguage(uiLocale, true);
			}

			// create the dialog
			using (var dlg = new ArchivingDlg(model, localizationMgrId, string.Empty, dialogFont,
				() => GetFilesToArchive(filesToArchive), new FormSettings()))
			using (var reportingAdapter = new PalasoErrorReportingAdapter(dlg, mediator))
			{
				ErrorReport.SetErrorReporter(reportingAdapter);
				dlg.ShowDialog(owner);
				ErrorReport.SetErrorReporter(null);
			}

			return true;
		}
		public void Setup()
		{
			IDictionary<string, string> overrides = new Dictionary<string, string>();
			overrides.Add("Story", "Bone");
			overrides.Add("DEF", "fed");

			mgr = new LocalizationManager("en", new MyTemplateSetLoader(), overrides, "Base", "Scrum", "Custom");
			loc = mgr.DefaultLocalizer;
		}