Example #1
0
        /// <summary>
        /// Remove a player to the lobby.
        /// </summary>
        /// <param name="sender">Must be an object of the Player class, the player you wish to remove.</param>
        private async void LobbyRemovePlayer(object sender)
        {
            Player subtract = (Player)sender;
            // Are we sure the player wants to do this?
            var DialogResult = await Dialogs.ShowMessageAsync(this, "Are you sure?", "You're about to delete " + subtract.Name + " and remove them from this lobby. This cannot be undone - are you sure?", MessageDialogStyle.AffirmativeAndNegative, YesNoSettings);

            // Check for the answer...
            if (DialogResult == MessageDialogResult.Negative)
            {
                // The player has cancelled the operation. Return.
                return;
            }
            // The player would like to continue with the operation. Remove the player...
            ObservableCollection <Player> newPlayers = new ObservableCollection <Player>();

            foreach (Player player in Players)
            {
                if (player == subtract)
                {
                    subtract = null;
                }
                else
                {
                    if (subtract == null)
                    {
                        player.Digit--;
                    }
                    newPlayers.Add(player);
                }
            }
            Players = newPlayers; OnPropertyChanged("Players");
        }
        /// <summary>
        /// Prompt the user to confirm action
        /// Remove the current packaged solution from the view
        /// Initialize new packaged solution
        /// </summary>
        private async void CreateNewPackagedSolution()
        {
            // Run message dialog and await response
            var result = await _dialogCoordinator.ShowMessageAsync(this,
                                                                   "Ny pakkeløsning",
                                                                   "Hvis du opretter en ny pakkeløsning mister du arbejdet på din nuværende pakkeløsning. Vil du fortsætte?",
                                                                   MessageDialogStyle.AffirmativeAndNegative,
                                                                   new MetroDialogSettings()
            {
                NegativeButtonText = "Afbryd"
            });

            // If negative button was pressed => return
            if (result == MessageDialogResult.Negative)
            {
                return;
            }

            // Clear the appliance list for the current packaged solution
            AppliancesInPackagedSolution.Clear();

            // Reset collections and results
            PackagedSolution       = new PackagedSolution();
            EeiResultsRoomHeating  = new EEICalculationResult();
            EeiResultsWaterHeating = new EEICalculationResult();

            // Update the EEI (=> 0)
            UpdateEei();
        }
Example #3
0
        /// <summary>
        /// Добавяне на продукт в базата,при успех се връща статус 200
        /// </summary>
        /// <returns></returns>
        public async Task InsertGoodToDB()
        {
            using (var client = new HttpClient())
            {
                // client.BaseAddress = new Uri("http://" + base.IP + ":" + base.Port);
                client.BaseAddress = new Uri("http://" + base.Address);
                NewGood.SupplierID = GoodSupplier.ID;
                var info    = NewGood;
                var content = JsonConvert.SerializeObject(info);
                var buffer  = System.Text.Encoding.UTF8.GetBytes(content);

                var byteContent = new ByteArrayContent(buffer);
                byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                using (HttpResponseMessage response = await client.PostAsync(base.ApiController + "/" + base.SendGood_Url, byteContent))
                {
                    using (HttpContent httpcontent = response.Content)
                    {
                        string mycontent = await httpcontent.ReadAsStringAsync();

                        if (mycontent != "200")
                        {
                            await dialogCoordinator.ShowMessageAsync(this, "Error saving good", "Couldn't add good to database!");
                        }
                    }
                }
            }
        }
        public async void LoadRawMaterials()
        {
            string errorMessage = null;

            try
            {
                var rawMaterialsInDb    = _unitOfWork.RawMaterials.GetRawMaterials().ToList();
                var rawMaterialsForView = RestproMapper.MapRawMaterialListToWpfRawMaterialList(rawMaterialsInDb);
                RawMaterials = new BindingList <WpfRawMaterial>(rawMaterialsForView);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                errorMessage = e.Message;
            }

            if (errorMessage == null)
            {
                return;
            }

            await dialogCoordinator
            .ShowMessageAsync(this, "Error"
                              , "Fatal Error Occured. You're probably screwed!\n" +
                              errorMessage);
        }
        public async void Execute(object parametro)
        {
            if (parametro is Window)
            {
                if (this.UsuariosViewModel.Seleccionado == null)
                {
                    Usuarios nuevo = new Usuarios(5, Username, true, Nombres, Apellidos, Email);
                    nuevo.Password = ((PasswordBox)((Window)parametro).FindName("TxtPassword")).Password;
                    this.UsuariosViewModel.agregarElemento(nuevo);
                    await dialogCoordinator.ShowMessageAsync(this,
                                                             "Agregar usuario", "Elemento almacenado correctamente!", MessageDialogStyle.Affirmative);
                }
                else
                {
                    Usuario.Apellidos = this.Apellidos;
                    Usuario.Nombres   = this.Nombres;
                    Usuario.Email     = this.Email;
                    Usuario.Username  = this.Username;

                    int posicion = this.UsuariosViewModel.usuarios.IndexOf(this.UsuariosViewModel.Seleccionado);
                    this.UsuariosViewModel.usuarios.RemoveAt(posicion);
                    this.UsuariosViewModel.usuarios.Insert(posicion, Usuario);
                    await dialogCoordinator.ShowMessageAsync(this,
                                                             "Actualizar usuario", "Elemento actualizado correctamente!", MessageDialogStyle.Affirmative);
                }
                ((Window)parametro).Close();
            }
        }
        /// <summary>
        /// 预览
        /// </summary>
        public void EnQrCode()
        {
            // QrCode m_QrCode = new QrEncoder(drawingOptions.errorCorrectionLevel).Encode(drawingOptions.QrText);
            try
            {
                Task.Run <Bitmap>(() => {
                    QrCodeOptions options = GetQrCodeOptions();

                    if (ImageContentlist.Count > 0)
                    {
                        return(new DrawQrCode(options).QRCodeEncoder(ImageContentlist[0].Trim()));
                    }
                    else
                    {
                        return(new DrawQrCode(options).QRCodeEncoder());
                    }

                    //return DrawingQrCodeImg.DrawDarkModule();
                }).ContinueWith(result => {
                    if (result.IsCompleted)
                    {
                        if (result.Result != null)
                        {
                            ShowEmguImg(result.Result);
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                var controller = _dialogCoordinator.ShowMessageAsync(this, "提示", "程序EnQrCode运行出现异常" + ex.Message);
            }
        }
Example #7
0
        private async Task ExportCommandExecute()
        {
            if (!Directory.Exists(TargetFolder))
            {
                await dialCoord.ShowMessageAsync(this, "Error", "Target directory not found");

                return;
            }

            string fileName = TargetFolder + "\\" + TargetFile;

            if (DatePostfix)
            {
                fileName += "_" + DateTime.Now.ToString("yyyyMMdd-hhmmss");
            }

            if (!SplitBoardsToFiles)
            {
                await DoExportWhole(fileName);
            }
            else
            {
                await DoExportSplit(fileName);
            }

            await dialCoord.ShowMessageAsync(this, "Info", "Process finished");
        }
Example #8
0
        /// <summary>
        /// Loads Work Cycles with true flag from database
        /// </summary>
        public async void LoadWorkCycles()
        {
            string errorMessage = null;

            try
            {
                var workCyclesInDb = _unitOfWork.WorkCycles.GetWorkCycles().ToList();
                var wpfWorkCycles  = RestproMapper.MapWorkCycleListToWpfWorkCycleList(workCyclesInDb);
                WorkCycles = new ObservableCollection <WpfWorkCycle>(wpfWorkCycles);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                errorMessage = e.Message;
            }

            if (errorMessage == null)
            {
                return;
            }

            await dialogCoordinator
            .ShowMessageAsync(this, "Error"
                              , "Fatal Error Occured. You're probably screwed!\n" +
                              errorMessage);
        }
        private async void ResetRpdPwdAsync()
        {
            if (Info.NewPassword != Info.ConfirmPassword)
            {
                _ = await dialogCoordinator.ShowMessageAsync(this, "Alert!", "The passwords you have entered do not match.", MessageDialogStyle.Affirmative);
                Info.NewPassword = String.Empty;
                Info.ConfirmPassword = String.Empty;
                return;
            }

            QueryResult result = resetPwdQuery.Execute(Info);

            if (result.IsError)
            {
                _ = await dialogCoordinator.ShowMessageAsync(this, "Information!", result.ErorrMessage, MessageDialogStyle.Affirmative);
                return;
            }

            _ = await dialogCoordinator.ShowMessageAsync(this, "Information!", "Your password was successfully changed.", MessageDialogStyle.Affirmative);

            // Reset session timeout
            sessionData.UpdateTimeStamp();

            // Navigate to main screen
            regionManager.RequestNavigate("MainContentRegion", "MainContent");
        }
        private async void DeleteProduct()
        {
            var mySettings = new MetroDialogSettings()
            {
                AffirmativeButtonText = "Oui",
                NegativeButtonText    = "Non"
            };

            MessageDialogResult result = await dialogCoordinator.ShowMessageAsync(this, "Suppression de produit", "Êtes-vous sûr de vouloir supprimer ce produit? \nAttention : cette opération est irréversible. ",
                                                                                  MessageDialogStyle.AffirmativeAndNegative, mySettings);

            if (result == MessageDialogResult.Negative)
            {
                return;
            }

            var success = persistance.RemoveProductDB(SelectedProduct);

            if (success)
            {
                ProductsView.Remove(SelectedProduct);
                return;
            }

            await dialogCoordinator.ShowMessageAsync(this, "Suppression de produit", "Erreur lors de la suppression \nBase de donnée non modifié");
        }
        public async void AddProduct(Product product)
        {
            if (product is not null)
            {
                var dialogResult = await _dialogCoordinator.ShowMessageAsync(this, "Adding new product", "Are you sure you want to add this product?", MessageDialogStyle.AffirmativeAndNegative);

                if (dialogResult == MessageDialogResult.Affirmative)
                {
                    if (await _dataRepository.Add(product))
                    {
                        await _dialogCoordinator.ShowMessageAsync(this, "Informaction", "Product has been successfully added", MessageDialogStyle.Affirmative);

                        SetDefaultProperties();
                    }
                    else
                    {
                        await _dialogCoordinator.ShowMessageAsync(this, "Informaction", "Cannot add this product", MessageDialogStyle.Affirmative);
                    }
                }

                _productsViewModel.GetProducts();
            }
            else
            {
                await _dialogCoordinator.ShowMessageAsync(this, "Error", "Product cannot be empty!", MessageDialogStyle.Affirmative);
            }
        }
        private async void DecryptAndLoadAction()
        {
            CustomDialog customDialog = new CustomDialog()
            {
                Title = LocalizationManager.GetStringByKey("String_Header_MasterPassword")
            };

            CredentialsMasterPasswordViewModel credentialsMasterPasswordViewModel = new CredentialsMasterPasswordViewModel(async instance =>
            {
                await dialogCoordinator.HideMetroDialogAsync(this, customDialog);

                if (!CredentialManager.Load(instance.Password))
                {
                    await dialogCoordinator.ShowMessageAsync(this, LocalizationManager.GetStringByKey("String_Header_WrongPassword"), LocalizationManager.GetStringByKey("String_WrongPasswordDecryptionFailed"), MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog);
                }

                CheckCredentialsLoaded();

                TimerLockUIStart();
            }, instance =>
            {
                dialogCoordinator.HideMetroDialogAsync(this, customDialog);
            });

            customDialog.Content = new CredentialsMasterPasswordDialog
            {
                DataContext = credentialsMasterPasswordViewModel
            };

            await dialogCoordinator.ShowMetroDialogAsync(this, customDialog);
        }
Example #13
0
        private async void SaveDataAsync()
        {
            if (sessionData.IsSessionTimedOut)
            {
                _ = await dialogCoordinator.ShowMessageAsync(this, "Alert!", "Your RPD session has expired please log in again.", MessageDialogStyle.Affirmative);

                ReturnToLogin();
                return;
            }

            DocumentIdList <String> idList = new DocumentIdList <String>(DocumentIDs);
            CommandResult           result = submitDocumentList.Execute(idList.ToString());

            if (result.IsError)
            {
                // Display error message
                _ = await dialogCoordinator.ShowMessageAsync(this, "Error!", result.ErorrMessage, MessageDialogStyle.Affirmative);

                return;
            }

            // Display success message
            _ = await dialogCoordinator.ShowMessageAsync(this, "Information!", $"Your data was succesfully transmitted to RPD", MessageDialogStyle.Affirmative);

            // Reset session timeout
            sessionData.UpdateTimeStamp();

            // Clear the list
            DocumentIDs.Clear();
        }
Example #14
0
        private async void CreateAsync(object window)
        {
            Window         win    = window as Window;
            string         entity = "";
            ConnectionCore cc     = null;

            try
            {
                SettingsCore settings = new SettingsCore();
                settings.SettingsSerialize();
                cc     = new Cores.ConnectionCore(new ConnectionModel(Type, ConnString));
                entity = cc.CreateModel(Document.Text, settings.Settings);
            }
            catch (Exception ex)
            {
                await _dialogCoordinator.ShowMessageAsync(this, $"Error!", $"Error message: {ex.Message}  /r/nStackTrace: {ex.StackTrace}");

                return;
            }

            if (cc != null && cc.Errors.Count > 0)
            {
                await _dialogCoordinator.ShowMessageAsync(this, $"Error!", $"Error message: {cc.Errors.First().Message}  /r/nStackTrace: {cc.Errors.First().StackTrace}");
            }
            else
            {
                win.Tag          = entity;
                win.DialogResult = true;
                win.Close();
            }
        }
        private void Save(Discipline discipline)
        {
            EducationProcessContext context = new EducationProcessContext();

            if (context.Disciplines.FirstOrDefault(x => x.DisciplineIndex.ToLower() == DisciplineIndex.ToLower()) != null)
            {
                _dialogCoordinator.ShowMessageAsync(this, "Внимание", "Данный индекс уже существует");
                return;
            }

            if (discipline == null)
            {
                Discipline newDiscipline = new Discipline()
                {
                    CathedraId       = SelectedCathedra.CathedraId,
                    DisciplineIndex  = DisciplineIndex,
                    Name             = DisciplineName,
                    EducationCycleId = SelectedCyclesAndModule.EducationCycleId
                };
                context.Disciplines.Add(newDiscipline);
                context.SaveChanges();
            }
            else
            {
                _discipline.Name             = DisciplineName;
                _discipline.DisciplineIndex  = DisciplineIndex;
                _discipline.CathedraId       = SelectedCathedra.CathedraId;
                _discipline.EducationCycleId = SelectedCyclesAndModule.EducationCycleId;
                context.Disciplines.Update(_discipline);
                context.SaveChanges();
            }

            _dialogCoordinator.ShowMessageAsync(this, "Дисциплина сохранена", null);
        }
Example #16
0
        private async void OnTaxSave()
        {
            _unitOfWork.InventorySettings.SetTax(InventorySettings.Tax);
            string errorMessage = null;

            try
            {
                LoadSettings();
                await dialogCoordinator.ShowMessageAsync(this, "Success", "Items Saved Successfully. You Rock!");
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                errorMessage = e.Message;
            }

            if (errorMessage == null)
            {
                return;
            }

            await dialogCoordinator
            .ShowMessageAsync(this, "Error"
                              , "Fatal Error Occured. You're Screwed!\n" +
                              errorMessage);
        }
Example #17
0
        private void ConvertDataToExcel()
        {
            Discipline[] disciplines = new EducationProcessContext().Disciplines.ToArray();

            ExcelEducationPlanWriter.ToExcelFile(disciplines, null);
            _dialogCoordinator.ShowMessageAsync(this, "Конвертация в таблицу", "Операция завершена успешо.");
        }
Example #18
0
        private async void DeleteSelectedScript()
        {
            if (SelectedScript == null)
            {
                return;
            }

            MessageDialogResult result = await _dialogService.ShowMessageAsync(
                this,
                "Delete Script",
                "Are you sure you want to delete the script " + SelectedScript.Name + "?",
                MessageDialogStyle.AffirmativeAndNegative);

            if (result == MessageDialogResult.Negative)
            {
                return;
            }

            _dbContext.UserScripts.Remove(SelectedScript);
            _dbContext.SaveChanges();

            Scripts.Remove(SelectedScript);

            Code = "";

            SelectedScript = null;
        }
Example #19
0
        /// <summary>
        /// This method loads the plugins.
        /// </summary>
        private void AssembleComponents()
        {
            var catalog = new AggregateCatalog();

            //Note: we load not only from the plugins folder, but from this assembly as well.
            var executingAssemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            if (Directory.Exists(Environment.CurrentDirectory + "\\Plugins"))
            {
                catalog.Catalogs.Add(new DirectoryCatalog("Plugins"));
            }

            catalog.Catalogs.Add(executingAssemblyCatalog);

            var container = new CompositionContainer(catalog);

            try
            {
                container.ComposeParts(this);
            }
            catch (CompositionException compositionException)
            {
                _dialogService.ShowMessageAsync(_mainVm, "Error", string.Format("There was an error loading plugins: {0}", compositionException)).Forget();
            }
        }
        private async void OnSave()
        {
            var categoriesToDb = RestproMapper
                                 .MapWpfRawMaterialCategoryListToRawMaterialCategoryList(Categories.ToList());
            string errorMessage = null;

            try
            {
                _unitOfWork.RawMaterialCategories.AddOrUpdate(categoriesToDb);
                LoadCategories();
                await dialogCoordinator.ShowMessageAsync(this, "Success", "Items Saved Successfully. You Rock!");
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                errorMessage = e.Message;
            }

            if (errorMessage == null)
            {
                return;
            }

            await dialogCoordinator
            .ShowMessageAsync(this, "Error"
                              , "Fatal Error Occured. You're Screwed!\n" +
                              errorMessage);
        }
Example #21
0
        private void OpenFile()
        {
            string file;
            bool?  res = Dialogs.OpenFileDialog("CSV Files (*.csv)|*.csv", out file);

            if (!res.HasValue || res.Value == false)
            {
                //No file
                return;
            }

            FilePath = file;

            //Open the file
            try
            {
                RawData = File.ReadAllText(file);
            }
            catch (Exception ex)
            {
                _dialogService.ShowMessageAsync(this, "Error opening file.", ex.Message).Forget();
                return;
            }

            SplitData();
        }
Example #22
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;
        }
 public async Task ShowError(string message, string title, string buttonText, Action afterHideCallback)
 {
     await _dialogCoordinator.ShowMessageAsync(this, title, message, MessageDialogStyle.Affirmative, new MetroDialogSettings
     {
         AffirmativeButtonText = buttonText,
         ColorScheme           = MetroDialogColorScheme.Accented
     });
 }
        public void DisplayError(string message)
        {
            if (string.IsNullOrWhiteSpace(message))
            {
                throw new ArgumentNullException(nameof(message));
            }

            _dialogCoordinator.ShowMessageAsync(this, "Error", message);
        }
 private bool IsSelectedEducationPlan(EducationPlan educationPlan)
 {
     if (educationPlan == null)
     {
         _dialogCoordinator.ShowMessageAsync(this, "Внимание", "Выберите учебный план");
         return(false);
     }
     return(true);
 }
Example #26
0
 public async void StartDriver()
 {
     var result = await _dialogCoordinator.ShowMessageAsync(this, "Message", "Start Snappy Driver?", MessageDialogStyle.AffirmativeAndNegative, new MetroDialogSettings
     {
         AffirmativeButtonText = "Yes",
         NegativeButtonText    = "No",
         AnimateShow           = true,
         AnimateHide           = false
     });
 }
Example #27
0
        private async Task <IStatementDownloader> GetDownloaderByName(string name)
        {
            if (!DownloaderNames.Contains(name))
            {
                await _dialogService.ShowMessageAsync(_mainVm, "Error", "Statement downloader not found.");

                return(null);
            }

            return(StatementDownloaders.FirstOrDefault(x => x.Metadata.Name == name).CreateExport().Value);
        }
Example #28
0
 public async void OpenNetworkConnectionsAction()
 {
     try
     {
         Process.Start("NCPA.cpl");
     }
     catch (Exception ex)
     {
         await dialogCoordinator.ShowMessageAsync(this, Application.Current.Resources["String_Header_Error"] as string, ex.Message, MessageDialogStyle.Affirmative, AppearanceManager.MetroDialog);
     }
 }
Example #29
0
 private async void DisplayHelpAsync()
 {
     if (alternate = !alternate)
     {
         _ = await _dialogCoordinator.ShowMessageAsync(this, "Help!", $"You don't need Dev team's help, you just need to believe in yourself!", MessageDialogStyle.Affirmative);
     }
     else
     {
         _ = await _dialogCoordinator.ShowMessageAsync(this, "Help!", $"Craig will make your HAL file sing!", MessageDialogStyle.Affirmative);
     }
 }
        private void EditDiscipline(Discipline discipline)
        {
            if (discipline == null)
            {
                _dialogCoordinator.ShowMessageAsync(this, "Внимание", "Выберите дисциплину");
                return;
            }
            DisciplineEditViewModel viewModel = new DisciplineEditViewModel(discipline);

            new DisciplineEditorWindow(viewModel).ShowDialog();
            RefreshDisciplines();
        }
Example #31
0
        public PerformanceReportViewModel(filterReportDS data, ReportSettings settings, IDialogCoordinator dialogService) : base(null)
        {
            Data = data;
            Settings = settings;
            CopyChart = new RelayCommand<PlotView>(x => x.CopyToClipboard());
            SaveChart = new RelayCommand<PlotView>(x =>
                {
                    try
                    {
                        x.SaveAsPNG();
                    }
                    catch (Exception ex)
                    {
                        dialogService.ShowMessageAsync(this, "Error saving image", ex.Message);
                    }
                });

            //Calculate best fit line for the return vs size scatter chart
            double rsq;
            double[] b;
            MathUtils.MLR(
                Data.positionSizesVsReturns.Select(x => x.size).ToList(),
                Data.positionSizesVsReturns.Select(x => x.ret).ToList(),
                out b,
                out rsq);

            _retVsSizeBestFitLineConstant = b[0];
            _retVsSizeBestFitLineSlope = b[1];

            //Calculate best fit line for the return vs length scatter chart
            MathUtils.MLR(
                Data.tradeLengthsVsReturns.Select(x => x.ret).ToList(),
                Data.tradeLengthsVsReturns.Select(x => x.length).ToList(),
                out b,
                out rsq);

                _retVsLengthBestFitLineConstant = b[0];
                _retVsLengthBestFitLineSlope = b[1];

            //Histograms
            try
            {
                var sharpeHistogram = new Histogram(Enumerable.Select(Data.MCRatios, x => x.Sharpe), 20);
                MCSharpeHistogramBuckets = sharpeHistogram.GetBuckets();

                var marHistogram = new Histogram(Enumerable.Select(Data.MCRatios, x => x.MAR), 20);
                MCMARHistogramBuckets = marHistogram.GetBuckets();

                var kRatioHistogram = new Histogram(Enumerable.Select(Data.MCRatios, x => x.KRatio), 20);
                MCKRatioHistogramBuckets = kRatioHistogram.GetBuckets("0");
            }
            catch { } //Yeah this is bad, there's a ton of stupid errors that are not easy to check for...re-do this in the future

            //Benchmark stats
            if (Settings.Benchmark != null)
            {
                BenchmarkAlpha = ((filterReportDS.benchmarkStatsRow)Data.benchmarkStats.Rows[0]).alpha;
                BenchmarkBeta = ((filterReportDS.benchmarkStatsRow)Data.benchmarkStats.Rows[0]).beta;
                BenchmarkCorrelation = ((filterReportDS.benchmarkStatsRow)Data.benchmarkStats.Rows[0]).correlation;
                BenchmarkRSquare = ((filterReportDS.benchmarkStatsRow)Data.benchmarkStats.Rows[0]).rsquare;
                BenchmarkInformationRatio = ((filterReportDS.benchmarkStatsRow)Data.benchmarkStats.Rows[0]).informationRatio;
                BenchmarkActiveReturn = ((filterReportDS.benchmarkStatsRow)Data.benchmarkStats.Rows[0]).activeReturn;
                BenchmarkTrackingError = ((filterReportDS.benchmarkStatsRow)Data.benchmarkStats.Rows[0]).trackingError;
                BenchmarkInstrument = Settings.Benchmark.Name;
            }

            //avg cumulative winner/loser returns by day in trade
            AvgCumulativeWinnerRets = 
                Enumerable.Select(data
                    .AverageDailyRets
                    .Where(x => !x.IswinnersRetsNull()), x => new KeyValuePair<int, double>(x.day, x.winnersRets))
                .ToList();

            AvgCumulativeLoserRets =
                Enumerable.Select(data
                    .AverageDailyRets
                    .Where(x => !x.IslosersRetsNull()), x => new KeyValuePair<int, double>(x.day, x.losersRets))
                .ToList();

            //build plot models
            CreatePLByStrategyChartModel();
            CreateCapitalUsageByStrategyChartModel();
            CreateRelativeCapitalUsageByStrategyChartModel();
            CreateRoacByStrategyChartModel();
            CreateMdsChartModel();
            CreateTradeRetsByDayAndHourChartModel();
        }
        public MainViewModel(IDialogCoordinator _dialogCoordinator)
        {
            DialogCoordinator = _dialogCoordinator;

            try {
                NativeMethods.EnablePrivilege("SeBackupPrivilege");
                NativeMethods.EnablePrivilege("SeRestorePrivilege");
                IsAdmin = true;
            }
            catch {
            }

            ActiveView = this;

            var computer = new RegistryKeyItemSpecial(null) {
                Text = "Computer",
                Icon = "/images/workstation2.png",
                IsExpanded = true
            };
            computer.SubItems.Add(new RegistryKeyItem(computer, Registry.ClassesRoot));
            computer.SubItems.Add(new RegistryKeyItem(computer, Registry.CurrentUser));
            computer.SubItems.Add(new RegistryKeyItem(computer, Registry.LocalMachine));
            computer.SubItems.Add(new RegistryKeyItem(computer, Registry.CurrentConfig));
            computer.SubItems.Add(new RegistryKeyItem(computer, Registry.Users));

            _roots = new List<RegistryKeyItemBase> {
                computer,
                //new RegistryKeyItemSpecial(null) {
                //	Text = "Files",
                //	Icon = "/images/folder_blue.png"
                //},
                new RegistryKeyItemSpecial(null) {
                    Text = "Favorites",
                    Icon = "/images/favorites.png",
                    IsExpanded = true
                }
            };

            LoadFavorites();

            ExitCommand = new DelegateCommand(() => Application.Current.Shutdown());

            LaunchWithAdminRightsCommand = new DelegateCommand(() => {
                var pi = new ProcessStartInfo(Process.GetCurrentProcess().MainModule.FileName) { Verb = "RunAs" };
                try {
                    if(Process.Start(pi) != null) {
                        Environment.Exit(0);
                    }
                }
                catch(Exception ex) {
                    MessageBox.Show(ex.Message, App.Name);
                }
            }, () => !IsAdmin);

            EditNewKeyCommand = new DelegateCommand<RegistryKeyItem>(item => {
                var name = item.GenerateUniqueSubKeyName();
                CommandManager.AddCommand(Commands.CreateKey(new CreateKeyCommandContext {
                    Key = item,
                    Name = name
                }));
                item.IsExpanded = true;
                var newItem = item.GetSubItem<RegistryKeyItem>(name);
                newItem.IsSelected = true;
                Dispatcher.CurrentDispatcher.InvokeAsync(() => IsEditMode = true, DispatcherPriority.Background);
            }, item => !IsReadOnlyMode && item is RegistryKeyItem)
            .ObservesProperty(() => IsReadOnlyMode);

            EditPermissionsCommand = new DelegateCommand(() => {
                // TODO
            }, () => SelectedItem is RegistryKeyItem)
            .ObservesProperty(() => SelectedItem);

            CopyKeyNameCommand = new DelegateCommand<RegistryKeyItemBase>(_ => Clipboard.SetText(SelectedItem.Text),
                _ => SelectedItem != null).ObservesProperty(() => SelectedItem);

            CopyKeyPathCommand = new DelegateCommand(() => Clipboard.SetText(((RegistryKeyItem)SelectedItem).Path ?? SelectedItem.Text),
                () => SelectedItem is RegistryKeyItem)
                .ObservesProperty(() => SelectedItem);

            RefreshCommand = new DelegateCommand(() => SelectedItem.Refresh(), () => SelectedItem != null)
                .ObservesProperty(() => SelectedItem);

            EndEditingCommand = new DelegateCommand<string>(async name => {
                try {
                    var item = SelectedItem as RegistryKeyItem;
                    Debug.Assert(item != null);
                    if(name == null || name.Equals(item.Text, StringComparison.InvariantCultureIgnoreCase))
                        return;

                    if(item.Parent.SubItems.Any(i => name.Equals(i.Text, StringComparison.InvariantCultureIgnoreCase))) {
                        await DialogCoordinator.ShowMessageAsync(this, App.Name, string.Format("Key name '{0}' already exists", name));
                        return;
                    }
                    CommandManager.AddCommand(Commands.RenameKey(new RenameKeyCommandContext {
                        Key = item,
                        OldName = item.Text,
                        NewName = name
                    }));
                }
                catch(Exception ex) {
                    MessageBox.Show(ex.Message, App.Name);
                }
                finally {
                    IsEditMode = false;
                    CommandManager.UpdateChanges();
                    UndoCommand.RaiseCanExecuteChanged();
                    RedoCommand.RaiseCanExecuteChanged();
                }
            }, _ => IsEditMode).ObservesCanExecute(_ => IsEditMode);

            BeginRenameCommand = new DelegateCommand(() => IsEditMode = true,
                () => !IsReadOnlyMode && SelectedItem is RegistryKeyItem && !string.IsNullOrEmpty(((RegistryKeyItem)SelectedItem).Path))
                .ObservesProperty(() => SelectedItem).ObservesProperty(() => IsReadOnlyMode);

            UndoCommand = new DelegateCommand(() => {
                CommandManager.Undo();
                RedoCommand.RaiseCanExecuteChanged();
                UndoCommand.RaiseCanExecuteChanged();
            }, () => !IsReadOnlyMode && CommandManager.CanUndo).ObservesProperty(() => IsReadOnlyMode);

            RedoCommand = new DelegateCommand(() => {
                CommandManager.Redo();
                UndoCommand.RaiseCanExecuteChanged();
                RedoCommand.RaiseCanExecuteChanged();
            }, () => !IsReadOnlyMode && CommandManager.CanRedo).ObservesProperty(() => IsReadOnlyMode);

            LoadHiveCommand = new DelegateCommand(async () => {
                var vm = DialogHelper.ShowDialog<LoadHiveViewModel, LoadHiveView>();
                if(vm.ShowDialog() == true) {
                    int error = NativeMethods.RegLoadKey(vm.Hive == "HKLM" ? Registry.LocalMachine.Handle : Registry.Users.Handle, vm.Name, vm.FileName);
                    if(error != 0) {
                        await DialogCoordinator.ShowMessageAsync(this, App.Name, string.Format("Error opening file: {0}", error.ToString()));
                        return;
                    }

                    var item = _roots[0].SubItems[vm.Hive == "HKLM" ? 2 : 4];
                    item.Refresh();
                    ((RegistryKeyItem)item.SubItems.First(i => i.Text == vm.Name)).HiveKey = true;
                }
            }, () => IsAdmin && !IsReadOnlyMode)
            .ObservesProperty(() => IsReadOnlyMode);

            DeleteCommand = new DelegateCommand(() => {
                var item = SelectedItem as RegistryKeyItem;
                Debug.Assert(item != null);

                if(!IsAdmin) {
                    if(MessageBox.Show("Running with standard user rights prevents undo for deletion. Delete anyway?",
                        App.Name, MessageBoxButton.OKCancel, MessageBoxImage.Exclamation) == MessageBoxResult.Cancel)
                        return;
                    CommandManager.Clear();
                }
                var tempFile = Path.GetTempFileName();
                CommandManager.AddCommand(Commands.DeleteKey(new DeleteKeyCommandContext {
                    Key = item,
                    TempFile = tempFile
                }));
                CommandManager.UpdateChanges();
                UndoCommand.RaiseCanExecuteChanged();
                RedoCommand.RaiseCanExecuteChanged();
            }, () => !IsReadOnlyMode && SelectedItem is RegistryKeyItem && SelectedItem.Path != null).ObservesProperty(() => IsReadOnlyMode);

            ExportCommand = new DelegateCommand(() => {
                var dlg = new SaveFileDialog {
                    Title = "Select output file",
                    Filter = "Registry data files|*.dat",
                    OverwritePrompt = true
                };
                if(dlg.ShowDialog() == true) {
                    var item = SelectedItem as RegistryKeyItem;
                    Debug.Assert(item != null);
                    using(var key = item.Root.OpenSubKey(item.Path)) {
                        File.Delete(dlg.FileName);
                        int error = NativeMethods.RegSaveKeyEx(key.Handle, dlg.FileName, IntPtr.Zero, 2);
                        Debug.Assert(error == 0);
                    }
                }
            }, () => IsAdmin && SelectedItem is RegistryKeyItem)
            .ObservesProperty(() => SelectedItem);

            CreateNewValueCommand = new DelegateCommand<ValueViewModel>(vm => {

            }, vm => !IsReadOnlyMode)
            .ObservesProperty(() => IsReadOnlyMode);

            AddToFavoritesCommand = new DelegateCommand(() => {
                var item = SelectedItem as RegistryKeyItem;
                Debug.Assert(item != null);

                _roots[1].SubItems.Add(new RegistryKeyItem(item.Parent as RegistryKeyItem, item.Text));
                SaveFavorites();
            }, () => SelectedItem is RegistryKeyItem && !string.IsNullOrEmpty(SelectedItem.Path))
            .ObservesProperty(() => SelectedItem);

            RemoveFromFavoritesCommand = new DelegateCommand(() => {
                _roots[1].SubItems.Remove(SelectedItem);
                SaveFavorites();
            }, () => SelectedItem != null && SelectedItem.Flags.HasFlag(RegistryKeyFlags.Favorite))
            .ObservesProperty(() => SelectedItem);
        }