public override void Build()
        {
            _contextMenu.Section1.Add(new ContextDiItemsCommand <FileViewModel, EntryViewModel, FileExplorerViewModel>
            {
                Header  = Tx.T("FileExplorer:Execute"),
                Icon    = _icons.StartupProject,
                Command = new ContextDelegateCommand <FileViewModel, FileExplorerViewModel>(ExecuteFile)
            });

            _contextMenu.Section2Path.Header = Tx.T("FileExplorer:PathCopy");
            _contextMenu.Section2Path.Icon   = _icons.CopyToClipboard;
            _contextMenu.Section2.AddAtBeginning(new ContextDiItemsCommand <FileViewModel, EntryViewModel, FileExplorerViewModel>
            {
                Header  = Tx.T("FileExplorer:CopyFilePath"),
                Command = new ContextDelegateCommand <FileViewModel, FileExplorerViewModel>(EntryViewModelCommands.CopyPath)
            });
            _contextMenu.Section2Path.Add(new ContextDiItemsCommand <FileViewModel, EntryViewModel, FileExplorerViewModel>
            {
                Header  = Tx.T("Name"),
                Command = new ContextDelegateCommand <FileViewModel, FileExplorerViewModel>(EntryViewModelCommands.CopyName)
            });
            _contextMenu.Section2Path.Add(new ContextDiItemsCommand <FileViewModel, EntryViewModel, FileExplorerViewModel>
            {
                Header  = Tx.T("FileExplorer:ParentFolderPath"),
                Command = new ContextDelegateCommand <FileViewModel, FileExplorerViewModel>(EntryViewModelCommands.CopyParentFolderPath)
            });
            _contextMenu.Section2Path.Add(new MenuSection <ContextDiItemsCommand <FileViewModel, EntryViewModel, FileExplorerViewModel> >
            {
                new ContextDiItemsCommand <FileViewModel, EntryViewModel, FileExplorerViewModel>
                {
                    Header  = Tx.T("FileExplorer:CopyPathOnRemoteComputer"),
                    Command = new ContextDelegateCommand <FileViewModel, FileExplorerViewModel>(EntryViewModelCommands.CopyPathOnRemoteComputer)
                }
            });

            _contextMenu.Section3Archive.Header = Tx.T("FileExplorer:Archive");
            _contextMenu.Section3Archive.Icon   = _icons.ZipFile;
            _contextMenu.Section3.Add(new ContextDiItemsCommand <FileViewModel, EntryViewModel, FileExplorerViewModel>
            {
                Header          = Tx.T("FileExplorer:Download"),
                Icon            = _icons.DownloadFile,
                Command         = new ContextDelegateCommand <FileViewModel, FileExplorerViewModel>(DownloadFile),
                MultipleCommand = new ContextDelegateCommand <IEnumerable <EntryViewModel>, FileExplorerViewModel>(EntryViewModelCommands.DownloadEntries)
            });
            _contextMenu.Section4.Add(new ContextDiItemsCommand <FileViewModel, EntryViewModel, FileExplorerViewModel>
            {
                Header          = Tx.T("FileExplorer:Remove"),
                Icon            = _icons.Cancel,
                Command         = new ContextDelegateCommand <FileViewModel, FileExplorerViewModel>((model, viewModel) => EntryViewModelCommands.DeleteEntries(model.Yield(), viewModel)),
                MultipleCommand = new ContextDelegateCommand <IEnumerable <EntryViewModel>, FileExplorerViewModel>(EntryViewModelCommands.DeleteEntries)
            });
            _contextMenu.Section4.Add(new ContextDiItemsCommand <FileViewModel, EntryViewModel, FileExplorerViewModel>
            {
                Header  = Tx.T("FileExplorer:Rename"),
                Icon    = _icons.Rename,
                Command = new ContextDelegateCommand <FileViewModel, FileExplorerViewModel>(EntryViewModelCommands.Rename)
            });
            _contextMenu.Section5.Add(new ContextDiItemsCommand <FileViewModel, EntryViewModel, FileExplorerViewModel>
            {
                Header  = Tx.T("FileExplorer:Properties"),
                Icon    = _icons.Property,
                Command = new ContextDelegateCommand <FileViewModel, FileExplorerViewModel>(OpenFileProperties)
            });
        }
Esempio n. 2
0
 public void Initialize(DeviceViewModel device)
 {
     Device = device;
     Title  = $"{device.Caption} - {Tx.T("DeviceManager:Properties")}";
 }
Esempio n. 3
0
 public GroupsViewModel(IClientManager clientManager, IRestClient restClient, IWindowService windowService) : base(Tx.T("Groups"),
                                                                                                                   PackIconFontAwesomeKind.ThLargeSolid)
 {
     _clientManager = clientManager;
     _restClient    = restClient;
     _windowService = windowService;
 }
Esempio n. 4
0
        public ModulesViewModel(IMazeRestClient restClient, IWindowService windowService) : base(Tx.T("Modules"), PackIconFontAwesomeKind.PuzzlePieceSolid)
        {
            _restClient    = restClient;
            _windowService = windowService;

            _tabViewModels = new List <IModuleTabViewModel> {
                new BrowseTabViewModel(), new InstalledTabViewModel(), new UpdatesTabViewModel()
            };
            BrowseLoaded = new PubSubEvent();
        }
Esempio n. 5
0
 private void LoginButton_Click(object sender, EventArgs e)
 {
     MessageBox.Show(Tx.T("message"), Tx.T("message.caption"), MessageBoxButtons.OK, MessageBoxIcon.Information);
 }
Esempio n. 6
0
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
 Tx.T("TasksInfrastructure:CreateTask.AddAnother", "entry", value.ToString());
Esempio n. 7
0
 public void SetConfigError(Exception ex)
 {
     ConfigErrorLabel.Text = Tx.T("log selection view.config error", "msg", ex.Message);
     ConfigErrorLabel.Show();
 }
Esempio n. 8
0
        private void CompressWorker_DoWork(object sender, DoWorkEventArgs args)
        {
            try
            {
                // Quickly set the UI state
                CompressWorker.ReportProgress(0, new ProgressInfo {
                    CompressedSize = 0
                });

                // Collect all data
                DateTime minTime = DateTime.MinValue;
                if (SharedData.Instance.LogTimeSpan != TimeSpan.MaxValue)
                {
                    minTime = SharedData.Instance.LastLogUpdateTime - SharedData.Instance.LogTimeSpan;
                }
                string        notes        = SharedData.Instance.Notes;
                string        eMailAddress = SharedData.Instance.EMailAddress;
                List <string> logFiles     = new List <string>();
                totalLogSize = 0;
                long processedLogSize = 0;
                foreach (string basePath in SharedData.Instance.LogBasePaths)
                {
                    string dir              = Path.GetDirectoryName(basePath);
                    string baseName         = Path.GetFileName(basePath);
                    var    interestingFiles =
                        Directory.GetFiles(dir, baseName + "-?-*.fl")
                        .Concat(Directory.GetFiles(dir, baseName + "-scr-*.png"))
                        .Concat(Directory.GetFiles(dir, baseName + "-scr-*.jpg"));
                    foreach (string logFile in interestingFiles)
                    {
                        FileInfo fi = new FileInfo(logFile);
                        if (fi.LastWriteTimeUtc >= minTime)
                        {
                            logFiles.Add(logFile);
                            totalLogSize += fi.Length;
                        }
                    }
                }

                if (logFiles.Count == 0)
                {
                    throw new Exception(Tx.T("msg.no log files selected"));
                }

                InitializeArchive();

                if (!string.IsNullOrWhiteSpace(notes))
                {
                    using (var notesStream = new MemoryStream())
                        using (var writer = new StreamWriter(notesStream, Encoding.UTF8))
                        {
                            writer.Write(notes);
                            writer.Flush();
                            notesStream.Seek(0, SeekOrigin.Begin);
                            AddFile(notesStream, "notes.txt", DateTime.UtcNow);
                        }
                }

                if (!string.IsNullOrWhiteSpace(eMailAddress))
                {
                    using (var eMailStream = new MemoryStream())
                        using (var writer = new StreamWriter(eMailStream, Encoding.UTF8))
                        {
                            writer.Write("[InternetShortcut]\r\nURL=mailto:");
                            writer.Write(eMailAddress);
                            writer.Flush();
                            eMailStream.Seek(0, SeekOrigin.Begin);
                            AddFile(eMailStream, "email.url", DateTime.UtcNow);
                        }
                }

                EnsureDirectory("log/");
                foreach (string logFile in logFiles)
                {
                    if (CompressWorker.CancellationPending)
                    {
                        args.Cancel = true;
                        return;
                    }

                    FileInfo fi = new FileInfo(logFile);

                    AddFile(logFile, "log/" + Path.GetFileName(logFile));

                    processedLogSize += fi.Length;
                    //int percent = (int) (Math.Round(100.0 * processedLogSize / totalLogSize));
                    //CompressWorker.ReportProgress(percent, new ProgressInfo { CompressedSize = gzFile.Length });
                }

                if (CompressWorker.CancellationPending)
                {
                    args.Cancel = true;
                    return;
                }

                CloseArchive();

                CompressArchive();

                FileInfo archiveInfo = new FileInfo(archiveFileName2);
                CompressWorker.ReportProgress(1000, new ProgressInfo {
                    CompressedSize = archiveInfo.Length
                });
            }
            catch (ObjectDisposedException)
            {
                // We're leaving, don't do anything more.
                // Somehow this isn't caught by the BackgroundWorker management.
                return;
            }
        }
Esempio n. 9
0
 public SystemInfoGroupViewModel(string name, IEnumerable <SystemInfoDto> systemInfos)
 {
     Name   = Tx.T($"SystemInformation:Category.{name}");
     Childs = systemInfos.Select(x => new SystemInfoViewModel(x)).OrderBy(x => x.Childs.Any()).ThenBy(x => x.Name).ToList();
 }
Esempio n. 10
0
        private async void UpdateDiffDocumentAsync()
        {
            if (!IsLoaded)
            {
                return;
            }
            if (!diffInvalidated)
            {
                return;
            }
            // Concurrency: We assume the invoker is on main thread.
            if (updatingDiff)
            {
                return;
            }
            updatingDiff = true;
            try
            {
                if (summaryTextBlock != null)
                {
                    summaryTextBlock.Text = Tx.T("please wait");
                }
RETRY:
                await Task.Delay(10);

                string t1 = Text1, t2 = Text2;
                string text1 = t1 ?? "", text2 = t2 ?? "";
                Action diffAction = () =>
                {
                    // Diff
                    var diff = new diff_match_patch {
                        Diff_Timeout = 10
                    };
                    var diffs = diff.diff_main(text1, text2);
                    diff.diff_cleanupSemantic(diffs);
                    int add = 0, addl = 0, remove = 0, removel = 0;
                    foreach (var d in diffs)
                    {
                        if (d.operation == Operation.INSERT)
                        {
                            add++;
                            addl += d.text.Length;
                        }
                        else if (d.operation == Operation.DELETE)
                        {
                            remove++;
                            removel += d.text.Length;
                        }
                    }
                    //
                    _DiffSummary = Tx.T("diff.summary", "length", (text2.Length - text1.Length).ToString("+#;-#;0"),
                                        "add", add + "", "addlength", addl + "",
                                        "remove", remove + "", "removelength", removel + "");
                    diffLines = DiffToLines(diffs);
                };
                if (Math.Max(text1.Length, text2.Length) > 2 * 1024)
                {
                    await Task.Factory.StartNew(diffAction, CancellationToken.None,
                                                TaskCreationOptions.LongRunning, TaskScheduler.Default);
                }
                else
                {
                    diffAction();
                }
                diffLinesView = new ListCollectionView(diffLines);
                // Ensure we've compared the latest text
                if (t1 != Text1 || t2 != Text2)
                {
                    goto RETRY;
                }
                diffInvalidated = false;
                if (summaryTextBlock != null)
                {
                    summaryTextBlock.Text = _DiffSummary;
                }
                if (presenter != null)
                {
                    presenter.ItemsSource = diffLinesView;
                    // Move to the first difference
                    for (int l = 0; l < diffLinesView.Count; l++)
                    {
                        var diff = (DiffLine)diffLinesView.GetItemAt(l);
                        if (diff.Segments.Any(s => s.Style != DiffSegmentStyle.Normal))
                        {
                            var l1 = l;
                            await Dispatcher.BeginInvoke(DispatcherPriority.Input,
                                                         (Action)(() => SelectLineByIndex(l1)));

                            break;
                        }
                    }
                }
            }
            finally
            {
                updatingDiff = false;
            }
        }
Esempio n. 11
0
        public ValidationResult ValidateInput()
        {
            if (!string.IsNullOrWhiteSpace(FileHash))
            {
                if (!Hash.TryParse(FileHash, out var hash))
                {
                    return(new ValidationResult(Tx.T("TasksCommon:Utilities.FileSource.Errors.InvalidFileHash"), nameof(FileHash).Yield()));
                }

                using (var hashAlgorithm = HashAlgorithm.CreateHashAlgorithm())
                {
                    if (hash.HashData.Length != hashAlgorithm.HashSize / 8)
                    {
                        return(new ValidationResult(
                                   Tx.T("TasksCommon:Utilities.FileSource.Errors.InvalidHashSize", "algorithm", HashAlgorithm.ToString(), "expected",
                                        hashAlgorithm.HashSize.ToString(), "current", (FileHash.Length * 8).ToString()), nameof(FileHash).Yield()));
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(LocalPath) && string.IsNullOrWhiteSpace(Url))
            {
                return(new ValidationResult(Tx.T("TasksCommon:Utilities.FileSource.Errors.NoFileSourceSelected"), new [] { nameof(Url), nameof(LocalPath) }));
            }

            if (!string.IsNullOrWhiteSpace(LocalPath) && !string.IsNullOrWhiteSpace(Url))
            {
                return(new ValidationResult(Tx.T("TasksCommon:Utilities.FileSource.Errors.OnlyOneSourceAllowed"), new[] { nameof(Url), nameof(LocalPath) }));
            }

            if (!string.IsNullOrWhiteSpace(LocalPath))
            {
                if (LocalPath == BinaryPlaceholder)
                {
                    if (_cachedFile != null)
                    {
                        return(ValidationResult.Success);
                    }

                    return(new ValidationResult(Tx.T("TasksCommon:Utilities.FileSource.Errors.NoCachedFileAvailable"), nameof(LocalPath).Yield()));
                }

                try
                {
                    if (!File.Exists(LocalPath))
                    {
                        return(new ValidationResult(Tx.T("TasksCommon:Utilities.FileSource.Errors.FileDoesNotExist"), nameof(LocalPath).Yield()));
                    }
                }
                catch (Exception)
                {
                    return(new ValidationResult(Tx.T("TasksCommon:Utilities.FileSource.Errors.InvalidLocalPath"), nameof(LocalPath).Yield()));
                }

                return(ValidationResult.Success);
            }

            if (!string.IsNullOrWhiteSpace(Url))
            {
                try
                {
                    var uri = new Uri(Url, UriKind.Absolute);
                    if (!string.Equals(uri.Scheme, "http", StringComparison.OrdinalIgnoreCase) &&
                        !string.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase))
                    {
                        return(new ValidationResult(Tx.T("TasksCommon:Utilities.FileSource.Errors.UrlNotHttp"), nameof(Url).Yield()));
                    }

                    return(ValidationResult.Success);
                }
                catch (Exception)
                {
                    return(new ValidationResult(Tx.T("TasksCommon:Utilities.FileSource.Errors.InvalidUri"), nameof(Url).Yield()));
                }
            }

            throw new InvalidOperationException();
        }
Esempio n. 12
0
 public TasksViewModel(IWindowService windowService, IMazeRestClient restClient, IAppDispatcher dispatcher, IServiceProvider services,
                       CommandExecutionManager commandExecutionManager) : base(Tx.T("TasksInfrastructure:Tasks"), PackIconFontAwesomeKind.CalendarCheckRegular)
 {
     CommandExecutionManager = commandExecutionManager;
     _windowService          = windowService;
     _restClient             = restClient;
     _dispatcher             = dispatcher;
     _services = services;
 }
Esempio n. 13
0
        public static bool CheckPlaceholdersConsistency(string a, string b, bool includeCount, out string message)
        {
            if (a == null)
            {
                a = "";
            }
            if (b == null)
            {
                b = "";
            }

            string placeholderPattern;

            if (includeCount)
            {
                placeholderPattern = @"(?<!\{)\{(#|[^{=#]+)\}";
            }
            else
            {
                placeholderPattern = @"(?<!\{)\{([^{=#]+)\}";
            }

            List <string> varNamesA = new List <string>();
            Match         m         = Regex.Match(a, placeholderPattern);

            while (m.Success)
            {
                if (!varNamesA.Contains(m.Groups[1].Value))
                {
                    varNamesA.Add(m.Groups[1].Value);
                }
                m = m.NextMatch();
            }

            List <string> varNamesB = new List <string>();

            m = Regex.Match(b, placeholderPattern);
            while (m.Success)
            {
                if (!varNamesB.Contains(m.Groups[1].Value))
                {
                    varNamesB.Add(m.Groups[1].Value);
                }
                m = m.NextMatch();
            }

            foreach (string n in varNamesA)
            {
                if (!varNamesB.Remove(n))
                {
                    message = Tx.T("validation.content.missing placeholder", "name", n);
                    return(false);
                }
            }
            if (varNamesB.Count > 0)
            {
                message = Tx.T("validation.content.additional placeholder", "name", varNamesB[0]);
                return(false);
            }

            message = null;
            return(true);
        }
Esempio n. 14
0
        public bool Validate()
        {
            // NOTE: All checks are performed in their decreasing order of significance. The most-
            //       severe errors come first, proceeding to more informational problems. The first
            //       determined error generates the visible message and quits the method so that
            //       no other checks are performed or could overwrite the message.

            // First validate all children recursively and remember whether there was a problem
            // somewhere down the tree
            bool anyChildError = false;

            foreach (TextKeyViewModel child in Children)
            {
                if (!child.Validate())
                {
                    anyChildError = true;
                }
            }

            // Partial keys can only indicate problems in the subtree
            if (!IsFullKey)
            {
                HasOwnProblem = false;
                HasProblem    = anyChildError;
                Remarks       = null;
                return(!anyChildError);
            }

            // The Tx namespace generally has no problems
            if (TextKey.StartsWith("Tx:"))
            {
                HasOwnProblem = false;
                HasProblem    = anyChildError;
                Remarks       = null;
                return(!anyChildError);
            }

            HasOwnProblem = false;
            HasProblem    = anyChildError;
            Remarks       = null;

            // ----- Check for count/modulo errors -----

            // Check for invalid count values in any CultureText
            if (CultureTextVMs.Any(ct =>
                                   ct.QuantifiedTextVMs.Any(qt =>
                                                            qt.Count < 0 || qt.Count >= 0xFFFF)))
            {
                HasOwnProblem = true;
                HasProblem    = true;
                AddRemarks(Tx.T("validation.content.invalid count"));
            }
            // Check for invalid modulo values in any CultureText
            if (CultureTextVMs.Any(ct =>
                                   ct.QuantifiedTextVMs.Any(qt =>
                                                            qt.Modulo != 0 && (qt.Modulo < 2 || qt.Modulo > 1000))))
            {
                HasOwnProblem = true;
                HasProblem    = true;
                AddRemarks(Tx.T("validation.content.invalid modulo"));
            }
            // Check for duplicate count/modulo values in any CultureText
            if (CultureTextVMs.Any(ct =>
                                   ct.QuantifiedTextVMs
                                   .GroupBy(qt => qt.Count << 16 | qt.Modulo)
                                   .Any(grp => grp.Count() > 1)))
            {
                HasOwnProblem = true;
                HasProblem    = true;
                AddRemarks(Tx.T("validation.content.duplicate count modulo"));
            }

            // ----- Check referenced keys -----

            if (CultureTextVMs.Any(ct =>
                                   ct.TextKeyReferences != null &&
                                   ct.TextKeyReferences.OfType <string>().Any(key => key == TextKey)))
            {
                HasOwnProblem = true;
                HasProblem    = true;
                AddRemarks(Tx.T("validation.content.referenced key loop"));
            }

            if (CultureTextVMs.Any(ct =>
                                   ct.QuantifiedTextVMs.Any(qt =>
                                                            qt.TextKeyReferences != null &&
                                                            qt.TextKeyReferences.OfType <string>().Any(key => key == TextKey))))
            {
                HasOwnProblem = true;
                HasProblem    = true;
                AddRemarks(Tx.T("validation.content.referenced key loop"));
            }

            if (CultureTextVMs.Any(ct =>
                                   ct.TextKeyReferences != null &&
                                   ct.TextKeyReferences.OfType <string>().Any(key => !MainWindowVM.TextKeys.ContainsKey(key))))
            {
                HasOwnProblem = true;
                HasProblem    = true;
                AddRemarks(Tx.T("validation.content.missing referenced key"));
            }

            if (CultureTextVMs.Any(ct =>
                                   ct.QuantifiedTextVMs.Any(qt =>
                                                            qt.TextKeyReferences != null &&
                                                            qt.TextKeyReferences.OfType <string>().Any(key => !MainWindowVM.TextKeys.ContainsKey(key)))))
            {
                HasOwnProblem = true;
                HasProblem    = true;
                AddRemarks(Tx.T("validation.content.missing referenced key"));
            }

            // ----- Check translations consistency -----

            IsAccepted = false;

            if (CultureTextVMs.Count > 1)
            {
                string primaryText = CultureTextVMs[0].Text;

                for (int i = 0; i < CultureTextVMs.Count; i++)
                {
                    // Skip main text of primary culture, it's what we compare everything else with
                    if (i > 0)
                    {
                        string transText = CultureTextVMs[i].Text;
                        // Ignore any empty text. If that's a problem, it'll be found as missing below.
                        if (!String.IsNullOrEmpty(transText))
                        {
                            string message;
                            if (!CheckPlaceholdersConsistency(primaryText, transText, true, out message))
                            {
                                CultureTextVMs[i].IsPlaceholdersProblem = true;
                                if (CultureTextVMs[i].AcceptPlaceholders)
                                {
                                    IsAccepted = true;
                                }
                                else
                                {
                                    HasOwnProblem = true;
                                    HasProblem    = true;
                                    AddRemarks(message);
                                }
                            }
                            else
                            {
                                CultureTextVMs[i].IsPlaceholdersProblem = false;
                            }
                            if (!CheckPunctuationConsistency(primaryText, transText, out message))
                            {
                                CultureTextVMs[i].IsPunctuationProblem = true;
                                if (CultureTextVMs[i].AcceptPunctuation)
                                {
                                    IsAccepted = true;
                                }
                                else
                                {
                                    HasOwnProblem = true;
                                    HasProblem    = true;
                                    AddRemarks(message);
                                }
                            }
                            else
                            {
                                CultureTextVMs[i].IsPunctuationProblem = false;
                            }
                        }
                        else
                        {
                            // If there's no text, and it hasn't been checked, there is no problem
                            CultureTextVMs[i].IsPlaceholdersProblem = false;
                            CultureTextVMs[i].IsPunctuationProblem  = false;
                        }
                    }

                    foreach (var qt in CultureTextVMs[i].QuantifiedTextVMs)
                    {
                        string transText = qt.Text;
                        // Ignore any empty text for quantified texts.
                        if (!String.IsNullOrEmpty(transText))
                        {
                            string message;
                            if (!CheckPlaceholdersConsistency(primaryText, transText, false, out message))                               // Ignore count placeholder here
                            {
                                qt.IsPlaceholdersProblem = true;
                                if (qt.AcceptPlaceholders)
                                {
                                    IsAccepted = true;
                                }
                                else
                                {
                                    HasOwnProblem = true;
                                    HasProblem    = true;
                                    AddRemarks(message);
                                }
                            }
                            else
                            {
                                qt.IsPlaceholdersProblem = false;
                            }
                            if (!CheckPunctuationConsistency(primaryText, transText, out message))
                            {
                                qt.IsPunctuationProblem = true;
                                if (qt.AcceptPunctuation)
                                {
                                    IsAccepted = true;
                                }
                                else
                                {
                                    HasOwnProblem = true;
                                    HasProblem    = true;
                                    AddRemarks(message);
                                }
                            }
                            else
                            {
                                qt.IsPunctuationProblem = false;
                            }
                        }
                        else
                        {
                            // If there's no text, and it hasn't been checked, there is no problem
                            qt.IsPlaceholdersProblem = false;
                            qt.IsPunctuationProblem  = false;
                        }
                    }
                }
            }

            // ----- Check for missing translations -----

            foreach (var ctVM in CultureTextVMs)
            {
                if (ctVM.CultureName.Length == 2)
                {
                    // Check that every non-region culture has a text set
                    if (String.IsNullOrEmpty(ctVM.Text))
                    {
                        ctVM.IsMissing = true;
                        if (ctVM.AcceptMissing)
                        {
                            IsAccepted = true;
                        }
                        else
                        {
                            HasOwnProblem = true;
                            HasProblem    = true;
                            AddRemarks(Tx.T("validation.content.missing translation"));
                        }
                    }
                    else
                    {
                        ctVM.IsMissing = false;
                    }
                }
                else if (ctVM.CultureName.Length == 5)
                {
                    // Check that every region-culture with no text has a non-region culture with a
                    // text set (as fallback)
                    if (String.IsNullOrEmpty(ctVM.Text) &&
                        !CultureTextVMs.Any(vm2 => vm2.CultureName == ctVM.CultureName.Substring(0, 2)))
                    {
                        ctVM.IsMissing = true;
                        if (ctVM.AcceptMissing)
                        {
                            IsAccepted = true;
                        }
                        else
                        {
                            HasOwnProblem = true;
                            HasProblem    = true;
                            AddRemarks(Tx.T("validation.content.missing translation"));
                        }
                    }
                    else
                    {
                        ctVM.IsMissing = false;
                    }
                }

                // Also check quantified texts for missing texts
                foreach (var qt in ctVM.QuantifiedTextVMs)
                {
                    if (String.IsNullOrEmpty(qt.Text))
                    {
                        qt.IsMissing = true;
                        if (qt.AcceptMissing)
                        {
                            IsAccepted = true;
                        }
                        else
                        {
                            HasOwnProblem = true;
                            HasProblem    = true;
                            AddRemarks(Tx.T("validation.content.missing translation"));
                        }
                    }
                    else
                    {
                        qt.IsMissing = false;
                    }
                }
            }

            return(!HasProblem);
        }
Esempio n. 15
0
 public DurationStopEventViewModel()
 {
     this.RegisterProperty(() => Duration, Tx.T("TasksCommon:StopEvents.Duration.Properties.Duration"),
                           Tx.T("TasksCommon:StopEvents.Duration.Properties.Duration.Description"), Tx.T("TasksCommon:Categories.Common"));
 }
Esempio n. 16
0
 /// <summary>
 ///     Register a new property for the <see cref="IProvideEditableProperties" />
 /// </summary>
 /// <typeparam name="T">The type of the property</typeparam>
 /// <param name="provideEditableProperties">
 ///     The <see cref="IProvideEditableProperties" /> the property should be registered
 ///     to
 /// </param>
 /// <param name="property">The expression which points to the property</param>
 /// <param name="name">The display name of the property</param>
 /// <param name="description">The description of the property</param>
 /// <param name="category">The category of the property</param>
 /// <returns>Returns the <see cref="provideEditableProperties" /> to allow the fluent usage of this method</returns>
 public static IProvideEditableProperties RegisterProperty <T>(this IProvideEditableProperties provideEditableProperties,
                                                               Expression <Func <T> > property, string name, string description, string category)
 {
     provideEditableProperties.Properties.Add(new Property <T>(provideEditableProperties, property, name, description, category ?? Tx.T("TasksInfrastructure:CreateTask.Common")));
     return(provideEditableProperties);
 }
Esempio n. 17
0
        private async Task fetchUserData(string player_name, int gamemode_index, bool show_errors = true)
        {
            bool samename = false;
            bool samemode = false;

            if (player_name == previousUsername)
            {
                samename = true;
            }
            if (gamemode_index == previousGamemode)
            {
                samemode = true;
            }
            if (samemode == true && samename == true)
            {
                previousRefresh = userdata;
            }
            dynamic rawreturns = await ripple.GetUserAsync(player : player_name, gamemode : gamemode_index, showErrors : show_errors);

            userdata         = rawreturns[0];
            previousUsername = player_name;
            previousGamemode = gamemode_index;
            // do nothing if player did not play or player is invalid
            if (Convert.ToString(userdata) == Convert.ToString(int.MaxValue))
            {
                return;
            }
            if (userdata.pp_rank == null)
            {
                return;
            }
            if (userdata == null)
            {
                return;
            }

            playername.Content  = Convert.ToString(userdata.username);
            Avatar.Source       = new ImageSourceConverter().ConvertFromString("http://a.ripple.moe/" + userdata.user_id) as ImageSource;
            globalrank.Content  = "#" + userdata.pp_rank;
            countryRank.Content = "#" + userdata.pp_country_rank + " (" + userdata.country + ")";

            rankedScore.Content = Tx.TC("player.Ranked score") + " " + Convert.ToInt64(userdata.ranked_score).ToString("n", NFInoDecimal);
            playCount.Content   = Tx.TC("player.Play count") + " " + Convert.ToInt32(userdata.playcount).ToString("n", NFInoDecimal);
            acc.Content         = Math.Round(Convert.ToDouble(userdata.accuracy), 2) + "%";
            pp.Content          = Convert.ToDouble(userdata.pp_raw).ToString("n", NFIperformance) + " pp";
            totalScore.Content  = Tx.TC("player.Total score") + " " + Convert.ToInt64(userdata.total_score).ToString("n", NFInoDecimal);
            level.Content       = Tx.TC("player.Level") + " " + Math.Truncate(Convert.ToDouble(userdata.level)) + " (" + ((Convert.ToDouble(userdata.level) - Math.Truncate(Convert.ToDouble(userdata.level))) * 100).ToString("n", NFInoDecimal) + "%)";

            /* grades.Content = "SS / S / A: " + Convert.ToInt32(userdata.count_rank_ss).ToString("n", NFInoDecimal) + " / "
             + Convert.ToInt32(userdata.count_rank_s).ToString("n", NFInoDecimal) + " / "
             + Convert.ToInt32(userdata.count_rank_a).ToString("n", NFInoDecimal); */
            SS.Content     = Convert.ToInt32(userdata.count_rank_ss).ToString("n", NFInoDecimal);
            S.Content      = Convert.ToInt32(userdata.count_rank_s).ToString("n", NFInoDecimal);
            A.Content      = Convert.ToInt32(userdata.count_rank_a).ToString("n", NFInoDecimal);
            userID.Content = Tx.TC("player.User ID") + " " + userdata.user_id;
            flag.Source    = new BitmapImage(new Uri("/osu!rank;component/Drapeaux/" + userdata.country + ".png", UriKind.Relative));
            // {pack://application:,,,/osu!rank;component/Drapeaux/unknown.png}
            levelProgress.Value = ((Convert.ToDouble(userdata.level) - Math.Truncate(Convert.ToDouble(userdata.level))) * 100);
            if (samename == true && samemode == true)
            {
                updateVariation(previousRefresh, userdata);
            }
            else
            {
                resetVariation();
            }
            lastUpdatedRefresher.Stop();
            lastRefreshedAgo       = new TimeSpan(0);
            lastRefresh.Visibility = Visibility.Visible;
            string currentTime = lastRefreshedAgo.ToString();

            lastRefresh.Content = Tx.T("osu rank.auto refresh.updated ago", "time", currentTime);
            lastUpdatedRefresher.Start();
        }
Esempio n. 18
0
        private void compareStats(dynamic player1, dynamic player2)
        {
            #region comparison
            // variables to simplify comparison
            // player 1
            int    p1ranking     = Convert.ToInt32(player1.pp_rank);
            double p1pp          = Convert.ToDouble(player1.pp_raw);
            double p1acc         = Convert.ToDouble(player1.accuracy);
            int    p1playcount   = Convert.ToInt32(player1.playcount);
            long   p1totalscore  = Convert.ToInt64(player1.total_score);
            long   p1rankedscore = Convert.ToInt64(player1.ranked_score);
            // player 2
            int    p2ranking     = Convert.ToInt32(player2.pp_rank);
            double p2pp          = Convert.ToDouble(player2.pp_raw);
            double p2acc         = Convert.ToDouble(player2.accuracy);
            int    p2playcount   = Convert.ToInt32(player2.playcount);
            long   p2totalscore  = Convert.ToInt64(player2.total_score);
            long   p2rankedscore = Convert.ToInt64(player2.ranked_score);
            // difference
            long drankedscore, dtotalscore; int dranking, dplaycount; double dpp, dacc;

            // actual comparison display
            // pp and ranking
            if (p1pp > p2pp)
            {
                dranking = p2ranking - p1ranking;
                dpp      = p1pp - p2pp;
                p1_ranking.FontWeight     = bold;
                p1_performance.FontWeight = bold;
            }
            else
            {
                dranking = p1ranking - p2ranking;
                dpp      = p2pp - p1pp;
                p2_ranking.FontWeight     = bold;
                p2_performance.FontWeight = bold;
            }
            diff_ranking.Content     = Tx.T("comparator.n ranks", dranking);
            diff_performance.Content = dpp.ToString("n", NFIperformance) + " pp";
            // acc
            if (p1acc > p2acc)
            {
                dacc = p1acc - p2acc;
                p1_acc.FontWeight = bold;
            }
            else
            {
                dacc = p2acc - p1acc;
                p2_acc.FontWeight = bold;
            }
            diff_acc.Content = dacc.ToString("n", NFIperformance) + "%";
            // playcount
            if (p1playcount > p2playcount)
            {
                dplaycount = p1playcount - p2playcount;
                p1_playcount.FontWeight = bold;
            }
            else
            {
                dplaycount = p2playcount - p1playcount;
                p2_playcount.FontWeight = bold;
            }
            diff_playcount.Content = dplaycount.ToString("n", NFInoDecimal);
            // totalscore
            if (p1totalscore > p2totalscore)
            {
                dtotalscore = p1totalscore - p2totalscore;
                p1_totalscore.FontWeight = bold;
            }
            else
            {
                dtotalscore = p2totalscore - p1totalscore;
                p2_totalscore.FontWeight = bold;
            }
            diff_totalscore.Content = dtotalscore.ToString("n", NFInoDecimal);
            // rankedscore
            if (p1rankedscore > p2rankedscore)
            {
                drankedscore = p1rankedscore - p2rankedscore;
                p1_rankedscore.FontWeight = bold;
            }
            else
            {
                drankedscore = p2rankedscore - p1rankedscore;
                p2_rankedscore.FontWeight = bold;
            }
            diff_rankedscore.Content = drankedscore.ToString("n", NFInoDecimal);
            #endregion
        }
Esempio n. 19
0
        private void OKButton_Click(object sender, RoutedEventArgs args)
        {
            // Unfocus parameter name TextBox to have its changes updated
            OKButton.Focus();

            string textKey = TextKeyText.Text != null?TextKeyText.Text.Trim() : "";

            // Validate the entered text key
            string errorMessage;

            if (!TextKeyViewModel.ValidateName(textKey, out errorMessage))
            {
                App.WarningMessage(Tx.T("msg.invalid text key entered", "msg", errorMessage));
                return;
            }

            // Check if the text key already exists but the translated text is different
            TextKeyViewModel existingTextKeyVM;

            if (MainViewModel.Instance.TextKeys.TryGetValue(textKey, out existingTextKeyVM))
            {
                if (TranslationText.Text != existingTextKeyVM.CultureTextVMs[0].Text)
                {
                    TaskDialogResult result = TaskDialog.Show(
                        owner: this,
                        allowDialogCancellation: true,
                        title: "TxEditor",
                        mainInstruction: Tx.T("window.wizard.text key exists", "key", Tx.Q(textKey)),
                        content: Tx.T("window.wizard.text key exists.content"),
                        customButtons: new string[] { Tx.T("task dialog.button.overwrite"), Tx.T("task dialog.button.cancel") });
                    if (result.CustomButtonResult != 0)
                    {
                        return;
                    }
                }
            }

            // Backup current clipboard content
            ClipboardBackup = ClipboardHelper.GetDataObject();

            // Build the text to paste back into the source document, depending on the selected code
            // language
            if (SourceCSharpButton.IsChecked == true)
            {
                App.Settings.Wizard.SourceCode = "C#";

                string keyString = textKey.Replace("\\", "\\\\").Replace("\"", "\\\"");

                StringBuilder codeSb = new StringBuilder();
                if (isPartialString)
                {
                    codeSb.Append("\" + ");
                }
                codeSb.Append("Tx.T(\"" + keyString + "\"");
                var countPlaceholder = placeholders.FirstOrDefault(p => p.Name == "#");
                if (countPlaceholder != null)
                {
                    codeSb.Append(", ");
                    codeSb.Append(countPlaceholder.Code);
                }
                foreach (var pd in placeholders)
                {
                    if (pd == countPlaceholder)
                    {
                        continue;                                               // Already processed
                    }
                    codeSb.Append(", \"" + pd.Name.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"");
                    codeSb.Append(", ");
                    if (pd.IsQuoted)
                    {
                        codeSb.Append("Tx.Q(");
                    }
                    codeSb.Append(pd.Code);
                    if (pd.IsQuoted)
                    {
                        codeSb.Append(")");
                    }
                }
                codeSb.Append(")");
                if (isPartialString)
                {
                    codeSb.Append(" + \"");
                }
                Clipboard.SetText(codeSb.ToString());
            }
            if (SourceXamlButton.IsChecked == true)
            {
                App.Settings.Wizard.SourceCode = "XAML";

                string keyString     = textKey.Replace("\\", "\\\\").Replace("'", "\\'");
                string defaultString = TranslationText.Text.Replace("\\", "\\\\").Replace("'", "\\'");

                string code = "{Tx:T '" + keyString + "'";
                if (SetDefaultCheckbox.IsChecked == true)
                {
                    code += ", Default='" + defaultString + "'";
                }
                code += "}";
                Clipboard.SetText(code);
            }
            if (SourceAspxButton.IsChecked == true)
            {
                App.Settings.Wizard.SourceCode = "aspx";

                string keyString = textKey.Replace("\\", "\\\\").Replace("\"", "\\\"");

                StringBuilder codeSb = new StringBuilder();
                codeSb.Append("<%= Tx.T(\"" + keyString + "\") %>");
                Clipboard.SetText(codeSb.ToString());
            }

            // Remember the text key for next time and close the wizard dialog window
            prevTextKey  = textKey;
            DialogResult = true;
            Close();
        }
Esempio n. 20
0
        public DownloadViewModel()
        {
            FileSource = new FileSourceViewModel();

            this.RegisterFileSource(FileSource);
            this.RegisterProperty(() => TargetPath, Tx.T("TasksCommon:Commands.Download.Properties.TargetPath"),
                                  Tx.T("TasksCommon:Commands.Download.Properties.TargetPath.Description"), Tx.T("TasksCommon:Categories.Common"));
            this.RegisterProperty(() => FileExistsBehavior, Tx.T("TasksCommon:Commands.Download.Properties.FileExistsBehavior"),
                                  Tx.T("TasksCommon:Commands.Download.Properties.FileExistsBehavior.Description"), Tx.T("TasksCommon:Categories.Behavior"));
        }