private async Task LoadFilesAsync()
        {
            try
            {
                var files = await Task.Factory.StartNew(() => Directory.EnumerateFiles(TempPath, "*.xaml"));

                foreach (var file in files)
                {
                    //Replaces the special chars.
                    var text = File.ReadAllText(file, Encoding.UTF8).Replace("&#", "&#");
                    File.WriteAllText(file, text, Encoding.UTF8);

                    //Saves the template for later, when exporting the translation.
                    if (file.EndsWith("en.xaml"))
                    {
                        _resourceTemplate = text;
                    }

                    var dictionary = new ResourceDictionary {
                        Source = new Uri(Path.GetFullPath(file), UriKind.Absolute)
                    };

                    _resourceList.Add(dictionary);
                }
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() => Dialog.Ok("Translator", "Translator - Loading Offline File", ex.Message));
            }
        }
示例#2
0
        private async Task <IEnumerable <string> > GetProperCulturesAsync()
        {
            IEnumerable <string> allCodes = await Task.Factory.StartNew(() => CultureInfo.GetCultures(CultureTypes.AllCultures).Where(x => !string.IsNullOrEmpty(x.Name)).Select(x => x.Name));

            try
            {
                IEnumerable <string> downloadedCodes = await GetLanguageCodesAsync();

                IEnumerable <string> properCodes = await Task.Factory.StartNew(() => allCodes.Where(x => downloadedCodes.Contains(x)));

                if (properCodes == null)
                {
                    return(allCodes);
                }

                return(properCodes);
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() => Dialog.Ok("Translator", "Translator - Getting Language Codes", ex.Message +
                                                  Environment.NewLine + "Loading all local language codes."));
            }

            GC.Collect();
            return(allCodes);
        }
示例#3
0
        private async Task DownloadFileAsync2(Uri uri, string name)
        {
            try
            {
                var file = Path.Combine(Dispatcher.Invoke(() => TempPath), name);

                if (File.Exists(file))
                    File.Delete(file);

                using (var webClient = new WebClient { Credentials = CredentialCache.DefaultNetworkCredentials })
                    await webClient.DownloadFileTaskAsync(uri, file);

                //Saves the template for later, when exporting the translation.
                if (name.EndsWith("en.xaml"))
                    _resourceTemplate = File.ReadAllText(file);

                using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var dictionary = (ResourceDictionary)XamlReader.Load(fs, new ParserContext { XmlSpace = "preserve" });
                    //var dictionary = new ResourceDictionary();
                    dictionary.Source = new Uri(Path.GetFullPath(file), UriKind.Absolute);

                    _resourceList.Add(dictionary);

                    if (name.EndsWith("en.xaml"))
                        Application.Current.Resources.MergedDictionaries.Add(dictionary);
                }
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() => Dialog.Ok("Translator", "Translator - Downloading File", ex.Message));
            }
        }
        private async Task DownloadResources(string baseCulture, string specificCulture)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create("https://api.github.com/repos/NickeManarin/ScreenToGif/contents/ScreenToGif/Resources/Localization");
                request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393";

                var response = (HttpWebResponse)await request.GetResponseAsync();

                using (var resultStream = response.GetResponseStream())
                {
                    if (resultStream == null)
                    {
                        return;
                    }

                    using (var reader = new StreamReader(resultStream))
                    {
                        var result = reader.ReadToEnd();

                        var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(result),
                                                                                  new System.Xml.XmlDictionaryReaderQuotas());

                        var json = await Task <XElement> .Factory.StartNew(() => XElement.Load(jsonReader));

                        foreach (var element in json.XPathSelectElement("/").Elements())
                        {
                            var name = element.XPathSelectElement("name").Value;

                            if (string.IsNullOrEmpty(name) || (!name.EndsWith(baseCulture + ".xaml") && !name.EndsWith(specificCulture + ".xaml")))
                            {
                                continue;
                            }

                            var downloadUrl = element.XPathSelectElement("download_url").Value;

                            await DownloadFileAsync(new Uri(downloadUrl), name);
                        }

                        CommandManager.InvalidateRequerySuggested();
                    }
                }
            }
            catch (WebException web)
            {
                Dispatcher.Invoke(() => Dialog.Ok("Translator", "Translator - Downloading Resources", web.Message +
                                                  Environment.NewLine + "Trying to load files already downloaded."));

                await LoadFilesAsync();
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() => Dialog.Ok("Translator", "Translator - Downloading Resources", ex.Message));
            }

            GC.Collect();
        }
 private void TutorialHyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
 {
     try
     {
         Process.Start("https://github.com/NickeManarin/ScreenToGif/wiki/Localization");
     }
     catch (Exception ex)
     {
         Dialog.Ok("Translator", "Tutorial", "Error while trying to open the tutorial link");
     }
 }
        private bool ExportTranslation(string path)
        {
            try
            {
                var lines = _resourceTemplate.Split('\n');

                for (var i = 0; i < lines.Length; i++)
                {
                    var keyIndex = lines[i].IndexOf(":Key=", StringComparison.Ordinal);

                    if (keyIndex == -1)
                    {
                        continue;
                    }

                    var keyAux = lines[i].Substring(keyIndex + 6);
                    var key    = keyAux.Substring(0, keyAux.IndexOf("\"", StringComparison.Ordinal));

                    var translated = _translationList.FirstOrDefault(x => x.Key == key);

                    //"    <s:String x:Key=\"Size\">Size</s:String>"
                    if (string.IsNullOrWhiteSpace(translated?.SpecificText))
                    {
                        lines[i] = $"    <!--{lines[i].TrimStart()}-->"; //Comment the line.
                    }
                    else
                    {
                        lines[i] = $"    <s:String x:Key=\"{key}\">{translated.SpecificText}</s:String>";
                    }
                }

                if (File.Exists(path))
                {
                    File.Delete(path);
                }

                File.WriteAllText(path, string.Join(Environment.NewLine, lines).Replace("&amp;#", "&#"), Encoding.UTF8);
                return(true);
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() => Dialog.Ok("Translator", "Translator - Saving Translation", ex.Message));
                return(false);
            }
        }
        private async Task DownloadFileAsync(Uri uri, string name)
        {
            try
            {
                var file = Path.Combine(Dispatcher.Invoke(() => TempPath), name);

                if (File.Exists(file))
                {
                    File.Delete(file);
                }

                using (var webClient = new WebClient {
                    Credentials = CredentialCache.DefaultNetworkCredentials
                })
                    await webClient.DownloadFileTaskAsync(uri, file);

                //Replaces the special chars.
                var text = File.ReadAllText(file, Encoding.UTF8).Replace("&#", "&amp;#");
                File.WriteAllText(file, text, Encoding.UTF8);

                //Saves the template for later, when exporting the translation.
                if (name.EndsWith("en.xaml"))
                {
                    _resourceTemplate = text;
                }

                var dictionary = new ResourceDictionary {
                    Source = new Uri(Path.GetFullPath(file), UriKind.Absolute)
                };

                _resourceList.Add(dictionary);

                //if (name.EndsWith("en.xaml"))
                //    Application.Current.Resources.MergedDictionaries.Add(dictionary);

                //using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(text)))
                //{
                //    var dictionary = (ResourceDictionary)System.Windows.Markup.XamlReader.Load(stream, new ParserContext { XmlSpace = "preserve" });
                //}
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() => Dialog.Ok("Translator", "Translator - Downloading File", ex.Message));
            }
        }
示例#8
0
        private async void Load_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var ofd = new OpenFileDialog
            {
                AddExtension     = true,
                CheckFileExists  = true,
                Title            = "Open a Resource Dictionary",
                Filter           = "Resource Dictionay (*.xaml)|*.xaml;",
                InitialDirectory = Path.GetFullPath(TempPath)
            };

            var result = ofd.ShowDialog();

            if (!result.HasValue || !result.Value)
            {
                return;
            }

            //Replaces the special chars.
            var text = await Task.Factory.StartNew(() => File.ReadAllText(ofd.FileName, Encoding.UTF8).Replace("&#", "&amp;#"));

            await Task.Factory.StartNew(() => File.WriteAllText(ofd.FileName, text, Encoding.UTF8));

            var dictionary = await Task.Factory.StartNew(() => new ResourceDictionary { Source = new Uri(Path.GetFullPath(ofd.FileName), UriKind.Absolute) });

            _resourceList.Add(dictionary);

            var baseCulture     = FromComboBox.SelectedValue as string;
            var specificCulture = Path.GetFileName(ofd.FileName).Replace("StringResources.", "").Replace(".xaml", "");

            string properCulture;

            //Catching here, because we can access UI thread easily here to show dialogs
            try
            {
                properCulture = await Task.Factory.StartNew(() => CheckSupportedCulture(specificCulture));
            }
            catch (CultureNotFoundException)
            {
                Dialog.Ok("Action Denied", "Unknown Language.",
                          $"The \"{specificCulture}\" and its family were not recognized as a valid language codes.");

                return;
            }
            catch (Exception ex)
            {
                Dialog.Ok("Action Denied", "Error checking culture.", ex.Message);

                return;
            }

            if (properCulture != specificCulture)
            {
                Dialog.Ok("Action Denied", "Redundant Language Code.",
                          $"The \"{specificCulture}\" code is redundant. Try using \'{properCulture}\" instead");

                return;
            }

            ToComboBox.SelectedValue = specificCulture;

            ShowTranslations(baseCulture, specificCulture);

            BaseDataGrid.IsEnabled = true;
        }